< Summary

Information
Line coverage
86%
Covered lines: 1397
Uncovered lines: 218
Coverable lines: 1615
Total lines: 2865
Line coverage: 86.5%
Branch coverage
73%
Covered branches: 452
Total branches: 613
Branch coverage: 73.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%11100%
.cctor()100%11100%
get_FfiEventLock()100%11100%
get_E2EEManager()100%11100%
get_IsConnected()100%22100%
get_RemoteParticipants()100%11100%
get_RemoteDataTracks()100%11100%
RegisterTextStreamHandler(...)100%11100%
UnregisterTextStreamHandler(...)100%11100%
RegisterByteStreamHandler(...)100%11100%
UnregisterByteStreamHandler(...)100%11100%
Raise(...)100%44100%
Raise(...)100%4471.42%
DispatchEvent(...)100%1178.94%
DispatchEvent(...)100%1173.91%
UpdateConnectionState(...)100%22100%
ConnectAsync()87.5%8894.44%
ConnectCoreAsync()80%303096%
AbandonConnectAsync()62.5%10868.42%
ReleaseAbandonedConnectionAsync()50%412874.57%
DisconnectAsync()100%66100%
DisconnectCoreAsync()50%2296%
SimulateScenarioAsync()50%101088.46%
GetRtcStatsAsync()70%111082.75%
Disconnect()100%11100%
UpdateFromInfo(...)83.33%6683.33%
OnFfiEvent(...)93.75%171685%
HandleRoomEvent(...)97.87%4747100%
HandleParticipantConnected(...)28.57%151484.21%
HandleParticipantDisconnected(...)66.66%6686.66%
RememberDeparture(...)16.66%13642.85%
FindRemoteParticipant(...)100%22100%
HandleLocalTrackPublished(...)66.66%7675%
HandleLocalTrackUnpublished(...)66.66%7665.45%
HandleLocalTrackSubscribed(...)66.66%7673.07%
HandleTrackPublished(...)40%532056.66%
HandleTrackUnpublished(...)75%121295%
HandleTrackSubscribed(...)67.85%502869.49%
Release()50%44100%
Drop()100%11100%
HandleTrackUnsubscribed(...)87.5%161696.55%
HandleTrackMuted(...)50%44100%
HandleTrackUnmuted(...)50%44100%
HandleTrackMuteChanged(...)60%191055.81%
HandleActiveSpeakersChanged(...)80%101095%
HandleConnectionQualityChanged(...)83.33%6686.66%
HandleDataPacketReceived(...)65.38%262697.95%
HandleRoomMetadataChanged(...)75%4483.33%
HandleParticipantMetadataChanged(...)62.5%8894.44%
HandleParticipantNameChanged(...)62.5%8892.85%
HandleParticipantAttributesChanged(...)80%101096.77%
HandleParticipantEncryptionStatusChanged(...)66.66%6694.44%
HandleTrackSubscriptionFailed(...)75%8894.44%
HandleRoomUpdated(...)100%2283.33%
HandleRoomSidChanged(...)75%4483.33%
HandleMoved(...)100%2283.33%
HandleChatMessage(...)66.66%6691.66%
HandleE2EEStateChanged(...)66.66%6693.33%
HandleTranscriptionReceived(...)75%4492.3%
HandleTokenRefreshed(...)75%4480%
GetParticipantByIdentity(...)62.5%8890.9%
HandleTextStreamOpened(...)83.33%6685.36%
HandleByteStreamOpened(...)83.33%6685.36%
RunStreamHandler(...)100%1169.23%
HandleParticipantPermissionChanged(...)83.33%6687.5%
HandleParticipantActive(...)66.66%6681.81%
HandleParticipantsUpdated(...)87.5%9880%
HandleLocalTrackRepublished(...)62.5%8885.1%
HandleDataTrackPublished(...)62.5%8890%
HandleDataTrackUnpublished(...)75%4493.33%
HandleDataChannelLowThresholdChanged(...)100%2292.85%
CleanupOnDisconnect(...)83.33%121297.05%
ClearConnectionState(...)100%22100%
FailStreamReaders(...)25%19844.44%
DrainEndedConnection(...)75%44100%
ReleaseOwnedHandles(...)97.36%3838100%
EndOfStreamBeforeCleanup(...)75%4490%
StopDraining(...)100%22100%
StopDrainingAfterTimeout(...)100%22100%
StopListeningIfIdle()100%66100%
StopListeningUnlessDraining()100%22100%
Dispose()83.33%6681.25%

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()
 73        {
 74            var proto = new Proto.RoomOptions
 75            {
 76                AutoSubscribe = AutoSubscribe,
 77                Dynacast = Dynacast,
 78                AdaptiveStream = AdaptiveStream,
 79                JoinRetries = JoinRetries,
 80            };
 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.
 84            if (E2EE != null)
 85            {
 86                proto.Encryption = E2EE.ToProto();
 87            }
 88
 89            if (RtcConfig != null)
 90            {
 91                proto.RtcConfig = RtcConfig.ToProto();
 92            }
 93
 94            if (ConnectTimeout.HasValue)
 95            {
 96                var milliseconds = Math.Ceiling(ConnectTimeout.Value.TotalMilliseconds);
 97                if (milliseconds <= 0)
 98                    throw new ArgumentOutOfRangeException(
 99                        nameof(ConnectTimeout),
 100                        ConnectTimeout,
 101                        "The connect timeout must be positive."
 102                    );
 103                proto.ConnectTimeoutMs = (ulong)milliseconds;
 104            }
 105
 106            if (SinglePeerConnection.HasValue)
 107            {
 108                proto.SinglePeerConnection = SinglePeerConnection.Value;
 109            }
 110
 111            if (DataStream != null)
 112            {
 113                proto.DataStream = DataStream.ToProto();
 114            }
 115
 116            return proto;
 117        }
 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;
 445262        private readonly object _lock = new object();
 445263        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.
 445275        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.
 445290        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.
 445294        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
 1297        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;
 445305        private readonly Dictionary<string, long> _departedParticipants =
 445306            new Dictionary<string, long>();
 445307        private readonly Queue<KeyValuePair<string, long>> _departureOrder =
 445308            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
 445313        private Task _eventTaskChain = Task.CompletedTask;
 445314        private readonly object _eventLock = new object();
 315
 316        // Stream handling
 445317        private readonly Dictionary<string, TextStreamReader> _textStreamReaders =
 445318            new Dictionary<string, TextStreamReader>();
 445319        private readonly Dictionary<string, ByteStreamReader> _byteStreamReaders =
 445320            new Dictionary<string, ByteStreamReader>();
 445321        private readonly StreamHandlerRegistry _streamHandlers = new StreamHandlerRegistry();
 322
 323        // Remote data tracks by SID, delivered by DataTrackPublished. Protected by _lock.
 445324        private readonly Dictionary<string, RemoteDataTrack> _remoteDataTracks =
 445325            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>
 1398335        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>
 26380        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 =>
 999397            _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
 2711405            {
 2711406                lock (_lock)
 2711407                {
 2711408                    return new Dictionary<string, RemoteParticipant>(_remoteParticipants);
 409                }
 2711410            }
 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
 2622            {
 2623                lock (_lock)
 2624                {
 2625                    return new Dictionary<string, RemoteDataTrack>(_remoteDataTracks);
 626                }
 2627            }
 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)
 27639        {
 27640            _streamHandlers.RegisterTextStreamHandler(topic, handler);
 26641        }
 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)
 1648        {
 1649            _streamHandlers.UnregisterTextStreamHandler(topic);
 1650        }
 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)
 13659        {
 13660            _streamHandlers.RegisterByteStreamHandler(topic, handler);
 12661        }
 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)
 1668        {
 1669            _streamHandlers.UnregisterByteStreamHandler(topic);
 1670        }
 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)
 5927675        {
 5927676            if (handlers == null)
 3504677                return;
 13451678            foreach (var handler in handlers.GetInvocationList())
 3091679            {
 680                try
 3091681                {
 3091682                    ((EventHandler<TArgs>)handler)(this, args);
 3039683                }
 52684                catch (Exception ex)
 52685                {
 52686                    Console.Error.WriteLine($"[ERROR] Room.{eventName} handler threw: {ex}");
 52687                }
 3091688            }
 5927689        }
 690
 691        private void Raise(EventHandler? handlers, string eventName)
 497692        {
 497693            if (handlers == null)
 240694                return;
 1359695            foreach (var handler in handlers.GetInvocationList())
 294696            {
 697                try
 294698                {
 294699                    ((EventHandler)handler)(this, EventArgs.Empty);
 294700                }
 0701                catch (Exception ex)
 0702                {
 0703                    Console.Error.WriteLine($"[ERROR] Room.{eventName} handler threw: {ex}");
 0704                }
 294705            }
 497706        }
 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)
 6269713        {
 6269714            lock (_eventLock)
 6269715            {
 6269716                _eventTaskChain = _eventTaskChain.ContinueWith(
 6269717                    _ =>
 6269718                    {
 6269719                        try
 6269720                        {
 6269721                            action();
 6269722                        }
 0723                        catch (Exception ex)
 0724                        {
 0725                            Console.Error.WriteLine($"[ERROR] Room event handler exception: {ex}");
 0726                        }
 6269727                    },
 6269728                    TaskScheduler.Default
 6269729                );
 6269730            }
 6269731        }
 732
 733        // Overload to handle async delegates directly
 734        private void DispatchEvent(Func<Task> action)
 606735        {
 606736            lock (_eventLock)
 606737            {
 606738                _eventTaskChain = _eventTaskChain
 606739                    .ContinueWith(
 606740                        async _ =>
 606741                        {
 606742                            try
 606743                            {
 606744                                await action();
 606745                            }
 0746                            catch (Exception ex)
 0747                            {
 0748                                Console.Error.WriteLine(
 0749                                    $"[ERROR] Room event handler exception: {ex}"
 0750                                );
 0751                            }
 606752                        },
 606753                        TaskScheduler.Default
 606754                    )
 606755                    .Unwrap();
 606756            }
 606757        }
 758
 759        /// <summary>
 760        /// Creates a new Room instance.
 761        /// </summary>
 445762        public Room()
 445763        {
 445764            _remoteParticipants = new Dictionary<string, RemoteParticipant>();
 445765        }
 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)
 950770        {
 950771            if (ConnectionState == newState)
 2772                return;
 948773            ConnectionState = newState;
 948774            var state = newState;
 948775            DispatchEvent(() =>
 948776                Raise(ConnectionStateChanged, state, nameof(ConnectionStateChanged))
 948777            );
 950778        }
 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        )
 466804        {
 466805            if (_disposed)
 1806                throw new ObjectDisposedException(nameof(Room));
 807
 808            // Validates the options, before any side effect
 465809            options ??= new RoomOptions();
 465810            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
 464814            cancellationToken.ThrowIfCancellationRequested();
 815
 462816            if (Interlocked.CompareExchange(ref _connecting, 1, 0) != 0)
 3817                throw new InvalidOperationException("Room is already connecting");
 818            try
 459819            {
 459820                if (IsConnected)
 0821                    throw new InvalidOperationException("Room is already connected");
 822
 459823                await ConnectCoreAsync(url, token, options, protoOptions, cancellationToken)
 459824                    .ConfigureAwait(false);
 451825            }
 826            finally
 459827            {
 459828                Volatile.Write(ref _connecting, 0);
 459829            }
 451830        }
 831
 832        private async Task ConnectCoreAsync(
 833            string url,
 834            string token,
 835            RoomOptions options,
 836            Proto.RoomOptions protoOptions,
 837            CancellationToken cancellationToken
 838        )
 459839        {
 840            List<TextStreamReader> staleTextReaders;
 841            List<ByteStreamReader> staleByteReaders;
 459842            lock (_connectionLock)
 459843            {
 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.
 459846                _connectionGeneration++;
 459847                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
 459852                FfiClient.Instance.EventReceived -= OnFfiEvent;
 459853                FfiClient.Instance.EventReceived += OnFfiEvent;
 459854                Interlocked.Exchange(ref _cleanedUp, 0);
 459855            }
 459856            FailStreamReaders(staleTextReaders, staleByteReaders);
 857
 858            // Send connect request
 459859            var request = new FfiRequest
 459860            {
 459861                Connect = new ConnectRequest
 459862                {
 459863                    Url = url,
 459864                    Token = token,
 459865                    Options = protoOptions,
 459866                },
 459867            };
 868
 459869            var response = FfiClient.Instance.SendRequest(request);
 870
 459871            if (response.Connect == null)
 0872                throw new InvalidOperationException("Invalid connect response");
 873
 459874            var asyncId = response.Connect.AsyncId;
 875
 876            // Wait for connect callback
 877            FfiEvent connectEvent;
 878            try
 459879            {
 459880                connectEvent = await FfiClient.Instance.WaitForEventAsync(
 459881                    e =>
 459588882                        e.MessageCase == FfiEvent.MessageOneofCase.Connect
 459588883                        && e.Connect?.AsyncId == asyncId,
 459884                    TimeSpan.FromSeconds(30),
 459885                    cancellationToken
 459886                );
 454887            }
 5888            catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
 5889            {
 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.
 5893                StopListeningUnlessDraining();
 5894                _ = AbandonConnectAsync(asyncId);
 5895                throw;
 896            }
 897
 454898            var callback = connectEvent.Connect!;
 899
 454900            if (!string.IsNullOrEmpty(callback.Error))
 2901            {
 2902                StopListeningUnlessDraining();
 2903                UpdateConnectionState(Proto.ConnectionState.ConnDisconnected);
 2904                throw new RoomException($"Failed to connect: {callback.Error}");
 905            }
 906
 907            // Get the result from the callback
 452908            var result = callback.Result;
 452909            if (result == null)
 0910            {
 0911                StopListeningUnlessDraining();
 0912                throw new RoomException("Connect callback has no result");
 913            }
 914
 452915            if (_disposed)
 1916            {
 917                // Disposed while connecting: nothing may keep the native room alive
 1918                StopListeningUnlessDraining();
 1919                _ = ReleaseAbandonedConnectionAsync(result);
 1920                throw new ObjectDisposedException(nameof(Room));
 921            }
 922
 923            // Store room handle and info
 451924            if (result.Room?.Handle != null)
 451925            {
 451926                _roomHandle = FfiHandle.FromId(result.Room.Handle.Id);
 451927                UpdateFromInfo(result.Room.Info);
 928
 929                // Initialize E2EE manager if E2EE options were provided
 451930                if (options.E2EE != null)
 25931                {
 25932                    _e2eeManager = new E2EEManager(_roomHandle.HandleId, options.E2EE);
 25933                }
 451934            }
 935
 936            // Create local participant
 451937            if (result.LocalParticipant?.Handle != null)
 451938            {
 451939                LocalParticipant = new LocalParticipant(
 451940                    FfiHandle.FromId(result.LocalParticipant.Handle.Id),
 451941                    result.LocalParticipant.Info,
 451942                    this
 451943                );
 451944            }
 945
 946            // Create remote participants
 1769947            foreach (var participantWithTracks in result.Participants)
 208948            {
 208949                if (participantWithTracks.Participant?.Info != null)
 208950                {
 208951                    var remoteParticipant = new RemoteParticipant(
 208952                        FfiHandle.FromId(participantWithTracks.Participant.Handle!.Id),
 208953                        participantWithTracks.Participant.Info,
 208954                        this
 208955                    );
 956
 957                    // Add publications
 626958                    foreach (var pub in participantWithTracks.Publications)
 1959                    {
 1960                        if (pub.Handle != null && pub.Info != null)
 1961                        {
 1962                            remoteParticipant.AddPublication(pub);
 1963                        }
 1964                    }
 965
 208966                    lock (_lock)
 208967                    {
 208968                        _remoteParticipants[remoteParticipant.Identity] = remoteParticipant;
 208969                    }
 208970                }
 208971            }
 972
 451973            UpdateConnectionState(Proto.ConnectionState.ConnConnected);
 974
 975            // Release the FFI room event gate after our listener and local state are ready.
 451976            var readyRequest = new FfiRequest
 451977            {
 451978                ReadyForRoomEvent = new ReadyForRoomEventRequest
 451979                {
 451980                    RoomHandle = _roomHandle!.HandleId,
 451981                },
 451982            };
 451983            FfiClient.Instance.SendRequest(readyRequest);
 984
 902985            DispatchEvent(() => Raise(Connected, nameof(Connected)));
 451986        }
 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)
 5991        {
 992            try
 5993            {
 5994                var connectEvent = await FfiClient.Instance.WaitForEventAsync(
 5995                    e =>
 9792996                        e.MessageCase == FfiEvent.MessageOneofCase.Connect
 9792997                        && e.Connect?.AsyncId == asyncId,
 5998                    TimeSpan.FromSeconds(60)
 5999                );
 51000                var result = connectEvent.Connect?.Result;
 51001                if (result != null && string.IsNullOrEmpty(connectEvent.Connect?.Error))
 51002                {
 51003                    await ReleaseAbandonedConnectionAsync(result);
 51004                }
 51005            }
 01006            catch (Exception ex)
 01007            {
 01008                Console.Error.WriteLine(
 01009                    $"[WARN] Could not release an abandoned room connection: {ex.Message}"
 01010                );
 01011            }
 51012        }
 1013
 1014        private static async Task ReleaseAbandonedConnectionAsync(
 1015            ConnectCallback.Types.Result result
 1016        )
 61017        {
 61018            var handles = new List<ulong>();
 61019            if (result.Room?.Handle != null)
 61020                handles.Add(result.Room.Handle.Id);
 61021            if (result.LocalParticipant?.Handle != null)
 61022                handles.Add(result.LocalParticipant.Handle.Id);
 181023            foreach (var participant in result.Participants)
 01024            {
 01025                if (participant.Participant?.Handle != null)
 01026                    handles.Add(participant.Participant.Handle.Id);
 01027                foreach (var publication in participant.Publications)
 01028                {
 01029                    if (publication.Handle != null)
 01030                        handles.Add(publication.Handle.Id);
 01031                }
 01032            }
 1033
 1034            try
 61035            {
 61036                var roomHandleId = result.Room?.Handle?.Id ?? 0;
 61037                if (roomHandleId != 0)
 61038                {
 1039                    // The FFI forwards nothing (and panics after 15 s) until it gets this
 61040                    FfiClient.Instance.SendRequest(
 61041                        new FfiRequest
 61042                        {
 61043                            ReadyForRoomEvent = new ReadyForRoomEventRequest
 61044                            {
 61045                                RoomHandle = roomHandleId,
 61046                            },
 61047                        }
 61048                    );
 61049                    var response = FfiClient.Instance.SendRequest(
 61050                        new FfiRequest
 61051                        {
 61052                            Disconnect = new DisconnectRequest
 61053                            {
 61054                                RoomHandle = roomHandleId,
 61055                                Reason = Proto.DisconnectReason.ClientInitiated,
 61056                            },
 61057                        }
 61058                    );
 61059                    var asyncId = response.Disconnect?.AsyncId ?? 0;
 61060                    await FfiClient.Instance.WaitForEventAsync(
 61061                        e =>
 60451062                            e.MessageCase == FfiEvent.MessageOneofCase.Disconnect
 60451063                            && e.Disconnect?.AsyncId == asyncId,
 61064                        TimeSpan.FromSeconds(10)
 61065                    );
 61066                }
 61067            }
 01068            catch (Exception ex)
 01069            {
 01070                Console.Error.WriteLine(
 01071                    $"[WARN] Could not release an abandoned room connection: {ex.Message}"
 01072                );
 01073            }
 1074            finally
 61075            {
 421076                foreach (var id in handles)
 121077                {
 121078                    FfiHandle.FromId(id).Dispose();
 121079                }
 61080            }
 61081        }
 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()
 4781089        {
 4781090            lock (_connectionLock)
 4781091            {
 4781092                if (_disconnecting != null && !_disconnecting.IsCompleted)
 201093                    return _disconnecting;
 1094
 1095                // Read once: the cleanup of a disconnection that is finishing clears it
 4581096                var roomHandle = _roomHandle;
 4581097                if (roomHandle == null)
 101098                    return Task.CompletedTask;
 1099
 4481100                _disconnecting = DisconnectCoreAsync(roomHandle);
 4481101                return _disconnecting;
 1102            }
 4781103        }
 1104
 1105        private async Task DisconnectCoreAsync(FfiHandle roomHandle)
 4481106        {
 4481107            var request = new FfiRequest
 4481108            {
 4481109                Disconnect = new DisconnectRequest
 4481110                {
 4481111                    RoomHandle = roomHandle.HandleId,
 4481112                    Reason = Proto.DisconnectReason.ClientInitiated,
 4481113                },
 4481114            };
 1115
 1116            try
 4481117            {
 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
 4481120                var response = FfiClient.Instance.SendRequest(request);
 1121
 4481122                if (response.Disconnect == null)
 01123                    throw new InvalidOperationException("Invalid disconnect response");
 1124
 4481125                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
 4481129                await FfiClient
 4481130                    .Instance.WaitForEventAsync(
 4481131                        e =>
 4497281132                            e.MessageCase == FfiEvent.MessageOneofCase.Disconnect
 4497281133                            && e.Disconnect?.AsyncId == asyncId,
 4481134                        TimeSpan.FromSeconds(10)
 4481135                    )
 4481136                    .ConfigureAwait(false);
 4481137            }
 1138            finally
 4481139            {
 1140                // Even if the callback never came: the room must not stay "connected"
 4481141                CleanupOnDisconnect(Proto.DisconnectReason.ClientInitiated);
 4481142            }
 4481143        }
 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        )
 231168        {
 231169            if (!IsConnected || _roomHandle == null)
 01170                throw new InvalidOperationException("Not connected to a room");
 231171            cancellationToken.ThrowIfCancellationRequested();
 1172
 221173            var response = FfiClient.Instance.SendRequest(
 221174                new FfiRequest
 221175                {
 221176                    SimulateScenario = new SimulateScenarioRequest
 221177                    {
 221178                        RoomHandle = _roomHandle.HandleId,
 221179                        Scenario = scenario,
 221180                    },
 221181                }
 221182            );
 1183
 221184            if (response.SimulateScenario == null)
 01185                throw new InvalidOperationException("Invalid simulate scenario response");
 1186
 221187            var asyncId = response.SimulateScenario.AsyncId;
 1188
 221189            var callbackEvent = await FfiClient.Instance.WaitForEventAsync(
 221190                e =>
 219991191                    e.MessageCase == FfiEvent.MessageOneofCase.SimulateScenario
 219991192                    && e.SimulateScenario?.AsyncId == asyncId,
 221193                TimeSpan.FromSeconds(30),
 221194                cancellationToken
 221195            );
 1196
 211197            var callback = callbackEvent.SimulateScenario!;
 211198            if (callback.HasError && !string.IsNullOrEmpty(callback.Error))
 01199                throw new RoomException($"Simulate scenario failed: {callback.Error}");
 211200        }
 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()
 161208        {
 161209            if (!IsConnected || _roomHandle == null)
 21210                throw new InvalidOperationException("Not connected to a room");
 1211
 141212            var request = new FfiRequest
 141213            {
 141214                GetSessionStats = new GetSessionStatsRequest { RoomHandle = _roomHandle.HandleId },
 141215            };
 1216
 141217            var response = FfiClient.Instance.SendRequest(request);
 1218
 141219            if (response.GetSessionStats == null)
 01220                throw new InvalidOperationException("Invalid get session stats response");
 1221
 141222            var asyncId = response.GetSessionStats.AsyncId;
 1223
 1224            // Wait for stats callback
 141225            var statsEvent = await FfiClient.Instance.WaitForEventAsync(
 141226                e =>
 140101227                    e.MessageCase == FfiEvent.MessageOneofCase.GetSessionStats
 140101228                    && e.GetSessionStats?.AsyncId == asyncId,
 141229                TimeSpan.FromSeconds(10)
 141230            );
 1231
 141232            var callback = statsEvent.GetSessionStats!;
 1233
 141234            if (!string.IsNullOrEmpty(callback.Error))
 01235            {
 01236                throw new RoomException($"Failed to get RTC stats: {callback.Error}");
 1237            }
 1238
 141239            var result = callback.Result;
 141240            if (result == null)
 01241            {
 01242                throw new RoomException("Get session stats callback has no result");
 1243            }
 1244
 141245            return new RtcStats
 141246            {
 141247                PublisherStats = new List<Proto.RtcStats>(result.PublisherStats),
 141248                SubscriberStats = new List<Proto.RtcStats>(result.SubscriberStats),
 141249            };
 141250        }
 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()
 321257        {
 321258            DisconnectAsync().GetAwaiter().GetResult();
 321259        }
 1260
 1261        private void UpdateFromInfo(RoomInfo? info)
 4891262        {
 4891263            if (info == null)
 01264                return;
 1265
 4891266            Sid = info.Sid;
 4891267            Name = info.Name;
 4891268            Metadata = info.Metadata;
 4891269            NumParticipants = info.NumParticipants;
 4891270            NumPublishers = info.NumPublishers;
 4891271            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
 4891275            var creationTimeValue = info.CreationTime;
 4891276            if (creationTimeValue > 0)
 4891277            {
 1278                // If value looks like seconds (less than year 3000 in ms), convert to ms
 4891279                if (creationTimeValue < 1_000_000_000_000L)
 11280                {
 11281                    creationTimeValue *= 1000;
 11282                }
 4891283                CreationTime = DateTimeOffset.FromUnixTimeMilliseconds(creationTimeValue).DateTime;
 4891284            }
 1285            else
 01286            {
 01287                CreationTime = DateTime.MinValue;
 01288            }
 1289
 4891290            DepartureTimeout = info.DepartureTimeout;
 4891291            EmptyTimeout = info.EmptyTimeout;
 4891292        }
 1293
 1294        private void OnFfiEvent(object? sender, FfiEvent e)
 683301295        {
 683301296            if (e.MessageCase == FfiEvent.MessageOneofCase.RoomEvent)
 223571297            {
 223571298                var roomEvent = e.RoomEvent;
 223571299                if (roomEvent == null)
 01300                    return;
 1301
 223571302                var roomHandle = _roomHandle;
 223571303                if (roomHandle != null && roomEvent.RoomHandle == roomHandle.HandleId)
 98631304                    HandleRoomEvent(roomEvent);
 1305                else
 124941306                    DrainEndedConnection(roomEvent);
 223571307            }
 459731308            else if (e.MessageCase == FfiEvent.MessageOneofCase.RpcMethodInvocation)
 1581309            {
 1581310                var invocation = e.RpcMethodInvocation;
 1581311                var localParticipant = LocalParticipant; // cleared by CleanupOnDisconnect meanwhile
 1581312                if (invocation == null || localParticipant == null)
 01313                    return;
 1314
 1315                // Check if this event is for our local participant
 1581316                if (invocation.LocalParticipantHandle != localParticipant.Handle.HandleId)
 941317                    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.
 641321                _ = Task.Run(async () =>
 641322                {
 641323                    try
 641324                    {
 641325                        await localParticipant.HandleRpcMethodInvocationAsync(
 641326                            invocation.InvocationId,
 641327                            invocation.Method,
 641328                            invocation.RequestId,
 641329                            invocation.CallerIdentity,
 641330                            invocation.Payload,
 641331                            invocation.ResponseTimeoutMs
 641332                        );
 641333                    }
 01334                    catch (Exception ex)
 01335                    {
 641336                        // Log error but don't crash
 01337                        Console.Error.WriteLine($"[ERROR] Error handling RPC invocation: {ex}");
 01338                    }
 1281339                });
 641340            }
 683301341        }
 1342
 1343        private void HandleRoomEvent(RoomEvent roomEvent)
 98631344        {
 98631345            switch (roomEvent.MessageCase)
 1346            {
 1347                case RoomEvent.MessageOneofCase.ParticipantConnected:
 2341348                    HandleParticipantConnected(roomEvent.ParticipantConnected);
 2341349                    break;
 1350
 1351                case RoomEvent.MessageOneofCase.ParticipantDisconnected:
 861352                    HandleParticipantDisconnected(roomEvent.ParticipantDisconnected);
 861353                    break;
 1354
 1355                case RoomEvent.MessageOneofCase.LocalTrackPublished:
 2311356                    HandleLocalTrackPublished(roomEvent.LocalTrackPublished);
 2311357                    break;
 1358
 1359                case RoomEvent.MessageOneofCase.LocalTrackUnpublished:
 2271360                    HandleLocalTrackUnpublished(roomEvent.LocalTrackUnpublished);
 2271361                    break;
 1362
 1363                case RoomEvent.MessageOneofCase.LocalTrackSubscribed:
 1081364                    HandleLocalTrackSubscribed(roomEvent.LocalTrackSubscribed);
 1081365                    break;
 1366
 1367                case RoomEvent.MessageOneofCase.TrackPublished:
 1541368                    HandleTrackPublished(roomEvent.TrackPublished);
 1541369                    break;
 1370
 1371                case RoomEvent.MessageOneofCase.TrackUnpublished:
 941372                    HandleTrackUnpublished(roomEvent.TrackUnpublished);
 941373                    break;
 1374
 1375                case RoomEvent.MessageOneofCase.TrackSubscribed:
 1501376                    HandleTrackSubscribed(roomEvent.TrackSubscribed);
 1501377                    break;
 1378
 1379                case RoomEvent.MessageOneofCase.TrackUnsubscribed:
 911380                    HandleTrackUnsubscribed(roomEvent.TrackUnsubscribed);
 911381                    break;
 1382
 1383                case RoomEvent.MessageOneofCase.TrackMuted:
 91384                    HandleTrackMuted(roomEvent.TrackMuted);
 91385                    break;
 1386
 1387                case RoomEvent.MessageOneofCase.TrackUnmuted:
 41388                    HandleTrackUnmuted(roomEvent.TrackUnmuted);
 41389                    break;
 1390
 1391                case RoomEvent.MessageOneofCase.ActiveSpeakersChanged:
 451392                    HandleActiveSpeakersChanged(roomEvent.ActiveSpeakersChanged);
 451393                    break;
 1394
 1395                case RoomEvent.MessageOneofCase.ConnectionQualityChanged:
 1291396                    HandleConnectionQualityChanged(roomEvent.ConnectionQualityChanged);
 1291397                    break;
 1398
 1399                case RoomEvent.MessageOneofCase.DataPacketReceived:
 17261400                    HandleDataPacketReceived(roomEvent.DataPacketReceived);
 17261401                    break;
 1402
 1403                case RoomEvent.MessageOneofCase.RoomMetadataChanged:
 291404                    HandleRoomMetadataChanged(roomEvent.RoomMetadataChanged);
 291405                    break;
 1406
 1407                case RoomEvent.MessageOneofCase.ParticipantMetadataChanged:
 101408                    HandleParticipantMetadataChanged(roomEvent.ParticipantMetadataChanged);
 101409                    break;
 1410
 1411                case RoomEvent.MessageOneofCase.ParticipantNameChanged:
 21412                    HandleParticipantNameChanged(roomEvent.ParticipantNameChanged);
 21413                    break;
 1414
 1415                case RoomEvent.MessageOneofCase.ParticipantAttributesChanged:
 41416                    HandleParticipantAttributesChanged(roomEvent.ParticipantAttributesChanged);
 41417                    break;
 1418
 1419                case RoomEvent.MessageOneofCase.ParticipantEncryptionStatusChanged:
 141420                    HandleParticipantEncryptionStatusChanged(
 141421                        roomEvent.ParticipantEncryptionStatusChanged
 141422                    );
 141423                    break;
 1424
 1425                case RoomEvent.MessageOneofCase.TrackSubscriptionFailed:
 21426                    HandleTrackSubscriptionFailed(roomEvent.TrackSubscriptionFailed);
 21427                    break;
 1428
 1429                case RoomEvent.MessageOneofCase.RoomUpdated:
 371430                    HandleRoomUpdated(roomEvent.RoomUpdated);
 371431                    break;
 1432
 1433                case RoomEvent.MessageOneofCase.RoomSidChanged:
 4511434                    HandleRoomSidChanged(roomEvent.RoomSidChanged);
 4511435                    break;
 1436
 1437                case RoomEvent.MessageOneofCase.Moved:
 11438                    HandleMoved(roomEvent.Moved);
 11439                    break;
 1440
 1441                case RoomEvent.MessageOneofCase.ChatMessage:
 21442                    HandleChatMessage(roomEvent.ChatMessage);
 21443                    break;
 1444
 1445                case RoomEvent.MessageOneofCase.E2EeStateChanged:
 171446                    HandleE2EEStateChanged(roomEvent.E2EeStateChanged);
 171447                    break;
 1448
 1449                case RoomEvent.MessageOneofCase.TranscriptionReceived:
 11450                    HandleTranscriptionReceived(roomEvent.TranscriptionReceived);
 11451                    break;
 1452
 1453                case RoomEvent.MessageOneofCase.TokenRefreshed:
 4871454                    HandleTokenRefreshed(roomEvent.TokenRefreshed);
 4871455                    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.
 27571464                    break;
 1465
 1466                case RoomEvent.MessageOneofCase.ParticipantPermissionChanged:
 21467                    HandleParticipantPermissionChanged(roomEvent.ParticipantPermissionChanged);
 21468                    break;
 1469
 1470                case RoomEvent.MessageOneofCase.ParticipantActive:
 1991471                    HandleParticipantActive(roomEvent.ParticipantActive);
 1991472                    break;
 1473
 1474                case RoomEvent.MessageOneofCase.ParticipantsUpdated:
 9741475                    HandleParticipantsUpdated(roomEvent.ParticipantsUpdated);
 9741476                    break;
 1477
 1478                case RoomEvent.MessageOneofCase.LocalTrackRepublished:
 271479                    HandleLocalTrackRepublished(roomEvent.LocalTrackRepublished);
 271480                    break;
 1481
 1482                case RoomEvent.MessageOneofCase.DataTrackPublished:
 31483                    HandleDataTrackPublished(roomEvent.DataTrackPublished);
 31484                    break;
 1485
 1486                case RoomEvent.MessageOneofCase.DataTrackUnpublished:
 21487                    HandleDataTrackUnpublished(roomEvent.DataTrackUnpublished);
 21488                    break;
 1489
 1490                case RoomEvent.MessageOneofCase.DataChannelLowThresholdChanged:
 11491                    HandleDataChannelLowThresholdChanged(roomEvent.DataChannelLowThresholdChanged);
 11492                    break;
 1493
 1494                case RoomEvent.MessageOneofCase.TextStreamOpened:
 731495                    HandleTextStreamOpened(roomEvent.TextStreamOpened);
 731496                    break;
 1497
 1498                case RoomEvent.MessageOneofCase.ByteStreamOpened:
 381499                    HandleByteStreamOpened(roomEvent.ByteStreamOpened);
 381500                    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
 541506                    EndOfStreamBeforeCleanup(roomEvent.RoomHandle);
 541507                    break;
 1508
 1509                case RoomEvent.MessageOneofCase.Disconnected:
 3971510                    CleanupOnDisconnect(
 3971511                        roomEvent.Disconnected?.Reason ?? Proto.DisconnectReason.UnknownReason
 3971512                    );
 3971513                    break;
 1514
 1515                case RoomEvent.MessageOneofCase.Reconnecting:
 241516                    UpdateConnectionState(Proto.ConnectionState.ConnReconnecting);
 481517                    DispatchEvent(() => Raise(Reconnecting, nameof(Reconnecting)));
 241518                    break;
 1519
 1520                case RoomEvent.MessageOneofCase.Reconnected:
 221521                    UpdateConnectionState(Proto.ConnectionState.ConnConnected);
 441522                    DispatchEvent(() => Raise(Reconnected, nameof(Reconnected)));
 221523                    break;
 1524            }
 98631525        }
 1526
 1527        private void HandleParticipantConnected(Proto.ParticipantConnected evt)
 2341528        {
 2341529            if (evt?.Info?.Info == null)
 01530            {
 01531                FfiHandle.FromId(evt?.Info?.Handle?.Id ?? 0).Dispose();
 01532                return;
 1533            }
 1534
 2341535            var participant = new RemoteParticipant(
 2341536                FfiHandle.FromId(evt.Info.Handle?.Id ?? 0),
 2341537                evt.Info.Info,
 2341538                this
 2341539            );
 1540
 2341541            lock (_lock)
 2341542            {
 2341543                _remoteParticipants[participant.Identity] = participant;
 2341544                _departedParticipants.Remove(participant.Identity);
 2341545            }
 1546
 2341547            DispatchEvent(() =>
 2341548                Raise(ParticipantConnected, participant, nameof(ParticipantConnected))
 2341549            );
 2341550        }
 1551
 1552        private void HandleParticipantDisconnected(Proto.ParticipantDisconnected evt)
 861553        {
 861554            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 01555                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;
 861560            lock (_lock)
 861561            {
 861562                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 01563                    return;
 1564
 861565                _remoteParticipants.Remove(evt.ParticipantIdentity);
 861566                RememberDeparture(evt.ParticipantIdentity);
 861567            }
 1568
 861569            participant._info.DisconnectReason = evt.DisconnectReason;
 1570
 861571            DispatchEvent(() =>
 861572                Raise(ParticipantDisconnected, participant, nameof(ParticipantDisconnected))
 861573            );
 861574        }
 1575
 1576        // Caller holds _lock
 1577        private void RememberDeparture(string identity)
 861578        {
 861579            var departure = ++_departures;
 861580            _departedParticipants[identity] = departure;
 861581            _departureOrder.Enqueue(new KeyValuePair<string, long>(identity, departure));
 861582            while (_departureOrder.Count > DepartedParticipantsKept)
 01583            {
 01584                var oldest = _departureOrder.Dequeue();
 1585                // Unless the identity left again since
 01586                if (
 01587                    _departedParticipants.TryGetValue(oldest.Key, out var last)
 01588                    && last == oldest.Value
 01589                )
 01590                    _departedParticipants.Remove(oldest.Key);
 01591            }
 861592        }
 1593
 1594        // The remote participant, or null with whether it is one that already left
 1595        private RemoteParticipant? FindRemoteParticipant(string identity, out bool departed)
 3951596        {
 3951597            lock (_lock)
 3951598            {
 3951599                if (_remoteParticipants.TryGetValue(identity, out var participant))
 3911600                {
 3911601                    departed = false;
 3911602                    return participant;
 1603                }
 41604                departed = _departedParticipants.ContainsKey(identity);
 41605                return null;
 1606            }
 3951607        }
 1608
 1609        private void HandleLocalTrackPublished(Proto.LocalTrackPublished evt)
 2311610        {
 2311611            if (LocalParticipant == null || string.IsNullOrEmpty(evt?.TrackSid))
 01612                return;
 1613
 2311614            var localParticipant = LocalParticipant;
 2311615            DispatchEvent(async () =>
 2311616            {
 2311617                // PublishTrackAsync registers the publication from its own continuation; wait
 2311618                // for it instead of polling
 2311619                var publication = await localParticipant.WaitForPublicationAsync(
 2311620                    evt.TrackSid,
 2311621                    TimeSpan.FromSeconds(10)
 2311622                );
 2311623                if (publication == null)
 01624                {
 2311625                    // A publication whose PublishTrackAsync was abandoned is not reported
 01626                    if (!await localParticipant.IsAbandonedPublicationAsync(evt.TrackSid))
 01627                        Console.Error.WriteLine(
 01628                            $"[WARN] RoomEvent.LocalTrackPublished: Publication {evt.TrackSid} not found"
 01629                        );
 01630                    return;
 2311631                }
 2311632                Raise(
 2311633                    LocalTrackPublished,
 2311634                    new LocalTrackPublishedEventArgs(publication, localParticipant),
 2311635                    nameof(LocalTrackPublished)
 2311636                );
 4621637            });
 2311638        }
 1639
 1640        private void HandleLocalTrackUnpublished(Proto.LocalTrackUnpublished evt)
 2271641        {
 2271642            if (LocalParticipant == null || string.IsNullOrEmpty(evt?.PublicationSid))
 01643                return;
 1644
 2271645            DispatchEvent(async () =>
 2271646            {
 2271647                try
 2271648                {
 2271649                    var localParticipant = LocalParticipant;
 2271650                    if (localParticipant == null)
 01651                        throw new InvalidOperationException("Local participant not available");
 2271652
 2271653                    // Retrieve the publication directly from the local participant's unpublished tracks.
 2271654                    // Protected by Room.FfiEventLock.
 2271655                    LocalTrackPublication? publication;
 2271656                    await _ffiEventLock.WaitAsync();
 2271657                    try
 2271658                    {
 2271659                        publication = localParticipant.TakeUnpublishedTrackPublication(
 2271660                            evt.PublicationSid
 2271661                        );
 2271662                    }
 2271663                    finally
 2271664                    {
 2271665                        _ffiEventLock.Release();
 2271666                    }
 2271667
 2271668                    if (publication == null)
 01669                    {
 2271670                        // The unpublication of an abandoned publish is its last event
 01671                        if (
 01672                            await localParticipant.IsAbandonedPublicationAsync(
 01673                                evt.PublicationSid,
 01674                                forget: true
 01675                            )
 01676                        )
 01677                            return;
 01678                        throw new InvalidOperationException(
 01679                            $"Publication {evt.PublicationSid} not found"
 01680                        );
 2271681                    }
 2271682
 2271683                    Raise(
 2271684                        LocalTrackUnpublished,
 2271685                        new LocalTrackPublishedEventArgs(publication, localParticipant),
 2271686                        nameof(LocalTrackUnpublished)
 2271687                    );
 2271688                }
 01689                catch (Exception ex)
 01690                {
 01691                    Console.Error.WriteLine(
 01692                        $"[WARN] RoomEvent.LocalTrackUnpublished: {ex.Message}"
 01693                    );
 01694                }
 4541695            });
 2271696        }
 1697
 1698        private void HandleLocalTrackSubscribed(Proto.LocalTrackSubscribed evt)
 1081699        {
 1081700            if (LocalParticipant == null || string.IsNullOrEmpty(evt?.TrackSid))
 01701                return;
 1702
 1081703            var localParticipant = LocalParticipant;
 1081704            DispatchEvent(async () =>
 1081705            {
 1081706                var publication = await localParticipant.WaitForPublicationAsync(
 1081707                    evt.TrackSid,
 1081708                    TimeSpan.FromSeconds(10)
 1081709                );
 1081710                if (publication == null)
 01711                {
 01712                    if (!await localParticipant.IsAbandonedPublicationAsync(evt.TrackSid))
 01713                        Console.Error.WriteLine(
 01714                            $"[WARN] RoomEvent.LocalTrackSubscribed: Publication {evt.TrackSid} not found"
 01715                        );
 01716                    return;
 1081717                }
 1081718                publication.ResolveFirstSubscription();
 1081719                Raise(
 1081720                    LocalTrackSubscribed,
 1081721                    new LocalTrackSubscribedEventArgs(publication),
 1081722                    nameof(LocalTrackSubscribed)
 1081723                );
 2161724            });
 1081725        }
 1726
 1727        private void HandleTrackPublished(Proto.TrackPublished evt)
 1541728        {
 1541729            if (string.IsNullOrEmpty(evt?.ParticipantIdentity) || evt.Publication == null)
 01730                return;
 1731
 1541732            var participant = FindRemoteParticipant(evt.ParticipantIdentity, out var departed);
 1541733            if (participant == null)
 01734            {
 1735                // The event hands over the native publication: release it, as TrackSubscribed does,
 1736                // and report it unless the participant already left
 01737                if (!departed)
 01738                    Console.Error.WriteLine(
 01739                        $"[WARN] RoomEvent.TrackPublished: Participant {evt.ParticipantIdentity} not found"
 01740                    );
 01741                FfiHandle.FromId(evt.Publication.Handle?.Id ?? 0).Dispose();
 01742                return;
 1743            }
 1744
 1745            // Add publication to participant (synchronously, so later events can rely on it)
 1541746            participant.AddPublication(evt.Publication);
 1541747            var publication =
 1541748                participant.GetTrackPublication(evt.Publication.Info?.Sid ?? "")
 1541749                as RemoteTrackPublication;
 1541750            if (publication == null)
 01751            {
 01752                Console.Error.WriteLine(
 01753                    $"[WARN] RoomEvent.TrackPublished: Publication {evt.Publication.Info?.Sid} not found after AddPublic
 01754                );
 01755                return;
 1756            }
 1757
 1541758            DispatchEvent(() =>
 1541759                Raise(
 1541760                    TrackPublished,
 1541761                    new TrackPublishedEventArgs(publication, participant),
 1541762                    nameof(TrackPublished)
 1541763                )
 1541764            );
 1541765        }
 1766
 1767        private void HandleTrackUnpublished(Proto.TrackUnpublished evt)
 941768        {
 941769            if (
 941770                string.IsNullOrEmpty(evt?.ParticipantIdentity)
 941771                || string.IsNullOrEmpty(evt.PublicationSid)
 941772            )
 01773                return;
 1774
 1775            RemoteParticipant? participant;
 941776            lock (_lock)
 941777            {
 941778                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 01779                    return;
 941780            }
 1781
 941782            var publication =
 941783                participant.GetTrackPublication(evt.PublicationSid) as RemoteTrackPublication;
 941784            if (publication != null)
 931785            {
 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.
 931791                var track = publication.Track;
 931792                if (track != null)
 11793                {
 11794                    publication.Track = null;
 11795                    DispatchEvent(() =>
 11796                        Raise(
 11797                            TrackUnsubscribed,
 11798                            new TrackSubscribedEventArgs(track, publication, participant),
 11799                            nameof(TrackUnsubscribed)
 11800                        )
 11801                    );
 11802                }
 1803                else
 921804                {
 921805                    participant.MarkUnsubscribedBeforeSubscribed(evt.PublicationSid);
 921806                }
 931807                DispatchEvent(() =>
 931808                    Raise(
 931809                        TrackUnpublished,
 931810                        new TrackPublishedEventArgs(publication, participant),
 931811                        nameof(TrackUnpublished)
 931812                    )
 931813                );
 931814                participant.RemovePublication(evt.PublicationSid);
 931815            }
 941816        }
 1817
 1818        private void HandleTrackSubscribed(Proto.TrackSubscribed evt)
 1501819        {
 1501820            if (evt == null)
 01821                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.
 251826            void Release() => FfiHandle.FromId(evt.Track?.Handle?.Id ?? 0).Dispose();
 1827            void Drop(string reason)
 11828            {
 11829                Console.Error.WriteLine($"[WARN] RoomEvent.TrackSubscribed: {reason}");
 11830                Release();
 11831            }
 1832
 1501833            if (string.IsNullOrEmpty(evt.ParticipantIdentity) || evt.Track == null)
 01834            {
 01835                Drop("Event without a participant identity or a track");
 01836                return;
 1837            }
 1838
 1501839            var participant = FindRemoteParticipant(evt.ParticipantIdentity, out var departed);
 1501840            if (participant == null)
 21841            {
 1842                // A subscription that completed after its participant left is over already
 21843                if (departed)
 11844                    Release();
 1845                else
 11846                    Drop($"Participant {evt.ParticipantIdentity} not found");
 21847                return;
 1848            }
 1849
 1481850            var trackInfo = evt.Track.Info;
 1481851            if (trackInfo == null)
 01852            {
 01853                Drop($"Track of participant {evt.ParticipantIdentity} has no info");
 01854                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
 1481859            if (participant.TakeUnsubscribedBeforeSubscribed(trackInfo.Sid ?? ""))
 231860            {
 231861                Release();
 231862                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
 1251867            var publication =
 1251868                participant.GetTrackPublication(trackInfo.Sid ?? "") as RemoteTrackPublication;
 1251869            if (publication == null)
 01870            {
 01871                Drop(
 01872                    $"Publication {trackInfo.Sid} not found for participant {evt.ParticipantIdentity}"
 01873                );
 01874                return;
 1875            }
 1876
 1877            // The handle is wrapped only for a track that keeps it, so Drop never wraps it twice
 1251878            var handleId = evt.Track.Handle?.Id ?? 0;
 1251879            RemoteTrack? track = trackInfo.Kind switch
 1251880            {
 831881                Proto.TrackKind.KindAudio => new RemoteAudioTrack(
 831882                    FfiHandle.FromId(handleId),
 831883                    evt.Track
 831884                ),
 421885                Proto.TrackKind.KindVideo => new RemoteVideoTrack(
 421886                    FfiHandle.FromId(handleId),
 421887                    evt.Track
 421888                ),
 01889                _ => null,
 1251890            };
 1251891            if (track == null)
 01892            {
 01893                Drop(
 01894                    $"Track {trackInfo.Sid} of participant {evt.ParticipantIdentity} has the unsupported kind {trackInfo
 01895                );
 01896                return;
 1897            }
 1898
 1251899            publication.Track = track;
 1251900            DispatchEvent(() =>
 1251901                Raise(
 1251902                    TrackSubscribed,
 1251903                    new TrackSubscribedEventArgs(track, publication, participant),
 1251904                    nameof(TrackSubscribed)
 1251905                )
 1251906            );
 1501907        }
 1908
 1909        private void HandleTrackUnsubscribed(Proto.TrackUnsubscribed evt)
 911910        {
 911911            if (
 911912                string.IsNullOrEmpty(evt?.ParticipantIdentity) || string.IsNullOrEmpty(evt.TrackSid)
 911913            )
 01914                return;
 1915
 911916            var participant = FindRemoteParticipant(evt.ParticipantIdentity, out var departed);
 911917            if (participant == null)
 21918            {
 21919                if (!departed)
 11920                    Console.Error.WriteLine(
 11921                        $"[WARN] RoomEvent.TrackUnsubscribed: Participant {evt.ParticipantIdentity} not found"
 11922                    );
 11923                return;
 1924            }
 1925
 891926            var publication =
 891927                participant.GetTrackPublication(evt.TrackSid) as RemoteTrackPublication;
 891928            var track = publication?.Track;
 891929            if (publication == null || track == null)
 231930            {
 1931                // The unsubscription of a subscription not delivered yet, or a second one: the
 1932                // TrackSubscribed that follows, if any, is stale
 231933                participant.MarkUnsubscribedBeforeSubscribed(evt.TrackSid);
 231934                return;
 1935            }
 1936
 661937            publication.Track = null;
 661938            DispatchEvent(() =>
 661939                Raise(
 661940                    TrackUnsubscribed,
 661941                    new TrackSubscribedEventArgs(track, publication, participant),
 661942                    nameof(TrackUnsubscribed)
 661943                )
 661944            );
 911945        }
 1946
 1947        private void HandleTrackMuted(Proto.TrackMuted evt)
 91948        {
 91949            HandleTrackMuteChanged(evt?.ParticipantIdentity, evt?.TrackSid, muted: true);
 91950        }
 1951
 1952        private void HandleTrackUnmuted(Proto.TrackUnmuted evt)
 41953        {
 41954            HandleTrackMuteChanged(evt?.ParticipantIdentity, evt?.TrackSid, muted: false);
 41955        }
 1956
 1957        private void HandleTrackMuteChanged(
 1958            string? participantIdentity,
 1959            string? trackSid,
 1960            bool muted
 1961        )
 131962        {
 131963            var eventName = muted ? "TrackMuted" : "TrackUnmuted";
 131964            if (string.IsNullOrEmpty(participantIdentity) || string.IsNullOrEmpty(trackSid))
 01965                return;
 1966
 131967            var participant = GetParticipantByIdentity(participantIdentity);
 131968            if (participant == null)
 01969            {
 01970                FindRemoteParticipant(participantIdentity, out var departed);
 01971                if (!departed)
 01972                    Console.Error.WriteLine(
 01973                        $"[WARN] RoomEvent.{eventName}: Participant {participantIdentity} not found"
 01974                    );
 01975                return;
 1976            }
 1977
 131978            DispatchEvent(async () =>
 131979            {
 131980                var publication = participant.GetTrackPublication(trackSid);
 131981                if (publication == null && participant is LocalParticipant localParticipant)
 01982                {
 131983                    // PublishTrackAsync may not have registered the publication yet
 01984                    publication = await localParticipant.WaitForPublicationAsync(
 01985                        trackSid,
 01986                        TimeSpan.FromSeconds(10)
 01987                    );
 01988                }
 131989                if (publication == null)
 01990                {
 01991                    Console.Error.WriteLine(
 01992                        $"[WARN] RoomEvent.{eventName}: Publication {trackSid} not found for participant {participantIde
 01993                    );
 01994                    return;
 131995                }
 131996
 131997                var updatedInfo = publication.Info;
 131998                updatedInfo.Muted = muted;
 131999                publication.UpdateInfo(updatedInfo);
 132000
 132001                var args = new TrackMutedEventArgs(publication, participant);
 132002                if (muted)
 92003                    Raise(TrackMuted, args, nameof(TrackMuted));
 132004                else
 42005                    Raise(TrackUnmuted, args, nameof(TrackUnmuted));
 262006            });
 132007        }
 2008
 2009        private void HandleActiveSpeakersChanged(Proto.ActiveSpeakersChanged evt)
 452010        {
 452011            if (evt?.ParticipantIdentities == null)
 02012                return;
 2013
 452014            var speakers = new List<Participant>();
 1532015            foreach (var identity in evt.ParticipantIdentities)
 92016            {
 92017                var participant = GetParticipantByIdentity(identity ?? "");
 92018                if (participant != null)
 92019                {
 92020                    speakers.Add(participant);
 92021                }
 92022            }
 2023
 452024            DispatchEvent(() =>
 452025                Raise(
 452026                    ActiveSpeakersChanged,
 452027                    new ActiveSpeakersChangedEventArgs(speakers),
 452028                    nameof(ActiveSpeakersChanged)
 452029                )
 452030            );
 452031        }
 2032
 2033        private void HandleConnectionQualityChanged(Proto.ConnectionQualityChanged evt)
 1292034        {
 1292035            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02036                return;
 2037
 1292038            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 1292039            if (participant == null)
 02040                return;
 2041
 1292042            var quality = evt.Quality;
 1292043            DispatchEvent(() =>
 1292044                Raise(
 1292045                    ConnectionQualityChanged,
 1292046                    new ConnectionQualityChangedEventArgs(quality, participant),
 1292047                    nameof(ConnectionQualityChanged)
 1292048                )
 1292049            );
 1292050        }
 2051
 2052        private void HandleDataPacketReceived(Proto.DataPacketReceived evt)
 17262053        {
 17262054            if (evt == null)
 02055                return;
 2056
 17262057            var participant = GetParticipantByIdentity(evt.ParticipantIdentity ?? "");
 17262058            var kind = evt.Kind;
 17262059            byte[] data = Array.Empty<byte>();
 17262060            string topic = string.Empty;
 2061
 17262062            if (evt.ValueCase == Proto.DataPacketReceived.ValueOneofCase.User && evt.User != null)
 17252063            {
 17252064                topic = evt.User.Topic ?? string.Empty;
 2065
 2066                // Copy data from native memory (block copy: this is the FFI callback thread)
 17252067                var bufferInfo = evt.User.Data?.Data;
 17252068                if (bufferInfo != null && bufferInfo.DataLen > 0)
 17242069                {
 17242070                    data = new byte[bufferInfo.DataLen];
 17242071                    Marshal.Copy((IntPtr)bufferInfo.DataPtr, data, 0, (int)bufferInfo.DataLen);
 17242072                }
 2073
 2074                // Release the native buffer whether or not it had data
 17252075                if (evt.User.Data?.Handle != null)
 17252076                {
 17252077                    FfiHandle.FromId(evt.User.Data.Handle.Id).Dispose();
 17252078                }
 2079
 17252080                DispatchEvent(() =>
 17252081                    Raise(
 17252082                        DataReceived,
 17252083                        new DataReceivedEventArgs(data, participant, kind, topic),
 17252084                        nameof(DataReceived)
 17252085                    )
 17252086                );
 17252087            }
 12088            else if (
 12089                evt.ValueCase == Proto.DataPacketReceived.ValueOneofCase.SipDtmf
 12090                && evt.SipDtmf != null
 12091            )
 12092            {
 2093                // Handle SIP DTMF
 12094                if (participant is RemoteParticipant remoteParticipant)
 12095                {
 12096                    DispatchEvent(() =>
 12097                        Raise(
 12098                            SipDtmfReceived,
 12099                            new SipDtmfReceivedEventArgs(
 12100                                evt.SipDtmf.Code,
 12101                                evt.SipDtmf.Digit,
 12102                                remoteParticipant
 12103                            ),
 12104                            nameof(SipDtmfReceived)
 12105                        )
 12106                    );
 12107                }
 12108            }
 17262109        }
 2110
 2111        private void HandleRoomMetadataChanged(Proto.RoomMetadataChanged evt)
 292112        {
 292113            if (evt == null)
 02114                return;
 2115
 292116            Metadata = evt.Metadata ?? string.Empty;
 582117            DispatchEvent(() => Raise(RoomMetadataChanged, Metadata, nameof(RoomMetadataChanged)));
 292118        }
 2119
 2120        private void HandleParticipantMetadataChanged(Proto.ParticipantMetadataChanged evt)
 102121        {
 102122            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02123                return;
 2124
 102125            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 102126            if (participant != null)
 102127            {
 102128                var updatedInfo = participant._info;
 102129                updatedInfo.Metadata = evt.Metadata ?? string.Empty;
 102130                participant.UpdateInfo(updatedInfo);
 2131
 102132                DispatchEvent(() =>
 102133                    Raise(
 102134                        ParticipantMetadataChanged,
 102135                        participant,
 102136                        nameof(ParticipantMetadataChanged)
 102137                    )
 102138                );
 102139            }
 102140        }
 2141
 2142        private void HandleParticipantNameChanged(Proto.ParticipantNameChanged evt)
 22143        {
 22144            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02145                return;
 2146
 22147            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 22148            if (participant != null)
 22149            {
 22150                var updatedInfo = participant._info;
 22151                updatedInfo.Name = evt.Name ?? string.Empty;
 22152                participant.UpdateInfo(updatedInfo);
 2153
 22154                DispatchEvent(() =>
 22155                    Raise(ParticipantNameChanged, participant, nameof(ParticipantNameChanged))
 22156                );
 22157            }
 22158        }
 2159
 2160        private void HandleParticipantAttributesChanged(Proto.ParticipantAttributesChanged evt)
 42161        {
 42162            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02163                return;
 2164
 42165            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 42166            if (participant != null)
 42167            {
 42168                var attributes = new Dictionary<string, string>();
 242169                foreach (var attr in evt.Attributes)
 62170                {
 62171                    attributes[attr.Key] = attr.Value;
 62172                }
 2173
 2174                // Keep Participant.Attributes current, like the Node and Python SDKs
 42175                participant._info.Attributes.Clear();
 42176                participant._info.Attributes.Add(attributes);
 2177
 42178                var changedAttributes = new Dictionary<string, string>();
 242179                foreach (var attr in evt.ChangedAttributes)
 62180                {
 62181                    changedAttributes[attr.Key] = attr.Value;
 62182                }
 2183
 42184                DispatchEvent(() =>
 42185                    Raise(
 42186                        ParticipantAttributesChanged,
 42187                        new ParticipantAttributesChangedEventArgs(
 42188                            participant,
 42189                            attributes,
 42190                            changedAttributes
 42191                        ),
 42192                        nameof(ParticipantAttributesChanged)
 42193                    )
 42194                );
 42195            }
 42196        }
 2197
 2198        private void HandleParticipantEncryptionStatusChanged(
 2199            Proto.ParticipantEncryptionStatusChanged evt
 2200        )
 142201        {
 142202            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02203                return;
 2204
 142205            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 142206            if (participant != null)
 142207            {
 142208                DispatchEvent(() =>
 142209                    Raise(
 142210                        ParticipantEncryptionStatusChanged,
 142211                        new ParticipantEncryptionStatusChangedEventArgs(
 142212                            participant,
 142213                            evt.IsEncrypted
 142214                        ),
 142215                        nameof(ParticipantEncryptionStatusChanged)
 142216                    )
 142217                );
 142218            }
 142219        }
 2220
 2221        private void HandleTrackSubscriptionFailed(Proto.TrackSubscriptionFailed evt)
 22222        {
 22223            if (
 22224                string.IsNullOrEmpty(evt?.ParticipantIdentity) || string.IsNullOrEmpty(evt.TrackSid)
 22225            )
 02226                return;
 2227
 2228            RemoteParticipant? participant;
 22229            lock (_lock)
 22230            {
 22231                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 12232                    return;
 12233            }
 2234
 12235            DispatchEvent(() =>
 12236                Raise(
 12237                    TrackSubscriptionFailed,
 12238                    new TrackSubscriptionFailedEventArgs(evt.TrackSid, participant, evt.Error),
 12239                    nameof(TrackSubscriptionFailed)
 12240                )
 12241            );
 22242        }
 2243
 2244        private void HandleRoomUpdated(Proto.RoomInfo evt)
 372245        {
 372246            if (evt == null)
 02247                return;
 2248
 372249            UpdateFromInfo(evt);
 742250            DispatchEvent(() => Raise(RoomUpdated, evt, nameof(RoomUpdated)));
 372251        }
 2252
 2253        private void HandleRoomSidChanged(Proto.RoomSidChanged evt)
 4512254        {
 4512255            if (string.IsNullOrEmpty(evt?.Sid))
 02256                return;
 2257
 4512258            Sid = evt.Sid;
 9022259            DispatchEvent(() => Raise(RoomSidChanged, evt.Sid, nameof(RoomSidChanged)));
 4512260        }
 2261
 2262        private void HandleMoved(Proto.RoomInfo evt)
 12263        {
 12264            if (evt == null)
 02265                return;
 2266
 12267            UpdateFromInfo(evt);
 22268            DispatchEvent(() => Raise(Moved, evt, nameof(Moved)));
 12269        }
 2270
 2271        private void HandleChatMessage(Proto.ChatMessageReceived evt)
 22272        {
 22273            if (evt?.Message == null)
 02274                return;
 2275
 22276            var participant = GetParticipantByIdentity(evt.ParticipantIdentity ?? "");
 2277
 22278            DispatchEvent(() =>
 22279                Raise(
 22280                    ChatMessageReceived,
 22281                    new ChatMessageReceivedEventArgs(evt.Message, participant),
 22282                    nameof(ChatMessageReceived)
 22283                )
 22284            );
 22285        }
 2286
 2287        private void HandleE2EEStateChanged(Proto.E2eeStateChanged evt)
 172288        {
 172289            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02290                return;
 2291
 172292            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 172293            if (participant != null)
 172294            {
 172295                DispatchEvent(() =>
 172296                    Raise(
 172297                        E2EEStateChanged,
 172298                        new E2EEStateChangedEventArgs(participant, evt.State),
 172299                        nameof(E2EEStateChanged)
 172300                    )
 172301                );
 172302            }
 172303        }
 2304
 2305        private void HandleTranscriptionReceived(Proto.TranscriptionReceived evt)
 12306        {
 12307            if (evt == null)
 02308                return;
 2309
 12310            var participant = GetParticipantByIdentity(evt.ParticipantIdentity ?? "");
 12311            var segments = new List<Proto.TranscriptionSegment>(evt.Segments);
 2312
 12313            DispatchEvent(() =>
 12314                Raise(
 12315                    TranscriptionReceived,
 12316                    new TranscriptionReceivedEventArgs(participant, evt.TrackSid, segments),
 12317                    nameof(TranscriptionReceived)
 12318                )
 12319            );
 12320        }
 2321
 2322        private void HandleTokenRefreshed(Proto.TokenRefreshed evt)
 4872323        {
 4872324            if (string.IsNullOrEmpty(evt?.Token))
 02325                return;
 2326
 9742327            DispatchEvent(() => Raise(TokenRefreshed, evt.Token, nameof(TokenRefreshed)));
 4872328        }
 2329
 2330        private Participant? GetParticipantByIdentity(string identity)
 30512331        {
 30512332            if (string.IsNullOrEmpty(identity))
 02333                return null;
 2334
 2335            // Check if it's the local participant
 30512336            if (LocalParticipant?.Identity == identity)
 8402337                return LocalParticipant;
 2338
 2339            // Check remote participants
 22112340            lock (_lock)
 22112341            {
 22112342                return _remoteParticipants.TryGetValue(identity, out var participant)
 22112343                    ? participant
 22112344                    : null;
 2345            }
 30512346        }
 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)
 732352        {
 732353            var nativeReader = FfiHandle.FromId(evt.Reader.Handle.Id);
 732354            var info = evt.Reader.Info;
 732355            if (!_streamHandlers.TryGetTextStreamHandler(info.Topic, out var handler))
 222356            {
 222357                nativeReader.Dispose();
 222358                return;
 2359            }
 2360
 512361            var reader = new TextStreamReader(
 512362                info,
 512363                evt.ParticipantIdentity,
 512364                ended =>
 512365                {
 512366                    lock (_lock)
 512367                    {
 512368                        if (
 512369                            _textStreamReaders.TryGetValue(ended.Info.StreamId, out var current)
 512370                            && current == ended
 512371                        )
 512372                            _textStreamReaders.Remove(ended.Info.StreamId);
 512373                    }
 512374                }
 512375            );
 512376            lock (_lock)
 512377            {
 512378                _textStreamReaders[info.StreamId] = reader;
 512379            }
 512380            RunStreamHandler(() =>
 512381            {
 512382                try
 512383                {
 512384                    reader.Start(nativeReader);
 512385                }
 02386                catch (Exception ex)
 02387                {
 02388                    reader.Fail(
 02389                        new StreamException($"Could not read the stream: {ex.Message}", ex)
 02390                    );
 02391                }
 512392                handler(reader, evt.ParticipantIdentity);
 1022393            });
 732394        }
 2395
 2396        private void HandleByteStreamOpened(Proto.ByteStreamOpened evt)
 382397        {
 382398            var nativeReader = FfiHandle.FromId(evt.Reader.Handle.Id);
 382399            var info = evt.Reader.Info;
 382400            if (!_streamHandlers.TryGetByteStreamHandler(info.Topic, out var handler))
 202401            {
 202402                nativeReader.Dispose();
 202403                return;
 2404            }
 2405
 182406            var reader = new ByteStreamReader(
 182407                info,
 182408                evt.ParticipantIdentity,
 182409                ended =>
 182410                {
 182411                    lock (_lock)
 182412                    {
 182413                        if (
 182414                            _byteStreamReaders.TryGetValue(ended.Info.StreamId, out var current)
 182415                            && current == ended
 182416                        )
 182417                            _byteStreamReaders.Remove(ended.Info.StreamId);
 182418                    }
 182419                }
 182420            );
 182421            lock (_lock)
 182422            {
 182423                _byteStreamReaders[info.StreamId] = reader;
 182424            }
 182425            RunStreamHandler(() =>
 182426            {
 182427                try
 182428                {
 182429                    reader.Start(nativeReader);
 182430                }
 02431                catch (Exception ex)
 02432                {
 02433                    reader.Fail(
 02434                        new StreamException($"Could not read the stream: {ex.Message}", ex)
 02435                    );
 02436                }
 182437                handler(reader, evt.ParticipantIdentity);
 362438            });
 382439        }
 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)
 692445        {
 692446            _ = Task.Run(() =>
 692447            {
 692448                try
 692449                {
 692450                    dispatch();
 692451                }
 02452                catch (Exception ex)
 02453                {
 02454                    Console.Error.WriteLine($"[ERROR] Data stream handler exception: {ex}");
 02455                }
 1382456            });
 692457        }
 2458
 2459        private void HandleParticipantPermissionChanged(Proto.ParticipantPermissionChanged evt)
 22460        {
 22461            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02462                return;
 2463
 22464            var participant = GetParticipantByIdentity(evt.ParticipantIdentity);
 22465            if (participant == null)
 02466                return;
 2467
 22468            var permissions = evt.Permission;
 22469            participant._info.Permission = permissions;
 22470            DispatchEvent(() =>
 22471                Raise(
 22472                    ParticipantPermissionsChanged,
 22473                    new ParticipantPermissionsChangedEventArgs(participant, permissions),
 22474                    nameof(ParticipantPermissionsChanged)
 22475                )
 22476            );
 22477        }
 2478
 2479        private void HandleParticipantActive(Proto.ParticipantActive evt)
 1992480        {
 1992481            if (string.IsNullOrEmpty(evt?.ParticipantIdentity))
 02482                return;
 2483
 2484            RemoteParticipant? participant;
 1992485            lock (_lock)
 1992486            {
 1992487                if (!_remoteParticipants.TryGetValue(evt.ParticipantIdentity, out participant))
 02488                    return;
 1992489            }
 2490
 1992491            participant._info.State = Proto.ParticipantState.Active;
 3982492            DispatchEvent(() => Raise(ParticipantActive, participant, nameof(ParticipantActive)));
 1992493        }
 2494
 2495        private void HandleParticipantsUpdated(Proto.ParticipantsUpdated evt)
 9742496        {
 9742497            if (evt == null)
 02498                return;
 2499
 2500            // Bulk refresh of participant infos; no public event, like the Node and Python SDKs
 51662501            foreach (var info in evt.Participants)
 11222502            {
 11222503                if (info == null)
 02504                    continue;
 11222505                GetParticipantByIdentity(info.Identity)?.UpdateInfo(info);
 11222506            }
 9742507        }
 2508
 2509        private void HandleLocalTrackRepublished(Proto.LocalTrackRepublished evt)
 272510        {
 272511            if (
 272512                LocalParticipant == null
 272513                || string.IsNullOrEmpty(evt?.PreviousSid)
 272514                || evt.Info == null
 272515            )
 02516                return;
 2517
 272518            DispatchEvent(async () =>
 272519            {
 272520                var localParticipant = LocalParticipant;
 272521                if (localParticipant == null)
 02522                    return;
 272523
 272524                // Protected by Room.FfiEventLock, like the unpublish bookkeeping.
 272525                LocalTrackPublication? publication;
 272526                await _ffiEventLock.WaitAsync();
 272527                try
 272528                {
 272529                    publication = localParticipant.RepublishTrackPublication(
 272530                        evt.PreviousSid,
 272531                        evt.Info
 272532                    );
 272533                }
 272534                finally
 272535                {
 272536                    _ffiEventLock.Release();
 272537                }
 272538
 272539                if (publication == null)
 02540                {
 02541                    Console.Error.WriteLine(
 02542                        $"[WARN] RoomEvent.LocalTrackRepublished: previous publication not found: {evt.PreviousSid}"
 02543                    );
 02544                    return;
 272545                }
 272546
 272547                Raise(
 272548                    LocalTrackRepublished,
 272549                    new LocalTrackRepublishedEventArgs(
 272550                        publication,
 272551                        evt.PreviousSid,
 272552                        localParticipant
 272553                    ),
 272554                    nameof(LocalTrackRepublished)
 272555                );
 542556            });
 272557        }
 2558
 2559        private void HandleDataTrackPublished(Proto.DataTrackPublished evt)
 32560        {
 32561            if (evt?.Track?.Handle == null || evt.Track.Info == null)
 02562                return;
 2563
 32564            var track = new RemoteDataTrack(evt.Track);
 32565            lock (_lock)
 32566            {
 32567                _remoteDataTracks[track.Info.Sid] = track;
 32568            }
 2569
 62570            DispatchEvent(() => Raise(DataTrackPublished, track, nameof(DataTrackPublished)));
 32571        }
 2572
 2573        private void HandleDataTrackUnpublished(Proto.DataTrackUnpublished evt)
 22574        {
 22575            if (string.IsNullOrEmpty(evt?.Sid))
 02576                return;
 2577
 2578            RemoteDataTrack? track;
 22579            lock (_lock)
 22580            {
 22581                _remoteDataTracks.Remove(evt.Sid, out track);
 22582            }
 2583
 22584            DispatchEvent(() =>
 22585                Raise(
 22586                    DataTrackUnpublished,
 22587                    new DataTrackUnpublishedEventArgs(evt.Sid, track),
 22588                    nameof(DataTrackUnpublished)
 22589                )
 22590            );
 22591        }
 2592
 2593        private void HandleDataChannelLowThresholdChanged(
 2594            Proto.DataChannelBufferedAmountLowThresholdChanged evt
 2595        )
 12596        {
 12597            if (evt == null)
 02598                return;
 2599
 12600            DispatchEvent(() =>
 12601                Raise(
 12602                    DataChannelBufferedAmountLowThresholdChanged,
 12603                    new DataChannelBufferedAmountLowThresholdChangedEventArgs(
 12604                        evt.Kind,
 12605                        evt.Threshold
 12606                    ),
 12607                    nameof(DataChannelBufferedAmountLowThresholdChanged)
 12608                )
 12609            );
 12610        }
 2611
 2612        private void CleanupOnDisconnect(Proto.DisconnectReason reason)
 8452613        {
 8452614            if (Interlocked.Exchange(ref _cleanedUp, 1) == 1)
 3942615                return;
 2616
 2617            int generation;
 4512618            var drain = false;
 4512619            var roomHandle = _roomHandle;
 4512620            lock (_connectionLock)
 4512621            {
 4512622                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
 4512625                if (roomHandle != null && !_endedStreams.Remove(roomHandle.HandleId))
 3972626                    drain = _endedRoomHandles.Add(roomHandle.HandleId);
 4512627            }
 2628
 2629            // From here on IsConnected is false
 4512630            _roomHandle = null;
 4512631            if (drain)
 3972632                StopDrainingAfterTimeout(roomHandle!.HandleId);
 2633
 4512634            UpdateConnectionState(Proto.ConnectionState.ConnDisconnected);
 9022635            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
 4512639            DispatchEvent(() =>
 4512640            {
 4512641                List<TextStreamReader> textReaders;
 4512642                List<ByteStreamReader> byteReaders;
 4512643                lock (_connectionLock)
 4512644                {
 4512645                    // ConnectAsync was called again meanwhile: that connection already cleared this
 4512646                    // state, and the listener and participants are now its own
 4512647                    if (generation != _connectionGeneration)
 02648                        return;
 4512649
 4512650                    ClearConnectionState(out textReaders, out byteReaders);
 4512651                }
 4512652                FailStreamReaders(textReaders, byteReaders);
 4512653                StopListeningIfIdle();
 9022654            });
 2655
 4512656            roomHandle?.Dispose();
 8452657        }
 2658
 2659        // Caller holds _connectionLock
 2660        private void ClearConnectionState(
 2661            out List<TextStreamReader> textReaders,
 2662            out List<ByteStreamReader> byteReaders
 2663        )
 9102664        {
 9102665            textReaders = new List<TextStreamReader>();
 9102666            byteReaders = new List<ByteStreamReader>();
 9102667            lock (_lock)
 9102668            {
 9102669                _remoteParticipants.Clear();
 9102670                _departedParticipants.Clear();
 9102671                _departureOrder.Clear();
 9102672                textReaders.AddRange(_textStreamReaders.Values);
 9102673                byteReaders.AddRange(_byteStreamReaders.Values);
 9102674                _textStreamReaders.Clear();
 9102675                _byteStreamReaders.Clear();
 9102676                _remoteDataTracks.Clear();
 9102677            }
 2678
 9102679            LocalParticipant?.CancelPendingSubscriptionWaits();
 9102680            LocalParticipant = null;
 9102681        }
 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        )
 9102688        {
 9102689            if (textReaders.Count == 0 && byteReaders.Count == 0)
 9102690                return;
 02691            var error = new StreamException("The room disconnected before the stream was closed");
 02692            foreach (var reader in textReaders)
 02693                reader.Fail(error);
 02694            foreach (var reader in byteReaders)
 02695                reader.Fail(error);
 9102696        }
 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)
 124942701        {
 124942702            lock (_connectionLock)
 124942703            {
 124942704                if (!_endedRoomHandles.Contains(roomEvent.RoomHandle))
 120972705                    return; // another room's event
 3972706            }
 2707
 3972708            ReleaseOwnedHandles(roomEvent);
 3972709            if (roomEvent.MessageCase == RoomEvent.MessageOneofCase.Eos)
 3972710                StopDraining(roomEvent.RoomHandle);
 124942711        }
 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)
 4112717        {
 4112718            var handle = roomEvent.MessageCase switch
 4112719            {
 22720                RoomEvent.MessageOneofCase.ParticipantConnected => roomEvent
 22721                    .ParticipantConnected
 22722                    .Info
 22723                    ?.Handle,
 22724                RoomEvent.MessageOneofCase.TrackPublished => roomEvent
 22725                    .TrackPublished
 22726                    .Publication
 22727                    ?.Handle,
 22728                RoomEvent.MessageOneofCase.TrackSubscribed => roomEvent
 22729                    .TrackSubscribed
 22730                    .Track
 22731                    ?.Handle,
 22732                RoomEvent.MessageOneofCase.DataPacketReceived => roomEvent
 22733                    .DataPacketReceived
 22734                    .User
 22735                    ?.Data
 22736                    ?.Handle,
 22737                RoomEvent.MessageOneofCase.DataTrackPublished => roomEvent
 22738                    .DataTrackPublished
 22739                    .Track
 22740                    ?.Handle,
 22741                RoomEvent.MessageOneofCase.TextStreamOpened => roomEvent
 22742                    .TextStreamOpened
 22743                    .Reader
 22744                    ?.Handle,
 22745                RoomEvent.MessageOneofCase.ByteStreamOpened => roomEvent
 22746                    .ByteStreamOpened
 22747                    .Reader
 22748                    ?.Handle,
 3972749                _ => null,
 4112750            };
 4112751            if (handle != null && handle.Id != FfiHandle.InvalidHandle)
 72752                FfiHandle.FromId(handle.Id).Dispose();
 4112753        }
 2754
 2755        private void EndOfStreamBeforeCleanup(ulong roomHandleId)
 542756        {
 2757            bool draining;
 542758            lock (_connectionLock)
 542759            {
 542760                draining = _endedRoomHandles.Contains(roomHandleId);
 542761                if (!draining)
 542762                    _endedStreams.Add(roomHandleId);
 542763            }
 542764            if (draining)
 02765                StopDraining(roomHandleId);
 542766        }
 2767
 2768        private void StopDraining(ulong roomHandleId)
 6072769        {
 6072770            lock (_connectionLock)
 6072771            {
 6072772                if (!_endedRoomHandles.Remove(roomHandleId))
 2102773                    return;
 3972774            }
 3972775            StopListeningIfIdle();
 6072776        }
 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)
 3972782        {
 3972783            var room = new WeakReference<Room>(this);
 3972784            _ = Task.Delay(EndedConnectionDrainTimeout)
 3972785                .ContinueWith(
 3972786                    _ =>
 3882787                    {
 3882788                        if (room.TryGetTarget(out var target))
 2102789                            target.StopDraining(roomHandleId);
 3882790                    },
 3972791                    TaskScheduler.Default
 3972792                );
 3972793        }
 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()
 12902798        {
 12902799            lock (_connectionLock)
 12902800            {
 12902801                if (
 12902802                    _roomHandle == null
 12902803                    && Volatile.Read(ref _connecting) == 0
 12902804                    && _endedRoomHandles.Count == 0
 12902805                )
 11872806                    FfiClient.Instance.EventReceived -= OnFfiEvent;
 12902807            }
 12902808        }
 2809
 2810        // For a ConnectAsync that failed: no connection of its own to wait for
 2811        private void StopListeningUnlessDraining()
 82812        {
 82813            lock (_connectionLock)
 82814            {
 82815                if (_endedRoomHandles.Count == 0)
 82816                    FfiClient.Instance.EventReceived -= OnFfiEvent;
 82817            }
 82818        }
 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()
 4532825        {
 4532826            if (_disposed)
 112827                return;
 4422828            _disposed = true;
 2829
 2830            // Disconnect while still listening, so the teardown events (LocalTrackUnpublished,
 2831            // TrackUnsubscribed, ParticipantDisconnected...) are delivered like DisconnectAsync does
 4422832            if (IsConnected)
 202833            {
 2834                try
 202835                {
 202836                    Disconnect();
 202837                }
 02838                catch
 02839                {
 2840                    // Ignore errors during disposal
 02841                }
 202842            }
 2843
 4422844            StopListeningIfIdle();
 4422845            _roomHandle?.Dispose();
 4532846        }
 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

