| | | 1 | | // author: https://github.com/pabloFuente |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Runtime.InteropServices; |
| | | 6 | | using LiveKit.Proto; |
| | | 7 | | using LiveKit.Rtc.Internal; |
| | | 8 | | |
| | | 9 | | namespace 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. |
| | 1182 | 25 | | 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> |
| | 1182 | 35 | | public AudioResampler( |
| | 1182 | 36 | | uint inputRate, |
| | 1182 | 37 | | uint outputRate, |
| | 1182 | 38 | | uint numChannels = 1, |
| | 1182 | 39 | | SoxQualityRecipe quality = SoxQualityRecipe.SoxrQualityMedium |
| | 1182 | 40 | | ) |
| | 1182 | 41 | | { |
| | 1182 | 42 | | _inputRate = inputRate; |
| | 1182 | 43 | | _outputRate = outputRate; |
| | 1182 | 44 | | _numChannels = numChannels; |
| | | 45 | | |
| | 1182 | 46 | | var request = new FfiRequest |
| | 1182 | 47 | | { |
| | 1182 | 48 | | NewSoxResampler = new NewSoxResamplerRequest |
| | 1182 | 49 | | { |
| | 1182 | 50 | | InputRate = inputRate, |
| | 1182 | 51 | | OutputRate = outputRate, |
| | 1182 | 52 | | NumChannels = numChannels, |
| | 1182 | 53 | | QualityRecipe = quality, |
| | 1182 | 54 | | InputDataType = SoxResamplerDataType.SoxrDatatypeInt16I, |
| | 1182 | 55 | | OutputDataType = SoxResamplerDataType.SoxrDatatypeInt16I, |
| | 1182 | 56 | | Flags = 0, |
| | 1182 | 57 | | }, |
| | 1182 | 58 | | }; |
| | | 59 | | |
| | 1182 | 60 | | var response = FfiClient.Instance.SendRequest(request); |
| | | 61 | | |
| | 1182 | 62 | | if (!string.IsNullOrEmpty(response.NewSoxResampler.Error)) |
| | 0 | 63 | | { |
| | 0 | 64 | | throw new InvalidOperationException( |
| | 0 | 65 | | $"Failed to create resampler: {response.NewSoxResampler.Error}" |
| | 0 | 66 | | ); |
| | | 67 | | } |
| | | 68 | | |
| | 1182 | 69 | | _handle = FfiHandle.FromId(response.NewSoxResampler.Resampler.Handle.Id); |
| | 1182 | 70 | | } |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// Gets the input sample rate. |
| | | 74 | | /// </summary> |
| | 0 | 75 | | public uint InputRate => _inputRate; |
| | | 76 | | |
| | | 77 | | /// <summary> |
| | | 78 | | /// Gets the output sample rate. |
| | | 79 | | /// </summary> |
| | 0 | 80 | | public uint OutputRate => _outputRate; |
| | | 81 | | |
| | | 82 | | /// <summary> |
| | | 83 | | /// Gets the number of channels. |
| | | 84 | | /// </summary> |
| | 0 | 85 | | 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) |
| | 1026 | 93 | | { |
| | 1026 | 94 | | if (frame == null) |
| | 0 | 95 | | throw new ArgumentNullException(nameof(frame)); |
| | 1026 | 96 | | if (frame.NumChannels != _numChannels) |
| | 1 | 97 | | throw new ArgumentException( |
| | 1 | 98 | | $"The resampler takes {_numChannels}-channel audio, the frame has {frame.NumChannels} channels", |
| | 1 | 99 | | nameof(frame) |
| | 1 | 100 | | ); |
| | 1025 | 101 | | if (frame.SampleRate != _inputRate) |
| | 1 | 102 | | throw new ArgumentException( |
| | 1 | 103 | | $"The resampler takes {_inputRate} Hz audio, the frame is {frame.SampleRate} Hz", |
| | 1 | 104 | | nameof(frame) |
| | 1 | 105 | | ); |
| | 1024 | 106 | | return Push(frame.DataBytes); |
| | 1023 | 107 | | } |
| | | 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) |
| | 2980 | 115 | | { |
| | 2980 | 116 | | ThrowIfDisposed(); |
| | | 117 | | |
| | 2675 | 118 | | if (data == null || data.Length == 0) |
| | 0 | 119 | | return new List<AudioFrame>(); |
| | | 120 | | |
| | 2675 | 121 | | lock (_lock) |
| | 2675 | 122 | | fixed (byte* dataPtr = data) |
| | 2675 | 123 | | { |
| | | 124 | | // Checked again under the lock: Dispose takes it before releasing the handle |
| | 2675 | 125 | | ThrowIfDisposed(); |
| | | 126 | | |
| | 2379 | 127 | | var request = new FfiRequest |
| | 2379 | 128 | | { |
| | 2379 | 129 | | PushSoxResampler = new PushSoxResamplerRequest |
| | 2379 | 130 | | { |
| | 2379 | 131 | | ResamplerHandle = _handle.HandleId, |
| | 2379 | 132 | | DataPtr = (ulong)dataPtr, |
| | 2379 | 133 | | Size = (uint)data.Length, |
| | 2379 | 134 | | }, |
| | 2379 | 135 | | }; |
| | | 136 | | |
| | 2379 | 137 | | var response = FfiClient.Instance.SendRequest(request); |
| | | 138 | | |
| | 2379 | 139 | | if (!string.IsNullOrEmpty(response.PushSoxResampler.Error)) |
| | 0 | 140 | | { |
| | 0 | 141 | | throw new InvalidOperationException( |
| | 0 | 142 | | $"Resampling failed: {response.PushSoxResampler.Error}" |
| | 0 | 143 | | ); |
| | | 144 | | } |
| | | 145 | | |
| | 2379 | 146 | | if (response.PushSoxResampler.OutputPtr == 0) |
| | 161 | 147 | | { |
| | 161 | 148 | | return new List<AudioFrame>(); |
| | | 149 | | } |
| | | 150 | | |
| | 2218 | 151 | | var outputData = new byte[response.PushSoxResampler.Size]; |
| | 2218 | 152 | | Marshal.Copy( |
| | 2218 | 153 | | (IntPtr)response.PushSoxResampler.OutputPtr, |
| | 2218 | 154 | | outputData, |
| | 2218 | 155 | | 0, |
| | 2218 | 156 | | (int)response.PushSoxResampler.Size |
| | 2218 | 157 | | ); |
| | | 158 | | |
| | 2218 | 159 | | var samplesPerChannel = outputData.Length / ((int)_numChannels * sizeof(short)); |
| | 2218 | 160 | | var frame = new AudioFrame( |
| | 2218 | 161 | | outputData, |
| | 2218 | 162 | | (int)_outputRate, |
| | 2218 | 163 | | (int)_numChannels, |
| | 2218 | 164 | | samplesPerChannel |
| | 2218 | 165 | | ); |
| | | 166 | | |
| | 2218 | 167 | | return new List<AudioFrame> { frame }; |
| | | 168 | | } |
| | 2379 | 169 | | } |
| | | 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() |
| | 463 | 177 | | { |
| | 463 | 178 | | ThrowIfDisposed(); |
| | | 179 | | |
| | 463 | 180 | | var request = new FfiRequest |
| | 463 | 181 | | { |
| | 463 | 182 | | FlushSoxResampler = new FlushSoxResamplerRequest |
| | 463 | 183 | | { |
| | 463 | 184 | | ResamplerHandle = _handle.HandleId, |
| | 463 | 185 | | }, |
| | 463 | 186 | | }; |
| | | 187 | | |
| | 463 | 188 | | lock (_lock) |
| | 463 | 189 | | { |
| | 463 | 190 | | ThrowIfDisposed(); |
| | 463 | 191 | | var response = FfiClient.Instance.SendRequest(request); |
| | | 192 | | |
| | 463 | 193 | | if (!string.IsNullOrEmpty(response.FlushSoxResampler.Error)) |
| | 0 | 194 | | { |
| | 0 | 195 | | throw new InvalidOperationException( |
| | 0 | 196 | | $"Resampling failed: {response.FlushSoxResampler.Error}" |
| | 0 | 197 | | ); |
| | | 198 | | } |
| | | 199 | | |
| | | 200 | | // An empty flush returns a valid pointer with a size of 0: no frame to return |
| | 463 | 201 | | if ( |
| | 463 | 202 | | response.FlushSoxResampler.OutputPtr == 0 |
| | 463 | 203 | | || response.FlushSoxResampler.Size == 0 |
| | 463 | 204 | | ) |
| | 41 | 205 | | { |
| | 41 | 206 | | return new List<AudioFrame>(); |
| | | 207 | | } |
| | | 208 | | |
| | 422 | 209 | | var outputData = new byte[response.FlushSoxResampler.Size]; |
| | 422 | 210 | | Marshal.Copy( |
| | 422 | 211 | | (IntPtr)response.FlushSoxResampler.OutputPtr, |
| | 422 | 212 | | outputData, |
| | 422 | 213 | | 0, |
| | 422 | 214 | | (int)response.FlushSoxResampler.Size |
| | 422 | 215 | | ); |
| | | 216 | | |
| | 422 | 217 | | var samplesPerChannel = outputData.Length / ((int)_numChannels * sizeof(short)); |
| | 422 | 218 | | var frame = new AudioFrame( |
| | 422 | 219 | | outputData, |
| | 422 | 220 | | (int)_outputRate, |
| | 422 | 221 | | (int)_numChannels, |
| | 422 | 222 | | samplesPerChannel |
| | 422 | 223 | | ); |
| | | 224 | | |
| | 422 | 225 | | return new List<AudioFrame> { frame }; |
| | | 226 | | } |
| | 463 | 227 | | } |
| | | 228 | | |
| | | 229 | | private void ThrowIfDisposed() |
| | 6581 | 230 | | { |
| | 6581 | 231 | | if (_disposed) |
| | 601 | 232 | | throw new ObjectDisposedException(nameof(AudioResampler)); |
| | 5980 | 233 | | } |
| | | 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() |
| | 1089 | 241 | | { |
| | 1089 | 242 | | if (_disposed) |
| | 175 | 243 | | 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 |
| | 914 | 247 | | _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. |
| | 914 | 252 | | lock (_lock) |
| | 914 | 253 | | { |
| | 914 | 254 | | _handle.Dispose(); |
| | 914 | 255 | | } |
| | 1089 | 256 | | } |
| | | 257 | | } |
| | | 258 | | } |