< Summary

Information
Line coverage
84%
Covered lines: 249
Uncovered lines: 46
Coverable lines: 295
Total lines: 550
Line coverage: 84.4%
Branch coverage
72%
Covered branches: 61
Total branches: 84
Branch coverage: 72.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)62.5%8890%
.ctor(...)62.5%8890.62%
CreateChannel(...)100%22100%
Start()100%44100%
FromParticipant(...)100%11100%
FromTrack(...)100%11100%
get_Handle()100%11100%
get_SampleRate()100%11100%
get_NumChannels()100%11100%
CreateOwnedStream()37.5%11865.62%
CreateOwnedStreamFromParticipant()40%191055.88%
OnFfiEvent(...)85.71%151480.76%
RunFrameProcessorAsync()83.33%6693.75%
Process(...)75%44100%
StopListeningAfterEos()100%11100%
ReadAsync()100%4485%
TryRead(...)100%210%
GetAsyncEnumerator()50%22100%
Dispose()100%6692.3%
DisposeAsync()87.5%8892.85%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Runtime.CompilerServices;
 6using System.Threading;
 7using System.Threading.Channels;
 8using System.Threading.Tasks;
 9using LiveKit.Proto;
 10using LiveKit.Rtc.Internal;
 11
 12namespace LiveKit.Rtc
 13{
 14    /// <summary>
 15    /// Represents an audio frame received event.
 16    /// </summary>
 17    public readonly struct AudioFrameEvent
 18    {
 19        /// <summary>
 20        /// Gets the audio frame.
 21        /// </summary>
 22        public AudioFrame Frame { get; }
 23
 24        /// <summary>
 25        /// Initializes a new AudioFrameEvent.
 26        /// </summary>
 27        /// <param name="frame">The audio frame.</param>
 28        public AudioFrameEvent(AudioFrame frame)
 29        {
 30            Frame = frame ?? throw new ArgumentNullException(nameof(frame));
 31        }
 32    }
 33
 34    /// <summary>
 35    /// Options for noise cancellation processing.
 36    /// </summary>
 37    public class NoiseCancellationOptions
 38    {
 39        /// <summary>
 40        /// Gets or sets the noise cancellation module ID.
 41        /// </summary>
 42        public string ModuleId { get; set; } = string.Empty;
 43
 44        /// <summary>
 45        /// Gets or sets additional options as JSON.
 46        /// </summary>
 47        public string OptionsJson { get; set; } = string.Empty;
 48    }
 49
 50    /// <summary>
 51    /// An audio stream for receiving audio frames from a remote track or participant.
 52    /// Implements IAsyncEnumerable for modern async iteration patterns.
 53    /// </summary>
 54    public class AudioStream : IAsyncDisposable, IDisposable, IAsyncEnumerable<AudioFrameEvent>
 55    {
 56        private readonly FfiHandle _handle;
 57        private readonly Track? _track;
 58        private readonly Participant? _participant;
 59        private readonly Proto.TrackSource? _trackSource;
 60        private readonly uint _sampleRate;
 61        private readonly uint _numChannels;
 62        private readonly uint? _frameSizeMs;
 63        private readonly NoiseCancellationOptions? _noiseCancellation;
 64        private readonly FrameProcessor<AudioFrame>? _frameProcessor;
 65        private readonly Channel<AudioFrameEvent> _channel;
 66
 67        // With a frame processor, the frames go through it on a task of their own instead of on the
 68        // native thread that delivers them
 69        private readonly Channel<AudioFrame>? _processorInput;
 70        private readonly CancellationTokenSource _cts;
 71        private bool _disposed;
 72
 73        /// <summary>
 74        /// Initializes a new AudioStream from a track.
 75        /// </summary>
 76        /// <param name="track">The audio track to stream from.</param>
 77        /// <param name="sampleRate">The sample rate in Hz (default 48000).</param>
 78        /// <param name="numChannels">The number of channels (default 1).</param>
 79        /// <param name="frameSizeMs">Optional frame size in milliseconds.</param>
 80        /// <param name="capacity">The capacity of the internal channel (0 for unbounded).</param>
 81        /// <param name="noiseCancellation">Optional noise cancellation options.</param>
 82        /// <param name="frameProcessor">Optional frame processor for custom audio processing.</param>
 5383        public AudioStream(
 5384            Track track,
 5385            uint sampleRate = 48000,
 5386            uint numChannels = 1,
 5387            uint? frameSizeMs = null,
 5388            int capacity = 0,
 5389            NoiseCancellationOptions? noiseCancellation = null,
 5390            FrameProcessor<AudioFrame>? frameProcessor = null
 5391        )
 5392        {
 5393            _track = track ?? throw new ArgumentNullException(nameof(track));
 5394            _sampleRate = sampleRate;
 5395            _numChannels = numChannels;
 5396            _frameSizeMs = frameSizeMs;
 5397            _noiseCancellation = noiseCancellation;
 5398            _frameProcessor = frameProcessor;
 99
 53100            _channel = CreateChannel<AudioFrameEvent>(capacity);
 53101            if (frameProcessor != null)
 6102                _processorInput = CreateChannel<AudioFrame>(capacity);
 103
 53104            _cts = new CancellationTokenSource();
 105
 106            OwnedAudioStream stream;
 53107            if (_participant != null && _trackSource.HasValue)
 0108            {
 0109                stream = CreateOwnedStreamFromParticipant();
 0110            }
 111            else
 53112            {
 53113                stream = CreateOwnedStream();
 53114            }
 115
 53116            _handle = FfiHandle.FromId(stream.Handle.Id);
 53117            Start();
 53118        }
 119
 120        /// <summary>
 121        /// Private constructor for creating AudioStream from participant.
 122        /// </summary>
 3123        private AudioStream(
 3124            Participant participant,
 3125            Proto.TrackSource trackSource,
 3126            uint sampleRate,
 3127            uint numChannels,
 3128            uint? frameSizeMs,
 3129            int capacity,
 3130            NoiseCancellationOptions? noiseCancellation,
 3131            FrameProcessor<AudioFrame>? frameProcessor
 3132        )
 3133        {
 3134            _participant = participant ?? throw new ArgumentNullException(nameof(participant));
 3135            _trackSource = trackSource;
 3136            _sampleRate = sampleRate;
 3137            _numChannels = numChannels;
 3138            _frameSizeMs = frameSizeMs;
 3139            _noiseCancellation = noiseCancellation;
 3140            _frameProcessor = frameProcessor;
 141
 3142            _channel = CreateChannel<AudioFrameEvent>(capacity);
 3143            if (frameProcessor != null)
 1144                _processorInput = CreateChannel<AudioFrame>(capacity);
 145
 3146            _cts = new CancellationTokenSource();
 147
 148            OwnedAudioStream stream;
 3149            if (_participant != null && _trackSource.HasValue)
 3150            {
 3151                stream = CreateOwnedStreamFromParticipant();
 3152            }
 153            else
 0154            {
 0155                stream = CreateOwnedStream();
 0156            }
 157
 3158            _handle = FfiHandle.FromId(stream.Handle.Id);
 3159            Start();
 3160        }
 161
 162        // Bounded for backpressure, keeping the latest audio like VideoStream and the Python SDK, or
 163        // unbounded for high throughput
 164        private static Channel<T> CreateChannel<T>(int capacity) =>
 63165            capacity > 0
 63166                ? Channel.CreateBounded<T>(
 63167                    new BoundedChannelOptions(capacity)
 63168                    {
 63169                        FullMode = BoundedChannelFullMode.DropOldest,
 63170                        SingleReader = false,
 63171                        SingleWriter = true,
 63172                    }
 63173                )
 63174                : Channel.CreateUnbounded<T>(
 63175                    new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 63176                );
 177
 178        private void Start()
 56179        {
 56180            FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent);
 56181            if (_frameProcessor != null && _processorInput != null)
 7182            {
 7183                var processor = _frameProcessor;
 7184                var input = _processorInput.Reader;
 14185                _ = Task.Run(() => RunFrameProcessorAsync(processor, input));
 7186            }
 56187        }
 188
 189        /// <summary>
 190        /// Creates an AudioStream from a participant's track source.
 191        /// </summary>
 192        /// <param name="participant">The participant.</param>
 193        /// <param name="trackSource">The track source type.</param>
 194        /// <param name="sampleRate">The sample rate in Hz (default 48000).</param>
 195        /// <param name="numChannels">The number of channels (default 1).</param>
 196        /// <param name="frameSizeMs">Optional frame size in milliseconds.</param>
 197        /// <param name="capacity">The capacity of the internal channel.</param>
 198        /// <param name="noiseCancellation">Optional noise cancellation options.</param>
 199        /// <param name="frameProcessor">Optional frame processor for custom audio processing.</param>
 200        /// <returns>A new AudioStream instance.</returns>
 201        public static AudioStream FromParticipant(
 202            Participant participant,
 203            Proto.TrackSource trackSource,
 204            uint sampleRate = 48000,
 205            uint numChannels = 1,
 206            uint? frameSizeMs = null,
 207            int capacity = 0,
 208            NoiseCancellationOptions? noiseCancellation = null,
 209            FrameProcessor<AudioFrame>? frameProcessor = null
 210        )
 3211        {
 3212            return new AudioStream(
 3213                participant,
 3214                trackSource,
 3215                sampleRate,
 3216                numChannels,
 3217                frameSizeMs,
 3218                capacity,
 3219                noiseCancellation,
 3220                frameProcessor
 3221            );
 3222        }
 223
 224        /// <summary>
 225        /// Creates an AudioStream from an existing track.
 226        /// </summary>
 227        /// <param name="track">The track.</param>
 228        /// <param name="sampleRate">The sample rate in Hz (default 48000).</param>
 229        /// <param name="numChannels">The number of channels (default 1).</param>
 230        /// <param name="frameSizeMs">Optional frame size in milliseconds.</param>
 231        /// <param name="capacity">The capacity of the internal channel.</param>
 232        /// <param name="noiseCancellation">Optional noise cancellation options.</param>
 233        /// <param name="frameProcessor">Optional frame processor for custom audio processing.</param>
 234        /// <returns>A new AudioStream instance.</returns>
 235        public static AudioStream FromTrack(
 236            Track track,
 237            uint sampleRate = 48000,
 238            uint numChannels = 1,
 239            uint? frameSizeMs = null,
 240            int capacity = 0,
 241            NoiseCancellationOptions? noiseCancellation = null,
 242            FrameProcessor<AudioFrame>? frameProcessor = null
 243        )
 47244        {
 47245            return new AudioStream(
 47246                track,
 47247                sampleRate,
 47248                numChannels,
 47249                frameSizeMs,
 47250                capacity,
 47251                noiseCancellation,
 47252                frameProcessor
 47253            );
 47254        }
 255
 256        /// <summary>
 257        /// Gets the internal handle.
 258        /// </summary>
 1259        internal FfiHandle Handle => _handle;
 260
 261        /// <summary>
 262        /// Gets the sample rate.
 263        /// </summary>
 3264        public uint SampleRate => _sampleRate;
 265
 266        /// <summary>
 267        /// Gets the number of channels.
 268        /// </summary>
 2269        public uint NumChannels => _numChannels;
 270
 271        private OwnedAudioStream CreateOwnedStream()
 53272        {
 53273            if (_track == null)
 0274                throw new InvalidOperationException("Track is required for creating audio stream");
 275
 53276            var request = new FfiRequest
 53277            {
 53278                NewAudioStream = new NewAudioStreamRequest
 53279                {
 53280                    TrackHandle = _track.Handle.HandleId,
 53281                    SampleRate = _sampleRate,
 53282                    NumChannels = _numChannels,
 53283                    Type = AudioStreamType.AudioStreamNative,
 53284                    // Unbounded native queue, like the Python SDK: the frames are dropped only by
 53285                    // the channel of this stream, by its capacity, never while the managed side is
 53286                    // paused (by a long garbage collection, for example)
 53287                    QueueSizeFrames = 0,
 53288                },
 53289            };
 290
 53291            if (_frameSizeMs.HasValue)
 0292            {
 0293                request.NewAudioStream.FrameSizeMs = _frameSizeMs.Value;
 0294            }
 295
 53296            if (_noiseCancellation != null)
 0297            {
 0298                request.NewAudioStream.AudioFilterModuleId = _noiseCancellation.ModuleId;
 0299                if (!string.IsNullOrEmpty(_noiseCancellation.OptionsJson))
 0300                {
 0301                    request.NewAudioStream.AudioFilterOptions = _noiseCancellation.OptionsJson;
 0302                }
 0303            }
 304
 53305            var response = FfiClient.Instance.SendRequest(request);
 53306            return response.NewAudioStream.Stream;
 53307        }
 308
 309        private OwnedAudioStream CreateOwnedStreamFromParticipant()
 3310        {
 3311            if (_participant == null || !_trackSource.HasValue)
 0312                throw new InvalidOperationException(
 0313                    "Participant and track source are required for creating audio stream"
 0314                );
 315
 3316            var request = new FfiRequest
 3317            {
 3318                AudioStreamFromParticipant = new AudioStreamFromParticipantRequest
 3319                {
 3320                    ParticipantHandle = _participant.Handle.HandleId,
 3321                    TrackSource = (Proto.TrackSource)_trackSource.Value,
 3322                    SampleRate = _sampleRate,
 3323                    NumChannels = _numChannels,
 3324                    Type = AudioStreamType.AudioStreamNative,
 3325                    QueueSizeFrames = 0,
 3326                },
 3327            };
 328
 3329            if (_frameSizeMs.HasValue)
 0330            {
 0331                request.AudioStreamFromParticipant.FrameSizeMs = _frameSizeMs.Value;
 0332            }
 333
 3334            if (_noiseCancellation != null)
 0335            {
 0336                request.AudioStreamFromParticipant.AudioFilterModuleId =
 0337                    _noiseCancellation.ModuleId;
 0338                if (!string.IsNullOrEmpty(_noiseCancellation.OptionsJson))
 0339                {
 0340                    request.AudioStreamFromParticipant.AudioFilterOptions =
 0341                        _noiseCancellation.OptionsJson;
 0342                }
 0343            }
 344
 3345            var response = FfiClient.Instance.SendRequest(request);
 3346            return response.AudioStreamFromParticipant.Stream;
 3347        }
 348
 349        private void OnFfiEvent(FfiEvent e)
 985350        {
 985351            if (e.MessageCase != FfiEvent.MessageOneofCase.AudioStreamEvent)
 0352                return;
 353
 985354            var audioEvent = e.AudioStreamEvent;
 985355            if (audioEvent.StreamHandle != _handle.HandleId)
 0356                return;
 357
 985358            if (audioEvent.MessageCase == AudioStreamEvent.MessageOneofCase.FrameReceived)
 929359            {
 929360                var ownedBuffer = audioEvent.FrameReceived.Frame;
 929361                if (_disposed)
 0362                {
 363                    // The native task can still emit a few frames after the stream was closed:
 364                    // release their buffers instead of leaking them
 0365                    FfiHandle.FromId(ownedBuffer.Handle.Id).Dispose();
 0366                    return;
 367                }
 368
 929369                var frame = AudioFrame.FromOwnedInfo(ownedBuffer);
 929370                if (_processorInput != null)
 205371                    _processorInput.Writer.TryWrite(frame);
 372                else
 724373                    _channel.Writer.TryWrite(new AudioFrameEvent(frame));
 929374            }
 56375            else if (audioEvent.MessageCase == AudioStreamEvent.MessageOneofCase.Eos)
 56376            {
 377                // With a frame processor, its task completes the channel after the last frame
 56378                if (_processorInput != null)
 7379                    _processorInput.Writer.TryComplete();
 380                else
 49381                    _channel.Writer.TryComplete();
 382                // Nothing more will come for this handle
 56383                FfiClient.Instance.RemoveStreamHandler(_handle.HandleId);
 56384            }
 985385        }
 386
 387        // One frame at a time, in order, on a thread pool thread: a slow processor only delays this
 388        // stream, not the native thread that also delivers the events of every other stream and room
 389        private async Task RunFrameProcessorAsync(
 390            FrameProcessor<AudioFrame> processor,
 391            ChannelReader<AudioFrame> input
 392        )
 7393        {
 394            try
 7395            {
 212396                while (await input.WaitToReadAsync().ConfigureAwait(false))
 205397                {
 410398                    while (input.TryRead(out var frame))
 205399                    {
 205400                        if (_disposed)
 0401                            return;
 205402                        _channel.Writer.TryWrite(new AudioFrameEvent(Process(processor, frame)));
 205403                    }
 205404                }
 7405            }
 406            finally
 7407            {
 7408                _channel.Writer.TryComplete();
 7409            }
 7410        }
 411
 412        private static AudioFrame Process(FrameProcessor<AudioFrame> processor, AudioFrame frame)
 205413        {
 414            try
 205415            {
 205416                return processor.IsEnabled ? processor.Process(frame) ?? frame : frame;
 417            }
 31418            catch (Exception ex)
 31419            {
 31420                Console.Error.WriteLine(
 31421                    $"[WARN] AudioStream: frame processor threw, passing the frame through: {ex}"
 31422                );
 31423                return frame;
 424            }
 205425        }
 426
 427        // Keep receiving (and releasing) the frames the native side may still emit after the
 428        // stream is closed, until its end-of-stream event; stop listening after a grace period in
 429        // case it never comes.
 430        private void StopListeningAfterEos()
 55431        {
 55432            _ = Task.Delay(TimeSpan.FromSeconds(5))
 55433                .ContinueWith(
 55434                    _ => FfiClient.Instance.RemoveStreamHandler(_handle.HandleId),
 55435                    TaskScheduler.Default
 55436                );
 55437        }
 438
 439        /// <summary>
 440        /// Reads the next audio frame event from the stream.
 441        /// </summary>
 442        /// <param name="cancellationToken">Cancellation token.</param>
 443        /// <returns>The next audio frame event, or null if the stream has ended.</returns>
 444        public async ValueTask<AudioFrameEvent?> ReadAsync(
 445            CancellationToken cancellationToken = default
 446        )
 222447        {
 448            try
 222449            {
 222450                using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 222451                    cancellationToken,
 222452                    _cts.Token
 222453                );
 221454                if (await _channel.Reader.WaitToReadAsync(linkedCts.Token).ConfigureAwait(false))
 192455                {
 192456                    if (_channel.Reader.TryRead(out var frame))
 162457                    {
 162458                        return frame;
 459                    }
 30460                }
 30461                return null;
 462            }
 29463            catch (OperationCanceledException)
 29464            {
 29465                return null;
 466            }
 0467            catch (ChannelClosedException)
 0468            {
 0469                return null;
 470            }
 221471        }
 472
 473        /// <summary>
 474        /// Tries to read the next audio frame event without blocking.
 475        /// </summary>
 476        /// <param name="frameEvent">The frame event if available.</param>
 477        /// <returns>True if a frame was available.</returns>
 478        public bool TryRead(out AudioFrameEvent frameEvent)
 0479        {
 0480            return _channel.Reader.TryRead(out frameEvent);
 0481        }
 482
 483        /// <summary>
 484        /// Returns an async enumerator for iterating over audio frames.
 485        /// </summary>
 486        /// <param name="cancellationToken">Cancellation token.</param>
 487        /// <returns>An async enumerator of audio frame events.</returns>
 488        public async IAsyncEnumerator<AudioFrameEvent> GetAsyncEnumerator(
 489            CancellationToken cancellationToken = default
 490        )
 13491        {
 13492            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 13493                cancellationToken,
 13494                _cts.Token
 13495            );
 496
 13497            await foreach (
 907498                var frame in _channel.Reader.ReadAllAsync(linkedCts.Token).ConfigureAwait(false)
 499            )
 447500            {
 447501                yield return frame;
 434502            }
 13503        }
 504
 505        /// <summary>
 506        /// Stops the stream, closes the frame processor and releases the native stream. Pending reads return null and l
 507        /// </summary>
 508        public void Dispose()
 44509        {
 44510            if (_disposed)
 0511                return;
 44512            _disposed = true;
 513
 44514            _cts.Cancel();
 44515            StopListeningAfterEos();
 44516            _processorInput?.Writer.TryComplete();
 44517            _channel.Writer.TryComplete();
 44518            _frameProcessor?.Close();
 44519            _handle.Dispose();
 44520            _cts.Dispose();
 521
 44522            GC.SuppressFinalize(this);
 44523        }
 524
 525        /// <summary>
 526        /// Stops the stream, closes the frame processor and releases the native stream. Pending reads return null and l
 527        /// </summary>
 528        /// <returns>A task that completes once the stream is released.</returns>
 529        public async ValueTask DisposeAsync()
 11530        {
 11531            if (_disposed)
 0532                return;
 11533            _disposed = true;
 534
 11535            _cts.Cancel();
 11536            StopListeningAfterEos();
 11537            _processorInput?.Writer.TryComplete();
 11538            _channel.Writer.TryComplete();
 539
 540            // Wait for any pending reads to complete
 11541            await Task.Yield();
 542
 11543            _frameProcessor?.Close();
 11544            _handle.Dispose();
 11545            _cts.Dispose();
 546
 11547            GC.SuppressFinalize(this);
 11548        }
 549    }
 550}