< Summary

Information
Class: LiveKit.Rtc.EncodedVideoSource
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/EncodedVideoSource.cs
Line coverage
89%
Covered lines: 82
Uncovered lines: 10
Coverable lines: 92
Total lines: 308
Line coverage: 89.1%
Branch coverage
68%
Covered branches: 17
Total branches: 25
Branch coverage: 68%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Handle()100%11100%
.ctor(...)100%55100%
CaptureFrame(...)50%101087.5%
TakeFeedback()50%7672.72%
CreateTrack(...)100%11100%
ThrowIfDisposed()100%22100%
Dispose()100%22100%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using LiveKit.Proto;
 5using LiveKit.Rtc.Internal;
 6
 7namespace LiveKit.Rtc
 8{
 9    /// <summary>
 10    /// One complete encoded video access unit, without container or RTP headers.
 11    /// </summary>
 12    public class EncodedVideoFrame
 13    {
 14        /// <summary>
 15        /// A single frame encoded with <see cref="Codec"/> (Annex B for H.264/H.265).
 16        /// </summary>
 17        public byte[] Data { get; }
 18
 19        /// <summary>
 20        /// Frame width in pixels.
 21        /// </summary>
 22        public int Width { get; }
 23
 24        /// <summary>
 25        /// Frame height in pixels.
 26        /// </summary>
 27        public int Height { get; }
 28
 29        /// <summary>
 30        /// The codec of <see cref="Data"/>. It must match the publication and stay fixed for the
 31        /// lifetime of the track.
 32        /// </summary>
 33        public Proto.VideoCodec Codec { get; }
 34
 35        /// <summary>
 36        /// Whether this is a key frame or a delta frame.
 37        /// </summary>
 38        public Proto.EncodedFrameType FrameType { get; }
 39
 40        /// <summary>
 41        /// Capture time in microseconds, increasing along the stream.
 42        /// </summary>
 43        public long TimestampUs { get; }
 44
 45        /// <summary>
 46        /// Optional metadata delivered with the frame.
 47        /// </summary>
 48        public Proto.FrameMetadata? Metadata { get; }
 49
 50        /// <summary>
 51        /// Creates an encoded frame to capture with <see cref="EncodedVideoSource.CaptureFrame"/>.
 52        /// </summary>
 53        /// <param name="data">Encoded payload of the frame.</param>
 54        /// <param name="width">Frame width in pixels.</param>
 55        /// <param name="height">Frame height in pixels.</param>
 56        /// <param name="codec">Codec the payload is encoded with.</param>
 57        /// <param name="frameType">Key frame or delta frame.</param>
 58        /// <param name="timestampUs">Capture time in microseconds, increasing along the stream.</param>
 59        /// <param name="metadata">Optional metadata delivered with the frame.</param>
 60        public EncodedVideoFrame(
 61            byte[] data,
 62            int width,
 63            int height,
 64            Proto.VideoCodec codec,
 65            Proto.EncodedFrameType frameType,
 66            long timestampUs,
 67            Proto.FrameMetadata? metadata = null
 68        )
 69        {
 70            if (data == null)
 71                throw new ArgumentNullException(nameof(data));
 72            if (data.Length == 0)
 73                throw new ArgumentException("Encoded frame data must not be empty", nameof(data));
 74            if (width <= 0 || height <= 0)
 75                throw new ArgumentOutOfRangeException(
 76                    width <= 0 ? nameof(width) : nameof(height),
 77                    "Encoded frame dimensions must be positive"
 78                );
 79
 80            Data = data;
 81            Width = width;
 82            Height = height;
 83            Codec = codec;
 84            FrameType = frameType;
 85            TimestampUs = timestampUs;
 86            Metadata = metadata;
 87        }
 88    }
 89
 90    /// <summary>
 91    /// The latest bitrate and frame-rate targets requested by WebRTC for a pre-encoded track.
 92    /// </summary>
 93    public class EncodedRateControl
 94    {
 95        /// <summary>
 96        /// Target bitrate in bits per second.
 97        /// </summary>
 98        public ulong TargetBitrateBps { get; }
 99
 100        /// <summary>
 101        /// Target frame rate in frames per second.
 102        /// </summary>
 103        public double FramerateFps { get; }
 104
 105        internal EncodedRateControl(ulong targetBitrateBps, double framerateFps)
 106        {
 107            TargetBitrateBps = targetBitrateBps;
 108            FramerateFps = framerateFps;
 109        }
 110    }
 111
 112    /// <summary>
 113    /// Encoder feedback accumulated since the previous call to
 114    /// <see cref="EncodedVideoSource.TakeFeedback"/>.
 115    /// </summary>
 116    public class EncodedVideoSourceFeedback
 117    {
 118        /// <summary>
 119        /// Whether a key frame was requested (for example by a late subscriber). Forward it to
 120        /// the upstream encoder.
 121        /// </summary>
 122        public bool KeyframeRequested { get; }
 123
 124        /// <summary>
 125        /// The latest rate-control targets, or null if none were received.
 126        /// </summary>
 127        public EncodedRateControl? RateControl { get; }
 128
 129        internal EncodedVideoSourceFeedback(bool keyframeRequested, EncodedRateControl? rateControl)
 130        {
 131            KeyframeRequested = keyframeRequested;
 132            RateControl = rateControl;
 133        }
 134    }
 135
 136    /// <summary>
 137    /// Publishes pre-encoded video without decoding or re-encoding it.
 138    /// </summary>
 139    /// <remarks>
 140    /// Create a <see cref="LocalVideoTrack"/> from this source and publish it with a
 141    /// <see cref="TrackPublishOptions"/> whose <c>VideoCodec</c> matches the frames,
 142    /// <c>VideoEncoder</c> is <c>Proto.VideoEncoderBackend.EncoderBackendPreEncoded</c> and
 143    /// <c>Simulcast</c> is false. Feed complete access units at the intended playback rate from a
 144    /// single producer; the source does not pace or buffer. Poll <see cref="TakeFeedback"/> and
 145    /// forward key-frame and rate-control requests to the upstream encoder, since a demuxer alone
 146    /// cannot produce a new key frame or adapt the bitrate.
 147    /// </remarks>
 148    public class EncodedVideoSource : IDisposable
 149    {
 150        private readonly FfiHandle _handle;
 151        private bool _disposed;
 152
 153        /// <summary>
 154        /// Initial frame width in pixels.
 155        /// </summary>
 156        public int Width { get; }
 157
 158        /// <summary>
 159        /// Initial frame height in pixels.
 160        /// </summary>
 161        public int Height { get; }
 162
 1163        internal FfiHandle Handle => _handle;
 164
 165        /// <summary>
 166        /// Creates a source with the initial encoded frame dimensions.
 167        /// </summary>
 168        /// <param name="width">Initial frame width in pixels.</param>
 169        /// <param name="height">Initial frame height in pixels.</param>
 81170        public EncodedVideoSource(int width, int height)
 81171        {
 81172            if (width <= 0 || height <= 0)
 2173                throw new ArgumentOutOfRangeException(
 2174                    width <= 0 ? nameof(width) : nameof(height),
 2175                    "Encoded source dimensions must be positive"
 2176                );
 177
 178            Width = width;
 179            Height = height;
 180
 79181            var response = FfiClient.Instance.SendRequest(
 79182                new FfiRequest
 79183                {
 79184                    NewVideoSource = new NewVideoSourceRequest
 79185                    {
 79186                        Type = VideoSourceType.VideoSourceEncoded,
 79187                        Resolution = new VideoSourceResolution
 79188                        {
 79189                            Width = (uint)width,
 79190                            Height = (uint)height,
 79191                        },
 79192                    },
 79193                }
 79194            );
 195
 79196            _handle = FfiHandle.FromId(response.NewVideoSource.Source.Handle.Id);
 79197        }
 198
 199        /// <summary>
 200        /// Submits a frame and returns whether the native source accepted it. The payload is copied
 201        /// before this method returns; acceptance does not guarantee delivery to subscribers.
 202        /// </summary>
 203        /// <param name="frame">The encoded frame to submit.</param>
 204        /// <exception cref="InvalidOperationException">The FFI rejected the frame.</exception>
 205        /// <returns>True when the native source accepted the frame, false when it was dropped.</returns>
 206        public bool CaptureFrame(EncodedVideoFrame frame)
 1207        {
 1208            if (frame == null)
 0209                throw new ArgumentNullException(nameof(frame));
 1210            ThrowIfDisposed();
 211
 212            FfiResponse response;
 213            unsafe
 1214            {
 215                // The FFI reads the payload through the pointer while the request is served: keep
 216                // it pinned through request serialization and the native call.
 1217                fixed (byte* dataPtr = frame.Data)
 1218                {
 1219                    var request = new CaptureEncodedVideoFrameRequest
 1220                    {
 1221                        SourceHandle = _handle.HandleId,
 1222                        Buffer = new EncodedVideoBufferInfo
 1223                        {
 1224                            DataPtr = (ulong)dataPtr,
 1225                            DataLen = (ulong)frame.Data.Length,
 1226                        },
 1227                        Codec = frame.Codec,
 1228                        FrameType = frame.FrameType,
 1229                        Width = (uint)frame.Width,
 1230                        Height = (uint)frame.Height,
 1231                        TimestampUs = frame.TimestampUs,
 1232                    };
 1233                    if (frame.Metadata != null)
 0234                    {
 0235                        request.Metadata = frame.Metadata;
 0236                    }
 237
 1238                    response = FfiClient.Instance.SendRequest(
 1239                        new FfiRequest { CaptureEncodedVideoFrame = request }
 1240                    );
 1241                }
 1242            }
 243
 1244            return response.CaptureEncodedVideoFrame?.Accepted == true;
 1245        }
 246
 247        /// <summary>
 248        /// Consumes the feedback accumulated since the previous call, including key-frame requests
 249        /// from late subscribers.
 250        /// </summary>
 251        /// <returns>The feedback collected since the previous call: key-frame request and rate control.</returns>
 252        public EncodedVideoSourceFeedback TakeFeedback()
 4253        {
 4254            ThrowIfDisposed();
 255
 2256            var response = FfiClient.Instance.SendRequest(
 2257                new FfiRequest
 2258                {
 2259                    TakeEncodedVideoSourceFeedback = new TakeEncodedVideoSourceFeedbackRequest
 2260                    {
 2261                        SourceHandle = _handle.HandleId,
 2262                    },
 2263                }
 2264            );
 265
 2266            var feedback = response.TakeEncodedVideoSourceFeedback;
 2267            EncodedRateControl? rateControl = null;
 2268            if (feedback?.RateControl != null)
 0269            {
 0270                rateControl = new EncodedRateControl(
 0271                    feedback.RateControl.TargetBitrateBps,
 0272                    feedback.RateControl.FramerateFps
 0273                );
 0274            }
 275
 2276            return new EncodedVideoSourceFeedback(feedback?.KeyframeRequested == true, rateControl);
 2277        }
 278
 279        /// <summary>
 280        /// Creates a local video track from this source.
 281        /// </summary>
 282        /// <param name="name">The name of the track.</param>
 283        /// <returns>A local video track fed by this source.</returns>
 284        public LocalVideoTrack CreateTrack(string name = "video")
 2285        {
 2286            ThrowIfDisposed();
 1287            return LocalVideoTrack.Create(name, this);
 1288        }
 289
 290        private void ThrowIfDisposed()
 7291        {
 7292            if (_disposed)
 3293                throw new ObjectDisposedException(nameof(EncodedVideoSource));
 4294        }
 295
 296        /// <summary>
 297        /// Releases the native source. Later calls to <see cref="CaptureFrame"/> throw
 298        /// <see cref="ObjectDisposedException"/>.
 299        /// </summary>
 300        public void Dispose()
 206301        {
 206302            if (_disposed)
 177303                return;
 29304            _disposed = true;
 29305            _handle.Dispose();
 206306        }
 307    }
 308}