< Summary

Information
Line coverage
91%
Covered lines: 170
Uncovered lines: 15
Coverable lines: 185
Total lines: 413
Line coverage: 91.8%
Branch coverage
75%
Covered branches: 27
Total branches: 36
Branch coverage: 75%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)75%44100%
.ctor(...)50%22100%
FromParticipant(...)100%22100%
FromTrack(...)100%11100%
get_Handle()100%210%
get_Format()100%11100%
CreateOwnedStream()50%4478.94%
CreateStreamFromParticipant(...)50%22100%
OnFfiEvent(...)80%101083.33%
StopListeningAfterEos()100%11100%
ReadAsync()100%4485%
TryRead(...)100%11100%
GetAsyncEnumerator()50%22100%
Dispose()100%2290.9%
DisposeAsync()75%4491.66%

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>
 3691        public VideoStream(Track track, VideoBufferType? format = null, int capacity = 0)
 3692        {
 3693            _track = track ?? throw new ArgumentNullException(nameof(track));
 3694            _format = format;
 95
 3696            _channel =
 3697                capacity > 0
 3698                    ? Channel.CreateBounded<VideoFrameEvent>(
 3699                        new BoundedChannelOptions(capacity)
 36100                        {
 36101                            FullMode = BoundedChannelFullMode.DropOldest, // Drop oldest frames under backpressure
 36102                            SingleReader = false,
 36103                            SingleWriter = true,
 36104                        }
 36105                    )
 36106                    : Channel.CreateUnbounded<VideoFrameEvent>(
 36107                        new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 36108                    );
 109
 36110            _cts = new CancellationTokenSource();
 111
 36112            var stream = CreateOwnedStream();
 36113            _handle = FfiHandle.FromId(stream.Handle.Id);
 114
 36115            FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent);
 36116        }
 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
 1124        protected VideoStream(FfiHandle handle, VideoBufferType? format, int capacity)
 1125        {
 1126            _handle = handle;
 1127            _track = null;
 1128            _format = format;
 129
 1130            _channel =
 1131                capacity > 0
 1132                    ? Channel.CreateBounded<VideoFrameEvent>(
 1133                        new BoundedChannelOptions(capacity)
 1134                        {
 1135                            FullMode = BoundedChannelFullMode.DropOldest,
 1136                            SingleReader = false,
 1137                            SingleWriter = true,
 1138                        }
 1139                    )
 1140                    : Channel.CreateUnbounded<VideoFrameEvent>(
 1141                        new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 1142                    );
 143
 1144            _cts = new CancellationTokenSource();
 145
 1146            FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent);
 1147        }
 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        )
 2163        {
 2164            _ = participant ?? throw new ArgumentNullException(nameof(participant));
 165
 1166            var handle = CreateStreamFromParticipant(participant, trackSource, format);
 1167            return new VideoStreamFromHandle(handle, format, capacity);
 1168        }
 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        )
 32182        {
 32183            return new VideoStream(track, format, capacity);
 32184        }
 185
 186        /// <summary>
 187        /// Gets the internal handle.
 188        /// </summary>
 0189        internal FfiHandle Handle => _handle;
 190
 191        /// <summary>
 192        /// Gets the video format.
 193        /// </summary>
 1194        public VideoBufferType? Format => _format;
 195
 196        private OwnedVideoStream CreateOwnedStream()
 36197        {
 36198            if (_track == null)
 0199                throw new InvalidOperationException("Track is required for creating video stream");
 200
 36201            var request = new FfiRequest
 36202            {
 36203                NewVideoStream = new NewVideoStreamRequest
 36204                {
 36205                    TrackHandle = _track.Handle.HandleId,
 36206                    Type = VideoStreamType.VideoStreamNative,
 36207                    NormalizeStride = true,
 36208                },
 36209            };
 210
 36211            if (_format.HasValue)
 0212            {
 0213                request.NewVideoStream.Format = (LiveKit.Proto.VideoBufferType)_format.Value;
 0214            }
 215
 36216            var response = FfiClient.Instance.SendRequest(request);
 36217            return response.NewVideoStream.Stream;
 36218        }
 219
 220        private static FfiHandle CreateStreamFromParticipant(
 221            Participant participant,
 222            Proto.TrackSource trackSource,
 223            VideoBufferType? format
 224        )
 1225        {
 1226            var request = new FfiRequest
 1227            {
 1228                VideoStreamFromParticipant = new VideoStreamFromParticipantRequest
 1229                {
 1230                    ParticipantHandle = participant.Handle.HandleId,
 1231                    TrackSource = trackSource,
 1232                    Type = VideoStreamType.VideoStreamNative,
 1233                    NormalizeStride = true,
 1234                },
 1235            };
 236
 1237            if (format.HasValue)
 1238            {
 1239                request.VideoStreamFromParticipant.Format = (LiveKit.Proto.VideoBufferType)
 1240                    format.Value;
 1241            }
 242
 1243            var response = FfiClient.Instance.SendRequest(request);
 1244            return FfiHandle.FromId(response.VideoStreamFromParticipant.Stream.Handle.Id);
 1245        }
 246
 247        private void OnFfiEvent(FfiEvent e)
 114248        {
 114249            if (e.MessageCase != FfiEvent.MessageOneofCase.VideoStreamEvent)
 0250                return;
 251
 114252            var videoEvent = e.VideoStreamEvent;
 114253            if (videoEvent.StreamHandle != _handle.HandleId)
 0254                return;
 255
 114256            if (videoEvent.MessageCase == VideoStreamEvent.MessageOneofCase.FrameReceived)
 78257            {
 78258                var ownedBuffer = videoEvent.FrameReceived.Buffer;
 78259                if (_disposed)
 0260                {
 261                    // The native task can still emit a few frames after the stream was closed:
 262                    // release their buffers instead of leaking them
 0263                    FfiHandle.FromId(ownedBuffer.Handle.Id).Dispose();
 0264                    return;
 265                }
 266
 78267                var frame = VideoFrame.FromOwnedInfo(ownedBuffer);
 78268                var received = videoEvent.FrameReceived;
 78269                _channel.Writer.TryWrite(
 78270                    new VideoFrameEvent(
 78271                        frame,
 78272                        received.TimestampUs,
 78273                        received.Rotation,
 78274                        received.Metadata
 78275                    )
 78276                );
 78277            }
 36278            else if (videoEvent.MessageCase == VideoStreamEvent.MessageOneofCase.Eos)
 36279            {
 36280                _channel.Writer.TryComplete();
 281                // Nothing more will come for this handle
 36282                FfiClient.Instance.RemoveStreamHandler(_handle.HandleId);
 36283            }
 114284        }
 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()
 37290        {
 37291            _ = Task.Delay(TimeSpan.FromSeconds(5))
 37292                .ContinueWith(
 37293                    _ => FfiClient.Instance.RemoveStreamHandler(_handle.HandleId),
 37294                    TaskScheduler.Default
 37295                );
 37296        }
 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        )
 99306        {
 307            try
 99308            {
 99309                using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 99310                    cancellationToken,
 99311                    _cts.Token
 99312                );
 99313                if (await _channel.Reader.WaitToReadAsync(linkedCts.Token).ConfigureAwait(false))
 63314                {
 63315                    if (_channel.Reader.TryRead(out var frame))
 39316                    {
 39317                        return frame;
 318                    }
 24319                }
 24320                return null;
 321            }
 36322            catch (OperationCanceledException)
 36323            {
 36324                return null;
 325            }
 0326            catch (ChannelClosedException)
 0327            {
 0328                return null;
 329            }
 99330        }
 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)
 1338        {
 1339            return _channel.Reader.TryRead(out frameEvent);
 1340        }
 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        )
 3350        {
 3351            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 3352                cancellationToken,
 3353                _cts.Token
 3354            );
 355
 3356            await foreach (
 27357                var frame in _channel.Reader.ReadAllAsync(linkedCts.Token).ConfigureAwait(false)
 358            )
 12359            {
 12360                yield return frame;
 9361            }
 3362        }
 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()
 22368        {
 22369            if (_disposed)
 0370                return;
 22371            _disposed = true;
 372
 22373            _cts.Cancel();
 22374            StopListeningAfterEos();
 22375            _channel.Writer.TryComplete();
 22376            _handle.Dispose();
 22377            _cts.Dispose();
 378
 22379            GC.SuppressFinalize(this);
 22380        }
 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()
 15387        {
 15388            if (_disposed)
 0389                return;
 15390            _disposed = true;
 391
 15392            _cts.Cancel();
 15393            StopListeningAfterEos();
 15394            _channel.Writer.TryComplete();
 395
 15396            await Task.Yield();
 397
 15398            _handle.Dispose();
 15399            _cts.Dispose();
 400
 15401            GC.SuppressFinalize(this);
 15402        }
 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)
 411            : base(handle, format, capacity) { }
 412    }
 413}