< Summary - Jellyfin

Information
Class: MediaBrowser.MediaEncoding.Probing.ProbeResultNormalizer
Assembly: MediaBrowser.MediaEncoding
File(s): /srv/git/jellyfin/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
Line coverage
79%
Covered lines: 589
Uncovered lines: 153
Coverable lines: 742
Total lines: 1713
Line coverage: 79.3%
Branch coverage
75%
Covered branches: 460
Total branches: 610
Branch coverage: 75.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_SplitWhitelist()100%22100%
GetMediaInfo(...)83.78%767492.94%
NormalizeFormat(...)85.71%141486.66%
GetEstimatedAudioBitrate(...)50%622662.5%
FetchFromItunesInfo(...)83.33%141276.92%
ReadFromDictNode(...)90%212087.09%
ReadValueArray(...)83.33%141277.77%
ProcessPairs(...)64.28%441446.66%
GetNameValuePair(...)92.85%141490.9%
NormalizeSubtitleCodec(...)62.5%10866.66%
GetMediaAttachment(...)90%1010100%
GetMediaStream(...)79.45%27914681.59%
NormalizeStreamTitle(...)100%44100%
GetDictionaryValue(...)100%22100%
ParseChannelLayout(...)100%22100%
GetAspectRatio(...)85.29%393483.87%
IsClose(...)100%11100%
GetFrameRate(...)60%141066.66%
SetAudioRuntimeTicks(...)62.5%9877.77%
GetBPSFromTags(...)75%8883.33%
GetRuntimeSecondsFromTags(...)75%8883.33%
GetNumberOfBytesFromTags(...)75%8885.71%
SetSize(...)75%44100%
SetAudioInfoFromTags(...)80%847085.93%
GetMultipleMusicBrainzId(...)100%22100%
Split(...)100%44100%
SplitDistinctArtists(...)83.33%6691.66%
FetchStudios(...)100%1010100%
FetchGenres(...)100%66100%
GetDictionaryTrackOrDiscNumber(...)50%2275%
GetChapterInfo(...)0%4260%
FetchWtvInfo(...)50%5654233.33%
ExtractTimestamp(...)87.5%9878.57%
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
 2133        private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
 2134        private readonly string[] _webmVideoCodecs = { "av1", "vp8", "vp9" };
 2135        private readonly string[] _webmAudioCodecs = { "opus", "vorbis" };
 36
 37        private readonly ILogger _logger;
 38        private readonly ILocalizationManager _localization;
 39
 40        private string[] _splitWhiteList;
 41
 42        /// <summary>
 43        /// Initializes a new instance of the <see cref="ProbeResultNormalizer"/> class.
 44        /// </summary>
 45        /// <param name="logger">The <see cref="ILogger{ProbeResultNormalizer}"/> for use with the <see cref="ProbeResul
 46        /// <param name="localization">The <see cref="ILocalizationManager"/> for use with the <see cref="ProbeResultNor
 47        public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
 48        {
 2149            _logger = logger;
 2150            _localization = localization;
 2151        }
 52
 553        private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
 554        {
 555            "AC/DC",
 556            "A/T/O/S",
 557            "As/Hi Soundworks",
 558            "Au/Ra",
 559            "Bremer/McCoy",
 560            "b/bqスタヂオ",
 561            "DOV/S",
 562            "DJ'TEKINA//SOMETHING",
 563            "IX/ON",
 564            "J-CORE SLi//CER",
 565            "M(a/u)SH",
 566            "Kaoru/Brilliance",
 567            "signum/ii",
 568            "Richiter(LORB/DUGEM DI BARAT)",
 569            "이달의 소녀 1/3",
 570            "R!N / Gemie",
 571            "LOONA 1/3",
 572            "LOONA / yyxy",
 573            "LOONA / ODD EYE CIRCLE",
 574            "K/DA",
 575            "22/7",
 576            "諭吉佳作/men",
 577            "//dARTH nULL",
 578            "Phantom/Ghost",
 579            "She/Her/Hers",
 580            "5/8erl in Ehr'n",
 581            "Smith/Kotzen",
 582            "We;Na",
 583            "LSR/CITY",
 584        };
 85
 86        /// <summary>
 87        /// Transforms a FFprobe response into its <see cref="MediaInfo"/> equivalent.
 88        /// </summary>
 89        /// <param name="data">The <see cref="InternalMediaInfoResult"/>.</param>
 90        /// <param name="videoType">The <see cref="VideoType"/>.</param>
 91        /// <param name="isAudio">A boolean indicating whether the media is audio.</param>
 92        /// <param name="path">Path to media file.</param>
 93        /// <param name="protocol">Path media protocol.</param>
 94        /// <returns>The <see cref="MediaInfo"/>.</returns>
 95        public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, Med
 96        {
 1197            var info = new MediaInfo
 1198            {
 1199                Path = path,
 11100                Protocol = protocol,
 11101                VideoType = videoType
 11102            };
 103
 11104            FFProbeHelpers.NormalizeFFProbeResult(data);
 11105            SetSize(data, info);
 106
 11107            var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
 11108            var internalFrames = data.Frames ?? Array.Empty<MediaFrameInfo>();
 109
 11110            info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format, internalFrames))
 11111                .Where(i => i is not null)
 11112                // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know
 11113                .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
 11114                .ToList();
 115
 11116            info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
 11117                .Where(i => i is not null)
 11118                .ToList();
 119
 11120            if (data.Format is not null)
 121            {
 10122                info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
 123
 10124                if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
 125                {
 10126                    info.Bitrate = value;
 127                }
 128            }
 129
 11130            var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 11131            var tagStreamType = isAudio ? CodecType.Audio : CodecType.Video;
 132
 11133            var tagStream = data.Streams?.FirstOrDefault(i => i.CodecType == tagStreamType);
 134
 11135            if (tagStream?.Tags is not null)
 136            {
 70137                foreach (var (key, value) in tagStream.Tags)
 138                {
 27139                    tags[key] = value;
 140                }
 141            }
 142
 11143            if (data.Format?.Tags is not null)
 144            {
 274145                foreach (var (key, value) in data.Format.Tags)
 146                {
 129147                    tags[key] = value;
 148                }
 149            }
 150
 11151            FetchGenres(info, tags);
 152
 11153            info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
 11154            info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
 11155            info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc");
 156
 11157            info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort");
 11158            info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
 11159            info.ShowName = tags.GetValueOrDefault("show_name");
 11160            info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
 161
 162            // Several different forms of retail/premiere date
 11163            info.PremiereDate =
 11164                FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
 11165                FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
 11166                FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
 11167                FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
 11168                FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
 11169                FFProbeHelpers.GetDictionaryDateTime(tags, "date") ??
 11170                FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time");
 171
 172            // Set common metadata for music (audio) and music videos (video)
 11173            info.Album = tags.GetValueOrDefault("album");
 174
 11175            if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
 176            {
 2177                info.Artists = SplitDistinctArtists(artists, new[] { '/', ';' }, false).ToArray();
 178            }
 179            else
 180            {
 9181                var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
 9182                info.Artists = artist is null
 9183                    ? Array.Empty<string>()
 9184                    : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
 185            }
 186
 187            // Guess ProductionYear from PremiereDate if missing
 11188            if (!info.ProductionYear.HasValue && info.PremiereDate.HasValue)
 189            {
 5190                info.ProductionYear = info.PremiereDate.Value.Year;
 191            }
 192
 193            // Set mediaType-specific metadata
 11194            if (isAudio)
 195            {
 2196                SetAudioRuntimeTicks(data, info);
 197
 198                // tags are normally located under data.format, but we've seen some cases with ogg where they're part of
 199                // so let's create a combined list of both
 200
 2201                SetAudioInfoFromTags(info, tags);
 202            }
 203            else
 204            {
 9205                FetchStudios(info, tags, "copyright");
 206
 9207                var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
 9208                if (iTunExtc is not null)
 209                {
 0210                    var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
 211                    // Example
 212                    // mpaa|G|100|For crude humor
 0213                    if (parts.Length > 1)
 214                    {
 0215                        info.OfficialRating = parts[1];
 216
 0217                        if (parts.Length > 3)
 218                        {
 0219                            info.OfficialRatingDescription = parts[3];
 220                        }
 221                    }
 222                }
 223
 9224                var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
 9225                if (iTunXml is not null)
 226                {
 1227                    FetchFromItunesInfo(iTunXml, info);
 228                }
 229
 9230                if (data.Format is not null && !string.IsNullOrEmpty(data.Format.Duration))
 231                {
 8232                    info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCul
 233                }
 234
 9235                FetchWtvInfo(info, data);
 236
 9237                if (data.Chapters is not null)
 238                {
 3239                    info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
 240                }
 241
 9242                ExtractTimestamp(info);
 243
 9244                if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", Strin
 245                {
 0246                    info.Video3DFormat = Video3DFormat.FullSideBySide;
 247                }
 248
 62249                foreach (var mediaStream in info.MediaStreams)
 250                {
 22251                    if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
 252                    {
 3253                        mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Channels);
 254                    }
 255                }
 256
 9257                var videoStreamsBitrate = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).Select(i => i.Bi
 258                // If ffprobe reported the container bitrate as being the same as the video stream bitrate, then it's wr
 9259                if (videoStreamsBitrate == (info.Bitrate ?? 0))
 260                {
 5261                    info.InferTotalBitrate(true);
 262                }
 263            }
 264
 11265            return info;
 266        }
 267
 268        private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
 269        {
 10270            if (string.IsNullOrWhiteSpace(format))
 271            {
 0272                return null;
 273            }
 274
 275            // Input can be a list of multiple, comma-delimited formats - each of them needs to be checked
 10276            var splitFormat = format.Split(',');
 78277            for (var i = 0; i < splitFormat.Length; i++)
 278            {
 279                // Handle MPEG-1 container
 29280                if (string.Equals(splitFormat[i], "mpegvideo", StringComparison.OrdinalIgnoreCase))
 281                {
 0282                    splitFormat[i] = "mpeg";
 283                }
 284
 285                // Handle MPEG-TS container
 29286                else if (string.Equals(splitFormat[i], "mpegts", StringComparison.OrdinalIgnoreCase))
 287                {
 1288                    splitFormat[i] = "ts";
 289                }
 290
 291                // Handle matroska container
 28292                else if (string.Equals(splitFormat[i], "matroska", StringComparison.OrdinalIgnoreCase))
 293                {
 4294                    splitFormat[i] = "mkv";
 295                }
 296
 297                // Handle WebM
 24298                else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
 299                {
 300                    // Limit WebM to supported codecs
 4301                    if (mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contains(s
 4302                        || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringCompa
 303                    {
 3304                        splitFormat[i] = string.Empty;
 305                    }
 306                }
 307            }
 308
 10309            return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
 310        }
 311
 312        private int? GetEstimatedAudioBitrate(string codec, int? channels)
 313        {
 3314            if (!channels.HasValue)
 315            {
 0316                return null;
 317            }
 318
 3319            var channelsValue = channels.Value;
 320
 3321            if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase)
 3322                || string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
 323            {
 324                switch (channelsValue)
 325                {
 326                    case <= 2:
 1327                        return 192000;
 328                    case >= 5:
 0329                        return 320000;
 330                }
 331            }
 332
 2333            if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase)
 2334                || string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
 335            {
 336                switch (channelsValue)
 337                {
 338                    case <= 2:
 0339                        return 192000;
 340                    case >= 5:
 0341                        return 640000;
 342                }
 343            }
 344
 2345            if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase)
 2346                || string.Equals(codec, "alac", StringComparison.OrdinalIgnoreCase))
 347            {
 348                switch (channelsValue)
 349                {
 350                    case <= 2:
 0351                        return 960000;
 352                    case >= 5:
 0353                        return 2880000;
 354                }
 355            }
 356
 2357            return null;
 358        }
 359
 360        private void FetchFromItunesInfo(string xml, MediaInfo info)
 361        {
 362            // Make things simpler and strip out the dtd
 1363            var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
 364
 1365            if (plistIndex != -1)
 366            {
 1367                xml = xml.Substring(plistIndex);
 368            }
 369
 1370            xml = "<?xml version=\"1.0\"?>" + xml;
 371
 372            // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http
 1373            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
 1374            using (var streamReader = new StreamReader(stream))
 375            {
 376                try
 377                {
 1378                    using (var reader = XmlReader.Create(streamReader))
 379                    {
 1380                        reader.MoveToContent();
 1381                        reader.Read();
 382
 383                        // Loop through each element
 4384                        while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 385                        {
 3386                            if (reader.NodeType == XmlNodeType.Element)
 387                            {
 1388                                switch (reader.Name)
 389                                {
 390                                    case "dict":
 1391                                        if (reader.IsEmptyElement)
 392                                        {
 0393                                            reader.Read();
 0394                                            continue;
 395                                        }
 396
 1397                                        using (var subtree = reader.ReadSubtree())
 398                                        {
 1399                                            ReadFromDictNode(subtree, info);
 1400                                        }
 401
 402                                        break;
 403                                    default:
 0404                                        reader.Skip();
 0405                                        break;
 406                                }
 407                            }
 408                            else
 409                            {
 2410                                reader.Read();
 411                            }
 412                        }
 1413                    }
 1414                }
 0415                catch (XmlException)
 416                {
 417                    // I've seen probe examples where the iTunMOVI value is just "<"
 418                    // So we should not allow this to fail the entire probing operation
 0419                }
 420            }
 1421        }
 422
 423        private void ReadFromDictNode(XmlReader reader, MediaInfo info)
 424        {
 1425            string currentKey = null;
 1426            var pairs = new List<NameValuePair>();
 427
 1428            reader.MoveToContent();
 1429            reader.Read();
 430
 431            // Loop through each element
 19432            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 433            {
 18434                if (reader.NodeType == XmlNodeType.Element)
 435                {
 12436                    switch (reader.Name)
 437                    {
 438                        case "key":
 6439                            if (!string.IsNullOrWhiteSpace(currentKey))
 440                            {
 5441                                ProcessPairs(currentKey, pairs, info);
 442                            }
 443
 6444                            currentKey = reader.ReadElementContentAsString();
 6445                            pairs = new List<NameValuePair>();
 6446                            break;
 447                        case "string":
 1448                            var value = reader.ReadElementContentAsString();
 1449                            if (!string.IsNullOrWhiteSpace(value))
 450                            {
 1451                                pairs.Add(new NameValuePair
 1452                                {
 1453                                    Name = value,
 1454                                    Value = value
 1455                                });
 456                            }
 457
 1458                            break;
 459                        case "array":
 5460                            if (reader.IsEmptyElement)
 461                            {
 0462                                reader.Read();
 0463                                continue;
 464                            }
 465
 5466                            using (var subtree = reader.ReadSubtree())
 467                            {
 5468                                if (!string.IsNullOrWhiteSpace(currentKey))
 469                                {
 5470                                    pairs.AddRange(ReadValueArray(subtree));
 471                                }
 5472                            }
 473
 474                            break;
 475                        default:
 0476                            reader.Skip();
 0477                            break;
 478                    }
 479                }
 480                else
 481                {
 6482                    reader.Read();
 483                }
 484            }
 1485        }
 486
 487        private List<NameValuePair> ReadValueArray(XmlReader reader)
 488        {
 5489            var pairs = new List<NameValuePair>();
 490
 5491            reader.MoveToContent();
 5492            reader.Read();
 493
 494            // Loop through each element
 20495            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 496            {
 15497                if (reader.NodeType == XmlNodeType.Element)
 498                {
 5499                    switch (reader.Name)
 500                    {
 501                        case "dict":
 502
 5503                            if (reader.IsEmptyElement)
 504                            {
 0505                                reader.Read();
 0506                                continue;
 507                            }
 508
 5509                            using (var subtree = reader.ReadSubtree())
 510                            {
 5511                                var dict = GetNameValuePair(subtree);
 5512                                if (dict is not null)
 513                                {
 1514                                    pairs.Add(dict);
 515                                }
 5516                            }
 517
 518                            break;
 519                        default:
 0520                            reader.Skip();
 0521                            break;
 522                    }
 523                }
 524                else
 525                {
 10526                    reader.Read();
 527                }
 528            }
 529
 5530            return pairs;
 531        }
 532
 533        private void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
 534        {
 5535            List<BaseItemPerson> peoples = new List<BaseItemPerson>();
 5536            var distinctPairs = pairs.Select(p => p.Value)
 5537                    .Where(i => !string.IsNullOrWhiteSpace(i))
 5538                    .Trimmed()
 5539                    .Distinct(StringComparer.OrdinalIgnoreCase);
 540
 5541            if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
 542            {
 1543                info.Studios = distinctPairs.ToArray();
 544            }
 4545            else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
 546            {
 0547                foreach (var pair in distinctPairs)
 548                {
 0549                    peoples.Add(new BaseItemPerson
 0550                    {
 0551                        Name = pair,
 0552                        Type = PersonKind.Writer
 0553                    });
 554                }
 555            }
 4556            else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
 557            {
 2558                foreach (var pair in distinctPairs)
 559                {
 0560                    peoples.Add(new BaseItemPerson
 0561                    {
 0562                        Name = pair,
 0563                        Type = PersonKind.Producer
 0564                    });
 565                }
 566            }
 3567            else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
 568            {
 2569                foreach (var pair in distinctPairs)
 570                {
 0571                    peoples.Add(new BaseItemPerson
 0572                    {
 0573                        Name = pair,
 0574                        Type = PersonKind.Director
 0575                    });
 576                }
 577            }
 578
 5579            info.People = peoples.ToArray();
 5580        }
 581
 582        private NameValuePair GetNameValuePair(XmlReader reader)
 583        {
 5584            string name = null;
 5585            string value = null;
 586
 5587            reader.MoveToContent();
 5588            reader.Read();
 589
 590            // Loop through each element
 20591            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 592            {
 15593                if (reader.NodeType == XmlNodeType.Element)
 594                {
 10595                    switch (reader.Name)
 596                    {
 597                        case "key":
 5598                            name = reader.ReadNormalizedString();
 5599                            break;
 600                        case "string":
 5601                            value = reader.ReadNormalizedString();
 5602                            break;
 603                        default:
 0604                            reader.Skip();
 0605                            break;
 606                    }
 607                }
 608                else
 609                {
 5610                    reader.Read();
 611                }
 612            }
 613
 5614            if (string.IsNullOrEmpty(name)
 5615                || string.IsNullOrEmpty(value))
 616            {
 4617                return null;
 618            }
 619
 1620            return new NameValuePair
 1621            {
 1622                Name = name,
 1623                Value = value
 1624            };
 625        }
 626
 627        private string NormalizeSubtitleCodec(string codec)
 628        {
 3629            if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
 630            {
 0631                codec = "DVBSUB";
 632            }
 3633            else if (string.Equals(codec, "dvb_teletext", StringComparison.OrdinalIgnoreCase))
 634            {
 0635                codec = "DVBTXT";
 636            }
 3637            else if (string.Equals(codec, "dvd_subtitle", StringComparison.OrdinalIgnoreCase))
 638            {
 1639                codec = "DVDSUB"; // .sub+.idx
 640            }
 2641            else if (string.Equals(codec, "hdmv_pgs_subtitle", StringComparison.OrdinalIgnoreCase))
 642            {
 0643                codec = "PGSSUB"; // .sup
 644            }
 645
 3646            return codec;
 647        }
 648
 649        /// <summary>
 650        /// Converts ffprobe stream info to our MediaAttachment class.
 651        /// </summary>
 652        /// <param name="streamInfo">The stream info.</param>
 653        /// <returns>MediaAttachments.</returns>
 654        private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
 655        {
 26656            if (streamInfo.CodecType != CodecType.Attachment
 26657                && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
 658            {
 24659                return null;
 660            }
 661
 2662            var attachment = new MediaAttachment
 2663            {
 2664                Codec = streamInfo.CodecName,
 2665                Index = streamInfo.Index
 2666            };
 667
 2668            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
 669            {
 2670                attachment.CodecTag = streamInfo.CodecTagString;
 671            }
 672
 2673            if (streamInfo.Tags is not null)
 674            {
 2675                attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
 2676                attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
 2677                attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 678            }
 679
 2680            return attachment;
 681        }
 682
 683        /// <summary>
 684        /// Converts ffprobe stream info to our MediaStream class.
 685        /// </summary>
 686        /// <param name="isAudio">if set to <c>true</c> [is info].</param>
 687        /// <param name="streamInfo">The stream info.</param>
 688        /// <param name="formatInfo">The format info.</param>
 689        /// <param name="frameInfoList">The frame info.</param>
 690        /// <returns>MediaStream.</returns>
 691        private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo, IReadOn
 692        {
 693            // These are mp4 chapters
 26694            if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
 695            {
 696                // Edit: but these are also sometimes subtitles?
 697                // return null;
 698            }
 699
 26700            var stream = new MediaStream
 26701            {
 26702                Codec = streamInfo.CodecName,
 26703                Profile = streamInfo.Profile,
 26704                Level = streamInfo.Level,
 26705                Index = streamInfo.Index,
 26706                PixelFormat = streamInfo.PixelFormat,
 26707                NalLengthSize = streamInfo.NalLengthSize,
 26708                TimeBase = streamInfo.TimeBase,
 26709                CodecTimeBase = streamInfo.CodecTimeBase,
 26710                IsAVC = streamInfo.IsAvc
 26711            };
 712
 713            // Filter out junk
 26714            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", Stri
 715            {
 10716                stream.CodecTag = streamInfo.CodecTagString;
 717            }
 718
 26719            if (streamInfo.Tags is not null)
 720            {
 22721                stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
 22722                stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 22723                stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
 724            }
 725
 26726            if (streamInfo.CodecType == CodecType.Audio)
 727            {
 11728                stream.Type = MediaStreamType.Audio;
 11729                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 11730                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 731
 11732                stream.Channels = streamInfo.Channels;
 733
 11734                if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
 735                {
 11736                    stream.SampleRate = sampleRate;
 737                }
 738
 11739                stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
 740
 11741                if (streamInfo.BitsPerSample > 0)
 742                {
 0743                    stream.BitDepth = streamInfo.BitsPerSample;
 744                }
 11745                else if (streamInfo.BitsPerRawSample > 0)
 746                {
 3747                    stream.BitDepth = streamInfo.BitsPerRawSample;
 748                }
 749
 11750                if (string.IsNullOrEmpty(stream.Title))
 751                {
 752                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 11753                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 11754                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComparis
 755                    {
 3756                        stream.Title = handlerName;
 757                    }
 758                }
 759            }
 15760            else if (streamInfo.CodecType == CodecType.Subtitle)
 761            {
 3762                stream.Type = MediaStreamType.Subtitle;
 3763                stream.Codec = NormalizeSubtitleCodec(stream.Codec);
 3764                stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
 3765                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 3766                stream.LocalizedForced = _localization.GetLocalizedString("Forced");
 3767                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 3768                stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
 769
 770                // Graphical subtitle may have width and height info
 3771                stream.Width = streamInfo.Width;
 3772                stream.Height = streamInfo.Height;
 773
 3774                if (string.IsNullOrEmpty(stream.Title))
 775                {
 776                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 3777                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 3778                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringCompa
 779                    {
 1780                        stream.Title = handlerName;
 781                    }
 782                }
 783            }
 12784            else if (streamInfo.CodecType == CodecType.Video)
 785            {
 12786                stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
 12787                stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
 788
 12789                stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
 12790                    && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
 791
 12792                if (isAudio
 12793                    || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
 12794                    || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
 12795                    || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
 12796                    || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
 797                {
 2798                    stream.Type = MediaStreamType.EmbeddedImage;
 799                }
 10800                else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 801                {
 802                    // How to differentiate between video and embedded image?
 803                    // The only difference I've seen thus far is presence of codec tag, also embedded images have high (
 1804                    if (!string.IsNullOrWhiteSpace(stream.CodecTag))
 805                    {
 0806                        stream.Type = MediaStreamType.Video;
 807                    }
 808                    else
 809                    {
 1810                        stream.Type = MediaStreamType.EmbeddedImage;
 811                    }
 812                }
 813                else
 814                {
 9815                    stream.Type = MediaStreamType.Video;
 816                }
 817
 12818                stream.Width = streamInfo.Width;
 12819                stream.Height = streamInfo.Height;
 12820                stream.AspectRatio = GetAspectRatio(streamInfo);
 821
 12822                if (streamInfo.BitsPerSample > 0)
 823                {
 0824                    stream.BitDepth = streamInfo.BitsPerSample;
 825                }
 12826                else if (streamInfo.BitsPerRawSample > 0)
 827                {
 11828                    stream.BitDepth = streamInfo.BitsPerRawSample;
 829                }
 830
 12831                if (!stream.BitDepth.HasValue)
 832                {
 1833                    if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
 834                    {
 1835                        if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
 1836                            || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
 837                        {
 1838                            stream.BitDepth = 8;
 839                        }
 0840                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase
 0841                                 || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreC
 842                        {
 0843                            stream.BitDepth = 10;
 844                        }
 0845                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase
 0846                                 || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreC
 847                        {
 0848                            stream.BitDepth = 12;
 849                        }
 850                    }
 851                }
 852
 853                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 12854                if (string.Equals(streamInfo.SampleAspectRatio, "1:1", StringComparison.OrdinalIgnoreCase))
 855                {
 8856                    stream.IsAnamorphic = false;
 857                }
 4858                else if (!string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
 859                {
 3860                    stream.IsAnamorphic = true;
 861                }
 1862                else if (string.Equals(streamInfo.DisplayAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
 863                {
 1864                    stream.IsAnamorphic = false;
 865                }
 0866                else if (!string.Equals(
 0867                             streamInfo.DisplayAspectRatio,
 0868                             // Force GetAspectRatio() to derive ratio from Width/Height directly by using null DAR
 0869                             GetAspectRatio(new MediaStreamInfo
 0870                             {
 0871                                 Width = streamInfo.Width,
 0872                                 Height = streamInfo.Height,
 0873                                 DisplayAspectRatio = null
 0874                             }),
 0875                             StringComparison.OrdinalIgnoreCase))
 876                {
 0877                    stream.IsAnamorphic = true;
 878                }
 879                else
 880                {
 0881                    stream.IsAnamorphic = false;
 882                }
 883
 12884                if (streamInfo.Refs > 0)
 885                {
 12886                    stream.RefFrames = streamInfo.Refs;
 887                }
 888
 12889                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 890                {
 5891                    stream.ColorRange = streamInfo.ColorRange;
 892                }
 893
 12894                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 895                {
 5896                    stream.ColorSpace = streamInfo.ColorSpace;
 897                }
 898
 12899                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 900                {
 2901                    stream.ColorTransfer = streamInfo.ColorTransfer;
 902                }
 903
 12904                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 905                {
 2906                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 907                }
 908
 12909                if (streamInfo.SideDataList is not null)
 910                {
 6911                    foreach (var data in streamInfo.SideDataList)
 912                    {
 913                        // Parse Dolby Vision metadata from side_data
 2914                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 915                        {
 1916                            stream.DvVersionMajor = data.DvVersionMajor;
 1917                            stream.DvVersionMinor = data.DvVersionMinor;
 1918                            stream.DvProfile = data.DvProfile;
 1919                            stream.DvLevel = data.DvLevel;
 1920                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1921                            stream.ElPresentFlag = data.ElPresentFlag;
 1922                            stream.BlPresentFlag = data.BlPresentFlag;
 1923                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 924                        }
 925
 926                        // Parse video rotation metadata from side_data
 1927                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 928                        {
 1929                            stream.Rotation = data.Rotation;
 930                        }
 931                    }
 932                }
 933
 12934                var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
 12935                if (frameInfo?.SideDataList != null)
 936                {
 0937                    if (frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE2
 938                    {
 0939                        stream.Hdr10PlusPresentFlag = true;
 940                    }
 941                }
 942            }
 0943            else if (streamInfo.CodecType == CodecType.Data)
 944            {
 0945                stream.Type = MediaStreamType.Data;
 946            }
 947            else
 948            {
 0949                return null;
 950            }
 951
 952            // Get stream bitrate
 26953            var bitrate = 0;
 954
 26955            if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
 956            {
 12957                bitrate = value;
 958            }
 959
 960            // The bitrate info of FLAC musics and some videos is included in formatInfo.
 26961            if (bitrate == 0
 26962                && formatInfo is not null
 26963                && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
 964            {
 965                // If the stream info doesn't have a bitrate get the value from the media format info
 7966                if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
 967                {
 7968                    bitrate = value;
 969                }
 970            }
 971
 26972            if (bitrate > 0)
 973            {
 19974                stream.BitRate = bitrate;
 975            }
 976
 977            // Extract bitrate info from tag "BPS" if possible.
 26978            if (!stream.BitRate.HasValue
 26979                && (streamInfo.CodecType == CodecType.Audio
 26980                    || streamInfo.CodecType == CodecType.Video))
 981            {
 7982                var bps = GetBPSFromTags(streamInfo);
 7983                if (bps > 0)
 984                {
 1985                    stream.BitRate = bps;
 986                }
 987                else
 988                {
 989                    // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
 6990                    var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
 6991                    var bytes = GetNumberOfBytesFromTags(streamInfo);
 6992                    if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
 993                    {
 0994                        bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
 0995                        if (bps > 0)
 996                        {
 0997                            stream.BitRate = bps;
 998                        }
 999                    }
 1000                }
 1001            }
 1002
 261003            var disposition = streamInfo.Disposition;
 261004            if (disposition is not null)
 1005            {
 261006                if (disposition.GetValueOrDefault("default") == 1)
 1007                {
 151008                    stream.IsDefault = true;
 1009                }
 1010
 261011                if (disposition.GetValueOrDefault("forced") == 1)
 1012                {
 01013                    stream.IsForced = true;
 1014                }
 1015
 261016                if (disposition.GetValueOrDefault("hearing_impaired") == 1)
 1017                {
 11018                    stream.IsHearingImpaired = true;
 1019                }
 1020            }
 1021
 261022            NormalizeStreamTitle(stream);
 1023
 261024            return stream;
 1025        }
 1026
 1027        private void NormalizeStreamTitle(MediaStream stream)
 1028        {
 261029            if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
 261030                || stream.Type == MediaStreamType.EmbeddedImage)
 1031            {
 31032                stream.Title = null;
 1033            }
 261034        }
 1035
 1036        /// <summary>
 1037        /// Gets a string from an FFProbeResult tags dictionary.
 1038        /// </summary>
 1039        /// <param name="tags">The tags.</param>
 1040        /// <param name="key">The key.</param>
 1041        /// <returns>System.String.</returns>
 1042        private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
 1043        {
 1241044            if (tags is null)
 1045            {
 31046                return null;
 1047            }
 1048
 1211049            tags.TryGetValue(key, out var val);
 1050
 1211051            return val;
 1052        }
 1053
 1054        private string ParseChannelLayout(string input)
 1055        {
 111056            if (string.IsNullOrEmpty(input))
 1057            {
 11058                return null;
 1059            }
 1060
 101061            return input.AsSpan().LeftPart('(').ToString();
 1062        }
 1063
 1064        private string GetAspectRatio(MediaStreamInfo info)
 1065        {
 121066            var original = info.DisplayAspectRatio;
 1067
 121068            var parts = (original ?? string.Empty).Split(':');
 121069            if (!(parts.Length == 2
 121070                    && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
 121071                    && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
 121072                    && width > 0
 121073                    && height > 0))
 1074            {
 31075                width = info.Width;
 31076                height = info.Height;
 1077            }
 1078
 121079            if (width > 0 && height > 0)
 1080            {
 121081                double ratio = width;
 121082                ratio /= height;
 1083
 121084                if (IsClose(ratio, 1.777777778, .03))
 1085                {
 71086                    return "16:9";
 1087                }
 1088
 51089                if (IsClose(ratio, 1.3333333333, .05))
 1090                {
 11091                    return "4:3";
 1092                }
 1093
 41094                if (IsClose(ratio, 1.41))
 1095                {
 01096                    return "1.41:1";
 1097                }
 1098
 41099                if (IsClose(ratio, 1.5))
 1100                {
 11101                    return "1.5:1";
 1102                }
 1103
 31104                if (IsClose(ratio, 1.6))
 1105                {
 01106                    return "1.6:1";
 1107                }
 1108
 31109                if (IsClose(ratio, 1.66666666667))
 1110                {
 01111                    return "5:3";
 1112                }
 1113
 31114                if (IsClose(ratio, 1.85, .02))
 1115                {
 01116                    return "1.85:1";
 1117                }
 1118
 31119                if (IsClose(ratio, 2.35, .025))
 1120                {
 01121                    return "2.35:1";
 1122                }
 1123
 31124                if (IsClose(ratio, 2.4, .025))
 1125                {
 11126                    return "2.40:1";
 1127                }
 1128            }
 1129
 21130            return original;
 1131        }
 1132
 1133        private bool IsClose(double d1, double d2, double variance = .005)
 1134        {
 401135            return Math.Abs(d1 - d2) <= variance;
 1136        }
 1137
 1138        /// <summary>
 1139        /// Gets a frame rate from a string value in ffprobe output
 1140        /// This could be a number or in the format of 2997/125.
 1141        /// </summary>
 1142        /// <param name="value">The value.</param>
 1143        /// <returns>System.Nullable{System.Single}.</returns>
 1144        internal static float? GetFrameRate(ReadOnlySpan<char> value)
 1145        {
 331146            if (value.IsEmpty)
 1147            {
 01148                return null;
 1149            }
 1150
 331151            int index = value.IndexOf('/');
 331152            if (index == -1)
 1153            {
 01154                return null;
 1155            }
 1156
 331157            if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
 331158                || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var div
 1159            {
 01160                return null;
 1161            }
 1162
 331163            return divisor == 0f ? null : dividend / divisor;
 1164        }
 1165
 1166        private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
 1167        {
 1168            // Get the first info stream
 21169            var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
 21170            if (stream is null)
 1171            {
 01172                return;
 1173            }
 1174
 1175            // Get duration from stream properties
 21176            var duration = stream.Duration;
 1177
 1178            // If it's not there go into format properties
 21179            if (string.IsNullOrEmpty(duration))
 1180            {
 01181                duration = result.Format.Duration;
 1182            }
 1183
 1184            // If we got something, parse it
 21185            if (!string.IsNullOrEmpty(duration))
 1186            {
 21187                data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
 1188            }
 21189        }
 1190
 1191        private int? GetBPSFromTags(MediaStreamInfo streamInfo)
 1192        {
 71193            if (streamInfo?.Tags is null)
 1194            {
 01195                return null;
 1196            }
 1197
 71198            var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
 71199            if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
 1200            {
 21201                return parsedBps;
 1202            }
 1203
 51204            return null;
 1205        }
 1206
 1207        private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
 1208        {
 61209            if (streamInfo?.Tags is null)
 1210            {
 01211                return null;
 1212            }
 1213
 61214            var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "D
 61215            if (TimeSpan.TryParse(duration, out var parsedDuration))
 1216            {
 11217                return parsedDuration.TotalSeconds;
 1218            }
 1219
 51220            return null;
 1221        }
 1222
 1223        private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
 1224        {
 61225            if (streamInfo?.Tags is null)
 1226            {
 01227                return null;
 1228            }
 1229
 61230            var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
 61231                                ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
 61232            if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
 1233            {
 11234                return parsedBytes;
 1235            }
 1236
 51237            return null;
 1238        }
 1239
 1240        private void SetSize(InternalMediaInfoResult data, MediaInfo info)
 1241        {
 111242            if (data.Format is null)
 1243            {
 11244                return;
 1245            }
 1246
 101247            info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.Invaria
 101248        }
 1249
 1250        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
 1251        {
 21252            var people = new List<BaseItemPerson>();
 21253            if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
 1254            {
 121255                foreach (var person in Split(composer, false))
 1256                {
 41257                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
 1258                }
 1259            }
 1260
 21261            if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
 1262            {
 01263                foreach (var person in Split(conductor, false))
 1264                {
 01265                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
 1266                }
 1267            }
 1268
 21269            if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
 1270            {
 81271                foreach (var person in Split(lyricist, false))
 1272                {
 21273                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
 1274                }
 1275            }
 1276
 21277            if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
 1278            {
 501279                foreach (var person in Split(performer, false))
 1280                {
 231281                    Match match = PerformerRegex().Match(person);
 1282
 1283                    // If the performer doesn't have any instrument/role associated, it won't match. In that case, chanc
 231284                    if (match.Success)
 1285                    {
 221286                        people.Add(new BaseItemPerson
 221287                        {
 221288                            Name = match.Groups["name"].Value,
 221289                            Type = PersonKind.Actor,
 221290                            Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
 221291                        });
 1292                    }
 1293                }
 1294            }
 1295
 1296            // In cases where there isn't sufficient information as to which role a writer performed on a recording, tag
 21297            if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
 1298            {
 01299                foreach (var person in Split(writer, false))
 1300                {
 01301                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
 1302                }
 1303            }
 1304
 21305            if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
 1306            {
 121307                foreach (var person in Split(arranger, false))
 1308                {
 41309                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
 1310                }
 1311            }
 1312
 21313            if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
 1314            {
 01315                foreach (var person in Split(engineer, false))
 1316                {
 01317                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
 1318                }
 1319            }
 1320
 21321            if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
 1322            {
 81323                foreach (var person in Split(mixer, false))
 1324                {
 21325                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
 1326                }
 1327            }
 1328
 21329            if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
 1330            {
 01331                foreach (var person in Split(remixer, false))
 1332                {
 01333                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
 1334                }
 1335            }
 1336
 21337            audio.People = people.ToArray();
 1338
 1339            // Set album artist
 21340            var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
 21341            audio.AlbumArtists = albumArtist is not null
 21342                ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
 21343                : Array.Empty<string>();
 1344
 1345            // Set album artist to artist if empty
 21346            if (audio.AlbumArtists.Length == 0)
 1347            {
 01348                audio.AlbumArtists = audio.Artists;
 1349            }
 1350
 1351            // Track number
 21352            audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
 1353
 1354            // Disc number
 21355            audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
 1356
 1357            // There's several values in tags may or may not be present
 21358            FetchStudios(audio, tags, "organization");
 21359            FetchStudios(audio, tags, "ensemble");
 21360            FetchStudios(audio, tags, "publisher");
 21361            FetchStudios(audio, tags, "label");
 1362
 1363            // These support multiple values, but for now we only store the first.
 21364            var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
 21365                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
 21366            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
 1367
 21368            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
 21369                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
 21370            audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
 1371
 21372            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
 21373                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
 21374            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
 1375
 21376            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
 21377                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
 21378            audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
 1379
 21380            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
 21381                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
 21382            audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
 21383        }
 1384
 1385        private string GetMultipleMusicBrainzId(string value)
 1386        {
 201387            if (string.IsNullOrWhiteSpace(value))
 1388            {
 101389                return null;
 1390            }
 1391
 101392            return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
 101393                .FirstOrDefault();
 1394        }
 1395
 1396        /// <summary>
 1397        /// Splits the specified val.
 1398        /// </summary>
 1399        /// <param name="val">The val.</param>
 1400        /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
 1401        /// <returns>System.String[][].</returns>
 1402        private string[] Split(string val, bool allowCommaDelimiter)
 1403        {
 1404            // Only use the comma as a delimiter if there are no slashes or pipes.
 1405            // We want to be careful not to split names that have commas in them
 141406            return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
 141407                val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
 141408                val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1409        }
 1410
 1411        private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
 1412        {
 51413            if (splitFeaturing)
 1414            {
 31415                val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
 31416                    .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
 1417            }
 1418
 51419            var artistsFound = new List<string>();
 1420
 3001421            foreach (var whitelistArtist in SplitWhitelist)
 1422            {
 1451423                var originalVal = val;
 1451424                val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
 1425
 1451426                if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
 1427                {
 01428                    artistsFound.Add(whitelistArtist);
 1429                }
 1430            }
 1431
 51432            var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1433
 51434            artistsFound.AddRange(artists);
 51435            return artistsFound.DistinctNames();
 1436        }
 1437
 1438        /// <summary>
 1439        /// Gets the studios from the tags collection.
 1440        /// </summary>
 1441        /// <param name="info">The info.</param>
 1442        /// <param name="tags">The tags.</param>
 1443        /// <param name="tagName">Name of the tag.</param>
 1444        private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
 1445        {
 171446            var val = tags.GetValueOrDefault(tagName);
 1447
 171448            if (string.IsNullOrEmpty(val))
 1449            {
 151450                return;
 1451            }
 1452
 21453            var studios = Split(val, true);
 21454            var studioList = new List<string>();
 1455
 81456            foreach (var studio in studios)
 1457            {
 21458                if (string.IsNullOrWhiteSpace(studio))
 1459                {
 1460                    continue;
 1461                }
 1462
 1463                // Don't add artist/album artist name to studios, even if it's listed there
 21464                if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
 21465                    || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
 1466                {
 1467                    continue;
 1468                }
 1469
 21470                studioList.Add(studio);
 1471            }
 1472
 21473            info.Studios = studioList
 21474                .Distinct(StringComparer.OrdinalIgnoreCase)
 21475                .ToArray();
 21476        }
 1477
 1478        /// <summary>
 1479        /// Gets the genres from the tags collection.
 1480        /// </summary>
 1481        /// <param name="info">The information.</param>
 1482        /// <param name="tags">The tags.</param>
 1483        private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
 1484        {
 111485            var genreVal = tags.GetValueOrDefault("genre");
 111486            if (string.IsNullOrEmpty(genreVal))
 1487            {
 91488                return;
 1489            }
 1490
 21491            var genres = new List<string>(info.Genres);
 201492            foreach (var genre in Split(genreVal, true))
 1493            {
 81494                if (string.IsNullOrEmpty(genre))
 1495                {
 1496                    continue;
 1497                }
 1498
 81499                genres.Add(genre);
 1500            }
 1501
 21502            info.Genres = genres
 21503                .Distinct(StringComparer.OrdinalIgnoreCase)
 21504                .ToArray();
 21505        }
 1506
 1507        /// <summary>
 1508        /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
 1509        /// </summary>
 1510        /// <param name="tags">The tags.</param>
 1511        /// <param name="tagName">Name of the tag.</param>
 1512        /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
 1513        private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
 1514        {
 41515            var disc = tags.GetValueOrDefault(tagName);
 1516
 41517            if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
 1518            {
 41519                return discNum;
 1520            }
 1521
 01522            return null;
 1523        }
 1524
 1525        private static ChapterInfo GetChapterInfo(MediaChapter chapter)
 1526        {
 01527            var info = new ChapterInfo();
 1528
 01529            if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
 1530            {
 01531                info.Name = name;
 1532            }
 1533
 1534            // Limit accuracy to milliseconds to match xml saving
 01535            var secondsString = chapter.StartTime;
 1536
 01537            if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
 1538            {
 01539                var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
 01540                info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
 1541            }
 1542
 01543            return info;
 1544        }
 1545
 1546        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
 1547        {
 91548            var tags = data.Format?.Tags;
 1549
 91550            if (tags is null)
 1551            {
 31552                return;
 1553            }
 1554
 61555            if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
 1556            {
 01557                var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries | StringSpli
 1558
 1559                // If this is empty then don't overwrite genres that might have been fetched earlier
 01560                if (genreList.Length > 0)
 1561                {
 01562                    video.Genres = genreList;
 1563                }
 1564            }
 1565
 61566            if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRati
 1567            {
 01568                video.OfficialRating = officialRating;
 1569            }
 1570
 61571            if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
 1572            {
 01573                video.People = Array.ConvertAll(
 01574                    people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntr
 01575                    i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
 1576            }
 1577
 61578            if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, Cul
 1579            {
 01580                video.ProductionYear = parsedYear;
 1581            }
 1582
 1583            // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1584            // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
 61585            if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(y
 1586            {
 01587                video.PremiereDate = parsedDate;
 1588            }
 1589
 61590            var description = tags.GetValueOrDefault("WM/SubTitleDescription");
 1591
 61592            var subTitle = tags.GetValueOrDefault("WM/SubTitle");
 1593
 1594            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1595
 1596            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, ex
 1597            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
 1598            // OR -> COMMENT. SUBTITLE: DESCRIPTION
 1599            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the 
 1600            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in t
 61601            if (string.IsNullOrWhiteSpace(subTitle)
 61602                && !string.IsNullOrWhiteSpace(description)
 61603                && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains
 1604            {
 01605                string[] descriptionParts = description.Split(':');
 01606                if (descriptionParts.Length > 0)
 1607                {
 01608                    string subtitle = descriptionParts[0];
 1609                    try
 1610                    {
 1611                        // Check if it contains a episode number and season number
 01612                        if (subtitle.Contains('/', StringComparison.Ordinal))
 1613                        {
 01614                            string[] subtitleParts = subtitle.Split(' ');
 01615                            string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Spl
 01616                            video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
 1617                            // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
 1618
 1619                            // Skip the numbers, concatenate the rest, trim and set as new description
 01620                            description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1621                        }
 01622                        else if (subtitle.Contains('.', StringComparison.Ordinal))
 1623                        {
 01624                            var subtitleParts = subtitle.Split('.');
 01625                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1626                        }
 1627                        else
 1628                        {
 01629                            description = subtitle.Trim();
 1630                        }
 01631                    }
 01632                    catch (Exception ex)
 1633                    {
 01634                        _logger.LogError(ex, "Error while parsing subtitle field");
 1635
 1636                        // Fallback to default parsing
 01637                        if (subtitle.Contains('.', StringComparison.Ordinal))
 1638                        {
 01639                            var subtitleParts = subtitle.Split('.');
 01640                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1641                        }
 1642                        else
 1643                        {
 01644                            description = subtitle.Trim();
 1645                        }
 01646                    }
 1647                }
 1648            }
 1649
 61650            if (!string.IsNullOrWhiteSpace(description))
 1651            {
 01652                video.Overview = description;
 1653            }
 61654        }
 1655
 1656        private void ExtractTimestamp(MediaInfo video)
 1657        {
 91658            if (video.VideoType != VideoType.VideoFile)
 1659            {
 01660                return;
 1661            }
 1662
 91663            if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
 91664                && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
 91665                && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
 1666            {
 81667                return;
 1668            }
 1669
 1670            try
 1671            {
 11672                video.Timestamp = GetMpegTimestamp(video.Path);
 01673                _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
 01674            }
 11675            catch (Exception ex)
 1676            {
 11677                video.Timestamp = null;
 11678                _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
 11679            }
 11680        }
 1681
 1682        // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
 1683        private TransportStreamTimestamp GetMpegTimestamp(string path)
 1684        {
 11685            var packetBuffer = new byte[197];
 1686
 11687            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
 1688            {
 01689                fs.ReadExactly(packetBuffer);
 01690            }
 1691
 01692            if (packetBuffer[0] == 71)
 1693            {
 01694                return TransportStreamTimestamp.None;
 1695            }
 1696
 01697            if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
 1698            {
 01699                return TransportStreamTimestamp.None;
 1700            }
 1701
 01702            if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
 1703            {
 01704                return TransportStreamTimestamp.Zero;
 1705            }
 1706
 01707            return TransportStreamTimestamp.Valid;
 1708        }
 1709
 1710        [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
 1711        private static partial Regex PerformerRegex();
 1712    }
 1713}

Methods/Properties

.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.Nullable`1<System.Int32>)
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)
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)