< Summary

Information
Class: LiveKit.Rtc.AudioResampler
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/AudioResampler.cs
Line coverage
88%
Covered lines: 128
Uncovered lines: 17
Coverable lines: 145
Total lines: 258
Line coverage: 88.2%
Branch coverage
70%
Covered branches: 21
Total branches: 30
Branch coverage: 70%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%2287.5%
get_InputRate()100%210%
get_OutputRate()100%210%
get_NumChannels()100%210%
Push(...)83.33%6693.33%
Push(...)58.33%121288.09%
Flush()66.66%6690%
ThrowIfDisposed()100%22100%
Dispose()100%22100%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Runtime.InteropServices;
 6using LiveKit.Proto;
 7using LiveKit.Rtc.Internal;
 8
 9namespace LiveKit.Rtc
 10{
 11    /// <summary>
 12    /// A class for resampling audio data from one sample rate to another.
 13    /// Uses the Sox resampling library under the hood.
 14    /// </summary>
 15    public class AudioResampler : IDisposable
 16    {
 17        private readonly FfiHandle _handle;
 18        private readonly uint _inputRate;
 19        private readonly uint _outputRate;
 20        private readonly uint _numChannels;
 21
 22        // The FFI returns a pointer into the resampler's own output buffer, which the next
 23        // Push/Flush overwrites and releasing the handle frees: the request, the copy and the
 24        // release must not interleave between threads.
 118225        private readonly object _lock = new object();
 26        private volatile bool _disposed;
 27
 28        /// <summary>
 29        /// Initializes a new AudioResampler instance.
 30        /// </summary>
 31        /// <param name="inputRate">The sample rate of the input audio data (in Hz).</param>
 32        /// <param name="outputRate">The desired sample rate of the output audio data (in Hz).</param>
 33        /// <param name="numChannels">The number of audio channels (default 1).</param>
 34        /// <param name="quality">The quality setting for the resampler (default Medium).</param>
 118235        public AudioResampler(
 118236            uint inputRate,
 118237            uint outputRate,
 118238            uint numChannels = 1,
 118239            SoxQualityRecipe quality = SoxQualityRecipe.SoxrQualityMedium
 118240        )
 118241        {
 118242            _inputRate = inputRate;
 118243            _outputRate = outputRate;
 118244            _numChannels = numChannels;
 45
 118246            var request = new FfiRequest
 118247            {
 118248                NewSoxResampler = new NewSoxResamplerRequest
 118249                {
 118250                    InputRate = inputRate,
 118251                    OutputRate = outputRate,
 118252                    NumChannels = numChannels,
 118253                    QualityRecipe = quality,
 118254                    InputDataType = SoxResamplerDataType.SoxrDatatypeInt16I,
 118255                    OutputDataType = SoxResamplerDataType.SoxrDatatypeInt16I,
 118256                    Flags = 0,
 118257                },
 118258            };
 59
 118260            var response = FfiClient.Instance.SendRequest(request);
 61
 118262            if (!string.IsNullOrEmpty(response.NewSoxResampler.Error))
 063            {
 064                throw new InvalidOperationException(
 065                    $"Failed to create resampler: {response.NewSoxResampler.Error}"
 066                );
 67            }
 68
 118269            _handle = FfiHandle.FromId(response.NewSoxResampler.Resampler.Handle.Id);
 118270        }
 71
 72        /// <summary>
 73        /// Gets the input sample rate.
 74        /// </summary>
 075        public uint InputRate => _inputRate;
 76
 77        /// <summary>
 78        /// Gets the output sample rate.
 79        /// </summary>
 080        public uint OutputRate => _outputRate;
 81
 82        /// <summary>
 83        /// Gets the number of channels.
 84        /// </summary>
 085        public uint NumChannels => _numChannels;
 86
 87        /// <summary>
 88        /// Push audio data into the resampler and retrieve any available resampled data.
 89        /// </summary>
 90        /// <param name="frame">The audio frame to resample.</param>
 91        /// <returns>A list of resampled audio frames.</returns>
 92        public List<AudioFrame> Push(AudioFrame frame)
 102693        {
 102694            if (frame == null)
 095                throw new ArgumentNullException(nameof(frame));
 102696            if (frame.NumChannels != _numChannels)
 197                throw new ArgumentException(
 198                    $"The resampler takes {_numChannels}-channel audio, the frame has {frame.NumChannels} channels",
 199                    nameof(frame)
 1100                );
 1025101            if (frame.SampleRate != _inputRate)
 1102                throw new ArgumentException(
 1103                    $"The resampler takes {_inputRate} Hz audio, the frame is {frame.SampleRate} Hz",
 1104                    nameof(frame)
 1105                );
 1024106            return Push(frame.DataBytes);
 1023107        }
 108
 109        /// <summary>
 110        /// Push audio data into the resampler and retrieve any available resampled data.
 111        /// </summary>
 112        /// <param name="data">The raw audio data in int16le format.</param>
 113        /// <returns>A list of resampled audio frames.</returns>
 114        public unsafe List<AudioFrame> Push(byte[] data)
 2980115        {
 2980116            ThrowIfDisposed();
 117
 2675118            if (data == null || data.Length == 0)
 0119                return new List<AudioFrame>();
 120
 2675121            lock (_lock)
 2675122                fixed (byte* dataPtr = data)
 2675123                {
 124                    // Checked again under the lock: Dispose takes it before releasing the handle
 2675125                    ThrowIfDisposed();
 126
 2379127                    var request = new FfiRequest
 2379128                    {
 2379129                        PushSoxResampler = new PushSoxResamplerRequest
 2379130                        {
 2379131                            ResamplerHandle = _handle.HandleId,
 2379132                            DataPtr = (ulong)dataPtr,
 2379133                            Size = (uint)data.Length,
 2379134                        },
 2379135                    };
 136
 2379137                    var response = FfiClient.Instance.SendRequest(request);
 138
 2379139                    if (!string.IsNullOrEmpty(response.PushSoxResampler.Error))
 0140                    {
 0141                        throw new InvalidOperationException(
 0142                            $"Resampling failed: {response.PushSoxResampler.Error}"
 0143                        );
 144                    }
 145
 2379146                    if (response.PushSoxResampler.OutputPtr == 0)
 161147                    {
 161148                        return new List<AudioFrame>();
 149                    }
 150
 2218151                    var outputData = new byte[response.PushSoxResampler.Size];
 2218152                    Marshal.Copy(
 2218153                        (IntPtr)response.PushSoxResampler.OutputPtr,
 2218154                        outputData,
 2218155                        0,
 2218156                        (int)response.PushSoxResampler.Size
 2218157                    );
 158
 2218159                    var samplesPerChannel = outputData.Length / ((int)_numChannels * sizeof(short));
 2218160                    var frame = new AudioFrame(
 2218161                        outputData,
 2218162                        (int)_outputRate,
 2218163                        (int)_numChannels,
 2218164                        samplesPerChannel
 2218165                    );
 166
 2218167                    return new List<AudioFrame> { frame };
 168                }
 2379169        }
 170
 171        /// <summary>
 172        /// Flush any remaining audio data through the resampler.
 173        /// Call this when no more input data will be provided.
 174        /// </summary>
 175        /// <returns>A list of remaining resampled audio frames.</returns>
 176        public List<AudioFrame> Flush()
 463177        {
 463178            ThrowIfDisposed();
 179
 463180            var request = new FfiRequest
 463181            {
 463182                FlushSoxResampler = new FlushSoxResamplerRequest
 463183                {
 463184                    ResamplerHandle = _handle.HandleId,
 463185                },
 463186            };
 187
 463188            lock (_lock)
 463189            {
 463190                ThrowIfDisposed();
 463191                var response = FfiClient.Instance.SendRequest(request);
 192
 463193                if (!string.IsNullOrEmpty(response.FlushSoxResampler.Error))
 0194                {
 0195                    throw new InvalidOperationException(
 0196                        $"Resampling failed: {response.FlushSoxResampler.Error}"
 0197                    );
 198                }
 199
 200                // An empty flush returns a valid pointer with a size of 0: no frame to return
 463201                if (
 463202                    response.FlushSoxResampler.OutputPtr == 0
 463203                    || response.FlushSoxResampler.Size == 0
 463204                )
 41205                {
 41206                    return new List<AudioFrame>();
 207                }
 208
 422209                var outputData = new byte[response.FlushSoxResampler.Size];
 422210                Marshal.Copy(
 422211                    (IntPtr)response.FlushSoxResampler.OutputPtr,
 422212                    outputData,
 422213                    0,
 422214                    (int)response.FlushSoxResampler.Size
 422215                );
 216
 422217                var samplesPerChannel = outputData.Length / ((int)_numChannels * sizeof(short));
 422218                var frame = new AudioFrame(
 422219                    outputData,
 422220                    (int)_outputRate,
 422221                    (int)_numChannels,
 422222                    samplesPerChannel
 422223                );
 224
 422225                return new List<AudioFrame> { frame };
 226            }
 463227        }
 228
 229        private void ThrowIfDisposed()
 6581230        {
 6581231            if (_disposed)
 601232                throw new ObjectDisposedException(nameof(AudioResampler));
 5980233        }
 234
 235        /// <summary>
 236        /// Releases the native resampler. Call <see cref="Flush"/> first to get the audio it still buffers.
 237        /// A <see cref="Push(byte[])"/> or <see cref="Flush"/> running on another thread completes first;
 238        /// later calls throw <see cref="ObjectDisposedException"/>.
 239        /// </summary>
 240        public void Dispose()
 1089241        {
 1089242            if (_disposed)
 175243                return;
 244
 245            // Set before taking the lock: new Push and Flush calls fail fast instead of competing
 246            // for it, so a thread pushing in a loop cannot hold Dispose off
 914247            _disposed = true;
 248
 249            // Under the lock: the output of an in-flight Push or Flush is read from the native
 250            // resampler's own buffer, which releasing the handle frees. Releasing a SafeHandle
 251            // twice is harmless, so concurrent Dispose calls need no more than this.
 914252            lock (_lock)
 914253            {
 914254                _handle.Dispose();
 914255            }
 1089256        }
 257    }
 258}