< Summary

Information
Class: LiveKit.Rtc.RemoteParticipant
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/Participant.cs
Line coverage
93%
Covered lines: 45
Uncovered lines: 3
Coverable lines: 48
Total lines: 1836
Line coverage: 93.7%
Branch coverage
78%
Covered branches: 11
Total branches: 14
Branch coverage: 78.5%
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%
MarkUnsubscribedBeforeSubscribed(...)75%8888.88%
TakeUnsubscribedBeforeSubscribed(...)100%22100%
AddPublication(...)75%4492.3%
RemovePublication(...)100%11100%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Concurrent;
 5using System.Collections.Generic;
 6using System.ComponentModel;
 7using System.Diagnostics;
 8using System.Linq;
 9using System.Runtime.CompilerServices;
 10using System.Text;
 11using System.Threading;
 12using System.Threading.Tasks;
 13using LiveKit.Proto;
 14using LiveKit.Rtc.Internal;
 15
 16namespace LiveKit.Rtc
 17{
 18    /// <summary>
 19    /// Base class for participants in a room.
 20    /// </summary>
 21    public abstract class Participant
 22    {
 23        internal FfiHandle Handle { get; }
 24        internal Room Room { get; }
 25
 26        internal ParticipantInfo _info;
 27
 28        /// <summary>
 29        /// Participant session ID.
 30        /// </summary>
 31        public string Sid => _info.Sid;
 32
 33        /// <summary>
 34        /// Participant identity.
 35        /// </summary>
 36        public string Identity => _info.Identity;
 37
 38        /// <summary>
 39        /// Participant display name.
 40        /// </summary>
 41        public string Name => _info.Name;
 42
 43        /// <summary>
 44        /// Participant metadata.
 45        /// </summary>
 46        public string Metadata => _info.Metadata;
 47
 48        /// <summary>
 49        /// Kind of participant.
 50        /// </summary>
 51        public Proto.ParticipantKind Kind => _info.Kind;
 52
 53        /// <summary>
 54        /// The participant's permissions in the room, or null if the server has not sent them.
 55        /// Updated before <see cref="Room.ParticipantPermissionsChanged"/> is raised.
 56        /// </summary>
 57        public Proto.ParticipantPermission? Permissions => _info.Permission;
 58
 59        /// <summary>
 60        /// Participant attributes, as last reported by the server.
 61        /// </summary>
 62        public IReadOnlyDictionary<string, string> Attributes
 63        {
 64            get
 65            {
 66                var info = _info;
 67                return new Dictionary<string, string>(info.Attributes);
 68            }
 69        }
 70
 71        /// <summary>
 72        /// Connection state of the participant.
 73        /// </summary>
 74        public Proto.ParticipantState State => _info.State;
 75
 76        /// <summary>
 77        /// Why the participant left, set before <see cref="Room.ParticipantDisconnected"/> is raised.
 78        /// </summary>
 79        public Proto.DisconnectReason DisconnectReason => _info.DisconnectReason;
 80
 81        /// <summary>
 82        /// Track publications by this participant. The FFI callback thread mutates it, so every
 83        /// access goes through <see cref="PublicationsLock"/>.
 84        /// </summary>
 85        protected readonly Dictionary<string, TrackPublication> _trackPublications;
 86
 87        internal readonly object PublicationsLock = new object();
 88
 89        /// <summary>
 90        /// Gets all track publications by this participant (a snapshot).
 91        /// </summary>
 92        public IReadOnlyDictionary<string, TrackPublication> TrackPublications
 93        {
 94            get
 95            {
 96                lock (PublicationsLock)
 97                {
 98                    return new Dictionary<string, TrackPublication>(_trackPublications);
 99                }
 100            }
 101        }
 102
 103        internal Participant(FfiHandle handle, ParticipantInfo? info, Room room)
 104        {
 105            Handle = handle;
 106            Room = room;
 107            _info = info ?? new ParticipantInfo();
 108            _trackPublications = new Dictionary<string, TrackPublication>();
 109        }
 110
 111        internal void UpdateInfo(ParticipantInfo info)
 112        {
 113            _info = info;
 114        }
 115
 116        /// <summary>
 117        /// Gets a track publication by SID.
 118        /// </summary>
 119        /// <param name="sid">Track SID.</param>
 120        /// <returns>The track publication, or null if not found.</returns>
 121        public TrackPublication? GetTrackPublication(string sid)
 122        {
 123            lock (PublicationsLock)
 124            {
 125                return _trackPublications.TryGetValue(sid, out var pub) ? pub : null;
 126            }
 127        }
 128    }
 129
 130    /// <summary>
 131    /// Represents the local participant in the room.
 132    /// </summary>
 133    public class LocalParticipant : Participant
 134    {
 135        // Registered on user threads, read from the Task.Run that serves each invocation
 136        private readonly ConcurrentDictionary<string, RpcMethodHandler> _rpcHandlers =
 137            new ConcurrentDictionary<string, RpcMethodHandler>();
 138
 139        // LocalTrackPublished/Subscribed room events can be processed before PublishTrackAsync
 140        // has registered the publication (the FFI sends the callback first, but its continuation
 141        // runs on the thread pool). The event handlers wait here instead of polling.
 142        // Protected by Room.FfiEventLock.
 143        private readonly Dictionary<
 144            string,
 145            TaskCompletionSource<LocalTrackPublication>
 146        > _pendingPublicationWaiters =
 147            new Dictionary<string, TaskCompletionSource<LocalTrackPublication>>();
 148
 149        // Publications that UnpublishTrackAsync already removed, but whose
 150        // Room.LocalTrackUnpublished event has not arrived yet. The FFI may deliver the event after
 151        // UnpublishTrackAsync has already removed the publication from _trackPublications. This
 152        // collection allows the event to be raised with the proper LocalTrackPublication.
 153        // Protected by Room.FfiEventLock.
 154        private readonly Dictionary<
 155            string,
 156            LocalTrackPublication
 157        > _publicationsPendingUnpublishedEvent = new Dictionary<string, LocalTrackPublication>();
 158
 159        // Publications whose PublishTrackAsync was cancelled or timed out after the FFI published
 160        // them. ReconcileAbandonedPublishAsync unpublishes them; their room events are not raised
 161        // (the caller never got the publication), and nothing waits for their registration.
 162        // Protected by Room.FfiEventLock.
 163        private readonly HashSet<string> _abandonedPublications = new HashSet<string>();
 164
 165        internal LocalParticipant(FfiHandle handle, ParticipantInfo? info, Room room)
 166            : base(handle, info, room) { }
 167
 168        /// <summary>
 169        /// Resolves and removes the publication a LocalTrackUnpublished room event refers to,
 170        /// whether it is still in <see cref="Participant.TrackPublications"/> or was already
 171        /// removed by <see cref="UnpublishTrackAsync"/>. The caller must hold Room.FfiEventLock.
 172        /// </summary>
 173        /// <param name="trackSid">The SID of the unpublished track.</param>
 174        /// <returns>The publication, or null if the SID is unknown.</returns>
 175        internal LocalTrackPublication? TakeUnpublishedTrackPublication(string trackSid)
 176        {
 177            lock (PublicationsLock)
 178            {
 179                if (_trackPublications.Remove(trackSid, out var publication))
 180                    return publication as LocalTrackPublication;
 181            }
 182
 183            return _publicationsPendingUnpublishedEvent.Remove(trackSid, out var pending)
 184                ? pending
 185                : null;
 186        }
 187
 188        /// <summary>
 189        /// Returns the local publication with the given SID, waiting for
 190        /// <see cref="PublishTrackAsync"/> to register it if it has not yet. Null after the timeout.
 191        /// </summary>
 192        internal async Task<LocalTrackPublication?> WaitForPublicationAsync(
 193            string trackSid,
 194            TimeSpan timeout
 195        )
 196        {
 197            TaskCompletionSource<LocalTrackPublication> waiter;
 198            await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 199            try
 200            {
 201                if (_abandonedPublications.Contains(trackSid))
 202                    return null;
 203                lock (PublicationsLock)
 204                {
 205                    if (
 206                        _trackPublications.TryGetValue(trackSid, out var existing)
 207                        && existing is LocalTrackPublication found
 208                    )
 209                        return found;
 210                }
 211                // Registered and unpublished before the room's chain reached this event:
 212                // UnpublishTrackAsync handed the publication over to its LocalTrackUnpublished
 213                // event, which follows this one in the chain
 214                if (_publicationsPendingUnpublishedEvent.TryGetValue(trackSid, out var unpublished))
 215                    return unpublished;
 216                if (!_pendingPublicationWaiters.TryGetValue(trackSid, out waiter))
 217                {
 218                    waiter = new TaskCompletionSource<LocalTrackPublication>(
 219                        TaskCreationOptions.RunContinuationsAsynchronously
 220                    );
 221                    _pendingPublicationWaiters[trackSid] = waiter;
 222                }
 223            }
 224            finally
 225            {
 226                Room.FfiEventLock.Release();
 227            }
 228
 229            using var timeoutCts = new CancellationTokenSource(timeout);
 230            using (timeoutCts.Token.Register(() => waiter.TrySetCanceled()))
 231            {
 232                try
 233                {
 234                    return await waiter.Task.ConfigureAwait(false);
 235                }
 236                catch (OperationCanceledException)
 237                {
 238                    await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 239                    try
 240                    {
 241                        _pendingPublicationWaiters.Remove(trackSid);
 242                    }
 243                    finally
 244                    {
 245                        Room.FfiEventLock.Release();
 246                    }
 247                    return null;
 248                }
 249            }
 250        }
 251
 252        /// <summary>
 253        /// Records a publication whose <see cref="PublishTrackAsync"/> was abandoned, and wakes the
 254        /// room event handler waiting for its registration, which would otherwise stall the room's
 255        /// event chain until its timeout.
 256        /// </summary>
 257        private async Task MarkPublicationAbandonedAsync(string trackSid)
 258        {
 259            await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 260            try
 261            {
 262                _abandonedPublications.Add(trackSid);
 263                if (_pendingPublicationWaiters.Remove(trackSid, out var waiter))
 264                    waiter.TrySetCanceled();
 265            }
 266            finally
 267            {
 268                Room.FfiEventLock.Release();
 269            }
 270        }
 271
 272        /// <summary>
 273        /// Whether a room event refers to a publication whose <see cref="PublishTrackAsync"/> was
 274        /// abandoned: such events are dropped silently. <paramref name="forget"/> removes the record,
 275        /// for the last event of the publication (its unpublication).
 276        /// </summary>
 277        internal async Task<bool> IsAbandonedPublicationAsync(string trackSid, bool forget = false)
 278        {
 279            await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 280            try
 281            {
 282                return forget
 283                    ? _abandonedPublications.Remove(trackSid)
 284                    : _abandonedPublications.Contains(trackSid);
 285            }
 286            finally
 287            {
 288                Room.FfiEventLock.Release();
 289            }
 290        }
 291
 292        /// <summary>
 293        /// The room disconnected: nobody will subscribe to the local tracks anymore.
 294        /// </summary>
 295        internal void CancelPendingSubscriptionWaits()
 296        {
 297            foreach (var publication in TrackPublications.Values.OfType<LocalTrackPublication>())
 298            {
 299                publication.CancelFirstSubscription();
 300            }
 301        }
 302
 303        /// <summary>
 304        /// Applies a LocalTrackRepublished room event: the SDK re-published the track during a full
 305        /// reconnect and the server issued new SIDs. The existing publication object is updated in
 306        /// place (so cached references stay valid) and re-keyed under its new SID. The caller must
 307        /// hold Room.FfiEventLock.
 308        /// </summary>
 309        /// <param name="previousSid">The SID the publication had before the reconnect.</param>
 310        /// <param name="info">The new publication info.</param>
 311        /// <returns>The updated publication, or null if the previous SID is unknown.</returns>
 312        internal LocalTrackPublication? RepublishTrackPublication(
 313            string previousSid,
 314            TrackPublicationInfo info
 315        )
 316        {
 317            lock (PublicationsLock)
 318            {
 319                if (!_trackPublications.Remove(previousSid, out var existing))
 320                    return null;
 321                if (!(existing is LocalTrackPublication publication))
 322                    return null;
 323
 324                publication.UpdateInfo(info);
 325                _trackPublications[publication.Sid] = publication;
 326                // Keep the local-track invariant (track.Sid == publication.Sid) across the republish
 327                publication.Track?.UpdateSid(publication.Sid);
 328                return publication;
 329            }
 330        }
 331
 332        /// <summary>
 333        /// Publishes a track to the room.
 334        /// </summary>
 335        /// <param name="track">The track to publish.</param>
 336        /// <param name="options">Publication options.</param>
 337        /// <param name="cancellationToken">
 338        /// Cancels the publication. A track the native side publishes after the cancellation is unpublished
 339        /// in the background; a token that is already cancelled throws before anything is published.
 340        /// </param>
 341        /// <returns>The track publication.</returns>
 342        public async Task<LocalTrackPublication> PublishTrackAsync(
 343            LocalTrack track,
 344            TrackPublishOptions? options = null,
 345            CancellationToken cancellationToken = default
 346        )
 347        {
 348            options ??= new TrackPublishOptions();
 349            // Before any side effect: once requested, a publication that the cancellation abandons
 350            // has to be unpublished in the background
 351            cancellationToken.ThrowIfCancellationRequested();
 352
 353            var request = new FfiRequest
 354            {
 355                PublishTrack = new PublishTrackRequest
 356                {
 357                    LocalParticipantHandle = Handle.HandleId,
 358                    TrackHandle = track.Handle.HandleId,
 359                    Options = options.ToProto(),
 360                },
 361            };
 362
 363            var response = FfiClient.Instance.SendRequest(request);
 364
 365            if (response.PublishTrack == null)
 366                throw new InvalidOperationException("Invalid publish track response");
 367
 368            var asyncId = response.PublishTrack.AsyncId;
 369
 370            // Wait for publish callback (don't hold lock during wait)
 371            FfiEvent publishEvent;
 372            try
 373            {
 374                publishEvent = await FfiClient.Instance.WaitForEventAsync(
 375                    e =>
 376                        e.MessageCase == FfiEvent.MessageOneofCase.PublishTrack
 377                        && e.PublishTrack?.AsyncId == asyncId,
 378                    TimeSpan.FromSeconds(30),
 379                    cancellationToken
 380                );
 381            }
 382            catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
 383            {
 384                // The FFI may still publish the track; it would then be live on the server but
 385                // unknown to this SDK. Undo it when its callback arrives.
 386                _ = ReconcileAbandonedPublishAsync(asyncId);
 387                throw;
 388            }
 389
 390            var callback = publishEvent.PublishTrack!;
 391
 392            if (callback.HasError)
 393            {
 394                throw new RoomException($"Failed to publish track: {callback.Error}");
 395            }
 396
 397            var publication = callback.Publication;
 398            if (publication == null || publication.Info == null)
 399            {
 400                throw new RoomException("Publish callback has no publication");
 401            }
 402
 403            var localPublication = new LocalTrackPublication(
 404                FfiHandle.FromId(publication.Handle.Id),
 405                publication.Info,
 406                this
 407            );
 408
 409            localPublication.Track = track;
 410            // A freshly created local track reports "TR_unknown" until it is published
 411            track.UpdateSid(localPublication.Sid);
 412
 413            // Acquire lock only for modifying state (matches Node SDK pattern). Not cancellable:
 414            // the track is published, so it must be registered.
 415            await Room.FfiEventLock.WaitAsync();
 416            try
 417            {
 418                lock (PublicationsLock)
 419                {
 420                    _trackPublications[localPublication.Sid] = localPublication;
 421                }
 422                if (_pendingPublicationWaiters.Remove(localPublication.Sid, out var waiter))
 423                {
 424                    waiter.TrySetResult(localPublication);
 425                }
 426                return localPublication;
 427            }
 428            finally
 429            {
 430                // Release lock - now FFI events can be processed
 431                Room.FfiEventLock.Release();
 432            }
 433        }
 434
 435        private async Task ReconcileAbandonedPublishAsync(ulong asyncId)
 436        {
 437            try
 438            {
 439                var publishEvent = await FfiClient.Instance.WaitForEventAsync(
 440                    e =>
 441                        e.MessageCase == FfiEvent.MessageOneofCase.PublishTrack
 442                        && e.PublishTrack?.AsyncId == asyncId,
 443                    TimeSpan.FromSeconds(60)
 444                );
 445                var publication = publishEvent.PublishTrack?.Publication;
 446                if (publishEvent.PublishTrack?.HasError == true || publication?.Info == null)
 447                    return;
 448
 449                using var handle = FfiHandle.FromId(publication.Handle.Id);
 450                Console.Error.WriteLine(
 451                    $"[WARN] PublishTrackAsync was cancelled after track {publication.Info.Sid} was published: unpublish
 452                );
 453                await MarkPublicationAbandonedAsync(publication.Info.Sid).ConfigureAwait(false);
 454                await UnpublishTrackAsync(publication.Info.Sid).ConfigureAwait(false);
 455            }
 456            catch (Exception ex)
 457            {
 458                Console.Error.WriteLine(
 459                    $"[WARN] Could not reconcile a cancelled PublishTrackAsync: {ex.Message}"
 460                );
 461            }
 462        }
 463
 464        /// <summary>
 465        /// Unpublishes a track from the room.
 466        /// </summary>
 467        /// <param name="trackSid">The SID of the track to unpublish.</param>
 468        /// <param name="cancellationToken">
 469        /// Cancels the wait for the unpublication. A token that is already cancelled throws before the
 470        /// unpublication is requested.
 471        /// </param>
 472        /// <returns>A task that completes once the track is unpublished.</returns>
 473        public async Task UnpublishTrackAsync(
 474            string trackSid,
 475            CancellationToken cancellationToken = default
 476        )
 477        {
 478            // The FFI unwraps the SID conversion: anything but a "TR_..." SID panics the native
 479            // side, which terminates the process
 480            if (
 481                string.IsNullOrEmpty(trackSid)
 482                || !trackSid.StartsWith("TR_", StringComparison.Ordinal)
 483            )
 484                throw new ArgumentException(
 485                    $"'{trackSid}' is not a track SID (expected 'TR_...'), use publication.Sid",
 486                    nameof(trackSid)
 487                );
 488            cancellationToken.ThrowIfCancellationRequested();
 489
 490            var request = new FfiRequest
 491            {
 492                UnpublishTrack = new UnpublishTrackRequest
 493                {
 494                    LocalParticipantHandle = Handle.HandleId,
 495                    TrackSid = trackSid,
 496                    StopOnUnpublish = true,
 497                },
 498            };
 499
 500            var response = FfiClient.Instance.SendRequest(request);
 501
 502            if (response.UnpublishTrack == null)
 503                throw new InvalidOperationException("Invalid unpublish track response");
 504
 505            var asyncId = response.UnpublishTrack.AsyncId;
 506
 507            // Wait for unpublish callback (don't hold lock during wait)
 508            var unpublishEvent = await FfiClient.Instance.WaitForEventAsync(
 509                e =>
 510                    e.MessageCase == FfiEvent.MessageOneofCase.UnpublishTrack
 511                    && e.UnpublishTrack?.AsyncId == asyncId,
 512                TimeSpan.FromSeconds(10),
 513                cancellationToken
 514            );
 515
 516            var callback = unpublishEvent.UnpublishTrack!;
 517
 518            if (!string.IsNullOrEmpty(callback.Error))
 519            {
 520                throw new RoomException($"Failed to unpublish track: {callback.Error}");
 521            }
 522
 523            // Acquire lock only for modifying state (matches Node SDK pattern)
 524            await Room.FfiEventLock.WaitAsync(cancellationToken);
 525            try
 526            {
 527                // If the LocalTrackUnpublished room event has not been processed yet, hand the
 528                // publication over to it instead of dropping it, so the event can still be raised
 529                // with the publication after it leaves TrackPublications. If the room event was
 530                // processed first, it has already removed the publication and there is nothing to do.
 531                TrackPublication? removed;
 532                lock (PublicationsLock)
 533                {
 534                    _trackPublications.Remove(trackSid, out removed);
 535                }
 536                if (removed is LocalTrackPublication localPublication)
 537                {
 538                    _publicationsPendingUnpublishedEvent[trackSid] = localPublication;
 539                }
 540            }
 541            finally
 542            {
 543                // Release lock - now FFI events can be processed
 544                Room.FfiEventLock.Release();
 545            }
 546        }
 547
 548        /// <summary>
 549        /// Publishes data to the room.
 550        /// </summary>
 551        /// <param name="data">The data to publish.</param>
 552        /// <param name="options">Publish options.</param>
 553        /// <returns>A task that completes once the data has been sent.</returns>
 554        public async Task PublishDataAsync(byte[] data, DataPublishOptions? options = null)
 555        {
 556            options ??= new DataPublishOptions();
 557
 558            ulong asyncId;
 559
 560            unsafe
 561            {
 562                fixed (byte* dataPtr = data)
 563                {
 564                    var request = new FfiRequest
 565                    {
 566                        PublishData = new PublishDataRequest
 567                        {
 568                            LocalParticipantHandle = Handle.HandleId,
 569                            DataPtr = (ulong)dataPtr,
 570                            DataLen = (ulong)data.Length,
 571                            Reliable = options.Reliable,
 572                            Topic = options.Topic ?? string.Empty,
 573                        },
 574                    };
 575
 576                    if (options.DestinationIdentities != null)
 577                    {
 578                        request.PublishData.DestinationIdentities.AddRange(
 579                            options.DestinationIdentities
 580                        );
 581                    }
 582
 583                    var response = FfiClient.Instance.SendRequest(request);
 584                    asyncId = response.PublishData?.AsyncId ?? 0;
 585                }
 586            }
 587
 588            // Wait for publish callback (outside unsafe context)
 589            var publishEvent = await FfiClient.Instance.WaitForEventAsync(
 590                e =>
 591                    e.MessageCase == FfiEvent.MessageOneofCase.PublishData
 592                    && e.PublishData?.AsyncId == asyncId,
 593                TimeSpan.FromSeconds(30)
 594            );
 595
 596            if (publishEvent.PublishData?.HasError == true)
 597            {
 598                throw new RoomException(
 599                    $"Failed to publish data: {publishEvent.PublishData.Error}"
 600                );
 601            }
 602        }
 603
 604        /// <summary>
 605        /// Publishes a data track. Push frames on the returned track with
 606        /// <see cref="LocalDataTrack.TryPush"/>; remote participants receive it through
 607        /// <see cref="Room.DataTrackPublished"/>.
 608        /// </summary>
 609        /// <param name="name">
 610        /// The track name, used by other participants to identify it. Must not be empty and must be
 611        /// unique per publisher.
 612        /// </param>
 613        /// <param name="cancellationToken">
 614        /// Cancels the wait for the publication. A token that is already cancelled throws before the track
 615        /// is published.
 616        /// </param>
 617        /// <returns>The published data track.</returns>
 618        /// <exception cref="PublishDataTrackException">The track could not be published.</exception>
 619        public async Task<LocalDataTrack> PublishDataTrackAsync(
 620            string name,
 621            CancellationToken cancellationToken = default
 622        )
 623        {
 624            if (string.IsNullOrEmpty(name))
 625                throw new ArgumentException("Data track name must not be empty", nameof(name));
 626            cancellationToken.ThrowIfCancellationRequested();
 627
 628            var response = FfiClient.Instance.SendRequest(
 629                new FfiRequest
 630                {
 631                    PublishDataTrack = new PublishDataTrackRequest
 632                    {
 633                        LocalParticipantHandle = Handle.HandleId,
 634                        Options = new DataTrackOptions { Name = name },
 635                    },
 636                }
 637            );
 638
 639            if (response.PublishDataTrack == null)
 640                throw new InvalidOperationException("Invalid publish data track response");
 641
 642            var asyncId = response.PublishDataTrack.AsyncId;
 643
 644            var publishEvent = await FfiClient.Instance.WaitForEventAsync(
 645                e =>
 646                    e.MessageCase == FfiEvent.MessageOneofCase.PublishDataTrack
 647                    && e.PublishDataTrack?.AsyncId == asyncId,
 648                TimeSpan.FromSeconds(30),
 649                cancellationToken
 650            );
 651
 652            var callback = publishEvent.PublishDataTrack!;
 653            if (callback.ResultCase == PublishDataTrackCallback.ResultOneofCase.Error)
 654            {
 655                throw new PublishDataTrackException(callback.Error.Code, callback.Error.Message);
 656            }
 657            if (callback.Track?.Handle == null || callback.Track.Info == null)
 658            {
 659                throw new RoomException("Publish data track callback has no track");
 660            }
 661
 662            return new LocalDataTrack(callback.Track);
 663        }
 664
 665        /// <summary>
 666        /// Sets the buffered-amount-low threshold of the lossy or reliable data channel. The room
 667        /// raises <see cref="Room.DataChannelBufferedAmountLowThresholdChanged"/> once applied.
 668        /// </summary>
 669        /// <param name="threshold">The new threshold in bytes.</param>
 670        /// <param name="kind">The data channel to configure.</param>
 671        public void SetDataChannelBufferedAmountLowThreshold(
 672            ulong threshold,
 673            Proto.DataPacketKind kind
 674        )
 675        {
 676            FfiClient.Instance.SendRequest(
 677                new FfiRequest
 678                {
 679                    SetDataChannelBufferedAmountLowThreshold =
 680                        new SetDataChannelBufferedAmountLowThresholdRequest
 681                        {
 682                            LocalParticipantHandle = Handle.HandleId,
 683                            Threshold = threshold,
 684                            Kind = kind,
 685                        },
 686                }
 687            );
 688        }
 689
 690        /// <summary>
 691        /// Publishes SIP DTMF (Dual-Tone Multi-Frequency) tones to the room.
 692        /// </summary>
 693        /// <param name="code">The DTMF code.</param>
 694        /// <param name="digit">The DTMF digit as a string.</param>
 695        /// <param name="destinationIdentities">Optional destination participant identities.</param>
 696        /// <returns>A task that completes once the tones have been sent.</returns>
 697        public async Task PublishSipDtmfAsync(
 698            uint code,
 699            string digit,
 700            string[]? destinationIdentities = null
 701        )
 702        {
 703            var request = new FfiRequest
 704            {
 705                PublishSipDtmf = new PublishSipDtmfRequest
 706                {
 707                    LocalParticipantHandle = Handle.HandleId,
 708                    Code = code,
 709                    Digit = digit ?? string.Empty,
 710                },
 711            };
 712
 713            if (destinationIdentities != null)
 714            {
 715                request.PublishSipDtmf.DestinationIdentities.AddRange(destinationIdentities);
 716            }
 717
 718            var response = FfiClient.Instance.SendRequest(request);
 719            var asyncId = response.PublishSipDtmf?.AsyncId ?? 0;
 720
 721            var dtmfEvent = await FfiClient.Instance.WaitForEventAsync(
 722                e =>
 723                    e.MessageCase == FfiEvent.MessageOneofCase.PublishSipDtmf
 724                    && e.PublishSipDtmf?.AsyncId == asyncId,
 725                TimeSpan.FromSeconds(30)
 726            );
 727
 728            if (dtmfEvent.PublishSipDtmf?.HasError == true)
 729            {
 730                throw new RoomException(
 731                    $"Failed to publish SIP DTMF: {dtmfEvent.PublishSipDtmf.Error}"
 732                );
 733            }
 734        }
 735
 736        /// <summary>
 737        /// Publishes transcription data to the room.
 738        /// </summary>
 739        /// <param name="transcription">The transcription to publish.</param>
 740        /// <returns>A task that completes once the transcription has been sent.</returns>
 741        public async Task PublishTranscriptionAsync(Transcription transcription)
 742        {
 743            if (transcription == null)
 744                throw new ArgumentNullException(nameof(transcription));
 745
 746            var request = new FfiRequest
 747            {
 748                PublishTranscription = new PublishTranscriptionRequest
 749                {
 750                    LocalParticipantHandle = Handle.HandleId,
 751                    ParticipantIdentity = transcription.ParticipantIdentity,
 752                    TrackId = transcription.TrackSid,
 753                },
 754            };
 755
 756            foreach (var segment in transcription.Segments)
 757            {
 758                request.PublishTranscription.Segments.Add(segment);
 759            }
 760
 761            var response = FfiClient.Instance.SendRequest(request);
 762            var asyncId = response.PublishTranscription?.AsyncId ?? 0;
 763
 764            var transcriptionEvent = await FfiClient.Instance.WaitForEventAsync(
 765                e =>
 766                    e.MessageCase == FfiEvent.MessageOneofCase.PublishTranscription
 767                    && e.PublishTranscription?.AsyncId == asyncId,
 768                TimeSpan.FromSeconds(30)
 769            );
 770
 771            if (transcriptionEvent.PublishTranscription?.HasError == true)
 772            {
 773                throw new RoomException(
 774                    $"Failed to publish transcription: {transcriptionEvent.PublishTranscription.Error}"
 775                );
 776            }
 777        }
 778
 779        /// <summary>
 780        /// Sets the local participant's metadata.
 781        /// </summary>
 782        /// <param name="metadata">The new metadata.</param>
 783        /// <returns>A task that completes once the update has been sent.</returns>
 784        public async Task SetMetadataAsync(string metadata)
 785        {
 786            var request = new FfiRequest
 787            {
 788                SetLocalMetadata = new SetLocalMetadataRequest
 789                {
 790                    LocalParticipantHandle = Handle.HandleId,
 791                    Metadata = metadata,
 792                },
 793            };
 794
 795            var response = FfiClient.Instance.SendRequest(request);
 796            var asyncId = response.SetLocalMetadata?.AsyncId ?? 0;
 797
 798            // Wait for metadata update callback
 799            var metadataEvent = await FfiClient.Instance.WaitForEventAsync(
 800                e =>
 801                    e.MessageCase == FfiEvent.MessageOneofCase.SetLocalMetadata
 802                    && e.SetLocalMetadata?.AsyncId == asyncId,
 803                TimeSpan.FromSeconds(30)
 804            );
 805
 806            if (metadataEvent.SetLocalMetadata?.HasError == true)
 807            {
 808                throw new RoomException(
 809                    $"Failed to set metadata: {metadataEvent.SetLocalMetadata.Error}"
 810                );
 811            }
 812        }
 813
 814        /// <summary>
 815        /// Sets the local participant's name.
 816        /// </summary>
 817        /// <param name="name">The new name.</param>
 818        /// <returns>A task that completes once the update has been sent.</returns>
 819        public async Task SetNameAsync(string name)
 820        {
 821            var request = new FfiRequest
 822            {
 823                SetLocalName = new SetLocalNameRequest
 824                {
 825                    LocalParticipantHandle = Handle.HandleId,
 826                    Name = name,
 827                },
 828            };
 829
 830            var response = FfiClient.Instance.SendRequest(request);
 831            var asyncId = response.SetLocalName?.AsyncId ?? 0;
 832
 833            // Wait for name update callback
 834            var nameEvent = await FfiClient.Instance.WaitForEventAsync(
 835                e =>
 836                    e.MessageCase == FfiEvent.MessageOneofCase.SetLocalName
 837                    && e.SetLocalName?.AsyncId == asyncId,
 838                TimeSpan.FromSeconds(30)
 839            );
 840
 841            if (nameEvent.SetLocalName?.HasError == true)
 842            {
 843                throw new RoomException($"Failed to set name: {nameEvent.SetLocalName.Error}");
 844            }
 845        }
 846
 847        /// <summary>
 848        /// Sets custom attributes for the local participant.
 849        /// </summary>
 850        /// <param name="attributes">The attributes to set.</param>
 851        /// <remarks>
 852        /// This requires `canUpdateOwnMetadata` permission.
 853        /// Existing attributes that are not overridden will remain unchanged.
 854        /// </remarks>
 855        /// <returns>A task that completes once the update has been sent.</returns>
 856        public async Task SetAttributesAsync(Dictionary<string, string> attributes)
 857        {
 858            if (attributes == null)
 859                throw new ArgumentNullException(nameof(attributes));
 860
 861            var request = new FfiRequest
 862            {
 863                SetLocalAttributes = new SetLocalAttributesRequest
 864                {
 865                    LocalParticipantHandle = Handle.HandleId,
 866                },
 867            };
 868
 869            foreach (var kvp in attributes)
 870            {
 871                request.SetLocalAttributes.Attributes.Add(
 872                    new Proto.AttributesEntry { Key = kvp.Key, Value = kvp.Value }
 873                );
 874            }
 875
 876            var response = FfiClient.Instance.SendRequest(request);
 877            var asyncId = response.SetLocalAttributes?.AsyncId ?? 0;
 878
 879            var attributesEvent = await FfiClient.Instance.WaitForEventAsync(
 880                e =>
 881                    e.MessageCase == FfiEvent.MessageOneofCase.SetLocalAttributes
 882                    && e.SetLocalAttributes?.AsyncId == asyncId,
 883                TimeSpan.FromSeconds(30)
 884            );
 885
 886            if (attributesEvent.SetLocalAttributes?.HasError == true)
 887            {
 888                throw new RoomException(
 889                    $"Failed to set attributes: {attributesEvent.SetLocalAttributes.Error}"
 890                );
 891            }
 892        }
 893
 894        /// <summary>
 895        /// Sends a chat message to participants in the room.
 896        /// </summary>
 897        /// <param name="message">The message text to send.</param>
 898        /// <param name="destinationIdentities">Optional array of destination participant identities. If null, broadcast
 899        /// <param name="senderIdentity">Optional sender identity override.</param>
 900        /// <returns>The sent chat message.</returns>
 901        public async Task<ChatMessage> SendChatMessageAsync(
 902            string message,
 903            string[]? destinationIdentities = null,
 904            string? senderIdentity = null
 905        )
 906        {
 907            if (string.IsNullOrEmpty(message))
 908                throw new ArgumentException("Message cannot be null or empty", nameof(message));
 909
 910            var request = new FfiRequest
 911            {
 912                SendChatMessage = new SendChatMessageRequest
 913                {
 914                    LocalParticipantHandle = Handle.HandleId,
 915                    Message = message,
 916                },
 917            };
 918
 919            if (destinationIdentities != null)
 920            {
 921                request.SendChatMessage.DestinationIdentities.AddRange(destinationIdentities);
 922            }
 923
 924            if (!string.IsNullOrEmpty(senderIdentity))
 925            {
 926                request.SendChatMessage.SenderIdentity = senderIdentity;
 927            }
 928
 929            var response = FfiClient.Instance.SendRequest(request);
 930            var asyncId = response.SendChatMessage?.AsyncId ?? 0;
 931
 932            var chatEvent = await FfiClient.Instance.WaitForEventAsync(
 933                e =>
 934                    e.MessageCase == FfiEvent.MessageOneofCase.ChatMessage
 935                    && e.ChatMessage?.AsyncId == asyncId,
 936                TimeSpan.FromSeconds(30)
 937            );
 938
 939            if (chatEvent.ChatMessage?.HasError == true)
 940            {
 941                throw new RoomException(
 942                    $"Failed to send chat message: {chatEvent.ChatMessage.Error}"
 943                );
 944            }
 945
 946            return chatEvent.ChatMessage!.ChatMessage!;
 947        }
 948
 949        /// <summary>
 950        /// Edits a previously sent chat message.
 951        /// </summary>
 952        /// <param name="editText">The new text for the message.</param>
 953        /// <param name="originalMessage">The original message to edit.</param>
 954        /// <param name="destinationIdentities">Optional array of destination participant identities.</param>
 955        /// <param name="senderIdentity">Optional sender identity override.</param>
 956        /// <returns>The edited chat message.</returns>
 957        public async Task<ChatMessage> EditChatMessageAsync(
 958            string editText,
 959            ChatMessage originalMessage,
 960            string[]? destinationIdentities = null,
 961            string? senderIdentity = null
 962        )
 963        {
 964            if (string.IsNullOrEmpty(editText))
 965                throw new ArgumentException("Edit text cannot be null or empty", nameof(editText));
 966            if (originalMessage == null)
 967                throw new ArgumentNullException(nameof(originalMessage));
 968
 969            var request = new FfiRequest
 970            {
 971                EditChatMessage = new EditChatMessageRequest
 972                {
 973                    LocalParticipantHandle = Handle.HandleId,
 974                    EditText = editText,
 975                    OriginalMessage = originalMessage,
 976                },
 977            };
 978
 979            if (destinationIdentities != null)
 980            {
 981                request.EditChatMessage.DestinationIdentities.AddRange(destinationIdentities);
 982            }
 983
 984            if (!string.IsNullOrEmpty(senderIdentity))
 985            {
 986                request.EditChatMessage.SenderIdentity = senderIdentity;
 987            }
 988
 989            var response = FfiClient.Instance.SendRequest(request);
 990            var asyncId = response.SendChatMessage?.AsyncId ?? 0;
 991
 992            var chatEvent = await FfiClient.Instance.WaitForEventAsync(
 993                e =>
 994                    e.MessageCase == FfiEvent.MessageOneofCase.ChatMessage
 995                    && e.ChatMessage?.AsyncId == asyncId,
 996                TimeSpan.FromSeconds(30)
 997            );
 998
 999            if (chatEvent.ChatMessage?.HasError == true)
 1000            {
 1001                throw new RoomException(
 1002                    $"Failed to edit chat message: {chatEvent.ChatMessage.Error}"
 1003                );
 1004            }
 1005
 1006            return chatEvent.ChatMessage!.ChatMessage!;
 1007        }
 1008
 1009        /// <summary>
 1010        /// Streams text incrementally to participants in the room.
 1011        /// </summary>
 1012        /// <param name="topic">Optional topic for the stream.</param>
 1013        /// <param name="attributes">Optional attributes for the stream.</param>
 1014        /// <param name="destinationIdentities">Optional destination participant identities.</param>
 1015        /// <param name="streamId">Optional custom stream ID (auto-generated if not provided).</param>
 1016        /// <param name="senderIdentity">Optional sender identity override.</param>
 1017        /// <param name="totalSize">Optional total size hint.</param>
 1018        /// <returns>A text stream writer for sending text chunks.</returns>
 1019        public async Task<TextStreamWriter> StreamTextAsync(
 1020            string? topic = null,
 1021            Dictionary<string, string>? attributes = null,
 1022            string[]? destinationIdentities = null,
 1023            string? streamId = null,
 1024            string? senderIdentity = null,
 1025            long? totalSize = null
 1026        )
 1027        {
 1028            streamId ??= Guid.NewGuid().ToString();
 1029            senderIdentity ??= Identity;
 1030            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
 1031
 1032            var header = new DataStream.Types.Header
 1033            {
 1034                StreamId = streamId,
 1035                MimeType = "text/plain",
 1036                Topic = topic ?? string.Empty,
 1037                Timestamp = timestamp,
 1038                TextHeader = new DataStream.Types.TextHeader
 1039                {
 1040                    OperationType = DataStream.Types.OperationType.Create,
 1041                    Version = 0,
 1042                    ReplyToStreamId = string.Empty,
 1043                    Generated = false,
 1044                },
 1045            };
 1046
 1047            if (totalSize.HasValue)
 1048            {
 1049                header.TotalLength = (ulong)totalSize.Value;
 1050            }
 1051
 1052            if (attributes != null)
 1053            {
 1054                foreach (var kvp in attributes)
 1055                {
 1056                    header.Attributes.Add(kvp.Key, kvp.Value);
 1057                }
 1058            }
 1059
 1060            await SendStreamHeaderAsync(header, senderIdentity, destinationIdentities);
 1061
 1062            return new TextStreamWriter(
 1063                this,
 1064                streamId,
 1065                topic ?? string.Empty,
 1066                "text/plain",
 1067                (long)timestamp,
 1068                totalSize,
 1069                attributes,
 1070                destinationIdentities,
 1071                senderIdentity
 1072            );
 1073        }
 1074
 1075        /// <summary>
 1076        /// Sends text to participants in the room.
 1077        /// </summary>
 1078        /// <param name="text">The text to send.</param>
 1079        /// <param name="topic">Optional topic for the message.</param>
 1080        /// <param name="attributes">Optional attributes.</param>
 1081        /// <param name="destinationIdentities">Optional destination participant identities.</param>
 1082        /// <param name="streamId">Optional custom stream ID.</param>
 1083        /// <returns>The text stream info.</returns>
 1084        public async Task<TextStreamInfo> SendTextAsync(
 1085            string text,
 1086            string? topic = null,
 1087            Dictionary<string, string>? attributes = null,
 1088            string[]? destinationIdentities = null,
 1089            string? streamId = null
 1090        )
 1091        {
 1092            var totalSize = Encoding.UTF8.GetByteCount(text);
 1093            var writer = await StreamTextAsync(
 1094                topic,
 1095                attributes,
 1096                destinationIdentities,
 1097                streamId,
 1098                null,
 1099                totalSize
 1100            );
 1101
 1102            await writer.WriteAsync(text);
 1103            await writer.CloseAsync();
 1104
 1105            return writer.Info;
 1106        }
 1107
 1108        /// <summary>
 1109        /// Streams bytes incrementally to participants in the room.
 1110        /// </summary>
 1111        /// <param name="name">The stream name (e.g., filename).</param>
 1112        /// <param name="topic">Optional topic for the stream.</param>
 1113        /// <param name="mimeType">MIME type (default: application/octet-stream).</param>
 1114        /// <param name="attributes">Optional attributes for the stream.</param>
 1115        /// <param name="destinationIdentities">Optional destination participant identities.</param>
 1116        /// <param name="streamId">Optional custom stream ID.</param>
 1117        /// <param name="senderIdentity">Optional sender identity override.</param>
 1118        /// <param name="totalSize">Optional total size hint.</param>
 1119        /// <returns>A byte stream writer for sending byte chunks.</returns>
 1120        public async Task<ByteStreamWriter> StreamBytesAsync(
 1121            string name,
 1122            string? topic = null,
 1123            string? mimeType = null,
 1124            Dictionary<string, string>? attributes = null,
 1125            string[]? destinationIdentities = null,
 1126            string? streamId = null,
 1127            string? senderIdentity = null,
 1128            long? totalSize = null
 1129        )
 1130        {
 1131            streamId ??= Guid.NewGuid().ToString();
 1132            senderIdentity ??= Identity;
 1133            mimeType ??= "application/octet-stream";
 1134            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
 1135
 1136            var header = new DataStream.Types.Header
 1137            {
 1138                StreamId = streamId,
 1139                MimeType = mimeType,
 1140                Topic = topic ?? string.Empty,
 1141                Timestamp = timestamp,
 1142                ByteHeader = new DataStream.Types.ByteHeader { Name = name },
 1143            };
 1144
 1145            if (totalSize.HasValue)
 1146            {
 1147                header.TotalLength = (ulong)totalSize.Value;
 1148            }
 1149
 1150            if (attributes != null)
 1151            {
 1152                foreach (var kvp in attributes)
 1153                {
 1154                    header.Attributes.Add(kvp.Key, kvp.Value);
 1155                }
 1156            }
 1157
 1158            await SendStreamHeaderAsync(header, senderIdentity, destinationIdentities);
 1159
 1160            return new ByteStreamWriter(
 1161                this,
 1162                streamId,
 1163                topic ?? string.Empty,
 1164                mimeType,
 1165                (long)timestamp,
 1166                totalSize,
 1167                attributes,
 1168                name,
 1169                destinationIdentities,
 1170                senderIdentity
 1171            );
 1172        }
 1173
 1174        /// <summary>
 1175        /// Sends a file to participants in the room.
 1176        /// </summary>
 1177        /// <param name="filePath">The path to the file to send.</param>
 1178        /// <param name="topic">Optional topic for the file.</param>
 1179        /// <param name="mimeType">Optional MIME type (auto-detected if not provided).</param>
 1180        /// <param name="attributes">Optional attributes.</param>
 1181        /// <param name="destinationIdentities">Optional destination participant identities.</param>
 1182        /// <param name="streamId">Optional custom stream ID.</param>
 1183        /// <returns>The byte stream info.</returns>
 1184        public async Task<ByteStreamInfo> SendFileAsync(
 1185            string filePath,
 1186            string? topic = null,
 1187            string? mimeType = null,
 1188            Dictionary<string, string>? attributes = null,
 1189            string[]? destinationIdentities = null,
 1190            string? streamId = null
 1191        )
 1192        {
 1193            if (!System.IO.File.Exists(filePath))
 1194                throw new System.IO.FileNotFoundException("File not found", filePath);
 1195
 1196            var fileInfo = new System.IO.FileInfo(filePath);
 1197            var fileName = fileInfo.Name;
 1198            var fileSize = fileInfo.Length;
 1199
 1200            // Auto-detect MIME type if not provided
 1201            if (string.IsNullOrEmpty(mimeType))
 1202            {
 1203                var extension = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
 1204                mimeType = extension switch
 1205                {
 1206                    ".txt" => "text/plain",
 1207                    ".html" => "text/html",
 1208                    ".json" => "application/json",
 1209                    ".xml" => "application/xml",
 1210                    ".pdf" => "application/pdf",
 1211                    ".jpg" or ".jpeg" => "image/jpeg",
 1212                    ".png" => "image/png",
 1213                    ".gif" => "image/gif",
 1214                    ".mp4" => "video/mp4",
 1215                    ".mp3" => "audio/mpeg",
 1216                    ".wav" => "audio/wav",
 1217                    ".zip" => "application/zip",
 1218                    _ => "application/octet-stream",
 1219                };
 1220            }
 1221
 1222            var writer = await StreamBytesAsync(
 1223                fileName,
 1224                topic,
 1225                mimeType,
 1226                attributes,
 1227                destinationIdentities,
 1228                streamId,
 1229                null,
 1230                fileSize
 1231            );
 1232
 1233            await using (var fileStream = System.IO.File.OpenRead(filePath))
 1234            {
 1235                var buffer = new byte[DataStreamConstants.StreamChunkSize];
 1236                int bytesRead;
 1237                while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
 1238                {
 1239                    var chunk = new byte[bytesRead];
 1240                    Buffer.BlockCopy(buffer, 0, chunk, 0, bytesRead);
 1241                    await writer.WriteAsync(chunk);
 1242                }
 1243            }
 1244
 1245            await writer.CloseAsync();
 1246            return writer.Info;
 1247        }
 1248
 1249        /// <summary>
 1250        /// Sets track subscription permissions for this local participant.
 1251        /// </summary>
 1252        /// <param name="allParticipantsAllowed">Whether all participants are allowed to subscribe.</param>
 1253        /// <param name="participantPermissions">Specific permissions for individual participants.</param>
 1254        public void SetTrackSubscriptionPermissions(
 1255            bool allParticipantsAllowed,
 1256            Proto.ParticipantTrackPermission[]? participantPermissions = null
 1257        )
 1258        {
 1259            var request = new FfiRequest
 1260            {
 1261                SetTrackSubscriptionPermissions = new SetTrackSubscriptionPermissionsRequest
 1262                {
 1263                    LocalParticipantHandle = Handle.HandleId,
 1264                    AllParticipantsAllowed = allParticipantsAllowed,
 1265                },
 1266            };
 1267
 1268            if (participantPermissions != null)
 1269            {
 1270                request.SetTrackSubscriptionPermissions.Permissions.AddRange(
 1271                    participantPermissions
 1272                );
 1273            }
 1274
 1275            FfiClient.Instance.SendRequest(request);
 1276        }
 1277
 1278        /// <summary>
 1279        /// Performs an RPC call to a remote participant. Deprecated, kept for the applications compiled
 1280        /// against an earlier version: use
 1281        /// <see cref="PerformRpcAsync(string, string, string, double?, double?)"/>.
 1282        /// </summary>
 1283        /// <param name="destinationIdentity">The identity of the destination participant.</param>
 1284        /// <param name="method">The RPC method name to call.</param>
 1285        /// <param name="payload">The payload to send with the request.</param>
 1286        /// <param name="responseTimeout">Seconds to wait for the response; 15 when null.</param>
 1287        /// <returns>The response payload from the remote participant.</returns>
 1288        /// <exception cref="RpcError">Thrown when the RPC call fails.</exception>
 1289        // The signature of 0.1.7 without its default value: callers compiled against it keep binding
 1290        // to it, and source code binds to the overload below
 1291        [Obsolete(
 1292            "Use PerformRpcAsync(string destinationIdentity, string method, string payload, double? responseTimeout = nu
 1293        )]
 1294        [EditorBrowsable(EditorBrowsableState.Never)]
 1295        [OverloadResolutionPriority(-1)]
 1296        public Task<string> PerformRpcAsync(
 1297            string destinationIdentity,
 1298            string method,
 1299            string payload,
 1300            double? responseTimeout
 1301        ) => PerformRpcAsync(destinationIdentity, method, payload, responseTimeout, null);
 1302
 1303        /// <summary>
 1304        /// Performs an RPC call to a remote participant.
 1305        /// </summary>
 1306        /// <param name="destinationIdentity">The identity of the destination participant.</param>
 1307        /// <param name="method">The RPC method name to call.</param>
 1308        /// <param name="payload">The payload to send with the request.</param>
 1309        /// <param name="responseTimeout">Seconds to wait for the response; 15 when null.</param>
 1310        /// <param name="maxRoundTripLatency">
 1311        /// Most seconds the request may take to reach the destination and its acknowledgment to come
 1312        /// back, after which the call fails with <see cref="RpcErrorCode.ConnectionTimeout"/>; 7 when
 1313        /// null. Raise it on high-latency networks, where requests can wait behind other messages on
 1314        /// the data channel.
 1315        /// </param>
 1316        /// <returns>The response payload from the remote participant.</returns>
 1317        /// <exception cref="RpcError">Thrown when the RPC call fails.</exception>
 1318        public async Task<string> PerformRpcAsync(
 1319            string destinationIdentity,
 1320            string method,
 1321            string payload,
 1322            double? responseTimeout = null,
 1323            double? maxRoundTripLatency = null
 1324        )
 1325        {
 1326            if (string.IsNullOrEmpty(destinationIdentity))
 1327                throw new ArgumentNullException(nameof(destinationIdentity));
 1328            if (string.IsNullOrEmpty(method))
 1329                throw new ArgumentNullException(nameof(method));
 1330            if (maxRoundTripLatency.HasValue && !(maxRoundTripLatency.Value > 0))
 1331                throw new ArgumentOutOfRangeException(
 1332                    nameof(maxRoundTripLatency),
 1333                    maxRoundTripLatency,
 1334                    "The maximum round-trip latency must be positive."
 1335                );
 1336
 1337            var request = new FfiRequest
 1338            {
 1339                PerformRpc = new PerformRpcRequest
 1340                {
 1341                    LocalParticipantHandle = Handle.HandleId,
 1342                    DestinationIdentity = destinationIdentity,
 1343                    Method = method,
 1344                    Payload = payload ?? string.Empty,
 1345                },
 1346            };
 1347
 1348            if (responseTimeout.HasValue)
 1349            {
 1350                request.PerformRpc.ResponseTimeoutMs = (uint)(responseTimeout.Value * 1000);
 1351            }
 1352
 1353            if (maxRoundTripLatency.HasValue)
 1354            {
 1355                request.PerformRpc.MaxRoundTripLatencyMs = (uint)
 1356                    Math.Ceiling(maxRoundTripLatency.Value * 1000);
 1357            }
 1358
 1359            var response = FfiClient.Instance.SendRequest(request);
 1360            var asyncId = response.PerformRpc?.AsyncId ?? 0;
 1361
 1362            // The FFI reports its own timeout errors after responseTimeout (15 s by default) and
 1363            // maxRoundTripLatency; wait longer than that so callers get the RpcError, not a
 1364            // TimeoutException
 1365            var callback = await FfiClient.Instance.WaitForEventAsync(
 1366                e =>
 1367                    e.MessageCase == FfiEvent.MessageOneofCase.PerformRpc
 1368                    && e.PerformRpc?.AsyncId == asyncId,
 1369                TimeSpan.FromSeconds((responseTimeout ?? 15) + (maxRoundTripLatency ?? 0) + 15)
 1370            );
 1371
 1372            if (callback.PerformRpc?.Error != null)
 1373            {
 1374                throw RpcError.FromProto(callback.PerformRpc.Error);
 1375            }
 1376
 1377            return callback.PerformRpc?.Payload ?? string.Empty;
 1378        }
 1379
 1380        /// <summary>
 1381        /// Registers a handler for incoming RPC method calls.
 1382        /// Replaces any existing handler for the same method name.
 1383        /// </summary>
 1384        /// <param name="method">The RPC method name to handle.</param>
 1385        /// <param name="handler">The handler function to invoke when this method is called.</param>
 1386        /// <remarks>
 1387        /// The handler should return a string response or throw an RpcError.
 1388        /// Other exceptions will be converted to ApplicationError responses.
 1389        /// </remarks>
 1390        public void RegisterRpcMethod(string method, RpcMethodHandler handler)
 1391        {
 1392            if (string.IsNullOrEmpty(method))
 1393                throw new ArgumentNullException(nameof(method));
 1394            if (handler == null)
 1395                throw new ArgumentNullException(nameof(handler));
 1396
 1397            _rpcHandlers[method] = handler;
 1398
 1399            var request = new FfiRequest
 1400            {
 1401                RegisterRpcMethod = new RegisterRpcMethodRequest
 1402                {
 1403                    LocalParticipantHandle = Handle.HandleId,
 1404                    Method = method,
 1405                },
 1406            };
 1407
 1408            FfiClient.Instance.SendRequest(request);
 1409        }
 1410
 1411        /// <summary>
 1412        /// Unregisters a previously registered RPC method handler.
 1413        /// </summary>
 1414        /// <param name="method">The RPC method name to unregister.</param>
 1415        public void UnregisterRpcMethod(string method)
 1416        {
 1417            if (string.IsNullOrEmpty(method))
 1418                return;
 1419
 1420            _rpcHandlers.TryRemove(method, out _);
 1421
 1422            var request = new FfiRequest
 1423            {
 1424                UnregisterRpcMethod = new UnregisterRpcMethodRequest
 1425                {
 1426                    LocalParticipantHandle = Handle.HandleId,
 1427                    Method = method,
 1428                },
 1429            };
 1430
 1431            FfiClient.Instance.SendRequest(request);
 1432        }
 1433
 1434        /// <summary>
 1435        /// Internal handler for processing incoming RPC method invocations.
 1436        /// </summary>
 1437        internal async Task HandleRpcMethodInvocationAsync(
 1438            ulong invocationId,
 1439            string method,
 1440            string requestId,
 1441            string callerIdentity,
 1442            string payload,
 1443            uint responseTimeoutMs
 1444        )
 1445        {
 1446            RpcError? responseError = null;
 1447            string? responsePayload = null;
 1448
 1449            if (!_rpcHandlers.TryGetValue(method, out var handler))
 1450            {
 1451                responseError = RpcError.BuiltIn(
 1452                    RpcErrorCode.UnsupportedMethod,
 1453                    $"Method '{method}' is not registered"
 1454                );
 1455            }
 1456            else
 1457            {
 1458                try
 1459                {
 1460                    var invocationData = new RpcInvocationData(
 1461                        requestId,
 1462                        callerIdentity,
 1463                        payload,
 1464                        responseTimeoutMs / 1000.0
 1465                    );
 1466
 1467                    responsePayload = await handler(invocationData);
 1468                    responsePayload ??= string.Empty;
 1469                }
 1470                catch (RpcError rpcError)
 1471                {
 1472                    responseError = rpcError;
 1473                }
 1474                catch (Exception ex)
 1475                {
 1476                    // Like the Node and Python SDKs, the caller only learns that the handler
 1477                    // failed: the message and the stack trace stay in this process
 1478                    Console.Error.WriteLine($"[ERROR] RPC handler for '{method}' threw: {ex}");
 1479                    responseError = RpcError.BuiltIn(RpcErrorCode.ApplicationError);
 1480                }
 1481            }
 1482
 1483            var request = new FfiRequest
 1484            {
 1485                RpcMethodInvocationResponse = new RpcMethodInvocationResponseRequest
 1486                {
 1487                    LocalParticipantHandle = Handle.HandleId,
 1488                    InvocationId = invocationId,
 1489                    Payload = responsePayload ?? string.Empty, // Always set payload, even for errors
 1490                },
 1491            };
 1492
 1493            if (responseError != null)
 1494            {
 1495                request.RpcMethodInvocationResponse.Error = responseError.ToProto();
 1496            }
 1497
 1498            var response = FfiClient.Instance.SendRequest(request);
 1499
 1500            if (!string.IsNullOrEmpty(response.RpcMethodInvocationResponse?.Error))
 1501            {
 1502                throw new RoomException(
 1503                    $"Failed to send RPC invocation response: {response.RpcMethodInvocationResponse.Error}"
 1504                );
 1505            }
 1506        }
 1507
 1508        private async Task SendStreamHeaderAsync(
 1509            DataStream.Types.Header header,
 1510            string senderIdentity,
 1511            string[]? destinationIdentities
 1512        )
 1513        {
 1514            var request = new FfiRequest
 1515            {
 1516                SendStreamHeader = new SendStreamHeaderRequest
 1517                {
 1518                    LocalParticipantHandle = Handle.HandleId,
 1519                    SenderIdentity = senderIdentity,
 1520                    Header = header,
 1521                },
 1522            };
 1523
 1524            if (destinationIdentities != null && destinationIdentities.Length > 0)
 1525            {
 1526                request.SendStreamHeader.DestinationIdentities.AddRange(destinationIdentities);
 1527            }
 1528
 1529            var response = FfiClient.Instance.SendRequest(request);
 1530            var asyncId = response.SendStreamHeader?.AsyncId ?? 0;
 1531
 1532            var headerEvent = await FfiClient.Instance.WaitForEventAsync(
 1533                e =>
 1534                    e.MessageCase == FfiEvent.MessageOneofCase.SendStreamHeader
 1535                    && e.SendStreamHeader?.AsyncId == asyncId,
 1536                TimeSpan.FromSeconds(30)
 1537            );
 1538
 1539            if (headerEvent.SendStreamHeader?.HasError == true)
 1540            {
 1541                throw new RoomException(
 1542                    $"Failed to send stream header: {headerEvent.SendStreamHeader.Error}"
 1543                );
 1544            }
 1545        }
 1546    }
 1547
 1548    /// <summary>
 1549    /// Represents a remote participant in the room.
 1550    /// </summary>
 1551    public class RemoteParticipant : Participant
 1552    {
 1553        // Tracks whose subscription ended (TrackUnsubscribed, or TrackUnpublished of a publication
 1554        // without a track) although the room had not delivered their TrackSubscribed, by SID, with
 1555        // the time it ended. The Rust SDK dispatches TrackSubscribed from the media path and the
 1556        // unpublication's events from the signal path, with no lock spanning the state change and
 1557        // the dispatch: a participant that unpublishes while its track is being subscribed can have
 1558        // the unsubscription, a second one, or the unpublication delivered first. The
 1559        // TrackSubscribed that follows within milliseconds is stale. Protected by PublicationsLock.
 4421560        private readonly Dictionary<string, long> _unsubscribedBeforeSubscribed =
 4421561            new Dictionary<string, long>();
 1562
 1563        // A TrackSubscribed later than this is a new subscription, not the stale half of a race
 11564        private static readonly long UnsubscribedBeforeSubscribedWindow = Stopwatch.Frequency * 10;
 1565
 1566        internal RemoteParticipant(FfiHandle handle, ParticipantInfo? info, Room room)
 13261567            : base(handle, info, room) { }
 1568
 1569        /// <summary>
 1570        /// Records the end of a subscription the room has not delivered.
 1571        /// </summary>
 1572        internal void MarkUnsubscribedBeforeSubscribed(string trackSid)
 1151573        {
 1151574            var now = Stopwatch.GetTimestamp();
 1151575            lock (PublicationsLock)
 1151576            {
 1577                // Most records are never taken (no TrackSubscribed follows an unpublication that
 1578                // beat the subscription): drop the expired ones, so a participant that publishes
 1579                // and unpublishes for hours keeps a handful at most
 1151580                if (_unsubscribedBeforeSubscribed.Count > 0)
 281581                {
 281582                    var expired = new List<string>();
 1401583                    foreach (var record in _unsubscribedBeforeSubscribed)
 281584                    {
 281585                        if (now - record.Value > UnsubscribedBeforeSubscribedWindow)
 01586                            expired.Add(record.Key);
 281587                    }
 841588                    foreach (var sid in expired)
 01589                        _unsubscribedBeforeSubscribed.Remove(sid);
 281590                }
 1151591                _unsubscribedBeforeSubscribed[trackSid] = now;
 1151592            }
 1151593        }
 1594
 1595        /// <summary>
 1596        /// Whether a TrackSubscribed is the stale half of an unsubscription delivered before it.
 1597        /// Consumes the record.
 1598        /// </summary>
 1599        internal bool TakeUnsubscribedBeforeSubscribed(string trackSid)
 1481600        {
 1481601            lock (PublicationsLock)
 1481602            {
 1481603                if (!_unsubscribedBeforeSubscribed.Remove(trackSid, out var at))
 1251604                    return false;
 231605                return Stopwatch.GetTimestamp() - at <= UnsubscribedBeforeSubscribedWindow;
 1606            }
 1481607        }
 1608
 1609        internal void AddPublication(OwnedTrackPublication pub)
 1551610        {
 1551611            if (pub.Handle == null || pub.Info == null)
 01612                return;
 1613
 1551614            var publication = new RemoteTrackPublication(
 1551615                FfiHandle.FromId(pub.Handle.Id),
 1551616                pub.Info,
 1551617                this
 1551618            );
 1619
 1551620            lock (PublicationsLock)
 1551621            {
 1551622                _trackPublications[publication.Sid] = publication;
 1551623            }
 1551624        }
 1625
 1626        internal void RemovePublication(string sid)
 931627        {
 931628            lock (PublicationsLock)
 931629            {
 931630                _trackPublications.Remove(sid);
 931631            }
 931632        }
 1633    }
 1634
 1635    /// <summary>
 1636    /// Options for publishing a track.
 1637    /// </summary>
 1638    public class TrackPublishOptions
 1639    {
 1640        /// <summary>
 1641        /// Video encoding settings.
 1642        /// </summary>
 1643        public VideoEncodingOptions? VideoEncoding { get; set; }
 1644
 1645        /// <summary>
 1646        /// Audio encoding settings.
 1647        /// </summary>
 1648        public AudioEncodingOptions? AudioEncoding { get; set; }
 1649
 1650        /// <summary>
 1651        /// Preferred codec for video tracks (VP8, H264, AV1, VP9...). When
 1652        /// null, the SDK default codec (VP8) is used.
 1653        /// </summary>
 1654        public Proto.VideoCodec? VideoCodec { get; set; }
 1655
 1656        /// <summary>
 1657        /// Whether to enable DTX (discontinuous transmission) for audio
 1658        /// tracks. When null, the SDK default (enabled) is used.
 1659        /// </summary>
 1660        public bool? Dtx { get; set; }
 1661
 1662        /// <summary>
 1663        /// Whether to enable RED (redundant encoding) for audio tracks. When
 1664        /// null, the SDK default (enabled) is used.
 1665        /// </summary>
 1666        public bool? Red { get; set; }
 1667
 1668        /// <summary>
 1669        /// Whether to publish video in several quality layers, so each subscriber receives the one it can
 1670        /// handle. Defaults to true; must be false for pre-encoded tracks.
 1671        /// </summary>
 1672        public bool Simulcast { get; set; } = true;
 1673
 1674        /// <summary>
 1675        /// Track source.
 1676        /// </summary>
 1677        public Proto.TrackSource Source { get; set; } = Proto.TrackSource.SourceUnknown;
 1678
 1679        /// <summary>
 1680        /// Name of the stream the track belongs to, used to group tracks
 1681        /// together (e.g. camera and screen share with their audios). When
 1682        /// null, the server infers it from the track source.
 1683        /// </summary>
 1684        public string? Stream { get; set; }
 1685
 1686        /// <summary>
 1687        /// Whether to use the preconnect audio buffer for this track. When
 1688        /// null, the SDK default (disabled) is used.
 1689        /// </summary>
 1690        public bool? PreconnectBuffer { get; set; }
 1691
 1692        /// <summary>
 1693        /// Per-frame metadata features to enable for this track (user
 1694        /// timestamps, frame IDs, user data...).
 1695        /// </summary>
 1696        public IList<Proto.FrameMetadataFeature>? FrameMetadataFeatures { get; set; }
 1697
 1698        /// <summary>
 1699        /// RTP scalability mode (e.g. "L3T3_KEY"). When set, a single RTP
 1700        /// encoding is produced with this mode, enabling true SVC for codecs
 1701        /// that support it (VP9, AV1). Has no effect for VP8/H264.
 1702        /// </summary>
 1703        public string? ScalabilityMode { get; set; }
 1704
 1705        /// <summary>
 1706        /// Preferred encoder backend to use when publishing a video track.
 1707        /// When null, the backend is chosen automatically.
 1708        /// </summary>
 1709        public Proto.VideoEncoderBackend? VideoEncoder { get; set; }
 1710
 1711        /// <summary>
 1712        /// Controls how the encoder trades off between resolution and
 1713        /// framerate when bandwidth is constrained. When null, the SDK default
 1714        /// (maintain resolution) is used.
 1715        /// </summary>
 1716        public Proto.DegradationPreference? DegradationPreference { get; set; }
 1717
 1718        internal Proto.TrackPublishOptions ToProto()
 1719        {
 1720            var proto = new Proto.TrackPublishOptions { Source = Source, Simulcast = Simulcast };
 1721
 1722            if (VideoCodec != null)
 1723            {
 1724                proto.VideoCodec = VideoCodec.Value;
 1725            }
 1726
 1727            if (Dtx != null)
 1728            {
 1729                proto.Dtx = Dtx.Value;
 1730            }
 1731
 1732            if (Red != null)
 1733            {
 1734                proto.Red = Red.Value;
 1735            }
 1736
 1737            if (Stream != null)
 1738            {
 1739                proto.Stream = Stream;
 1740            }
 1741
 1742            if (PreconnectBuffer != null)
 1743            {
 1744                proto.PreconnectBuffer = PreconnectBuffer.Value;
 1745            }
 1746
 1747            if (FrameMetadataFeatures != null)
 1748            {
 1749                proto.FrameMetadataFeatures.AddRange(FrameMetadataFeatures);
 1750            }
 1751
 1752            if (ScalabilityMode != null)
 1753            {
 1754                proto.ScalabilityMode = ScalabilityMode;
 1755            }
 1756
 1757            if (VideoEncoder != null)
 1758            {
 1759                proto.VideoEncoder = VideoEncoder.Value;
 1760            }
 1761
 1762            if (DegradationPreference != null)
 1763            {
 1764                proto.DegradationPreference = DegradationPreference.Value;
 1765            }
 1766
 1767            if (AudioEncoding != null)
 1768            {
 1769                proto.AudioEncoding = new Proto.AudioEncoding
 1770                {
 1771                    MaxBitrate = AudioEncoding.MaxBitrate,
 1772                };
 1773            }
 1774
 1775            if (VideoEncoding != null)
 1776            {
 1777                proto.VideoEncoding = new Proto.VideoEncoding
 1778                {
 1779                    MaxBitrate = VideoEncoding.MaxBitrate,
 1780                    MaxFramerate = VideoEncoding.MaxFramerate,
 1781                };
 1782            }
 1783
 1784            return proto;
 1785        }
 1786    }
 1787
 1788    /// <summary>
 1789    /// Video encoding options.
 1790    /// </summary>
 1791    public class VideoEncodingOptions
 1792    {
 1793        /// <summary>
 1794        /// Maximum bitrate in bits per second.
 1795        /// </summary>
 1796        public uint MaxBitrate { get; set; }
 1797
 1798        /// <summary>
 1799        /// Maximum framerate.
 1800        /// </summary>
 1801        public uint MaxFramerate { get; set; }
 1802    }
 1803
 1804    /// <summary>
 1805    /// Audio encoding options.
 1806    /// </summary>
 1807    public class AudioEncodingOptions
 1808    {
 1809        /// <summary>
 1810        /// Maximum bitrate in bits per second.
 1811        /// </summary>
 1812        public uint MaxBitrate { get; set; }
 1813    }
 1814
 1815    /// <summary>
 1816    /// Options for publishing data.
 1817    /// </summary>
 1818    public class DataPublishOptions
 1819    {
 1820        /// <summary>
 1821        /// Whether to send the data on the reliable channel, which retransmits lost packets and keeps their
 1822        /// order. Defaults to true; false uses the lossy channel.
 1823        /// </summary>
 1824        public bool Reliable { get; set; } = true;
 1825
 1826        /// <summary>
 1827        /// Topic for the data message.
 1828        /// </summary>
 1829        public string? Topic { get; set; }
 1830
 1831        /// <summary>
 1832        /// Destination participant identities. If empty, sends to all.
 1833        /// </summary>
 1834        public string[]? DestinationIdentities { get; set; }
 1835    }
 1836}