< Summary

Information
Line coverage
100%
Covered lines: 149
Uncovered lines: 0
Coverable lines: 149
Total lines: 368
Line coverage: 100%
Branch coverage
85%
Covered branches: 29
Total branches: 34
Branch coverage: 85.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%44100%
.ctor(...)83.33%66100%
Create(...)100%11100%
FromOwnedInfo(...)100%22100%
WithPinnedBuffer(...)50%44100%
get_Data()100%11100%
get_DataArray()100%11100%
get_DataMutable()100%11100%
get_DataBytes()100%11100%
get_SampleRate()100%11100%
get_NumChannels()100%11100%
get_SamplesPerChannel()100%11100%
get_TotalSamples()100%11100%
get_Duration()100%11100%
get_Userdata()100%11100%
ToWavBytes()100%22100%
GetSample(...)75%88100%
SetSample(...)100%88100%
Clone()100%11100%
ToString()100%11100%

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>
 247533        public AudioFrame(
 247534            short[] data,
 247535            int sampleRate,
 247536            int numChannels,
 247537            int samplesPerChannel,
 247538            Dictionary<string, object>? userdata = null
 247539        )
 247540        {
 247541            if (data.Length < numChannels * samplesPerChannel)
 142            {
 143                throw new ArgumentException(
 144                    "Data length must be >= numChannels * samplesPerChannel",
 145                    nameof(data)
 146                );
 47            }
 48
 247449            _data = data;
 247450            _sampleRate = sampleRate;
 247451            _numChannels = numChannels;
 247452            _samplesPerChannel = samplesPerChannel;
 247453            _userdata = userdata ?? new Dictionary<string, object>();
 247454        }
 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>
 264764        public AudioFrame(
 264765            byte[] data,
 264766            int sampleRate,
 264767            int numChannels,
 264768            int samplesPerChannel,
 264769            Dictionary<string, object>? userdata = null
 264770        )
 264771        {
 264772            int requiredBytes = numChannels * samplesPerChannel * sizeof(short);
 264773            if (data.Length < requiredBytes)
 174            {
 175                throw new ArgumentException(
 176                    $"Data length ({data.Length}) must be >= numChannels * samplesPerChannel * sizeof(short) ({requiredB
 177                    nameof(data)
 178                );
 79            }
 80
 264681            if (data.Length % sizeof(short) != 0)
 182            {
 183                throw new ArgumentException(
 184                    "Data length must be a multiple of sizeof(short)",
 185                    nameof(data)
 186                );
 87            }
 88
 264589            int numSamples = data.Length / sizeof(short);
 264590            _data = new short[numSamples];
 264591            Buffer.BlockCopy(data, 0, _data, 0, data.Length);
 92
 264593            _sampleRate = sampleRate;
 264594            _numChannels = numChannels;
 264595            _samplesPerChannel = samplesPerChannel;
 264596            _userdata = userdata ?? new Dictionary<string, object>();
 264597        }
 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)
 5107        {
 5108            var data = new short[numChannels * samplesPerChannel];
 5109            return new AudioFrame(data, sampleRate, numChannels, samplesPerChannel);
 5110        }
 111
 112        /// <summary>
 113        /// Creates an AudioFrame from an owned FFI buffer.
 114        /// </summary>
 115        internal static AudioFrame FromOwnedInfo(OwnedAudioFrameBuffer ownedInfo)
 929116        {
 117            // Own the native buffer first, so it is released even if the copy below throws
 929118            using var handle = FfiHandle.FromId(ownedInfo.Handle.Id);
 119
 929120            var info = ownedInfo.Info;
 929121            int size = (int)(info.NumChannels * info.SamplesPerChannel);
 122
 123            // Block copy from native memory: this runs on the FFI callback thread
 929124            var data = new short[size];
 929125            if (size > 0)
 929126            {
 929127                Marshal.Copy((IntPtr)info.DataPtr, data, 0, size);
 929128            }
 129
 929130            return new AudioFrame(
 929131                data,
 929132                (int)info.SampleRate,
 929133                (int)info.NumChannels,
 929134                (int)info.SamplesPerChannel
 929135            );
 929136        }
 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)
 10485143        {
 144            unsafe
 10485145            {
 10485146                fixed (short* ptr = _data)
 10485147                {
 10485148                    var buffer = new AudioFrameBufferInfo
 10485149                    {
 10485150                        DataPtr = (ulong)ptr,
 10485151                        SampleRate = (uint)_sampleRate,
 10485152                        NumChannels = (uint)_numChannels,
 10485153                        SamplesPerChannel = (uint)_samplesPerChannel,
 10485154                    };
 10485155                    return callback(buffer);
 156                }
 157            }
 10484158        }
 159
 160        /// <summary>
 161        /// Gets the raw audio data as Int16 samples.
 162        /// </summary>
 365163        public ReadOnlySpan<short> Data => _data;
 164
 165        /// <summary>
 166        /// Gets the raw audio data as an array (for async operations).
 167        /// </summary>
 2484168        public short[] DataArray => _data;
 169
 170        /// <summary>
 171        /// Gets the raw audio data as a mutable span.
 172        /// </summary>
 1173        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
 1069181            {
 1069182                var bytes = new byte[_data.Length * sizeof(short)];
 1069183                Buffer.BlockCopy(_data, 0, bytes, 0, bytes.Length);
 1069184                return bytes;
 1069185            }
 186        }
 187
 188        /// <summary>
 189        /// Gets the sample rate of the audio frame in Hz.
 190        /// </summary>
 2427191        public int SampleRate => _sampleRate;
 192
 193        /// <summary>
 194        /// Gets the number of channels in the audio frame.
 195        /// </summary>
 1389196        public int NumChannels => _numChannels;
 197
 198        /// <summary>
 199        /// Gets the number of samples per channel.
 200        /// </summary>
 21729201        public int SamplesPerChannel => _samplesPerChannel;
 202
 203        /// <summary>
 204        /// Gets the total number of samples (all channels).
 205        /// </summary>
 1765206        public int TotalSamples => _numChannels * _samplesPerChannel;
 207
 208        /// <summary>
 209        /// Gets the duration of the audio frame in seconds.
 210        /// </summary>
 2211        public double Duration => (double)_samplesPerChannel / _sampleRate;
 212
 213        /// <summary>
 214        /// Gets the user data associated with the audio frame.
 215        /// </summary>
 2216        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()
 1223        {
 1224            using var ms = new MemoryStream();
 1225            using var writer = new BinaryWriter(ms);
 226
 1227            int dataSize = _data.Length * sizeof(short);
 1228            int fileSize = 44 + dataSize;
 229
 230            // RIFF header
 1231            writer.Write(new char[] { 'R', 'I', 'F', 'F' });
 1232            writer.Write(fileSize - 8);
 1233            writer.Write(new char[] { 'W', 'A', 'V', 'E' });
 234
 235            // fmt chunk
 1236            writer.Write(new char[] { 'f', 'm', 't', ' ' });
 1237            writer.Write(16); // chunk size
 1238            writer.Write((short)1); // audio format (PCM)
 1239            writer.Write((short)_numChannels);
 1240            writer.Write(_sampleRate);
 1241            writer.Write(_sampleRate * _numChannels * sizeof(short)); // byte rate
 1242            writer.Write((short)(_numChannels * sizeof(short))); // block align
 1243            writer.Write((short)16); // bits per sample
 244
 245            // data chunk
 1246            writer.Write(new char[] { 'd', 'a', 't', 'a' });
 1247            writer.Write(dataSize);
 248
 249            // Write audio data
 11250            foreach (var sample in _data)
 4251            {
 4252                writer.Write(sample);
 4253            }
 254
 1255            return ms.ToArray();
 1256        }
 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)
 6265        {
 6266            if (channel < 0 || channel >= _numChannels)
 1267                throw new ArgumentOutOfRangeException(nameof(channel));
 5268            if (sampleIndex < 0 || sampleIndex >= _samplesPerChannel)
 1269                throw new ArgumentOutOfRangeException(nameof(sampleIndex));
 270
 271            // Interleaved format
 4272            return _data[sampleIndex * _numChannels + channel];
 4273        }
 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)
 9605282        {
 9605283            if (channel < 0 || channel >= _numChannels)
 1284                throw new ArgumentOutOfRangeException(nameof(channel));
 9604285            if (sampleIndex < 0 || sampleIndex >= _samplesPerChannel)
 1286                throw new ArgumentOutOfRangeException(nameof(sampleIndex));
 287
 9603288            _data[sampleIndex * _numChannels + channel] = value;
 9603289        }
 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()
 2296        {
 2297            var dataCopy = new short[_data.Length];
 2298            Array.Copy(_data, dataCopy, _data.Length);
 2299            return new AudioFrame(
 2300                dataCopy,
 2301                _sampleRate,
 2302                _numChannels,
 2303                _samplesPerChannel,
 2304                new Dictionary<string, object>(_userdata)
 2305            );
 2306        }
 307
 308        /// <inheritdoc />
 309        public override string ToString()
 1310        {
 1311            return $"AudioFrame(sampleRate={_sampleRate}, numChannels={_numChannels}, "
 1312                + $"samplesPerChannel={_samplesPerChannel}, duration={Duration:F3}s)";
 1313        }
 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}