< Summary

Information
Class: LiveKit.Rtc.LocalParticipant
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/Participant.cs
Line coverage
82%
Covered lines: 691
Uncovered lines: 148
Coverable lines: 839
Total lines: 1836
Line coverage: 82.3%
Branch coverage
67%
Covered branches: 228
Total branches: 340
Branch coverage: 67%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

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
 451136        private readonly ConcurrentDictionary<string, RpcMethodHandler> _rpcHandlers =
 451137            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.
 451143        private readonly Dictionary<
 451144            string,
 451145            TaskCompletionSource<LocalTrackPublication>
 451146        > _pendingPublicationWaiters =
 451147            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.
 451154        private readonly Dictionary<
 451155            string,
 451156            LocalTrackPublication
 451157        > _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.
 451163        private readonly HashSet<string> _abandonedPublications = new HashSet<string>();
 164
 165        internal LocalParticipant(FfiHandle handle, ParticipantInfo? info, Room room)
 1353166            : 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)
 227176        {
 227177            lock (PublicationsLock)
 227178            {
 227179                if (_trackPublications.Remove(trackSid, out var publication))
 226180                    return publication as LocalTrackPublication;
 1181            }
 182
 1183            return _publicationsPendingUnpublishedEvent.Remove(trackSid, out var pending)
 1184                ? pending
 1185                : null;
 227186        }
 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        )
 339196        {
 197            TaskCompletionSource<LocalTrackPublication> waiter;
 339198            await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 199            try
 339200            {
 339201                if (_abandonedPublications.Contains(trackSid))
 0202                    return null;
 339203                lock (PublicationsLock)
 339204                {
 339205                    if (
 339206                        _trackPublications.TryGetValue(trackSid, out var existing)
 339207                        && existing is LocalTrackPublication found
 339208                    )
 333209                        return found;
 6210                }
 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
 6214                if (_publicationsPendingUnpublishedEvent.TryGetValue(trackSid, out var unpublished))
 1215                    return unpublished;
 5216                if (!_pendingPublicationWaiters.TryGetValue(trackSid, out waiter))
 5217                {
 5218                    waiter = new TaskCompletionSource<LocalTrackPublication>(
 5219                        TaskCreationOptions.RunContinuationsAsynchronously
 5220                    );
 5221                    _pendingPublicationWaiters[trackSid] = waiter;
 5222                }
 5223            }
 224            finally
 339225            {
 339226                Room.FfiEventLock.Release();
 339227            }
 228
 5229            using var timeoutCts = new CancellationTokenSource(timeout);
 5230            using (timeoutCts.Token.Register(() => waiter.TrySetCanceled()))
 5231            {
 232                try
 5233                {
 5234                    return await waiter.Task.ConfigureAwait(false);
 235                }
 0236                catch (OperationCanceledException)
 0237                {
 0238                    await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 239                    try
 0240                    {
 0241                        _pendingPublicationWaiters.Remove(trackSid);
 0242                    }
 243                    finally
 0244                    {
 0245                        Room.FfiEventLock.Release();
 0246                    }
 0247                    return null;
 248                }
 0249            }
 339250        }
 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)
 0258        {
 0259            await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 260            try
 0261            {
 0262                _abandonedPublications.Add(trackSid);
 0263                if (_pendingPublicationWaiters.Remove(trackSid, out var waiter))
 0264                    waiter.TrySetCanceled();
 0265            }
 266            finally
 0267            {
 0268                Room.FfiEventLock.Release();
 0269            }
 0270        }
 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)
 0278        {
 0279            await Room.FfiEventLock.WaitAsync().ConfigureAwait(false);
 280            try
 0281            {
 0282                return forget
 0283                    ? _abandonedPublications.Remove(trackSid)
 0284                    : _abandonedPublications.Contains(trackSid);
 285            }
 286            finally
 0287            {
 0288                Room.FfiEventLock.Release();
 0289            }
 0290        }
 291
 292        /// <summary>
 293        /// The room disconnected: nobody will subscribe to the local tracks anymore.
 294        /// </summary>
 295        internal void CancelPendingSubscriptionWaits()
 451296        {
 1361297            foreach (var publication in TrackPublications.Values.OfType<LocalTrackPublication>())
 4298            {
 4299                publication.CancelFirstSubscription();
 4300            }
 451301        }
 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        )
 27316        {
 27317            lock (PublicationsLock)
 27318            {
 27319                if (!_trackPublications.Remove(previousSid, out var existing))
 0320                    return null;
 27321                if (!(existing is LocalTrackPublication publication))
 0322                    return null;
 323
 27324                publication.UpdateInfo(info);
 27325                _trackPublications[publication.Sid] = publication;
 326                // Keep the local-track invariant (track.Sid == publication.Sid) across the republish
 27327                publication.Track?.UpdateSid(publication.Sid);
 27328                return publication;
 329            }
 27330        }
 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        )
 235347        {
 235348            options ??= new TrackPublishOptions();
 349            // Before any side effect: once requested, a publication that the cancellation abandons
 350            // has to be unpublished in the background
 235351            cancellationToken.ThrowIfCancellationRequested();
 352
 233353            var request = new FfiRequest
 233354            {
 233355                PublishTrack = new PublishTrackRequest
 233356                {
 233357                    LocalParticipantHandle = Handle.HandleId,
 233358                    TrackHandle = track.Handle.HandleId,
 233359                    Options = options.ToProto(),
 233360                },
 233361            };
 362
 233363            var response = FfiClient.Instance.SendRequest(request);
 364
 233365            if (response.PublishTrack == null)
 0366                throw new InvalidOperationException("Invalid publish track response");
 367
 233368            var asyncId = response.PublishTrack.AsyncId;
 369
 370            // Wait for publish callback (don't hold lock during wait)
 371            FfiEvent publishEvent;
 372            try
 233373            {
 233374                publishEvent = await FfiClient.Instance.WaitForEventAsync(
 233375                    e =>
 243064376                        e.MessageCase == FfiEvent.MessageOneofCase.PublishTrack
 243064377                        && e.PublishTrack?.AsyncId == asyncId,
 233378                    TimeSpan.FromSeconds(30),
 233379                    cancellationToken
 233380                );
 233381            }
 0382            catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
 0383            {
 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.
 0386                _ = ReconcileAbandonedPublishAsync(asyncId);
 0387                throw;
 388            }
 389
 233390            var callback = publishEvent.PublishTrack!;
 391
 233392            if (callback.HasError)
 2393            {
 2394                throw new RoomException($"Failed to publish track: {callback.Error}");
 395            }
 396
 231397            var publication = callback.Publication;
 231398            if (publication == null || publication.Info == null)
 0399            {
 0400                throw new RoomException("Publish callback has no publication");
 401            }
 402
 231403            var localPublication = new LocalTrackPublication(
 231404                FfiHandle.FromId(publication.Handle.Id),
 231405                publication.Info,
 231406                this
 231407            );
 408
 231409            localPublication.Track = track;
 410            // A freshly created local track reports "TR_unknown" until it is published
 231411            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.
 231415            await Room.FfiEventLock.WaitAsync();
 416            try
 231417            {
 231418                lock (PublicationsLock)
 231419                {
 231420                    _trackPublications[localPublication.Sid] = localPublication;
 231421                }
 231422                if (_pendingPublicationWaiters.Remove(localPublication.Sid, out var waiter))
 5423                {
 5424                    waiter.TrySetResult(localPublication);
 5425                }
 231426                return localPublication;
 427            }
 428            finally
 231429            {
 430                // Release lock - now FFI events can be processed
 231431                Room.FfiEventLock.Release();
 231432            }
 231433        }
 434
 435        private async Task ReconcileAbandonedPublishAsync(ulong asyncId)
 0436        {
 437            try
 0438            {
 0439                var publishEvent = await FfiClient.Instance.WaitForEventAsync(
 0440                    e =>
 0441                        e.MessageCase == FfiEvent.MessageOneofCase.PublishTrack
 0442                        && e.PublishTrack?.AsyncId == asyncId,
 0443                    TimeSpan.FromSeconds(60)
 0444                );
 0445                var publication = publishEvent.PublishTrack?.Publication;
 0446                if (publishEvent.PublishTrack?.HasError == true || publication?.Info == null)
 0447                    return;
 448
 0449                using var handle = FfiHandle.FromId(publication.Handle.Id);
 0450                Console.Error.WriteLine(
 0451                    $"[WARN] PublishTrackAsync was cancelled after track {publication.Info.Sid} was published: unpublish
 0452                );
 0453                await MarkPublicationAbandonedAsync(publication.Info.Sid).ConfigureAwait(false);
 0454                await UnpublishTrackAsync(publication.Info.Sid).ConfigureAwait(false);
 0455            }
 0456            catch (Exception ex)
 0457            {
 0458                Console.Error.WriteLine(
 0459                    $"[WARN] Could not reconcile a cancelled PublishTrackAsync: {ex.Message}"
 0460                );
 0461            }
 0462        }
 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        )
 132477        {
 478            // The FFI unwraps the SID conversion: anything but a "TR_..." SID panics the native
 479            // side, which terminates the process
 132480            if (
 132481                string.IsNullOrEmpty(trackSid)
 132482                || !trackSid.StartsWith("TR_", StringComparison.Ordinal)
 132483            )
 2484                throw new ArgumentException(
 2485                    $"'{trackSid}' is not a track SID (expected 'TR_...'), use publication.Sid",
 2486                    nameof(trackSid)
 2487                );
 130488            cancellationToken.ThrowIfCancellationRequested();
 489
 129490            var request = new FfiRequest
 129491            {
 129492                UnpublishTrack = new UnpublishTrackRequest
 129493                {
 129494                    LocalParticipantHandle = Handle.HandleId,
 129495                    TrackSid = trackSid,
 129496                    StopOnUnpublish = true,
 129497                },
 129498            };
 499
 129500            var response = FfiClient.Instance.SendRequest(request);
 501
 129502            if (response.UnpublishTrack == null)
 0503                throw new InvalidOperationException("Invalid unpublish track response");
 504
 129505            var asyncId = response.UnpublishTrack.AsyncId;
 506
 507            // Wait for unpublish callback (don't hold lock during wait)
 129508            var unpublishEvent = await FfiClient.Instance.WaitForEventAsync(
 129509                e =>
 145927510                    e.MessageCase == FfiEvent.MessageOneofCase.UnpublishTrack
 145927511                    && e.UnpublishTrack?.AsyncId == asyncId,
 129512                TimeSpan.FromSeconds(10),
 129513                cancellationToken
 129514            );
 515
 129516            var callback = unpublishEvent.UnpublishTrack!;
 517
 129518            if (!string.IsNullOrEmpty(callback.Error))
 0519            {
 0520                throw new RoomException($"Failed to unpublish track: {callback.Error}");
 521            }
 522
 523            // Acquire lock only for modifying state (matches Node SDK pattern)
 129524            await Room.FfiEventLock.WaitAsync(cancellationToken);
 525            try
 129526            {
 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;
 129532                lock (PublicationsLock)
 129533                {
 129534                    _trackPublications.Remove(trackSid, out removed);
 129535                }
 129536                if (removed is LocalTrackPublication localPublication)
 1537                {
 1538                    _publicationsPendingUnpublishedEvent[trackSid] = localPublication;
 1539                }
 129540            }
 541            finally
 129542            {
 543                // Release lock - now FFI events can be processed
 129544                Room.FfiEventLock.Release();
 129545            }
 129546        }
 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)
 10354555        {
 10354556            options ??= new DataPublishOptions();
 557
 558            ulong asyncId;
 559
 560            unsafe
 10354561            {
 10354562                fixed (byte* dataPtr = data)
 10354563                {
 10354564                    var request = new FfiRequest
 10354565                    {
 10354566                        PublishData = new PublishDataRequest
 10354567                        {
 10354568                            LocalParticipantHandle = Handle.HandleId,
 10354569                            DataPtr = (ulong)dataPtr,
 10354570                            DataLen = (ulong)data.Length,
 10354571                            Reliable = options.Reliable,
 10354572                            Topic = options.Topic ?? string.Empty,
 10354573                        },
 10354574                    };
 575
 10354576                    if (options.DestinationIdentities != null)
 10338577                    {
 10338578                        request.PublishData.DestinationIdentities.AddRange(
 10338579                            options.DestinationIdentities
 10338580                        );
 10338581                    }
 582
 10354583                    var response = FfiClient.Instance.SendRequest(request);
 10354584                    asyncId = response.PublishData?.AsyncId ?? 0;
 10354585                }
 10354586            }
 587
 588            // Wait for publish callback (outside unsafe context)
 10354589            var publishEvent = await FfiClient.Instance.WaitForEventAsync(
 10354590                e =>
 10372102591                    e.MessageCase == FfiEvent.MessageOneofCase.PublishData
 10372102592                    && e.PublishData?.AsyncId == asyncId,
 10354593                TimeSpan.FromSeconds(30)
 10354594            );
 595
 10354596            if (publishEvent.PublishData?.HasError == true)
 0597            {
 0598                throw new RoomException(
 0599                    $"Failed to publish data: {publishEvent.PublishData.Error}"
 0600                );
 601            }
 10354602        }
 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        )
 4623        {
 4624            if (string.IsNullOrEmpty(name))
 0625                throw new ArgumentException("Data track name must not be empty", nameof(name));
 4626            cancellationToken.ThrowIfCancellationRequested();
 627
 3628            var response = FfiClient.Instance.SendRequest(
 3629                new FfiRequest
 3630                {
 3631                    PublishDataTrack = new PublishDataTrackRequest
 3632                    {
 3633                        LocalParticipantHandle = Handle.HandleId,
 3634                        Options = new DataTrackOptions { Name = name },
 3635                    },
 3636                }
 3637            );
 638
 3639            if (response.PublishDataTrack == null)
 0640                throw new InvalidOperationException("Invalid publish data track response");
 641
 3642            var asyncId = response.PublishDataTrack.AsyncId;
 643
 3644            var publishEvent = await FfiClient.Instance.WaitForEventAsync(
 3645                e =>
 3002646                    e.MessageCase == FfiEvent.MessageOneofCase.PublishDataTrack
 3002647                    && e.PublishDataTrack?.AsyncId == asyncId,
 3648                TimeSpan.FromSeconds(30),
 3649                cancellationToken
 3650            );
 651
 3652            var callback = publishEvent.PublishDataTrack!;
 3653            if (callback.ResultCase == PublishDataTrackCallback.ResultOneofCase.Error)
 0654            {
 0655                throw new PublishDataTrackException(callback.Error.Code, callback.Error.Message);
 656            }
 3657            if (callback.Track?.Handle == null || callback.Track.Info == null)
 0658            {
 0659                throw new RoomException("Publish data track callback has no track");
 660            }
 661
 3662            return new LocalDataTrack(callback.Track);
 3663        }
 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        )
 1675        {
 1676            FfiClient.Instance.SendRequest(
 1677                new FfiRequest
 1678                {
 1679                    SetDataChannelBufferedAmountLowThreshold =
 1680                        new SetDataChannelBufferedAmountLowThresholdRequest
 1681                        {
 1682                            LocalParticipantHandle = Handle.HandleId,
 1683                            Threshold = threshold,
 1684                            Kind = kind,
 1685                        },
 1686                }
 1687            );
 1688        }
 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        )
 1702        {
 1703            var request = new FfiRequest
 1704            {
 1705                PublishSipDtmf = new PublishSipDtmfRequest
 1706                {
 1707                    LocalParticipantHandle = Handle.HandleId,
 1708                    Code = code,
 1709                    Digit = digit ?? string.Empty,
 1710                },
 1711            };
 712
 1713            if (destinationIdentities != null)
 0714            {
 0715                request.PublishSipDtmf.DestinationIdentities.AddRange(destinationIdentities);
 0716            }
 717
 1718            var response = FfiClient.Instance.SendRequest(request);
 1719            var asyncId = response.PublishSipDtmf?.AsyncId ?? 0;
 720
 1721            var dtmfEvent = await FfiClient.Instance.WaitForEventAsync(
 1722                e =>
 1000723                    e.MessageCase == FfiEvent.MessageOneofCase.PublishSipDtmf
 1000724                    && e.PublishSipDtmf?.AsyncId == asyncId,
 1725                TimeSpan.FromSeconds(30)
 1726            );
 727
 1728            if (dtmfEvent.PublishSipDtmf?.HasError == true)
 0729            {
 0730                throw new RoomException(
 0731                    $"Failed to publish SIP DTMF: {dtmfEvent.PublishSipDtmf.Error}"
 0732                );
 733            }
 1734        }
 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)
 2742        {
 2743            if (transcription == null)
 1744                throw new ArgumentNullException(nameof(transcription));
 745
 1746            var request = new FfiRequest
 1747            {
 1748                PublishTranscription = new PublishTranscriptionRequest
 1749                {
 1750                    LocalParticipantHandle = Handle.HandleId,
 1751                    ParticipantIdentity = transcription.ParticipantIdentity,
 1752                    TrackId = transcription.TrackSid,
 1753                },
 1754            };
 755
 5756            foreach (var segment in transcription.Segments)
 1757            {
 1758                request.PublishTranscription.Segments.Add(segment);
 1759            }
 760
 1761            var response = FfiClient.Instance.SendRequest(request);
 1762            var asyncId = response.PublishTranscription?.AsyncId ?? 0;
 763
 1764            var transcriptionEvent = await FfiClient.Instance.WaitForEventAsync(
 1765                e =>
 1000766                    e.MessageCase == FfiEvent.MessageOneofCase.PublishTranscription
 1000767                    && e.PublishTranscription?.AsyncId == asyncId,
 1768                TimeSpan.FromSeconds(30)
 1769            );
 770
 1771            if (transcriptionEvent.PublishTranscription?.HasError == true)
 0772            {
 0773                throw new RoomException(
 0774                    $"Failed to publish transcription: {transcriptionEvent.PublishTranscription.Error}"
 0775                );
 776            }
 1777        }
 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)
 9785        {
 9786            var request = new FfiRequest
 9787            {
 9788                SetLocalMetadata = new SetLocalMetadataRequest
 9789                {
 9790                    LocalParticipantHandle = Handle.HandleId,
 9791                    Metadata = metadata,
 9792                },
 9793            };
 794
 9795            var response = FfiClient.Instance.SendRequest(request);
 9796            var asyncId = response.SetLocalMetadata?.AsyncId ?? 0;
 797
 798            // Wait for metadata update callback
 9799            var metadataEvent = await FfiClient.Instance.WaitForEventAsync(
 9800                e =>
 9012801                    e.MessageCase == FfiEvent.MessageOneofCase.SetLocalMetadata
 9012802                    && e.SetLocalMetadata?.AsyncId == asyncId,
 9803                TimeSpan.FromSeconds(30)
 9804            );
 805
 9806            if (metadataEvent.SetLocalMetadata?.HasError == true)
 0807            {
 0808                throw new RoomException(
 0809                    $"Failed to set metadata: {metadataEvent.SetLocalMetadata.Error}"
 0810                );
 811            }
 9812        }
 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)
 1820        {
 1821            var request = new FfiRequest
 1822            {
 1823                SetLocalName = new SetLocalNameRequest
 1824                {
 1825                    LocalParticipantHandle = Handle.HandleId,
 1826                    Name = name,
 1827                },
 1828            };
 829
 1830            var response = FfiClient.Instance.SendRequest(request);
 1831            var asyncId = response.SetLocalName?.AsyncId ?? 0;
 832
 833            // Wait for name update callback
 1834            var nameEvent = await FfiClient.Instance.WaitForEventAsync(
 1835                e =>
 1001836                    e.MessageCase == FfiEvent.MessageOneofCase.SetLocalName
 1001837                    && e.SetLocalName?.AsyncId == asyncId,
 1838                TimeSpan.FromSeconds(30)
 1839            );
 840
 1841            if (nameEvent.SetLocalName?.HasError == true)
 0842            {
 0843                throw new RoomException($"Failed to set name: {nameEvent.SetLocalName.Error}");
 844            }
 1845        }
 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)
 2857        {
 2858            if (attributes == null)
 0859                throw new ArgumentNullException(nameof(attributes));
 860
 2861            var request = new FfiRequest
 2862            {
 2863                SetLocalAttributes = new SetLocalAttributesRequest
 2864                {
 2865                    LocalParticipantHandle = Handle.HandleId,
 2866                },
 2867            };
 868
 12869            foreach (var kvp in attributes)
 3870            {
 3871                request.SetLocalAttributes.Attributes.Add(
 3872                    new Proto.AttributesEntry { Key = kvp.Key, Value = kvp.Value }
 3873                );
 3874            }
 875
 2876            var response = FfiClient.Instance.SendRequest(request);
 2877            var asyncId = response.SetLocalAttributes?.AsyncId ?? 0;
 878
 2879            var attributesEvent = await FfiClient.Instance.WaitForEventAsync(
 2880                e =>
 2007881                    e.MessageCase == FfiEvent.MessageOneofCase.SetLocalAttributes
 2007882                    && e.SetLocalAttributes?.AsyncId == asyncId,
 2883                TimeSpan.FromSeconds(30)
 2884            );
 885
 2886            if (attributesEvent.SetLocalAttributes?.HasError == true)
 0887            {
 0888                throw new RoomException(
 0889                    $"Failed to set attributes: {attributesEvent.SetLocalAttributes.Error}"
 0890                );
 891            }
 2892        }
 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        )
 2906        {
 2907            if (string.IsNullOrEmpty(message))
 1908                throw new ArgumentException("Message cannot be null or empty", nameof(message));
 909
 1910            var request = new FfiRequest
 1911            {
 1912                SendChatMessage = new SendChatMessageRequest
 1913                {
 1914                    LocalParticipantHandle = Handle.HandleId,
 1915                    Message = message,
 1916                },
 1917            };
 918
 1919            if (destinationIdentities != null)
 0920            {
 0921                request.SendChatMessage.DestinationIdentities.AddRange(destinationIdentities);
 0922            }
 923
 1924            if (!string.IsNullOrEmpty(senderIdentity))
 0925            {
 0926                request.SendChatMessage.SenderIdentity = senderIdentity;
 0927            }
 928
 1929            var response = FfiClient.Instance.SendRequest(request);
 1930            var asyncId = response.SendChatMessage?.AsyncId ?? 0;
 931
 1932            var chatEvent = await FfiClient.Instance.WaitForEventAsync(
 1933                e =>
 1000934                    e.MessageCase == FfiEvent.MessageOneofCase.ChatMessage
 1000935                    && e.ChatMessage?.AsyncId == asyncId,
 1936                TimeSpan.FromSeconds(30)
 1937            );
 938
 1939            if (chatEvent.ChatMessage?.HasError == true)
 0940            {
 0941                throw new RoomException(
 0942                    $"Failed to send chat message: {chatEvent.ChatMessage.Error}"
 0943                );
 944            }
 945
 1946            return chatEvent.ChatMessage!.ChatMessage!;
 1947        }
 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        )
 3963        {
 3964            if (string.IsNullOrEmpty(editText))
 1965                throw new ArgumentException("Edit text cannot be null or empty", nameof(editText));
 2966            if (originalMessage == null)
 1967                throw new ArgumentNullException(nameof(originalMessage));
 968
 1969            var request = new FfiRequest
 1970            {
 1971                EditChatMessage = new EditChatMessageRequest
 1972                {
 1973                    LocalParticipantHandle = Handle.HandleId,
 1974                    EditText = editText,
 1975                    OriginalMessage = originalMessage,
 1976                },
 1977            };
 978
 1979            if (destinationIdentities != null)
 0980            {
 0981                request.EditChatMessage.DestinationIdentities.AddRange(destinationIdentities);
 0982            }
 983
 1984            if (!string.IsNullOrEmpty(senderIdentity))
 0985            {
 0986                request.EditChatMessage.SenderIdentity = senderIdentity;
 0987            }
 988
 1989            var response = FfiClient.Instance.SendRequest(request);
 1990            var asyncId = response.SendChatMessage?.AsyncId ?? 0;
 991
 1992            var chatEvent = await FfiClient.Instance.WaitForEventAsync(
 1993                e =>
 1000994                    e.MessageCase == FfiEvent.MessageOneofCase.ChatMessage
 1000995                    && e.ChatMessage?.AsyncId == asyncId,
 1996                TimeSpan.FromSeconds(30)
 1997            );
 998
 1999            if (chatEvent.ChatMessage?.HasError == true)
 01000            {
 01001                throw new RoomException(
 01002                    $"Failed to edit chat message: {chatEvent.ChatMessage.Error}"
 01003                );
 1004            }
 1005
 11006            return chatEvent.ChatMessage!.ChatMessage!;
 11007        }
 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        )
 701027        {
 701028            streamId ??= Guid.NewGuid().ToString();
 701029            senderIdentity ??= Identity;
 701030            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
 1031
 701032            var header = new DataStream.Types.Header
 701033            {
 701034                StreamId = streamId,
 701035                MimeType = "text/plain",
 701036                Topic = topic ?? string.Empty,
 701037                Timestamp = timestamp,
 701038                TextHeader = new DataStream.Types.TextHeader
 701039                {
 701040                    OperationType = DataStream.Types.OperationType.Create,
 701041                    Version = 0,
 701042                    ReplyToStreamId = string.Empty,
 701043                    Generated = false,
 701044                },
 701045            };
 1046
 701047            if (totalSize.HasValue)
 431048            {
 431049                header.TotalLength = (ulong)totalSize.Value;
 431050            }
 1051
 701052            if (attributes != null)
 21053            {
 141054                foreach (var kvp in attributes)
 41055                {
 41056                    header.Attributes.Add(kvp.Key, kvp.Value);
 41057                }
 21058            }
 1059
 701060            await SendStreamHeaderAsync(header, senderIdentity, destinationIdentities);
 1061
 701062            return new TextStreamWriter(
 701063                this,
 701064                streamId,
 701065                topic ?? string.Empty,
 701066                "text/plain",
 701067                (long)timestamp,
 701068                totalSize,
 701069                attributes,
 701070                destinationIdentities,
 701071                senderIdentity
 701072            );
 701073        }
 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        )
 411091        {
 411092            var totalSize = Encoding.UTF8.GetByteCount(text);
 411093            var writer = await StreamTextAsync(
 411094                topic,
 411095                attributes,
 411096                destinationIdentities,
 411097                streamId,
 411098                null,
 411099                totalSize
 411100            );
 1101
 411102            await writer.WriteAsync(text);
 411103            await writer.CloseAsync();
 1104
 411105            return writer.Info;
 411106        }
 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        )
 371130        {
 371131            streamId ??= Guid.NewGuid().ToString();
 371132            senderIdentity ??= Identity;
 371133            mimeType ??= "application/octet-stream";
 371134            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
 1135
 371136            var header = new DataStream.Types.Header
 371137            {
 371138                StreamId = streamId,
 371139                MimeType = mimeType,
 371140                Topic = topic ?? string.Empty,
 371141                Timestamp = timestamp,
 371142                ByteHeader = new DataStream.Types.ByteHeader { Name = name },
 371143            };
 1144
 371145            if (totalSize.HasValue)
 71146            {
 71147                header.TotalLength = (ulong)totalSize.Value;
 71148            }
 1149
 371150            if (attributes != null)
 11151            {
 51152                foreach (var kvp in attributes)
 11153                {
 11154                    header.Attributes.Add(kvp.Key, kvp.Value);
 11155                }
 11156            }
 1157
 371158            await SendStreamHeaderAsync(header, senderIdentity, destinationIdentities);
 1159
 371160            return new ByteStreamWriter(
 371161                this,
 371162                streamId,
 371163                topic ?? string.Empty,
 371164                mimeType,
 371165                (long)timestamp,
 371166                totalSize,
 371167                attributes,
 371168                name,
 371169                destinationIdentities,
 371170                senderIdentity
 371171            );
 371172        }
 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        )
 61192        {
 61193            if (!System.IO.File.Exists(filePath))
 11194                throw new System.IO.FileNotFoundException("File not found", filePath);
 1195
 51196            var fileInfo = new System.IO.FileInfo(filePath);
 51197            var fileName = fileInfo.Name;
 51198            var fileSize = fileInfo.Length;
 1199
 1200            // Auto-detect MIME type if not provided
 51201            if (string.IsNullOrEmpty(mimeType))
 41202            {
 41203                var extension = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
 41204                mimeType = extension switch
 41205                {
 01206                    ".txt" => "text/plain",
 01207                    ".html" => "text/html",
 11208                    ".json" => "application/json",
 01209                    ".xml" => "application/xml",
 01210                    ".pdf" => "application/pdf",
 01211                    ".jpg" or ".jpeg" => "image/jpeg",
 01212                    ".png" => "image/png",
 01213                    ".gif" => "image/gif",
 01214                    ".mp4" => "video/mp4",
 01215                    ".mp3" => "audio/mpeg",
 01216                    ".wav" => "audio/wav",
 01217                    ".zip" => "application/zip",
 31218                    _ => "application/octet-stream",
 41219                };
 41220            }
 1221
 51222            var writer = await StreamBytesAsync(
 51223                fileName,
 51224                topic,
 51225                mimeType,
 51226                attributes,
 51227                destinationIdentities,
 51228                streamId,
 51229                null,
 51230                fileSize
 51231            );
 1232
 51233            await using (var fileStream = System.IO.File.OpenRead(filePath))
 51234            {
 51235                var buffer = new byte[DataStreamConstants.StreamChunkSize];
 1236                int bytesRead;
 791237                while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
 741238                {
 741239                    var chunk = new byte[bytesRead];
 741240                    Buffer.BlockCopy(buffer, 0, chunk, 0, bytesRead);
 741241                    await writer.WriteAsync(chunk);
 741242                }
 51243            }
 1244
 51245            await writer.CloseAsync();
 51246            return writer.Info;
 51247        }
 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        )
 21258        {
 21259            var request = new FfiRequest
 21260            {
 21261                SetTrackSubscriptionPermissions = new SetTrackSubscriptionPermissionsRequest
 21262                {
 21263                    LocalParticipantHandle = Handle.HandleId,
 21264                    AllParticipantsAllowed = allParticipantsAllowed,
 21265                },
 21266            };
 1267
 21268            if (participantPermissions != null)
 21269            {
 21270                request.SetTrackSubscriptionPermissions.Permissions.AddRange(
 21271                    participantPermissions
 21272                );
 21273            }
 1274
 21275            FfiClient.Instance.SendRequest(request);
 21276        }
 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
 01301        ) => 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        )
 701325        {
 701326            if (string.IsNullOrEmpty(destinationIdentity))
 11327                throw new ArgumentNullException(nameof(destinationIdentity));
 691328            if (string.IsNullOrEmpty(method))
 11329                throw new ArgumentNullException(nameof(method));
 681330            if (maxRoundTripLatency.HasValue && !(maxRoundTripLatency.Value > 0))
 11331                throw new ArgumentOutOfRangeException(
 11332                    nameof(maxRoundTripLatency),
 11333                    maxRoundTripLatency,
 11334                    "The maximum round-trip latency must be positive."
 11335                );
 1336
 671337            var request = new FfiRequest
 671338            {
 671339                PerformRpc = new PerformRpcRequest
 671340                {
 671341                    LocalParticipantHandle = Handle.HandleId,
 671342                    DestinationIdentity = destinationIdentity,
 671343                    Method = method,
 671344                    Payload = payload ?? string.Empty,
 671345                },
 671346            };
 1347
 671348            if (responseTimeout.HasValue)
 371349            {
 371350                request.PerformRpc.ResponseTimeoutMs = (uint)(responseTimeout.Value * 1000);
 371351            }
 1352
 671353            if (maxRoundTripLatency.HasValue)
 21354            {
 21355                request.PerformRpc.MaxRoundTripLatencyMs = (uint)
 21356                    Math.Ceiling(maxRoundTripLatency.Value * 1000);
 21357            }
 1358
 671359            var response = FfiClient.Instance.SendRequest(request);
 671360            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
 671365            var callback = await FfiClient.Instance.WaitForEventAsync(
 671366                e =>
 682201367                    e.MessageCase == FfiEvent.MessageOneofCase.PerformRpc
 682201368                    && e.PerformRpc?.AsyncId == asyncId,
 671369                TimeSpan.FromSeconds((responseTimeout ?? 15) + (maxRoundTripLatency ?? 0) + 15)
 671370            );
 1371
 671372            if (callback.PerformRpc?.Error != null)
 61373            {
 61374                throw RpcError.FromProto(callback.PerformRpc.Error);
 1375            }
 1376
 611377            return callback.PerformRpc?.Payload ?? string.Empty;
 611378        }
 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)
 321391        {
 321392            if (string.IsNullOrEmpty(method))
 21393                throw new ArgumentNullException(nameof(method));
 301394            if (handler == null)
 11395                throw new ArgumentNullException(nameof(handler));
 1396
 291397            _rpcHandlers[method] = handler;
 1398
 291399            var request = new FfiRequest
 291400            {
 291401                RegisterRpcMethod = new RegisterRpcMethodRequest
 291402                {
 291403                    LocalParticipantHandle = Handle.HandleId,
 291404                    Method = method,
 291405                },
 291406            };
 1407
 291408            FfiClient.Instance.SendRequest(request);
 291409        }
 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)
 41416        {
 41417            if (string.IsNullOrEmpty(method))
 21418                return;
 1419
 21420            _rpcHandlers.TryRemove(method, out _);
 1421
 21422            var request = new FfiRequest
 21423            {
 21424                UnregisterRpcMethod = new UnregisterRpcMethodRequest
 21425                {
 21426                    LocalParticipantHandle = Handle.HandleId,
 21427                    Method = method,
 21428                },
 21429            };
 1430
 21431            FfiClient.Instance.SendRequest(request);
 41432        }
 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        )
 641445        {
 641446            RpcError? responseError = null;
 641447            string? responsePayload = null;
 1448
 641449            if (!_rpcHandlers.TryGetValue(method, out var handler))
 01450            {
 01451                responseError = RpcError.BuiltIn(
 01452                    RpcErrorCode.UnsupportedMethod,
 01453                    $"Method '{method}' is not registered"
 01454                );
 01455            }
 1456            else
 641457            {
 1458                try
 641459                {
 641460                    var invocationData = new RpcInvocationData(
 641461                        requestId,
 641462                        callerIdentity,
 641463                        payload,
 641464                        responseTimeoutMs / 1000.0
 641465                    );
 1466
 641467                    responsePayload = await handler(invocationData);
 621468                    responsePayload ??= string.Empty;
 621469                }
 11470                catch (RpcError rpcError)
 11471                {
 11472                    responseError = rpcError;
 11473                }
 11474                catch (Exception ex)
 11475                {
 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
 11478                    Console.Error.WriteLine($"[ERROR] RPC handler for '{method}' threw: {ex}");
 11479                    responseError = RpcError.BuiltIn(RpcErrorCode.ApplicationError);
 11480                }
 641481            }
 1482
 641483            var request = new FfiRequest
 641484            {
 641485                RpcMethodInvocationResponse = new RpcMethodInvocationResponseRequest
 641486                {
 641487                    LocalParticipantHandle = Handle.HandleId,
 641488                    InvocationId = invocationId,
 641489                    Payload = responsePayload ?? string.Empty, // Always set payload, even for errors
 641490                },
 641491            };
 1492
 641493            if (responseError != null)
 21494            {
 21495                request.RpcMethodInvocationResponse.Error = responseError.ToProto();
 21496            }
 1497
 641498            var response = FfiClient.Instance.SendRequest(request);
 1499
 641500            if (!string.IsNullOrEmpty(response.RpcMethodInvocationResponse?.Error))
 01501            {
 01502                throw new RoomException(
 01503                    $"Failed to send RPC invocation response: {response.RpcMethodInvocationResponse.Error}"
 01504                );
 1505            }
 641506        }
 1507
 1508        private async Task SendStreamHeaderAsync(
 1509            DataStream.Types.Header header,
 1510            string senderIdentity,
 1511            string[]? destinationIdentities
 1512        )
 1071513        {
 1071514            var request = new FfiRequest
 1071515            {
 1071516                SendStreamHeader = new SendStreamHeaderRequest
 1071517                {
 1071518                    LocalParticipantHandle = Handle.HandleId,
 1071519                    SenderIdentity = senderIdentity,
 1071520                    Header = header,
 1071521                },
 1071522            };
 1523
 1071524            if (destinationIdentities != null && destinationIdentities.Length > 0)
 581525            {
 581526                request.SendStreamHeader.DestinationIdentities.AddRange(destinationIdentities);
 581527            }
 1528
 1071529            var response = FfiClient.Instance.SendRequest(request);
 1071530            var asyncId = response.SendStreamHeader?.AsyncId ?? 0;
 1531
 1071532            var headerEvent = await FfiClient.Instance.WaitForEventAsync(
 1071533                e =>
 1076431534                    e.MessageCase == FfiEvent.MessageOneofCase.SendStreamHeader
 1076431535                    && e.SendStreamHeader?.AsyncId == asyncId,
 1071536                TimeSpan.FromSeconds(30)
 1071537            );
 1538
 1071539            if (headerEvent.SendStreamHeader?.HasError == true)
 01540            {
 01541                throw new RoomException(
 01542                    $"Failed to send stream header: {headerEvent.SendStreamHeader.Error}"
 01543                );
 1544            }
 1071545        }
 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.
 1560        private readonly Dictionary<string, long> _unsubscribedBeforeSubscribed =
 1561            new Dictionary<string, long>();
 1562
 1563        // A TrackSubscribed later than this is a new subscription, not the stale half of a race
 1564        private static readonly long UnsubscribedBeforeSubscribedWindow = Stopwatch.Frequency * 10;
 1565
 1566        internal RemoteParticipant(FfiHandle handle, ParticipantInfo? info, Room room)
 1567            : 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)
 1573        {
 1574            var now = Stopwatch.GetTimestamp();
 1575            lock (PublicationsLock)
 1576            {
 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
 1580                if (_unsubscribedBeforeSubscribed.Count > 0)
 1581                {
 1582                    var expired = new List<string>();
 1583                    foreach (var record in _unsubscribedBeforeSubscribed)
 1584                    {
 1585                        if (now - record.Value > UnsubscribedBeforeSubscribedWindow)
 1586                            expired.Add(record.Key);
 1587                    }
 1588                    foreach (var sid in expired)
 1589                        _unsubscribedBeforeSubscribed.Remove(sid);
 1590                }
 1591                _unsubscribedBeforeSubscribed[trackSid] = now;
 1592            }
 1593        }
 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)
 1600        {
 1601            lock (PublicationsLock)
 1602            {
 1603                if (!_unsubscribedBeforeSubscribed.Remove(trackSid, out var at))
 1604                    return false;
 1605                return Stopwatch.GetTimestamp() - at <= UnsubscribedBeforeSubscribedWindow;
 1606            }
 1607        }
 1608
 1609        internal void AddPublication(OwnedTrackPublication pub)
 1610        {
 1611            if (pub.Handle == null || pub.Info == null)
 1612                return;
 1613
 1614            var publication = new RemoteTrackPublication(
 1615                FfiHandle.FromId(pub.Handle.Id),
 1616                pub.Info,
 1617                this
 1618            );
 1619
 1620            lock (PublicationsLock)
 1621            {
 1622                _trackPublications[publication.Sid] = publication;
 1623            }
 1624        }
 1625
 1626        internal void RemovePublication(string sid)
 1627        {
 1628            lock (PublicationsLock)
 1629            {
 1630                _trackPublications.Remove(sid);
 1631            }
 1632        }
 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}