< Summary

Information
Class: LiveKit.Rtc.AudioFrameExtensions
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/AudioFrame.cs
Line coverage
100%
Covered lines: 30
Uncovered lines: 0
Coverable lines: 30
Total lines: 368
Line coverage: 100%
Branch coverage
100%
Covered branches: 12
Total branches: 12
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Combine(...)100%1212100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/AudioFrame.cs

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.IO;
 6using System.Runtime.InteropServices;
 7using LiveKit.Proto;
 8using LiveKit.Rtc.Internal;
 9
 10namespace 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>
 33        public AudioFrame(
 34            short[] data,
 35            int sampleRate,
 36            int numChannels,
 37            int samplesPerChannel,
 38            Dictionary<string, object>? userdata = null
 39        )
 40        {
 41            if (data.Length < numChannels * samplesPerChannel)
 42            {
 43                throw new ArgumentException(
 44                    "Data length must be >= numChannels * samplesPerChannel",
 45                    nameof(data)
 46                );
 47            }
 48
 49            _data = data;
 50            _sampleRate = sampleRate;
 51            _numChannels = numChannels;
 52            _samplesPerChannel = samplesPerChannel;
 53            _userdata = userdata ?? new Dictionary<string, object>();
 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>
 64        public AudioFrame(
 65            byte[] data,
 66            int sampleRate,
 67            int numChannels,
 68            int samplesPerChannel,
 69            Dictionary<string, object>? userdata = null
 70        )
 71        {
 72            int requiredBytes = numChannels * samplesPerChannel * sizeof(short);
 73            if (data.Length < requiredBytes)
 74            {
 75                throw new ArgumentException(
 76                    $"Data length ({data.Length}) must be >= numChannels * samplesPerChannel * sizeof(short) ({requiredB
 77                    nameof(data)
 78                );
 79            }
 80
 81            if (data.Length % sizeof(short) != 0)
 82            {
 83                throw new ArgumentException(
 84                    "Data length must be a multiple of sizeof(short)",
 85                    nameof(data)
 86                );
 87            }
 88
 89            int numSamples = data.Length / sizeof(short);
 90            _data = new short[numSamples];
 91            Buffer.BlockCopy(data, 0, _data, 0, data.Length);
 92
 93            _sampleRate = sampleRate;
 94            _numChannels = numChannels;
 95            _samplesPerChannel = samplesPerChannel;
 96            _userdata = userdata ?? new Dictionary<string, object>();
 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)
 107        {
 108            var data = new short[numChannels * samplesPerChannel];
 109            return new AudioFrame(data, sampleRate, numChannels, samplesPerChannel);
 110        }
 111
 112        /// <summary>
 113        /// Creates an AudioFrame from an owned FFI buffer.
 114        /// </summary>
 115        internal static AudioFrame FromOwnedInfo(OwnedAudioFrameBuffer ownedInfo)
 116        {
 117            // Own the native buffer first, so it is released even if the copy below throws
 118            using var handle = FfiHandle.FromId(ownedInfo.Handle.Id);
 119
 120            var info = ownedInfo.Info;
 121            int size = (int)(info.NumChannels * info.SamplesPerChannel);
 122
 123            // Block copy from native memory: this runs on the FFI callback thread
 124            var data = new short[size];
 125            if (size > 0)
 126            {
 127                Marshal.Copy((IntPtr)info.DataPtr, data, 0, size);
 128            }
 129
 130            return new AudioFrame(
 131                data,
 132                (int)info.SampleRate,
 133                (int)info.NumChannels,
 134                (int)info.SamplesPerChannel
 135            );
 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)
 143        {
 144            unsafe
 145            {
 146                fixed (short* ptr = _data)
 147                {
 148                    var buffer = new AudioFrameBufferInfo
 149                    {
 150                        DataPtr = (ulong)ptr,
 151                        SampleRate = (uint)_sampleRate,
 152                        NumChannels = (uint)_numChannels,
 153                        SamplesPerChannel = (uint)_samplesPerChannel,
 154                    };
 155                    return callback(buffer);
 156                }
 157            }
 158        }
 159
 160        /// <summary>
 161        /// Gets the raw audio data as Int16 samples.
 162        /// </summary>
 163        public ReadOnlySpan<short> Data => _data;
 164
 165        /// <summary>
 166        /// Gets the raw audio data as an array (for async operations).
 167        /// </summary>
 168        public short[] DataArray => _data;
 169
 170        /// <summary>
 171        /// Gets the raw audio data as a mutable span.
 172        /// </summary>
 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
 181            {
 182                var bytes = new byte[_data.Length * sizeof(short)];
 183                Buffer.BlockCopy(_data, 0, bytes, 0, bytes.Length);
 184                return bytes;
 185            }
 186        }
 187
 188        /// <summary>
 189        /// Gets the sample rate of the audio frame in Hz.
 190        /// </summary>
 191        public int SampleRate => _sampleRate;
 192
 193        /// <summary>
 194        /// Gets the number of channels in the audio frame.
 195        /// </summary>
 196        public int NumChannels => _numChannels;
 197
 198        /// <summary>
 199        /// Gets the number of samples per channel.
 200        /// </summary>
 201        public int SamplesPerChannel => _samplesPerChannel;
 202
 203        /// <summary>
 204        /// Gets the total number of samples (all channels).
 205        /// </summary>
 206        public int TotalSamples => _numChannels * _samplesPerChannel;
 207
 208        /// <summary>
 209        /// Gets the duration of the audio frame in seconds.
 210        /// </summary>
 211        public double Duration => (double)_samplesPerChannel / _sampleRate;
 212
 213        /// <summary>
 214        /// Gets the user data associated with the audio frame.
 215        /// </summary>
 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()
 223        {
 224            using var ms = new MemoryStream();
 225            using var writer = new BinaryWriter(ms);
 226
 227            int dataSize = _data.Length * sizeof(short);
 228            int fileSize = 44 + dataSize;
 229
 230            // RIFF header
 231            writer.Write(new char[] { 'R', 'I', 'F', 'F' });
 232            writer.Write(fileSize - 8);
 233            writer.Write(new char[] { 'W', 'A', 'V', 'E' });
 234
 235            // fmt chunk
 236            writer.Write(new char[] { 'f', 'm', 't', ' ' });
 237            writer.Write(16); // chunk size
 238            writer.Write((short)1); // audio format (PCM)
 239            writer.Write((short)_numChannels);
 240            writer.Write(_sampleRate);
 241            writer.Write(_sampleRate * _numChannels * sizeof(short)); // byte rate
 242            writer.Write((short)(_numChannels * sizeof(short))); // block align
 243            writer.Write((short)16); // bits per sample
 244
 245            // data chunk
 246            writer.Write(new char[] { 'd', 'a', 't', 'a' });
 247            writer.Write(dataSize);
 248
 249            // Write audio data
 250            foreach (var sample in _data)
 251            {
 252                writer.Write(sample);
 253            }
 254
 255            return ms.ToArray();
 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)
 265        {
 266            if (channel < 0 || channel >= _numChannels)
 267                throw new ArgumentOutOfRangeException(nameof(channel));
 268            if (sampleIndex < 0 || sampleIndex >= _samplesPerChannel)
 269                throw new ArgumentOutOfRangeException(nameof(sampleIndex));
 270
 271            // Interleaved format
 272            return _data[sampleIndex * _numChannels + channel];
 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)
 282        {
 283            if (channel < 0 || channel >= _numChannels)
 284                throw new ArgumentOutOfRangeException(nameof(channel));
 285            if (sampleIndex < 0 || sampleIndex >= _samplesPerChannel)
 286                throw new ArgumentOutOfRangeException(nameof(sampleIndex));
 287
 288            _data[sampleIndex * _numChannels + channel] = value;
 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()
 296        {
 297            var dataCopy = new short[_data.Length];
 298            Array.Copy(_data, dataCopy, _data.Length);
 299            return new AudioFrame(
 300                dataCopy,
 301                _sampleRate,
 302                _numChannels,
 303                _samplesPerChannel,
 304                new Dictionary<string, object>(_userdata)
 305            );
 306        }
 307
 308        /// <inheritdoc />
 309        public override string ToString()
 310        {
 311            return $"AudioFrame(sampleRate={_sampleRate}, numChannels={_numChannels}, "
 312                + $"samplesPerChannel={_samplesPerChannel}, duration={Duration:F3}s)";
 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)
 5328        {
 5329            var frameList = new List<AudioFrame>(frames);
 330
 5331            if (frameList.Count == 0)
 1332                throw new ArgumentException("At least one frame is required", nameof(frames));
 333
 4334            if (frameList.Count == 1)
 1335                return frameList[0].Clone();
 336
 3337            int sampleRate = frameList[0].SampleRate;
 3338            int numChannels = frameList[0].NumChannels;
 3339            int totalSamplesPerChannel = 0;
 340
 19341            foreach (var frame in frameList)
 6342            {
 6343                if (frame.SampleRate != sampleRate)
 1344                    throw new ArgumentException(
 1345                        $"Sample rate mismatch: expected {sampleRate}, got {frame.SampleRate}"
 1346                    );
 347
 5348                if (frame.NumChannels != numChannels)
 1349                    throw new ArgumentException(
 1350                        $"Channel mismatch: expected {numChannels}, got {frame.NumChannels}"
 1351                    );
 352
 4353                totalSamplesPerChannel += frame.SamplesPerChannel;
 4354            }
 355
 1356            var combinedData = new short[numChannels * totalSamplesPerChannel];
 1357            int offset = 0;
 358
 7359            foreach (var frame in frameList)
 2360            {
 2361                Array.Copy(frame.Data.ToArray(), 0, combinedData, offset, frame.TotalSamples);
 2362                offset += frame.TotalSamples;
 2363            }
 364
 1365            return new AudioFrame(combinedData, sampleRate, numChannels, totalSamplesPerChannel);
 2366        }
 367    }
 368}