| | | 1 | | // author: https://github.com/pabloFuente |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Channels; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using LiveKit.Proto; |
| | | 10 | | using LiveKit.Rtc.Internal; |
| | | 11 | | |
| | | 12 | | namespace 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> |
| | 36 | 91 | | public VideoStream(Track track, VideoBufferType? format = null, int capacity = 0) |
| | 36 | 92 | | { |
| | 36 | 93 | | _track = track ?? throw new ArgumentNullException(nameof(track)); |
| | 36 | 94 | | _format = format; |
| | | 95 | | |
| | 36 | 96 | | _channel = |
| | 36 | 97 | | capacity > 0 |
| | 36 | 98 | | ? Channel.CreateBounded<VideoFrameEvent>( |
| | 36 | 99 | | new BoundedChannelOptions(capacity) |
| | 36 | 100 | | { |
| | 36 | 101 | | FullMode = BoundedChannelFullMode.DropOldest, // Drop oldest frames under backpressure |
| | 36 | 102 | | SingleReader = false, |
| | 36 | 103 | | SingleWriter = true, |
| | 36 | 104 | | } |
| | 36 | 105 | | ) |
| | 36 | 106 | | : Channel.CreateUnbounded<VideoFrameEvent>( |
| | 36 | 107 | | new UnboundedChannelOptions { SingleReader = false, SingleWriter = true } |
| | 36 | 108 | | ); |
| | | 109 | | |
| | 36 | 110 | | _cts = new CancellationTokenSource(); |
| | | 111 | | |
| | 36 | 112 | | var stream = CreateOwnedStream(); |
| | 36 | 113 | | _handle = FfiHandle.FromId(stream.Handle.Id); |
| | | 114 | | |
| | 36 | 115 | | FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent); |
| | 36 | 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 |
| | 1 | 124 | | protected VideoStream(FfiHandle handle, VideoBufferType? format, int capacity) |
| | 1 | 125 | | { |
| | 1 | 126 | | _handle = handle; |
| | 1 | 127 | | _track = null; |
| | 1 | 128 | | _format = format; |
| | | 129 | | |
| | 1 | 130 | | _channel = |
| | 1 | 131 | | capacity > 0 |
| | 1 | 132 | | ? Channel.CreateBounded<VideoFrameEvent>( |
| | 1 | 133 | | new BoundedChannelOptions(capacity) |
| | 1 | 134 | | { |
| | 1 | 135 | | FullMode = BoundedChannelFullMode.DropOldest, |
| | 1 | 136 | | SingleReader = false, |
| | 1 | 137 | | SingleWriter = true, |
| | 1 | 138 | | } |
| | 1 | 139 | | ) |
| | 1 | 140 | | : Channel.CreateUnbounded<VideoFrameEvent>( |
| | 1 | 141 | | new UnboundedChannelOptions { SingleReader = false, SingleWriter = true } |
| | 1 | 142 | | ); |
| | | 143 | | |
| | 1 | 144 | | _cts = new CancellationTokenSource(); |
| | | 145 | | |
| | 1 | 146 | | FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent); |
| | 1 | 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 | | ) |
| | 2 | 163 | | { |
| | 2 | 164 | | _ = participant ?? throw new ArgumentNullException(nameof(participant)); |
| | | 165 | | |
| | 1 | 166 | | var handle = CreateStreamFromParticipant(participant, trackSource, format); |
| | 1 | 167 | | return new VideoStreamFromHandle(handle, format, capacity); |
| | 1 | 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 | | ) |
| | 32 | 182 | | { |
| | 32 | 183 | | return new VideoStream(track, format, capacity); |
| | 32 | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Gets the internal handle. |
| | | 188 | | /// </summary> |
| | 0 | 189 | | internal FfiHandle Handle => _handle; |
| | | 190 | | |
| | | 191 | | /// <summary> |
| | | 192 | | /// Gets the video format. |
| | | 193 | | /// </summary> |
| | 1 | 194 | | public VideoBufferType? Format => _format; |
| | | 195 | | |
| | | 196 | | private OwnedVideoStream CreateOwnedStream() |
| | 36 | 197 | | { |
| | 36 | 198 | | if (_track == null) |
| | 0 | 199 | | throw new InvalidOperationException("Track is required for creating video stream"); |
| | | 200 | | |
| | 36 | 201 | | var request = new FfiRequest |
| | 36 | 202 | | { |
| | 36 | 203 | | NewVideoStream = new NewVideoStreamRequest |
| | 36 | 204 | | { |
| | 36 | 205 | | TrackHandle = _track.Handle.HandleId, |
| | 36 | 206 | | Type = VideoStreamType.VideoStreamNative, |
| | 36 | 207 | | NormalizeStride = true, |
| | 36 | 208 | | }, |
| | 36 | 209 | | }; |
| | | 210 | | |
| | 36 | 211 | | if (_format.HasValue) |
| | 0 | 212 | | { |
| | 0 | 213 | | request.NewVideoStream.Format = (LiveKit.Proto.VideoBufferType)_format.Value; |
| | 0 | 214 | | } |
| | | 215 | | |
| | 36 | 216 | | var response = FfiClient.Instance.SendRequest(request); |
| | 36 | 217 | | return response.NewVideoStream.Stream; |
| | 36 | 218 | | } |
| | | 219 | | |
| | | 220 | | private static FfiHandle CreateStreamFromParticipant( |
| | | 221 | | Participant participant, |
| | | 222 | | Proto.TrackSource trackSource, |
| | | 223 | | VideoBufferType? format |
| | | 224 | | ) |
| | 1 | 225 | | { |
| | 1 | 226 | | var request = new FfiRequest |
| | 1 | 227 | | { |
| | 1 | 228 | | VideoStreamFromParticipant = new VideoStreamFromParticipantRequest |
| | 1 | 229 | | { |
| | 1 | 230 | | ParticipantHandle = participant.Handle.HandleId, |
| | 1 | 231 | | TrackSource = trackSource, |
| | 1 | 232 | | Type = VideoStreamType.VideoStreamNative, |
| | 1 | 233 | | NormalizeStride = true, |
| | 1 | 234 | | }, |
| | 1 | 235 | | }; |
| | | 236 | | |
| | 1 | 237 | | if (format.HasValue) |
| | 1 | 238 | | { |
| | 1 | 239 | | request.VideoStreamFromParticipant.Format = (LiveKit.Proto.VideoBufferType) |
| | 1 | 240 | | format.Value; |
| | 1 | 241 | | } |
| | | 242 | | |
| | 1 | 243 | | var response = FfiClient.Instance.SendRequest(request); |
| | 1 | 244 | | return FfiHandle.FromId(response.VideoStreamFromParticipant.Stream.Handle.Id); |
| | 1 | 245 | | } |
| | | 246 | | |
| | | 247 | | private void OnFfiEvent(FfiEvent e) |
| | 114 | 248 | | { |
| | 114 | 249 | | if (e.MessageCase != FfiEvent.MessageOneofCase.VideoStreamEvent) |
| | 0 | 250 | | return; |
| | | 251 | | |
| | 114 | 252 | | var videoEvent = e.VideoStreamEvent; |
| | 114 | 253 | | if (videoEvent.StreamHandle != _handle.HandleId) |
| | 0 | 254 | | return; |
| | | 255 | | |
| | 114 | 256 | | if (videoEvent.MessageCase == VideoStreamEvent.MessageOneofCase.FrameReceived) |
| | 78 | 257 | | { |
| | 78 | 258 | | var ownedBuffer = videoEvent.FrameReceived.Buffer; |
| | 78 | 259 | | if (_disposed) |
| | 0 | 260 | | { |
| | | 261 | | // The native task can still emit a few frames after the stream was closed: |
| | | 262 | | // release their buffers instead of leaking them |
| | 0 | 263 | | FfiHandle.FromId(ownedBuffer.Handle.Id).Dispose(); |
| | 0 | 264 | | return; |
| | | 265 | | } |
| | | 266 | | |
| | 78 | 267 | | var frame = VideoFrame.FromOwnedInfo(ownedBuffer); |
| | 78 | 268 | | var received = videoEvent.FrameReceived; |
| | 78 | 269 | | _channel.Writer.TryWrite( |
| | 78 | 270 | | new VideoFrameEvent( |
| | 78 | 271 | | frame, |
| | 78 | 272 | | received.TimestampUs, |
| | 78 | 273 | | received.Rotation, |
| | 78 | 274 | | received.Metadata |
| | 78 | 275 | | ) |
| | 78 | 276 | | ); |
| | 78 | 277 | | } |
| | 36 | 278 | | else if (videoEvent.MessageCase == VideoStreamEvent.MessageOneofCase.Eos) |
| | 36 | 279 | | { |
| | 36 | 280 | | _channel.Writer.TryComplete(); |
| | | 281 | | // Nothing more will come for this handle |
| | 36 | 282 | | FfiClient.Instance.RemoveStreamHandler(_handle.HandleId); |
| | 36 | 283 | | } |
| | 114 | 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() |
| | 37 | 290 | | { |
| | 37 | 291 | | _ = Task.Delay(TimeSpan.FromSeconds(5)) |
| | 37 | 292 | | .ContinueWith( |
| | 37 | 293 | | _ => FfiClient.Instance.RemoveStreamHandler(_handle.HandleId), |
| | 37 | 294 | | TaskScheduler.Default |
| | 37 | 295 | | ); |
| | 37 | 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 | | ) |
| | 99 | 306 | | { |
| | | 307 | | try |
| | 99 | 308 | | { |
| | 99 | 309 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 99 | 310 | | cancellationToken, |
| | 99 | 311 | | _cts.Token |
| | 99 | 312 | | ); |
| | 99 | 313 | | if (await _channel.Reader.WaitToReadAsync(linkedCts.Token).ConfigureAwait(false)) |
| | 63 | 314 | | { |
| | 63 | 315 | | if (_channel.Reader.TryRead(out var frame)) |
| | 39 | 316 | | { |
| | 39 | 317 | | return frame; |
| | | 318 | | } |
| | 24 | 319 | | } |
| | 24 | 320 | | return null; |
| | | 321 | | } |
| | 36 | 322 | | catch (OperationCanceledException) |
| | 36 | 323 | | { |
| | 36 | 324 | | return null; |
| | | 325 | | } |
| | 0 | 326 | | catch (ChannelClosedException) |
| | 0 | 327 | | { |
| | 0 | 328 | | return null; |
| | | 329 | | } |
| | 99 | 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) |
| | 1 | 338 | | { |
| | 1 | 339 | | return _channel.Reader.TryRead(out frameEvent); |
| | 1 | 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 | | ) |
| | 3 | 350 | | { |
| | 3 | 351 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 3 | 352 | | cancellationToken, |
| | 3 | 353 | | _cts.Token |
| | 3 | 354 | | ); |
| | | 355 | | |
| | 3 | 356 | | await foreach ( |
| | 27 | 357 | | var frame in _channel.Reader.ReadAllAsync(linkedCts.Token).ConfigureAwait(false) |
| | | 358 | | ) |
| | 12 | 359 | | { |
| | 12 | 360 | | yield return frame; |
| | 9 | 361 | | } |
| | 3 | 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() |
| | 22 | 368 | | { |
| | 22 | 369 | | if (_disposed) |
| | 0 | 370 | | return; |
| | 22 | 371 | | _disposed = true; |
| | | 372 | | |
| | 22 | 373 | | _cts.Cancel(); |
| | 22 | 374 | | StopListeningAfterEos(); |
| | 22 | 375 | | _channel.Writer.TryComplete(); |
| | 22 | 376 | | _handle.Dispose(); |
| | 22 | 377 | | _cts.Dispose(); |
| | | 378 | | |
| | 22 | 379 | | GC.SuppressFinalize(this); |
| | 22 | 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() |
| | 15 | 387 | | { |
| | 15 | 388 | | if (_disposed) |
| | 0 | 389 | | return; |
| | 15 | 390 | | _disposed = true; |
| | | 391 | | |
| | 15 | 392 | | _cts.Cancel(); |
| | 15 | 393 | | StopListeningAfterEos(); |
| | 15 | 394 | | _channel.Writer.TryComplete(); |
| | | 395 | | |
| | 15 | 396 | | await Task.Yield(); |
| | | 397 | | |
| | 15 | 398 | | _handle.Dispose(); |
| | 15 | 399 | | _cts.Dispose(); |
| | | 400 | | |
| | 15 | 401 | | GC.SuppressFinalize(this); |
| | 15 | 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) |
| | | 411 | | : base(handle, format, capacity) { } |
| | | 412 | | } |
| | | 413 | | } |