< Summary

Information
Class: LiveKit.Rtc.RoomOptions
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/Room.cs
Line coverage
100%
Covered lines: 37
Uncovered lines: 0
Coverable lines: 37
Total lines: 2865
Line coverage: 100%
Branch coverage
100%
Covered branches: 12
Total branches: 12
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
ToProto()100%1212100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/Room.cs

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Runtime.InteropServices;
 6using System.Threading;
 7using System.Threading.Tasks;
 8using LiveKit.Proto;
 9using LiveKit.Rtc.Internal;
 10
 11namespace LiveKit.Rtc
 12{
 13    /// <summary>
 14    /// Room options for connecting to a LiveKit room.
 15    /// </summary>
 16    public class RoomOptions
 17    {
 18        /// <summary>
 19        /// Whether to subscribe automatically to every track the remote participants publish. Defaults to
 20        /// true.
 21        /// </summary>
 22        public bool AutoSubscribe { get; set; } = true;
 23
 24        /// <summary>
 25        /// Whether to enable dynacast, which pauses the video layers no subscriber receives. Defaults to
 26        /// false.
 27        /// </summary>
 28        public bool Dynacast { get; set; } = false;
 29
 30        /// <summary>
 31        /// Whether to enable adaptive stream, which adapts the quality of subscribed video to how it is
 32        /// consumed. Defaults to false.
 33        /// </summary>
 34        public bool AdaptiveStream { get; set; } = false;
 35
 36        /// <summary>
 37        /// Number of times the connection is retried before <see cref="Room.ConnectAsync"/> fails. Defaults
 38        /// to 3.
 39        /// </summary>
 40        public uint JoinRetries { get; set; } = 3;
 41
 42        /// <summary>
 43        /// End-to-end encryption options. Null, the default, disables encryption.
 44        /// </summary>
 45        public E2EEOptions? E2EE { get; set; }
 46
 47        /// <summary>
 48        /// WebRTC configuration of the connection: which ICE candidates to use (for example only TURN
 49        /// relays), how to gather them and which ICE servers to use. Null, the default, keeps the
 50        /// defaults: every candidate type and the ICE servers the LiveKit server provides.
 51        /// </summary>
 52        public RtcConfiguration? RtcConfig { get; set; }
 53
 54        /// <summary>
 55        /// Timeout of each signal connection attempt; <see cref="JoinRetries"/> sets how many attempts
 56        /// are made. Null, the default, waits 5 seconds.
 57        /// </summary>
 58        public TimeSpan? ConnectTimeout { get; set; }
 59
 60        /// <summary>
 61        /// Whether to publish and subscribe over a single peer connection, when the server supports
 62        /// it, instead of one peer connection for each. Null, the default, keeps the default of the
 63        /// native SDK, a single peer connection.
 64        /// </summary>
 65        public bool? SinglePeerConnection { get; set; }
 66
 67        /// <summary>
 68        /// Options of the incoming data streams. Null, the default, keeps the defaults.
 69        /// </summary>
 70        public DataStreamOptions? DataStream { get; set; }
 71
 72        internal Proto.RoomOptions ToProto()
 48573        {
 48574            var proto = new Proto.RoomOptions
 48575            {
 48576                AutoSubscribe = AutoSubscribe,
 48577                Dynacast = Dynacast,
 48578                AdaptiveStream = AdaptiveStream,
 48579                JoinRetries = JoinRetries,
 48580            };
 81
 82            // Without this the FFI ConnectRequest carries no E2EE configuration, the Rust SDK
 83            // never attaches frame cryptors, and media is silently sent/received in plaintext.
 48584            if (E2EE != null)
 3185            {
 3186                proto.Encryption = E2EE.ToProto();
 3187            }
 88
 48589            if (RtcConfig != null)
 1190            {
 1191                proto.RtcConfig = RtcConfig.ToProto();
 892            }
 93
 48294            if (ConnectTimeout.HasValue)
 795            {
 796                var milliseconds = Math.Ceiling(ConnectTimeout.Value.TotalMilliseconds);
 797                if (milliseconds <= 0)
 398                    throw new ArgumentOutOfRangeException(
 399                        nameof(ConnectTimeout),
 3100                        ConnectTimeout,
 3101                        "The connect timeout must be positive."
 3102                    );
 4103                proto.ConnectTimeoutMs = (ulong)milliseconds;
 4104            }
 105
 479106            if (SinglePeerConnection.HasValue)
 3107            {
 3108                proto.SinglePeerConnection = SinglePeerConnection.Value;
 3109            }
 110
 479111            if (DataStream != null)
 5112            {
 5113                proto.DataStream = DataStream.ToProto();
 4114            }
 115
 478116            return proto;
 478117        }
 118    }
 119
 120    /// <summary>
 121    /// WebRTC configuration of a room connection, set in <see cref="RoomOptions.RtcConfig"/>. Every
 122    /// property left unset keeps its default.
 123    /// </summary>
 124    /// <example>
 125    /// Use only TURN relays, for example behind a firewall that only lets TURN traffic through:
 126    /// <code language="csharp">
 127    /// var options = new RoomOptions
 128    /// {
 129    ///     RtcConfig = new RtcConfiguration { IceTransportType = IceTransportType.TransportRelay },
 130    /// };
 131    /// await room.ConnectAsync(url, token, options);
 132    /// </code>
 133    /// </example>
 134    public class RtcConfiguration
 135    {
 136        /// <summary>
 137        /// Which ICE candidates the connection may use: <see cref="Proto.IceTransportType.TransportRelay"/>
 138        /// only TURN relays, <see cref="Proto.IceTransportType.TransportNohost"/> every candidate but the
 139        /// host ones, <see cref="Proto.IceTransportType.TransportAll"/> all of them. Null, the default,
 140        /// uses all of them. Relays need a TURN server: the LiveKit server provides its own when TURN is
 141        /// enabled in its configuration, or set <see cref="IceServers"/>.
 142        /// </summary>
 143        public Proto.IceTransportType? IceTransportType { get; set; }
 144
 145        /// <summary>
 146        /// Whether ICE candidates are gathered once or continually, as the network changes. Null, the
 147        /// default, gathers them continually.
 148        /// </summary>
 149        public Proto.ContinualGatheringPolicy? ContinualGatheringPolicy { get; set; }
 150
 151        /// <summary>
 152        /// STUN and TURN servers to use instead of the ones the LiveKit server provides, which are
 153        /// replaced, not extended. Empty, the default, uses the ones of the LiveKit server.
 154        /// </summary>
 155        public IList<Proto.IceServer> IceServers { get; set; } = new List<Proto.IceServer>();
 156
 157        internal Proto.RtcConfig ToProto()
 158        {
 159            var proto = new Proto.RtcConfig();
 160
 161            if (IceTransportType.HasValue)
 162            {
 163                // The native SDK aborts the process on a value it does not know
 164                if (!Enum.IsDefined(typeof(Proto.IceTransportType), IceTransportType.Value))
 165                    throw new ArgumentOutOfRangeException(
 166                        nameof(IceTransportType),
 167                        IceTransportType.Value,
 168                        "Unknown ICE transport type."
 169                    );
 170                proto.IceTransportType = IceTransportType.Value;
 171            }
 172
 173            if (ContinualGatheringPolicy.HasValue)
 174            {
 175                if (
 176                    !Enum.IsDefined(
 177                        typeof(Proto.ContinualGatheringPolicy),
 178                        ContinualGatheringPolicy.Value
 179                    )
 180                )
 181                    throw new ArgumentOutOfRangeException(
 182                        nameof(ContinualGatheringPolicy),
 183                        ContinualGatheringPolicy.Value,
 184                        "Unknown continual gathering policy."
 185                    );
 186                proto.ContinualGatheringPolicy = ContinualGatheringPolicy.Value;
 187            }
 188
 189            if (IceServers != null)
 190            {
 191                foreach (var server in IceServers)
 192                {
 193                    if (server == null || server.Urls.Count == 0)
 194                        throw new ArgumentException(
 195                            "Every ICE server needs at least one URL.",
 196                            nameof(IceServers)
 197                        );
 198                    proto.IceServers.Add(server.Clone());
 199                }
 200            }
 201
 202            return proto;
 203        }
 204    }
 205
 206    /// <summary>
 207    /// Options of the incoming data streams of a room, set in <see cref="RoomOptions.DataStream"/>.
 208    /// </summary>
 209    public class DataStreamOptions
 210    {
 211        /// <summary>
 212        /// Maximum size in bytes, once decompressed, of one incoming text or byte stream. A longer
 213        /// stream ends with a <see cref="StreamException"/> on the reader. Null, the default, keeps the
 214        /// limit of the native SDK.
 215        /// </summary>
 216        public long? MaxPayloadByteLength { get; set; }
 217
 218        internal Proto.RoomDataStreamOptions ToProto()
 219        {
 220            var proto = new Proto.RoomDataStreamOptions();
 221            if (MaxPayloadByteLength.HasValue)
 222            {
 223                if (MaxPayloadByteLength.Value <= 0)
 224                    throw new ArgumentOutOfRangeException(
 225                        nameof(MaxPayloadByteLength),
 226                        MaxPayloadByteLength.Value,
 227                        "The maximum payload length must be positive."
 228                    );
 229                proto.MaxPayloadByteLength = (ulong)MaxPayloadByteLength.Value;
 230            }
 231            return proto;
 232        }
 233    }
 234
 235    /// <summary>
 236    /// A connection to a LiveKit room: joins it with <see cref="ConnectAsync"/>, exposes the local and remote
 237    /// participants and their tracks, and raises an event for every change.
 238    /// </summary>
 239    /// <example>
 240    /// <code language="csharp">
 241    /// using var room = new Room();
 242    /// room.ParticipantConnected += (sender, participant) =>
 243    ///     Console.WriteLine($"{participant.Identity} joined");
 244    /// room.TrackSubscribed += (sender, e) =>
 245    ///     Console.WriteLine($"Subscribed to {e.Track.Name} of {e.Participant.Identity}");
 246    ///
 247    /// await room.ConnectAsync("wss://my.livekit.instance", token);
 248    ///
 249    /// // Publish an audio track and feed it 10 ms frames of 16-bit PCM
 250    /// var source = new AudioSource(48000, 1);
 251    /// var track = LocalAudioTrack.Create("microphone", source);
 252    /// await room.LocalParticipant!.PublishTrackAsync(track);
 253    /// await source.CaptureFrameAsync(new AudioFrame(new short[480], 48000, 1, 480));
 254    ///
 255    /// await room.DisconnectAsync();
 256    /// </code>
 257    /// </example>
 258    public class Room : IDisposable
 259    {
 260        private FfiHandle? _roomHandle;
 261        private readonly Dictionary<string, RemoteParticipant> _remoteParticipants;
 262        private readonly object _lock = new object();
 263        private readonly SemaphoreSlim _ffiEventLock = new SemaphoreSlim(1, 1);
 264        private bool _disposed;
 265
 266        // CleanupOnDisconnect runs at most once per connection: DisconnectAsync and the FFI's
 267        // Disconnected room event both reach it
 268        private int _cleanedUp;
 269
 270        // Each ConnectAsync starts a new generation. The cleanup a disconnection defers to the event
 271        // chain only applies to its own generation: DisconnectAsync returns before the chain runs
 272        // it, so a ConnectAsync right after would otherwise have its listener and participants
 273        // removed by the previous connection's cleanup. Guarded by _connectionLock, as is the
 274        // listener subscription.
 275        private readonly object _connectionLock = new object();
 276        private int _connectionGeneration;
 277
 278        // 1 while a ConnectAsync call is in progress: a second one would open another native
 279        // connection that the room could not track
 280        private int _connecting;
 281
 282        // The disconnection in progress, shared by concurrent DisconnectAsync, Disconnect and
 283        // Dispose calls. Guarded by _connectionLock.
 284        private Task? _disconnecting;
 285
 286        // Native handles of connections that ended but whose event stream has not: the FFI keeps
 287        // emitting events for a closing room until its end-of-stream event, and some carry native
 288        // handles (a participant, a publication, a track, a data buffer) that leak unless someone
 289        // releases them. The room keeps listening until then. Guarded by _connectionLock.
 290        private readonly HashSet<ulong> _endedRoomHandles = new HashSet<ulong>();
 291
 292        // Connections whose end-of-stream event came before their cleanup, which then has nothing
 293        // to drain. Guarded by _connectionLock.
 294        private readonly HashSet<ulong> _endedStreams = new HashSet<ulong>();
 295
 296        // How long an ended connection is drained if its end-of-stream event never comes
 297        private static readonly TimeSpan EndedConnectionDrainTimeout = TimeSpan.FromSeconds(15);
 298
 299        // Remote participants that left, by identity, with a departure number: the FFI can still
 300        // deliver one of their track events after ParticipantDisconnected (the Rust SDK dispatches
 301        // subscriptions from another thread). Such an event is released without a warning. An
 302        // identity that joins again is removed, and only the last departures are kept. Protected by
 303        // _lock.
 304        private const int DepartedParticipantsKept = 128;
 305        private readonly Dictionary<string, long> _departedParticipants =
 306            new Dictionary<string, long>();
 307        private readonly Queue<KeyValuePair<string, long>> _departureOrder =
 308            new Queue<KeyValuePair<string, long>>();
 309        private long _departures;
 310        private E2EEManager? _e2eeManager;
 311
 312        // Serial Task Queue for event dispatching to ensure ordering and prevent deadlocks
 313        private Task _eventTaskChain = Task.CompletedTask;
 314        private readonly object _eventLock = new object();
 315
 316        // Stream handling
 317        private readonly Dictionary<string, TextStreamReader> _textStreamReaders =
 318            new Dictionary<string, TextStreamReader>();
 319        private readonly Dictionary<string, ByteStreamReader> _byteStreamReaders =
 320            new Dictionary<string, ByteStreamReader>();
 321        private readonly StreamHandlerRegistry _streamHandlers = new StreamHandlerRegistry();
 322
 323        // Remote data tracks by SID, delivered by DataTrackPublished. Protected by _lock.
 324        private readonly Dictionary<string, RemoteDataTrack> _remoteDataTracks =
 325            new Dictionary<string, RemoteDataTrack>();
 326
 327        /// <summary>
 328        /// Room session ID (assigned by the server).
 329        /// </summary>
 330        public string? Sid { get; private set; }
 331
 332        /// <summary>
 333        /// Internal FFI event lock for synchronization.
 334        /// </summary>
 335        internal SemaphoreSlim FfiEventLock => _ffiEventLock;
 336
 337        /// <summary>
 338        /// Room name.
 339        /// </summary>
 340        public string? Name { get; private set; }
 341
 342        /// <summary>
 343        /// Room metadata.
 344        /// </summary>
 345        public string? Metadata { get; private set; }
 346
 347        /// <summary>
 348        /// Number of participants in the room.
 349        /// </summary>
 350        public uint NumParticipants { get; private set; }
 351
 352        /// <summary>
 353        /// Number of publishers in the room.
 354        /// </summary>
 355        public uint NumPublishers { get; private set; }
 356
 357        /// <summary>
 358        /// Whether the room has an active recording.
 359        /// </summary>
 360        public bool ActiveRecording { get; private set; }
 361
 362        /// <summary>
 363        /// The time when the room was created.
 364        /// </summary>
 365        public DateTime CreationTime { get; private set; }
 366
 367        /// <summary>
 368        /// The time in seconds after which a room will be closed after the last participant has disconnected.
 369        /// </summary>
 370        public double DepartureTimeout { get; private set; }
 371
 372        /// <summary>
 373        /// The time in seconds after which an empty room will be automatically closed.
 374        /// </summary>
 375        public double EmptyTimeout { get; private set; }
 376
 377        /// <summary>
 378        /// The E2EE manager for this room. Null if E2EE is not enabled.
 379        /// </summary>
 380        public E2EEManager? E2EEManager => _e2eeManager;
 381
 382        /// <summary>
 383        /// The local participant in this room.
 384        /// </summary>
 385        public LocalParticipant? LocalParticipant { get; private set; }
 386
 387        /// <summary>
 388        /// Current connection state.
 389        /// </summary>
 390        public Proto.ConnectionState ConnectionState { get; private set; } =
 391            Proto.ConnectionState.ConnDisconnected;
 392
 393        /// <summary>
 394        /// Whether the room is currently connected.
 395        /// </summary>
 396        public bool IsConnected =>
 397            _roomHandle != null && ConnectionState != Proto.ConnectionState.ConnDisconnected;
 398
 399        /// <summary>
 400        /// Remote participants in the room (keyed by identity).
 401        /// </summary>
 402        public IReadOnlyDictionary<string, RemoteParticipant> RemoteParticipants
 403        {
 404            get
 405            {
 406                lock (_lock)
 407                {
 408                    return new Dictionary<string, RemoteParticipant>(_remoteParticipants);
 409                }
 410            }
 411        }
 412
 413        #region Events
 414
 415        /// <summary>
 416        /// Event raised when a participant connects to the room.
 417        /// </summary>
 418        public event EventHandler<Participant>? ParticipantConnected;
 419
 420        /// <summary>
 421        /// Event raised when a participant disconnects from the room.
 422        /// </summary>
 423        public event EventHandler<Participant>? ParticipantDisconnected;
 424
 425        /// <summary>
 426        /// Event raised when a local track is published.
 427        /// </summary>
 428        public event EventHandler<LocalTrackPublishedEventArgs>? LocalTrackPublished;
 429
 430        /// <summary>
 431        /// Event raised when a local track is unpublished.
 432        /// </summary>
 433        public event EventHandler<LocalTrackPublishedEventArgs>? LocalTrackUnpublished;
 434
 435        /// <summary>
 436        /// Event raised when a remote track is published.
 437        /// </summary>
 438        public event EventHandler<TrackPublishedEventArgs>? TrackPublished;
 439
 440        /// <summary>
 441        /// Event raised when a remote track is unpublished.
 442        /// </summary>
 443        public event EventHandler<TrackPublishedEventArgs>? TrackUnpublished;
 444
 445        /// <summary>
 446        /// Event raised when a remote track is subscribed.
 447        /// </summary>
 448        public event EventHandler<TrackSubscribedEventArgs>? TrackSubscribed;
 449
 450        /// <summary>
 451        /// Event raised when a remote track is unsubscribed.
 452        /// </summary>
 453        public event EventHandler<TrackSubscribedEventArgs>? TrackUnsubscribed;
 454
 455        /// <summary>
 456        /// Event raised when a track is muted.
 457        /// </summary>
 458        public event EventHandler<TrackMutedEventArgs>? TrackMuted;
 459
 460        /// <summary>
 461        /// Event raised when a track is unmuted.
 462        /// </summary>
 463        public event EventHandler<TrackMutedEventArgs>? TrackUnmuted;
 464
 465        /// <summary>
 466        /// Event raised when active speakers change.
 467        /// </summary>
 468        public event EventHandler<ActiveSpeakersChangedEventArgs>? ActiveSpeakersChanged;
 469
 470        /// <summary>
 471        /// Event raised when connection quality changes for a participant.
 472        /// </summary>
 473        public event EventHandler<ConnectionQualityChangedEventArgs>? ConnectionQualityChanged;
 474
 475        /// <summary>
 476        /// Event raised when data is received.
 477        /// </summary>
 478        public event EventHandler<DataReceivedEventArgs>? DataReceived;
 479
 480        /// <summary>
 481        /// Event raised when connection state changes.
 482        /// </summary>
 483        public event EventHandler<Proto.ConnectionState>? ConnectionStateChanged;
 484
 485        /// <summary>
 486        /// Event raised when room is connected.
 487        /// </summary>
 488        public event EventHandler? Connected;
 489
 490        /// <summary>
 491        /// Event raised when room is disconnected.
 492        /// </summary>
 493        public event EventHandler<Proto.DisconnectReason>? Disconnected;
 494
 495        /// <summary>
 496        /// Event raised when room is reconnecting.
 497        /// </summary>
 498        public event EventHandler? Reconnecting;
 499
 500        /// <summary>
 501        /// Event raised when room has reconnected.
 502        /// </summary>
 503        public event EventHandler? Reconnected;
 504
 505        /// <summary>
 506        /// Event raised when room metadata changes.
 507        /// </summary>
 508        public event EventHandler<string>? RoomMetadataChanged;
 509
 510        /// <summary>
 511        /// Event raised when a participant's metadata changes.
 512        /// </summary>
 513        public event EventHandler<Participant>? ParticipantMetadataChanged;
 514
 515        /// <summary>
 516        /// Event raised when a participant's name changes.
 517        /// </summary>
 518        public event EventHandler<Participant>? ParticipantNameChanged;
 519
 520        /// <summary>
 521        /// Event raised when a participant's attributes change.
 522        /// </summary>
 523        public event EventHandler<ParticipantAttributesChangedEventArgs>? ParticipantAttributesChanged;
 524
 525        /// <summary>
 526        /// Event raised when a participant's encryption status changes.
 527        /// </summary>
 528        public event EventHandler<ParticipantEncryptionStatusChangedEventArgs>? ParticipantEncryptionStatusChanged;
 529
 530        /// <summary>
 531        /// Event raised when a local track is subscribed by a remote participant.
 532        /// </summary>
 533        public event EventHandler<LocalTrackSubscribedEventArgs>? LocalTrackSubscribed;
 534
 535        /// <summary>
 536        /// Event raised when track subscription fails.
 537        /// </summary>
 538        public event EventHandler<TrackSubscriptionFailedEventArgs>? TrackSubscriptionFailed;
 539
 540        /// <summary>
 541        /// Event raised when room information is updated.
 542        /// </summary>
 543        public event EventHandler<RoomInfo>? RoomUpdated;
 544
 545        /// <summary>
 546        /// Event raised when the room SID changes.
 547        /// </summary>
 548        public event EventHandler<string>? RoomSidChanged;
 549
 550        /// <summary>
 551        /// Event raised when the local participant is moved to a new room.
 552        /// </summary>
 553        public event EventHandler<RoomInfo>? Moved;
 554
 555        /// <summary>
 556        /// Event raised when a chat message is received.
 557        /// </summary>
 558        public event EventHandler<ChatMessageReceivedEventArgs>? ChatMessageReceived;
 559
 560        /// <summary>
 561        /// Event raised when a SIP DTMF tone is received.
 562        /// </summary>
 563        public event EventHandler<SipDtmfReceivedEventArgs>? SipDtmfReceived;
 564
 565        /// <summary>
 566        /// Raised when the encryption state of a participant changes: <c>Ok</c> once its frames encrypt or
 567        /// decrypt, or a failure such as <c>MissingKey</c> or <c>DecryptionFailed</c>.
 568        /// </summary>
 569        public event EventHandler<E2EEStateChangedEventArgs>? E2EEStateChanged;
 570
 571        /// <summary>
 572        /// Event raised when a transcription is received.
 573        /// </summary>
 574        public event EventHandler<TranscriptionReceivedEventArgs>? TranscriptionReceived;
 575
 576        /// <summary>
 577        /// Event raised when the access token is refreshed.
 578        /// </summary>
 579        public event EventHandler<string>? TokenRefreshed;
 580
 581        /// <summary>
 582        /// Raised when the permissions of a participant (local or remote) change.
 583        /// <see cref="Participant.Permissions"/> is already updated when the event fires.
 584        /// </summary>
 585        public event EventHandler<ParticipantPermissionsChangedEventArgs>? ParticipantPermissionsChanged;
 586
 587        /// <summary>
 588        /// Raised when a remote participant becomes active and is ready to receive data messages.
 589        /// </summary>
 590        public event EventHandler<RemoteParticipant>? ParticipantActive;
 591
 592        /// <summary>
 593        /// Raised when the SDK re-published a local track during a full reconnect. The publication
 594        /// object is updated in place with the new server-assigned SIDs; the previous SID is passed
 595        /// so state keyed by it can be reconciled.
 596        /// </summary>
 597        public event EventHandler<LocalTrackRepublishedEventArgs>? LocalTrackRepublished;
 598
 599        /// <summary>
 600        /// Raised when a remote participant publishes a data track. Subscribe to it with
 601        /// <see cref="RemoteDataTrack.Subscribe"/>.
 602        /// </summary>
 603        public event EventHandler<RemoteDataTrack>? DataTrackPublished;
 604
 605        /// <summary>
 606        /// Raised when a remote data track is unpublished.
 607        /// </summary>
 608        public event EventHandler<DataTrackUnpublishedEventArgs>? DataTrackUnpublished;
 609
 610        /// <summary>
 611        /// Raised after <see cref="LocalParticipant.SetDataChannelBufferedAmountLowThreshold"/>
 612        /// changed the threshold of a data channel.
 613        /// </summary>
 614        public event EventHandler<DataChannelBufferedAmountLowThresholdChangedEventArgs>? DataChannelBufferedAmountLowTh
 615
 616        /// <summary>
 617        /// Data tracks currently published by remote participants, by SID.
 618        /// </summary>
 619        public IReadOnlyDictionary<string, RemoteDataTrack> RemoteDataTracks
 620        {
 621            get
 622            {
 623                lock (_lock)
 624                {
 625                    return new Dictionary<string, RemoteDataTrack>(_remoteDataTracks);
 626                }
 627            }
 628        }
 629
 630        #endregion
 631
 632        /// <summary>
 633        /// Registers a handler for incoming text data streams on a specific topic.
 634        /// </summary>
 635        /// <param name="topic">The topic to listen for text streams on.</param>
 636        /// <param name="handler">Handler to process incoming text streams.</param>
 637        /// <exception cref="StreamException">Thrown when a handler for this topic is already registered.</exception>
 638        public void RegisterTextStreamHandler(string topic, TextStreamHandler handler)
 639        {
 640            _streamHandlers.RegisterTextStreamHandler(topic, handler);
 641        }
 642
 643        /// <summary>
 644        /// Unregisters a text stream handler for a specific topic.
 645        /// </summary>
 646        /// <param name="topic">The topic to unregister.</param>
 647        public void UnregisterTextStreamHandler(string topic)
 648        {
 649            _streamHandlers.UnregisterTextStreamHandler(topic);
 650        }
 651
 652        /// <summary>
 653        /// Registers a handler for incoming byte data streams on a specific topic.
 654        /// </summary>
 655        /// <param name="topic">The topic to listen for byte streams on.</param>
 656        /// <param name="handler">Handler to process incoming byte streams.</param>
 657        /// <exception cref="StreamException">Thrown when a handler for this topic is already registered.</exception>
 658        public void RegisterByteStreamHandler(string topic, ByteStreamHandler handler)
 659        {
 660            _streamHandlers.RegisterByteStreamHandler(topic, handler);
 661        }
 662
 663        /// <summary>
 664        /// Unregisters a byte stream handler for a specific topic.
 665        /// </summary>
 666        /// <param name="topic">The topic to unregister.</param>
 667        public void UnregisterByteStreamHandler(string topic)
 668        {
 669            _streamHandlers.UnregisterByteStreamHandler(topic);
 670        }
 671
 672        // Invokes each handler on its own: one that throws is logged and must not hide the event
 673        // from the handlers subscribed after it
 674        private void Raise<TArgs>(EventHandler<TArgs>? handlers, TArgs args, string eventName)
 675        {
 676            if (handlers == null)
 677                return;
 678            foreach (var handler in handlers.GetInvocationList())
 679            {
 680                try
 681                {
 682                    ((EventHandler<TArgs>)handler)(this, args);
 683                }
 684                catch (Exception ex)
 685                {
 686                    Console.Error.WriteLine($"[ERROR] Room.{eventName} handler threw: {ex}");
 687                }
 688            }
 689        }
 690
 691        private void Raise(EventHandler? handlers, string eventName)
 692        {
 693            if (handlers == null)
 694                return;
 695            foreach (var handler in handlers.GetInvocationList())
 696            {
 697                try
 698                {
 699                    ((EventHandler)handler)(this, EventArgs.Empty);
 700                }
 701                catch (Exception ex)
 702                {
 703                    Console.Error.WriteLine($"[ERROR] Room.{eventName} handler threw: {ex}");
 704                }
 705            }
 706        }
 707
 708        /// <summary>
 709        /// Dispatches events asynchronously while maintaining strict FIFO order.
 710        /// This prevents deadlocks and protects the FFI thread from user-code exceptions.
 711        /// </summary>
 712        private void DispatchEvent(Action action)
 713        {
 714            lock (_eventLock)
 715            {
 716                _eventTaskChain = _eventTaskChain.ContinueWith(
 717                    _ =>
 718                    {
 719                        try
 720                        {
 721                            action();
 722                        }
 723                        catch (Exception ex)
 724                        {
 725                            Console.Error.WriteLine($"[ERROR] Room event handler exception: {ex}");
 726                        }
 727                    },
 728                    TaskScheduler.Default
 729                );
 730            }
 731        }
 732
 733        // Overload to handle async delegates directly
 734        private void DispatchEvent(Func<Task> action)
 735        {
 736            lock (_eventLock)
 737            {
 738                _eventTaskChain = _eventTaskChain
 739                    .ContinueWith(
 740                        async _ =>
 741                        {
 742                            try
 743                            {
 744                                await action();
 745                            }
 746                            catch (Exception ex)
 747                            {
 748                                Console.Error.WriteLine(
 749                                    $"[ERROR] Room event handler exception: {ex}"
 750                                );
 751                            }
 752                        },
 753                        TaskScheduler.Default
 754                    )
 755                    .Unwrap();
 756            }
 757        }
 758
 759        /// <summary>
 760        /// Creates a new Room instance.
 761        /// </summary>
 762        public Room()
 763        {
 764            _remoteParticipants = new Dictionary<string, RemoteParticipant>();
 765        }
 766
 767        // Reports a state once per change, with the value at the time of the change (the
 768        // handler may run later, when the state has already moved on)
 769        private void UpdateConnectionState(Proto.ConnectionState newState)
 770        {
 771            if (ConnectionState == newState)
 772                return;
 773            ConnectionState = newState;
 774            var state = newState;
 775            DispatchEvent(() =>
 776                Raise(ConnectionStateChanged, state, nameof(ConnectionStateChanged))
 777            );
 778        }
 779
 780        /// <summary>
 781        /// Connects to a LiveKit room.
 782        /// </summary>
 783        /// <param name="url">The LiveKit server URL (e.g., wss://your-server.livekit.cloud).</param>
 784        /// <param name="token">The access token for authentication.</param>
 785        /// <param name="options">Optional room options.</param>
 786        /// <param name="cancellationToken">
 787        /// Cancels the connection attempt. A connection the native side completes after the cancellation is
 788        /// left in the background; a token that is already cancelled throws before anything is sent.
 789        /// </param>
 790        /// <returns>A task that completes when the connection is established.</returns>
 791        /// <exception cref="InvalidOperationException">
 792        /// Thrown when the room is already connected, or another <see cref="ConnectAsync"/> call is connecting it.
 793        /// </exception>
 794        /// <exception cref="ArgumentException">
 795        /// Thrown, before anything is sent, when an option is invalid (a non-positive timeout or payload
 796        /// length, an unknown enum value, an ICE server without URL).
 797        /// </exception>
 798        public async Task ConnectAsync(
 799            string url,
 800            string token,
 801            RoomOptions? options = null,
 802            CancellationToken cancellationToken = default
 803        )
 804        {
 805            if (_disposed)
 806                throw new ObjectDisposedException(nameof(Room));
 807
 808            // Validates the options, before any side effect
 809            options ??= new RoomOptions();
 810            var protoOptions = options.ToProto();
 811
 812            // Before any side effect: a connect request, once sent, opens a native connection that a
 813            // cancellation can only abandon in the background
 814            cancellationToken.ThrowIfCancellationRequested();
 815
 816            if (Interlocked.CompareExchange(ref _connecting, 1, 0) != 0)
 817                throw new InvalidOperationException("Room is already connecting");
 818            try
 819            {
 820                if (IsConnected)
 821                    throw new InvalidOperationException("Room is already connected");
 822
 823                await ConnectCoreAsync(url, token, options, protoOptions, cancellationToken)
 824                    .ConfigureAwait(false);
 825            }
 826            finally
 827            {
 828                Volatile.Write(ref _connecting, 0);
 829            }
 830        }
 831
 832        private async Task ConnectCoreAsync(
 833            string url,
 834            string token,
 835            RoomOptions options,
 836            Proto.RoomOptions protoOptions,
 837            CancellationToken cancellationToken
 838        )
 839        {
 840            List<TextStreamReader> staleTextReaders;
 841            List<ByteStreamReader> staleByteReaders;
 842            lock (_connectionLock)
 843            {
 844                // A new generation: the deferred cleanup of the previous connection, if it has not
 845                // run yet, leaves this one alone. What it would have cleared is cleared here.
 846                _connectionGeneration++;
 847                ClearConnectionState(out staleTextReaders, out staleByteReaders);
 848
 849                // Listen to FFI events for the lifetime of this connection (CleanupOnDisconnect
 850                // unsubscribes): a Room that is never disposed must not stay in the process-wide
 851                // FfiClient forever
 852                FfiClient.Instance.EventReceived -= OnFfiEvent;
 853                FfiClient.Instance.EventReceived += OnFfiEvent;
 854                Interlocked.Exchange(ref _cleanedUp, 0);
 855            }
 856            FailStreamReaders(staleTextReaders, staleByteReaders);
 857
 858            // Send connect request
 859            var request = new FfiRequest
 860            {
 861                Connect = new ConnectRequest
 862                {
 863                    Url = url,
 864                    Token = token,
 865                    Options = protoOptions,
 866                },
 867            };
 868
 869            var response = FfiClient.Instance.SendRequest(request);
 870
 871            if (response.Connect == null)
 872                throw new InvalidOperationException("Invalid connect response");
 873
 874            var asyncId = response.Connect.AsyncId;
 875
 876            // Wait for connect callback
 877            FfiEvent connectEvent;
 878            try
 879            {
 880                connectEvent = await FfiClient.Instance.WaitForEventAsync(
 881                    e =>
 882                        e.MessageCase == FfiEvent.MessageOneofCase.Connect
 883                        && e.Connect?.AsyncId == asyncId,
 884                    TimeSpan.FromSeconds(30),
 885                    cancellationToken
 886                );
 887            }
 888            catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
 889            {
 890                // The FFI may still complete the connection. It then waits for ReadyForRoomEvent
 891                // and, if it never comes, panics, which terminates the process. Finish the
 892                // handshake and leave the room in the background.
 893                StopListeningUnlessDraining();
 894                _ = AbandonConnectAsync(asyncId);
 895                throw;
 896            }
 897
 898            var callback = connectEvent.Connect!;
 899
 900            if (!string.IsNullOrEmpty(callback.Error))
 901            {
 902                StopListeningUnlessDraining();
 903                UpdateConnectionState(Proto.ConnectionState.ConnDisconnected);
 904                throw new RoomException($"Failed to connect: {callback.Error}");
 905            }
 906
 907            // Get the result from the callback
 908            var result = callback.Result;
 909            if (result == null)
 910            {
 911                StopListeningUnlessDraining();
 912                throw new RoomException("Connect callback has no result");
 913            }
 914
 915            if (_disposed)
 916            {
 917                // Disposed while connecting: nothing may keep the native room alive
 918                StopListeningUnlessDraining();
 919                _ = ReleaseAbandonedConnectionAsync(result);
 920                throw new ObjectDisposedException(nameof(Room));
 921            }
 922
 923            // Store room handle and info
 924            if (result.Room?.Handle != null)
 925            {
 926                _roomHandle = FfiHandle.FromId(result.Room.Handle.Id);
 927                UpdateFromInfo(result.Room.Info);
 928
 929                // Initialize E2EE manager if E2EE options were provided
 930                if (options.E2EE != null)
 931                {
 932                    _e2eeManager = new E2EEManager(_roomHandle.HandleId, options.E2EE);
 933                }
 934            }
 935
 936            // Create local participant
 937            if (result.LocalParticipant?.Handle != null)
 938            {
 939                LocalParticipant = new LocalParticipant(
 940                    FfiHandle.FromId(result.LocalParticipant.Handle.Id),
 941                    result.LocalParticipant.Info,
 942                    this
 943                );
 944            }
 945
 946            // Create remote participants
 947            foreach (var participantWithTracks in result.Participants)
 948            {
 949                if (participantWithTracks.Participant?.Info != null)
 950                {
 951                    var remoteParticipant = new RemoteParticipant(
 952                        FfiHandle.FromId(participantWithTracks.Participant.Handle!.Id),
 953                        participantWithTracks.Participant.Info,
 954                        this
 955                    );
 956
 957                    // Add publications
 958                    foreach (var pub in participantWithTracks.Publications)
 959                    {
 960                        if (pub.Handle != null && pub.Info != null)
 961                        {
 962                            remoteParticipant.AddPublication(pub);
 963                        }
 964                    }
 965
 966                    lock (_lock)
 967                    {
 968                        _remoteParticipants[remoteParticipant.Identity] = remoteParticipant;
 969                    }
 970                }
 971            }
 972
 973            UpdateConnectionState(Proto.ConnectionState.ConnConnected);
 974
 975            // Release the FFI room event gate after our listener and local state are ready.
 976            var readyRequest = new FfiRequest
 977            {
 978                ReadyForRoomEvent = new ReadyForRoomEventRequest
 979                {
 980                    RoomHandle = _roomHandle!.HandleId,
 981                },
 982            };
 983            FfiClient.Instance.SendRequest(readyRequest);
 984
 985            DispatchEvent(() => Raise(Connected, nameof(Connected)));
 986        }
 987
 988        // A connect that the caller gave up on (cancellation, timeout) but that the FFI may still
 989        // complete: wait for its callback, then release the room properly.
 990        private async Task AbandonConnectAsync(ulong asyncId)
 991        {
 992            try
 993            {
 994                var connectEvent = await FfiClient.Instance.WaitForEventAsync(
 995                    e =>
 996                        e.MessageCase == FfiEvent.MessageOneofCase.Connect
 997                        && e.Connect?.AsyncId == asyncId,
 998                    TimeSpan.FromSeconds(60)
 999                );
 1000                var result = connectEvent.Connect?.Result;
 1001                if (result != null && string.IsNullOrEmpty(connectEvent.Connect?.Error))
 1002                {
 1003                    await ReleaseAbandonedConnectionAsync(result);
 1004                }
 1005            }
 1006            catch (Exception ex)
 1007            {
 1008                Console.Error.WriteLine(
 1009                    $"[WARN] Could not release an abandoned room connection: {ex.Message}"
 1010                );
 1011            }
 1012        }
 1013
 1014        private static async Task ReleaseAbandonedConnectionAsync(
 1015            ConnectCallback.Types.Result result
 1016        )
 1017        {
 1018            var handles = new List<ulong>();
 1019            if (result.Room?.Handle != null)
 1020                handles.Add(result.Room.Handle.Id);
 1021            if (result.LocalParticipant?.Handle != null)
 1022                handles.Add(result.LocalParticipant.Handle.Id);
 1023            foreach (var participant in result.Participants)
 1024            {
 1025                if (participant.Participant?.Handle != null)
 1026                    handles.Add(participant.Participant.Handle.Id);
 1027                foreach (var publication in participant.Publications)
 1028                {
 1029                    if (publication.Handle != null)
 1030                        handles.Add(publication.Handle.Id);
 1031                }
 1032            }
 1033
 1034            try
 1035            {
 1036                var roomHandleId = result.Room?.Handle?.Id ?? 0;
 1037                if (roomHandleId != 0)
 1038                {
 1039                    // The FFI forwards nothing (and panics after 15 s) until it gets this
 1040                    FfiClient.Instance.SendRequest(
 1041                        new FfiRequest
 1042                        {
 1043                            ReadyForRoomEvent = new ReadyForRoomEventRequest
 1044                            {
 1045                                RoomHandle = roomHandleId,
 1046                            },
 1047                        }
 1048                    );
 1049                    var response = FfiClient.Instance.SendRequest(
 1050                        new FfiRequest
 1051                        {
 1052                            Disconnect = new DisconnectRequest
 1053                            {
 1054                                RoomHandle = roomHandleId,
 1055                                Reason = Proto.DisconnectReason.ClientInitiated,
 1056                            },
 1057                        }
 1058                    );
 1059                    var asyncId = response.Disconnect?.AsyncId ?? 0;
 1060                    await FfiClient.Instance.WaitForEventAsync(
 1061                        e =>
 1062                            e.MessageCase == FfiEvent.MessageOneofCase.Disconnect
 1063                            && e.Disconnect?.AsyncId == asyncId,
 1064                        TimeSpan.FromSeconds(10)
 1065                    );
 1066                }
 1067            }
 1068            catch (Exception ex)
 1069            {
 1070                Console.Error.WriteLine(
 1071                    $"[WARN] Could not release an abandoned room connection: {ex.Message}"
 1072                );
 1073            }
 1074            finally
 1075            {
 1076                foreach (var id in handles)
 1077                {
 1078                    FfiHandle.FromId(id).Dispose();
 1079                }
 1080            }
 1081        }
 1082
 1083        /// <summary>
 1084        /// Disconnects from the room. Concurrent calls (and <see cref="Disconnect"/> or <see cref="Dispose"/>)
 1085        /// share the same disconnection; a call on a room that is not connected does nothing.
 1086        /// </summary>
 1087        /// <returns>A task that completes once the room is disconnected and its resources are released.</returns>
 1088        public Task DisconnectAsync()
 1089        {
 1090            lock (_connectionLock)
 1091            {
 1092                if (_disconnecting != null && !_disconnecting.IsCompleted)
 1093                    return _disconnecting;
 1094
 1095                // Read once: the cleanup of a disconnection that is finishing clears it
 1096                var roomHandle = _roomHandle;
 1097                if (roomHandle == null)
 1098                    return Task.CompletedTask;
 1099
 1100                _disconnecting = DisconnectCoreAsync(roomHandle);
 1101                return _disconnecting;
 1102            }
 1103        }
 1104
 1105        private async Task DisconnectCoreAsync(FfiHandle roomHandle)
 1106        {
 1107            var request = new FfiRequest
 1108            {
 1109                Disconnect = new DisconnectRequest
 1110                {
 1111                    RoomHandle = roomHandle.HandleId,
 1112                    Reason = Proto.DisconnectReason.ClientInitiated,
 1113                },
 1114            };
 1115
 1116            try
 1117            {
 1118                // The FFI may have closed the room on its own meanwhile (the server removed the
 1119                // participant): the request then fails, and the cleanup below is all that is left
 1120                var response = FfiClient.Instance.SendRequest(request);
 1121
 1122                if (response.Disconnect == null)
 1123                    throw new InvalidOperationException("Invalid disconnect response");
 1124
 1125                var asyncId = response.Disconnect.AsyncId;
 1126
 1127                // Wait for disconnect callback. Not resumed on the caller's context: Disconnect and
 1128                // Dispose block on this method, which would deadlock a UI thread
 1129                await FfiClient
 1130                    .Instance.WaitForEventAsync(
 1131                        e =>
 1132                            e.MessageCase == FfiEvent.MessageOneofCase.Disconnect
 1133                            && e.Disconnect?.AsyncId == asyncId,
 1134                        TimeSpan.FromSeconds(10)
 1135                    )
 1136                    .ConfigureAwait(false);
 1137            }
 1138            finally
 1139            {
 1140                // Even if the callback never came: the room must not stay "connected"
 1141                CleanupOnDisconnect(Proto.DisconnectReason.ClientInitiated);
 1142            }
 1143        }
 1144
 1145        /// <summary>
 1146        /// Forces a reconnection scenario, for tests. With
 1147        /// <see cref="Proto.SimulateScenarioKind.SimulateFullReconnect"/> the SDK rebuilds its session
 1148        /// and republishes the local tracks: <see cref="Reconnecting"/> fires, then one
 1149        /// <see cref="LocalTrackRepublished"/> per published track, then <see cref="Reconnected"/>.
 1150        /// With <see cref="Proto.SimulateScenarioKind.SimulateSignalReconnect"/> only the signaling
 1151        /// connection is re-established (a resume) and the publications are kept. See
 1152        /// <see cref="Proto.SimulateScenarioKind"/> for the other variants. The returned task completes
 1153        /// once the SDK has started the scenario, not when the reconnection has finished: observe that
 1154        /// through the room events.
 1155        /// </summary>
 1156        /// <param name="scenario">The scenario to simulate.</param>
 1157        /// <param name="cancellationToken">
 1158        /// Cancels the wait for the SDK to start the scenario, not the scenario. A token that is already
 1159        /// cancelled throws before the scenario is requested.
 1160        /// </param>
 1161        /// <returns>A task that completes once the SDK has started the scenario, not when the reconnection has finished
 1162        /// <exception cref="InvalidOperationException">Thrown when not connected to a room.</exception>
 1163        /// <exception cref="RoomException">Thrown when the SDK reports that the scenario failed.</exception>
 1164        public async Task SimulateScenarioAsync(
 1165            Proto.SimulateScenarioKind scenario,
 1166            CancellationToken cancellationToken = default
 1167        )
 1168        {
 1169            if (!IsConnected || _roomHandle == null)
 1170                throw new InvalidOperationException("Not connected to a room");
 1171            cancellationToken.ThrowIfCancellationRequested();
 1172
 1173            var response = FfiClient.Instance.SendRequest(
 1174                new FfiRequest
 1175                {
 1176                    SimulateScenario = new SimulateScenarioRequest
 1177                    {
 1178                        RoomHandle = _roomHandle.HandleId,
 1179                        Scenario = scenario,
 1180                    },
 1181                }
 1182            );
 1183
 1184            if (response.SimulateScenario == null)
 1185                throw new InvalidOperationException("Invalid simulate scenario response");
 1186
 1187            var asyncId = response.SimulateScenario.AsyncId;
 1188
 1189            var callbackEvent = await FfiClient.Instance.WaitForEventAsync(
 1190                e =>
 1191                    e.MessageCase == FfiEvent.MessageOneofCase.SimulateScenario
 1192                    && e.SimulateScenario?.AsyncId == asyncId,
 1193                TimeSpan.FromSeconds(30),
 1194                cancellationToken
 1195            );
 1196
 1197            var callback = callbackEvent.SimulateScenario!;
 1198            if (callback.HasError && !string.IsNullOrEmpty(callback.Error))
 1199                throw new RoomException($"Simulate scenario failed: {callback.Error}");
 1200        }
 1201
 1202        /// <summary>
 1203        /// Gets RTC statistics for the current session.
 1204        /// </summary>
 1205        /// <returns>RTC statistics containing publisher and subscriber stats.</returns>
 1206        /// <exception cref="InvalidOperationException">Thrown when not connected to a room.</exception>
 1207        public async Task<RtcStats> GetRtcStatsAsync()
 1208        {
 1209            if (!IsConnected || _roomHandle == null)
 1210                throw new InvalidOperationException("Not connected to a room");
 1211
 1212            var request = new FfiRequest
 1213            {
 1214                GetSessionStats = new GetSessionStatsRequest { RoomHandle = _roomHandle.HandleId },
 1215            };
 1216
 1217            var response = FfiClient.Instance.SendRequest(request);
 1218
 1219            if (response.GetSessionStats == null)
 1220                throw new InvalidOperationException("Invalid get session stats response");
 1221
 1222            var asyncId = response.GetSessionStats.AsyncId;
 1223
 1224            // Wait for stats callback
 1225            var statsEvent = await FfiClient.Instance.WaitForEventAsync(
 1226                e =>
 1227                    e.MessageCase == FfiEvent.MessageOneofCase.GetSessionStats
 1228                    && e.GetSessionStats?.AsyncId == asyncId,
 1229                TimeSpan.FromSeconds(10)
 1230            );
 1231
 1232            var callback = statsEvent.GetSessionStats!;
 1233
 1234            if (!string.IsNullOrEmpty(callback.Error))
 1235            {
 1236                throw new RoomException($"Failed to get RTC stats: {callback.Error}");
 1237            }
 1238
 1239            var result = callback.Result;
 1240            if (result == null)
 1241            {
 1242                throw new RoomException("Get session stats callback has no result");
 1243            }
 1244
 1245            return new RtcStats
 1246            {
 1247                PublisherStats = new List<Proto.RtcStats>(result.PublisherStats),
 1248                SubscriberStats = new List<Proto.RtcStats>(result.SubscriberStats),
 1249            };
 1250        }
 1251
 1252        /// <summary>
 1253        /// Disconnects from the room, blocking the calling thread until it is done. Prefer
 1254        /// <see cref="DisconnectAsync"/> in asynchronous code.
 1255        /// </summary>
 1256        public void Disconnect()
 1257        {
 1258            DisconnectAsync().GetAwaiter().GetResult();
 1259        }
 1260
 1261        private void UpdateFromInfo(RoomInfo? info)
 1262        {
 1263            if (info == null)
 1264                return;
 1265
 1266            Sid = info.Sid;
 1267            Name = info.Name;
 1268            Metadata = info.Metadata;
 1269            NumParticipants = info.NumParticipants;
 1270            NumPublishers = info.NumPublishers;
 1271            ActiveRecording = info.ActiveRecording;
 1272
 1273            // Convert creation time from nanoseconds to DateTime
 1274            // Note: Rust SDK may send seconds or ms, we handle both cases
 1275            var creationTimeValue = info.CreationTime;
 1276            if (creationTimeValue > 0)
 1277            {
 1278                // If value looks like seconds (less than year 3000 in ms), convert to ms
 1279                if (creationTimeValue < 1_000_000_000_000L)
 1280                {
 1281                    creationTimeValue *= 1000;
 1282                }
 1283                CreationTime = DateTimeOffset.FromUnixTimeMilliseconds(creationTimeValue).DateTime;
 1284            }
 1285            else
 1286            {
 1287                CreationTime = DateTime.MinValue;
 1288            }
 1289
 1290            DepartureTimeout = info.DepartureTimeout;
 1291            EmptyTimeout = info.EmptyTimeout;
 1292        }
 1293
 1294        private void OnFfiEvent(object? sender, FfiEvent e)
 1295        {
 1296            if (e.MessageCase == FfiEvent.MessageOneofCase.RoomEvent)
 1297            {
 1298                var roomEvent = e.RoomEvent;
 1299                if (roomEvent == null)
 1300                    return;
 1301
 1302                var roomHandle = _roomHandle;
 1303                if (roomHandle != null && roomEvent.RoomHandle == roomHandle.HandleId)
 1304                    HandleRoomEvent(roomEvent);
 1305                else
 1306                    DrainEndedConnection(roomEvent);
 1307            }
 1308            else if (e.MessageCase == FfiEvent.MessageOneofCase.RpcMethodInvocation)
 1309            {
 1310                var invocation = e.RpcMethodInvocation;
 1311                var localParticipant = LocalParticipant; // cleared by CleanupOnDisconnect meanwhile
 1312                if (invocation == null || localParticipant == null)
 1313                    return;
 1314
 1315                // Check if this event is for our local participant
 1316                if (invocation.LocalParticipantHandle != localParticipant.Handle.HandleId)
 1317                    return;
 1318
 1319                // Fire and forget immediately. Do NOT use DispatchEvent.
 1320                // RPCs are independent request/response cycles and should not be blocked by the event queue.
 1321                _ = Task.Run(async () =>
 1322                {
 1323                    try
 1324                    {
 1325                        await localParticipant.HandleRpcMethodInvocationAsync(
 1326                            invocation.InvocationId,
 1327                            invocation.Method,
 1328                            invocation.RequestId,
 1329                            invocation.CallerIdentity,
 1330                            invocation.Payload,
 1331                            invocation.ResponseTimeoutMs
 1332                        );
 1333                    }
 1334                    catch (Exception ex)
 1335                    {
 1336                        // Log error but don't crash
 1337                        Console.Error.WriteLine($"[ERROR] Error handling RPC invocation: {ex}");
 1338                    }
 1339                });
 1340            }
 1341        }
 1342
 1343        private void HandleRoomEvent(RoomEvent roomEvent)
 1344        {
 1345            switch (roomEvent.MessageCase)
 1346            {
 1347                case RoomEvent.MessageOneofCase.ParticipantConnected:
 1348                    HandleParticipantConnected(roomEvent.ParticipantConnected);
 1349                    break;
 1350
 1351                case RoomEvent.MessageOneofCase.ParticipantDisconnected:
 1352                    HandleParticipantDisconnected(roomEvent.ParticipantDisconnected);
 1353                    break;
 1354
 1355                case RoomEvent.MessageOneofCase.LocalTrackPublished:
 1356                    HandleLocalTrackPublished(roomEvent.LocalTrackPublished);
 1357                    break;
 1358
 1359                case RoomEvent.MessageOneofCase.LocalTrackUnpublished:
 1360                    HandleLocalTrackUnpublished(roomEvent.LocalTrackUnpublished);
 1361                    break;
 1362
 1363                case RoomEvent.MessageOneofCase.LocalTrackSubscribed:
 1364                    HandleLocalTrackSubscribed(roomEvent.LocalTrackSubscribed);
 1365                    break;
 1366
 1367                case RoomEvent.MessageOneofCase.TrackPublished:
 1368                    HandleTrackPublished(roomEvent.TrackPublished);
 1369                    break;
 1370
 1371                case RoomEvent.MessageOneofCase.TrackUnpublished:
 1372                    HandleTrackUnpublished(roomEvent.TrackUnpublished);
 1373                    break;
 1374
 1375                case RoomEvent.MessageOneofCase.TrackSubscribed:
 1376                    HandleTrackSubscribed(roomEvent.TrackSubscribed);
 1377                    break;
 1378
 1379                case RoomEvent.MessageOneofCase.TrackUnsubscribed:
 1380                    HandleTrackUnsubscribed(roomEvent.TrackUnsubscribed);
 1381                    break;
 1382
 1383                case RoomEvent.MessageOneofCase.TrackMuted:
 1384                    HandleTrackMuted(roomEvent.TrackMuted);
 1385                    break;
 1386
 1387                case RoomEvent.MessageOneofCase.TrackUnmuted:
 1388                    HandleTrackUnmuted(roomEvent.TrackUnmuted);
 1389                    break;
 1390
 1391                case RoomEvent.MessageOneofCase.ActiveSpeakersChanged:
 1392                    HandleActiveSpeakersChanged(roomEvent.ActiveSpeakersChanged);
 1393                    break;
 1394
 1395                case RoomEvent.MessageOneofCase.ConnectionQualityChanged:
 1396                    HandleConnectionQualityChanged(roomEvent.ConnectionQualityChanged);
 1397                    break;
 1398
 1399                case RoomEvent.MessageOneofCase.DataPacketReceived:
 1400                    HandleDataPacketReceived(roomEvent.DataPacketReceived);
 1401                    break;
 1402
 1403                case RoomEvent.MessageOneofCase.RoomMetadataChanged:
 1404                    HandleRoomMetadataChanged(roomEvent.RoomMetadataChanged);
 1405                    break;
 1406
 1407                case RoomEvent.MessageOneofCase.ParticipantMetadataChanged:
 1408                    HandleParticipantMetadataChanged(roomEvent.ParticipantMetadataChanged);
 1409                    break;
 1410
 1411                case RoomEvent.MessageOneofCase.ParticipantNameChanged:
 1412                    HandleParticipantNameChanged(roomEvent.ParticipantNameChanged);
 1413                    break;
 1414
 1415                case RoomEvent.MessageOneofCase.ParticipantAttributesChanged:
 1416                    HandleParticipantAttributesChanged(roomEvent.ParticipantAttributesChanged);
 1417                    break;
 1418
 1419                case RoomEvent.MessageOneofCase.ParticipantEncryptionStatusChanged:
 1420                    HandleParticipantEncryptionStatusChanged(
 1421                        roomEvent.ParticipantEncryptionStatusChanged
 1422                    );
 1423                    break;
 1424
 1425                case RoomEvent.MessageOneofCase.TrackSubscriptionFailed:
 1426                    HandleTrackSubscriptionFailed(roomEvent.TrackSubscriptionFailed);
 1427                    break;
 1428
 1429                case RoomEvent.MessageOneofCase.RoomUpdated:
 1430                    HandleRoomUpdated(roomEvent.RoomUpdated);
 1431                    break;
 1432
 1433                case RoomEvent.MessageOneofCase.RoomSidChanged:
 1434                    HandleRoomSidChanged(roomEvent.RoomSidChanged);
 1435                    break;
 1436
 1437                case RoomEvent.MessageOneofCase.Moved:
 1438                    HandleMoved(roomEvent.Moved);
 1439                    break;
 1440
 1441                case RoomEvent.MessageOneofCase.ChatMessage:
 1442                    HandleChatMessage(roomEvent.ChatMessage);
 1443                    break;
 1444
 1445                case RoomEvent.MessageOneofCase.E2EeStateChanged:
 1446                    HandleE2EEStateChanged(roomEvent.E2EeStateChanged);
 1447                    break;
 1448
 1449                case RoomEvent.MessageOneofCase.TranscriptionReceived:
 1450                    HandleTranscriptionReceived(roomEvent.TranscriptionReceived);
 1451                    break;
 1452
 1453                case RoomEvent.MessageOneofCase.TokenRefreshed:
 1454                    HandleTokenRefreshed(roomEvent.TokenRefreshed);
 1455                    break;
 1456
 1457                case RoomEvent.MessageOneofCase.StreamHeaderReceived:
 1458                case RoomEvent.MessageOneofCase.StreamChunkReceived:
 1459                case RoomEvent.MessageOneofCase.StreamTrailerReceived:
 1460                    // The raw packets of a data stream, kept by the FFI for backward compatibility:
 1461                    // they carry the compressed content of a compressed stream and nothing of one
 1462                    // inlined in its header. The SDK reads the streams through the native readers
 1463                    // of TextStreamOpened and ByteStreamOpened, like the Node and Python SDKs.
 1464                    break;
 1465
 1466                case RoomEvent.MessageOneofCase.ParticipantPermissionChanged:
 1467                    HandleParticipantPermissionChanged(roomEvent.ParticipantPermissionChanged);
 1468                    break;
 1469
 1470                case RoomEvent.MessageOneofCase.ParticipantActive:
 1471                    HandleParticipantActive(roomEvent.ParticipantActive);
 1472                    break;
 1473
 1474                case RoomEvent.MessageOneofCase.ParticipantsUpdated:
 1475                    HandleParticipantsUpdated(roomEvent.ParticipantsUpdated);
 1476                    break;
 1477
 1478                case RoomEvent.MessageOneofCase.LocalTrackRepublished:
 1479                    HandleLocalTrackRepublished(roomEvent.LocalTrackRepublished);
 1480                    break;
 1481
 1482                case RoomEvent.MessageOneofCase.DataTrackPublished:
 1483                    HandleDataTrackPublished(roomEvent.DataTrackPublished);
 1484                    break;
 1485
 1486                case RoomEvent.MessageOneofCase.DataTrackUnpublished:
 1487                    HandleDataTrackUnpublished(roomEvent.DataTrackUnpublished);
 1488                    break;
 1489
 1490                case RoomEvent.MessageOneofCase.DataChannelLowThresholdChanged:
 1491                    HandleDataChannelLowThresholdChanged(roomEvent.DataChannelLowThresholdChanged);
 1492                    break;
 1493
 1494                case RoomEvent.MessageOneofCase.TextStreamOpened:
 1495                    HandleTextStreamOpened(roomEvent.TextStreamOpened);
 1496                    break;
 1497
 1498                case RoomEvent.MessageOneofCase.ByteStreamOpened:
 1499                    HandleByteStreamOpened(roomEvent.ByteStreamOpened);
 1500                    break;
 1501
 1502                case RoomEvent.MessageOneofCase.Eos:
 1503                    // End of this connection's event stream before or during its cleanup (the
 1504                    // disconnect callback that DisconnectAsync waits for can come after it);
 1505                    // DrainEndedConnection handles the one of a connection already cleaned up
 1506                    EndOfStreamBeforeCleanup(roomEvent.RoomHandle);
 1507                    break;
 1508
 1509                case RoomEvent.MessageOneofCase.Disconnected:
 1510                    CleanupOnDisconnect(
 1511                        roomEvent.Disconnected?.Reason ?? Proto.DisconnectReason.UnknownReason
 1512                    );
 1513                    break;
 1514
 1515                case RoomEvent.MessageOneofCase.Reconnecting:
 1516                    UpdateConnectionState(Proto.ConnectionState.ConnReconnecting);
 1517                    DispatchEvent(() => Raise(Reconnecting, nameof(Reconnecting)));
 1518                    break;
 1519
 1520                case RoomEvent.MessageOneofCase.Reconnected:
 1521                    UpdateConnectionState(Proto.ConnectionState.ConnConnected);
 1522                    DispatchEvent(() => Raise(Reconnected, nameof(Reconnected)));
 1523                    break;
 1524            }
 1525        }
 1526
 1527        private void HandleParticipantConnected(Proto.ParticipantConnected evt)
 1528        {
 1529            if (evt?.Info?.Info == null)
 1530            {
 1531                FfiHandle.FromId(evt?.Info?.Handle?.Id ?? 0).Dispose();
 1532                return;
 1533            }
 1534
 1535            var participant = new RemoteParticipant(
 1536                FfiHandle.FromId(evt.Info.Handle?.Id ?? 0),
 1537                evt.Info.Info,
 1538                this
 1539            );
 1540
 1541            lock (_lock)
 1542            {
 1543                _remoteParticipants[participant.Identity] = participant;
 1544                _departedParticipants.Remove(participant.Identity);
 1545            }
 1546
 1547            DispatchEvent(() =>
 1548                Raise(ParticipantConnected, participant, nameof(ParticipantConnected))
 1549            );
 1550        }
 1551
 1552        private void HandleParticipantDisconnected(Proto.ParticipantDisconnected evt)
 1553        {
 1554            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 1555                return;
 1556
 1557            // Its unfinished data streams are not failed here: the native readers end them with an
 1558            // error, in order after the chunks they already received
 1559            RemoteParticipant? participant;
 1560            lock (_lock)
 1561            {
 1562                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 1563                    return;
 1564
 1565                _remoteParticipants.Remove(evt.ParticipantIdentity);
 1566                RememberDeparture(evt.ParticipantIdentity);
 1567            }
 1568
 1569            participant._info.DisconnectReason = evt.DisconnectReason;
 1570
 1571            DispatchEvent(() =>
 1572                Raise(ParticipantDisconnected, participant, nameof(ParticipantDisconnected))
 1573            );
 1574        }
 1575
 1576        // Caller holds _lock
 1577        private void RememberDeparture(string identity)
 1578        {
 1579            var departure = ++_departures;
 1580            _departedParticipants[identity] = departure;
 1581            _departureOrder.Enqueue(new KeyValuePair<string, long>(identity, departure));
 1582            while (_departureOrder.Count > DepartedParticipantsKept)
 1583            {
 1584                var oldest = _departureOrder.Dequeue();
 1585                // Unless the identity left again since
 1586                if (
 1587                    _departedParticipants.TryGetValue(oldest.Key, out var last)
 1588                    && last == oldest.Value
 1589                )
 1590                    _departedParticipants.Remove(oldest.Key);
 1591            }
 1592        }
 1593
 1594        // The remote participant, or null with whether it is one that already left
 1595        private RemoteParticipant? FindRemoteParticipant(string identity, out bool departed)
 1596        {
 1597            lock (_lock)
 1598            {
 1599                if (_remoteParticipants.TryGetValue(identity, out var participant))
 1600                {
 1601                    departed = false;
 1602                    return participant;
 1603                }
 1604                departed = _departedParticipants.ContainsKey(identity);
 1605                return null;
 1606            }
 1607        }
 1608
 1609        private void HandleLocalTrackPublished(Proto.LocalTrackPublished evt)
 1610        {
 1611            if (LocalParticipant == null || string.IsNullOrEmpty(evt?.TrackSid))
 1612                return;
 1613
 1614            var localParticipant = LocalParticipant;
 1615            DispatchEvent(async () =>
 1616            {
 1617                // PublishTrackAsync registers the publication from its own continuation; wait
 1618                // for it instead of polling
 1619                var publication = await localParticipant.WaitForPublicationAsync(
 1620                    evt.TrackSid,
 1621                    TimeSpan.FromSeconds(10)
 1622                );
 1623                if (publication == null)
 1624                {
 1625                    // A publication whose PublishTrackAsync was abandoned is not reported
 1626                    if (!await localParticipant.IsAbandonedPublicationAsync(evt.TrackSid))
 1627                        Console.Error.WriteLine(
 1628                            $"[WARN] RoomEvent.LocalTrackPublished: Publication {evt.TrackSid} not found"
 1629                        );
 1630                    return;
 1631                }
 1632                Raise(
 1633                    LocalTrackPublished,
 1634                    new LocalTrackPublishedEventArgs(publication, localParticipant),
 1635                    nameof(LocalTrackPublished)
 1636                );
 1637            });
 1638        }
 1639
 1640        private void HandleLocalTrackUnpublished(Proto.LocalTrackUnpublished evt)
 1641        {
 1642            if (LocalParticipant == null || string.IsNullOrEmpty(evt?.PublicationSid))
 1643                return;
 1644
 1645            DispatchEvent(async () =>
 1646            {
 1647                try
 1648                {
 1649                    var localParticipant = LocalParticipant;
 1650                    if (localParticipant == null)
 1651                        throw new InvalidOperationException("Local participant not available");
 1652
 1653                    // Retrieve the publication directly from the local participant's unpublished tracks.
 1654                    // Protected by Room.FfiEventLock.
 1655                    LocalTrackPublication? publication;
 1656                    await _ffiEventLock.WaitAsync();
 1657                    try
 1658                    {
 1659                        publication = localParticipant.TakeUnpublishedTrackPublication(
 1660                            evt.PublicationSid
 1661                        );
 1662                    }
 1663                    finally
 1664                    {
 1665                        _ffiEventLock.Release();
 1666                    }
 1667
 1668                    if (publication == null)
 1669                    {
 1670                        // The unpublication of an abandoned publish is its last event
 1671                        if (
 1672                            await localParticipant.IsAbandonedPublicationAsync(
 1673                                evt.PublicationSid,
 1674                                forget: true
 1675                            )
 1676                        )
 1677                            return;
 1678                        throw new InvalidOperationException(
 1679                            $"Publication {evt.PublicationSid} not found"
 1680                        );
 1681                    }
 1682
 1683                    Raise(
 1684                        LocalTrackUnpublished,
 1685                        new LocalTrackPublishedEventArgs(publication, localParticipant),
 1686                        nameof(LocalTrackUnpublished)
 1687                    );
 1688                }
 1689                catch (Exception ex)
 1690                {
 1691                    Console.Error.WriteLine(
 1692                        $"[WARN] RoomEvent.LocalTrackUnpublished: {ex.Message}"
 1693                    );
 1694                }
 1695            });
 1696        }
 1697
 1698        private void HandleLocalTrackSubscribed(Proto.LocalTrackSubscribed evt)
 1699        {
 1700            if (LocalParticipant == null || string.IsNullOrEmpty(evt?.TrackSid))
 1701                return;
 1702
 1703            var localParticipant = LocalParticipant;
 1704            DispatchEvent(async () =>
 1705            {
 1706                var publication = await localParticipant.WaitForPublicationAsync(
 1707                    evt.TrackSid,
 1708                    TimeSpan.FromSeconds(10)
 1709                );
 1710                if (publication == null)
 1711                {
 1712                    if (!await localParticipant.IsAbandonedPublicationAsync(evt.TrackSid))
 1713                        Console.Error.WriteLine(
 1714                            $"[WARN] RoomEvent.LocalTrackSubscribed: Publication {evt.TrackSid} not found"
 1715                        );
 1716                    return;
 1717                }
 1718                publication.ResolveFirstSubscription();
 1719                Raise(
 1720                    LocalTrackSubscribed,
 1721                    new LocalTrackSubscribedEventArgs(publication),
 1722                    nameof(LocalTrackSubscribed)
 1723                );
 1724            });
 1725        }
 1726
 1727        private void HandleTrackPublished(Proto.TrackPublished evt)
 1728        {
 1729            if (string.IsNullOrEmpty(evt?.ParticipantIdentity) || evt.Publication == null)
 1730                return;
 1731
 1732            var participant = FindRemoteParticipant(evt.ParticipantIdentity, out var departed);
 1733            if (participant == null)
 1734            {
 1735                // The event hands over the native publication: release it, as TrackSubscribed does,
 1736                // and report it unless the participant already left
 1737                if (!departed)
 1738                    Console.Error.WriteLine(
 1739                        $"[WARN] RoomEvent.TrackPublished: Participant {evt.ParticipantIdentity} not found"
 1740                    );
 1741                FfiHandle.FromId(evt.Publication.Handle?.Id ?? 0).Dispose();
 1742                return;
 1743            }
 1744
 1745            // Add publication to participant (synchronously, so later events can rely on it)
 1746            participant.AddPublication(evt.Publication);
 1747            var publication =
 1748                participant.GetTrackPublication(evt.Publication.Info?.Sid ?? "")
 1749                as RemoteTrackPublication;
 1750            if (publication == null)
 1751            {
 1752                Console.Error.WriteLine(
 1753                    $"[WARN] RoomEvent.TrackPublished: Publication {evt.Publication.Info?.Sid} not found after AddPublic
 1754                );
 1755                return;
 1756            }
 1757
 1758            DispatchEvent(() =>
 1759                Raise(
 1760                    TrackPublished,
 1761                    new TrackPublishedEventArgs(publication, participant),
 1762                    nameof(TrackPublished)
 1763                )
 1764            );
 1765        }
 1766
 1767        private void HandleTrackUnpublished(Proto.TrackUnpublished evt)
 1768        {
 1769            if (
 1770                string.IsNullOrEmpty(evt?.ParticipantIdentity)
 1771                || string.IsNullOrEmpty(evt.PublicationSid)
 1772            )
 1773                return;
 1774
 1775            RemoteParticipant? participant;
 1776            lock (_lock)
 1777            {
 1778                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 1779                    return;
 1780            }
 1781
 1782            var publication =
 1783                participant.GetTrackPublication(evt.PublicationSid) as RemoteTrackPublication;
 1784            if (publication != null)
 1785            {
 1786                // A track subscribed while it was being unpublished: the Rust SDK's unpublication
 1787                // found no track to unsubscribe, so the FFI sends no TrackUnsubscribed, and its
 1788                // TrackSubscribed is delivered before or after this event (see RemoteParticipant).
 1789                // The room ends that subscription here, as the unpublication of a subscribed track
 1790                // does, or marks the late TrackSubscribed as stale.
 1791                var track = publication.Track;
 1792                if (track != null)
 1793                {
 1794                    publication.Track = null;
 1795                    DispatchEvent(() =>
 1796                        Raise(
 1797                            TrackUnsubscribed,
 1798                            new TrackSubscribedEventArgs(track, publication, participant),
 1799                            nameof(TrackUnsubscribed)
 1800                        )
 1801                    );
 1802                }
 1803                else
 1804                {
 1805                    participant.MarkUnsubscribedBeforeSubscribed(evt.PublicationSid);
 1806                }
 1807                DispatchEvent(() =>
 1808                    Raise(
 1809                        TrackUnpublished,
 1810                        new TrackPublishedEventArgs(publication, participant),
 1811                        nameof(TrackUnpublished)
 1812                    )
 1813                );
 1814                participant.RemovePublication(evt.PublicationSid);
 1815            }
 1816        }
 1817
 1818        private void HandleTrackSubscribed(Proto.TrackSubscribed evt)
 1819        {
 1820            if (evt == null)
 1821                return;
 1822
 1823            // The event hands over the native track. Every path that does not keep it releases it
 1824            // and says why: a silent return leaked the track, and hid the cause of the
 1825            // "TrackUnsubscribed: ... is not subscribed" warning that follows the dropped event.
 1826            void Release() => FfiHandle.FromId(evt.Track?.Handle?.Id ?? 0).Dispose();
 1827            void Drop(string reason)
 1828            {
 1829                Console.Error.WriteLine($"[WARN] RoomEvent.TrackSubscribed: {reason}");
 1830                Release();
 1831            }
 1832
 1833            if (string.IsNullOrEmpty(evt.ParticipantIdentity) || evt.Track == null)
 1834            {
 1835                Drop("Event without a participant identity or a track");
 1836                return;
 1837            }
 1838
 1839            var participant = FindRemoteParticipant(evt.ParticipantIdentity, out var departed);
 1840            if (participant == null)
 1841            {
 1842                // A subscription that completed after its participant left is over already
 1843                if (departed)
 1844                    Release();
 1845                else
 1846                    Drop($"Participant {evt.ParticipantIdentity} not found");
 1847                return;
 1848            }
 1849
 1850            var trackInfo = evt.Track.Info;
 1851            if (trackInfo == null)
 1852            {
 1853                Drop($"Track of participant {evt.ParticipantIdentity} has no info");
 1854                return;
 1855            }
 1856
 1857            // Its unsubscription or its unpublication was delivered first (see RemoteParticipant):
 1858            // the subscription is over already, so neither half is raised
 1859            if (participant.TakeUnsubscribedBeforeSubscribed(trackInfo.Sid ?? ""))
 1860            {
 1861                Release();
 1862                return;
 1863            }
 1864
 1865            // The participant and the publication are resolved here, on the callback thread:
 1866            // a ParticipantDisconnected that follows would remove them before the chain runs
 1867            var publication =
 1868                participant.GetTrackPublication(trackInfo.Sid ?? "") as RemoteTrackPublication;
 1869            if (publication == null)
 1870            {
 1871                Drop(
 1872                    $"Publication {trackInfo.Sid} not found for participant {evt.ParticipantIdentity}"
 1873                );
 1874                return;
 1875            }
 1876
 1877            // The handle is wrapped only for a track that keeps it, so Drop never wraps it twice
 1878            var handleId = evt.Track.Handle?.Id ?? 0;
 1879            RemoteTrack? track = trackInfo.Kind switch
 1880            {
 1881                Proto.TrackKind.KindAudio => new RemoteAudioTrack(
 1882                    FfiHandle.FromId(handleId),
 1883                    evt.Track
 1884                ),
 1885                Proto.TrackKind.KindVideo => new RemoteVideoTrack(
 1886                    FfiHandle.FromId(handleId),
 1887                    evt.Track
 1888                ),
 1889                _ => null,
 1890            };
 1891            if (track == null)
 1892            {
 1893                Drop(
 1894                    $"Track {trackInfo.Sid} of participant {evt.ParticipantIdentity} has the unsupported kind {trackInfo
 1895                );
 1896                return;
 1897            }
 1898
 1899            publication.Track = track;
 1900            DispatchEvent(() =>
 1901                Raise(
 1902                    TrackSubscribed,
 1903                    new TrackSubscribedEventArgs(track, publication, participant),
 1904                    nameof(TrackSubscribed)
 1905                )
 1906            );
 1907        }
 1908
 1909        private void HandleTrackUnsubscribed(Proto.TrackUnsubscribed evt)
 1910        {
 1911            if (
 1912                string.IsNullOrEmpty(evt?.ParticipantIdentity) || string.IsNullOrEmpty(evt.TrackSid)
 1913            )
 1914                return;
 1915
 1916            var participant = FindRemoteParticipant(evt.ParticipantIdentity, out var departed);
 1917            if (participant == null)
 1918            {
 1919                if (!departed)
 1920                    Console.Error.WriteLine(
 1921                        $"[WARN] RoomEvent.TrackUnsubscribed: Participant {evt.ParticipantIdentity} not found"
 1922                    );
 1923                return;
 1924            }
 1925
 1926            var publication =
 1927                participant.GetTrackPublication(evt.TrackSid) as RemoteTrackPublication;
 1928            var track = publication?.Track;
 1929            if (publication == null || track == null)
 1930            {
 1931                // The unsubscription of a subscription not delivered yet, or a second one: the
 1932                // TrackSubscribed that follows, if any, is stale
 1933                participant.MarkUnsubscribedBeforeSubscribed(evt.TrackSid);
 1934                return;
 1935            }
 1936
 1937            publication.Track = null;
 1938            DispatchEvent(() =>
 1939                Raise(
 1940                    TrackUnsubscribed,
 1941                    new TrackSubscribedEventArgs(track, publication, participant),
 1942                    nameof(TrackUnsubscribed)
 1943                )
 1944            );
 1945        }
 1946
 1947        private void HandleTrackMuted(Proto.TrackMuted evt)
 1948        {
 1949            HandleTrackMuteChanged(evt?.ParticipantIdentity, evt?.TrackSid, muted: true);
 1950        }
 1951
 1952        private void HandleTrackUnmuted(Proto.TrackUnmuted evt)
 1953        {
 1954            HandleTrackMuteChanged(evt?.ParticipantIdentity, evt?.TrackSid, muted: false);
 1955        }
 1956
 1957        private void HandleTrackMuteChanged(
 1958            string? participantIdentity,
 1959            string? trackSid,
 1960            bool muted
 1961        )
 1962        {
 1963            var eventName = muted ? "TrackMuted" : "TrackUnmuted";
 1964            if (string.IsNullOrEmpty(participantIdentity) || string.IsNullOrEmpty(trackSid))
 1965                return;
 1966
 1967            var participant = GetParticipantByIdentity(participantIdentity);
 1968            if (participant == null)
 1969            {
 1970                FindRemoteParticipant(participantIdentity, out var departed);
 1971                if (!departed)
 1972                    Console.Error.WriteLine(
 1973                        $"[WARN] RoomEvent.{eventName}: Participant {participantIdentity} not found"
 1974                    );
 1975                return;
 1976            }
 1977
 1978            DispatchEvent(async () =>
 1979            {
 1980                var publication = participant.GetTrackPublication(trackSid);
 1981                if (publication == null && participant is LocalParticipant localParticipant)
 1982                {
 1983                    // PublishTrackAsync may not have registered the publication yet
 1984                    publication = await localParticipant.WaitForPublicationAsync(
 1985                        trackSid,
 1986                        TimeSpan.FromSeconds(10)
 1987                    );
 1988                }
 1989                if (publication == null)
 1990                {
 1991                    Console.Error.WriteLine(
 1992                        $"[WARN] RoomEvent.{eventName}: Publication {trackSid} not found for participant {participantIde
 1993                    );
 1994                    return;
 1995                }
 1996
 1997                var updatedInfo = publication.Info;
 1998                updatedInfo.Muted = muted;
 1999                publication.UpdateInfo(updatedInfo);
 2000
 2001                var args = new TrackMutedEventArgs(publication, participant);
 2002                if (muted)
 2003                    Raise(TrackMuted, args, nameof(TrackMuted));
 2004                else
 2005                    Raise(TrackUnmuted, args, nameof(TrackUnmuted));
 2006            });
 2007        }
 2008
 2009        private void HandleActiveSpeakersChanged(Proto.ActiveSpeakersChanged evt)
 2010        {
 2011            if (evt?.ParticipantIdentities == null)
 2012                return;
 2013
 2014            var speakers = new List<Participant>();
 2015            foreach (var identity in evt.ParticipantIdentities)
 2016            {
 2017                var participant = GetParticipantByIdentity(identity ?? "");
 2018                if (participant != null)
 2019                {
 2020                    speakers.Add(participant);
 2021                }
 2022            }
 2023
 2024            DispatchEvent(() =>
 2025                Raise(
 2026                    ActiveSpeakersChanged,
 2027                    new ActiveSpeakersChangedEventArgs(speakers),
 2028                    nameof(ActiveSpeakersChanged)
 2029                )
 2030            );
 2031        }
 2032
 2033        private void HandleConnectionQualityChanged(Proto.ConnectionQualityChanged evt)
 2034        {
 2035            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2036                return;
 2037
 2038            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2039            if (participant == null)
 2040                return;
 2041
 2042            var quality = evt.Quality;
 2043            DispatchEvent(() =>
 2044                Raise(
 2045                    ConnectionQualityChanged,
 2046                    new ConnectionQualityChangedEventArgs(quality, participant),
 2047                    nameof(ConnectionQualityChanged)
 2048                )
 2049            );
 2050        }
 2051
 2052        private void HandleDataPacketReceived(Proto.DataPacketReceived evt)
 2053        {
 2054            if (evt == null)
 2055                return;
 2056
 2057            var participant = GetParticipantByIdentity(evt.ParticipantIdentity ?? "");
 2058            var kind = evt.Kind;
 2059            byte[] data = Array.Empty<byte>();
 2060            string topic = string.Empty;
 2061
 2062            if (evt.ValueCase == Proto.DataPacketReceived.ValueOneofCase.User && evt.User != null)
 2063            {
 2064                topic = evt.User.Topic ?? string.Empty;
 2065
 2066                // Copy data from native memory (block copy: this is the FFI callback thread)
 2067                var bufferInfo = evt.User.Data?.Data;
 2068                if (bufferInfo != null && bufferInfo.DataLen > 0)
 2069                {
 2070                    data = new byte[bufferInfo.DataLen];
 2071                    Marshal.Copy((IntPtr)bufferInfo.DataPtr, data, 0, (int)bufferInfo.DataLen);
 2072                }
 2073
 2074                // Release the native buffer whether or not it had data
 2075                if (evt.User.Data?.Handle != null)
 2076                {
 2077                    FfiHandle.FromId(evt.User.Data.Handle.Id).Dispose();
 2078                }
 2079
 2080                DispatchEvent(() =>
 2081                    Raise(
 2082                        DataReceived,
 2083                        new DataReceivedEventArgs(data, participant, kind, topic),
 2084                        nameof(DataReceived)
 2085                    )
 2086                );
 2087            }
 2088            else if (
 2089                evt.ValueCase == Proto.DataPacketReceived.ValueOneofCase.SipDtmf
 2090                && evt.SipDtmf != null
 2091            )
 2092            {
 2093                // Handle SIP DTMF
 2094                if (participant is RemoteParticipant remoteParticipant)
 2095                {
 2096                    DispatchEvent(() =>
 2097                        Raise(
 2098                            SipDtmfReceived,
 2099                            new SipDtmfReceivedEventArgs(
 2100                                evt.SipDtmf.Code,
 2101                                evt.SipDtmf.Digit,
 2102                                remoteParticipant
 2103                            ),
 2104                            nameof(SipDtmfReceived)
 2105                        )
 2106                    );
 2107                }
 2108            }
 2109        }
 2110
 2111        private void HandleRoomMetadataChanged(Proto.RoomMetadataChanged evt)
 2112        {
 2113            if (evt == null)
 2114                return;
 2115
 2116            Metadata = evt.Metadata ?? string.Empty;
 2117            DispatchEvent(() => Raise(RoomMetadataChanged, Metadata, nameof(RoomMetadataChanged)));
 2118        }
 2119
 2120        private void HandleParticipantMetadataChanged(Proto.ParticipantMetadataChanged evt)
 2121        {
 2122            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2123                return;
 2124
 2125            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2126            if (participant != null)
 2127            {
 2128                var updatedInfo = participant._info;
 2129                updatedInfo.Metadata = evt.Metadata ?? string.Empty;
 2130                participant.UpdateInfo(updatedInfo);
 2131
 2132                DispatchEvent(() =>
 2133                    Raise(
 2134                        ParticipantMetadataChanged,
 2135                        participant,
 2136                        nameof(ParticipantMetadataChanged)
 2137                    )
 2138                );
 2139            }
 2140        }
 2141
 2142        private void HandleParticipantNameChanged(Proto.ParticipantNameChanged evt)
 2143        {
 2144            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2145                return;
 2146
 2147            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2148            if (participant != null)
 2149            {
 2150                var updatedInfo = participant._info;
 2151                updatedInfo.Name = evt.Name ?? string.Empty;
 2152                participant.UpdateInfo(updatedInfo);
 2153
 2154                DispatchEvent(() =>
 2155                    Raise(ParticipantNameChanged, participant, nameof(ParticipantNameChanged))
 2156                );
 2157            }
 2158        }
 2159
 2160        private void HandleParticipantAttributesChanged(Proto.ParticipantAttributesChanged evt)
 2161        {
 2162            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2163                return;
 2164
 2165            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2166            if (participant != null)
 2167            {
 2168                var attributes = new Dictionary<string, string>();
 2169                foreach (var attr in evt.Attributes)
 2170                {
 2171                    attributes[attr.Key] = attr.Value;
 2172                }
 2173
 2174                // Keep Participant.Attributes current, like the Node and Python SDKs
 2175                participant._info.Attributes.Clear();
 2176                participant._info.Attributes.Add(attributes);
 2177
 2178                var changedAttributes = new Dictionary<string, string>();
 2179                foreach (var attr in evt.ChangedAttributes)
 2180                {
 2181                    changedAttributes[attr.Key] = attr.Value;
 2182                }
 2183
 2184                DispatchEvent(() =>
 2185                    Raise(
 2186                        ParticipantAttributesChanged,
 2187                        new ParticipantAttributesChangedEventArgs(
 2188                            participant,
 2189                            attributes,
 2190                            changedAttributes
 2191                        ),
 2192                        nameof(ParticipantAttributesChanged)
 2193                    )
 2194                );
 2195            }
 2196        }
 2197
 2198        private void HandleParticipantEncryptionStatusChanged(
 2199            Proto.ParticipantEncryptionStatusChanged evt
 2200        )
 2201        {
 2202            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2203                return;
 2204
 2205            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2206            if (participant != null)
 2207            {
 2208                DispatchEvent(() =>
 2209                    Raise(
 2210                        ParticipantEncryptionStatusChanged,
 2211                        new ParticipantEncryptionStatusChangedEventArgs(
 2212                            participant,
 2213                            evt.IsEncrypted
 2214                        ),
 2215                        nameof(ParticipantEncryptionStatusChanged)
 2216                    )
 2217                );
 2218            }
 2219        }
 2220
 2221        private void HandleTrackSubscriptionFailed(Proto.TrackSubscriptionFailed evt)
 2222        {
 2223            if (
 2224                string.IsNullOrEmpty(evt?.ParticipantIdentity) || string.IsNullOrEmpty(evt.TrackSid)
 2225            )
 2226                return;
 2227
 2228            RemoteParticipant? participant;
 2229            lock (_lock)
 2230            {
 2231                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 2232                    return;
 2233            }
 2234
 2235            DispatchEvent(() =>
 2236                Raise(
 2237                    TrackSubscriptionFailed,
 2238                    new TrackSubscriptionFailedEventArgs(evt.TrackSid, participant, evt.Error),
 2239                    nameof(TrackSubscriptionFailed)
 2240                )
 2241            );
 2242        }
 2243
 2244        private void HandleRoomUpdated(Proto.RoomInfo evt)
 2245        {
 2246            if (evt == null)
 2247                return;
 2248
 2249            UpdateFromInfo(evt);
 2250            DispatchEvent(() => Raise(RoomUpdated, evt, nameof(RoomUpdated)));
 2251        }
 2252
 2253        private void HandleRoomSidChanged(Proto.RoomSidChanged evt)
 2254        {
 2255            if (string.IsNullOrEmpty(evt?.Sid))
 2256                return;
 2257
 2258            Sid = evt.Sid;
 2259            DispatchEvent(() => Raise(RoomSidChanged, evt.Sid, nameof(RoomSidChanged)));
 2260        }
 2261
 2262        private void HandleMoved(Proto.RoomInfo evt)
 2263        {
 2264            if (evt == null)
 2265                return;
 2266
 2267            UpdateFromInfo(evt);
 2268            DispatchEvent(() => Raise(Moved, evt, nameof(Moved)));
 2269        }
 2270
 2271        private void HandleChatMessage(Proto.ChatMessageReceived evt)
 2272        {
 2273            if (evt?.Message == null)
 2274                return;
 2275
 2276            var participant = GetParticipantByIdentity(evt.ParticipantIdentity ?? "");
 2277
 2278            DispatchEvent(() =>
 2279                Raise(
 2280                    ChatMessageReceived,
 2281                    new ChatMessageReceivedEventArgs(evt.Message, participant),
 2282                    nameof(ChatMessageReceived)
 2283                )
 2284            );
 2285        }
 2286
 2287        private void HandleE2EEStateChanged(Proto.E2eeStateChanged evt)
 2288        {
 2289            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2290                return;
 2291
 2292            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2293            if (participant != null)
 2294            {
 2295                DispatchEvent(() =>
 2296                    Raise(
 2297                        E2EEStateChanged,
 2298                        new E2EEStateChangedEventArgs(participant, evt.State),
 2299                        nameof(E2EEStateChanged)
 2300                    )
 2301                );
 2302            }
 2303        }
 2304
 2305        private void HandleTranscriptionReceived(Proto.TranscriptionReceived evt)
 2306        {
 2307            if (evt == null)
 2308                return;
 2309
 2310            var participant = GetParticipantByIdentity(evt.ParticipantIdentity ?? "");
 2311            var segments = new List<Proto.TranscriptionSegment>(evt.Segments);
 2312
 2313            DispatchEvent(() =>
 2314                Raise(
 2315                    TranscriptionReceived,
 2316                    new TranscriptionReceivedEventArgs(participant, evt.TrackSid, segments),
 2317                    nameof(TranscriptionReceived)
 2318                )
 2319            );
 2320        }
 2321
 2322        private void HandleTokenRefreshed(Proto.TokenRefreshed evt)
 2323        {
 2324            if (string.IsNullOrEmpty(evt?.Token))
 2325                return;
 2326
 2327            DispatchEvent(() => Raise(TokenRefreshed, evt.Token, nameof(TokenRefreshed)));
 2328        }
 2329
 2330        private Participant? GetParticipantByIdentity(string identity)
 2331        {
 2332            if (string.IsNullOrEmpty(identity))
 2333                return null;
 2334
 2335            // Check if it's the local participant
 2336            if (LocalParticipant?.Identity == identity)
 2337                return LocalParticipant;
 2338
 2339            // Check remote participants
 2340            lock (_lock)
 2341            {
 2342                return _remoteParticipants.TryGetValue(identity, out var participant)
 2343                    ? participant
 2344                    : null;
 2345            }
 2346        }
 2347
 2348        // The native reader of a stream decompresses it, delivers the content inlined in the header
 2349        // of a short one and enforces RoomOptions.DataStream; without a handler for its topic it is
 2350        // dropped at once, like in the Node SDK
 2351        private void HandleTextStreamOpened(Proto.TextStreamOpened evt)
 2352        {
 2353            var nativeReader = FfiHandle.FromId(evt.Reader.Handle.Id);
 2354            var info = evt.Reader.Info;
 2355            if (!_streamHandlers.TryGetTextStreamHandler(info.Topic, out var handler))
 2356            {
 2357                nativeReader.Dispose();
 2358                return;
 2359            }
 2360
 2361            var reader = new TextStreamReader(
 2362                info,
 2363                evt.ParticipantIdentity,
 2364                ended =>
 2365                {
 2366                    lock (_lock)
 2367                    {
 2368                        if (
 2369                            _textStreamReaders.TryGetValue(ended.Info.StreamId, out var current)
 2370                            && current == ended
 2371                        )
 2372                            _textStreamReaders.Remove(ended.Info.StreamId);
 2373                    }
 2374                }
 2375            );
 2376            lock (_lock)
 2377            {
 2378                _textStreamReaders[info.StreamId] = reader;
 2379            }
 2380            RunStreamHandler(() =>
 2381            {
 2382                try
 2383                {
 2384                    reader.Start(nativeReader);
 2385                }
 2386                catch (Exception ex)
 2387                {
 2388                    reader.Fail(
 2389                        new StreamException($"Could not read the stream: {ex.Message}", ex)
 2390                    );
 2391                }
 2392                handler(reader, evt.ParticipantIdentity);
 2393            });
 2394        }
 2395
 2396        private void HandleByteStreamOpened(Proto.ByteStreamOpened evt)
 2397        {
 2398            var nativeReader = FfiHandle.FromId(evt.Reader.Handle.Id);
 2399            var info = evt.Reader.Info;
 2400            if (!_streamHandlers.TryGetByteStreamHandler(info.Topic, out var handler))
 2401            {
 2402                nativeReader.Dispose();
 2403                return;
 2404            }
 2405
 2406            var reader = new ByteStreamReader(
 2407                info,
 2408                evt.ParticipantIdentity,
 2409                ended =>
 2410                {
 2411                    lock (_lock)
 2412                    {
 2413                        if (
 2414                            _byteStreamReaders.TryGetValue(ended.Info.StreamId, out var current)
 2415                            && current == ended
 2416                        )
 2417                            _byteStreamReaders.Remove(ended.Info.StreamId);
 2418                    }
 2419                }
 2420            );
 2421            lock (_lock)
 2422            {
 2423                _byteStreamReaders[info.StreamId] = reader;
 2424            }
 2425            RunStreamHandler(() =>
 2426            {
 2427                try
 2428                {
 2429                    reader.Start(nativeReader);
 2430                }
 2431                catch (Exception ex)
 2432                {
 2433                    reader.Fail(
 2434                        new StreamException($"Could not read the stream: {ex.Message}", ex)
 2435                    );
 2436                }
 2437                handler(reader, evt.ParticipantIdentity);
 2438            });
 2439        }
 2440
 2441        // The read starts and the handler runs on the thread pool (like RPC invocations), never on
 2442        // the FFI callback thread that delivers the chunks: a handler that blocks on ReadAllAsync
 2443        // would otherwise deadlock and stall every FFI event in the process
 2444        private static void RunStreamHandler(Action dispatch)
 2445        {
 2446            _ = Task.Run(() =>
 2447            {
 2448                try
 2449                {
 2450                    dispatch();
 2451                }
 2452                catch (Exception ex)
 2453                {
 2454                    Console.Error.WriteLine($"[ERROR] Data stream handler exception: {ex}");
 2455                }
 2456            });
 2457        }
 2458
 2459        private void HandleParticipantPermissionChanged(Proto.ParticipantPermissionChanged evt)
 2460        {
 2461            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2462                return;
 2463
 2464            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 2465            if (participant == null)
 2466                return;
 2467
 2468            var permissions = evt.Permission;
 2469            participant._info.Permission = permissions;
 2470            DispatchEvent(() =>
 2471                Raise(
 2472                    ParticipantPermissionsChanged,
 2473                    new ParticipantPermissionsChangedEventArgs(participant, permissions),
 2474                    nameof(ParticipantPermissionsChanged)
 2475                )
 2476            );
 2477        }
 2478
 2479        private void HandleParticipantActive(Proto.ParticipantActive evt)
 2480        {
 2481            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 2482                return;
 2483
 2484            RemoteParticipant? participant;
 2485            lock (_lock)
 2486            {
 2487                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 2488                    return;
 2489            }
 2490
 2491            participant._info.State = Proto.ParticipantState.Active;
 2492            DispatchEvent(() => Raise(ParticipantActive, participant, nameof(ParticipantActive)));
 2493        }
 2494
 2495        private void HandleParticipantsUpdated(Proto.ParticipantsUpdated evt)
 2496        {
 2497            if (evt == null)
 2498                return;
 2499
 2500            // Bulk refresh of participant infos; no public event, like the Node and Python SDKs
 2501            foreach (var info in evt.Participants)
 2502            {
 2503                if (info == null)
 2504                    continue;
 2505                GetParticipantByIdentity(info.Identity)?.UpdateInfo(info);
 2506            }
 2507        }
 2508
 2509        private void HandleLocalTrackRepublished(Proto.LocalTrackRepublished evt)
 2510        {
 2511            if (
 2512                LocalParticipant == null
 2513                || string.IsNullOrEmpty(evt?.PreviousSid)
 2514                || evt.Info == null
 2515            )
 2516                return;
 2517
 2518            DispatchEvent(async () =>
 2519            {
 2520                var localParticipant = LocalParticipant;
 2521                if (localParticipant == null)
 2522                    return;
 2523
 2524                // Protected by Room.FfiEventLock, like the unpublish bookkeeping.
 2525                LocalTrackPublication? publication;
 2526                await _ffiEventLock.WaitAsync();
 2527                try
 2528                {
 2529                    publication = localParticipant.RepublishTrackPublication(
 2530                        evt.PreviousSid,
 2531                        evt.Info
 2532                    );
 2533                }
 2534                finally
 2535                {
 2536                    _ffiEventLock.Release();
 2537                }
 2538
 2539                if (publication == null)
 2540                {
 2541                    Console.Error.WriteLine(
 2542                        $"[WARN] RoomEvent.LocalTrackRepublished: previous publication not found: {evt.PreviousSid}"
 2543                    );
 2544                    return;
 2545                }
 2546
 2547                Raise(
 2548                    LocalTrackRepublished,
 2549                    new LocalTrackRepublishedEventArgs(
 2550                        publication,
 2551                        evt.PreviousSid,
 2552                        localParticipant
 2553                    ),
 2554                    nameof(LocalTrackRepublished)
 2555                );
 2556            });
 2557        }
 2558
 2559        private void HandleDataTrackPublished(Proto.DataTrackPublished evt)
 2560        {
 2561            if (evt?.Track?.Handle == null || evt.Track.Info == null)
 2562                return;
 2563
 2564            var track = new RemoteDataTrack(evt.Track);
 2565            lock (_lock)
 2566            {
 2567                _remoteDataTracks[track.Info.Sid] = track;
 2568            }
 2569
 2570            DispatchEvent(() => Raise(DataTrackPublished, track, nameof(DataTrackPublished)));
 2571        }
 2572
 2573        private void HandleDataTrackUnpublished(Proto.DataTrackUnpublished evt)
 2574        {
 2575            if (string.IsNullOrEmpty(evt?.Sid))
 2576                return;
 2577
 2578            RemoteDataTrack? track;
 2579            lock (_lock)
 2580            {
 2581                _remoteDataTracks.Remove(evt.Sid, out track);
 2582            }
 2583
 2584            DispatchEvent(() =>
 2585                Raise(
 2586                    DataTrackUnpublished,
 2587                    new DataTrackUnpublishedEventArgs(evt.Sid, track),
 2588                    nameof(DataTrackUnpublished)
 2589                )
 2590            );
 2591        }
 2592
 2593        private void HandleDataChannelLowThresholdChanged(
 2594            Proto.DataChannelBufferedAmountLowThresholdChanged evt
 2595        )
 2596        {
 2597            if (evt == null)
 2598                return;
 2599
 2600            DispatchEvent(() =>
 2601                Raise(
 2602                    DataChannelBufferedAmountLowThresholdChanged,
 2603                    new DataChannelBufferedAmountLowThresholdChangedEventArgs(
 2604                        evt.Kind,
 2605                        evt.Threshold
 2606                    ),
 2607                    nameof(DataChannelBufferedAmountLowThresholdChanged)
 2608                )
 2609            );
 2610        }
 2611
 2612        private void CleanupOnDisconnect(Proto.DisconnectReason reason)
 2613        {
 2614            if (Interlocked.Exchange(ref _cleanedUp, 1) == 1)
 2615                return;
 2616
 2617            int generation;
 2618            var drain = false;
 2619            var roomHandle = _roomHandle;
 2620            lock (_connectionLock)
 2621            {
 2622                generation = _connectionGeneration;
 2623                // Registered before the handle is cleared: from here on OnFfiEvent drains the
 2624                // events of this connection instead of applying them, unless none can come
 2625                if (roomHandle != null && !_endedStreams.Remove(roomHandle.HandleId))
 2626                    drain = _endedRoomHandles.Add(roomHandle.HandleId);
 2627            }
 2628
 2629            // From here on IsConnected is false
 2630            _roomHandle = null;
 2631            if (drain)
 2632                StopDrainingAfterTimeout(roomHandle!.HandleId);
 2633
 2634            UpdateConnectionState(Proto.ConnectionState.ConnDisconnected);
 2635            DispatchEvent(() => Raise(Disconnected, reason, nameof(Disconnected)));
 2636
 2637            // Clear the participant state only after the handlers above ran, so a Disconnected
 2638            // handler can still read LocalParticipant and RemoteParticipants
 2639            DispatchEvent(() =>
 2640            {
 2641                List<TextStreamReader> textReaders;
 2642                List<ByteStreamReader> byteReaders;
 2643                lock (_connectionLock)
 2644                {
 2645                    // ConnectAsync was called again meanwhile: that connection already cleared this
 2646                    // state, and the listener and participants are now its own
 2647                    if (generation != _connectionGeneration)
 2648                        return;
 2649
 2650                    ClearConnectionState(out textReaders, out byteReaders);
 2651                }
 2652                FailStreamReaders(textReaders, byteReaders);
 2653                StopListeningIfIdle();
 2654            });
 2655
 2656            roomHandle?.Dispose();
 2657        }
 2658
 2659        // Caller holds _connectionLock
 2660        private void ClearConnectionState(
 2661            out List<TextStreamReader> textReaders,
 2662            out List<ByteStreamReader> byteReaders
 2663        )
 2664        {
 2665            textReaders = new List<TextStreamReader>();
 2666            byteReaders = new List<ByteStreamReader>();
 2667            lock (_lock)
 2668            {
 2669                _remoteParticipants.Clear();
 2670                _departedParticipants.Clear();
 2671                _departureOrder.Clear();
 2672                textReaders.AddRange(_textStreamReaders.Values);
 2673                byteReaders.AddRange(_byteStreamReaders.Values);
 2674                _textStreamReaders.Clear();
 2675                _byteStreamReaders.Clear();
 2676                _remoteDataTracks.Clear();
 2677            }
 2678
 2679            LocalParticipant?.CancelPendingSubscriptionWaits();
 2680            LocalParticipant = null;
 2681        }
 2682
 2683        // Readers waiting for more chunks would otherwise wait forever
 2684        private static void FailStreamReaders(
 2685            List<TextStreamReader> textReaders,
 2686            List<ByteStreamReader> byteReaders
 2687        )
 2688        {
 2689            if (textReaders.Count == 0 && byteReaders.Count == 0)
 2690                return;
 2691            var error = new StreamException("The room disconnected before the stream was closed");
 2692            foreach (var reader in textReaders)
 2693                reader.Fail(error);
 2694            foreach (var reader in byteReaders)
 2695                reader.Fail(error);
 2696        }
 2697
 2698        // An event of a connection that ended, or of another room: the former is released, and its
 2699        // end-of-stream event ends the draining
 2700        private void DrainEndedConnection(RoomEvent roomEvent)
 2701        {
 2702            lock (_connectionLock)
 2703            {
 2704                if (!_endedRoomHandles.Contains(roomEvent.RoomHandle))
 2705                    return; // another room's event
 2706            }
 2707
 2708            ReleaseOwnedHandles(roomEvent);
 2709            if (roomEvent.MessageCase == RoomEvent.MessageOneofCase.Eos)
 2710                StopDraining(roomEvent.RoomHandle);
 2711        }
 2712
 2713        // The native handles a room event hands over, for an event the room does not apply (or, for
 2714        // the stream readers, applies without them). The message of the event's case is set; the
 2715        // owned object inside it is checked, as for an applied event.
 2716        internal static void ReleaseOwnedHandles(RoomEvent roomEvent)
 2717        {
 2718            var handle = roomEvent.MessageCase switch
 2719            {
 2720                RoomEvent.MessageOneofCase.ParticipantConnected => roomEvent
 2721                    .ParticipantConnected
 2722                    .Info
 2723                    ?.Handle,
 2724                RoomEvent.MessageOneofCase.TrackPublished => roomEvent
 2725                    .TrackPublished
 2726                    .Publication
 2727                    ?.Handle,
 2728                RoomEvent.MessageOneofCase.TrackSubscribed => roomEvent
 2729                    .TrackSubscribed
 2730                    .Track
 2731                    ?.Handle,
 2732                RoomEvent.MessageOneofCase.DataPacketReceived => roomEvent
 2733                    .DataPacketReceived
 2734                    .User
 2735                    ?.Data
 2736                    ?.Handle,
 2737                RoomEvent.MessageOneofCase.DataTrackPublished => roomEvent
 2738                    .DataTrackPublished
 2739                    .Track
 2740                    ?.Handle,
 2741                RoomEvent.MessageOneofCase.TextStreamOpened => roomEvent
 2742                    .TextStreamOpened
 2743                    .Reader
 2744                    ?.Handle,
 2745                RoomEvent.MessageOneofCase.ByteStreamOpened => roomEvent
 2746                    .ByteStreamOpened
 2747                    .Reader
 2748                    ?.Handle,
 2749                _ => null,
 2750            };
 2751            if (handle != null && handle.Id != FfiHandle.InvalidHandle)
 2752                FfiHandle.FromId(handle.Id).Dispose();
 2753        }
 2754
 2755        private void EndOfStreamBeforeCleanup(ulong roomHandleId)
 2756        {
 2757            bool draining;
 2758            lock (_connectionLock)
 2759            {
 2760                draining = _endedRoomHandles.Contains(roomHandleId);
 2761                if (!draining)
 2762                    _endedStreams.Add(roomHandleId);
 2763            }
 2764            if (draining)
 2765                StopDraining(roomHandleId);
 2766        }
 2767
 2768        private void StopDraining(ulong roomHandleId)
 2769        {
 2770            lock (_connectionLock)
 2771            {
 2772                if (!_endedRoomHandles.Remove(roomHandleId))
 2773                    return;
 2774            }
 2775            StopListeningIfIdle();
 2776        }
 2777
 2778        // Weak, or the timer would keep an ended room alive for the whole timeout although its
 2779        // end-of-stream event already stopped the draining. A room still draining is reachable
 2780        // anyway: it listens to the process-wide FfiClient.
 2781        private void StopDrainingAfterTimeout(ulong roomHandleId)
 2782        {
 2783            var room = new WeakReference<Room>(this);
 2784            _ = Task.Delay(EndedConnectionDrainTimeout)
 2785                .ContinueWith(
 2786                    _ =>
 2787                    {
 2788                        if (room.TryGetTarget(out var target))
 2789                            target.StopDraining(roomHandleId);
 2790                    },
 2791                    TaskScheduler.Default
 2792                );
 2793        }
 2794
 2795        // Stops listening to the FFI events once no connection is live, starting or draining: a
 2796        // Room that is never disposed must not stay in the process-wide FfiClient forever
 2797        private void StopListeningIfIdle()
 2798        {
 2799            lock (_connectionLock)
 2800            {
 2801                if (
 2802                    _roomHandle == null
 2803                    && Volatile.Read(ref _connecting) == 0
 2804                    && _endedRoomHandles.Count == 0
 2805                )
 2806                    FfiClient.Instance.EventReceived -= OnFfiEvent;
 2807            }
 2808        }
 2809
 2810        // For a ConnectAsync that failed: no connection of its own to wait for
 2811        private void StopListeningUnlessDraining()
 2812        {
 2813            lock (_connectionLock)
 2814            {
 2815                if (_endedRoomHandles.Count == 0)
 2816                    FfiClient.Instance.EventReceived -= OnFfiEvent;
 2817            }
 2818        }
 2819
 2820        /// <summary>
 2821        /// Disconnects from the room if it is still connected, raising the usual teardown events, and
 2822        /// releases the native resources.
 2823        /// </summary>
 2824        public void Dispose()
 2825        {
 2826            if (_disposed)
 2827                return;
 2828            _disposed = true;
 2829
 2830            // Disconnect while still listening, so the teardown events (LocalTrackUnpublished,
 2831            // TrackUnsubscribed, ParticipantDisconnected...) are delivered like DisconnectAsync does
 2832            if (IsConnected)
 2833            {
 2834                try
 2835                {
 2836                    Disconnect();
 2837                }
 2838                catch
 2839                {
 2840                    // Ignore errors during disposal
 2841                }
 2842            }
 2843
 2844            StopListeningIfIdle();
 2845            _roomHandle?.Dispose();
 2846        }
 2847    }
 2848
 2849    /// <summary>
 2850    /// Statistics of the two WebRTC peer connections of the session, returned by
 2851    /// <see cref="Room.GetRtcStatsAsync"/>.
 2852    /// </summary>
 2853    public class RtcStats
 2854    {
 2855        /// <summary>
 2856        /// Statistics of the publishing peer connection, one <see cref="Proto.RtcStats"/> per WebRTC stats report.
 2857        /// </summary>
 2858        public List<Proto.RtcStats> PublisherStats { get; set; } = new List<Proto.RtcStats>();
 2859
 2860        /// <summary>
 2861        /// Statistics of the subscribing peer connection, one <see cref="Proto.RtcStats"/> per WebRTC stats report.
 2862        /// </summary>
 2863        public List<Proto.RtcStats> SubscriberStats { get; set; } = new List<Proto.RtcStats>();
 2864    }
 2865}

Methods/Properties

ToProto()