< Summary

Information
Class: LiveKit.Rtc.AudioFrameEvent
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/AudioStream.cs
Line coverage
100%
Covered lines: 3
Uncovered lines: 0
Coverable lines: 3
Total lines: 550
Line coverage: 100%
Branch coverage
50%
Covered branches: 1
Total branches: 2
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%22100%

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)
 92929        {
 92930            Frame = frame ?? throw new ArgumentNullException(nameof(frame));
 92931        }
 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>
 83        public AudioStream(
 84            Track track,
 85            uint sampleRate = 48000,
 86            uint numChannels = 1,
 87            uint? frameSizeMs = null,
 88            int capacity = 0,
 89            NoiseCancellationOptions? noiseCancellation = null,
 90            FrameProcessor<AudioFrame>? frameProcessor = null
 91        )
 92        {
 93            _track = track ?? throw new ArgumentNullException(nameof(track));
 94            _sampleRate = sampleRate;
 95            _numChannels = numChannels;
 96            _frameSizeMs = frameSizeMs;
 97            _noiseCancellation = noiseCancellation;
 98            _frameProcessor = frameProcessor;
 99
 100            _channel = CreateChannel<AudioFrameEvent>(capacity);
 101            if (frameProcessor != null)
 102                _processorInput = CreateChannel<AudioFrame>(capacity);
 103
 104            _cts = new CancellationTokenSource();
 105
 106            OwnedAudioStream stream;
 107            if (_participant != null && _trackSource.HasValue)
 108            {
 109                stream = CreateOwnedStreamFromParticipant();
 110            }
 111            else
 112            {
 113                stream = CreateOwnedStream();
 114            }
 115
 116            _handle = FfiHandle.FromId(stream.Handle.Id);
 117            Start();
 118        }
 119
 120        /// <summary>
 121        /// Private constructor for creating AudioStream from participant.
 122        /// </summary>
 123        private AudioStream(
 124            Participant participant,
 125            Proto.TrackSource trackSource,
 126            uint sampleRate,
 127            uint numChannels,
 128            uint? frameSizeMs,
 129            int capacity,
 130            NoiseCancellationOptions? noiseCancellation,
 131            FrameProcessor<AudioFrame>? frameProcessor
 132        )
 133        {
 134            _participant = participant ?? throw new ArgumentNullException(nameof(participant));
 135            _trackSource = trackSource;
 136            _sampleRate = sampleRate;
 137            _numChannels = numChannels;
 138            _frameSizeMs = frameSizeMs;
 139            _noiseCancellation = noiseCancellation;
 140            _frameProcessor = frameProcessor;
 141
 142            _channel = CreateChannel<AudioFrameEvent>(capacity);
 143            if (frameProcessor != null)
 144                _processorInput = CreateChannel<AudioFrame>(capacity);
 145
 146            _cts = new CancellationTokenSource();
 147
 148            OwnedAudioStream stream;
 149            if (_participant != null && _trackSource.HasValue)
 150            {
 151                stream = CreateOwnedStreamFromParticipant();
 152            }
 153            else
 154            {
 155                stream = CreateOwnedStream();
 156            }
 157
 158            _handle = FfiHandle.FromId(stream.Handle.Id);
 159            Start();
 160        }
 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) =>
 165            capacity > 0
 166                ? Channel.CreateBounded<T>(
 167                    new BoundedChannelOptions(capacity)
 168                    {
 169                        FullMode = BoundedChannelFullMode.DropOldest,
 170                        SingleReader = false,
 171                        SingleWriter = true,
 172                    }
 173                )
 174                : Channel.CreateUnbounded<T>(
 175                    new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 176                );
 177
 178        private void Start()
 179        {
 180            FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent);
 181            if (_frameProcessor != null && _processorInput != null)
 182            {
 183                var processor = _frameProcessor;
 184                var input = _processorInput.Reader;
 185                _ = Task.Run(() => RunFrameProcessorAsync(processor, input));
 186            }
 187        }
 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        )
 211        {
 212            return new AudioStream(
 213                participant,
 214                trackSource,
 215                sampleRate,
 216                numChannels,
 217                frameSizeMs,
 218                capacity,
 219                noiseCancellation,
 220                frameProcessor
 221            );
 222        }
 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        )
 244        {
 245            return new AudioStream(
 246                track,
 247                sampleRate,
 248                numChannels,
 249                frameSizeMs,
 250                capacity,
 251                noiseCancellation,
 252                frameProcessor
 253            );
 254        }
 255
 256        /// <summary>
 257        /// Gets the internal handle.
 258        /// </summary>
 259        internal FfiHandle Handle => _handle;
 260
 261        /// <summary>
 262        /// Gets the sample rate.
 263        /// </summary>
 264        public uint SampleRate => _sampleRate;
 265
 266        /// <summary>
 267        /// Gets the number of channels.
 268        /// </summary>
 269        public uint NumChannels => _numChannels;
 270
 271        private OwnedAudioStream CreateOwnedStream()
 272        {
 273            if (_track == null)
 274                throw new InvalidOperationException("Track is required for creating audio stream");
 275
 276            var request = new FfiRequest
 277            {
 278                NewAudioStream = new NewAudioStreamRequest
 279                {
 280                    TrackHandle = _track.Handle.HandleId,
 281                    SampleRate = _sampleRate,
 282                    NumChannels = _numChannels,
 283                    Type = AudioStreamType.AudioStreamNative,
 284                    // Unbounded native queue, like the Python SDK: the frames are dropped only by
 285                    // the channel of this stream, by its capacity, never while the managed side is
 286                    // paused (by a long garbage collection, for example)
 287                    QueueSizeFrames = 0,
 288                },
 289            };
 290
 291            if (_frameSizeMs.HasValue)
 292            {
 293                request.NewAudioStream.FrameSizeMs = _frameSizeMs.Value;
 294            }
 295
 296            if (_noiseCancellation != null)
 297            {
 298                request.NewAudioStream.AudioFilterModuleId = _noiseCancellation.ModuleId;
 299                if (!string.IsNullOrEmpty(_noiseCancellation.OptionsJson))
 300                {
 301                    request.NewAudioStream.AudioFilterOptions = _noiseCancellation.OptionsJson;
 302                }
 303            }
 304
 305            var response = FfiClient.Instance.SendRequest(request);
 306            return response.NewAudioStream.Stream;
 307        }
 308
 309        private OwnedAudioStream CreateOwnedStreamFromParticipant()
 310        {
 311            if (_participant == null || !_trackSource.HasValue)
 312                throw new InvalidOperationException(
 313                    "Participant and track source are required for creating audio stream"
 314                );
 315
 316            var request = new FfiRequest
 317            {
 318                AudioStreamFromParticipant = new AudioStreamFromParticipantRequest
 319                {
 320                    ParticipantHandle = _participant.Handle.HandleId,
 321                    TrackSource = (Proto.TrackSource)_trackSource.Value,
 322                    SampleRate = _sampleRate,
 323                    NumChannels = _numChannels,
 324                    Type = AudioStreamType.AudioStreamNative,
 325                    QueueSizeFrames = 0,
 326                },
 327            };
 328
 329            if (_frameSizeMs.HasValue)
 330            {
 331                request.AudioStreamFromParticipant.FrameSizeMs = _frameSizeMs.Value;
 332            }
 333
 334            if (_noiseCancellation != null)
 335            {
 336                request.AudioStreamFromParticipant.AudioFilterModuleId =
 337                    _noiseCancellation.ModuleId;
 338                if (!string.IsNullOrEmpty(_noiseCancellation.OptionsJson))
 339                {
 340                    request.AudioStreamFromParticipant.AudioFilterOptions =
 341                        _noiseCancellation.OptionsJson;
 342                }
 343            }
 344
 345            var response = FfiClient.Instance.SendRequest(request);
 346            return response.AudioStreamFromParticipant.Stream;
 347        }
 348
 349        private void OnFfiEvent(FfiEvent e)
 350        {
 351            if (e.MessageCase != FfiEvent.MessageOneofCase.AudioStreamEvent)
 352                return;
 353
 354            var audioEvent = e.AudioStreamEvent;
 355            if (audioEvent.StreamHandle != _handle.HandleId)
 356                return;
 357
 358            if (audioEvent.MessageCase == AudioStreamEvent.MessageOneofCase.FrameReceived)
 359            {
 360                var ownedBuffer = audioEvent.FrameReceived.Frame;
 361                if (_disposed)
 362                {
 363                    // The native task can still emit a few frames after the stream was closed:
 364                    // release their buffers instead of leaking them
 365                    FfiHandle.FromId(ownedBuffer.Handle.Id).Dispose();
 366                    return;
 367                }
 368
 369                var frame = AudioFrame.FromOwnedInfo(ownedBuffer);
 370                if (_processorInput != null)
 371                    _processorInput.Writer.TryWrite(frame);
 372                else
 373                    _channel.Writer.TryWrite(new AudioFrameEvent(frame));
 374            }
 375            else if (audioEvent.MessageCase == AudioStreamEvent.MessageOneofCase.Eos)
 376            {
 377                // With a frame processor, its task completes the channel after the last frame
 378                if (_processorInput != null)
 379                    _processorInput.Writer.TryComplete();
 380                else
 381                    _channel.Writer.TryComplete();
 382                // Nothing more will come for this handle
 383                FfiClient.Instance.RemoveStreamHandler(_handle.HandleId);
 384            }
 385        }
 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        )
 393        {
 394            try
 395            {
 396                while (await input.WaitToReadAsync().ConfigureAwait(false))
 397                {
 398                    while (input.TryRead(out var frame))
 399                    {
 400                        if (_disposed)
 401                            return;
 402                        _channel.Writer.TryWrite(new AudioFrameEvent(Process(processor, frame)));
 403                    }
 404                }
 405            }
 406            finally
 407            {
 408                _channel.Writer.TryComplete();
 409            }
 410        }
 411
 412        private static AudioFrame Process(FrameProcessor<AudioFrame> processor, AudioFrame frame)
 413        {
 414            try
 415            {
 416                return processor.IsEnabled ? processor.Process(frame) ?? frame : frame;
 417            }
 418            catch (Exception ex)
 419            {
 420                Console.Error.WriteLine(
 421                    $"[WARN] AudioStream: frame processor threw, passing the frame through: {ex}"
 422                );
 423                return frame;
 424            }
 425        }
 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()
 431        {
 432            _ = Task.Delay(TimeSpan.FromSeconds(5))
 433                .ContinueWith(
 434                    _ => FfiClient.Instance.RemoveStreamHandler(_handle.HandleId),
 435                    TaskScheduler.Default
 436                );
 437        }
 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        )
 447        {
 448            try
 449            {
 450                using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 451                    cancellationToken,
 452                    _cts.Token
 453                );
 454                if (await _channel.Reader.WaitToReadAsync(linkedCts.Token).ConfigureAwait(false))
 455                {
 456                    if (_channel.Reader.TryRead(out var frame))
 457                    {
 458                        return frame;
 459                    }
 460                }
 461                return null;
 462            }
 463            catch (OperationCanceledException)
 464            {
 465                return null;
 466            }
 467            catch (ChannelClosedException)
 468            {
 469                return null;
 470            }
 471        }
 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)
 479        {
 480            return _channel.Reader.TryRead(out frameEvent);
 481        }
 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        )
 491        {
 492            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 493                cancellationToken,
 494                _cts.Token
 495            );
 496
 497            await foreach (
 498                var frame in _channel.Reader.ReadAllAsync(linkedCts.Token).ConfigureAwait(false)
 499            )
 500            {
 501                yield return frame;
 502            }
 503        }
 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()
 509        {
 510            if (_disposed)
 511                return;
 512            _disposed = true;
 513
 514            _cts.Cancel();
 515            StopListeningAfterEos();
 516            _processorInput?.Writer.TryComplete();
 517            _channel.Writer.TryComplete();
 518            _frameProcessor?.Close();
 519            _handle.Dispose();
 520            _cts.Dispose();
 521
 522            GC.SuppressFinalize(this);
 523        }
 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()
 530        {
 531            if (_disposed)
 532                return;
 533            _disposed = true;
 534
 535            _cts.Cancel();
 536            StopListeningAfterEos();
 537            _processorInput?.Writer.TryComplete();
 538            _channel.Writer.TryComplete();
 539
 540            // Wait for any pending reads to complete
 541            await Task.Yield();
 542
 543            _frameProcessor?.Close();
 544            _handle.Dispose();
 545            _cts.Dispose();
 546
 547            GC.SuppressFinalize(this);
 548        }
 549    }
 550}

Methods/Properties

.ctor(LiveKit.Rtc.AudioFrame)