< Summary

Information
Class: LiveKit.Rtc.PushFrameException
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/DataTrack.cs
Line coverage
100%
Covered lines: 3
Uncovered lines: 0
Coverable lines: 3
Total lines: 552
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/DataTrack.cs

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Threading;
 6using System.Threading.Channels;
 7using System.Threading.Tasks;
 8using Google.Protobuf;
 9using LiveKit.Proto;
 10using LiveKit.Rtc.Internal;
 11
 12namespace LiveKit.Rtc
 13{
 14    /// <summary>
 15    /// Information about a published data track.
 16    /// </summary>
 17    public class DataTrackInfo
 18    {
 19        /// <summary>
 20        /// Unique track identifier assigned by the SFU. It may change after a reconnect; use
 21        /// <see cref="Name"/> when a stable identifier is needed.
 22        /// </summary>
 23        public string Sid { get; }
 24
 25        /// <summary>
 26        /// Name of the track, assigned by the publisher.
 27        /// </summary>
 28        public string Name { get; }
 29
 30        /// <summary>
 31        /// Whether frames sent on the track use end-to-end encryption.
 32        /// </summary>
 33        public bool UsesE2EE { get; }
 34
 35        internal DataTrackInfo(Proto.DataTrackInfo info)
 36        {
 37            Sid = info.Sid ?? string.Empty;
 38            Name = info.Name ?? string.Empty;
 39            UsesE2EE = info.UsesE2Ee;
 40        }
 41    }
 42
 43    /// <summary>
 44    /// A frame published on a data track: a payload and an optional user timestamp.
 45    /// </summary>
 46    public class DataTrackFrame
 47    {
 48        /// <summary>
 49        /// The frame payload.
 50        /// </summary>
 51        public byte[] Payload { get; }
 52
 53        /// <summary>
 54        /// The user timestamp attached to the frame, if any.
 55        /// </summary>
 56        public ulong? UserTimestamp { get; }
 57
 58        /// <summary>
 59        /// Creates a frame to push on a <see cref="LocalDataTrack"/>.
 60        /// </summary>
 61        /// <param name="payload">The frame payload.</param>
 62        /// <param name="userTimestamp">Optional user timestamp delivered with the frame.</param>
 63        public DataTrackFrame(byte[] payload, ulong? userTimestamp = null)
 64        {
 65            Payload = payload ?? throw new ArgumentNullException(nameof(payload));
 66            UserTimestamp = userTimestamp;
 67        }
 68
 69        internal static DataTrackFrame FromProto(Proto.DataTrackFrame frame)
 70        {
 71            return new DataTrackFrame(
 72                frame.Payload.ToByteArray(),
 73                frame.HasUserTimestamp ? frame.UserTimestamp : (ulong?)null
 74            );
 75        }
 76
 77        internal Proto.DataTrackFrame ToProto()
 78        {
 79            var proto = new Proto.DataTrackFrame { Payload = ByteString.CopyFrom(Payload) };
 80            if (UserTimestamp.HasValue)
 81            {
 82                proto.UserTimestamp = UserTimestamp.Value;
 83            }
 84            return proto;
 85        }
 86    }
 87
 88    /// <summary>
 89    /// Thrown when a data track cannot be published.
 90    /// </summary>
 91    public class PublishDataTrackException : Exception
 92    {
 93        /// <summary>
 94        /// The error code reported by the SDK.
 95        /// </summary>
 96        public Proto.PublishDataTrackErrorCode Code { get; }
 97
 98        internal PublishDataTrackException(Proto.PublishDataTrackErrorCode code, string message)
 99            : base(message)
 100        {
 101            Code = code;
 102        }
 103    }
 104
 105    /// <summary>
 106    /// Thrown when a frame cannot be pushed on a <see cref="LocalDataTrack"/>: the track was
 107    /// unpublished (by the local participant or the SFU), the room is no longer connected, or
 108    /// frames are being pushed faster than they can be sent.
 109    /// </summary>
 110    public class PushFrameException : Exception
 111    {
 112        /// <summary>
 113        /// The error code reported by the SDK.
 114        /// </summary>
 115        public Proto.LocalDataTrackTryPushErrorCode Code { get; }
 116
 117        internal PushFrameException(Proto.LocalDataTrackTryPushErrorCode code, string message)
 1118            : base(message)
 1119        {
 120            Code = code;
 1121        }
 122    }
 123
 124    /// <summary>
 125    /// Thrown by <see cref="DataTrackStream.ReadAsync"/> when the subscription to a remote data
 126    /// track could not be established.
 127    /// </summary>
 128    public class SubscribeDataTrackException : Exception
 129    {
 130        /// <summary>
 131        /// The error code reported by the SDK.
 132        /// </summary>
 133        public Proto.SubscribeDataTrackErrorCode Code { get; }
 134
 135        internal SubscribeDataTrackException(Proto.SubscribeDataTrackErrorCode code, string message)
 136            : base(message)
 137        {
 138            Code = code;
 139        }
 140    }
 141
 142    /// <summary>
 143    /// A data track published by the local participant. Obtained from
 144    /// <see cref="LocalParticipant.PublishDataTrackAsync"/>.
 145    /// </summary>
 146    public class LocalDataTrack : IDisposable
 147    {
 148        private readonly FfiHandle _handle;
 149        private bool _disposed;
 150
 151        /// <summary>
 152        /// Information about the data track.
 153        /// </summary>
 154        public DataTrackInfo Info { get; }
 155
 156        internal LocalDataTrack(OwnedLocalDataTrack owned)
 157        {
 158            _handle = FfiHandle.FromId(owned.Handle.Id);
 159            Info = new DataTrackInfo(owned.Info);
 160        }
 161
 162        /// <summary>
 163        /// Tries to push a frame to the subscribers of the track.
 164        /// </summary>
 165        /// <param name="frame">The frame to send.</param>
 166        /// <exception cref="PushFrameException">The frame could not be pushed.</exception>
 167        public void TryPush(DataTrackFrame frame)
 168        {
 169            if (frame == null)
 170                throw new ArgumentNullException(nameof(frame));
 171            ThrowIfDisposed();
 172
 173            var response = FfiClient.Instance.SendRequest(
 174                new FfiRequest
 175                {
 176                    LocalDataTrackTryPush = new LocalDataTrackTryPushRequest
 177                    {
 178                        TrackHandle = _handle.HandleId,
 179                        Frame = frame.ToProto(),
 180                    },
 181                }
 182            );
 183
 184            var error = response.LocalDataTrackTryPush?.Error;
 185            if (error != null)
 186            {
 187                throw new PushFrameException(error.Code, error.Message);
 188            }
 189        }
 190
 191        /// <summary>
 192        /// Whether the track is still published.
 193        /// </summary>
 194        /// <returns>True while the track is published.</returns>
 195        public bool IsPublished()
 196        {
 197            ThrowIfDisposed();
 198            var response = FfiClient.Instance.SendRequest(
 199                new FfiRequest
 200                {
 201                    LocalDataTrackIsPublished = new LocalDataTrackIsPublishedRequest
 202                    {
 203                        TrackHandle = _handle.HandleId,
 204                    },
 205                }
 206            );
 207            return response.LocalDataTrackIsPublished?.IsPublished == true;
 208        }
 209
 210        /// <summary>
 211        /// Unpublishes the track.
 212        /// </summary>
 213        public void Unpublish()
 214        {
 215            ThrowIfDisposed();
 216            FfiClient.Instance.SendRequest(
 217                new FfiRequest
 218                {
 219                    LocalDataTrackUnpublish = new LocalDataTrackUnpublishRequest
 220                    {
 221                        TrackHandle = _handle.HandleId,
 222                    },
 223                }
 224            );
 225        }
 226
 227        private void ThrowIfDisposed()
 228        {
 229            if (_disposed)
 230                throw new ObjectDisposedException(nameof(LocalDataTrack));
 231        }
 232
 233        /// <summary>
 234        /// Releases the native handle of the track, which also unpublishes it if it is still published.
 235        /// </summary>
 236        public void Dispose()
 237        {
 238            if (_disposed)
 239                return;
 240            _disposed = true;
 241            _handle.Dispose();
 242        }
 243    }
 244
 245    /// <summary>
 246    /// A data track published by a remote participant. Delivered by
 247    /// <see cref="Room.DataTrackPublished"/>; call <see cref="Subscribe"/> to receive its frames.
 248    /// </summary>
 249    public class RemoteDataTrack : IDisposable
 250    {
 251        private readonly FfiHandle _handle;
 252        private bool _disposed;
 253
 254        /// <summary>
 255        /// Information about the data track.
 256        /// </summary>
 257        public DataTrackInfo Info { get; }
 258
 259        /// <summary>
 260        /// Identity of the participant who published the track.
 261        /// </summary>
 262        public string PublisherIdentity { get; }
 263
 264        internal RemoteDataTrack(OwnedRemoteDataTrack owned)
 265        {
 266            _handle = FfiHandle.FromId(owned.Handle.Id);
 267            Info = new DataTrackInfo(owned.Info);
 268            PublisherIdentity = owned.PublisherIdentity ?? string.Empty;
 269        }
 270
 271        /// <summary>
 272        /// Subscribes to the track. The returned stream yields the frames as they arrive; dispose
 273        /// it to unsubscribe.
 274        /// </summary>
 275        /// <param name="bufferSize">
 276        /// Maximum number of received frames buffered internally. Null keeps the SDK default. Zero is
 277        /// not valid and is clamped to one.
 278        /// </param>
 279        /// <returns>The stream of frames; dispose it to unsubscribe.</returns>
 280        public DataTrackStream Subscribe(uint? bufferSize = null)
 281        {
 282            ThrowIfDisposed();
 283
 284            var options = new DataTrackSubscribeOptions();
 285            if (bufferSize.HasValue)
 286            {
 287                options.BufferSize = bufferSize.Value;
 288            }
 289
 290            var response = FfiClient.Instance.SendRequest(
 291                new FfiRequest
 292                {
 293                    SubscribeDataTrack = new SubscribeDataTrackRequest
 294                    {
 295                        TrackHandle = _handle.HandleId,
 296                        Options = options,
 297                    },
 298                }
 299            );
 300
 301            return new DataTrackStream(response.SubscribeDataTrack.Stream);
 302        }
 303
 304        /// <summary>
 305        /// Whether the track is still published.
 306        /// </summary>
 307        /// <returns>True while the publisher keeps the track published.</returns>
 308        public bool IsPublished()
 309        {
 310            ThrowIfDisposed();
 311            var response = FfiClient.Instance.SendRequest(
 312                new FfiRequest
 313                {
 314                    RemoteDataTrackIsPublished = new RemoteDataTrackIsPublishedRequest
 315                    {
 316                        TrackHandle = _handle.HandleId,
 317                    },
 318                }
 319            );
 320            return response.RemoteDataTrackIsPublished?.IsPublished == true;
 321        }
 322
 323        /// <summary>
 324        /// Configures how incoming packets are reassembled into frames for this track. The options
 325        /// apply to all current and future subscriptions and take effect with the next packet.
 326        /// </summary>
 327        /// <param name="maxPartialFrames">
 328        /// Maximum number of partial frames tracked concurrently (default 1). Higher values tolerate
 329        /// more reordering for high-frequency senders at the cost of buffering. Zero is clamped to
 330        /// one; null keeps the current value.
 331        /// </param>
 332        public void SetPipelineOptions(uint? maxPartialFrames = null)
 333        {
 334            ThrowIfDisposed();
 335
 336            var options = new RemoteDataTrackPipelineOptions();
 337            if (maxPartialFrames.HasValue)
 338            {
 339                options.MaxPartialFrames = maxPartialFrames.Value;
 340            }
 341
 342            FfiClient.Instance.SendRequest(
 343                new FfiRequest
 344                {
 345                    RemoteDataTrackSetPipelineOptions = new RemoteDataTrackSetPipelineOptionsRequest
 346                    {
 347                        TrackHandle = _handle.HandleId,
 348                        Options = options,
 349                    },
 350                }
 351            );
 352        }
 353
 354        private void ThrowIfDisposed()
 355        {
 356            if (_disposed)
 357                throw new ObjectDisposedException(nameof(RemoteDataTrack));
 358        }
 359
 360        /// <summary>
 361        /// Releases the native handle of the track. The streams returned by <see cref="Subscribe"/> are
 362        /// disposed separately.
 363        /// </summary>
 364        public void Dispose()
 365        {
 366            if (_disposed)
 367                return;
 368            _disposed = true;
 369            _handle.Dispose();
 370        }
 371    }
 372
 373    /// <summary>
 374    /// An active subscription to a <see cref="RemoteDataTrack"/>. Read frames with
 375    /// <see cref="ReadAsync"/> or <c>await foreach</c>; the stream ends when the track is
 376    /// unpublished. Disposing the stream unsubscribes from the track.
 377    /// </summary>
 378    public class DataTrackStream : IAsyncEnumerable<DataTrackFrame>, IAsyncDisposable, IDisposable
 379    {
 380        private readonly FfiHandle _handle;
 381        private readonly ulong _handleId;
 382        private readonly Channel<DataTrackStreamEvent> _events;
 383        private readonly SemaphoreSlim _readLock = new SemaphoreSlim(1, 1);
 384        private SubscribeDataTrackException? _pendingError;
 385        private bool _ended;
 386        private bool _disposed;
 387
 388        internal DataTrackStream(OwnedDataTrackStream owned)
 389        {
 390            _handleId = owned.Handle.Id;
 391            _handle = FfiHandle.FromId(_handleId);
 392            _events = Channel.CreateUnbounded<DataTrackStreamEvent>(
 393                new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }
 394            );
 395
 396            // Subscribe before the first read request so no event can be missed
 397            FfiClient.Instance.AddStreamHandler(_handleId, OnFfiEvent);
 398        }
 399
 400        /// <summary>
 401        /// Whether the stream has ended (track unpublished, subscription failed, or disposed).
 402        /// </summary>
 403        public bool IsEnded => _ended || _disposed;
 404
 405        private void OnFfiEvent(FfiEvent e)
 406        {
 407            if (e.MessageCase != FfiEvent.MessageOneofCase.DataTrackStreamEvent)
 408                return;
 409
 410            var evt = e.DataTrackStreamEvent;
 411            if (evt == null || evt.StreamHandle != _handleId)
 412                return;
 413
 414            _events.Writer.TryWrite(evt);
 415        }
 416
 417        /// <summary>
 418        /// Reads the next frame, or returns null once the stream has ended.
 419        /// </summary>
 420        /// <param name="cancellationToken">Cancels the wait for the next frame.</param>
 421        /// <exception cref="SubscribeDataTrackException">
 422        /// The subscription could not be established. Thrown once, when the stream ends.
 423        /// </exception>
 424        /// <returns>The next frame, or null once the stream has ended.</returns>
 425        public async Task<DataTrackFrame?> ReadAsync(CancellationToken cancellationToken = default)
 426        {
 427            if (_disposed)
 428                throw new ObjectDisposedException(nameof(DataTrackStream));
 429
 430            await _readLock.WaitAsync(cancellationToken).ConfigureAwait(false);
 431            try
 432            {
 433                if (_ended)
 434                {
 435                    ThrowPendingError();
 436                    return null;
 437                }
 438
 439                // The FFI delivers exactly one stream event per read request (backpressure). If the
 440                // stream already ended, the response says so instead.
 441                var response = FfiClient.Instance.SendRequest(
 442                    new FfiRequest
 443                    {
 444                        DataTrackStreamRead = new DataTrackStreamReadRequest
 445                        {
 446                            StreamHandle = _handleId,
 447                        },
 448                    }
 449                );
 450
 451                var eos = response.DataTrackStreamRead?.EosEvent;
 452                if (eos != null)
 453                {
 454                    End(eos);
 455                    ThrowPendingError();
 456                    return null;
 457                }
 458
 459                while (true)
 460                {
 461                    DataTrackStreamEvent evt;
 462                    try
 463                    {
 464                        evt = await _events
 465                            .Reader.ReadAsync(cancellationToken)
 466                            .ConfigureAwait(false);
 467                    }
 468                    catch (ChannelClosedException)
 469                    {
 470                        // Disposed from another thread while waiting: the stream is over
 471                        _ended = true;
 472                        return null;
 473                    }
 474
 475                    switch (evt.DetailCase)
 476                    {
 477                        case DataTrackStreamEvent.DetailOneofCase.FrameReceived:
 478                            return DataTrackFrame.FromProto(evt.FrameReceived.Frame);
 479
 480                        case DataTrackStreamEvent.DetailOneofCase.Eos:
 481                            End(evt.Eos);
 482                            ThrowPendingError();
 483                            return null;
 484                    }
 485                }
 486            }
 487            finally
 488            {
 489                _readLock.Release();
 490            }
 491        }
 492
 493        /// <inheritdoc />
 494        /// <returns>The frames, until the stream ends.</returns>
 495        public async IAsyncEnumerator<DataTrackFrame> GetAsyncEnumerator(
 496            CancellationToken cancellationToken = default
 497        )
 498        {
 499            while (true)
 500            {
 501                var frame = await ReadAsync(cancellationToken).ConfigureAwait(false);
 502                if (frame == null)
 503                    yield break;
 504                yield return frame;
 505            }
 506        }
 507
 508        private void End(DataTrackStreamEOS eos)
 509        {
 510            _ended = true;
 511            if (eos.Error != null)
 512            {
 513                _pendingError = new SubscribeDataTrackException(eos.Error.Code, eos.Error.Message);
 514            }
 515            FfiClient.Instance.RemoveStreamHandler(_handleId);
 516            _events.Writer.TryComplete();
 517        }
 518
 519        private void ThrowPendingError()
 520        {
 521            var error = _pendingError;
 522            if (error != null)
 523            {
 524                _pendingError = null;
 525                throw error;
 526            }
 527        }
 528
 529        /// <summary>
 530        /// Unsubscribes from the track and releases the native resources.
 531        /// </summary>
 532        public void Dispose()
 533        {
 534            if (_disposed)
 535                return;
 536            _disposed = true;
 537            FfiClient.Instance.RemoveStreamHandler(_handleId);
 538            _events.Writer.TryComplete();
 539            _handle.Dispose();
 540        }
 541
 542        /// <summary>
 543        /// Unsubscribes from the track and releases the native resources, like <see cref="Dispose"/>.
 544        /// </summary>
 545        /// <returns>A completed task.</returns>
 546        public ValueTask DisposeAsync()
 547        {
 548            Dispose();
 549            return default;
 550        }
 551    }
 552}