| | | 1 | | // author: https://github.com/pabloFuente |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.IO; |
| | | 6 | | using System.Runtime.InteropServices; |
| | | 7 | | using LiveKit.Proto; |
| | | 8 | | using LiveKit.Rtc.Internal; |
| | | 9 | | |
| | | 10 | | namespace LiveKit.Rtc |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Represents a frame of audio data with specific properties such as sample rate, |
| | | 14 | | /// number of channels, and samples per channel. |
| | | 15 | | /// The format of the audio data is 16-bit signed integers (Int16) interleaved by channel. |
| | | 16 | | /// </summary> |
| | | 17 | | public class AudioFrame |
| | | 18 | | { |
| | | 19 | | private short[] _data; |
| | | 20 | | private readonly int _sampleRate; |
| | | 21 | | private readonly int _numChannels; |
| | | 22 | | private readonly int _samplesPerChannel; |
| | | 23 | | private readonly Dictionary<string, object> _userdata; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Initialize an AudioFrame instance. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="data">The raw audio data as Int16 samples.</param> |
| | | 29 | | /// <param name="sampleRate">The sample rate of the audio in Hz.</param> |
| | | 30 | | /// <param name="numChannels">The number of audio channels (e.g., 1 for mono, 2 for stereo).</param> |
| | | 31 | | /// <param name="samplesPerChannel">The number of samples per channel.</param> |
| | | 32 | | /// <param name="userdata">Optional user data dictionary.</param> |
| | 2475 | 33 | | public AudioFrame( |
| | 2475 | 34 | | short[] data, |
| | 2475 | 35 | | int sampleRate, |
| | 2475 | 36 | | int numChannels, |
| | 2475 | 37 | | int samplesPerChannel, |
| | 2475 | 38 | | Dictionary<string, object>? userdata = null |
| | 2475 | 39 | | ) |
| | 2475 | 40 | | { |
| | 2475 | 41 | | if (data.Length < numChannels * samplesPerChannel) |
| | 1 | 42 | | { |
| | 1 | 43 | | throw new ArgumentException( |
| | 1 | 44 | | "Data length must be >= numChannels * samplesPerChannel", |
| | 1 | 45 | | nameof(data) |
| | 1 | 46 | | ); |
| | | 47 | | } |
| | | 48 | | |
| | 2474 | 49 | | _data = data; |
| | 2474 | 50 | | _sampleRate = sampleRate; |
| | 2474 | 51 | | _numChannels = numChannels; |
| | 2474 | 52 | | _samplesPerChannel = samplesPerChannel; |
| | 2474 | 53 | | _userdata = userdata ?? new Dictionary<string, object>(); |
| | 2474 | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Initialize an AudioFrame instance from raw bytes. |
| | | 58 | | /// </summary> |
| | | 59 | | /// <param name="data">The raw audio data as bytes (must be Int16 samples).</param> |
| | | 60 | | /// <param name="sampleRate">The sample rate of the audio in Hz.</param> |
| | | 61 | | /// <param name="numChannels">The number of audio channels.</param> |
| | | 62 | | /// <param name="samplesPerChannel">The number of samples per channel.</param> |
| | | 63 | | /// <param name="userdata">Optional user data dictionary.</param> |
| | 2647 | 64 | | public AudioFrame( |
| | 2647 | 65 | | byte[] data, |
| | 2647 | 66 | | int sampleRate, |
| | 2647 | 67 | | int numChannels, |
| | 2647 | 68 | | int samplesPerChannel, |
| | 2647 | 69 | | Dictionary<string, object>? userdata = null |
| | 2647 | 70 | | ) |
| | 2647 | 71 | | { |
| | 2647 | 72 | | int requiredBytes = numChannels * samplesPerChannel * sizeof(short); |
| | 2647 | 73 | | if (data.Length < requiredBytes) |
| | 1 | 74 | | { |
| | 1 | 75 | | throw new ArgumentException( |
| | 1 | 76 | | $"Data length ({data.Length}) must be >= numChannels * samplesPerChannel * sizeof(short) ({requiredB |
| | 1 | 77 | | nameof(data) |
| | 1 | 78 | | ); |
| | | 79 | | } |
| | | 80 | | |
| | 2646 | 81 | | if (data.Length % sizeof(short) != 0) |
| | 1 | 82 | | { |
| | 1 | 83 | | throw new ArgumentException( |
| | 1 | 84 | | "Data length must be a multiple of sizeof(short)", |
| | 1 | 85 | | nameof(data) |
| | 1 | 86 | | ); |
| | | 87 | | } |
| | | 88 | | |
| | 2645 | 89 | | int numSamples = data.Length / sizeof(short); |
| | 2645 | 90 | | _data = new short[numSamples]; |
| | 2645 | 91 | | Buffer.BlockCopy(data, 0, _data, 0, data.Length); |
| | | 92 | | |
| | 2645 | 93 | | _sampleRate = sampleRate; |
| | 2645 | 94 | | _numChannels = numChannels; |
| | 2645 | 95 | | _samplesPerChannel = samplesPerChannel; |
| | 2645 | 96 | | _userdata = userdata ?? new Dictionary<string, object>(); |
| | 2645 | 97 | | } |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Create a new empty AudioFrame instance with specified parameters. |
| | | 101 | | /// </summary> |
| | | 102 | | /// <param name="sampleRate">The sample rate of the audio in Hz.</param> |
| | | 103 | | /// <param name="numChannels">The number of audio channels.</param> |
| | | 104 | | /// <param name="samplesPerChannel">The number of samples per channel.</param> |
| | | 105 | | /// <returns>A new AudioFrame instance with zeroed data.</returns> |
| | | 106 | | public static AudioFrame Create(int sampleRate, int numChannels, int samplesPerChannel) |
| | 5 | 107 | | { |
| | 5 | 108 | | var data = new short[numChannels * samplesPerChannel]; |
| | 5 | 109 | | return new AudioFrame(data, sampleRate, numChannels, samplesPerChannel); |
| | 5 | 110 | | } |
| | | 111 | | |
| | | 112 | | /// <summary> |
| | | 113 | | /// Creates an AudioFrame from an owned FFI buffer. |
| | | 114 | | /// </summary> |
| | | 115 | | internal static AudioFrame FromOwnedInfo(OwnedAudioFrameBuffer ownedInfo) |
| | 929 | 116 | | { |
| | | 117 | | // Own the native buffer first, so it is released even if the copy below throws |
| | 929 | 118 | | using var handle = FfiHandle.FromId(ownedInfo.Handle.Id); |
| | | 119 | | |
| | 929 | 120 | | var info = ownedInfo.Info; |
| | 929 | 121 | | int size = (int)(info.NumChannels * info.SamplesPerChannel); |
| | | 122 | | |
| | | 123 | | // Block copy from native memory: this runs on the FFI callback thread |
| | 929 | 124 | | var data = new short[size]; |
| | 929 | 125 | | if (size > 0) |
| | 929 | 126 | | { |
| | 929 | 127 | | Marshal.Copy((IntPtr)info.DataPtr, data, 0, size); |
| | 929 | 128 | | } |
| | | 129 | | |
| | 929 | 130 | | return new AudioFrame( |
| | 929 | 131 | | data, |
| | 929 | 132 | | (int)info.SampleRate, |
| | 929 | 133 | | (int)info.NumChannels, |
| | 929 | 134 | | (int)info.SamplesPerChannel |
| | 929 | 135 | | ); |
| | 929 | 136 | | } |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Pins the samples while a synchronous FFI operation consumes the buffer. |
| | | 140 | | /// The callback must not retain the buffer pointer after returning. |
| | | 141 | | /// </summary> |
| | | 142 | | internal TResult WithPinnedBuffer<TResult>(Func<AudioFrameBufferInfo, TResult> callback) |
| | 10485 | 143 | | { |
| | | 144 | | unsafe |
| | 10485 | 145 | | { |
| | 10485 | 146 | | fixed (short* ptr = _data) |
| | 10485 | 147 | | { |
| | 10485 | 148 | | var buffer = new AudioFrameBufferInfo |
| | 10485 | 149 | | { |
| | 10485 | 150 | | DataPtr = (ulong)ptr, |
| | 10485 | 151 | | SampleRate = (uint)_sampleRate, |
| | 10485 | 152 | | NumChannels = (uint)_numChannels, |
| | 10485 | 153 | | SamplesPerChannel = (uint)_samplesPerChannel, |
| | 10485 | 154 | | }; |
| | 10485 | 155 | | return callback(buffer); |
| | | 156 | | } |
| | | 157 | | } |
| | 10484 | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Gets the raw audio data as Int16 samples. |
| | | 162 | | /// </summary> |
| | 365 | 163 | | public ReadOnlySpan<short> Data => _data; |
| | | 164 | | |
| | | 165 | | /// <summary> |
| | | 166 | | /// Gets the raw audio data as an array (for async operations). |
| | | 167 | | /// </summary> |
| | 2484 | 168 | | public short[] DataArray => _data; |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Gets the raw audio data as a mutable span. |
| | | 172 | | /// </summary> |
| | 1 | 173 | | public Span<short> DataMutable => _data; |
| | | 174 | | |
| | | 175 | | /// <summary> |
| | | 176 | | /// Gets the raw audio data as bytes. |
| | | 177 | | /// </summary> |
| | | 178 | | public byte[] DataBytes |
| | | 179 | | { |
| | | 180 | | get |
| | 1069 | 181 | | { |
| | 1069 | 182 | | var bytes = new byte[_data.Length * sizeof(short)]; |
| | 1069 | 183 | | Buffer.BlockCopy(_data, 0, bytes, 0, bytes.Length); |
| | 1069 | 184 | | return bytes; |
| | 1069 | 185 | | } |
| | | 186 | | } |
| | | 187 | | |
| | | 188 | | /// <summary> |
| | | 189 | | /// Gets the sample rate of the audio frame in Hz. |
| | | 190 | | /// </summary> |
| | 2427 | 191 | | public int SampleRate => _sampleRate; |
| | | 192 | | |
| | | 193 | | /// <summary> |
| | | 194 | | /// Gets the number of channels in the audio frame. |
| | | 195 | | /// </summary> |
| | 1389 | 196 | | public int NumChannels => _numChannels; |
| | | 197 | | |
| | | 198 | | /// <summary> |
| | | 199 | | /// Gets the number of samples per channel. |
| | | 200 | | /// </summary> |
| | 21729 | 201 | | public int SamplesPerChannel => _samplesPerChannel; |
| | | 202 | | |
| | | 203 | | /// <summary> |
| | | 204 | | /// Gets the total number of samples (all channels). |
| | | 205 | | /// </summary> |
| | 1765 | 206 | | public int TotalSamples => _numChannels * _samplesPerChannel; |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Gets the duration of the audio frame in seconds. |
| | | 210 | | /// </summary> |
| | 2 | 211 | | public double Duration => (double)_samplesPerChannel / _sampleRate; |
| | | 212 | | |
| | | 213 | | /// <summary> |
| | | 214 | | /// Gets the user data associated with the audio frame. |
| | | 215 | | /// </summary> |
| | 2 | 216 | | public Dictionary<string, object> Userdata => _userdata; |
| | | 217 | | |
| | | 218 | | /// <summary> |
| | | 219 | | /// Converts the audio frame to a WAV file byte array. |
| | | 220 | | /// </summary> |
| | | 221 | | /// <returns>The audio data encoded in WAV format.</returns> |
| | | 222 | | public byte[] ToWavBytes() |
| | 1 | 223 | | { |
| | 1 | 224 | | using var ms = new MemoryStream(); |
| | 1 | 225 | | using var writer = new BinaryWriter(ms); |
| | | 226 | | |
| | 1 | 227 | | int dataSize = _data.Length * sizeof(short); |
| | 1 | 228 | | int fileSize = 44 + dataSize; |
| | | 229 | | |
| | | 230 | | // RIFF header |
| | 1 | 231 | | writer.Write(new char[] { 'R', 'I', 'F', 'F' }); |
| | 1 | 232 | | writer.Write(fileSize - 8); |
| | 1 | 233 | | writer.Write(new char[] { 'W', 'A', 'V', 'E' }); |
| | | 234 | | |
| | | 235 | | // fmt chunk |
| | 1 | 236 | | writer.Write(new char[] { 'f', 'm', 't', ' ' }); |
| | 1 | 237 | | writer.Write(16); // chunk size |
| | 1 | 238 | | writer.Write((short)1); // audio format (PCM) |
| | 1 | 239 | | writer.Write((short)_numChannels); |
| | 1 | 240 | | writer.Write(_sampleRate); |
| | 1 | 241 | | writer.Write(_sampleRate * _numChannels * sizeof(short)); // byte rate |
| | 1 | 242 | | writer.Write((short)(_numChannels * sizeof(short))); // block align |
| | 1 | 243 | | writer.Write((short)16); // bits per sample |
| | | 244 | | |
| | | 245 | | // data chunk |
| | 1 | 246 | | writer.Write(new char[] { 'd', 'a', 't', 'a' }); |
| | 1 | 247 | | writer.Write(dataSize); |
| | | 248 | | |
| | | 249 | | // Write audio data |
| | 11 | 250 | | foreach (var sample in _data) |
| | 4 | 251 | | { |
| | 4 | 252 | | writer.Write(sample); |
| | 4 | 253 | | } |
| | | 254 | | |
| | 1 | 255 | | return ms.ToArray(); |
| | 1 | 256 | | } |
| | | 257 | | |
| | | 258 | | /// <summary> |
| | | 259 | | /// Gets a sample at a specific index. |
| | | 260 | | /// </summary> |
| | | 261 | | /// <param name="channel">The channel index (0-based).</param> |
| | | 262 | | /// <param name="sampleIndex">The sample index within the channel.</param> |
| | | 263 | | /// <returns>The sample value.</returns> |
| | | 264 | | public short GetSample(int channel, int sampleIndex) |
| | 6 | 265 | | { |
| | 6 | 266 | | if (channel < 0 || channel >= _numChannels) |
| | 1 | 267 | | throw new ArgumentOutOfRangeException(nameof(channel)); |
| | 5 | 268 | | if (sampleIndex < 0 || sampleIndex >= _samplesPerChannel) |
| | 1 | 269 | | throw new ArgumentOutOfRangeException(nameof(sampleIndex)); |
| | | 270 | | |
| | | 271 | | // Interleaved format |
| | 4 | 272 | | return _data[sampleIndex * _numChannels + channel]; |
| | 4 | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary> |
| | | 276 | | /// Sets a sample at a specific index. |
| | | 277 | | /// </summary> |
| | | 278 | | /// <param name="channel">The channel index (0-based).</param> |
| | | 279 | | /// <param name="sampleIndex">The sample index within the channel.</param> |
| | | 280 | | /// <param name="value">The sample value to set.</param> |
| | | 281 | | public void SetSample(int channel, int sampleIndex, short value) |
| | 9605 | 282 | | { |
| | 9605 | 283 | | if (channel < 0 || channel >= _numChannels) |
| | 1 | 284 | | throw new ArgumentOutOfRangeException(nameof(channel)); |
| | 9604 | 285 | | if (sampleIndex < 0 || sampleIndex >= _samplesPerChannel) |
| | 1 | 286 | | throw new ArgumentOutOfRangeException(nameof(sampleIndex)); |
| | | 287 | | |
| | 9603 | 288 | | _data[sampleIndex * _numChannels + channel] = value; |
| | 9603 | 289 | | } |
| | | 290 | | |
| | | 291 | | /// <summary> |
| | | 292 | | /// Creates a copy of this audio frame. |
| | | 293 | | /// </summary> |
| | | 294 | | /// <returns>A deep copy of the frame, with its own sample buffer.</returns> |
| | | 295 | | public AudioFrame Clone() |
| | 2 | 296 | | { |
| | 2 | 297 | | var dataCopy = new short[_data.Length]; |
| | 2 | 298 | | Array.Copy(_data, dataCopy, _data.Length); |
| | 2 | 299 | | return new AudioFrame( |
| | 2 | 300 | | dataCopy, |
| | 2 | 301 | | _sampleRate, |
| | 2 | 302 | | _numChannels, |
| | 2 | 303 | | _samplesPerChannel, |
| | 2 | 304 | | new Dictionary<string, object>(_userdata) |
| | 2 | 305 | | ); |
| | 2 | 306 | | } |
| | | 307 | | |
| | | 308 | | /// <inheritdoc /> |
| | | 309 | | public override string ToString() |
| | 1 | 310 | | { |
| | 1 | 311 | | return $"AudioFrame(sampleRate={_sampleRate}, numChannels={_numChannels}, " |
| | 1 | 312 | | + $"samplesPerChannel={_samplesPerChannel}, duration={Duration:F3}s)"; |
| | 1 | 313 | | } |
| | | 314 | | } |
| | | 315 | | |
| | | 316 | | /// <summary> |
| | | 317 | | /// Utility methods for working with audio frames. |
| | | 318 | | /// </summary> |
| | | 319 | | public static class AudioFrameExtensions |
| | | 320 | | { |
| | | 321 | | /// <summary> |
| | | 322 | | /// Combines multiple audio frames into a single frame. |
| | | 323 | | /// All frames must have the same sample rate and number of channels. |
| | | 324 | | /// </summary> |
| | | 325 | | /// <param name="frames">The frames to combine.</param> |
| | | 326 | | /// <returns>A new AudioFrame containing all the data.</returns> |
| | | 327 | | public static AudioFrame Combine(this IEnumerable<AudioFrame> frames) |
| | | 328 | | { |
| | | 329 | | var frameList = new List<AudioFrame>(frames); |
| | | 330 | | |
| | | 331 | | if (frameList.Count == 0) |
| | | 332 | | throw new ArgumentException("At least one frame is required", nameof(frames)); |
| | | 333 | | |
| | | 334 | | if (frameList.Count == 1) |
| | | 335 | | return frameList[0].Clone(); |
| | | 336 | | |
| | | 337 | | int sampleRate = frameList[0].SampleRate; |
| | | 338 | | int numChannels = frameList[0].NumChannels; |
| | | 339 | | int totalSamplesPerChannel = 0; |
| | | 340 | | |
| | | 341 | | foreach (var frame in frameList) |
| | | 342 | | { |
| | | 343 | | if (frame.SampleRate != sampleRate) |
| | | 344 | | throw new ArgumentException( |
| | | 345 | | $"Sample rate mismatch: expected {sampleRate}, got {frame.SampleRate}" |
| | | 346 | | ); |
| | | 347 | | |
| | | 348 | | if (frame.NumChannels != numChannels) |
| | | 349 | | throw new ArgumentException( |
| | | 350 | | $"Channel mismatch: expected {numChannels}, got {frame.NumChannels}" |
| | | 351 | | ); |
| | | 352 | | |
| | | 353 | | totalSamplesPerChannel += frame.SamplesPerChannel; |
| | | 354 | | } |
| | | 355 | | |
| | | 356 | | var combinedData = new short[numChannels * totalSamplesPerChannel]; |
| | | 357 | | int offset = 0; |
| | | 358 | | |
| | | 359 | | foreach (var frame in frameList) |
| | | 360 | | { |
| | | 361 | | Array.Copy(frame.Data.ToArray(), 0, combinedData, offset, frame.TotalSamples); |
| | | 362 | | offset += frame.TotalSamples; |
| | | 363 | | } |
| | | 364 | | |
| | | 365 | | return new AudioFrame(combinedData, sampleRate, numChannels, totalSamplesPerChannel); |
| | | 366 | | } |
| | | 367 | | } |
| | | 368 | | } |