< Summary

Information
Line coverage
95%
Covered lines: 160
Uncovered lines: 8
Coverable lines: 168
Total lines: 326
Line coverage: 95.2%
Branch coverage
86%
Covered branches: 31
Total branches: 36
Branch coverage: 86.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_SampleRate()100%11100%
get_NumChannels()100%11100%
get_Handle()100%11100%
get_QueuedDuration()100%11100%
ClearQueue()100%11100%
CaptureFrameAsync()87.5%1616100%
CaptureFrame(...)100%11100%
WaitForPlayoutAsync()83.33%6689.47%
ReleaseWaiter()100%22100%
CreateTrack(...)100%1176.92%
Dispose()100%66100%
.ctor(...)100%11100%
ReleaseHandle()50%4485%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Diagnostics;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using LiveKit.Proto;
 8using LiveKit.Rtc.Internal;
 9
 10namespace LiveKit.Rtc
 11{
 12    /// <summary>
 13    /// Represents a real-time audio source with an internal audio queue.
 14    /// The AudioSource class allows you to push audio frames into a real-time audio
 15    /// source, managing an internal queue of audio data.
 16    /// </summary>
 17    public class AudioSource : IDisposable
 18    {
 19        private readonly int _sampleRate;
 20        private readonly int _numChannels;
 21        private readonly FfiHandle _handle;
 127322        private readonly Stopwatch _stopwatch = new Stopwatch();
 23
 24        private readonly int _queueSizeMs;
 25
 26        // Playout bookkeeping, shared by CaptureFrameAsync, the drain timer and Dispose
 127327        private readonly object _playoutLock = new object();
 28        private double _lastCapture;
 29        private double _queueSize;
 30        private TaskCompletionSource<bool>? _playoutTcs;
 31        private CancellationTokenSource? _playoutCts;
 32        private bool _disposed;
 33
 34        /// <summary>
 35        /// Initializes a new instance of the audio source.
 36        /// </summary>
 37        /// <param name="sampleRate">The sample rate of the audio source in Hz.</param>
 38        /// <param name="numChannels">The number of audio channels.</param>
 39        /// <param name="queueSizeMs">The buffer size of the audio queue in milliseconds. Defaults to 1000 ms.</param>
 127340        public AudioSource(int sampleRate, int numChannels, int queueSizeMs = 1000)
 127341        {
 127342            _sampleRate = sampleRate;
 127343            _numChannels = numChannels;
 127344            _queueSizeMs = queueSizeMs;
 127345            _stopwatch.Start();
 46
 127347            var request = new FfiRequest
 127348            {
 127349                NewAudioSource = new NewAudioSourceRequest
 127350                {
 127351                    Type = AudioSourceType.AudioSourceNative,
 127352                    SampleRate = (uint)sampleRate,
 127353                    NumChannels = (uint)numChannels,
 127354                    QueueSizeMs = (uint)queueSizeMs,
 127355                },
 127356            };
 57
 127358            var response = FfiClient.Instance.SendRequest(request);
 127359            var sourceInfo = response.NewAudioSource.Source;
 127360            _handle = new SourceHandle(sourceInfo.Handle.Id);
 127361        }
 62
 63        /// <summary>
 64        /// Gets the sample rate of the audio source in Hz.
 65        /// </summary>
 964166        public int SampleRate => _sampleRate;
 67
 68        /// <summary>
 69        /// Gets the number of audio channels.
 70        /// </summary>
 4171        public int NumChannels => _numChannels;
 72
 73        /// <summary>
 74        /// Gets the internal FFI handle.
 75        /// </summary>
 88776        internal FfiHandle Handle => _handle;
 77
 78        /// <summary>
 79        /// Gets the current duration (in seconds) of audio data queued for playback.
 80        /// </summary>
 81        public double QueuedDuration
 82        {
 83            get
 284            {
 285                double elapsed = _stopwatch.Elapsed.TotalSeconds;
 286                return Math.Max(_queueSize - elapsed + _lastCapture, 0.0);
 287            }
 88        }
 89
 90        /// <summary>
 91        /// Clears the internal audio queue, discarding all buffered audio data.
 92        /// </summary>
 93        public void ClearQueue()
 22294        {
 22295            var request = new FfiRequest
 22296            {
 22297                ClearAudioBuffer = new ClearAudioBufferRequest { SourceHandle = _handle.HandleId },
 22298            };
 99
 222100            FfiClient.Instance.SendRequest(request);
 221101            ReleaseWaiter();
 221102        }
 103
 104        /// <summary>
 105        /// Captures an AudioFrame and queues it for playback.
 106        /// </summary>
 107        /// <param name="frame">The audio frame to capture and queue.</param>
 108        /// <param name="cancellationToken">
 109        /// Cancels the wait for the native source to accept the frame, not the capture itself: the source
 110        /// keeps consuming the frame, and a capture made before it is done fails with
 111        /// <see cref="InvalidOperationException"/>. Await each capture before the next one. A token that is
 112        /// already cancelled throws before the frame is captured.
 113        /// </param>
 114        /// <returns>A task that completes once the native source has accepted the frame.</returns>
 115        public async Task CaptureFrameAsync(
 116            AudioFrame frame,
 117            CancellationToken cancellationToken = default
 118        )
 10482119        {
 120            // Before the frame reaches the native source, which would keep consuming it
 10482121            cancellationToken.ThrowIfCancellationRequested();
 10481122            if (frame.SamplesPerChannel == 0 || _disposed)
 1123                return;
 124
 10480125            var frameDuration = (double)frame.SamplesPerChannel / _sampleRate;
 126            CancellationTokenSource playoutCts;
 127            double drainDelaySeconds;
 10480128            lock (_playoutLock)
 10480129            {
 10480130                double now = _stopwatch.Elapsed.TotalSeconds;
 10480131                double elapsed = _lastCapture == 0.0 ? 0.0 : now - _lastCapture;
 10480132                _queueSize += frameDuration - elapsed;
 10480133                _lastCapture = now;
 134
 135                // Restart the drain timer; anyone already waiting for the playout keeps waiting on
 136                // the same task (a new one per capture would strand earlier waiters)
 10480137                _playoutCts?.Cancel();
 10480138                _playoutCts?.Dispose();
 10480139                _playoutTcs ??= new TaskCompletionSource<bool>(
 10480140                    TaskCreationOptions.RunContinuationsAsynchronously
 10480141                );
 10480142                playoutCts = _playoutCts = new CancellationTokenSource();
 10480143                drainDelaySeconds = Math.Max(0.0, Math.Min(_queueSize, int.MaxValue / 1000.0 - 1));
 10480144            }
 145
 10480146            _ = Task.Delay(TimeSpan.FromSeconds(drainDelaySeconds), playoutCts.Token)
 11139147                .ContinueWith(_ => ReleaseWaiter(), TaskContinuationOptions.OnlyOnRanToCompletion);
 148
 149            // The FFI copies the samples before SendRequest returns. Keep them pinned
 150            // through request serialization and the native call, but not the callback wait.
 10480151            var response = frame.WithPinnedBuffer(buffer =>
 10480152                FfiClient.Instance.SendRequest(
 10480153                    new FfiRequest
 10480154                    {
 10480155                        CaptureAudioFrame = new CaptureAudioFrameRequest
 10480156                        {
 10480157                            SourceHandle = _handle.HandleId,
 10480158                            Buffer = buffer,
 10480159                        },
 10480160                    }
 10480161                )
 10480162            );
 10480163            var asyncId = response.CaptureAudioFrame.AsyncId;
 164
 165            // The callback only arrives once the whole frame has been accepted into the native
 166            // queue, which for a long frame takes about its duration minus the queue size: wait
 167            // for that plus a margin instead of a fixed 10 s (which rejected 15 s clips).
 10480168            var timeout =
 10480169                TimeSpan.FromSeconds(10)
 10480170                + TimeSpan.FromSeconds(frameDuration)
 10480171                + TimeSpan.FromMilliseconds(_queueSizeMs);
 172            // Not resumed on the caller's context: CaptureFrame blocks on this method, which
 173            // would deadlock a UI thread
 10480174            var callbackEvent = await FfiClient
 10480175                .Instance.WaitForEventAsync(
 10481261176                    e => e.CaptureAudioFrame?.AsyncId == asyncId,
 10480177                    timeout,
 10480178                    cancellationToken
 10480179                )
 10480180                .ConfigureAwait(false);
 181
 10459182            if (!string.IsNullOrEmpty(callbackEvent.CaptureAudioFrame?.Error))
 36183            {
 36184                throw new InvalidOperationException(
 36185                    $"Audio capture failed: {callbackEvent.CaptureAudioFrame.Error}"
 36186                );
 187            }
 10424188        }
 189
 190        /// <summary>
 191        /// Captures an AudioFrame and blocks the calling thread until the native source accepts it, which
 192        /// can take a while when the queue is full. Prefer <see cref="CaptureFrameAsync"/> in asynchronous
 193        /// code.
 194        /// </summary>
 195        /// <param name="frame">The audio frame to capture and queue.</param>
 196        public void CaptureFrame(AudioFrame frame)
 205197        {
 205198            CaptureFrameAsync(frame).GetAwaiter().GetResult();
 205199        }
 200
 201        /// <summary>
 202        /// Waits for the audio source to finish playing out all audio data.
 203        /// </summary>
 204        /// <param name="cancellationToken">Cancels this wait only; the queued audio keeps playing.</param>
 205        /// <returns>A task that completes when all queued audio has been played out.</returns>
 206        public async Task WaitForPlayoutAsync(CancellationToken cancellationToken = default)
 5207        {
 208            Task playout;
 5209            lock (_playoutLock)
 5210            {
 5211                if (_playoutTcs == null)
 0212                    return;
 5213                playout = _playoutTcs.Task;
 5214            }
 215
 5216            if (!cancellationToken.CanBeCanceled)
 4217            {
 4218                await playout.ConfigureAwait(false);
 4219                return;
 220            }
 221
 222            // Cancel this wait only, not the shared playout task of the other waiters
 1223            var cancelled = new TaskCompletionSource<bool>(
 1224                TaskCreationOptions.RunContinuationsAsynchronously
 1225            );
 2226            using (cancellationToken.Register(() => cancelled.TrySetCanceled(cancellationToken)))
 1227            {
 1228                var completed = await Task.WhenAny(playout, cancelled.Task).ConfigureAwait(false);
 1229                await completed.ConfigureAwait(false);
 0230            }
 4231        }
 232
 233        private void ReleaseWaiter()
 1835234        {
 235            TaskCompletionSource<bool>? waiter;
 1835236            lock (_playoutLock)
 1835237            {
 1835238                waiter = _playoutTcs;
 1835239                _playoutTcs = null;
 1835240                _lastCapture = 0.0;
 1835241                _queueSize = 0.0;
 1835242            }
 1835243            waiter?.TrySetResult(true);
 1835244        }
 245
 246        /// <summary>
 247        /// Creates a local audio track from this audio source.
 248        /// </summary>
 249        /// <param name="name">The name of the track.</param>
 250        /// <returns>A new LocalAudioTrack.</returns>
 251        public LocalAudioTrack CreateTrack(string name = "audio")
 1252        {
 1253            var request = new FfiRequest
 1254            {
 1255                CreateAudioTrack = new CreateAudioTrackRequest
 1256                {
 1257                    Name = name,
 1258                    SourceHandle = _handle.HandleId,
 1259                },
 1260            };
 261
 1262            var response = FfiClient.Instance.SendRequest(request);
 0263            var trackInfo = response.CreateAudioTrack.Track;
 264
 0265            return new LocalAudioTrack(FfiHandle.FromId(trackInfo.Handle.Id), trackInfo);
 0266        }
 267
 268        /// <summary>
 269        /// Releases the native source. Queued audio is dropped and pending
 270        /// <see cref="WaitForPlayoutAsync"/> calls complete.
 271        /// </summary>
 272        public void Dispose()
 1130273        {
 1130274            if (_disposed)
 175275                return;
 955276            _disposed = true;
 277
 278            // Nothing will play out anymore: do not leave WaitForPlayoutAsync callers hanging
 955279            lock (_playoutLock)
 955280            {
 955281                _playoutCts?.Cancel();
 955282                _playoutCts?.Dispose();
 955283                _playoutCts = null;
 955284            }
 955285            ReleaseWaiter();
 955286            _handle.Dispose();
 1130287        }
 288
 289        // The native source (webrtc-sys AudioTrackSource) frees its queue before it stops the
 290        // 10 ms task that plays the queue out, and without the lock that task holds. A release
 291        // that lands while the task erases played samples leaves the task spinning forever, which
 292        // hangs the thread that released the source (it waits for the task's thread), or lets it
 293        // read the freed queue and crash the process. An empty queue leaves the task nothing to
 294        // erase, so every release, by Dispose or by the finalizer, first empties it under that
 295        // lock. Audio captured while the release runs can still refill it.
 296        private sealed class SourceHandle : FfiHandle
 297        {
 298            internal SourceHandle(ulong handleId)
 3819299                : base(handleId) { }
 300
 301            protected override bool ReleaseHandle()
 1273302            {
 1273303                if (!IsInvalid && !FfiClient.Instance.IsDisposed)
 1273304                {
 305                    try
 1273306                    {
 1273307                        FfiClient.Instance.SendRequest(
 1273308                            new FfiRequest
 1273309                            {
 1273310                                ClearAudioBuffer = new ClearAudioBufferRequest
 1273311                                {
 1273312                                    SourceHandle = HandleId,
 1273313                                },
 1273314                            }
 1273315                        );
 1273316                    }
 0317                    catch (Exception)
 0318                    {
 319                        // The release itself must still happen
 0320                    }
 1273321                }
 1273322                return base.ReleaseHandle();
 1273323            }
 324        }
 325    }
 326}