< Summary

Information
Class: LiveKit.Rtc.VideoStreamFromHandle
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/VideoStream.cs
Line coverage
100%
Covered lines: 1
Uncovered lines: 0
Coverable lines: 1
Total lines: 413
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/VideoStream.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 a video frame received event.
 16    /// </summary>
 17    public readonly struct VideoFrameEvent
 18    {
 19        /// <summary>
 20        /// Gets the video frame.
 21        /// </summary>
 22        public VideoFrame Frame { get; }
 23
 24        /// <summary>
 25        /// Gets the timestamp in microseconds.
 26        /// </summary>
 27        public long TimestampUs { get; }
 28
 29        /// <summary>
 30        /// Gets the frame rotation.
 31        /// </summary>
 32        public Proto.VideoRotation Rotation { get; }
 33
 34        /// <summary>
 35        /// Gets the metadata the publisher sent with the frame (user timestamp, frame ID, user data),
 36        /// or null when it sent none. The publisher sends it with
 37        /// <see cref="VideoSource.CaptureFrame(VideoFrame, long, Proto.VideoRotation, Proto.FrameMetadata)"/>
 38        /// on a track published with <see cref="TrackPublishOptions.FrameMetadataFeatures"/>.
 39        /// </summary>
 40        public Proto.FrameMetadata? Metadata { get; }
 41
 42        /// <summary>
 43        /// Initializes a new VideoFrameEvent.
 44        /// </summary>
 45        /// <param name="frame">The video frame.</param>
 46        /// <param name="timestampUs">The timestamp in microseconds.</param>
 47        /// <param name="rotation">The frame rotation.</param>
 48        public VideoFrameEvent(VideoFrame frame, long timestampUs, Proto.VideoRotation rotation)
 49            : this(frame, timestampUs, rotation, null) { }
 50
 51        /// <summary>
 52        /// Initializes a new VideoFrameEvent with frame metadata.
 53        /// </summary>
 54        /// <param name="frame">The video frame.</param>
 55        /// <param name="timestampUs">The timestamp in microseconds.</param>
 56        /// <param name="rotation">The frame rotation.</param>
 57        /// <param name="metadata">The metadata sent with the frame, or null.</param>
 58        internal VideoFrameEvent(
 59            VideoFrame frame,
 60            long timestampUs,
 61            Proto.VideoRotation rotation,
 62            Proto.FrameMetadata? metadata
 63        )
 64        {
 65            Frame = frame ?? throw new ArgumentNullException(nameof(frame));
 66            TimestampUs = timestampUs;
 67            Rotation = rotation;
 68            Metadata = metadata;
 69        }
 70    }
 71
 72    /// <summary>
 73    /// A video stream for receiving video frames from a remote track or participant.
 74    /// Implements IAsyncEnumerable for modern async iteration patterns.
 75    /// </summary>
 76    public class VideoStream : IAsyncDisposable, IDisposable, IAsyncEnumerable<VideoFrameEvent>
 77    {
 78        private readonly FfiHandle _handle;
 79        private readonly Track? _track;
 80        private readonly VideoBufferType? _format;
 81        private readonly Channel<VideoFrameEvent> _channel;
 82        private readonly CancellationTokenSource _cts;
 83        private bool _disposed;
 84
 85        /// <summary>
 86        /// Initializes a new VideoStream from a track.
 87        /// </summary>
 88        /// <param name="track">The video track to stream from.</param>
 89        /// <param name="format">Optional video buffer format to convert to.</param>
 90        /// <param name="capacity">The capacity of the internal channel (0 for unbounded).</param>
 91        public VideoStream(Track track, VideoBufferType? format = null, int capacity = 0)
 92        {
 93            _track = track ?? throw new ArgumentNullException(nameof(track));
 94            _format = format;
 95
 96            _channel =
 97                capacity > 0
 98                    ? Channel.CreateBounded<VideoFrameEvent>(
 99                        new BoundedChannelOptions(capacity)
 100                        {
 101                            FullMode = BoundedChannelFullMode.DropOldest, // Drop oldest frames under backpressure
 102                            SingleReader = false,
 103                            SingleWriter = true,
 104                        }
 105                    )
 106                    : Channel.CreateUnbounded<VideoFrameEvent>(
 107                        new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 108                    );
 109
 110            _cts = new CancellationTokenSource();
 111
 112            var stream = CreateOwnedStream();
 113            _handle = FfiHandle.FromId(stream.Handle.Id);
 114
 115            FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent);
 116        }
 117
 118        /// <summary>
 119        /// Used by the SDK to wrap a native video stream it already created.
 120        /// </summary>
 121        /// <param name="handle">Native handle of the stream.</param>
 122        /// <param name="format">Pixel format the frames are converted to, or null to keep the source format.</param>
 123        /// <param name="capacity">Capacity of the internal frame channel; 0 for unbounded, otherwise the oldest frame i
 124        protected VideoStream(FfiHandle handle, VideoBufferType? format, int capacity)
 125        {
 126            _handle = handle;
 127            _track = null;
 128            _format = format;
 129
 130            _channel =
 131                capacity > 0
 132                    ? Channel.CreateBounded<VideoFrameEvent>(
 133                        new BoundedChannelOptions(capacity)
 134                        {
 135                            FullMode = BoundedChannelFullMode.DropOldest,
 136                            SingleReader = false,
 137                            SingleWriter = true,
 138                        }
 139                    )
 140                    : Channel.CreateUnbounded<VideoFrameEvent>(
 141                        new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 142                    );
 143
 144            _cts = new CancellationTokenSource();
 145
 146            FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent);
 147        }
 148
 149        /// <summary>
 150        /// Creates a VideoStream from a participant's track source.
 151        /// </summary>
 152        /// <param name="participant">The participant.</param>
 153        /// <param name="trackSource">The track source type.</param>
 154        /// <param name="format">Optional video buffer format.</param>
 155        /// <param name="capacity">The capacity of the internal channel.</param>
 156        /// <returns>A new VideoStream instance.</returns>
 157        public static VideoStream FromParticipant(
 158            Participant participant,
 159            Proto.TrackSource trackSource,
 160            VideoBufferType? format = null,
 161            int capacity = 0
 162        )
 163        {
 164            _ = participant ?? throw new ArgumentNullException(nameof(participant));
 165
 166            var handle = CreateStreamFromParticipant(participant, trackSource, format);
 167            return new VideoStreamFromHandle(handle, format, capacity);
 168        }
 169
 170        /// <summary>
 171        /// Creates a VideoStream from an existing track.
 172        /// </summary>
 173        /// <param name="track">The track.</param>
 174        /// <param name="format">Optional video buffer format.</param>
 175        /// <param name="capacity">The capacity of the internal channel.</param>
 176        /// <returns>A new VideoStream instance.</returns>
 177        public static VideoStream FromTrack(
 178            Track track,
 179            VideoBufferType? format = null,
 180            int capacity = 0
 181        )
 182        {
 183            return new VideoStream(track, format, capacity);
 184        }
 185
 186        /// <summary>
 187        /// Gets the internal handle.
 188        /// </summary>
 189        internal FfiHandle Handle => _handle;
 190
 191        /// <summary>
 192        /// Gets the video format.
 193        /// </summary>
 194        public VideoBufferType? Format => _format;
 195
 196        private OwnedVideoStream CreateOwnedStream()
 197        {
 198            if (_track == null)
 199                throw new InvalidOperationException("Track is required for creating video stream");
 200
 201            var request = new FfiRequest
 202            {
 203                NewVideoStream = new NewVideoStreamRequest
 204                {
 205                    TrackHandle = _track.Handle.HandleId,
 206                    Type = VideoStreamType.VideoStreamNative,
 207                    NormalizeStride = true,
 208                },
 209            };
 210
 211            if (_format.HasValue)
 212            {
 213                request.NewVideoStream.Format = (LiveKit.Proto.VideoBufferType)_format.Value;
 214            }
 215
 216            var response = FfiClient.Instance.SendRequest(request);
 217            return response.NewVideoStream.Stream;
 218        }
 219
 220        private static FfiHandle CreateStreamFromParticipant(
 221            Participant participant,
 222            Proto.TrackSource trackSource,
 223            VideoBufferType? format
 224        )
 225        {
 226            var request = new FfiRequest
 227            {
 228                VideoStreamFromParticipant = new VideoStreamFromParticipantRequest
 229                {
 230                    ParticipantHandle = participant.Handle.HandleId,
 231                    TrackSource = trackSource,
 232                    Type = VideoStreamType.VideoStreamNative,
 233                    NormalizeStride = true,
 234                },
 235            };
 236
 237            if (format.HasValue)
 238            {
 239                request.VideoStreamFromParticipant.Format = (LiveKit.Proto.VideoBufferType)
 240                    format.Value;
 241            }
 242
 243            var response = FfiClient.Instance.SendRequest(request);
 244            return FfiHandle.FromId(response.VideoStreamFromParticipant.Stream.Handle.Id);
 245        }
 246
 247        private void OnFfiEvent(FfiEvent e)
 248        {
 249            if (e.MessageCase != FfiEvent.MessageOneofCase.VideoStreamEvent)
 250                return;
 251
 252            var videoEvent = e.VideoStreamEvent;
 253            if (videoEvent.StreamHandle != _handle.HandleId)
 254                return;
 255
 256            if (videoEvent.MessageCase == VideoStreamEvent.MessageOneofCase.FrameReceived)
 257            {
 258                var ownedBuffer = videoEvent.FrameReceived.Buffer;
 259                if (_disposed)
 260                {
 261                    // The native task can still emit a few frames after the stream was closed:
 262                    // release their buffers instead of leaking them
 263                    FfiHandle.FromId(ownedBuffer.Handle.Id).Dispose();
 264                    return;
 265                }
 266
 267                var frame = VideoFrame.FromOwnedInfo(ownedBuffer);
 268                var received = videoEvent.FrameReceived;
 269                _channel.Writer.TryWrite(
 270                    new VideoFrameEvent(
 271                        frame,
 272                        received.TimestampUs,
 273                        received.Rotation,
 274                        received.Metadata
 275                    )
 276                );
 277            }
 278            else if (videoEvent.MessageCase == VideoStreamEvent.MessageOneofCase.Eos)
 279            {
 280                _channel.Writer.TryComplete();
 281                // Nothing more will come for this handle
 282                FfiClient.Instance.RemoveStreamHandler(_handle.HandleId);
 283            }
 284        }
 285
 286        // Keep receiving (and releasing) the frames the native side may still emit after the
 287        // stream is closed, until its end-of-stream event; stop listening after a grace period in
 288        // case it never comes.
 289        private void StopListeningAfterEos()
 290        {
 291            _ = Task.Delay(TimeSpan.FromSeconds(5))
 292                .ContinueWith(
 293                    _ => FfiClient.Instance.RemoveStreamHandler(_handle.HandleId),
 294                    TaskScheduler.Default
 295                );
 296        }
 297
 298        /// <summary>
 299        /// Reads the next video frame event from the stream.
 300        /// </summary>
 301        /// <param name="cancellationToken">Cancellation token.</param>
 302        /// <returns>The next video frame event, or null if the stream has ended.</returns>
 303        public async ValueTask<VideoFrameEvent?> ReadAsync(
 304            CancellationToken cancellationToken = default
 305        )
 306        {
 307            try
 308            {
 309                using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 310                    cancellationToken,
 311                    _cts.Token
 312                );
 313                if (await _channel.Reader.WaitToReadAsync(linkedCts.Token).ConfigureAwait(false))
 314                {
 315                    if (_channel.Reader.TryRead(out var frame))
 316                    {
 317                        return frame;
 318                    }
 319                }
 320                return null;
 321            }
 322            catch (OperationCanceledException)
 323            {
 324                return null;
 325            }
 326            catch (ChannelClosedException)
 327            {
 328                return null;
 329            }
 330        }
 331
 332        /// <summary>
 333        /// Tries to read the next video frame event without blocking.
 334        /// </summary>
 335        /// <param name="frameEvent">The frame event if available.</param>
 336        /// <returns>True if a frame was available.</returns>
 337        public bool TryRead(out VideoFrameEvent frameEvent)
 338        {
 339            return _channel.Reader.TryRead(out frameEvent);
 340        }
 341
 342        /// <summary>
 343        /// Returns an async enumerator for iterating over video frames.
 344        /// </summary>
 345        /// <param name="cancellationToken">Cancellation token.</param>
 346        /// <returns>An async enumerator of video frame events.</returns>
 347        public async IAsyncEnumerator<VideoFrameEvent> GetAsyncEnumerator(
 348            CancellationToken cancellationToken = default
 349        )
 350        {
 351            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 352                cancellationToken,
 353                _cts.Token
 354            );
 355
 356            await foreach (
 357                var frame in _channel.Reader.ReadAllAsync(linkedCts.Token).ConfigureAwait(false)
 358            )
 359            {
 360                yield return frame;
 361            }
 362        }
 363
 364        /// <summary>
 365        /// Stops the stream and releases the native stream. Pending reads return null and later reads throw <see cref="
 366        /// </summary>
 367        public void Dispose()
 368        {
 369            if (_disposed)
 370                return;
 371            _disposed = true;
 372
 373            _cts.Cancel();
 374            StopListeningAfterEos();
 375            _channel.Writer.TryComplete();
 376            _handle.Dispose();
 377            _cts.Dispose();
 378
 379            GC.SuppressFinalize(this);
 380        }
 381
 382        /// <summary>
 383        /// Stops the stream and releases the native stream. Pending reads return null and later reads throw <see cref="
 384        /// </summary>
 385        /// <returns>A task that completes once the stream is released.</returns>
 386        public async ValueTask DisposeAsync()
 387        {
 388            if (_disposed)
 389                return;
 390            _disposed = true;
 391
 392            _cts.Cancel();
 393            StopListeningAfterEos();
 394            _channel.Writer.TryComplete();
 395
 396            await Task.Yield();
 397
 398            _handle.Dispose();
 399            _cts.Dispose();
 400
 401            GC.SuppressFinalize(this);
 402        }
 403    }
 404
 405    /// <summary>
 406    /// Video stream created from a handle.
 407    /// </summary>
 408    internal class VideoStreamFromHandle : VideoStream
 409    {
 410        internal VideoStreamFromHandle(FfiHandle handle, VideoBufferType? format, int capacity)
 3411            : base(handle, format, capacity) { }
 412    }
 413}