< Summary - Jellyfin

Information
Class: MediaBrowser.MediaEncoding.Probing.ProbeResultNormalizer
Assembly: MediaBrowser.MediaEncoding
File(s): /srv/git/jellyfin/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
Line coverage
81%
Covered lines: 640
Uncovered lines: 146
Coverable lines: 786
Total lines: 1796
Line coverage: 81.4%
Branch coverage
72%
Covered branches: 517
Total branches: 718
Branch coverage: 72%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/2/2026 - 12:12:50 AM Line coverage: 79.4% (607/764) Branch coverage: 74.6% (478/640) Total lines: 17555/8/2026 - 12:15:13 AM Line coverage: 79.5% (610/767) Branch coverage: 74.7% (480/642) Total lines: 17615/10/2026 - 12:15:26 AM Line coverage: 79.4% (611/769) Branch coverage: 74.6% (481/644) Total lines: 17685/20/2026 - 12:15:44 AM Line coverage: 79.4% (611/769) Branch coverage: 65.3% (421/644) Total lines: 17686/30/2026 - 12:15:32 AM Line coverage: 81.3% (638/784) Branch coverage: 71.7% (515/718) Total lines: 17827/22/2026 - 12:16:22 AM Line coverage: 81.3% (636/782) Branch coverage: 71.8% (513/714) Total lines: 17847/26/2026 - 12:17:51 AM Line coverage: 81.4% (640/786) Branch coverage: 72% (517/718) Total lines: 1796 5/2/2026 - 12:12:50 AM Line coverage: 79.4% (607/764) Branch coverage: 74.6% (478/640) Total lines: 17555/8/2026 - 12:15:13 AM Line coverage: 79.5% (610/767) Branch coverage: 74.7% (480/642) Total lines: 17615/10/2026 - 12:15:26 AM Line coverage: 79.4% (611/769) Branch coverage: 74.6% (481/644) Total lines: 17685/20/2026 - 12:15:44 AM Line coverage: 79.4% (611/769) Branch coverage: 65.3% (421/644) Total lines: 17686/30/2026 - 12:15:32 AM Line coverage: 81.3% (638/784) Branch coverage: 71.7% (515/718) Total lines: 17827/22/2026 - 12:16:22 AM Line coverage: 81.3% (636/782) Branch coverage: 71.8% (513/714) Total lines: 17847/26/2026 - 12:17:51 AM Line coverage: 81.4% (640/786) Branch coverage: 72% (517/718) Total lines: 1796

Coverage delta

Coverage delta 10 -10

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%11100%
get_SplitWhitelist()100%22100%
GetMediaInfo(...)78.57%868493.87%
NormalizeFormat(...)87.5%171687.5%
GetEstimatedAudioBitrate(...)91.3%9292100%
IsDtsLossless(...)100%22100%
FetchFromItunesInfo(...)75%141276.92%
ReadFromDictNode(...)85%212087.09%
ReadValueArray(...)83.33%141277.77%
ProcessPairs(...)64.28%441446.66%
GetNameValuePair(...)85.71%141490.9%
NormalizeSubtitleCodec(...)62.5%10866.66%
GetMediaAttachment(...)70%101093.33%
GetMediaStream(...)75%27516083.52%
NormalizeStreamTitle(...)75%44100%
GetDictionaryValue(...)100%22100%
ParseChannelLayout(...)100%22100%
GetAspectRatio(...)79.41%393483.87%
IsClose(...)100%11100%
IsNearSquarePixelSar(...)60%101088.88%
GetFrameRate(...)60%141066.66%
SetAudioRuntimeTicks(...)50%9877.77%
GetBPSFromTags(...)87.5%88100%
GetRuntimeSecondsFromTags(...)90%1010100%
GetNumberOfBytesFromTags(...)87.5%88100%
SetSize(...)75%44100%
SetAudioInfoFromTags(...)52.85%847085.93%
GetMultipleMusicBrainzId(...)100%22100%
Split(...)100%44100%
SplitDistinctArtists(...)83.33%6691.66%
FetchStudios(...)70%1010100%
FetchGenres(...)83.33%66100%
GetDictionaryTrackOrDiscNumber(...)50%2275%
GetChapterInfo(...)0%4260%
FetchWtvInfo(...)35.71%5654233.33%
ExtractTimestamp(...)80%121075%
GetMpegTimestamp(...)0%1211418.18%

File(s)

/srv/git/jellyfin/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs

