| | | 1 | | // author: https://github.com/pabloFuente |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using LiveKit.Proto; |
| | | 5 | | using LiveKit.Rtc.Internal; |
| | | 6 | | |
| | | 7 | | namespace LiveKit.Rtc |
| | | 8 | | { |
| | | 9 | | /// <summary> |
| | | 10 | | /// WebRTC audio processing (echo cancellation, noise suppression, high-pass filter and automatic |
| | | 11 | | /// gain control) applied in place to 16-bit audio, in frames of 10 ms (or a whole number of 10 ms |
| | | 12 | | /// periods). |
| | | 13 | | /// </summary> |
| | | 14 | | /// <example> |
| | | 15 | | /// Clean the audio captured from a microphone before publishing it, cancelling the echo of what |
| | | 16 | | /// the speaker plays: |
| | | 17 | | /// <code language="csharp"> |
| | | 18 | | /// using var apm = new AudioProcessingModule(echoCancellation: true, noiseSuppression: true); |
| | | 19 | | /// apm.SetStreamDelayMs(40); |
| | | 20 | | /// |
| | | 21 | | /// apm.ProcessReverseStream(playedFrame); // the 10 ms just sent to the speaker |
| | | 22 | | /// apm.ProcessStream(capturedFrame); // the 10 ms just captured, processed in place |
| | | 23 | | /// await source.CaptureFrameAsync(capturedFrame); |
| | | 24 | | /// </code> |
| | | 25 | | /// </example> |
| | | 26 | | public class AudioProcessingModule : IDisposable |
| | | 27 | | { |
| | | 28 | | private readonly FfiHandle _handle; |
| | | 29 | | |
| | | 30 | | // The module writes into the frame during the request: a request and the release of the |
| | | 31 | | // handle must not interleave between threads |
| | 5 | 32 | | private readonly object _lock = new object(); |
| | | 33 | | private bool _disposed; |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Creates an audio processing module with the given processing enabled. |
| | | 37 | | /// </summary> |
| | | 38 | | /// <param name="echoCancellation">Whether to cancel the echo of the reverse stream.</param> |
| | | 39 | | /// <param name="noiseSuppression">Whether to suppress background noise.</param> |
| | | 40 | | /// <param name="highPassFilter">Whether to remove low-frequency content, such as hum.</param> |
| | | 41 | | /// <param name="autoGainControl">Whether to adjust the level automatically.</param> |
| | 5 | 42 | | public AudioProcessingModule( |
| | 5 | 43 | | bool echoCancellation = false, |
| | 5 | 44 | | bool noiseSuppression = false, |
| | 5 | 45 | | bool highPassFilter = false, |
| | 5 | 46 | | bool autoGainControl = false |
| | 5 | 47 | | ) |
| | 5 | 48 | | { |
| | 5 | 49 | | var response = FfiClient.Instance.SendRequest( |
| | 5 | 50 | | new FfiRequest |
| | 5 | 51 | | { |
| | 5 | 52 | | NewApm = new NewApmRequest |
| | 5 | 53 | | { |
| | 5 | 54 | | EchoCancellerEnabled = echoCancellation, |
| | 5 | 55 | | NoiseSuppressionEnabled = noiseSuppression, |
| | 5 | 56 | | HighPassFilterEnabled = highPassFilter, |
| | 5 | 57 | | GainControllerEnabled = autoGainControl, |
| | 5 | 58 | | }, |
| | 5 | 59 | | } |
| | 5 | 60 | | ); |
| | 5 | 61 | | _handle = FfiHandle.FromId(response.NewApm.Apm.Handle.Id); |
| | 5 | 62 | | } |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Processes the near-end audio, the one captured locally, in place. |
| | | 66 | | /// </summary> |
| | | 67 | | /// <param name="frame">10 ms of audio, overwritten with the processed audio.</param> |
| | | 68 | | /// <exception cref="ArgumentException">The frame is not a whole number of 10 ms periods.</exception> |
| | | 69 | | /// <exception cref="ObjectDisposedException">The module was disposed.</exception> |
| | | 70 | | /// <exception cref="InvalidOperationException">The module rejected the frame, for example |
| | | 71 | | /// because of its sample rate.</exception> |
| | 156 | 72 | | public void ProcessStream(AudioFrame frame) => Process(frame, reverse: false); |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Processes the far-end audio, the one played locally, which the echo canceller removes from |
| | | 76 | | /// the near-end audio. Call it with each frame before it is played. |
| | | 77 | | /// </summary> |
| | | 78 | | /// <param name="frame">10 ms of audio, which the module may modify in place.</param> |
| | | 79 | | /// <exception cref="ArgumentException">The frame is not a whole number of 10 ms periods.</exception> |
| | | 80 | | /// <exception cref="ObjectDisposedException">The module was disposed.</exception> |
| | | 81 | | /// <exception cref="InvalidOperationException">The module rejected the frame, for example |
| | | 82 | | /// because of its sample rate.</exception> |
| | 3 | 83 | | public void ProcessReverseStream(AudioFrame frame) => Process(frame, reverse: true); |
| | | 84 | | |
| | | 85 | | /// <summary> |
| | | 86 | | /// Sets the delay between a far-end frame passed to <see cref="ProcessReverseStream"/> and the |
| | | 87 | | /// near-end frame passed to <see cref="ProcessStream"/> that contains its echo: |
| | | 88 | | /// <c>(t_render - t_analyze) + (t_process - t_capture)</c>, where <c>t_analyze</c> is when the |
| | | 89 | | /// frame was passed to <see cref="ProcessReverseStream"/> and <c>t_render</c> when the audio |
| | | 90 | | /// hardware played its first sample, <c>t_capture</c> when the hardware captured the first |
| | | 91 | | /// sample of a frame and <c>t_process</c> when it was passed to <see cref="ProcessStream"/>. |
| | | 92 | | /// Call it if and only if echo cancellation is enabled. |
| | | 93 | | /// </summary> |
| | | 94 | | /// <param name="delayMs">The delay in milliseconds.</param> |
| | | 95 | | /// <exception cref="ObjectDisposedException">The module was disposed.</exception> |
| | | 96 | | /// <exception cref="InvalidOperationException">The module rejected the delay.</exception> |
| | | 97 | | public void SetStreamDelayMs(int delayMs) |
| | 2 | 98 | | { |
| | 2 | 99 | | lock (_lock) |
| | 2 | 100 | | { |
| | 2 | 101 | | if (_disposed) |
| | 1 | 102 | | throw new ObjectDisposedException(nameof(AudioProcessingModule)); |
| | 1 | 103 | | var response = FfiClient.Instance.SendRequest( |
| | 1 | 104 | | new FfiRequest |
| | 1 | 105 | | { |
| | 1 | 106 | | ApmSetStreamDelay = new ApmSetStreamDelayRequest |
| | 1 | 107 | | { |
| | 1 | 108 | | ApmHandle = _handle.HandleId, |
| | 1 | 109 | | DelayMs = delayMs, |
| | 1 | 110 | | }, |
| | 1 | 111 | | } |
| | 1 | 112 | | ); |
| | 1 | 113 | | ThrowIfError(response.ApmSetStreamDelay.Error); |
| | 1 | 114 | | } |
| | 1 | 115 | | } |
| | | 116 | | |
| | | 117 | | private unsafe void Process(AudioFrame frame, bool reverse) |
| | 159 | 118 | | { |
| | 159 | 119 | | if (frame == null) |
| | 1 | 120 | | throw new ArgumentNullException(nameof(frame)); |
| | | 121 | | |
| | | 122 | | // The native module aborts the process (a Rust panic) on a buffer that is not a whole |
| | | 123 | | // number of 10 ms periods, so it must never receive one |
| | 158 | 124 | | var data = frame.DataArray; |
| | 158 | 125 | | var totalSamples = frame.TotalSamples; |
| | 158 | 126 | | var samplesPer10Ms = (long)(frame.SampleRate / 100) * frame.NumChannels; |
| | 158 | 127 | | if (samplesPer10Ms <= 0 || totalSamples <= 0 || totalSamples % samplesPer10Ms != 0) |
| | 4 | 128 | | throw new ArgumentException( |
| | 4 | 129 | | $"The frame must hold a whole number of 10 ms periods; it holds {frame.SamplesPerChannel} samples pe |
| | 4 | 130 | | nameof(frame) |
| | 4 | 131 | | ); |
| | | 132 | | |
| | 154 | 133 | | lock (_lock) |
| | 154 | 134 | | { |
| | 154 | 135 | | if (_disposed) |
| | 2 | 136 | | throw new ObjectDisposedException(nameof(AudioProcessingModule)); |
| | | 137 | | |
| | | 138 | | string error; |
| | | 139 | | |
| | | 140 | | // The module reads and writes the samples during the request: they stay pinned |
| | | 141 | | // until it returned |
| | 152 | 142 | | fixed (short* samples = data) |
| | 152 | 143 | | { |
| | 152 | 144 | | var dataPtr = (ulong)samples; |
| | 152 | 145 | | var size = (uint)(totalSamples * sizeof(short)); |
| | 152 | 146 | | var sampleRate = (uint)frame.SampleRate; |
| | 152 | 147 | | var numChannels = (uint)frame.NumChannels; |
| | 152 | 148 | | if (reverse) |
| | 1 | 149 | | { |
| | 1 | 150 | | error = FfiClient |
| | 1 | 151 | | .Instance.SendRequest( |
| | 1 | 152 | | new FfiRequest |
| | 1 | 153 | | { |
| | 1 | 154 | | ApmProcessReverseStream = new ApmProcessReverseStreamRequest |
| | 1 | 155 | | { |
| | 1 | 156 | | ApmHandle = _handle.HandleId, |
| | 1 | 157 | | DataPtr = dataPtr, |
| | 1 | 158 | | Size = size, |
| | 1 | 159 | | SampleRate = sampleRate, |
| | 1 | 160 | | NumChannels = numChannels, |
| | 1 | 161 | | }, |
| | 1 | 162 | | } |
| | 1 | 163 | | ) |
| | 1 | 164 | | .ApmProcessReverseStream.Error; |
| | 1 | 165 | | } |
| | | 166 | | else |
| | 151 | 167 | | { |
| | 151 | 168 | | error = FfiClient |
| | 151 | 169 | | .Instance.SendRequest( |
| | 151 | 170 | | new FfiRequest |
| | 151 | 171 | | { |
| | 151 | 172 | | ApmProcessStream = new ApmProcessStreamRequest |
| | 151 | 173 | | { |
| | 151 | 174 | | ApmHandle = _handle.HandleId, |
| | 151 | 175 | | DataPtr = dataPtr, |
| | 151 | 176 | | Size = size, |
| | 151 | 177 | | SampleRate = sampleRate, |
| | 151 | 178 | | NumChannels = numChannels, |
| | 151 | 179 | | }, |
| | 151 | 180 | | } |
| | 151 | 181 | | ) |
| | 151 | 182 | | .ApmProcessStream.Error; |
| | 151 | 183 | | } |
| | 152 | 184 | | } |
| | | 185 | | |
| | 152 | 186 | | ThrowIfError(error); |
| | 152 | 187 | | } |
| | 152 | 188 | | } |
| | | 189 | | |
| | | 190 | | private static void ThrowIfError(string error) |
| | 153 | 191 | | { |
| | 153 | 192 | | if (!string.IsNullOrEmpty(error)) |
| | 0 | 193 | | throw new InvalidOperationException($"Audio processing failed: {error}"); |
| | 153 | 194 | | } |
| | | 195 | | |
| | | 196 | | /// <summary> |
| | | 197 | | /// Releases the native module. A processing call in progress on another thread finishes |
| | | 198 | | /// first. |
| | | 199 | | /// </summary> |
| | | 200 | | public void Dispose() |
| | 6 | 201 | | { |
| | 6 | 202 | | lock (_lock) |
| | 6 | 203 | | { |
| | 6 | 204 | | if (_disposed) |
| | 1 | 205 | | return; |
| | 5 | 206 | | _disposed = true; |
| | 5 | 207 | | _handle.Dispose(); |
| | 5 | 208 | | } |
| | 5 | 209 | | GC.SuppressFinalize(this); |
| | 6 | 210 | | } |
| | | 211 | | } |
| | | 212 | | } |