< Summary

Information
Line coverage
91%
Covered lines: 330
Uncovered lines: 29
Coverable lines: 359
Total lines: 583
Line coverage: 91.9%
Branch coverage
76%
Covered branches: 39
Total branches: 51
Branch coverage: 76.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%4476.19%
Create(...)100%11100%
FromOwnedInfo(...)66.66%66100%
WithPinnedBuffer(...)66.66%66100%
get_Width()100%11100%
get_Height()100%11100%
get_Type()100%11100%
get_Data()100%210%
get_DataMutable()100%11100%
get_DataBytes()100%11100%
get_Userdata()100%210%
GetPlane(...)50%2288.88%
Convert(...)75%8887.09%
Clone()100%210%
ToString()100%210%
GetBufferSize(...)83.33%121292.3%
GetStride(...)75%4483.33%
GetPlaneInfos(...)100%22100%
GetPlaneInfosLocal(...)100%77100%

File(s)

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

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using LiveKit.Proto;
 6using LiveKit.Rtc.Internal;
 7
 8namespace LiveKit.Rtc
 9{
 10    /// <summary>
 11    /// Represents a video frame with associated metadata and pixel data.
 12    /// </summary>
 13    public class VideoFrame
 14    {
 15        private readonly int _width;
 16        private readonly int _height;
 17        private readonly Proto.VideoBufferType _type;
 18        private readonly byte[] _data;
 19        private readonly Dictionary<string, object> _userdata;
 20
 21        /// <summary>
 22        /// Initializes a new VideoFrame instance.
 23        /// </summary>
 24        /// <param name="width">The width of the video frame in pixels.</param>
 25        /// <param name="height">The height of the video frame in pixels.</param>
 26        /// <param name="type">The format type of the video frame data.</param>
 27        /// <param name="data">The raw pixel data for the video frame.</param>
 28        /// <param name="userdata">Optional user data dictionary.</param>
 200129        public VideoFrame(
 200130            int width,
 200131            int height,
 200132            Proto.VideoBufferType type,
 200133            byte[] data,
 200134            Dictionary<string, object>? userdata = null
 200135        )
 200136        {
 200137            int requiredSize = GetBufferSize(type, width, height);
 200138            if (data.Length < requiredSize)
 039            {
 040                throw new ArgumentException(
 041                    $"Data length ({data.Length}) must be >= required size ({requiredSize}) for {type} format",
 042                    nameof(data)
 043                );
 44            }
 45
 200146            _width = width;
 200147            _height = height;
 200148            _type = type;
 200149            _data = data;
 200150            _userdata = userdata ?? new Dictionary<string, object>();
 200151        }
 52
 53        /// <summary>
 54        /// Creates a new empty VideoFrame with the specified parameters.
 55        /// </summary>
 56        /// <param name="width">Width in pixels.</param>
 57        /// <param name="height">Height in pixels.</param>
 58        /// <param name="type">Pixel format of the buffer.</param>
 59        /// <returns>A frame of that size and format with a zeroed buffer.</returns>
 60        public static VideoFrame Create(int width, int height, VideoBufferType type)
 72061        {
 72062            int size = GetBufferSize(type, width, height);
 72063            var data = new byte[size];
 72064            return new VideoFrame(width, height, type, data);
 72065        }
 66
 67        /// <summary>
 68        /// Creates a VideoFrame from an owned FFI buffer.
 69        /// </summary>
 70        internal static VideoFrame FromOwnedInfo(OwnedVideoBuffer ownedInfo)
 93071        {
 72            // Own the native buffer first, so it is released even if the copy below throws
 93073            using var handle = FfiHandle.FromId(ownedInfo.Handle.Id);
 74
 93075            var info = ownedInfo.Info;
 93076            int dataLen = GetBufferSize(
 93077                (VideoBufferType)info.Type,
 93078                (int)info.Width,
 93079                (int)info.Height
 93080            );
 81
 82            // Copy the pixels from native memory. This runs on the FFI callback thread, so it
 83            // must be a block copy, not a byte loop (a 1080p frame is 3 MB).
 93084            var data = new byte[dataLen];
 93085            if (dataLen > 0)
 93086            {
 87                unsafe
 93088                {
 93089                    fixed (byte* destination = data)
 93090                    {
 93091                        Buffer.MemoryCopy((void*)info.DataPtr, destination, dataLen, dataLen);
 93092                    }
 93093                }
 93094            }
 95
 93096            return new VideoFrame(
 93097                (int)info.Width,
 93098                (int)info.Height,
 93099                (VideoBufferType)info.Type,
 930100                data
 930101            );
 930102        }
 103
 104        /// <summary>
 105        /// Pins the pixels while a synchronous FFI operation consumes the buffer.
 106        /// The callback must not retain the buffer or plane pointers after returning.
 107        /// </summary>
 108        internal TResult WithPinnedBuffer<TResult>(Func<VideoBufferInfo, TResult> callback)
 3780109        {
 110            unsafe
 3780111            {
 3780112                fixed (byte* ptr = _data)
 3780113                {
 3780114                    var info = new VideoBufferInfo
 3780115                    {
 3780116                        Width = (uint)_width,
 3780117                        Height = (uint)_height,
 3780118                        Type = (LiveKit.Proto.VideoBufferType)_type,
 3780119                        DataPtr = (ulong)ptr,
 3780120                        Stride = (uint)GetStride(_type, _width),
 3780121                    };
 122
 123                    // Add component infos
 3780124                    var components = GetPlaneInfos((ulong)ptr, _type, _width, _height);
 29902125                    foreach (var component in components)
 9281126                    {
 9281127                        info.Components.Add(component);
 9281128                    }
 129
 3780130                    return callback(info);
 131                }
 132            }
 3779133        }
 134
 135        /// <summary>Gets the width of the video frame in pixels.</summary>
 327136        public int Width => _width;
 137
 138        /// <summary>Gets the height of the video frame in pixels.</summary>
 327139        public int Height => _height;
 140
 141        /// <summary>Gets the format type of the video frame.</summary>
 15142        public VideoBufferType Type => _type;
 143
 144        /// <summary>Gets the raw pixel data.</summary>
 0145        public ReadOnlySpan<byte> Data => _data;
 146
 147        /// <summary>Gets the raw pixel data as a mutable span.</summary>
 61148        public Span<byte> DataMutable => _data;
 149
 150        /// <summary>Gets the raw pixel data as a byte array.</summary>
 280855151        public byte[] DataBytes => _data;
 152
 153        /// <summary>Gets the user data associated with the frame.</summary>
 0154        public Dictionary<string, object> Userdata => _userdata;
 155
 156        /// <summary>
 157        /// Gets a specific plane from the video frame data.
 158        /// </summary>
 159        /// <param name="planeIndex">The index of the plane (0-based).</param>
 160        /// <returns>The plane data, or null if the index is out of bounds.</returns>
 161        public byte[]? GetPlane(int planeIndex)
 62162        {
 62163            var planeInfos = GetPlaneInfosLocal(_type, _width, _height);
 62164            if (planeIndex >= planeInfos.Count)
 0165                return null;
 166
 62167            var planeInfo = planeInfos[planeIndex];
 62168            var planeData = new byte[planeInfo.Size];
 62169            Array.Copy(_data, planeInfo.Offset, planeData, 0, planeInfo.Size);
 62170            return planeData;
 62171        }
 172
 173        /// <summary>
 174        /// Converts the video frame to a different format type.
 175        /// </summary>
 176        /// <param name="targetType">The target format type.</param>
 177        /// <param name="flipY">If true, flip the frame vertically.</param>
 178        /// <returns>A new VideoFrame in the target format.</returns>
 179        public VideoFrame Convert(VideoBufferType targetType, bool flipY = false)
 852180        {
 181            // The FFI reads the pixels synchronously, before SendRequest returns and the result
 182            // is an independent native buffer, so the pin only needs to cover the request.
 852183            var response = WithPinnedBuffer(buffer =>
 852184            {
 852185                // Unlike capture (and libwebrtc), the FFI's I010 converter reads each plane as a u16
 852186                // slice of size / 2 samples and requires samples >= stride * rows, so it expects
 852187                // strides in samples rather than bytes.
 852188                if (_type == VideoBufferType.I010)
 2189                {
 18190                    foreach (var component in buffer.Components)
 6191                        component.Stride /= 2;
 2192                }
 852193
 852194                return FfiClient.Instance.SendRequest(
 852195                    new FfiRequest
 852196                    {
 852197                        VideoConvert = new VideoConvertRequest
 852198                        {
 852199                            FlipY = flipY,
 852200                            DstType = (LiveKit.Proto.VideoBufferType)targetType,
 852201                            Buffer = buffer,
 852202                        },
 852203                    }
 852204                );
 1704205            });
 206
 852207            if (!string.IsNullOrEmpty(response.VideoConvert?.Error))
 0208            {
 0209                throw new InvalidOperationException(
 0210                    $"Video conversion failed: {response.VideoConvert.Error}"
 0211                );
 212            }
 213
 852214            return FromOwnedInfo(response.VideoConvert!.Buffer);
 852215        }
 216
 217        /// <summary>
 218        /// Creates a copy of this video frame.
 219        /// </summary>
 220        /// <returns>A deep copy of the frame, with its own pixel buffer.</returns>
 221        public VideoFrame Clone()
 0222        {
 0223            var dataCopy = new byte[_data.Length];
 0224            Array.Copy(_data, dataCopy, _data.Length);
 0225            return new VideoFrame(
 0226                _width,
 0227                _height,
 0228                _type,
 0229                dataCopy,
 0230                new Dictionary<string, object>(_userdata)
 0231            );
 0232        }
 233
 234        /// <inheritdoc />
 235        public override string ToString()
 0236        {
 0237            return $"VideoFrame(width={_width}, height={_height}, type={_type})";
 0238        }
 239
 240        #region Static Helpers
 241
 242        /// <summary>
 243        /// Gets the buffer size in bytes for a video buffer type.
 244        /// </summary>
 245        /// <param name="type">Pixel format of the buffer.</param>
 246        /// <param name="width">Width in pixels.</param>
 247        /// <param name="height">Height in pixels.</param>
 248        /// <returns>Number of bytes a frame of that format and size occupies.</returns>
 249        public static int GetBufferSize(Proto.VideoBufferType type, int width, int height)
 3651250        {
 3651251            switch (type)
 252            {
 253                case Proto.VideoBufferType.Argb:
 254                case Proto.VideoBufferType.Abgr:
 255                case Proto.VideoBufferType.Rgba:
 256                case Proto.VideoBufferType.Bgra:
 1471257                    return width * height * 4;
 258
 259                case Proto.VideoBufferType.Rgb24:
 0260                    return width * height * 3;
 261
 262                case Proto.VideoBufferType.I420:
 2134263                {
 2134264                    int chromaWidth = (width + 1) / 2;
 2134265                    int chromaHeight = (height + 1) / 2;
 2134266                    return width * height + chromaWidth * chromaHeight * 2;
 267                }
 268
 269                case VideoBufferType.I420A:
 10270                {
 10271                    int chromaWidth = (width + 1) / 2;
 10272                    int chromaHeight = (height + 1) / 2;
 10273                    return width * height * 2 + chromaWidth * chromaHeight * 2;
 274                }
 275
 276                case VideoBufferType.I422:
 10277                {
 10278                    int chromaWidth = (width + 1) / 2;
 10279                    return width * height + chromaWidth * height * 2;
 280                }
 281
 282                case VideoBufferType.I444:
 10283                    return width * height * 3;
 284
 285                case VideoBufferType.I010:
 10286                {
 10287                    int chromaWidth = (width + 1) / 2;
 10288                    int chromaHeight = (height + 1) / 2;
 10289                    return width * height * 2 + chromaWidth * chromaHeight * 4;
 290                }
 291
 292                case VideoBufferType.Nv12:
 6293                {
 6294                    int chromaWidth = (width + 1) / 2;
 6295                    int chromaHeight = (height + 1) / 2;
 6296                    return width * height + chromaWidth * chromaHeight * 2;
 297                }
 298
 299                default:
 0300                    throw new ArgumentException($"Unsupported video buffer type: {type}");
 301            }
 3651302        }
 303
 304        /// <summary>
 305        /// Gets the stride for a video buffer type.
 306        /// </summary>
 307        /// <param name="type">Pixel format of the buffer.</param>
 308        /// <param name="width">Width in pixels.</param>
 309        /// <returns>Number of bytes per row of the first plane.</returns>
 310        public static int GetStride(VideoBufferType type, int width)
 3780311        {
 3780312            switch (type)
 313            {
 314                case VideoBufferType.Argb:
 315                case VideoBufferType.Abgr:
 316                case VideoBufferType.Rgba:
 317                case VideoBufferType.Bgra:
 687318                    return width * 4;
 319
 320                case VideoBufferType.Rgb24:
 0321                    return width * 3;
 322
 323                default:
 3093324                    return 0; // Planar formats don't have a single stride
 325            }
 3780326        }
 327
 328        /// <summary>
 329        /// Describes the planes of a buffer starting at <paramref name="addr"/> the way the FFI
 330        /// expects them. Derived from <see cref="GetPlaneInfosLocal"/> so both always agree.
 331        /// Packed formats have no planes.
 332        /// </summary>
 333        private static List<VideoBufferInfo.Types.ComponentInfo> GetPlaneInfos(
 334            ulong addr,
 335            VideoBufferType type,
 336            int width,
 337            int height
 338        )
 3780339        {
 3780340            var result = new List<VideoBufferInfo.Types.ComponentInfo>();
 29902341            foreach (var plane in GetPlaneInfosLocal(type, width, height))
 9281342            {
 9281343                result.Add(
 9281344                    new VideoBufferInfo.Types.ComponentInfo
 9281345                    {
 9281346                        DataPtr = addr + (ulong)plane.Offset,
 9281347                        Stride = (uint)plane.Stride,
 9281348                        Size = (uint)plane.Size,
 9281349                    }
 9281350                );
 9281351            }
 3780352            return result;
 3780353        }
 354
 355        private struct PlaneInfo
 356        {
 357            public int Offset;
 358            public int Size;
 359            public int Stride;
 360        }
 361
 362        private static List<PlaneInfo> GetPlaneInfosLocal(
 363            VideoBufferType type,
 364            int width,
 365            int height
 366        )
 3842367        {
 3842368            var result = new List<PlaneInfo>();
 369
 3842370            switch (type)
 371            {
 372                case VideoBufferType.I420:
 3102373                {
 3102374                    int chromaWidth = (width + 1) / 2;
 3102375                    int chromaHeight = (height + 1) / 2;
 376
 3102377                    int ySize = width * height;
 3102378                    int uvSize = chromaWidth * chromaHeight;
 379
 3102380                    result.Add(
 3102381                        new PlaneInfo
 3102382                        {
 3102383                            Offset = 0,
 3102384                            Size = ySize,
 3102385                            Stride = width,
 3102386                        }
 3102387                    );
 3102388                    result.Add(
 3102389                        new PlaneInfo
 3102390                        {
 3102391                            Offset = ySize,
 3102392                            Size = uvSize,
 3102393                            Stride = chromaWidth,
 3102394                        }
 3102395                    );
 3102396                    result.Add(
 3102397                        new PlaneInfo
 3102398                        {
 3102399                            Offset = ySize + uvSize,
 3102400                            Size = uvSize,
 3102401                            Stride = chromaWidth,
 3102402                        }
 3102403                    );
 3102404                    break;
 405                }
 406
 407                case VideoBufferType.I420A:
 13408                {
 13409                    int chromaWidth = (width + 1) / 2;
 13410                    int chromaHeight = (height + 1) / 2;
 411
 13412                    int ySize = width * height;
 13413                    int uvSize = chromaWidth * chromaHeight;
 414
 13415                    result.Add(
 13416                        new PlaneInfo
 13417                        {
 13418                            Offset = 0,
 13419                            Size = ySize,
 13420                            Stride = width,
 13421                        }
 13422                    );
 13423                    result.Add(
 13424                        new PlaneInfo
 13425                        {
 13426                            Offset = ySize,
 13427                            Size = uvSize,
 13428                            Stride = chromaWidth,
 13429                        }
 13430                    );
 13431                    result.Add(
 13432                        new PlaneInfo
 13433                        {
 13434                            Offset = ySize + uvSize,
 13435                            Size = uvSize,
 13436                            Stride = chromaWidth,
 13437                        }
 13438                    );
 13439                    result.Add(
 13440                        new PlaneInfo
 13441                        {
 13442                            Offset = ySize + uvSize * 2,
 13443                            Size = ySize,
 13444                            Stride = width,
 13445                        }
 13446                    );
 13447                    break;
 448                }
 449
 450                case VideoBufferType.I422:
 11451                {
 11452                    int chromaWidth = (width + 1) / 2;
 453
 11454                    int ySize = width * height;
 11455                    int uvSize = chromaWidth * height;
 456
 11457                    result.Add(
 11458                        new PlaneInfo
 11459                        {
 11460                            Offset = 0,
 11461                            Size = ySize,
 11462                            Stride = width,
 11463                        }
 11464                    );
 11465                    result.Add(
 11466                        new PlaneInfo
 11467                        {
 11468                            Offset = ySize,
 11469                            Size = uvSize,
 11470                            Stride = chromaWidth,
 11471                        }
 11472                    );
 11473                    result.Add(
 11474                        new PlaneInfo
 11475                        {
 11476                            Offset = ySize + uvSize,
 11477                            Size = uvSize,
 11478                            Stride = chromaWidth,
 11479                        }
 11480                    );
 11481                    break;
 482                }
 483
 484                case VideoBufferType.I444:
 11485                {
 11486                    int planeSize = width * height;
 11487                    result.Add(
 11488                        new PlaneInfo
 11489                        {
 11490                            Offset = 0,
 11491                            Size = planeSize,
 11492                            Stride = width,
 11493                        }
 11494                    );
 11495                    result.Add(
 11496                        new PlaneInfo
 11497                        {
 11498                            Offset = planeSize,
 11499                            Size = planeSize,
 11500                            Stride = width,
 11501                        }
 11502                    );
 11503                    result.Add(
 11504                        new PlaneInfo
 11505                        {
 11506                            Offset = planeSize * 2,
 11507                            Size = planeSize,
 11508                            Stride = width,
 11509                        }
 11510                    );
 11511                    break;
 512                }
 513
 514                case VideoBufferType.I010:
 11515                {
 516                    // 16-bit samples: strides and sizes are in bytes.
 11517                    int chromaWidth = (width + 1) / 2;
 11518                    int chromaHeight = (height + 1) / 2;
 519
 11520                    int ySize = width * height * 2;
 11521                    int uvSize = chromaWidth * chromaHeight * 2;
 522
 11523                    result.Add(
 11524                        new PlaneInfo
 11525                        {
 11526                            Offset = 0,
 11527                            Size = ySize,
 11528                            Stride = width * 2,
 11529                        }
 11530                    );
 11531                    result.Add(
 11532                        new PlaneInfo
 11533                        {
 11534                            Offset = ySize,
 11535                            Size = uvSize,
 11536                            Stride = chromaWidth * 2,
 11537                        }
 11538                    );
 11539                    result.Add(
 11540                        new PlaneInfo
 11541                        {
 11542                            Offset = ySize + uvSize,
 11543                            Size = uvSize,
 11544                            Stride = chromaWidth * 2,
 11545                        }
 11546                    );
 11547                    break;
 548                }
 549
 550                case VideoBufferType.Nv12:
 7551                {
 7552                    int chromaWidth = (width + 1) / 2;
 7553                    int chromaHeight = (height + 1) / 2;
 554
 7555                    int ySize = width * height;
 7556                    int uvSize = chromaWidth * chromaHeight * 2;
 557
 7558                    result.Add(
 7559                        new PlaneInfo
 7560                        {
 7561                            Offset = 0,
 7562                            Size = ySize,
 7563                            Stride = width,
 7564                        }
 7565                    );
 7566                    result.Add(
 7567                        new PlaneInfo
 7568                        {
 7569                            Offset = ySize,
 7570                            Size = uvSize,
 7571                            Stride = chromaWidth * 2,
 7572                        }
 7573                    );
 7574                    break;
 575                }
 576            }
 577
 3842578            return result;
 3842579        }
 580
 581        #endregion
 582    }
 583}