#LineLine coverage
 1#nullable disable
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Globalization;
 6using System.IO;
 7using System.Linq;
 8using System.Text;
 9using System.Text.RegularExpressions;
 10using System.Xml;
 11using Jellyfin.Data.Enums;
 12using Jellyfin.Extensions;
 13using MediaBrowser.Controller.Extensions;
 14using MediaBrowser.Controller.Library;
 15using MediaBrowser.Model.Dto;
 16using MediaBrowser.Model.Entities;
 17using MediaBrowser.Model.Globalization;
 18using MediaBrowser.Model.MediaInfo;
 19using Microsoft.Extensions.Logging;
 20
 21namespace MediaBrowser.MediaEncoding.Probing
 22{
 23    /// <summary>
 24    /// Class responsible for normalizing FFprobe output.
 25    /// </summary>
 26    public partial class ProbeResultNormalizer
 27    {
 28        // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
 29        private const int MaxSubtitleDescriptionExtractionLength = 100;
 30
 31        private const string ArtistReplaceValue = " | ";
 32
 133        private static readonly char[] _basicDelimiters = ['/', ';'];
 134        private static readonly char[] _nameDelimiters = [.. _basicDelimiters, '|', '\\'];
 135        private static readonly char[] _genreDelimiters = [.. _basicDelimiters, ','];
 136        private static readonly string[] _webmVideoCodecs = ["av1", "vp8", "vp9"];
 137        private static readonly string[] _webmAudioCodecs = ["opus", "vorbis"];
 38
 39        private readonly ILogger _logger;
 40        private readonly ILocalizationManager _localization;
 41
 42        private string[] _splitWhiteList;
 43
 44        /// <summary>
 45        /// Initializes a new instance of the <see cref="ProbeResultNormalizer"/> class.
 46        /// </summary>
 47        /// <param name="logger">The <see cref="ILogger{ProbeResultNormalizer}"/> for use with the <see cref="ProbeResul
 48        /// <param name="localization">The <see cref="ILocalizationManager"/> for use with the <see cref="ProbeResultNor
 49        public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
 50        {
 6451            _logger = logger;
 6452            _localization = localization;
 6453        }
 54
 555        private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
 556        {
 557            "AC/DC",
 558            "A/T/O/S",
 559            "As/Hi Soundworks",
 560            "Au/Ra",
 561            "Bremer/McCoy",
 562            "b/bqスタヂオ",
 563            "DOV/S",
 564            "DJ'TEKINA//SOMETHING",
 565            "IX/ON",
 566            "J-CORE SLi//CER",
 567            "M(a/u)SH",
 568            "Kaoru/Brilliance",
 569            "signum/ii",
 570            "Richiter(LORB/DUGEM DI BARAT)",
 571            "이달의 소녀 1/3",
 572            "R!N / Gemie",
 573            "LOONA 1/3",
 574            "LOONA / yyxy",
 575            "LOONA / ODD EYE CIRCLE",
 576            "K/DA",
 577            "22/7",
 578            "諭吉佳作/men",
 579            "//dARTH nULL",
 580            "Phantom/Ghost",
 581            "She/Her/Hers",
 582            "5/8erl in Ehr'n",
 583            "Smith/Kotzen",
 584            "We;Na",
 585            "LSR/CITY",
 586            "Kairon; IRSE!",
 587        };
 88
 89        /// <summary>
 90        /// Transforms a FFprobe response into its <see cref="MediaInfo"/> equivalent.
 91        /// </summary>
 92        /// <param name="data">The <see cref="InternalMediaInfoResult"/>.</param>
 93        /// <param name="videoType">The <see cref="VideoType"/>.</param>
 94        /// <param name="isAudio">A boolean indicating whether the media is audio.</param>
 95        /// <param name="path">Path to media file.</param>
 96        /// <param name="protocol">Path media protocol.</param>
 97        /// <returns>The <see cref="MediaInfo"/>.</returns>
 98        public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, Med
 99        {
 15100            var info = new MediaInfo
 15101            {
 15102                Path = path,
 15103                Protocol = protocol,
 15104                VideoType = videoType
 15105            };
 106
 15107            FFProbeHelpers.NormalizeFFProbeResult(data);
 15108            SetSize(data, info);
 109
 15110            var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
 15111            var internalFrames = data.Frames ?? Array.Empty<MediaFrameInfo>();
 112
 15113            info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format, internalFrames))
 15114                .Where(i => i is not null)
 15115                // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know
 15116                .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
 15117                .ToList();
 118
 15119            info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
 15120                .Where(i => i is not null)
 15121                .ToList();
 122
 15123            if (data.Format is not null)
 124            {
 14125                info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
 126
 14127                if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
 128                {
 13129                    info.Bitrate = value;
 130                }
 131            }
 132
 15133            var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 15134            var tagStreamType = isAudio ? CodecType.Audio : CodecType.Video;
 135
 15136            var tagStream = data.Streams?.FirstOrDefault(i => i.CodecType == tagStreamType);
 137
 15138            if (tagStream?.Tags is not null)
 139            {
 98140                foreach (var (key, value) in tagStream.Tags)
 141                {
 37142                    tags[key] = value;
 143                }
 144            }
 145
 15146            if (data.Format?.Tags is not null)
 147            {
 298148                foreach (var (key, value) in data.Format.Tags)
 149                {
 138150                    tags[key] = value;
 151                }
 152            }
 153
 15154            FetchGenres(info, tags);
 155
 15156            info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
 15157            info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
 15158            info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc", "comment");
 159
 15160            info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
 15161            info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort") ??
 15162                               FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_id");
 15163            info.ShowName = tags.GetValueOrDefault("show_name", "show");
 15164            info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
 165
 166            // Several different forms of retail/premiere date
 15167            info.PremiereDate =
 15168                FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
 15169                FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
 15170                FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
 15171                FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
 15172                FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
 15173                FFProbeHelpers.GetDictionaryDateTime(tags, "date") ??
 15174                FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time");
 175
 176            // Set common metadata for music (audio) and music videos (video)
 15177            info.Album = tags.GetValueOrDefault("album");
 178
 15179            if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
 180            {
 2181                info.Artists = SplitDistinctArtists(artists, _basicDelimiters, false).ToArray();
 182            }
 183            else
 184            {
 13185                var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
 13186                info.Artists = artist is null
 13187                    ? Array.Empty<string>()
 13188                    : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
 189            }
 190
 191            // Guess ProductionYear from PremiereDate if missing
 15192            if (info.ProductionYear is null && info.PremiereDate is not null)
 193            {
 5194                info.ProductionYear = info.PremiereDate.Value.Year;
 195            }
 196
 15197            if (data.Chapters is not null)
 198            {
 3199                info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
 200            }
 201
 202            // Set mediaType-specific metadata
 15203            if (isAudio)
 204            {
 2205                SetAudioRuntimeTicks(data, info);
 206
 207                // tags are normally located under data.format, but we've seen some cases with ogg where they're part of
 208                // so let's create a combined list of both
 209
 2210                SetAudioInfoFromTags(info, tags);
 211            }
 212            else
 213            {
 13214                FetchStudios(info, tags, "copyright");
 215
 13216                var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
 13217                if (iTunExtc is not null)
 218                {
 0219                    var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
 220                    // Example
 221                    // mpaa|G|100|For crude humor
 0222                    if (parts.Length > 1)
 223                    {
 0224                        info.OfficialRating = parts[1];
 225
 0226                        if (parts.Length > 3)
 227                        {
 0228                            info.OfficialRatingDescription = parts[3];
 229                        }
 230                    }
 231                }
 232
 13233                var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
 13234                if (iTunXml is not null)
 235                {
 1236                    FetchFromItunesInfo(iTunXml, info);
 237                }
 238
 13239                if (data.Format is not null && !string.IsNullOrEmpty(data.Format.Duration))
 240                {
 12241                    info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCul
 242                }
 243
 13244                FetchWtvInfo(info, data);
 245
 13246                ExtractTimestamp(info);
 247
 13248                if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", Strin
 249                {
 0250                    info.Video3DFormat = Video3DFormat.FullSideBySide;
 251                }
 252
 86253                foreach (var mediaStream in info.MediaStreams)
 254                {
 30255                    if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
 256                    {
 4257                        mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Profile, mediaStre
 258                    }
 259                }
 260
 261                // ffprobe frequently omits the per-stream video bitrate (common in MP4/MKV containers).
 262                // Estimate the missing video bitrate as the container bitrate minus the combined stream bitrates.
 13263                var videoStreams = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).ToList();
 13264                if (info.Bitrate.HasValue
 13265                    && videoStreams.Count == 1
 13266                    && !videoStreams[0].BitRate.HasValue)
 267                {
 7268                    var otherStreams = info.MediaStreams
 7269                        .Where(i => i.Type != MediaStreamType.Video && !i.IsExternal)
 7270                        .ToList();
 271
 272                    // Only attribute the leftover bitrate to the video stream if every audio stream's bitrate is known.
 7273                    var audioBitratesKnown = otherStreams
 7274                        .Where(i => i.Type == MediaStreamType.Audio)
 7275                        .All(i => i.BitRate.HasValue);
 276
 7277                    if (audioBitratesKnown)
 278                    {
 6279                        var estimatedVideoBitrate = info.Bitrate.Value - otherStreams.Sum(i => i.BitRate ?? 0);
 6280                        if (estimatedVideoBitrate > 0)
 281                        {
 5282                            videoStreams[0].BitRate = estimatedVideoBitrate;
 283                        }
 284                    }
 285                }
 286
 287                // If the container bitrate is still unknown, infer it from the sum of the streams.
 13288                info.InferTotalBitrate();
 289            }
 290
 15291            return info;
 292        }
 293
 294        private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
 295        {
 14296            if (string.IsNullOrWhiteSpace(format))
 297            {
 0298                return null;
 299            }
 300
 301            // Input can be a list of multiple, comma-delimited formats - each of them needs to be checked
 14302            var splitFormat = format.Split(',');
 118303            for (var i = 0; i < splitFormat.Length; i++)
 304            {
 305                // Handle MPEG-1 container
 45306                if (string.Equals(splitFormat[i], "mpegvideo", StringComparison.OrdinalIgnoreCase))
 307                {
 0308                    splitFormat[i] = "mpeg";
 309                }
 310
 311                // Handle MPEG-TS container
 45312                else if (string.Equals(splitFormat[i], "mpegts", StringComparison.OrdinalIgnoreCase))
 313                {
 1314                    splitFormat[i] = "ts";
 315                }
 316
 317                // Handle matroska container
 44318                else if (string.Equals(splitFormat[i], "matroska", StringComparison.OrdinalIgnoreCase))
 319                {
 6320                    splitFormat[i] = "mkv";
 321                }
 322
 323                // Handle WebM
 38324                else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
 325                {
 326                    // Limit WebM to supported stream types and codecs.
 327                    // FFprobe can report "matroska,webm" for Matroska-like containers, so only keep "webm" if all strea
 328                    // Any stream that is not video nor audio is not supported in WebM and should disqualify the webm co
 6329                    if (mediaStreams.Any(stream => stream.Type is not MediaStreamType.Video and not MediaStreamType.Audi
 6330                        || mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contain
 6331                            || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringC
 332                    {
 5333                        splitFormat[i] = string.Empty;
 334                    }
 335                }
 336            }
 337
 14338            return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
 339        }
 340
 341        internal static int? GetEstimatedAudioBitrate(string codec, string profile, int? channels)
 342        {
 30343            if (!channels.HasValue || channels.Value < 1 || string.IsNullOrEmpty(codec))
 344            {
 2345                return null;
 346            }
 347
 348            // Rough typical bitrates used only as a fallback when ffprobe doesn't report a stream bitrate.
 28349            var channelCount = channels.Value;
 28350            var isMultichannel = channelCount > 2;
 351
 28352            return codec.ToLowerInvariant() switch
 28353            {
 7354                "aac" or "mp3" or "mp2" => isMultichannel ? 320000 : 192000,
 3355                "ac3" or "eac3" => isMultichannel ? 640000 : 192000,
 6356                "dts" or "dca" => IsDtsLossless(profile) ? channelCount * 700000 : (isMultichannel ? 1509000 : 768000),
 1357                "opus" => isMultichannel ? 256000 : 128000,
 2358                "vorbis" => isMultichannel ? 320000 : 160000,
 1359                "wmav1" or "wmav2" or "wmapro" => isMultichannel ? 384000 : 192000,
 4360                "flac" or "alac" => channelCount * 480000,
 3361                "truehd" or "mlp" => channelCount * 700000,
 1362                _ => null
 28363            };
 364        }
 365
 366        private static bool IsDtsLossless(string profile)
 6367            => profile is not null && profile.Contains("HD MA", StringComparison.OrdinalIgnoreCase);
 368
 369        private void FetchFromItunesInfo(string xml, MediaInfo info)
 370        {
 371            // Make things simpler and strip out the dtd
 1372            var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
 373
 1374            if (plistIndex != -1)
 375            {
 1376                xml = xml.Substring(plistIndex);
 377            }
 378
 1379            xml = "<?xml version=\"1.0\"?>" + xml;
 380
 381            // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http
 1382            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
 1383            using (var streamReader = new StreamReader(stream))
 384            {
 385                try
 386                {
 1387                    using (var reader = XmlReader.Create(streamReader))
 388                    {
 1389                        reader.MoveToContent();
 1390                        reader.Read();
 391
 392                        // Loop through each element
 4393                        while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 394                        {
 3395                            if (reader.NodeType == XmlNodeType.Element)
 396                            {
 1397                                switch (reader.Name)
 398                                {
 399                                    case "dict":
 1400                                        if (reader.IsEmptyElement)
 401                                        {
 0402                                            reader.Read();
 0403                                            continue;
 404                                        }
 405
 1406                                        using (var subtree = reader.ReadSubtree())
 407                                        {
 1408                                            ReadFromDictNode(subtree, info);
 1409                                        }
 410
 411                                        break;
 412                                    default:
 0413                                        reader.Skip();
 0414                                        break;
 415                                }
 416                            }
 417                            else
 418                            {
 2419                                reader.Read();
 420                            }
 421                        }
 1422                    }
 1423                }
 0424                catch (XmlException)
 425                {
 426                    // I've seen probe examples where the iTunMOVI value is just "<"
 427                    // So we should not allow this to fail the entire probing operation
 0428                }
 429            }
 1430        }
 431
 432        private void ReadFromDictNode(XmlReader reader, MediaInfo info)
 433        {
 1434            string currentKey = null;
 1435            var pairs = new List<NameValuePair>();
 436
 1437            reader.MoveToContent();
 1438            reader.Read();
 439
 440            // Loop through each element
 19441            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 442            {
 18443                if (reader.NodeType == XmlNodeType.Element)
 444                {
 12445                    switch (reader.Name)
 446                    {
 447                        case "key":
 6448                            if (!string.IsNullOrWhiteSpace(currentKey))
 449                            {
 5450                                ProcessPairs(currentKey, pairs, info);
 451                            }
 452
 6453                            currentKey = reader.ReadElementContentAsString();
 6454                            pairs = new List<NameValuePair>();
 6455                            break;
 456                        case "string":
 1457                            var value = reader.ReadElementContentAsString();
 1458                            if (!string.IsNullOrWhiteSpace(value))
 459                            {
 1460                                pairs.Add(new NameValuePair
 1461                                {
 1462                                    Name = value,
 1463                                    Value = value
 1464                                });
 465                            }
 466
 1467                            break;
 468                        case "array":
 5469                            if (reader.IsEmptyElement)
 470                            {
 0471                                reader.Read();
 0472                                continue;
 473                            }
 474
 5475                            using (var subtree = reader.ReadSubtree())
 476                            {
 5477                                if (!string.IsNullOrWhiteSpace(currentKey))
 478                                {
 5479                                    pairs.AddRange(ReadValueArray(subtree));
 480                                }
 5481                            }
 482
 483                            break;
 484                        default:
 0485                            reader.Skip();
 0486                            break;
 487                    }
 488                }
 489                else
 490                {
 6491                    reader.Read();
 492                }
 493            }
 1494        }
 495
 496        private List<NameValuePair> ReadValueArray(XmlReader reader)
 497        {
 5498            var pairs = new List<NameValuePair>();
 499
 5500            reader.MoveToContent();
 5501            reader.Read();
 502
 503            // Loop through each element
 20504            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 505            {
 15506                if (reader.NodeType == XmlNodeType.Element)
 507                {
 5508                    switch (reader.Name)
 509                    {
 510                        case "dict":
 511
 5512                            if (reader.IsEmptyElement)
 513                            {
 0514                                reader.Read();
 0515                                continue;
 516                            }
 517
 5518                            using (var subtree = reader.ReadSubtree())
 519                            {
 5520                                var dict = GetNameValuePair(subtree);
 5521                                if (dict is not null)
 522                                {
 1523                                    pairs.Add(dict);
 524                                }
 5525                            }
 526
 527                            break;
 528                        default:
 0529                            reader.Skip();
 0530                            break;
 531                    }
 532                }
 533                else
 534                {
 10535                    reader.Read();
 536                }
 537            }
 538
 5539            return pairs;
 540        }
 541
 542        private static void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
 543        {
 5544            List<BaseItemPerson> peoples = new List<BaseItemPerson>();
 5545            var distinctPairs = pairs.Select(p => p.Value)
 5546                    .Where(i => !string.IsNullOrWhiteSpace(i))
 5547                    .Trimmed()
 5548                    .Distinct(StringComparer.OrdinalIgnoreCase);
 549
 5550            if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
 551            {
 1552                info.Studios = distinctPairs.ToArray();
 553            }
 4554            else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
 555            {
 0556                foreach (var pair in distinctPairs)
 557                {
 0558                    peoples.Add(new BaseItemPerson
 0559                    {
 0560                        Name = pair,
 0561                        Type = PersonKind.Writer
 0562                    });
 563                }
 564            }
 4565            else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
 566            {
 2567                foreach (var pair in distinctPairs)
 568                {
 0569                    peoples.Add(new BaseItemPerson
 0570                    {
 0571                        Name = pair,
 0572                        Type = PersonKind.Producer
 0573                    });
 574                }
 575            }
 3576            else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
 577            {
 2578                foreach (var pair in distinctPairs)
 579                {
 0580                    peoples.Add(new BaseItemPerson
 0581                    {
 0582                        Name = pair,
 0583                        Type = PersonKind.Director
 0584                    });
 585                }
 586            }
 587
 5588            info.People = peoples.ToArray();
 5589        }
 590
 591        private static NameValuePair GetNameValuePair(XmlReader reader)
 592        {
 5593            string name = null;
 5594            string value = null;
 595
 5596            reader.MoveToContent();
 5597            reader.Read();
 598
 599            // Loop through each element
 20600            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 601            {
 15602                if (reader.NodeType == XmlNodeType.Element)
 603                {
 10604                    switch (reader.Name)
 605                    {
 606                        case "key":
 5607                            name = reader.ReadNormalizedString();
 5608                            break;
 609                        case "string":
 5610                            value = reader.ReadNormalizedString();
 5611                            break;
 612                        default:
 0613                            reader.Skip();
 0614                            break;
 615                    }
 616                }
 617                else
 618                {
 5619                    reader.Read();
 620                }
 621            }
 622
 5623            if (string.IsNullOrEmpty(name)
 5624                || string.IsNullOrEmpty(value))
 625            {
 4626                return null;
 627            }
 628
 1629            return new NameValuePair
 1630            {
 1631                Name = name,
 1632                Value = value
 1633            };
 634        }
 635
 636        private static string NormalizeSubtitleCodec(string codec)
 637        {
 4638            if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
 639            {
 0640                codec = "DVBSUB";
 641            }
 4642            else if (string.Equals(codec, "dvb_teletext", StringComparison.OrdinalIgnoreCase))
 643            {
 0644                codec = "DVBTXT";
 645            }
 4646            else if (string.Equals(codec, "dvd_subtitle", StringComparison.OrdinalIgnoreCase))
 647            {
 1648                codec = "DVDSUB"; // .sub+.idx
 649            }
 3650            else if (string.Equals(codec, "hdmv_pgs_subtitle", StringComparison.OrdinalIgnoreCase))
 651            {
 0652                codec = "PGSSUB"; // .sup
 653            }
 654
 4655            return codec;
 656        }
 657
 658        /// <summary>
 659        /// Converts ffprobe stream info to our MediaAttachment class.
 660        /// </summary>
 661        /// <param name="streamInfo">The stream info.</param>
 662        /// <returns>MediaAttachments.</returns>
 663        private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
 664        {
 34665            if (streamInfo.CodecType != CodecType.Attachment
 34666                && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
 667            {
 32668                return null;
 669            }
 670
 2671            var attachment = new MediaAttachment
 2672            {
 2673                Codec = streamInfo.CodecName,
 2674                Index = streamInfo.Index
 2675            };
 676
 2677            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
 678            {
 0679                attachment.CodecTag = streamInfo.CodecTagString;
 680            }
 681
 2682            if (streamInfo.Tags is not null)
 683            {
 2684                attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
 2685                attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
 2686                attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 687            }
 688
 2689            return attachment;
 690        }
 691
 692        /// <summary>
 693        /// Converts ffprobe stream info to our MediaStream class.
 694        /// </summary>
 695        /// <param name="isAudio">if set to <c>true</c> [is info].</param>
 696        /// <param name="streamInfo">The stream info.</param>
 697        /// <param name="formatInfo">The format info.</param>
 698        /// <param name="frameInfoList">The frame info.</param>
 699        /// <returns>MediaStream.</returns>
 700        private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo, IReadOn
 701        {
 34702            var stream = new MediaStream
 34703            {
 34704                Codec = streamInfo.CodecName,
 34705                Profile = streamInfo.Profile,
 34706                Width = streamInfo.Width,
 34707                Height = streamInfo.Height,
 34708                Level = streamInfo.Level,
 34709                Index = streamInfo.Index,
 34710                PixelFormat = streamInfo.PixelFormat,
 34711                NalLengthSize = streamInfo.NalLengthSize,
 34712                TimeBase = streamInfo.TimeBase,
 34713                CodecTimeBase = streamInfo.CodecTimeBase
 34714            };
 715
 716            // Filter out junk
 34717            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", Stri
 718            {
 0719                stream.CodecTag = streamInfo.CodecTagString;
 720            }
 721
 34722            if (streamInfo.Tags is not null)
 723            {
 30724                stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
 30725                stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 30726                stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
 727            }
 728
 34729            if (streamInfo.CodecType == CodecType.Audio)
 730            {
 14731                stream.Type = MediaStreamType.Audio;
 14732                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 14733                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 14734                stream.LocalizedOriginal = _localization.GetLocalizedString("Original");
 14735                if (!string.IsNullOrEmpty(stream.Language))
 736                {
 11737                    stream.LocalizedLanguage = _localization.GetLanguageDisplayName(stream.Language);
 738                }
 739
 14740                stream.Channels = streamInfo.Channels;
 741
 14742                if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
 743                {
 14744                    stream.SampleRate = sampleRate;
 745                }
 746
 14747                stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
 748
 14749                if (streamInfo.BitsPerSample > 0)
 750                {
 0751                    stream.BitDepth = streamInfo.BitsPerSample;
 752                }
 14753                else if (streamInfo.BitsPerRawSample > 0)
 754                {
 3755                    stream.BitDepth = streamInfo.BitsPerRawSample;
 756                }
 757
 14758                if (string.IsNullOrEmpty(stream.Title))
 759                {
 760                    // FFprobe exposes MP4 track names via the name tag rather than title
 14761                    stream.Title = GetDictionaryValue(streamInfo.Tags, "name");
 762
 14763                    if (string.IsNullOrEmpty(stream.Title))
 764                    {
 765                        // fall back to handler_name if populated and not the default "SoundHandler"
 13766                        string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 13767                        if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComp
 768                        {
 2769                            stream.Title = handlerName;
 770                        }
 771                    }
 772                }
 773            }
 20774            else if (streamInfo.CodecType == CodecType.Subtitle)
 775            {
 4776                stream.Type = MediaStreamType.Subtitle;
 4777                stream.Codec = NormalizeSubtitleCodec(stream.Codec);
 4778                stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
 4779                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 4780                stream.LocalizedForced = _localization.GetLocalizedString("Forced");
 4781                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 4782                stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
 4783                if (!string.IsNullOrEmpty(stream.Language))
 784                {
 4785                    stream.LocalizedLanguage = _localization.GetLanguageDisplayName(stream.Language);
 786                }
 787
 4788                if (string.IsNullOrEmpty(stream.Title))
 789                {
 790                    // FFprobe exposes MP4 track names via the name tag rather than title
 4791                    stream.Title = GetDictionaryValue(streamInfo.Tags, "name");
 792
 4793                    if (string.IsNullOrEmpty(stream.Title))
 794                    {
 795                        // fall back to handler_name if populated and not the default "SubtitleHandler"
 3796                        string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 3797                        if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringC
 798                        {
 1799                            stream.Title = handlerName;
 800                        }
 801                    }
 802                }
 803            }
 16804            else if (streamInfo.CodecType == CodecType.Video)
 805            {
 16806                stream.IsAVC = streamInfo.IsAvc;
 16807                stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
 16808                stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
 809
 16810                stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
 16811                    && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
 812
 16813                if (isAudio
 16814                    || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
 16815                    || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
 16816                    || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
 16817                    || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
 818                {
 2819                    stream.Type = MediaStreamType.EmbeddedImage;
 820                }
 14821                else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 822                {
 823                    // How to differentiate between video and embedded image?
 824                    // The only difference I've seen thus far is presence of codec tag, also embedded images have high (
 1825                    if (!string.IsNullOrWhiteSpace(stream.CodecTag))
 826                    {
 0827                        stream.Type = MediaStreamType.Video;
 828                    }
 829                    else
 830                    {
 1831                        stream.Type = MediaStreamType.EmbeddedImage;
 832                    }
 833                }
 834                else
 835                {
 13836                    stream.Type = MediaStreamType.Video;
 837                }
 838
 16839                stream.AspectRatio = GetAspectRatio(streamInfo);
 840
 16841                if (streamInfo.BitsPerSample > 0)
 842                {
 0843                    stream.BitDepth = streamInfo.BitsPerSample;
 844                }
 16845                else if (streamInfo.BitsPerRawSample > 0)
 846                {
 13847                    stream.BitDepth = streamInfo.BitsPerRawSample;
 848                }
 849
 16850                if (!stream.BitDepth.HasValue)
 851                {
 3852                    if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
 853                    {
 3854                        if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
 3855                            || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
 856                        {
 3857                            stream.BitDepth = 8;
 858                        }
 0859                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase
 0860                                 || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreC
 861                        {
 0862                            stream.BitDepth = 10;
 863                        }
 0864                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase
 0865                                 || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreC
 866                        {
 0867                            stream.BitDepth = 12;
 868                        }
 869                    }
 870                }
 871
 872                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 16873                if (string.IsNullOrEmpty(streamInfo.SampleAspectRatio)
 16874                    && string.IsNullOrEmpty(streamInfo.DisplayAspectRatio))
 875                {
 5876                    stream.IsAnamorphic = false;
 877                }
 11878                else if (IsNearSquarePixelSar(streamInfo.SampleAspectRatio))
 879                {
 9880                    stream.IsAnamorphic = false;
 881                }
 2882                else if (!string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.Ordinal))
 883                {
 1884                    stream.IsAnamorphic = true;
 885                }
 1886                else if (string.Equals(streamInfo.DisplayAspectRatio, "0:1", StringComparison.Ordinal))
 887                {
 1888                    stream.IsAnamorphic = false;
 889                }
 0890                else if (!string.Equals(
 0891                             streamInfo.DisplayAspectRatio,
 0892                             // Force GetAspectRatio() to derive ratio from Width/Height directly by using null DAR
 0893                             GetAspectRatio(new MediaStreamInfo
 0894                             {
 0895                                 Width = streamInfo.Width,
 0896                                 Height = streamInfo.Height,
 0897                                 DisplayAspectRatio = null
 0898                             }),
 0899                             StringComparison.Ordinal))
 900                {
 0901                    stream.IsAnamorphic = true;
 902                }
 903                else
 904                {
 0905                    stream.IsAnamorphic = false;
 906                }
 907
 16908                if (streamInfo.Refs > 0)
 909                {
 15910                    stream.RefFrames = streamInfo.Refs;
 911                }
 912
 16913                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 914                {
 5915                    stream.ColorRange = streamInfo.ColorRange;
 916                }
 917
 16918                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 919                {
 5920                    stream.ColorSpace = streamInfo.ColorSpace;
 921                }
 922
 16923                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 924                {
 2925                    stream.ColorTransfer = streamInfo.ColorTransfer;
 926                }
 927
 16928                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 929                {
 2930                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 931                }
 932
 16933                if (streamInfo.SideDataList is not null)
 934                {
 6935                    foreach (var data in streamInfo.SideDataList)
 936                    {
 937                        // Parse Dolby Vision metadata from side_data
 2938                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 939                        {
 1940                            stream.DvVersionMajor = data.DvVersionMajor;
 1941                            stream.DvVersionMinor = data.DvVersionMinor;
 1942                            stream.DvProfile = data.DvProfile;
 1943                            stream.DvLevel = data.DvLevel;
 1944                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1945                            stream.ElPresentFlag = data.ElPresentFlag;
 1946                            stream.BlPresentFlag = data.BlPresentFlag;
 1947                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 948                        }
 949
 950                        // Parse video rotation metadata from side_data
 1951                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 952                        {
 1953                            stream.Rotation = data.Rotation;
 954                        }
 955
 956                        // Parse video frame cropping metadata from side_data
 957                        // TODO: save them and make HW filters to apply them in HWA pipelines
 0958                        else if (string.Equals(data.SideDataType, "Frame Cropping", StringComparison.OrdinalIgnoreCase))
 959                        {
 960                            // Streams containing artificially added frame cropping
 961                            // metadata should not be marked as anamorphic.
 0962                            stream.IsAnamorphic = false;
 963                        }
 964                    }
 965                }
 966
 16967                var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
 16968                if (frameInfo?.SideDataList is not null
 16969                    && frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE20
 970                {
 0971                    stream.Hdr10PlusPresentFlag = true;
 972                }
 973            }
 0974            else if (streamInfo.CodecType == CodecType.Data)
 975            {
 0976                stream.Type = MediaStreamType.Data;
 977            }
 978            else
 979            {
 0980                return null;
 981            }
 982
 983            // Get stream bitrate
 34984            var bitrate = 0;
 985
 34986            if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
 987            {
 14988                bitrate = value;
 989            }
 990
 991            // The bitrate info of FLAC audio is included in formatInfo.
 992            // Don't do this for video streams: formatInfo.BitRate is the overall container
 993            // bitrate (video + audio + subtitles + overhead), not the video bitrate.
 34994            if (bitrate == 0
 34995                && formatInfo is not null
 34996                && isAudio && stream.Type == MediaStreamType.Audio)
 997            {
 998                // If the stream info doesn't have a bitrate get the value from the media format info
 2999                if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
 1000                {
 21001                    bitrate = value;
 1002                }
 1003            }
 1004
 341005            if (bitrate > 0)
 1006            {
 161007                stream.BitRate = bitrate;
 1008            }
 1009
 1010            // Extract bitrate info from tag "BPS" if possible.
 341011            if (!stream.BitRate.HasValue
 341012                && (streamInfo.CodecType == CodecType.Audio
 341013                    || streamInfo.CodecType == CodecType.Video))
 1014            {
 171015                var bps = GetBPSFromTags(streamInfo);
 171016                if (bps > 0)
 1017                {
 21018                    stream.BitRate = bps;
 1019                }
 1020                else
 1021                {
 1022                    // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
 151023                    var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
 151024                    var bytes = GetNumberOfBytesFromTags(streamInfo);
 151025                    if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
 1026                    {
 11027                        bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
 11028                        if (bps > 0)
 1029                        {
 11030                            stream.BitRate = bps;
 1031                        }
 1032                    }
 1033                }
 1034            }
 1035
 341036            var disposition = streamInfo.Disposition;
 341037            if (disposition is not null)
 1038            {
 341039                if (disposition.GetValueOrDefault("default") == 1)
 1040                {
 221041                    stream.IsDefault = true;
 1042                }
 1043
 341044                if (disposition.GetValueOrDefault("forced") == 1)
 1045                {
 01046                    stream.IsForced = true;
 1047                }
 1048
 341049                if (disposition.GetValueOrDefault("hearing_impaired") == 1)
 1050                {
 11051                    stream.IsHearingImpaired = true;
 1052                }
 1053
 341054                if (disposition.GetValueOrDefault("original") == 1)
 1055                {
 11056                    stream.IsOriginal = true;
 1057                }
 1058            }
 1059
 341060            NormalizeStreamTitle(stream);
 1061
 341062            return stream;
 1063        }
 1064
 1065        private static void NormalizeStreamTitle(MediaStream stream)
 1066        {
 341067            if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
 341068                || stream.Type == MediaStreamType.EmbeddedImage)
 1069            {
 31070                stream.Title = null;
 1071            }
 341072        }
 1073
 1074        /// <summary>
 1075        /// Gets a string from an FFProbeResult tags dictionary.
 1076        /// </summary>
 1077        /// <param name="tags">The tags.</param>
 1078        /// <param name="key">The key.</param>
 1079        /// <returns>System.String.</returns>
 1080        private static string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
 1081        {
 2151082            if (tags is null)
 1083            {
 61084                return null;
 1085            }
 1086
 2091087            tags.TryGetValue(key, out var val);
 1088
 2091089            return val;
 1090        }
 1091
 1092        private static string ParseChannelLayout(string input)
 1093        {
 141094            if (string.IsNullOrEmpty(input))
 1095            {
 21096                return null;
 1097            }
 1098
 121099            return input.AsSpan().LeftPart('(').ToString();
 1100        }
 1101
 1102        private static string GetAspectRatio(MediaStreamInfo info)
 1103        {
 161104            var original = info.DisplayAspectRatio;
 1105
 161106            var parts = (original ?? string.Empty).Split(':');
 161107            if (!(parts.Length == 2
 161108                    && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
 161109                    && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
 161110                    && width > 0
 161111                    && height > 0))
 1112            {
 61113                width = info.Width.Value;
 61114                height = info.Height.Value;
 1115            }
 1116
 161117            if (width > 0 && height > 0)
 1118            {
 161119                double ratio = width;
 161120                ratio /= height;
 1121
 161122                if (IsClose(ratio, 1.777777778, .03))
 1123                {
 101124                    return "16:9";
 1125                }
 1126
 61127                if (IsClose(ratio, 1.3333333333, .05))
 1128                {
 11129                    return "4:3";
 1130                }
 1131
 51132                if (IsClose(ratio, 1.41))
 1133                {
 01134                    return "1.41:1";
 1135                }
 1136
 51137                if (IsClose(ratio, 1.5))
 1138                {
 21139                    return "1.5:1";
 1140                }
 1141
 31142                if (IsClose(ratio, 1.6))
 1143                {
 01144                    return "1.6:1";
 1145                }
 1146
 31147                if (IsClose(ratio, 1.66666666667))
 1148                {
 01149                    return "5:3";
 1150                }
 1151
 31152                if (IsClose(ratio, 1.85, .02))
 1153                {
 01154                    return "1.85:1";
 1155                }
 1156
 31157                if (IsClose(ratio, 2.35, .025))
 1158                {
 01159                    return "2.35:1";
 1160                }
 1161
 31162                if (IsClose(ratio, 2.4, .025))
 1163                {
 11164                    return "2.40:1";
 1165                }
 1166            }
 1167
 21168            return original;
 1169        }
 1170
 1171        private static bool IsClose(double d1, double d2, double variance = .005)
 1172        {
 691173            return Math.Abs(d1 - d2) <= variance;
 1174        }
 1175
 1176        /// <summary>
 1177        /// Determines whether a sample aspect ratio represents square (or near-square) pixels.
 1178        /// Some encoders produce SARs like 3201:3200 for content that is effectively 1:1,
 1179        /// which would be falsely classified as anamorphic by an exact string comparison.
 1180        /// A 1% tolerance safely covers encoder rounding artifacts while preserving detection
 1181        /// of genuine anamorphic content (closest standard is PAL 4:3 at 16:15 = 6.67% off).
 1182        /// </summary>
 1183        /// <param name="sar">The sample aspect ratio string in "N:D" format.</param>
 1184        /// <returns><c>true</c> if the SAR is within 1% of 1:1; otherwise <c>false</c>.</returns>
 1185        internal static bool IsNearSquarePixelSar(string sar)
 1186        {
 241187            if (string.IsNullOrEmpty(sar))
 1188            {
 21189                return false;
 1190            }
 1191
 221192            var parts = sar.Split(':');
 221193            if (parts.Length == 2
 221194                && double.TryParse(parts[0], CultureInfo.InvariantCulture, out var num)
 221195                && double.TryParse(parts[1], CultureInfo.InvariantCulture, out var den)
 221196                && den > 0)
 1197            {
 221198                return IsClose(num / den, 1.0, 0.01);
 1199            }
 1200
 01201            return string.Equals(sar, "1:1", StringComparison.Ordinal);
 1202        }
 1203
 1204        /// <summary>
 1205        /// Gets a frame rate from a string value in ffprobe output
 1206        /// This could be a number or in the format of 2997/125.
 1207        /// </summary>
 1208        /// <param name="value">The value.</param>
 1209        /// <returns>System.Nullable{System.Single}.</returns>
 1210        internal static float? GetFrameRate(ReadOnlySpan<char> value)
 1211        {
 411212            if (value.IsEmpty)
 1213            {
 01214                return null;
 1215            }
 1216
 411217            int index = value.IndexOf('/');
 411218            if (index == -1)
 1219            {
 01220                return null;
 1221            }
 1222
 411223            if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
 411224                || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var div
 1225            {
 01226                return null;
 1227            }
 1228
 411229            return divisor == 0f ? null : dividend / divisor;
 1230        }
 1231
 1232        private static void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
 1233        {
 1234            // Get the first info stream
 21235            var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
 21236            if (stream is null)
 1237            {
 01238                return;
 1239            }
 1240
 1241            // Get duration from stream properties
 21242            var duration = stream.Duration;
 1243
 1244            // If it's not there go into format properties
 21245            if (string.IsNullOrEmpty(duration))
 1246            {
 01247                duration = result.Format.Duration;
 1248            }
 1249
 1250            // If we got something, parse it
 21251            if (!string.IsNullOrEmpty(duration))
 1252            {
 21253                data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
 1254            }
 21255        }
 1256
 1257        private static int? GetBPSFromTags(MediaStreamInfo streamInfo)
 1258        {
 171259            if (streamInfo?.Tags is null)
 1260            {
 11261                return null;
 1262            }
 1263
 161264            var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
 161265            if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
 1266            {
 31267                return parsedBps;
 1268            }
 1269
 131270            return null;
 1271        }
 1272
 1273        private static double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
 1274        {
 151275            if (streamInfo?.Tags is null)
 1276            {
 11277                return null;
 1278            }
 1279
 141280            var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "D
 141281            if (!string.IsNullOrEmpty(duration))
 1282            {
 1283                // Matroska DURATION tags use nanosecond precision (e.g. "00:00:05.023000000"), but
 1284                // TimeSpan only supports up to 7 fractional digits (ticks). Trim the surplus digits so
 1285                // these durations parse instead of being silently dropped.
 31286                duration = DurationOverPrecisionRegex().Replace(duration, "$1");
 31287                if (TimeSpan.TryParse(duration, CultureInfo.InvariantCulture, out var parsedDuration))
 1288                {
 31289                    return parsedDuration.TotalSeconds;
 1290                }
 1291            }
 1292
 111293            return null;
 1294        }
 1295
 1296        private static long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
 1297        {
 151298            if (streamInfo?.Tags is null)
 1299            {
 11300                return null;
 1301            }
 1302
 141303            var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
 141304                                ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
 141305            if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
 1306            {
 21307                return parsedBytes;
 1308            }
 1309
 121310            return null;
 1311        }
 1312
 1313        private static void SetSize(InternalMediaInfoResult data, MediaInfo info)
 1314        {
 151315            if (data.Format is null)
 1316            {
 11317                return;
 1318            }
 1319
 141320            info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.Invaria
 141321        }
 1322
 1323        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
 1324        {
 21325            var people = new List<BaseItemPerson>();
 21326            if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
 1327            {
 121328                foreach (var person in Split(composer, false))
 1329                {
 41330                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
 1331                }
 1332            }
 1333
 21334            if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
 1335            {
 01336                foreach (var person in Split(conductor, false))
 1337                {
 01338                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
 1339                }
 1340            }
 1341
 21342            if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
 1343            {
 81344                foreach (var person in Split(lyricist, false))
 1345                {
 21346                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
 1347                }
 1348            }
 1349
 21350            if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
 1351            {
 501352                foreach (var person in Split(performer, false))
 1353                {
 231354                    Match match = PerformerRegex().Match(person);
 1355
 1356                    // If the performer doesn't have any instrument/role associated, it won't match. In that case, chanc
 231357                    if (match.Success)
 1358                    {
 221359                        people.Add(new BaseItemPerson
 221360                        {
 221361                            Name = match.Groups["name"].Value,
 221362                            Type = PersonKind.Actor,
 221363                            Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
 221364                        });
 1365                    }
 1366                }
 1367            }
 1368
 1369            // In cases where there isn't sufficient information as to which role a writer performed on a recording, tag
 21370            if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
 1371            {
 01372                foreach (var person in Split(writer, false))
 1373                {
 01374                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
 1375                }
 1376            }
 1377
 21378            if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
 1379            {
 121380                foreach (var person in Split(arranger, false))
 1381                {
 41382                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
 1383                }
 1384            }
 1385
 21386            if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
 1387            {
 01388                foreach (var person in Split(engineer, false))
 1389                {
 01390                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
 1391                }
 1392            }
 1393
 21394            if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
 1395            {
 81396                foreach (var person in Split(mixer, false))
 1397                {
 21398                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
 1399                }
 1400            }
 1401
 21402            if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
 1403            {
 01404                foreach (var person in Split(remixer, false))
 1405                {
 01406                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
 1407                }
 1408            }
 1409
 21410            audio.People = people.ToArray();
 1411
 1412            // Set album artist
 21413            var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
 21414            audio.AlbumArtists = albumArtist is not null
 21415                ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
 21416                : Array.Empty<string>();
 1417
 1418            // Set album artist to artist if empty
 21419            if (audio.AlbumArtists.Length == 0)
 1420            {
 01421                audio.AlbumArtists = audio.Artists;
 1422            }
 1423
 1424            // Track number
 21425            audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
 1426
 1427            // Disc number
 21428            audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
 1429
 1430            // There's several values in tags may or may not be present
 21431            FetchStudios(audio, tags, "organization");
 21432            FetchStudios(audio, tags, "ensemble");
 21433            FetchStudios(audio, tags, "publisher");
 21434            FetchStudios(audio, tags, "label");
 1435
 1436            // These support multiple values, but for now we only store the first.
 21437            var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
 21438                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
 21439            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
 1440
 21441            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
 21442                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
 21443            audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
 1444
 21445            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
 21446                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
 21447            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
 1448
 21449            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
 21450                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
 21451            audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
 1452
 21453            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
 21454                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
 21455            audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
 21456        }
 1457
 1458        private static string GetMultipleMusicBrainzId(string value)
 1459        {
 201460            if (string.IsNullOrWhiteSpace(value))
 1461            {
 101462                return null;
 1463            }
 1464
 101465            return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
 101466                .FirstOrDefault();
 1467        }
 1468
 1469        /// <summary>
 1470        /// Splits the specified val.
 1471        /// </summary>
 1472        /// <param name="val">The val.</param>
 1473        /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
 1474        /// <returns>System.String[][].</returns>
 1475        private string[] Split(string val, bool allowCommaDelimiter)
 1476        {
 1477            // Only use the comma as a delimiter if there are no slashes or pipes.
 1478            // We want to be careful not to split names that have commas in them
 141479            return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
 141480                val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
 141481                val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1482        }
 1483
 1484        private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
 1485        {
 51486            if (splitFeaturing)
 1487            {
 31488                val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
 31489                    .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
 1490            }
 1491
 51492            var artistsFound = new List<string>();
 1493
 3101494            foreach (var whitelistArtist in SplitWhitelist)
 1495            {
 1501496                var originalVal = val;
 1501497                val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
 1498
 1501499                if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
 1500                {
 01501                    artistsFound.Add(whitelistArtist);
 1502                }
 1503            }
 1504
 51505            var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1506
 51507            artistsFound.AddRange(artists);
 51508            return artistsFound.DistinctNames();
 1509        }
 1510
 1511        /// <summary>
 1512        /// Gets the studios from the tags collection.
 1513        /// </summary>
 1514        /// <param name="info">The info.</param>
 1515        /// <param name="tags">The tags.</param>
 1516        /// <param name="tagName">Name of the tag.</param>
 1517        private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
 1518        {
 211519            var val = tags.GetValueOrDefault(tagName);
 1520
 211521            if (string.IsNullOrEmpty(val))
 1522            {
 191523                return;
 1524            }
 1525
 21526            var studios = Split(val, true);
 21527            var studioList = new List<string>();
 1528
 81529            foreach (var studio in studios)
 1530            {
 21531                if (string.IsNullOrWhiteSpace(studio))
 1532                {
 1533                    continue;
 1534                }
 1535
 1536                // Don't add artist/album artist name to studios, even if it's listed there
 21537                if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
 21538                    || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
 1539                {
 1540                    continue;
 1541                }
 1542
 21543                studioList.Add(studio);
 1544            }
 1545
 21546            info.Studios = studioList
 21547                .Distinct(StringComparer.OrdinalIgnoreCase)
 21548                .ToArray();
 21549        }
 1550
 1551        /// <summary>
 1552        /// Gets the genres from the tags collection.
 1553        /// </summary>
 1554        /// <param name="info">The information.</param>
 1555        /// <param name="tags">The tags.</param>
 1556        private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
 1557        {
 151558            var genreVal = tags.GetValueOrDefault("genre");
 151559            if (string.IsNullOrEmpty(genreVal))
 1560            {
 131561                return;
 1562            }
 1563
 21564            var genres = new List<string>(info.Genres);
 201565            foreach (var genre in Split(genreVal, true))
 1566            {
 81567                if (string.IsNullOrEmpty(genre))
 1568                {
 1569                    continue;
 1570                }
 1571
 81572                genres.Add(genre);
 1573            }
 1574
 21575            info.Genres = genres
 21576                .Distinct(StringComparer.OrdinalIgnoreCase)
 21577                .ToArray();
 21578        }
 1579
 1580        /// <summary>
 1581        /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
 1582        /// </summary>
 1583        /// <param name="tags">The tags.</param>
 1584        /// <param name="tagName">Name of the tag.</param>
 1585        /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
 1586        private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
 1587        {
 41588            var disc = tags.GetValueOrDefault(tagName);
 1589
 41590            if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
 1591            {
 41592                return discNum;
 1593            }
 1594
 01595            return null;
 1596        }
 1597
 1598        private static ChapterInfo GetChapterInfo(MediaChapter chapter)
 1599        {
 01600            var info = new ChapterInfo();
 1601
 01602            if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
 1603            {
 01604                info.Name = name;
 1605            }
 1606
 1607            // Limit accuracy to milliseconds to match xml saving
 01608            var secondsString = chapter.StartTime;
 1609
 01610            if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
 1611            {
 01612                var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
 01613                info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
 1614            }
 1615
 01616            return info;
 1617        }
 1618
 1619        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
 1620        {
 131621            var tags = data.Format?.Tags;
 1622
 131623            if (tags is null)
 1624            {
 41625                return;
 1626            }
 1627
 91628            if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
 1629            {
 01630                var genreList = genres.Split(_genreDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOption
 1631
 1632                // If this is empty then don't overwrite genres that might have been fetched earlier
 01633                if (genreList.Length > 0)
 1634                {
 01635                    video.Genres = genreList;
 1636                }
 1637            }
 1638
 91639            if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRati
 1640            {
 01641                video.OfficialRating = officialRating;
 1642            }
 1643
 91644            if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
 1645            {
 01646                video.People = Array.ConvertAll(
 01647                    people.Split(_basicDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntrie
 01648                    i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
 1649            }
 1650
 91651            if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, Cul
 1652            {
 01653                video.ProductionYear = parsedYear;
 1654            }
 1655
 1656            // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1657            // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
 91658            if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(y
 1659            {
 01660                video.PremiereDate = parsedDate;
 1661            }
 1662
 91663            var description = tags.GetValueOrDefault("WM/SubTitleDescription");
 1664
 91665            var subTitle = tags.GetValueOrDefault("WM/SubTitle");
 1666
 1667            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1668
 1669            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, ex
 1670            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
 1671            // OR -> COMMENT. SUBTITLE: DESCRIPTION
 1672            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the 
 1673            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in t
 91674            if (string.IsNullOrWhiteSpace(subTitle)
 91675                && !string.IsNullOrWhiteSpace(description)
 91676                && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains
 1677            {
 01678                string[] descriptionParts = description.Split(':');
 01679                if (descriptionParts.Length > 0)
 1680                {
 01681                    string subtitle = descriptionParts[0];
 1682                    try
 1683                    {
 1684                        // Check if it contains a episode number and season number
 01685                        if (subtitle.Contains('/', StringComparison.Ordinal))
 1686                        {
 01687                            string[] subtitleParts = subtitle.Split(' ');
 01688                            string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Spl
 01689                            video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
 1690                            // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
 1691
 1692                            // Skip the numbers, concatenate the rest, trim and set as new description
 01693                            description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1694                        }
 01695                        else if (subtitle.Contains('.', StringComparison.Ordinal))
 1696                        {
 01697                            var subtitleParts = subtitle.Split('.');
 01698                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1699                        }
 1700                        else
 1701                        {
 01702                            description = subtitle.Trim();
 1703                        }
 01704                    }
 01705                    catch (Exception ex)
 1706                    {
 01707                        _logger.LogError(ex, "Error while parsing subtitle field");
 1708
 1709                        // Fallback to default parsing
 01710                        if (subtitle.Contains('.', StringComparison.Ordinal))
 1711                        {
 01712                            var subtitleParts = subtitle.Split('.');
 01713                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1714                        }
 1715                        else
 1716                        {
 01717                            description = subtitle.Trim();
 1718                        }
 01719                    }
 1720                }
 1721            }
 1722
 91723            if (!string.IsNullOrWhiteSpace(description))
 1724            {
 01725                video.Overview = description;
 1726            }
 91727        }
 1728
 1729        private void ExtractTimestamp(MediaInfo video)
 1730        {
 131731            if (video.VideoType != VideoType.VideoFile)
 1732            {
 01733                return;
 1734            }
 1735
 1736            // Skip timestamp extration for remote resource (http, rtsp, etc.)
 1737            // as they cannot be opened with FileStream
 131738            if (video.Protocol != MediaProtocol.File)
 1739            {
 01740                return;
 1741            }
 1742
 131743            if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
 131744                && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
 131745                && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
 1746            {
 121747                return;
 1748            }
 1749
 1750            try
 1751            {
 11752                video.Timestamp = GetMpegTimestamp(video.Path);
 01753                _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
 01754            }
 11755            catch (Exception ex)
 1756            {
 11757                video.Timestamp = null;
 11758                _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
 11759            }
 11760        }
 1761
 1762        // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
 1763        private static TransportStreamTimestamp GetMpegTimestamp(string path)
 1764        {
 11765            var packetBuffer = new byte[197];
 1766
 11767            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
 1768            {
 01769                fs.ReadExactly(packetBuffer);
 01770            }
 1771
 01772            if (packetBuffer[0] == 71)
 1773            {
 01774                return TransportStreamTimestamp.None;
 1775            }
 1776
 01777            if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
 1778            {
 01779                return TransportStreamTimestamp.None;
 1780            }
 1781
 01782            if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
 1783            {
 01784                return TransportStreamTimestamp.Zero;
 1785            }
 1786
 01787            return TransportStreamTimestamp.Valid;
 1788        }
 1789
 1790        [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
 1791        private static partial Regex PerformerRegex();
 1792
 1793        [GeneratedRegex(@"(\.\d{7})\d+")]
 1794        private static partial Regex DurationOverPrecisionRegex();
 1795    }
 1796}

Methods/Properties

.cctor()
.ctor(Microsoft.Extensions.Logging.ILogger,MediaBrowser.Model.Globalization.ILocalizationManager)
get_SplitWhitelist()
GetMediaInfo(MediaBrowser.MediaEncoding.Probing.InternalMediaInfoResult,System.Nullable`1<MediaBrowser.Model.Entities.VideoType>,System.Boolean,System.String,MediaBrowser.Model.MediaInfo.MediaProtocol)
NormalizeFormat(System.String,System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Model.Entities.MediaStream>)
GetEstimatedAudioBitrate(System.String,System.String,System.Nullable`1<System.Int32>)
IsDtsLossless(System.String)
FetchFromItunesInfo(System.String,MediaBrowser.Model.MediaInfo.MediaInfo)
ReadFromDictNode(System.Xml.XmlReader,MediaBrowser.Model.MediaInfo.MediaInfo)
ReadValueArray(System.Xml.XmlReader)
ProcessPairs(System.String,System.Collections.Generic.List`1<MediaBrowser.Model.Dto.NameValuePair>,MediaBrowser.Model.MediaInfo.MediaInfo)
GetNameValuePair(System.Xml.XmlReader)
NormalizeSubtitleCodec(System.String)
GetMediaAttachment(MediaBrowser.MediaEncoding.Probing.MediaStreamInfo)
GetMediaStream(System.Boolean,MediaBrowser.MediaEncoding.Probing.MediaStreamInfo,MediaBrowser.MediaEncoding.Probing.MediaFormatInfo,System.Collections.Generic.IReadOnlyList`1<MediaBrowser.MediaEncoding.Probing.MediaFrameInfo>)
NormalizeStreamTitle(MediaBrowser.Model.Entities.MediaStream)
GetDictionaryValue(System.Collections.Generic.IReadOnlyDictionary`2<System.String,System.String>,System.String)
ParseChannelLayout(System.String)
GetAspectRatio(MediaBrowser.MediaEncoding.Probing.MediaStreamInfo)
IsClose(System.Double,System.Double,System.Double)
IsNearSquarePixelSar(System.String)
GetFrameRate(System.ReadOnlySpan`1<System.Char>)
SetAudioRuntimeTicks(MediaBrowser.MediaEncoding.Probing.InternalMediaInfoResult,MediaBrowser.Model.MediaInfo.MediaInfo)
GetBPSFromTags(MediaBrowser.MediaEncoding.Probing.MediaStreamInfo)
GetRuntimeSecondsFromTags(MediaBrowser.MediaEncoding.Probing.MediaStreamInfo)
GetNumberOfBytesFromTags(MediaBrowser.MediaEncoding.Probing.MediaStreamInfo)
SetSize(MediaBrowser.MediaEncoding.Probing.InternalMediaInfoResult,MediaBrowser.Model.MediaInfo.MediaInfo)
SetAudioInfoFromTags(MediaBrowser.Model.MediaInfo.MediaInfo,System.Collections.Generic.Dictionary`2<System.String,System.String>)
GetMultipleMusicBrainzId(System.String)
Split(System.String,System.Boolean)
SplitDistinctArtists(System.String,System.Char[],System.Boolean)
FetchStudios(MediaBrowser.Model.MediaInfo.MediaInfo,System.Collections.Generic.IReadOnlyDictionary`2<System.String,System.String>,System.String)
FetchGenres(MediaBrowser.Model.MediaInfo.MediaInfo,System.Collections.Generic.IReadOnlyDictionary`2<System.String,System.String>)
GetDictionaryTrackOrDiscNumber(System.Collections.Generic.IReadOnlyDictionary`2<System.String,System.String>,System.String)
GetChapterInfo(MediaBrowser.MediaEncoding.Probing.MediaChapter)
FetchWtvInfo(MediaBrowser.Model.MediaInfo.MediaInfo,MediaBrowser.MediaEncoding.Probing.InternalMediaInfoResult)
ExtractTimestamp(MediaBrowser.Model.MediaInfo.MediaInfo)
GetMpegTimestamp(System.String)