< 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: 645
Uncovered lines: 143
Coverable lines: 788
Total lines: 1804
Line coverage: 81.8%
Branch coverage
72%
Covered branches: 527
Total branches: 724
Branch coverage: 72.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/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: 179610/29/2026 - 12:17:11 AM Line coverage: 81.8% (645/788) Branch coverage: 72.7% (528/726) Total lines: 180211/7/2026 - 12:19:31 AM Line coverage: 81.8% (645/788) Branch coverage: 72.7% (527/724) Total lines: 1804 5/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: 179610/29/2026 - 12:17:11 AM Line coverage: 81.8% (645/788) Branch coverage: 72.7% (528/726) Total lines: 180211/7/2026 - 12:19:31 AM Line coverage: 81.8% (645/788) Branch coverage: 72.7% (527/724) Total lines: 1804

Coverage delta

Coverage delta 7 -7

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%11100%
get_SplitWhitelist()100%22100%
GetMediaInfo(...)80.48%848293.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%1010100%
GetMediaStream(...)76.25%26316084.09%
NormalizeStreamTitle(...)75%44100%
GetDictionaryValue(...)100%22100%
ParseChannelLayout(...)100%22100%
GetAspectRatio(...)78.57%484284.84%
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(...)100%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(...)90%111081.25%
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        {
 6751            _logger = logger;
 6752            _localization = localization;
 6753        }
 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        {
 18100            var info = new MediaInfo
 18101            {
 18102                Path = path,
 18103                Protocol = protocol,
 18104                VideoType = videoType
 18105            };
 106
 18107            FFProbeHelpers.NormalizeFFProbeResult(data);
 18108            SetSize(data, info);
 109
 18110            var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
 18111            var internalFrames = data.Frames ?? Array.Empty<MediaFrameInfo>();
 112
 18113            info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format, internalFrames))
 18114                .Where(i => i is not null)
 18115                // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know
 18116                .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
 18117                .ToList();
 118
 18119            info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
 18120                .Where(i => i is not null)
 18121                .ToList();
 122
 18123            if (data.Format is not null)
 124            {
 17125                info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
 126
 17127                if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
 128                {
 14129                    info.Bitrate = value;
 130                }
 131            }
 132
 18133            var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 18134            var tagStreamType = isAudio ? CodecType.Audio : CodecType.Video;
 135
 18136            var tagStream = data.Streams?.FirstOrDefault(i => i.CodecType == tagStreamType);
 137
 18138            if (tagStream?.Tags is not null)
 139            {
 108140                foreach (var (key, value) in tagStream.Tags)
 141                {
 41142                    tags[key] = value;
 143                }
 144            }
 145
 18146            if (data.Format?.Tags is not null)
 147            {
 318148                foreach (var (key, value) in data.Format.Tags)
 149                {
 147150                    tags[key] = value;
 151                }
 152            }
 153
 18154            FetchGenres(info, tags);
 155
 18156            info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
 18157            info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
 18158            info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc", "comment");
 159
 18160            info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
 18161            info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort") ??
 18162                               FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_id");
 18163            info.ShowName = tags.GetValueOrDefault("show_name", "show");
 18164            info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
 165
 166            // Several different forms of retail/premiere date
 18167            info.PremiereDate =
 18168                FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
 18169                FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
 18170                FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
 18171                FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
 18172                FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
 18173                FFProbeHelpers.GetDictionaryDateTime(tags, "date");
 174
 175            // creation_time is when the file was written, not a release date
 18176            info.ContainerCreationDate = FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time");
 177
 178            // Set common metadata for music (audio) and music videos (video)
 18179            info.Album = tags.GetValueOrDefault("album");
 180
 18181            if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
 182            {
 2183                info.Artists = SplitDistinctArtists(artists, _basicDelimiters, false).ToArray();
 184            }
 185            else
 186            {
 16187                var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
 16188                info.Artists = artist is null
 16189                    ? Array.Empty<string>()
 16190                    : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
 191            }
 192
 193            // Guess ProductionYear from PremiereDate if missing
 18194            if (info.ProductionYear is null && info.PremiereDate is not null)
 195            {
 3196                info.ProductionYear = info.PremiereDate.Value.Year;
 197            }
 198
 18199            if (data.Chapters is not null)
 200            {
 3201                info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
 202            }
 203
 204            // Set mediaType-specific metadata
 18205            if (isAudio)
 206            {
 2207                SetAudioRuntimeTicks(data, info);
 208
 209                // tags are normally located under data.format, but we've seen some cases with ogg where they're part of
 210                // so let's create a combined list of both
 211
 2212                SetAudioInfoFromTags(info, tags);
 213            }
 214            else
 215            {
 16216                FetchStudios(info, tags, "copyright");
 217
 16218                var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
 16219                if (iTunExtc is not null)
 220                {
 0221                    var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
 222                    // Example
 223                    // mpaa|G|100|For crude humor
 0224                    if (parts.Length > 1)
 225                    {
 0226                        info.OfficialRating = parts[1];
 227
 0228                        if (parts.Length > 3)
 229                        {
 0230                            info.OfficialRatingDescription = parts[3];
 231                        }
 232                    }
 233                }
 234
 16235                var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
 16236                if (iTunXml is not null)
 237                {
 2238                    FetchFromItunesInfo(iTunXml, info);
 239                }
 240
 16241                if (data.Format is not null && !string.IsNullOrEmpty(data.Format.Duration))
 242                {
 13243                    info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCul
 244                }
 245
 16246                FetchWtvInfo(info, data);
 247
 16248                ExtractTimestamp(info);
 249
 16250                if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", Strin
 251                {
 0252                    info.Video3DFormat = Video3DFormat.FullSideBySide;
 253                }
 254
 104255                foreach (var mediaStream in info.MediaStreams)
 256                {
 36257                    if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
 258                    {
 4259                        mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Profile, mediaStre
 260                    }
 261                }
 262
 263                // ffprobe frequently omits the per-stream video bitrate (common in MP4/MKV containers).
 264                // Estimate the missing video bitrate as the container bitrate minus the combined stream bitrates.
 16265                var videoStreams = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).ToList();
 16266                if (info.Bitrate.HasValue
 16267                    && videoStreams.Count == 1
 16268                    && !videoStreams[0].BitRate.HasValue)
 269                {
 7270                    var otherStreams = info.MediaStreams
 7271                        .Where(i => i.Type != MediaStreamType.Video && !i.IsExternal)
 7272                        .ToList();
 273
 274                    // Only attribute the leftover bitrate to the video stream if every audio stream's bitrate is known.
 7275                    var audioBitratesKnown = otherStreams
 7276                        .Where(i => i.Type == MediaStreamType.Audio)
 7277                        .All(i => i.BitRate.HasValue);
 278
 7279                    if (audioBitratesKnown)
 280                    {
 6281                        var estimatedVideoBitrate = info.Bitrate.Value - otherStreams.Sum(i => i.BitRate ?? 0);
 6282                        if (estimatedVideoBitrate > 0)
 283                        {
 5284                            videoStreams[0].BitRate = estimatedVideoBitrate;
 285                        }
 286                    }
 287                }
 288
 289                // If the container bitrate is still unknown, infer it from the sum of the streams.
 16290                info.InferTotalBitrate();
 291            }
 292
 18293            return info;
 294        }
 295
 296        private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
 297        {
 17298            if (string.IsNullOrWhiteSpace(format))
 299            {
 0300                return null;
 301            }
 302
 303            // Input can be a list of multiple, comma-delimited formats - each of them needs to be checked
 17304            var splitFormat = format.Split(',');
 140305            for (var i = 0; i < splitFormat.Length; i++)
 306            {
 307                // Handle MPEG-1 container
 53308                if (string.Equals(splitFormat[i], "mpegvideo", StringComparison.OrdinalIgnoreCase))
 309                {
 0310                    splitFormat[i] = "mpeg";
 311                }
 312
 313                // Handle MPEG-TS container
 53314                else if (string.Equals(splitFormat[i], "mpegts", StringComparison.OrdinalIgnoreCase))
 315                {
 3316                    splitFormat[i] = "ts";
 317                }
 318
 319                // Handle matroska container
 50320                else if (string.Equals(splitFormat[i], "matroska", StringComparison.OrdinalIgnoreCase))
 321                {
 6322                    splitFormat[i] = "mkv";
 323                }
 324
 325                // Handle WebM
 44326                else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
 327                {
 328                    // Limit WebM to supported stream types and codecs.
 329                    // FFprobe can report "matroska,webm" for Matroska-like containers, so only keep "webm" if all strea
 330                    // Any stream that is not video nor audio is not supported in WebM and should disqualify the webm co
 6331                    if (mediaStreams.Any(stream => stream.Type is not MediaStreamType.Video and not MediaStreamType.Audi
 6332                        || mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contain
 6333                            || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringC
 334                    {
 5335                        splitFormat[i] = string.Empty;
 336                    }
 337                }
 338            }
 339
 17340            return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
 341        }
 342
 343        internal static int? GetEstimatedAudioBitrate(string codec, string profile, int? channels)
 344        {
 30345            if (!channels.HasValue || channels.Value < 1 || string.IsNullOrEmpty(codec))
 346            {
 2347                return null;
 348            }
 349
 350            // Rough typical bitrates used only as a fallback when ffprobe doesn't report a stream bitrate.
 28351            var channelCount = channels.Value;
 28352            var isMultichannel = channelCount > 2;
 353
 28354            return codec.ToLowerInvariant() switch
 28355            {
 7356                "aac" or "mp3" or "mp2" => isMultichannel ? 320000 : 192000,
 3357                "ac3" or "eac3" => isMultichannel ? 640000 : 192000,
 6358                "dts" or "dca" => IsDtsLossless(profile) ? channelCount * 700000 : (isMultichannel ? 1509000 : 768000),
 1359                "opus" => isMultichannel ? 256000 : 128000,
 2360                "vorbis" => isMultichannel ? 320000 : 160000,
 1361                "wmav1" or "wmav2" or "wmapro" => isMultichannel ? 384000 : 192000,
 4362                "flac" or "alac" => channelCount * 480000,
 3363                "truehd" or "mlp" => channelCount * 700000,
 1364                _ => null
 28365            };
 366        }
 367
 368        private static bool IsDtsLossless(string profile)
 6369            => profile is not null && profile.Contains("HD MA", StringComparison.OrdinalIgnoreCase);
 370
 371        private void FetchFromItunesInfo(string xml, MediaInfo info)
 372        {
 373            // Make things simpler and strip out the dtd
 2374            var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
 375
 2376            if (plistIndex != -1)
 377            {
 2378                xml = xml.Substring(plistIndex);
 379            }
 380
 2381            xml = "<?xml version=\"1.0\"?>" + xml;
 382
 383            // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http
 2384            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
 2385            using (var streamReader = new StreamReader(stream))
 386            {
 387                try
 388                {
 2389                    using (var reader = XmlReader.Create(streamReader))
 390                    {
 2391                        reader.MoveToContent();
 2392                        reader.Read();
 393
 394                        // Loop through each element
 8395                        while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 396                        {
 6397                            if (reader.NodeType == XmlNodeType.Element)
 398                            {
 2399                                switch (reader.Name)
 400                                {
 401                                    case "dict":
 2402                                        if (reader.IsEmptyElement)
 403                                        {
 0404                                            reader.Read();
 0405                                            continue;
 406                                        }
 407
 2408                                        using (var subtree = reader.ReadSubtree())
 409                                        {
 2410                                            ReadFromDictNode(subtree, info);
 2411                                        }
 412
 413                                        break;
 414                                    default:
 0415                                        reader.Skip();
 0416                                        break;
 417                                }
 418                            }
 419                            else
 420                            {
 4421                                reader.Read();
 422                            }
 423                        }
 2424                    }
 2425                }
 0426                catch (XmlException)
 427                {
 428                    // I've seen probe examples where the iTunMOVI value is just "<"
 429                    // So we should not allow this to fail the entire probing operation
 0430                }
 431            }
 2432        }
 433
 434        private void ReadFromDictNode(XmlReader reader, MediaInfo info)
 435        {
 2436            string currentKey = null;
 2437            var pairs = new List<NameValuePair>();
 438
 2439            reader.MoveToContent();
 2440            reader.Read();
 441
 442            // Loop through each element
 38443            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 444            {
 36445                if (reader.NodeType == XmlNodeType.Element)
 446                {
 24447                    switch (reader.Name)
 448                    {
 449                        case "key":
 12450                            if (!string.IsNullOrWhiteSpace(currentKey))
 451                            {
 10452                                ProcessPairs(currentKey, pairs, info);
 453                            }
 454
 12455                            currentKey = reader.ReadElementContentAsString();
 12456                            pairs = new List<NameValuePair>();
 12457                            break;
 458                        case "string":
 2459                            var value = reader.ReadElementContentAsString();
 2460                            if (!string.IsNullOrWhiteSpace(value))
 461                            {
 2462                                pairs.Add(new NameValuePair
 2463                                {
 2464                                    Name = value,
 2465                                    Value = value
 2466                                });
 467                            }
 468
 2469                            break;
 470                        case "array":
 10471                            if (reader.IsEmptyElement)
 472                            {
 0473                                reader.Read();
 0474                                continue;
 475                            }
 476
 10477                            using (var subtree = reader.ReadSubtree())
 478                            {
 10479                                if (!string.IsNullOrWhiteSpace(currentKey))
 480                                {
 10481                                    pairs.AddRange(ReadValueArray(subtree));
 482                                }
 10483                            }
 484
 485                            break;
 486                        default:
 0487                            reader.Skip();
 0488                            break;
 489                    }
 490                }
 491                else
 492                {
 12493                    reader.Read();
 494                }
 495            }
 2496        }
 497
 498        private List<NameValuePair> ReadValueArray(XmlReader reader)
 499        {
 10500            var pairs = new List<NameValuePair>();
 501
 10502            reader.MoveToContent();
 10503            reader.Read();
 504
 505            // Loop through each element
 40506            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 507            {
 30508                if (reader.NodeType == XmlNodeType.Element)
 509                {
 10510                    switch (reader.Name)
 511                    {
 512                        case "dict":
 513
 10514                            if (reader.IsEmptyElement)
 515                            {
 0516                                reader.Read();
 0517                                continue;
 518                            }
 519
 10520                            using (var subtree = reader.ReadSubtree())
 521                            {
 10522                                var dict = GetNameValuePair(subtree);
 10523                                if (dict is not null)
 524                                {
 2525                                    pairs.Add(dict);
 526                                }
 10527                            }
 528
 529                            break;
 530                        default:
 0531                            reader.Skip();
 0532                            break;
 533                    }
 534                }
 535                else
 536                {
 20537                    reader.Read();
 538                }
 539            }
 540
 10541            return pairs;
 542        }
 543
 544        private static void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
 545        {
 10546            List<BaseItemPerson> peoples = new List<BaseItemPerson>();
 10547            var distinctPairs = pairs.Select(p => p.Value)
 10548                    .Where(i => !string.IsNullOrWhiteSpace(i))
 10549                    .Trimmed()
 10550                    .Distinct(StringComparer.OrdinalIgnoreCase);
 551
 10552            if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
 553            {
 2554                info.Studios = distinctPairs.ToArray();
 555            }
 8556            else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
 557            {
 0558                foreach (var pair in distinctPairs)
 559                {
 0560                    peoples.Add(new BaseItemPerson
 0561                    {
 0562                        Name = pair,
 0563                        Type = PersonKind.Writer
 0564                    });
 565                }
 566            }
 8567            else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
 568            {
 4569                foreach (var pair in distinctPairs)
 570                {
 0571                    peoples.Add(new BaseItemPerson
 0572                    {
 0573                        Name = pair,
 0574                        Type = PersonKind.Producer
 0575                    });
 576                }
 577            }
 6578            else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
 579            {
 4580                foreach (var pair in distinctPairs)
 581                {
 0582                    peoples.Add(new BaseItemPerson
 0583                    {
 0584                        Name = pair,
 0585                        Type = PersonKind.Director
 0586                    });
 587                }
 588            }
 589
 10590            info.People = peoples.ToArray();
 10591        }
 592
 593        private static NameValuePair GetNameValuePair(XmlReader reader)
 594        {
 10595            string name = null;
 10596            string value = null;
 597
 10598            reader.MoveToContent();
 10599            reader.Read();
 600
 601            // Loop through each element
 40602            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 603            {
 30604                if (reader.NodeType == XmlNodeType.Element)
 605                {
 20606                    switch (reader.Name)
 607                    {
 608                        case "key":
 10609                            name = reader.ReadNormalizedString();
 10610                            break;
 611                        case "string":
 10612                            value = reader.ReadNormalizedString();
 10613                            break;
 614                        default:
 0615                            reader.Skip();
 0616                            break;
 617                    }
 618                }
 619                else
 620                {
 10621                    reader.Read();
 622                }
 623            }
 624
 10625            if (string.IsNullOrEmpty(name)
 10626                || string.IsNullOrEmpty(value))
 627            {
 8628                return null;
 629            }
 630
 2631            return new NameValuePair
 2632            {
 2633                Name = name,
 2634                Value = value
 2635            };
 636        }
 637
 638        private static string NormalizeSubtitleCodec(string codec)
 639        {
 4640            if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
 641            {
 0642                codec = "DVBSUB";
 643            }
 4644            else if (string.Equals(codec, "dvb_teletext", StringComparison.OrdinalIgnoreCase))
 645            {
 0646                codec = "DVBTXT";
 647            }
 4648            else if (string.Equals(codec, "dvd_subtitle", StringComparison.OrdinalIgnoreCase))
 649            {
 1650                codec = "DVDSUB"; // .sub+.idx
 651            }
 3652            else if (string.Equals(codec, "hdmv_pgs_subtitle", StringComparison.OrdinalIgnoreCase))
 653            {
 0654                codec = "PGSSUB"; // .sup
 655            }
 656
 4657            return codec;
 658        }
 659
 660        /// <summary>
 661        /// Converts ffprobe stream info to our MediaAttachment class.
 662        /// </summary>
 663        /// <param name="streamInfo">The stream info.</param>
 664        /// <returns>MediaAttachments.</returns>
 665        private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
 666        {
 40667            if (streamInfo.CodecType != CodecType.Attachment
 40668                && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
 669            {
 38670                return null;
 671            }
 672
 2673            var attachment = new MediaAttachment
 2674            {
 2675                Codec = streamInfo.CodecName,
 2676                Index = streamInfo.Index
 2677            };
 678
 2679            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
 680            {
 2681                attachment.CodecTag = streamInfo.CodecTagString;
 682            }
 683
 2684            if (streamInfo.Tags is not null)
 685            {
 2686                attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
 2687                attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
 2688                attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 689            }
 690
 2691            return attachment;
 692        }
 693
 694        /// <summary>
 695        /// Converts ffprobe stream info to our MediaStream class.
 696        /// </summary>
 697        /// <param name="isAudio">if set to <c>true</c> [is info].</param>
 698        /// <param name="streamInfo">The stream info.</param>
 699        /// <param name="formatInfo">The format info.</param>
 700        /// <param name="frameInfoList">The frame info.</param>
 701        /// <returns>MediaStream.</returns>
 702        private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo, IReadOn
 703        {
 40704            var stream = new MediaStream
 40705            {
 40706                Codec = streamInfo.CodecName,
 40707                Profile = streamInfo.Profile,
 40708                Width = streamInfo.Width,
 40709                Height = streamInfo.Height,
 40710                Level = streamInfo.Level,
 40711                Index = streamInfo.Index,
 40712                PixelFormat = streamInfo.PixelFormat,
 40713                NalLengthSize = streamInfo.NalLengthSize,
 40714                TimeBase = streamInfo.TimeBase,
 40715                CodecTimeBase = streamInfo.CodecTimeBase
 40716            };
 717
 718            // Filter out junk
 40719            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", Stri
 720            {
 15721                stream.CodecTag = streamInfo.CodecTagString;
 722            }
 723
 40724            if (streamInfo.Tags is not null)
 725            {
 34726                stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
 34727                stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 34728                stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
 729            }
 730
 40731            if (streamInfo.CodecType == CodecType.Audio)
 732            {
 17733                stream.Type = MediaStreamType.Audio;
 17734                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 17735                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 17736                stream.LocalizedOriginal = _localization.GetLocalizedString("Original");
 17737                if (!string.IsNullOrEmpty(stream.Language))
 738                {
 14739                    stream.LocalizedLanguage = _localization.GetLanguageDisplayName(stream.Language);
 740                }
 741
 17742                stream.Channels = streamInfo.Channels;
 743
 17744                if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
 745                {
 17746                    stream.SampleRate = sampleRate;
 747                }
 748
 17749                stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
 750
 17751                if (streamInfo.BitsPerSample > 0)
 752                {
 0753                    stream.BitDepth = streamInfo.BitsPerSample;
 754                }
 17755                else if (streamInfo.BitsPerRawSample > 0)
 756                {
 3757                    stream.BitDepth = streamInfo.BitsPerRawSample;
 758                }
 759
 17760                if (string.IsNullOrEmpty(stream.Title))
 761                {
 762                    // FFprobe exposes MP4 track names via the name tag rather than title
 17763                    stream.Title = GetDictionaryValue(streamInfo.Tags, "name");
 764
 17765                    if (string.IsNullOrEmpty(stream.Title))
 766                    {
 767                        // fall back to handler_name if populated and not the default "SoundHandler"
 16768                        string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 16769                        if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComp
 770                        {
 3771                            stream.Title = handlerName;
 772                        }
 773                    }
 774                }
 775            }
 23776            else if (streamInfo.CodecType == CodecType.Subtitle)
 777            {
 4778                stream.Type = MediaStreamType.Subtitle;
 4779                stream.Codec = NormalizeSubtitleCodec(stream.Codec);
 4780                stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
 4781                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 4782                stream.LocalizedForced = _localization.GetLocalizedString("Forced");
 4783                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 4784                stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
 4785                if (!string.IsNullOrEmpty(stream.Language))
 786                {
 4787                    stream.LocalizedLanguage = _localization.GetLanguageDisplayName(stream.Language);
 788                }
 789
 4790                if (string.IsNullOrEmpty(stream.Title))
 791                {
 792                    // FFprobe exposes MP4 track names via the name tag rather than title
 4793                    stream.Title = GetDictionaryValue(streamInfo.Tags, "name");
 794
 4795                    if (string.IsNullOrEmpty(stream.Title))
 796                    {
 797                        // fall back to handler_name if populated and not the default "SubtitleHandler"
 3798                        string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 3799                        if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringC
 800                        {
 1801                            stream.Title = handlerName;
 802                        }
 803                    }
 804                }
 805            }
 19806            else if (streamInfo.CodecType == CodecType.Video)
 807            {
 19808                stream.IsAVC = streamInfo.IsAvc;
 19809                stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
 19810                stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
 811
 19812                stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
 19813                    && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
 814
 19815                if (isAudio
 19816                    || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
 19817                    || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
 19818                    || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
 19819                    || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
 820                {
 2821                    stream.Type = MediaStreamType.EmbeddedImage;
 822                }
 17823                else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 824                {
 825                    // How to differentiate between video and embedded image?
 826                    // The only difference I've seen thus far is presence of codec tag, also embedded images have high (
 1827                    if (!string.IsNullOrWhiteSpace(stream.CodecTag))
 828                    {
 0829                        stream.Type = MediaStreamType.Video;
 830                    }
 831                    else
 832                    {
 1833                        stream.Type = MediaStreamType.EmbeddedImage;
 834                    }
 835                }
 836                else
 837                {
 16838                    stream.Type = MediaStreamType.Video;
 839                }
 840
 19841                stream.AspectRatio = GetAspectRatio(streamInfo);
 842
 19843                if (streamInfo.BitsPerSample > 0)
 844                {
 0845                    stream.BitDepth = streamInfo.BitsPerSample;
 846                }
 19847                else if (streamInfo.BitsPerRawSample > 0)
 848                {
 14849                    stream.BitDepth = streamInfo.BitsPerRawSample;
 850                }
 851
 19852                if (!stream.BitDepth.HasValue)
 853                {
 5854                    if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
 855                    {
 5856                        if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
 5857                            || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
 858                        {
 5859                            stream.BitDepth = 8;
 860                        }
 0861                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase
 0862                                 || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreC
 863                        {
 0864                            stream.BitDepth = 10;
 865                        }
 0866                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase
 0867                                 || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreC
 868                        {
 0869                            stream.BitDepth = 12;
 870                        }
 871                    }
 872                }
 873
 874                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 19875                if (string.IsNullOrEmpty(streamInfo.SampleAspectRatio)
 19876                    && string.IsNullOrEmpty(streamInfo.DisplayAspectRatio))
 877                {
 6878                    stream.IsAnamorphic = false;
 879                }
 13880                else if (IsNearSquarePixelSar(streamInfo.SampleAspectRatio))
 881                {
 10882                    stream.IsAnamorphic = false;
 883                }
 3884                else if (!string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.Ordinal))
 885                {
 1886                    stream.IsAnamorphic = true;
 887                }
 2888                else if (string.Equals(streamInfo.DisplayAspectRatio, "0:1", StringComparison.Ordinal))
 889                {
 2890                    stream.IsAnamorphic = false;
 891                }
 0892                else if (!string.Equals(
 0893                             streamInfo.DisplayAspectRatio,
 0894                             // Force GetAspectRatio() to derive ratio from Width/Height directly by using null DAR
 0895                             GetAspectRatio(new MediaStreamInfo
 0896                             {
 0897                                 Width = streamInfo.Width,
 0898                                 Height = streamInfo.Height,
 0899                                 DisplayAspectRatio = null
 0900                             }),
 0901                             StringComparison.Ordinal))
 902                {
 0903                    stream.IsAnamorphic = true;
 904                }
 905                else
 906                {
 0907                    stream.IsAnamorphic = false;
 908                }
 909
 19910                if (streamInfo.Refs > 0)
 911                {
 16912                    stream.RefFrames = streamInfo.Refs;
 913                }
 914
 19915                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 916                {
 5917                    stream.ColorRange = streamInfo.ColorRange;
 918                }
 919
 19920                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 921                {
 5922                    stream.ColorSpace = streamInfo.ColorSpace;
 923                }
 924
 19925                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 926                {
 2927                    stream.ColorTransfer = streamInfo.ColorTransfer;
 928                }
 929
 19930                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 931                {
 2932                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 933                }
 934
 19935                if (streamInfo.SideDataList is not null)
 936                {
 6937                    foreach (var data in streamInfo.SideDataList)
 938                    {
 939                        // Parse Dolby Vision metadata from side_data
 2940                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 941                        {
 1942                            stream.DvVersionMajor = data.DvVersionMajor;
 1943                            stream.DvVersionMinor = data.DvVersionMinor;
 1944                            stream.DvProfile = data.DvProfile;
 1945                            stream.DvLevel = data.DvLevel;
 1946                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1947                            stream.ElPresentFlag = data.ElPresentFlag;
 1948                            stream.BlPresentFlag = data.BlPresentFlag;
 1949                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 950                        }
 951
 952                        // Parse video rotation metadata from side_data
 1953                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 954                        {
 1955                            stream.Rotation = data.Rotation;
 956                        }
 957
 958                        // Parse video frame cropping metadata from side_data
 959                        // TODO: save them and make HW filters to apply them in HWA pipelines
 0960                        else if (string.Equals(data.SideDataType, "Frame Cropping", StringComparison.OrdinalIgnoreCase))
 961                        {
 962                            // Streams containing artificially added frame cropping
 963                            // metadata should not be marked as anamorphic.
 0964                            stream.IsAnamorphic = false;
 965                        }
 966                    }
 967                }
 968
 19969                var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
 19970                if (frameInfo?.SideDataList is not null
 19971                    && frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE20
 972                {
 0973                    stream.Hdr10PlusPresentFlag = true;
 974                }
 975            }
 0976            else if (streamInfo.CodecType == CodecType.Data)
 977            {
 0978                stream.Type = MediaStreamType.Data;
 979            }
 980            else
 981            {
 0982                return null;
 983            }
 984
 985            // Get stream bitrate
 40986            var bitrate = 0;
 987
 40988            if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
 989            {
 18990                bitrate = value;
 991            }
 992
 993            // The bitrate info of FLAC audio is included in formatInfo.
 994            // Don't do this for video streams: formatInfo.BitRate is the overall container
 995            // bitrate (video + audio + subtitles + overhead), not the video bitrate.
 40996            if (bitrate == 0
 40997                && formatInfo is not null
 40998                && isAudio && stream.Type == MediaStreamType.Audio)
 999            {
 1000                // If the stream info doesn't have a bitrate get the value from the media format info
 21001                if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
 1002                {
 21003                    bitrate = value;
 1004                }
 1005            }
 1006
 401007            if (bitrate > 0)
 1008            {
 201009                stream.BitRate = bitrate;
 1010            }
 1011
 1012            // Extract bitrate info from tag "BPS" if possible.
 401013            if (!stream.BitRate.HasValue
 401014                && (streamInfo.CodecType == CodecType.Audio
 401015                    || streamInfo.CodecType == CodecType.Video))
 1016            {
 191017                var bps = GetBPSFromTags(streamInfo);
 191018                if (bps > 0)
 1019                {
 21020                    stream.BitRate = bps;
 1021                }
 1022                else
 1023                {
 1024                    // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
 171025                    var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
 171026                    var bytes = GetNumberOfBytesFromTags(streamInfo);
 171027                    if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
 1028                    {
 11029                        bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
 11030                        if (bps > 0)
 1031                        {
 11032                            stream.BitRate = bps;
 1033                        }
 1034                    }
 1035                }
 1036            }
 1037
 401038            var disposition = streamInfo.Disposition;
 401039            if (disposition is not null)
 1040            {
 401041                if (disposition.GetValueOrDefault("default") == 1)
 1042                {
 241043                    stream.IsDefault = true;
 1044                }
 1045
 401046                if (disposition.GetValueOrDefault("forced") == 1)
 1047                {
 01048                    stream.IsForced = true;
 1049                }
 1050
 401051                if (disposition.GetValueOrDefault("hearing_impaired") == 1)
 1052                {
 11053                    stream.IsHearingImpaired = true;
 1054                }
 1055
 401056                if (disposition.GetValueOrDefault("original") == 1)
 1057                {
 11058                    stream.IsOriginal = true;
 1059                }
 1060            }
 1061
 401062            NormalizeStreamTitle(stream);
 1063
 401064            return stream;
 1065        }
 1066
 1067        private static void NormalizeStreamTitle(MediaStream stream)
 1068        {
 401069            if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
 401070                || stream.Type == MediaStreamType.EmbeddedImage)
 1071            {
 31072                stream.Title = null;
 1073            }
 401074        }
 1075
 1076        /// <summary>
 1077        /// Gets a string from an FFProbeResult tags dictionary.
 1078        /// </summary>
 1079        /// <param name="tags">The tags.</param>
 1080        /// <param name="key">The key.</param>
 1081        /// <returns>System.String.</returns>
 1082        private static string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
 1083        {
 2331084            if (tags is null)
 1085            {
 61086                return null;
 1087            }
 1088
 2271089            tags.TryGetValue(key, out var val);
 1090
 2271091            return val;
 1092        }
 1093
 1094        private static string ParseChannelLayout(string input)
 1095        {
 171096            if (string.IsNullOrEmpty(input))
 1097            {
 21098                return null;
 1099            }
 1100
 151101            return input.AsSpan().LeftPart('(').ToString();
 1102        }
 1103
 1104        private static string GetAspectRatio(MediaStreamInfo info)
 1105        {
 191106            var original = info.DisplayAspectRatio;
 1107
 191108            var parts = (original ?? string.Empty).Split(':');
 191109            if (!(parts.Length == 2
 191110                    && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
 191111                    && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
 191112                    && width > 0
 191113                    && height > 0))
 1114            {
 1115                // Live TV and other early probes can report neither a usable display aspect ratio nor the frame size
 81116                if (info.Width is not > 0 || info.Height is not > 0)
 1117                {
 21118                    return original;
 1119                }
 1120
 61121                width = info.Width.Value;
 61122                height = info.Height.Value;
 1123            }
 1124
 171125            if (width > 0 && height > 0)
 1126            {
 171127                double ratio = width;
 171128                ratio /= height;
 1129
 171130                if (IsClose(ratio, 1.777777778, .03))
 1131                {
 111132                    return "16:9";
 1133                }
 1134
 61135                if (IsClose(ratio, 1.3333333333, .05))
 1136                {
 11137                    return "4:3";
 1138                }
 1139
 51140                if (IsClose(ratio, 1.41))
 1141                {
 01142                    return "1.41:1";
 1143                }
 1144
 51145                if (IsClose(ratio, 1.5))
 1146                {
 21147                    return "1.5:1";
 1148                }
 1149
 31150                if (IsClose(ratio, 1.6))
 1151                {
 01152                    return "1.6:1";
 1153                }
 1154
 31155                if (IsClose(ratio, 1.66666666667))
 1156                {
 01157                    return "5:3";
 1158                }
 1159
 31160                if (IsClose(ratio, 1.85, .02))
 1161                {
 01162                    return "1.85:1";
 1163                }
 1164
 31165                if (IsClose(ratio, 2.35, .025))
 1166                {
 01167                    return "2.35:1";
 1168                }
 1169
 31170                if (IsClose(ratio, 2.4, .025))
 1171                {
 11172                    return "2.40:1";
 1173                }
 1174            }
 1175
 21176            return original;
 1177        }
 1178
 1179        private static bool IsClose(double d1, double d2, double variance = .005)
 1180        {
 721181            return Math.Abs(d1 - d2) <= variance;
 1182        }
 1183
 1184        /// <summary>
 1185        /// Determines whether a sample aspect ratio represents square (or near-square) pixels.
 1186        /// Some encoders produce SARs like 3201:3200 for content that is effectively 1:1,
 1187        /// which would be falsely classified as anamorphic by an exact string comparison.
 1188        /// A 1% tolerance safely covers encoder rounding artifacts while preserving detection
 1189        /// of genuine anamorphic content (closest standard is PAL 4:3 at 16:15 = 6.67% off).
 1190        /// </summary>
 1191        /// <param name="sar">The sample aspect ratio string in "N:D" format.</param>
 1192        /// <returns><c>true</c> if the SAR is within 1% of 1:1; otherwise <c>false</c>.</returns>
 1193        internal static bool IsNearSquarePixelSar(string sar)
 1194        {
 261195            if (string.IsNullOrEmpty(sar))
 1196            {
 21197                return false;
 1198            }
 1199
 241200            var parts = sar.Split(':');
 241201            if (parts.Length == 2
 241202                && double.TryParse(parts[0], CultureInfo.InvariantCulture, out var num)
 241203                && double.TryParse(parts[1], CultureInfo.InvariantCulture, out var den)
 241204                && den > 0)
 1205            {
 241206                return IsClose(num / den, 1.0, 0.01);
 1207            }
 1208
 01209            return string.Equals(sar, "1:1", StringComparison.Ordinal);
 1210        }
 1211
 1212        /// <summary>
 1213        /// Gets a frame rate from a string value in ffprobe output
 1214        /// This could be a number or in the format of 2997/125.
 1215        /// </summary>
 1216        /// <param name="value">The value.</param>
 1217        /// <returns>System.Nullable{System.Single}.</returns>
 1218        internal static float? GetFrameRate(ReadOnlySpan<char> value)
 1219        {
 471220            if (value.IsEmpty)
 1221            {
 01222                return null;
 1223            }
 1224
 471225            int index = value.IndexOf('/');
 471226            if (index == -1)
 1227            {
 01228                return null;
 1229            }
 1230
 471231            if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
 471232                || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var div
 1233            {
 01234                return null;
 1235            }
 1236
 471237            return divisor == 0f ? null : dividend / divisor;
 1238        }
 1239
 1240        private static void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
 1241        {
 1242            // Get the first info stream
 21243            var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
 21244            if (stream is null)
 1245            {
 01246                return;
 1247            }
 1248
 1249            // Get duration from stream properties
 21250            var duration = stream.Duration;
 1251
 1252            // If it's not there go into format properties
 21253            if (string.IsNullOrEmpty(duration))
 1254            {
 01255                duration = result.Format.Duration;
 1256            }
 1257
 1258            // If we got something, parse it
 21259            if (!string.IsNullOrEmpty(duration))
 1260            {
 21261                data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
 1262            }
 21263        }
 1264
 1265        private static int? GetBPSFromTags(MediaStreamInfo streamInfo)
 1266        {
 191267            if (streamInfo?.Tags is null)
 1268            {
 31269                return null;
 1270            }
 1271
 161272            var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
 161273            if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
 1274            {
 31275                return parsedBps;
 1276            }
 1277
 131278            return null;
 1279        }
 1280
 1281        private static double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
 1282        {
 171283            if (streamInfo?.Tags is null)
 1284            {
 31285                return null;
 1286            }
 1287
 141288            var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "D
 141289            if (!string.IsNullOrEmpty(duration))
 1290            {
 1291                // Matroska DURATION tags use nanosecond precision (e.g. "00:00:05.023000000"), but
 1292                // TimeSpan only supports up to 7 fractional digits (ticks). Trim the surplus digits so
 1293                // these durations parse instead of being silently dropped.
 31294                duration = DurationOverPrecisionRegex().Replace(duration, "$1");
 31295                if (TimeSpan.TryParse(duration, CultureInfo.InvariantCulture, out var parsedDuration))
 1296                {
 31297                    return parsedDuration.TotalSeconds;
 1298                }
 1299            }
 1300
 111301            return null;
 1302        }
 1303
 1304        private static long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
 1305        {
 171306            if (streamInfo?.Tags is null)
 1307            {
 31308                return null;
 1309            }
 1310
 141311            var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
 141312                                ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
 141313            if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
 1314            {
 21315                return parsedBytes;
 1316            }
 1317
 121318            return null;
 1319        }
 1320
 1321        private static void SetSize(InternalMediaInfoResult data, MediaInfo info)
 1322        {
 181323            if (data.Format is null)
 1324            {
 11325                return;
 1326            }
 1327
 171328            info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.Invaria
 171329        }
 1330
 1331        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
 1332        {
 21333            var people = new List<BaseItemPerson>();
 21334            if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
 1335            {
 121336                foreach (var person in Split(composer, false))
 1337                {
 41338                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
 1339                }
 1340            }
 1341
 21342            if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
 1343            {
 01344                foreach (var person in Split(conductor, false))
 1345                {
 01346                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
 1347                }
 1348            }
 1349
 21350            if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
 1351            {
 81352                foreach (var person in Split(lyricist, false))
 1353                {
 21354                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
 1355                }
 1356            }
 1357
 21358            if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
 1359            {
 501360                foreach (var person in Split(performer, false))
 1361                {
 231362                    Match match = PerformerRegex().Match(person);
 1363
 1364                    // If the performer doesn't have any instrument/role associated, it won't match. In that case, chanc
 231365                    if (match.Success)
 1366                    {
 221367                        people.Add(new BaseItemPerson
 221368                        {
 221369                            Name = match.Groups["name"].Value,
 221370                            Type = PersonKind.Actor,
 221371                            Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
 221372                        });
 1373                    }
 1374                }
 1375            }
 1376
 1377            // In cases where there isn't sufficient information as to which role a writer performed on a recording, tag
 21378            if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
 1379            {
 01380                foreach (var person in Split(writer, false))
 1381                {
 01382                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
 1383                }
 1384            }
 1385
 21386            if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
 1387            {
 121388                foreach (var person in Split(arranger, false))
 1389                {
 41390                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
 1391                }
 1392            }
 1393
 21394            if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
 1395            {
 01396                foreach (var person in Split(engineer, false))
 1397                {
 01398                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
 1399                }
 1400            }
 1401
 21402            if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
 1403            {
 81404                foreach (var person in Split(mixer, false))
 1405                {
 21406                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
 1407                }
 1408            }
 1409
 21410            if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
 1411            {
 01412                foreach (var person in Split(remixer, false))
 1413                {
 01414                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
 1415                }
 1416            }
 1417
 21418            audio.People = people.ToArray();
 1419
 1420            // Set album artist
 21421            var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
 21422            audio.AlbumArtists = albumArtist is not null
 21423                ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
 21424                : Array.Empty<string>();
 1425
 1426            // Set album artist to artist if empty
 21427            if (audio.AlbumArtists.Length == 0)
 1428            {
 01429                audio.AlbumArtists = audio.Artists;
 1430            }
 1431
 1432            // Track number
 21433            audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
 1434
 1435            // Disc number
 21436            audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
 1437
 1438            // There's several values in tags may or may not be present
 21439            FetchStudios(audio, tags, "organization");
 21440            FetchStudios(audio, tags, "ensemble");
 21441            FetchStudios(audio, tags, "publisher");
 21442            FetchStudios(audio, tags, "label");
 1443
 1444            // These support multiple values, but for now we only store the first.
 21445            var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
 21446                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
 21447            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
 1448
 21449            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
 21450                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
 21451            audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
 1452
 21453            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
 21454                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
 21455            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
 1456
 21457            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
 21458                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
 21459            audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
 1460
 21461            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
 21462                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
 21463            audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
 21464        }
 1465
 1466        private static string GetMultipleMusicBrainzId(string value)
 1467        {
 201468            if (string.IsNullOrWhiteSpace(value))
 1469            {
 101470                return null;
 1471            }
 1472
 101473            return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
 101474                .FirstOrDefault();
 1475        }
 1476
 1477        /// <summary>
 1478        /// Splits the specified val.
 1479        /// </summary>
 1480        /// <param name="val">The val.</param>
 1481        /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
 1482        /// <returns>System.String[][].</returns>
 1483        private string[] Split(string val, bool allowCommaDelimiter)
 1484        {
 1485            // Only use the comma as a delimiter if there are no slashes or pipes.
 1486            // We want to be careful not to split names that have commas in them
 141487            return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
 141488                val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
 141489                val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1490        }
 1491
 1492        private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
 1493        {
 51494            if (splitFeaturing)
 1495            {
 31496                val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
 31497                    .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
 1498            }
 1499
 51500            var artistsFound = new List<string>();
 1501
 3101502            foreach (var whitelistArtist in SplitWhitelist)
 1503            {
 1501504                var originalVal = val;
 1501505                val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
 1506
 1501507                if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
 1508                {
 01509                    artistsFound.Add(whitelistArtist);
 1510                }
 1511            }
 1512
 51513            var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1514
 51515            artistsFound.AddRange(artists);
 51516            return artistsFound.DistinctNames();
 1517        }
 1518
 1519        /// <summary>
 1520        /// Gets the studios from the tags collection.
 1521        /// </summary>
 1522        /// <param name="info">The info.</param>
 1523        /// <param name="tags">The tags.</param>
 1524        /// <param name="tagName">Name of the tag.</param>
 1525        private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
 1526        {
 241527            var val = tags.GetValueOrDefault(tagName);
 1528
 241529            if (string.IsNullOrEmpty(val))
 1530            {
 221531                return;
 1532            }
 1533
 21534            var studios = Split(val, true);
 21535            var studioList = new List<string>();
 1536
 81537            foreach (var studio in studios)
 1538            {
 21539                if (string.IsNullOrWhiteSpace(studio))
 1540                {
 1541                    continue;
 1542                }
 1543
 1544                // Don't add artist/album artist name to studios, even if it's listed there
 21545                if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
 21546                    || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
 1547                {
 1548                    continue;
 1549                }
 1550
 21551                studioList.Add(studio);
 1552            }
 1553
 21554            info.Studios = studioList
 21555                .Distinct(StringComparer.OrdinalIgnoreCase)
 21556                .ToArray();
 21557        }
 1558
 1559        /// <summary>
 1560        /// Gets the genres from the tags collection.
 1561        /// </summary>
 1562        /// <param name="info">The information.</param>
 1563        /// <param name="tags">The tags.</param>
 1564        private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
 1565        {
 181566            var genreVal = tags.GetValueOrDefault("genre");
 181567            if (string.IsNullOrEmpty(genreVal))
 1568            {
 161569                return;
 1570            }
 1571
 21572            var genres = new List<string>(info.Genres);
 201573            foreach (var genre in Split(genreVal, true))
 1574            {
 81575                if (string.IsNullOrEmpty(genre))
 1576                {
 1577                    continue;
 1578                }
 1579
 81580                genres.Add(genre);
 1581            }
 1582
 21583            info.Genres = genres
 21584                .Distinct(StringComparer.OrdinalIgnoreCase)
 21585                .ToArray();
 21586        }
 1587
 1588        /// <summary>
 1589        /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
 1590        /// </summary>
 1591        /// <param name="tags">The tags.</param>
 1592        /// <param name="tagName">Name of the tag.</param>
 1593        /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
 1594        private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
 1595        {
 41596            var disc = tags.GetValueOrDefault(tagName);
 1597
 41598            if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
 1599            {
 41600                return discNum;
 1601            }
 1602
 01603            return null;
 1604        }
 1605
 1606        private static ChapterInfo GetChapterInfo(MediaChapter chapter)
 1607        {
 01608            var info = new ChapterInfo();
 1609
 01610            if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
 1611            {
 01612                info.Name = name;
 1613            }
 1614
 1615            // Limit accuracy to milliseconds to match xml saving
 01616            var secondsString = chapter.StartTime;
 1617
 01618            if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
 1619            {
 01620                var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
 01621                info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
 1622            }
 1623
 01624            return info;
 1625        }
 1626
 1627        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
 1628        {
 161629            var tags = data.Format?.Tags;
 1630
 161631            if (tags is null)
 1632            {
 61633                return;
 1634            }
 1635
 101636            if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
 1637            {
 01638                var genreList = genres.Split(_genreDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOption
 1639
 1640                // If this is empty then don't overwrite genres that might have been fetched earlier
 01641                if (genreList.Length > 0)
 1642                {
 01643                    video.Genres = genreList;
 1644                }
 1645            }
 1646
 101647            if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRati
 1648            {
 01649                video.OfficialRating = officialRating;
 1650            }
 1651
 101652            if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
 1653            {
 01654                video.People = Array.ConvertAll(
 01655                    people.Split(_basicDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntrie
 01656                    i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
 1657            }
 1658
 101659            if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, Cul
 1660            {
 01661                video.ProductionYear = parsedYear;
 1662            }
 1663
 1664            // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1665            // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
 101666            if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(y
 1667            {
 01668                video.PremiereDate = parsedDate;
 1669            }
 1670
 101671            var description = tags.GetValueOrDefault("WM/SubTitleDescription");
 1672
 101673            var subTitle = tags.GetValueOrDefault("WM/SubTitle");
 1674
 1675            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1676
 1677            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, ex
 1678            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
 1679            // OR -> COMMENT. SUBTITLE: DESCRIPTION
 1680            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the 
 1681            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in t
 101682            if (string.IsNullOrWhiteSpace(subTitle)
 101683                && !string.IsNullOrWhiteSpace(description)
 101684                && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains
 1685            {
 01686                string[] descriptionParts = description.Split(':');
 01687                if (descriptionParts.Length > 0)
 1688                {
 01689                    string subtitle = descriptionParts[0];
 1690                    try
 1691                    {
 1692                        // Check if it contains a episode number and season number
 01693                        if (subtitle.Contains('/', StringComparison.Ordinal))
 1694                        {
 01695                            string[] subtitleParts = subtitle.Split(' ');
 01696                            string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Spl
 01697                            video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
 1698                            // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
 1699
 1700                            // Skip the numbers, concatenate the rest, trim and set as new description
 01701                            description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1702                        }
 01703                        else if (subtitle.Contains('.', StringComparison.Ordinal))
 1704                        {
 01705                            var subtitleParts = subtitle.Split('.');
 01706                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1707                        }
 1708                        else
 1709                        {
 01710                            description = subtitle.Trim();
 1711                        }
 01712                    }
 01713                    catch (Exception ex)
 1714                    {
 01715                        _logger.LogError(ex, "Error while parsing subtitle field");
 1716
 1717                        // Fallback to default parsing
 01718                        if (subtitle.Contains('.', StringComparison.Ordinal))
 1719                        {
 01720                            var subtitleParts = subtitle.Split('.');
 01721                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1722                        }
 1723                        else
 1724                        {
 01725                            description = subtitle.Trim();
 1726                        }
 01727                    }
 1728                }
 1729            }
 1730
 101731            if (!string.IsNullOrWhiteSpace(description))
 1732            {
 01733                video.Overview = description;
 1734            }
 101735        }
 1736
 1737        private void ExtractTimestamp(MediaInfo video)
 1738        {
 161739            if (video.VideoType != VideoType.VideoFile)
 1740            {
 01741                return;
 1742            }
 1743
 1744            // Skip timestamp extration for remote resource (http, rtsp, etc.)
 1745            // as they cannot be opened with FileStream
 161746            if (video.Protocol != MediaProtocol.File)
 1747            {
 21748                return;
 1749            }
 1750
 141751            if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
 141752                && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
 141753                && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
 1754            {
 131755                return;
 1756            }
 1757
 1758            try
 1759            {
 11760                video.Timestamp = GetMpegTimestamp(video.Path);
 01761                _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
 01762            }
 11763            catch (Exception ex)
 1764            {
 11765                video.Timestamp = null;
 11766                _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
 11767            }
 11768        }
 1769
 1770        // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
 1771        private static TransportStreamTimestamp GetMpegTimestamp(string path)
 1772        {
 11773            var packetBuffer = new byte[197];
 1774
 11775            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
 1776            {
 01777                fs.ReadExactly(packetBuffer);
 01778            }
 1779
 01780            if (packetBuffer[0] == 71)
 1781            {
 01782                return TransportStreamTimestamp.None;
 1783            }
 1784
 01785            if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
 1786            {
 01787                return TransportStreamTimestamp.None;
 1788            }
 1789
 01790            if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
 1791            {
 01792                return TransportStreamTimestamp.Zero;
 1793            }
 1794
 01795            return TransportStreamTimestamp.Valid;
 1796        }
 1797
 1798        [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
 1799        private static partial Regex PerformerRegex();
 1800
 1801        [GeneratedRegex(@"(\.\d{7})\d+")]
 1802        private static partial Regex DurationOverPrecisionRegex();
 1803    }
 1804}

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)