.ctor()
.cctor()
get_FfiEventLock()
get_E2EEManager()
get_IsConnected()
get_RemoteParticipants()
get_RemoteDataTracks()
RegisterTextStreamHandler(System.String,LiveKit.Rtc.TextStreamHandler)
UnregisterTextStreamHandler(System.String)
RegisterByteStreamHandler(System.String,LiveKit.Rtc.ByteStreamHandler)
UnregisterByteStreamHandler(System.String)
Raise(System.EventHandler`1<TArgs>,TArgs,System.String)
Raise(System.EventHandler,System.String)
DispatchEvent(System.Action)
DispatchEvent(System.Func`1<System.Threading.Tasks.Task>)
UpdateConnectionState(LiveKit.Proto.ConnectionState)
ConnectAsync()
ConnectCoreAsync()
AbandonConnectAsync()
ReleaseAbandonedConnectionAsync()
DisconnectAsync()
DisconnectCoreAsync()
SimulateScenarioAsync()
GetRtcStatsAsync()
Disconnect()
UpdateFromInfo(LiveKit.Proto.RoomInfo)
OnFfiEvent(System.Object,LiveKit.Proto.FfiEvent)
HandleRoomEvent(LiveKit.Proto.RoomEvent)
HandleParticipantConnected(LiveKit.Proto.ParticipantConnected)
HandleParticipantDisconnected(LiveKit.Proto.ParticipantDisconnected)
RememberDeparture(System.String)
FindRemoteParticipant(System.String,System.Boolean&)
HandleLocalTrackPublished(LiveKit.Proto.LocalTrackPublished)
HandleLocalTrackUnpublished(LiveKit.Proto.LocalTrackUnpublished)
HandleLocalTrackSubscribed(LiveKit.Proto.LocalTrackSubscribed)
HandleTrackPublished(LiveKit.Proto.TrackPublished)
HandleTrackUnpublished(LiveKit.Proto.TrackUnpublished)
HandleTrackSubscribed(LiveKit.Proto.TrackSubscribed)
Release()
Drop()
HandleTrackUnsubscribed(LiveKit.Proto.TrackUnsubscribed)
HandleTrackMuted(LiveKit.Proto.TrackMuted)
HandleTrackUnmuted(LiveKit.Proto.TrackUnmuted)
HandleTrackMuteChanged(System.String,System.String,System.Boolean)
HandleActiveSpeakersChanged(LiveKit.Proto.ActiveSpeakersChanged)
HandleConnectionQualityChanged(LiveKit.Proto.ConnectionQualityChanged)
HandleDataPacketReceived(LiveKit.Proto.DataPacketReceived)
HandleRoomMetadataChanged(LiveKit.Proto.RoomMetadataChanged)
HandleParticipantMetadataChanged(LiveKit.Proto.ParticipantMetadataChanged)
HandleParticipantNameChanged(LiveKit.Proto.ParticipantNameChanged)
HandleParticipantAttributesChanged(LiveKit.Proto.ParticipantAttributesChanged)
HandleParticipantEncryptionStatusChanged(LiveKit.Proto.ParticipantEncryptionStatusChanged)
HandleTrackSubscriptionFailed(LiveKit.Proto.TrackSubscriptionFailed)
HandleRoomUpdated(LiveKit.Proto.RoomInfo)
HandleRoomSidChanged(LiveKit.Proto.RoomSidChanged)
HandleMoved(LiveKit.Proto.RoomInfo)
HandleChatMessage(LiveKit.Proto.ChatMessageReceived)
HandleE2EEStateChanged(LiveKit.Proto.E2eeStateChanged)
HandleTranscriptionReceived(LiveKit.Proto.TranscriptionReceived)
HandleTokenRefreshed(LiveKit.Proto.TokenRefreshed)
GetParticipantByIdentity(System.String)
HandleTextStreamOpened(LiveKit.Proto.TextStreamOpened)
HandleByteStreamOpened(LiveKit.Proto.ByteStreamOpened)
RunStreamHandler(System.Action)
HandleParticipantPermissionChanged(LiveKit.Proto.ParticipantPermissionChanged)
HandleParticipantActive(LiveKit.Proto.ParticipantActive)
HandleParticipantsUpdated(LiveKit.Proto.ParticipantsUpdated)
HandleLocalTrackRepublished(LiveKit.Proto.LocalTrackRepublished)
HandleDataTrackPublished(LiveKit.Proto.DataTrackPublished)
HandleDataTrackUnpublished(LiveKit.Proto.DataTrackUnpublished)
HandleDataChannelLowThresholdChanged(LiveKit.Proto.DataChannelBufferedAmountLowThresholdChanged)
CleanupOnDisconnect(LiveKit.Proto.DisconnectReason)
ClearConnectionState(System.Collections.Generic.List`1<LiveKit.Rtc.TextStreamReader>&,System.Collections.Generic.List`1<LiveKit.Rtc.ByteStreamReader>&)
FailStreamReaders(System.Collections.Generic.List`1<LiveKit.Rtc.TextStreamReader>,System.Collections.Generic.List`1<LiveKit.Rtc.ByteStreamReader>)
DrainEndedConnection(LiveKit.Proto.RoomEvent)
ReleaseOwnedHandles(LiveKit.Proto.RoomEvent)
EndOfStreamBeforeCleanup(System.UInt64)
StopDraining(System.UInt64)
StopDrainingAfterTimeout(System.UInt64)
StopListeningIfIdle()
StopListeningUnlessDraining()
Dispose()