< Summary

Information
Class: LiveKit.Rtc.Internal.FfiClient
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/Internal/FfiClient.cs
Line coverage
70%
Covered lines: 174
Uncovered lines: 72
Coverable lines: 246
Total lines: 468
Line coverage: 70.7%
Branch coverage
66%
Covered branches: 71
Total branches: 106
Branch coverage: 66.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
get_Instance()100%11100%
.ctor()100%11100%
ReadSdkVersion()40%101085.71%
Initialize(...)66.66%6690.9%
SendRequest(...)66.66%66100%
WaitForEventAsync()87.5%88100%
OnFfiCallback(...)72.72%472262.96%
AddStreamHandler(...)100%11100%
RemoveStreamHandler(...)100%11100%
DispatchToStream(...)100%151482.6%
Enqueue(...)100%22100%
IsClaimable(...)100%1212100%
RaiseEventReceived(...)100%4473.33%
LogRecord(...)0%2040%
CopyBuffer(...)0%620%
RetrievePtr(...)0%2040%
get_IsDisposed()100%11100%
EnsureInitialized()100%22100%
Dispose()0%7280%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Concurrent;
 5using System.Collections.Generic;
 6using System.IO;
 7using System.Reflection;
 8using System.Runtime.InteropServices;
 9using System.Threading;
 10using System.Threading.Tasks;
 11using Google.Protobuf;
 12using LiveKit.Proto;
 13
 14namespace LiveKit.Rtc.Internal
 15{
 16    /// <summary>
 17    /// Process-wide client of the native <c>livekit_ffi</c> library: sends the requests and delivers the native
 18    /// events. Public for the tests; applications use <see cref="Room"/> and the track, source and stream classes.
 19    /// </summary>
 20    public sealed class FfiClient : IDisposable
 21    {
 122        private static readonly Lazy<FfiClient> _instance = new Lazy<FfiClient>(
 123            () => new FfiClient(),
 124            LazyThreadSafetyMode.ExecutionAndPublication
 125        );
 26
 27        /// <summary>
 28        /// The singleton instance.
 29        /// </summary>
 7602030        public static FfiClient Instance => _instance.Value;
 31
 32        private readonly FfiCallbackDelegate _callbackDelegate;
 33
 34        // Synchronization
 135        private readonly object _lock = new object();
 136        private readonly object _initLock = new object();
 37        private volatile bool _initialized;
 38        private volatile bool _disposed;
 39
 40        // Event Storage
 141        private readonly List<FfiEvent> _eventQueue = new();
 142        private readonly List<(
 143            Func<FfiEvent, bool> Predicate,
 144            TaskCompletionSource<FfiEvent> Tcs
 145        )> _waiters = new List<(Func<FfiEvent, bool>, TaskCompletionSource<FfiEvent>)>();
 46
 47        // Audio, video and data track stream events go straight to their stream, by handle, so their
 48        // cost does not grow with the number of open streams
 149        private readonly ConcurrentDictionary<ulong, Action<FfiEvent>> _streamHandlers = new();
 50
 51        /// <summary>
 52        /// Global event for all FFI messages. Invoked outside the internal lock.
 53        /// </summary>
 54        public event EventHandler<FfiEvent>? EventReceived;
 55
 56        /// <summary>
 57        /// The SDK name reported to the native library, and by it to the LiveKit server.
 58        /// </summary>
 59        public const string SdkName = "dotnet";
 60
 61        /// <summary>
 62        /// SDK version reported to the FFI and sent to the LiveKit server as the client SDK
 63        /// version. Read from the assembly, which the build stamps with the
 64        /// <c>&lt;Version&gt;</c> property of LivekitRtc.csproj, so it never has to be updated
 65        /// by hand on release.
 66        /// </summary>
 167        public static readonly string SdkVersion = ReadSdkVersion();
 68
 169        private FfiClient()
 170        {
 171            _callbackDelegate = OnFfiCallback;
 172        }
 73
 74        private static string ReadSdkVersion()
 175        {
 176            var assembly = typeof(FfiClient).Assembly;
 77
 78            // The informational version is the csproj <Version> as written (e.g. "0.1.4" or
 79            // "0.2.0-beta.1"), plus "+<commit sha>" build metadata appended by SourceLink.
 180            var informational = assembly
 181                .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
 182                ?.InformationalVersion;
 183            if (informational != null && informational.Length > 0)
 184            {
 185                var metadataStart = informational.IndexOf('+');
 186                return metadataStart >= 0
 187                    ? informational.Substring(0, metadataStart)
 188                    : informational;
 89            }
 90
 91            // Fallback: the four-part assembly version, trimmed to major.minor.patch
 092            var version = assembly.GetName().Version;
 093            return version == null ? "0.0.0" : $"{version.Major}.{version.Minor}.{version.Build}";
 194        }
 95
 96        /// <summary>
 97        /// Loads the native library and registers the event callback, once per process.
 98        /// <paramref name="captureLogs"/> forwards the native logs to the console.
 99        /// </summary>
 100        /// <param name="captureLogs">Forwards the native logs to the console when true.</param>
 101        public void Initialize(bool captureLogs = false)
 67102        {
 67103            if (_initialized)
 66104                return;
 105
 1106            lock (_initLock)
 1107            {
 1108                if (_initialized || _disposed)
 0109                    return;
 1110                NativeMethods.Initialize(_callbackDelegate, captureLogs, SdkName, SdkVersion);
 1111                _initialized = true;
 1112            }
 67113        }
 114
 115        /// <summary>
 116        /// Sends a synchronous request to the Rust SDK.
 117        /// </summary>
 118        /// <param name="request">The request to send.</param>
 119        /// <returns>The native response.</returns>
 120        public unsafe FfiResponse SendRequest(FfiRequest request)
 39214121        {
 39214122            EnsureInitialized();
 123
 39214124            byte[] requestData = request.ToByteArray();
 39214125            fixed (byte* dataPtr = requestData)
 39214126            {
 39214127                ulong handleId = NativeMethods.Request(
 39214128                    dataPtr,
 39214129                    (UIntPtr)requestData.Length,
 39214130                    out byte* responsePtr,
 39214131                    out UIntPtr responseLen
 39214132                );
 133
 39214134                if (handleId == FfiHandle.InvalidHandle)
 10135                    throw new InvalidOperationException("FFI request failed: invalid handle");
 136
 137                try
 39204138                {
 139                    // Direct parse from unmanaged memory to reduce allocations
 39204140                    using var stream = new UnmanagedMemoryStream(responsePtr, (long)responseLen);
 39204141                    return FfiResponse.Parser.ParseFrom(stream);
 142                }
 143                finally
 39204144                {
 39204145                    NativeMethods.DropHandle(handleId);
 39204146                }
 147            }
 39204148        }
 149
 150        /// <summary>
 151        /// Async waits for a specific event. Uses the Waiter Pattern to ensure no events
 152        /// are missed between a Request and a Wait call.
 153        /// </summary>
 154        /// <param name="predicate">Selects the awaited event.</param>
 155        /// <param name="timeout">Maximum time to wait; the default when null.</param>
 156        /// <param name="cancellationToken">Cancels the wait.</param>
 157        /// <returns>The first event that satisfies the predicate.</returns>
 158        public async Task<FfiEvent> WaitForEventAsync(
 159            Func<FfiEvent, bool> predicate,
 160            TimeSpan? timeout = null,
 161            CancellationToken cancellationToken = default
 162        )
 27354163        {
 27354164            TaskCompletionSource<FfiEvent> tcs = new(
 27354165                TaskCreationOptions.RunContinuationsAsynchronously
 27354166            );
 167
 27354168            lock (_lock)
 27354169            {
 170                // 1. Check if the event is already in the queue
 54713374171                for (int i = 0; i < _eventQueue.Count; i++)
 27329971172                {
 27329971173                    if (predicate(_eventQueue[i]))
 638174                    {
 638175                        var evt = _eventQueue[i];
 638176                        _eventQueue.RemoveAt(i); // Preserves order of remaining events
 638177                        return evt;
 178                    }
 27329333179                }
 180
 181                // 2. Not found in queue; register a waiter while holding the lock
 26716182                _waiters.Add((predicate, tcs));
 26716183            }
 184
 26716185            using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
 26716186            if (timeout.HasValue)
 26715187                cts.CancelAfter(timeout.Value);
 188
 26716189            using var registration = cts.Token.Register(() =>
 472190            {
 472191                lock (_lock)
 11595192                    _waiters.RemoveAll(w => w.Tcs == tcs);
 472193                tcs.TrySetCanceled();
 27188194            });
 195
 196            try
 26716197            {
 26716198                return await tcs.Task.ConfigureAwait(false);
 199            }
 472200            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
 327201            {
 327202                throw new TimeoutException(
 327203                    $"FFI event wait timed out after {timeout?.TotalSeconds}s"
 327204                );
 205            }
 26882206        }
 207
 208        private void OnFfiCallback(IntPtr dataPtr, UIntPtr dataLen)
 42881209        {
 42881210            if (_disposed)
 0211                return;
 212
 213            try
 42881214            {
 215                FfiEvent ffiEvent;
 216                unsafe
 42881217                {
 42881218                    using var stream = new UnmanagedMemoryStream((byte*)dataPtr, (long)dataLen);
 42881219                    ffiEvent = FfiEvent.Parser.ParseFrom(stream);
 42881220                }
 221
 42881222                if (ffiEvent.MessageCase == FfiEvent.MessageOneofCase.Logs)
 0223                {
 0224                    foreach (var record in ffiEvent.Logs.Records)
 0225                        LogRecord(record);
 0226                    return;
 227                }
 228
 42881229                if (ffiEvent.MessageCase == FfiEvent.MessageOneofCase.Panic)
 0230                {
 0231                    Console.Error.WriteLine($"FFI Panic: {ffiEvent.Panic.Message}");
 0232                    Environment.Exit(1);
 0233                    return;
 234                }
 235
 42881236                List<TaskCompletionSource<FfiEvent>> toTrigger = new();
 237
 42881238                lock (_lock)
 42881239                {
 42881240                    if (_disposed)
 0241                        return;
 242
 243                    // Match against active waiters
 1523508244                    for (int i = _waiters.Count - 1; i >= 0; i--)
 718873245                    {
 718873246                        if (_waiters[i].Predicate(ffiEvent))
 26244247                        {
 26244248                            toTrigger.Add(_waiters[i].Tcs);
 26244249                            _waiters.RemoveAt(i);
 26244250                        }
 718873251                    }
 252
 253                    // If no one is waiting for this specifically, queue it, unless it is a kind
 254                    // that is only ever consumed through EventReceived (room, track and stream
 255                    // fan-out events): those would fill the queue, evict pending callbacks and
 256                    // make every wait scan a thousand stale frames.
 42881257                    if (toTrigger.Count == 0 && IsClaimable(ffiEvent))
 3760258                    {
 3760259                        Enqueue(ffiEvent);
 3760260                    }
 42881261                }
 262
 263                // Trigger TaskCompletionSources and Events OUTSIDE the lock to prevent deadlocks
 181131264                foreach (var tcs in toTrigger)
 26244265                {
 266                    // The waiter may have been cancelled or timed out meanwhile: keep the event
 267                    // for a later wait on the same predicate instead of dropping it.
 26244268                    if (!tcs.TrySetResult(ffiEvent))
 0269                    {
 0270                        lock (_lock)
 0271                        {
 0272                            Enqueue(ffiEvent);
 0273                        }
 0274                    }
 26244275                }
 42881276                DispatchToStream(ffiEvent);
 42881277                RaiseEventReceived(ffiEvent);
 42881278            }
 0279            catch (Exception ex)
 0280            {
 0281                Console.Error.WriteLine($"Error in FFI Callback: {ex}");
 0282            }
 42881283        }
 284
 285        /// <summary>
 286        /// Delivers the audio, video, data track or data stream reader events of
 287        /// <paramref name="streamHandle"/> to <paramref name="handler"/>, on the native thread that
 288        /// raised them. They still reach <see cref="EventReceived"/> too.
 289        /// </summary>
 290        /// <param name="streamHandle">Native handle of the stream or reader.</param>
 291        /// <param name="handler">Receives the events; it must not block.</param>
 292        internal void AddStreamHandler(ulong streamHandle, Action<FfiEvent> handler) =>
 165293            _streamHandlers[streamHandle] = handler;
 294
 295        /// <summary>
 296        /// Stops delivering the events of <paramref name="streamHandle"/>.
 297        /// </summary>
 298        /// <param name="streamHandle">Native handle of the stream.</param>
 299        internal void RemoveStreamHandler(ulong streamHandle) =>
 257300            _streamHandlers.TryRemove(streamHandle, out _);
 301
 302        private void DispatchToStream(FfiEvent ffiEvent)
 42881303        {
 304            ulong streamHandle;
 42881305            switch (ffiEvent.MessageCase)
 306            {
 307                case FfiEvent.MessageOneofCase.AudioStreamEvent:
 985308                    streamHandle = ffiEvent.AudioStreamEvent.StreamHandle;
 985309                    break;
 310                case FfiEvent.MessageOneofCase.VideoStreamEvent:
 114311                    streamHandle = ffiEvent.VideoStreamEvent.StreamHandle;
 114312                    break;
 313                case FfiEvent.MessageOneofCase.DataTrackStreamEvent:
 9314                    streamHandle = ffiEvent.DataTrackStreamEvent.StreamHandle;
 9315                    break;
 316                case FfiEvent.MessageOneofCase.TextStreamReaderEvent:
 746317                    streamHandle = ffiEvent.TextStreamReaderEvent.ReaderHandle;
 746318                    break;
 319                case FfiEvent.MessageOneofCase.ByteStreamReaderEvent:
 668320                    streamHandle = ffiEvent.ByteStreamReaderEvent.ReaderHandle;
 668321                    break;
 322                default:
 40359323                    return;
 324            }
 325
 2522326            if (!_streamHandlers.TryGetValue(streamHandle, out var handler))
 10327                return;
 328            try
 2512329            {
 2512330                handler(ffiEvent);
 2512331            }
 0332            catch (Exception ex)
 0333            {
 0334                Console.Error.WriteLine($"[ERROR] FFI stream event handler threw: {ex}");
 0335            }
 42881336        }
 337
 338        // Caller holds _lock
 339        private void Enqueue(FfiEvent ffiEvent)
 3760340        {
 3760341            _eventQueue.Add(ffiEvent);
 3760342            if (_eventQueue.Count > 1000)
 2123343                _eventQueue.RemoveAt(0); // Circular buffer: remove oldest
 3760344        }
 345
 346        private static bool IsClaimable(FfiEvent ffiEvent)
 16646347        {
 16646348            switch (ffiEvent.MessageCase)
 349            {
 350                case FfiEvent.MessageOneofCase.RoomEvent:
 351                case FfiEvent.MessageOneofCase.TrackEvent:
 352                case FfiEvent.MessageOneofCase.AudioStreamEvent:
 353                case FfiEvent.MessageOneofCase.VideoStreamEvent:
 354                case FfiEvent.MessageOneofCase.DataTrackStreamEvent:
 355                case FfiEvent.MessageOneofCase.TextStreamReaderEvent:
 356                case FfiEvent.MessageOneofCase.ByteStreamReaderEvent:
 357                case FfiEvent.MessageOneofCase.RpcMethodInvocation:
 12886358                    return false;
 359                default:
 3760360                    return true;
 361            }
 16646362        }
 363
 364        // One throwing subscriber must not hide the event from the others (a second Room, the
 365        // audio and video streams...)
 366        private void RaiseEventReceived(FfiEvent ffiEvent)
 42881367        {
 42881368            var handlers = EventReceived;
 42881369            if (handlers == null)
 5103370                return;
 371
 252194372            foreach (var handler in handlers.GetInvocationList())
 69430373            {
 374                try
 69430375                {
 69430376                    ((EventHandler<FfiEvent>)handler)(this, ffiEvent);
 69430377                }
 0378                catch (Exception ex)
 0379                {
 0380                    Console.Error.WriteLine($"[ERROR] FFI event subscriber threw: {ex}");
 0381                }
 69430382            }
 42881383        }
 384
 385        private void LogRecord(LogRecord record)
 0386        {
 0387            var level = record.Level switch
 0388            {
 0389                LogLevel.LogError => "ERROR",
 0390                LogLevel.LogWarn => "WARN",
 0391                LogLevel.LogInfo => "INFO",
 0392                _ => "DEBUG",
 0393            };
 0394            Console.WriteLine($"[{level}] {record.Target} - {record.Message}");
 0395        }
 396
 397        /// <summary>
 398        /// Copies <paramref name="len"/> bytes from native memory. Implemented in managed code:
 399        /// the native library has no copy entry point (calling the old binding threw
 400        /// <see cref="EntryPointNotFoundException"/>).
 401        /// </summary>
 402        /// <param name="ptr">Address of the native buffer.</param>
 403        /// <param name="len">Number of bytes to copy.</param>
 404        /// <returns>A managed copy of the bytes.</returns>
 405        public byte[] CopyBuffer(ulong ptr, int len)
 0406        {
 0407            byte[] buffer = new byte[len];
 0408            if (len > 0)
 0409            {
 0410                Marshal.Copy((IntPtr)ptr, buffer, 0, len);
 0411            }
 0412            return buffer;
 0413        }
 414
 415        /// <summary>
 416        /// Never worked: the native library has no such entry point, and a pointer to a managed
 417        /// array is only valid while the array is pinned. Pin the buffer around the request
 418        /// instead (see <c>AudioFrame.WithPinnedBuffer</c>).
 419        /// </summary>
 420        /// <param name="data">The managed array.</param>
 421        /// <returns>A pointer that is only valid while the array stays pinned.</returns>
 422        [Obsolete(
 423            "The native entry point does not exist and the returned pointer would not be pinned. Pin the buffer with 'fi
 424        )]
 425        public unsafe ulong RetrievePtr(byte[] data)
 0426        {
 0427            fixed (byte* ptr = data)
 0428                return NativeMethods.RetrievePtr(ptr, (UIntPtr)data.Length);
 0429        }
 430
 431        // Whether Dispose released the native library: handle releases skip the requests that
 432        // precede them, since the library dropped every handle then
 1273433        internal bool IsDisposed => _disposed;
 434
 435        private void EnsureInitialized()
 39214436        {
 39214437            if (!_initialized)
 1438                Initialize();
 39214439        }
 440
 441        /// <summary>
 442        /// Releases the native library. The SDK cannot be used in this process afterwards.
 443        /// </summary>
 444        public void Dispose()
 0445        {
 0446            if (_disposed)
 0447                return;
 0448            lock (_initLock)
 0449            {
 0450                if (_disposed)
 0451                    return;
 0452                _disposed = true;
 453
 0454                lock (_lock)
 0455                {
 456                    // Cancel all pending async waiters
 0457                    foreach (var waiter in _waiters)
 0458                        waiter.Tcs.TrySetCanceled();
 0459                    _waiters.Clear();
 0460                    _eventQueue.Clear();
 0461                }
 462
 0463                if (_initialized)
 0464                    NativeMethods.Dispose();
 0465            }
 0466        }
 467    }
 468}