< Summary

Information
Class: LiveKit.Rtc.AudioProcessingModule
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/AudioProcessingModule.cs
Line coverage
99%
Covered lines: 115
Uncovered lines: 1
Coverable lines: 116
Total lines: 212
Line coverage: 99.1%
Branch coverage
86%
Covered branches: 19
Total branches: 22
Branch coverage: 86.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
ProcessStream(...)100%11100%
ProcessReverseStream(...)100%11100%
SetStreamDelayMs(...)100%22100%
Process(...)87.5%1616100%
ThrowIfError(...)50%2275%
Dispose()100%22100%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using LiveKit.Proto;
 5using LiveKit.Rtc.Internal;
 6
 7namespace 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
 532        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>
 542        public AudioProcessingModule(
 543            bool echoCancellation = false,
 544            bool noiseSuppression = false,
 545            bool highPassFilter = false,
 546            bool autoGainControl = false
 547        )
 548        {
 549            var response = FfiClient.Instance.SendRequest(
 550                new FfiRequest
 551                {
 552                    NewApm = new NewApmRequest
 553                    {
 554                        EchoCancellerEnabled = echoCancellation,
 555                        NoiseSuppressionEnabled = noiseSuppression,
 556                        HighPassFilterEnabled = highPassFilter,
 557                        GainControllerEnabled = autoGainControl,
 558                    },
 559                }
 560            );
 561            _handle = FfiHandle.FromId(response.NewApm.Apm.Handle.Id);
 562        }
 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>
 15672        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>
 383        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)
 298        {
 299            lock (_lock)
 2100            {
 2101                if (_disposed)
 1102                    throw new ObjectDisposedException(nameof(AudioProcessingModule));
 1103                var response = FfiClient.Instance.SendRequest(
 1104                    new FfiRequest
 1105                    {
 1106                        ApmSetStreamDelay = new ApmSetStreamDelayRequest
 1107                        {
 1108                            ApmHandle = _handle.HandleId,
 1109                            DelayMs = delayMs,
 1110                        },
 1111                    }
 1112                );
 1113                ThrowIfError(response.ApmSetStreamDelay.Error);
 1114            }
 1115        }
 116
 117        private unsafe void Process(AudioFrame frame, bool reverse)
 159118        {
 159119            if (frame == null)
 1120                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
 158124            var data = frame.DataArray;
 158125            var totalSamples = frame.TotalSamples;
 158126            var samplesPer10Ms = (long)(frame.SampleRate / 100) * frame.NumChannels;
 158127            if (samplesPer10Ms <= 0 || totalSamples <= 0 || totalSamples % samplesPer10Ms != 0)
 4128                throw new ArgumentException(
 4129                    $"The frame must hold a whole number of 10 ms periods; it holds {frame.SamplesPerChannel} samples pe
 4130                    nameof(frame)
 4131                );
 132
 154133            lock (_lock)
 154134            {
 154135                if (_disposed)
 2136                    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
 152142                fixed (short* samples = data)
 152143                {
 152144                    var dataPtr = (ulong)samples;
 152145                    var size = (uint)(totalSamples * sizeof(short));
 152146                    var sampleRate = (uint)frame.SampleRate;
 152147                    var numChannels = (uint)frame.NumChannels;
 152148                    if (reverse)
 1149                    {
 1150                        error = FfiClient
 1151                            .Instance.SendRequest(
 1152                                new FfiRequest
 1153                                {
 1154                                    ApmProcessReverseStream = new ApmProcessReverseStreamRequest
 1155                                    {
 1156                                        ApmHandle = _handle.HandleId,
 1157                                        DataPtr = dataPtr,
 1158                                        Size = size,
 1159                                        SampleRate = sampleRate,
 1160                                        NumChannels = numChannels,
 1161                                    },
 1162                                }
 1163                            )
 1164                            .ApmProcessReverseStream.Error;
 1165                    }
 166                    else
 151167                    {
 151168                        error = FfiClient
 151169                            .Instance.SendRequest(
 151170                                new FfiRequest
 151171                                {
 151172                                    ApmProcessStream = new ApmProcessStreamRequest
 151173                                    {
 151174                                        ApmHandle = _handle.HandleId,
 151175                                        DataPtr = dataPtr,
 151176                                        Size = size,
 151177                                        SampleRate = sampleRate,
 151178                                        NumChannels = numChannels,
 151179                                    },
 151180                                }
 151181                            )
 151182                            .ApmProcessStream.Error;
 151183                    }
 152184                }
 185
 152186                ThrowIfError(error);
 152187            }
 152188        }
 189
 190        private static void ThrowIfError(string error)
 153191        {
 153192            if (!string.IsNullOrEmpty(error))
 0193                throw new InvalidOperationException($"Audio processing failed: {error}");
 153194        }
 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()
 6201        {
 6202            lock (_lock)
 6203            {
 6204                if (_disposed)
 1205                    return;
 5206                _disposed = true;
 5207                _handle.Dispose();
 5208            }
 5209            GC.SuppressFinalize(this);
 6210        }
 211    }
 212}