< 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: 638
Uncovered lines: 146
Coverable lines: 784
Total lines: 1782
Line coverage: 81.3%
Branch coverage
71%
Covered branches: 515
Total branches: 718
Branch coverage: 71.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 3/26/2026 - 12:14:14 AM Line coverage: 79.6% (606/761) Branch coverage: 75.2% (474/630) Total lines: 17603/31/2026 - 12:14:24 AM Line coverage: 79.2% (601/758) Branch coverage: 74.8% (473/632) Total lines: 17494/12/2026 - 12:13:54 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: 1782 3/26/2026 - 12:14:14 AM Line coverage: 79.6% (606/761) Branch coverage: 75.2% (474/630) Total lines: 17603/31/2026 - 12:14:24 AM Line coverage: 79.2% (601/758) Branch coverage: 74.8% (473/632) Total lines: 17494/12/2026 - 12:13:54 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: 1782

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(...)73.75%27916083.33%
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.HasValue && info.PremiereDate.HasValue)
 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                stream.LocalizedLanguage = string.IsNullOrEmpty(stream.Language)
 14736                    ? null
 14737                    : _localization.FindLanguageInfo(stream.Language)?.DisplayName;
 738
 14739                stream.Channels = streamInfo.Channels;
 740
 14741                if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
 742                {
 14743                    stream.SampleRate = sampleRate;
 744                }
 745
 14746                stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
 747
 14748                if (streamInfo.BitsPerSample > 0)
 749                {
 0750                    stream.BitDepth = streamInfo.BitsPerSample;
 751                }
 14752                else if (streamInfo.BitsPerRawSample > 0)
 753                {
 3754                    stream.BitDepth = streamInfo.BitsPerRawSample;
 755                }
 756
 14757                if (string.IsNullOrEmpty(stream.Title))
 758                {
 759                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 14760                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 14761                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComparis
 762                    {
 3763                        stream.Title = handlerName;
 764                    }
 765                }
 766            }
 20767            else if (streamInfo.CodecType == CodecType.Subtitle)
 768            {
 4769                stream.Type = MediaStreamType.Subtitle;
 4770                stream.Codec = NormalizeSubtitleCodec(stream.Codec);
 4771                stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
 4772                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 4773                stream.LocalizedForced = _localization.GetLocalizedString("Forced");
 4774                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 4775                stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
 4776                stream.LocalizedLanguage = string.IsNullOrEmpty(stream.Language)
 4777                    ? null
 4778                    : _localization.FindLanguageInfo(stream.Language)?.DisplayName;
 779
 4780                if (string.IsNullOrEmpty(stream.Title))
 781                {
 782                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 4783                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 4784                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringCompa
 785                    {
 1786                        stream.Title = handlerName;
 787                    }
 788                }
 789            }
 16790            else if (streamInfo.CodecType == CodecType.Video)
 791            {
 16792                stream.IsAVC = streamInfo.IsAvc;
 16793                stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
 16794                stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
 795
 16796                stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
 16797                    && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
 798
 16799                if (isAudio
 16800                    || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
 16801                    || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
 16802                    || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
 16803                    || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
 804                {
 2805                    stream.Type = MediaStreamType.EmbeddedImage;
 806                }
 14807                else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 808                {
 809                    // How to differentiate between video and embedded image?
 810                    // The only difference I've seen thus far is presence of codec tag, also embedded images have high (
 1811                    if (!string.IsNullOrWhiteSpace(stream.CodecTag))
 812                    {
 0813                        stream.Type = MediaStreamType.Video;
 814                    }
 815                    else
 816                    {
 1817                        stream.Type = MediaStreamType.EmbeddedImage;
 818                    }
 819                }
 820                else
 821                {
 13822                    stream.Type = MediaStreamType.Video;
 823                }
 824
 16825                stream.AspectRatio = GetAspectRatio(streamInfo);
 826
 16827                if (streamInfo.BitsPerSample > 0)
 828                {
 0829                    stream.BitDepth = streamInfo.BitsPerSample;
 830                }
 16831                else if (streamInfo.BitsPerRawSample > 0)
 832                {
 13833                    stream.BitDepth = streamInfo.BitsPerRawSample;
 834                }
 835
 16836                if (!stream.BitDepth.HasValue)
 837                {
 3838                    if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
 839                    {
 3840                        if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
 3841                            || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
 842                        {
 3843                            stream.BitDepth = 8;
 844                        }
 0845                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase
 0846                                 || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreC
 847                        {
 0848                            stream.BitDepth = 10;
 849                        }
 0850                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase
 0851                                 || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreC
 852                        {
 0853                            stream.BitDepth = 12;
 854                        }
 855                    }
 856                }
 857
 858                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 16859                if (string.IsNullOrEmpty(streamInfo.SampleAspectRatio)
 16860                    && string.IsNullOrEmpty(streamInfo.DisplayAspectRatio))
 861                {
 5862                    stream.IsAnamorphic = false;
 863                }
 11864                else if (IsNearSquarePixelSar(streamInfo.SampleAspectRatio))
 865                {
 9866                    stream.IsAnamorphic = false;
 867                }
 2868                else if (!string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.Ordinal))
 869                {
 1870                    stream.IsAnamorphic = true;
 871                }
 1872                else if (string.Equals(streamInfo.DisplayAspectRatio, "0:1", StringComparison.Ordinal))
 873                {
 1874                    stream.IsAnamorphic = false;
 875                }
 0876                else if (!string.Equals(
 0877                             streamInfo.DisplayAspectRatio,
 0878                             // Force GetAspectRatio() to derive ratio from Width/Height directly by using null DAR
 0879                             GetAspectRatio(new MediaStreamInfo
 0880                             {
 0881                                 Width = streamInfo.Width,
 0882                                 Height = streamInfo.Height,
 0883                                 DisplayAspectRatio = null
 0884                             }),
 0885                             StringComparison.Ordinal))
 886                {
 0887                    stream.IsAnamorphic = true;
 888                }
 889                else
 890                {
 0891                    stream.IsAnamorphic = false;
 892                }
 893
 16894                if (streamInfo.Refs > 0)
 895                {
 15896                    stream.RefFrames = streamInfo.Refs;
 897                }
 898
 16899                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 900                {
 5901                    stream.ColorRange = streamInfo.ColorRange;
 902                }
 903
 16904                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 905                {
 5906                    stream.ColorSpace = streamInfo.ColorSpace;
 907                }
 908
 16909                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 910                {
 2911                    stream.ColorTransfer = streamInfo.ColorTransfer;
 912                }
 913
 16914                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 915                {
 2916                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 917                }
 918
 16919                if (streamInfo.SideDataList is not null)
 920                {
 6921                    foreach (var data in streamInfo.SideDataList)
 922                    {
 923                        // Parse Dolby Vision metadata from side_data
 2924                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 925                        {
 1926                            stream.DvVersionMajor = data.DvVersionMajor;
 1927                            stream.DvVersionMinor = data.DvVersionMinor;
 1928                            stream.DvProfile = data.DvProfile;
 1929                            stream.DvLevel = data.DvLevel;
 1930                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1931                            stream.ElPresentFlag = data.ElPresentFlag;
 1932                            stream.BlPresentFlag = data.BlPresentFlag;
 1933                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 934                        }
 935
 936                        // Parse video rotation metadata from side_data
 1937                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 938                        {
 1939                            stream.Rotation = data.Rotation;
 940                        }
 941
 942                        // Parse video frame cropping metadata from side_data
 943                        // TODO: save them and make HW filters to apply them in HWA pipelines
 0944                        else if (string.Equals(data.SideDataType, "Frame Cropping", StringComparison.OrdinalIgnoreCase))
 945                        {
 946                            // Streams containing artificially added frame cropping
 947                            // metadata should not be marked as anamorphic.
 0948                            stream.IsAnamorphic = false;
 949                        }
 950                    }
 951                }
 952
 16953                var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
 16954                if (frameInfo?.SideDataList is not null
 16955                    && frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE20
 956                {
 0957                    stream.Hdr10PlusPresentFlag = true;
 958                }
 959            }
 0960            else if (streamInfo.CodecType == CodecType.Data)
 961            {
 0962                stream.Type = MediaStreamType.Data;
 963            }
 964            else
 965            {
 0966                return null;
 967            }
 968
 969            // Get stream bitrate
 34970            var bitrate = 0;
 971
 34972            if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
 973            {
 14974                bitrate = value;
 975            }
 976
 977            // The bitrate info of FLAC audio is included in formatInfo.
 978            // Don't do this for video streams: formatInfo.BitRate is the overall container
 979            // bitrate (video + audio + subtitles + overhead), not the video bitrate.
 34980            if (bitrate == 0
 34981                && formatInfo is not null
 34982                && isAudio && stream.Type == MediaStreamType.Audio)
 983            {
 984                // If the stream info doesn't have a bitrate get the value from the media format info
 2985                if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
 986                {
 2987                    bitrate = value;
 988                }
 989            }
 990
 34991            if (bitrate > 0)
 992            {
 16993                stream.BitRate = bitrate;
 994            }
 995
 996            // Extract bitrate info from tag "BPS" if possible.
 34997            if (!stream.BitRate.HasValue
 34998                && (streamInfo.CodecType == CodecType.Audio
 34999                    || streamInfo.CodecType == CodecType.Video))
 1000            {
 171001                var bps = GetBPSFromTags(streamInfo);
 171002                if (bps > 0)
 1003                {
 21004                    stream.BitRate = bps;
 1005                }
 1006                else
 1007                {
 1008                    // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
 151009                    var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
 151010                    var bytes = GetNumberOfBytesFromTags(streamInfo);
 151011                    if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
 1012                    {
 11013                        bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
 11014                        if (bps > 0)
 1015                        {
 11016                            stream.BitRate = bps;
 1017                        }
 1018                    }
 1019                }
 1020            }
 1021
 341022            var disposition = streamInfo.Disposition;
 341023            if (disposition is not null)
 1024            {
 341025                if (disposition.GetValueOrDefault("default") == 1)
 1026                {
 221027                    stream.IsDefault = true;
 1028                }
 1029
 341030                if (disposition.GetValueOrDefault("forced") == 1)
 1031                {
 01032                    stream.IsForced = true;
 1033                }
 1034
 341035                if (disposition.GetValueOrDefault("hearing_impaired") == 1)
 1036                {
 11037                    stream.IsHearingImpaired = true;
 1038                }
 1039
 341040                if (disposition.GetValueOrDefault("original") == 1)
 1041                {
 11042                    stream.IsOriginal = true;
 1043                }
 1044            }
 1045
 341046            NormalizeStreamTitle(stream);
 1047
 341048            return stream;
 1049        }
 1050
 1051        private static void NormalizeStreamTitle(MediaStream stream)
 1052        {
 341053            if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
 341054                || stream.Type == MediaStreamType.EmbeddedImage)
 1055            {
 31056                stream.Title = null;
 1057            }
 341058        }
 1059
 1060        /// <summary>
 1061        /// Gets a string from an FFProbeResult tags dictionary.
 1062        /// </summary>
 1063        /// <param name="tags">The tags.</param>
 1064        /// <param name="key">The key.</param>
 1065        /// <returns>System.String.</returns>
 1066        private static string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
 1067        {
 1991068            if (tags is null)
 1069            {
 31070                return null;
 1071            }
 1072
 1961073            tags.TryGetValue(key, out var val);
 1074
 1961075            return val;
 1076        }
 1077
 1078        private static string ParseChannelLayout(string input)
 1079        {
 141080            if (string.IsNullOrEmpty(input))
 1081            {
 21082                return null;
 1083            }
 1084
 121085            return input.AsSpan().LeftPart('(').ToString();
 1086        }
 1087
 1088        private static string GetAspectRatio(MediaStreamInfo info)
 1089        {
 161090            var original = info.DisplayAspectRatio;
 1091
 161092            var parts = (original ?? string.Empty).Split(':');
 161093            if (!(parts.Length == 2
 161094                    && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
 161095                    && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
 161096                    && width > 0
 161097                    && height > 0))
 1098            {
 61099                width = info.Width.Value;
 61100                height = info.Height.Value;
 1101            }
 1102
 161103            if (width > 0 && height > 0)
 1104            {
 161105                double ratio = width;
 161106                ratio /= height;
 1107
 161108                if (IsClose(ratio, 1.777777778, .03))
 1109                {
 101110                    return "16:9";
 1111                }
 1112
 61113                if (IsClose(ratio, 1.3333333333, .05))
 1114                {
 11115                    return "4:3";
 1116                }
 1117
 51118                if (IsClose(ratio, 1.41))
 1119                {
 01120                    return "1.41:1";
 1121                }
 1122
 51123                if (IsClose(ratio, 1.5))
 1124                {
 21125                    return "1.5:1";
 1126                }
 1127
 31128                if (IsClose(ratio, 1.6))
 1129                {
 01130                    return "1.6:1";
 1131                }
 1132
 31133                if (IsClose(ratio, 1.66666666667))
 1134                {
 01135                    return "5:3";
 1136                }
 1137
 31138                if (IsClose(ratio, 1.85, .02))
 1139                {
 01140                    return "1.85:1";
 1141                }
 1142
 31143                if (IsClose(ratio, 2.35, .025))
 1144                {
 01145                    return "2.35:1";
 1146                }
 1147
 31148                if (IsClose(ratio, 2.4, .025))
 1149                {
 11150                    return "2.40:1";
 1151                }
 1152            }
 1153
 21154            return original;
 1155        }
 1156
 1157        private static bool IsClose(double d1, double d2, double variance = .005)
 1158        {
 691159            return Math.Abs(d1 - d2) <= variance;
 1160        }
 1161
 1162        /// <summary>
 1163        /// Determines whether a sample aspect ratio represents square (or near-square) pixels.
 1164        /// Some encoders produce SARs like 3201:3200 for content that is effectively 1:1,
 1165        /// which would be falsely classified as anamorphic by an exact string comparison.
 1166        /// A 1% tolerance safely covers encoder rounding artifacts while preserving detection
 1167        /// of genuine anamorphic content (closest standard is PAL 4:3 at 16:15 = 6.67% off).
 1168        /// </summary>
 1169        /// <param name="sar">The sample aspect ratio string in "N:D" format.</param>
 1170        /// <returns><c>true</c> if the SAR is within 1% of 1:1; otherwise <c>false</c>.</returns>
 1171        internal static bool IsNearSquarePixelSar(string sar)
 1172        {
 241173            if (string.IsNullOrEmpty(sar))
 1174            {
 21175                return false;
 1176            }
 1177
 221178            var parts = sar.Split(':');
 221179            if (parts.Length == 2
 221180                && double.TryParse(parts[0], CultureInfo.InvariantCulture, out var num)
 221181                && double.TryParse(parts[1], CultureInfo.InvariantCulture, out var den)
 221182                && den > 0)
 1183            {
 221184                return IsClose(num / den, 1.0, 0.01);
 1185            }
 1186
 01187            return string.Equals(sar, "1:1", StringComparison.Ordinal);
 1188        }
 1189
 1190        /// <summary>
 1191        /// Gets a frame rate from a string value in ffprobe output
 1192        /// This could be a number or in the format of 2997/125.
 1193        /// </summary>
 1194        /// <param name="value">The value.</param>
 1195        /// <returns>System.Nullable{System.Single}.</returns>
 1196        internal static float? GetFrameRate(ReadOnlySpan<char> value)
 1197        {
 411198            if (value.IsEmpty)
 1199            {
 01200                return null;
 1201            }
 1202
 411203            int index = value.IndexOf('/');
 411204            if (index == -1)
 1205            {
 01206                return null;
 1207            }
 1208
 411209            if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
 411210                || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var div
 1211            {
 01212                return null;
 1213            }
 1214
 411215            return divisor == 0f ? null : dividend / divisor;
 1216        }
 1217
 1218        private static void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
 1219        {
 1220            // Get the first info stream
 21221            var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
 21222            if (stream is null)
 1223            {
 01224                return;
 1225            }
 1226
 1227            // Get duration from stream properties
 21228            var duration = stream.Duration;
 1229
 1230            // If it's not there go into format properties
 21231            if (string.IsNullOrEmpty(duration))
 1232            {
 01233                duration = result.Format.Duration;
 1234            }
 1235
 1236            // If we got something, parse it
 21237            if (!string.IsNullOrEmpty(duration))
 1238            {
 21239                data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
 1240            }
 21241        }
 1242
 1243        private static int? GetBPSFromTags(MediaStreamInfo streamInfo)
 1244        {
 171245            if (streamInfo?.Tags is null)
 1246            {
 11247                return null;
 1248            }
 1249
 161250            var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
 161251            if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
 1252            {
 31253                return parsedBps;
 1254            }
 1255
 131256            return null;
 1257        }
 1258
 1259        private static double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
 1260        {
 151261            if (streamInfo?.Tags is null)
 1262            {
 11263                return null;
 1264            }
 1265
 141266            var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "D
 141267            if (!string.IsNullOrEmpty(duration))
 1268            {
 1269                // Matroska DURATION tags use nanosecond precision (e.g. "00:00:05.023000000"), but
 1270                // TimeSpan only supports up to 7 fractional digits (ticks). Trim the surplus digits so
 1271                // these durations parse instead of being silently dropped.
 31272                duration = DurationOverPrecisionRegex().Replace(duration, "$1");
 31273                if (TimeSpan.TryParse(duration, CultureInfo.InvariantCulture, out var parsedDuration))
 1274                {
 31275                    return parsedDuration.TotalSeconds;
 1276                }
 1277            }
 1278
 111279            return null;
 1280        }
 1281
 1282        private static long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
 1283        {
 151284            if (streamInfo?.Tags is null)
 1285            {
 11286                return null;
 1287            }
 1288
 141289            var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
 141290                                ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
 141291            if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
 1292            {
 21293                return parsedBytes;
 1294            }
 1295
 121296            return null;
 1297        }
 1298
 1299        private static void SetSize(InternalMediaInfoResult data, MediaInfo info)
 1300        {
 151301            if (data.Format is null)
 1302            {
 11303                return;
 1304            }
 1305
 141306            info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.Invaria
 141307        }
 1308
 1309        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
 1310        {
 21311            var people = new List<BaseItemPerson>();
 21312            if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
 1313            {
 121314                foreach (var person in Split(composer, false))
 1315                {
 41316                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
 1317                }
 1318            }
 1319
 21320            if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
 1321            {
 01322                foreach (var person in Split(conductor, false))
 1323                {
 01324                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
 1325                }
 1326            }
 1327
 21328            if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
 1329            {
 81330                foreach (var person in Split(lyricist, false))
 1331                {
 21332                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
 1333                }
 1334            }
 1335
 21336            if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
 1337            {
 501338                foreach (var person in Split(performer, false))
 1339                {
 231340                    Match match = PerformerRegex().Match(person);
 1341
 1342                    // If the performer doesn't have any instrument/role associated, it won't match. In that case, chanc
 231343                    if (match.Success)
 1344                    {
 221345                        people.Add(new BaseItemPerson
 221346                        {
 221347                            Name = match.Groups["name"].Value,
 221348                            Type = PersonKind.Actor,
 221349                            Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
 221350                        });
 1351                    }
 1352                }
 1353            }
 1354
 1355            // In cases where there isn't sufficient information as to which role a writer performed on a recording, tag
 21356            if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
 1357            {
 01358                foreach (var person in Split(writer, false))
 1359                {
 01360                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
 1361                }
 1362            }
 1363
 21364            if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
 1365            {
 121366                foreach (var person in Split(arranger, false))
 1367                {
 41368                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
 1369                }
 1370            }
 1371
 21372            if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
 1373            {
 01374                foreach (var person in Split(engineer, false))
 1375                {
 01376                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
 1377                }
 1378            }
 1379
 21380            if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
 1381            {
 81382                foreach (var person in Split(mixer, false))
 1383                {
 21384                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
 1385                }
 1386            }
 1387
 21388            if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
 1389            {
 01390                foreach (var person in Split(remixer, false))
 1391                {
 01392                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
 1393                }
 1394            }
 1395
 21396            audio.People = people.ToArray();
 1397
 1398            // Set album artist
 21399            var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
 21400            audio.AlbumArtists = albumArtist is not null
 21401                ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
 21402                : Array.Empty<string>();
 1403
 1404            // Set album artist to artist if empty
 21405            if (audio.AlbumArtists.Length == 0)
 1406            {
 01407                audio.AlbumArtists = audio.Artists;
 1408            }
 1409
 1410            // Track number
 21411            audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
 1412
 1413            // Disc number
 21414            audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
 1415
 1416            // There's several values in tags may or may not be present
 21417            FetchStudios(audio, tags, "organization");
 21418            FetchStudios(audio, tags, "ensemble");
 21419            FetchStudios(audio, tags, "publisher");
 21420            FetchStudios(audio, tags, "label");
 1421
 1422            // These support multiple values, but for now we only store the first.
 21423            var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
 21424                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
 21425            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
 1426
 21427            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
 21428                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
 21429            audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
 1430
 21431            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
 21432                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
 21433            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
 1434
 21435            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
 21436                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
 21437            audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
 1438
 21439            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
 21440                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
 21441            audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
 21442        }
 1443
 1444        private static string GetMultipleMusicBrainzId(string value)
 1445        {
 201446            if (string.IsNullOrWhiteSpace(value))
 1447            {
 101448                return null;
 1449            }
 1450
 101451            return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
 101452                .FirstOrDefault();
 1453        }
 1454
 1455        /// <summary>
 1456        /// Splits the specified val.
 1457        /// </summary>
 1458        /// <param name="val">The val.</param>
 1459        /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
 1460        /// <returns>System.String[][].</returns>
 1461        private string[] Split(string val, bool allowCommaDelimiter)
 1462        {
 1463            // Only use the comma as a delimiter if there are no slashes or pipes.
 1464            // We want to be careful not to split names that have commas in them
 141465            return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
 141466                val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
 141467                val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1468        }
 1469
 1470        private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
 1471        {
 51472            if (splitFeaturing)
 1473            {
 31474                val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
 31475                    .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
 1476            }
 1477
 51478            var artistsFound = new List<string>();
 1479
 3101480            foreach (var whitelistArtist in SplitWhitelist)
 1481            {
 1501482                var originalVal = val;
 1501483                val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
 1484
 1501485                if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
 1486                {
 01487                    artistsFound.Add(whitelistArtist);
 1488                }
 1489            }
 1490
 51491            var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1492
 51493            artistsFound.AddRange(artists);
 51494            return artistsFound.DistinctNames();
 1495        }
 1496
 1497        /// <summary>
 1498        /// Gets the studios from the tags collection.
 1499        /// </summary>
 1500        /// <param name="info">The info.</param>
 1501        /// <param name="tags">The tags.</param>
 1502        /// <param name="tagName">Name of the tag.</param>
 1503        private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
 1504        {
 211505            var val = tags.GetValueOrDefault(tagName);
 1506
 211507            if (string.IsNullOrEmpty(val))
 1508            {
 191509                return;
 1510            }
 1511
 21512            var studios = Split(val, true);
 21513            var studioList = new List<string>();
 1514
 81515            foreach (var studio in studios)
 1516            {
 21517                if (string.IsNullOrWhiteSpace(studio))
 1518                {
 1519                    continue;
 1520                }
 1521
 1522                // Don't add artist/album artist name to studios, even if it's listed there
 21523                if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
 21524                    || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
 1525                {
 1526                    continue;
 1527                }
 1528
 21529                studioList.Add(studio);
 1530            }
 1531
 21532            info.Studios = studioList
 21533                .Distinct(StringComparer.OrdinalIgnoreCase)
 21534                .ToArray();
 21535        }
 1536
 1537        /// <summary>
 1538        /// Gets the genres from the tags collection.
 1539        /// </summary>
 1540        /// <param name="info">The information.</param>
 1541        /// <param name="tags">The tags.</param>
 1542        private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
 1543        {
 151544            var genreVal = tags.GetValueOrDefault("genre");
 151545            if (string.IsNullOrEmpty(genreVal))
 1546            {
 131547                return;
 1548            }
 1549
 21550            var genres = new List<string>(info.Genres);
 201551            foreach (var genre in Split(genreVal, true))
 1552            {
 81553                if (string.IsNullOrEmpty(genre))
 1554                {
 1555                    continue;
 1556                }
 1557
 81558                genres.Add(genre);
 1559            }
 1560
 21561            info.Genres = genres
 21562                .Distinct(StringComparer.OrdinalIgnoreCase)
 21563                .ToArray();
 21564        }
 1565
 1566        /// <summary>
 1567        /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
 1568        /// </summary>
 1569        /// <param name="tags">The tags.</param>
 1570        /// <param name="tagName">Name of the tag.</param>
 1571        /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
 1572        private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
 1573        {
 41574            var disc = tags.GetValueOrDefault(tagName);
 1575
 41576            if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
 1577            {
 41578                return discNum;
 1579            }
 1580
 01581            return null;
 1582        }
 1583
 1584        private static ChapterInfo GetChapterInfo(MediaChapter chapter)
 1585        {
 01586            var info = new ChapterInfo();
 1587
 01588            if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
 1589            {
 01590                info.Name = name;
 1591            }
 1592
 1593            // Limit accuracy to milliseconds to match xml saving
 01594            var secondsString = chapter.StartTime;
 1595
 01596            if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
 1597            {
 01598                var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
 01599                info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
 1600            }
 1601
 01602            return info;
 1603        }
 1604
 1605        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
 1606        {
 131607            var tags = data.Format?.Tags;
 1608
 131609            if (tags is null)
 1610            {
 41611                return;
 1612            }
 1613
 91614            if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
 1615            {
 01616                var genreList = genres.Split(_genreDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOption
 1617
 1618                // If this is empty then don't overwrite genres that might have been fetched earlier
 01619                if (genreList.Length > 0)
 1620                {
 01621                    video.Genres = genreList;
 1622                }
 1623            }
 1624
 91625            if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRati
 1626            {
 01627                video.OfficialRating = officialRating;
 1628            }
 1629
 91630            if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
 1631            {
 01632                video.People = Array.ConvertAll(
 01633                    people.Split(_basicDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntrie
 01634                    i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
 1635            }
 1636
 91637            if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, Cul
 1638            {
 01639                video.ProductionYear = parsedYear;
 1640            }
 1641
 1642            // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1643            // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
 91644            if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(y
 1645            {
 01646                video.PremiereDate = parsedDate;
 1647            }
 1648
 91649            var description = tags.GetValueOrDefault("WM/SubTitleDescription");
 1650
 91651            var subTitle = tags.GetValueOrDefault("WM/SubTitle");
 1652
 1653            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1654
 1655            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, ex
 1656            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
 1657            // OR -> COMMENT. SUBTITLE: DESCRIPTION
 1658            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the 
 1659            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in t
 91660            if (string.IsNullOrWhiteSpace(subTitle)
 91661                && !string.IsNullOrWhiteSpace(description)
 91662                && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains
 1663            {
 01664                string[] descriptionParts = description.Split(':');
 01665                if (descriptionParts.Length > 0)
 1666                {
 01667                    string subtitle = descriptionParts[0];
 1668                    try
 1669                    {
 1670                        // Check if it contains a episode number and season number
 01671                        if (subtitle.Contains('/', StringComparison.Ordinal))
 1672                        {
 01673                            string[] subtitleParts = subtitle.Split(' ');
 01674                            string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Spl
 01675                            video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
 1676                            // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
 1677
 1678                            // Skip the numbers, concatenate the rest, trim and set as new description
 01679                            description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1680                        }
 01681                        else if (subtitle.Contains('.', StringComparison.Ordinal))
 1682                        {
 01683                            var subtitleParts = subtitle.Split('.');
 01684                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1685                        }
 1686                        else
 1687                        {
 01688                            description = subtitle.Trim();
 1689                        }
 01690                    }
 01691                    catch (Exception ex)
 1692                    {
 01693                        _logger.LogError(ex, "Error while parsing subtitle field");
 1694
 1695                        // Fallback to default parsing
 01696                        if (subtitle.Contains('.', StringComparison.Ordinal))
 1697                        {
 01698                            var subtitleParts = subtitle.Split('.');
 01699                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1700                        }
 1701                        else
 1702                        {
 01703                            description = subtitle.Trim();
 1704                        }
 01705                    }
 1706                }
 1707            }
 1708
 91709            if (!string.IsNullOrWhiteSpace(description))
 1710            {
 01711                video.Overview = description;
 1712            }
 91713        }
 1714
 1715        private void ExtractTimestamp(MediaInfo video)
 1716        {
 131717            if (video.VideoType != VideoType.VideoFile)
 1718            {
 01719                return;
 1720            }
 1721
 1722            // Skip timestamp extration for remote resource (http, rtsp, etc.)
 1723            // as they cannot be opened with FileStream
 131724            if (video.Protocol != MediaProtocol.File)
 1725            {
 01726                return;
 1727            }
 1728
 131729            if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
 131730                && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
 131731                && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
 1732            {
 121733                return;
 1734            }
 1735
 1736            try
 1737            {
 11738                video.Timestamp = GetMpegTimestamp(video.Path);
 01739                _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
 01740            }
 11741            catch (Exception ex)
 1742            {
 11743                video.Timestamp = null;
 11744                _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
 11745            }
 11746        }
 1747
 1748        // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
 1749        private static TransportStreamTimestamp GetMpegTimestamp(string path)
 1750        {
 11751            var packetBuffer = new byte[197];
 1752
 11753            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
 1754            {
 01755                fs.ReadExactly(packetBuffer);
 01756            }
 1757
 01758            if (packetBuffer[0] == 71)
 1759            {
 01760                return TransportStreamTimestamp.None;
 1761            }
 1762
 01763            if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
 1764            {
 01765                return TransportStreamTimestamp.None;
 1766            }
 1767
 01768            if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
 1769            {
 01770                return TransportStreamTimestamp.Zero;
 1771            }
 1772
 01773            return TransportStreamTimestamp.Valid;
 1774        }
 1775
 1776        [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
 1777        private static partial Regex PerformerRegex();
 1778
 1779        [GeneratedRegex(@"(\.\d{7})\d+")]
 1780        private static partial Regex DurationOverPrecisionRegex();
 1781    }
 1782}

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)