< Summary - Jellyfin

Information
Class: MediaBrowser.MediaEncoding.Probing.ProbeResultNormalizer
Assembly: MediaBrowser.MediaEncoding
File(s): /srv/git/jellyfin/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
Line coverage
80%
Covered lines: 584
Uncovered lines: 141
Coverable lines: 725
Total lines: 1689
Line coverage: 80.5%
Branch coverage
75%
Covered branches: 455
Total branches: 602
Branch coverage: 75.5%
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(...)80.43%17413887.67%
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                // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIg
 854                //    string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
 855                //    string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
 856
 857                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 12858                stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreC
 859
 12860                if (streamInfo.Refs > 0)
 861                {
 12862                    stream.RefFrames = streamInfo.Refs;
 863                }
 864
 12865                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 866                {
 5867                    stream.ColorRange = streamInfo.ColorRange;
 868                }
 869
 12870                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 871                {
 5872                    stream.ColorSpace = streamInfo.ColorSpace;
 873                }
 874
 12875                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 876                {
 2877                    stream.ColorTransfer = streamInfo.ColorTransfer;
 878                }
 879
 12880                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 881                {
 2882                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 883                }
 884
 12885                if (streamInfo.SideDataList is not null)
 886                {
 6887                    foreach (var data in streamInfo.SideDataList)
 888                    {
 889                        // Parse Dolby Vision metadata from side_data
 2890                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 891                        {
 1892                            stream.DvVersionMajor = data.DvVersionMajor;
 1893                            stream.DvVersionMinor = data.DvVersionMinor;
 1894                            stream.DvProfile = data.DvProfile;
 1895                            stream.DvLevel = data.DvLevel;
 1896                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1897                            stream.ElPresentFlag = data.ElPresentFlag;
 1898                            stream.BlPresentFlag = data.BlPresentFlag;
 1899                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 900                        }
 901
 902                        // Parse video rotation metadata from side_data
 1903                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 904                        {
 1905                            stream.Rotation = data.Rotation;
 906                        }
 907                    }
 908                }
 909
 12910                var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
 12911                if (frameInfo?.SideDataList != null)
 912                {
 0913                    if (frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE2
 914                    {
 0915                        stream.Hdr10PlusPresentFlag = true;
 916                    }
 917                }
 918            }
 0919            else if (streamInfo.CodecType == CodecType.Data)
 920            {
 0921                stream.Type = MediaStreamType.Data;
 922            }
 923            else
 924            {
 0925                return null;
 926            }
 927
 928            // Get stream bitrate
 26929            var bitrate = 0;
 930
 26931            if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
 932            {
 12933                bitrate = value;
 934            }
 935
 936            // The bitrate info of FLAC musics and some videos is included in formatInfo.
 26937            if (bitrate == 0
 26938                && formatInfo is not null
 26939                && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
 940            {
 941                // If the stream info doesn't have a bitrate get the value from the media format info
 7942                if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
 943                {
 7944                    bitrate = value;
 945                }
 946            }
 947
 26948            if (bitrate > 0)
 949            {
 19950                stream.BitRate = bitrate;
 951            }
 952
 953            // Extract bitrate info from tag "BPS" if possible.
 26954            if (!stream.BitRate.HasValue
 26955                && (streamInfo.CodecType == CodecType.Audio
 26956                    || streamInfo.CodecType == CodecType.Video))
 957            {
 7958                var bps = GetBPSFromTags(streamInfo);
 7959                if (bps > 0)
 960                {
 1961                    stream.BitRate = bps;
 962                }
 963                else
 964                {
 965                    // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
 6966                    var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
 6967                    var bytes = GetNumberOfBytesFromTags(streamInfo);
 6968                    if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
 969                    {
 0970                        bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
 0971                        if (bps > 0)
 972                        {
 0973                            stream.BitRate = bps;
 974                        }
 975                    }
 976                }
 977            }
 978
 26979            var disposition = streamInfo.Disposition;
 26980            if (disposition is not null)
 981            {
 26982                if (disposition.GetValueOrDefault("default") == 1)
 983                {
 15984                    stream.IsDefault = true;
 985                }
 986
 26987                if (disposition.GetValueOrDefault("forced") == 1)
 988                {
 0989                    stream.IsForced = true;
 990                }
 991
 26992                if (disposition.GetValueOrDefault("hearing_impaired") == 1)
 993                {
 1994                    stream.IsHearingImpaired = true;
 995                }
 996            }
 997
 26998            NormalizeStreamTitle(stream);
 999
 261000            return stream;
 1001        }
 1002
 1003        private void NormalizeStreamTitle(MediaStream stream)
 1004        {
 261005            if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
 261006                || stream.Type == MediaStreamType.EmbeddedImage)
 1007            {
 31008                stream.Title = null;
 1009            }
 261010        }
 1011
 1012        /// <summary>
 1013        /// Gets a string from an FFProbeResult tags dictionary.
 1014        /// </summary>
 1015        /// <param name="tags">The tags.</param>
 1016        /// <param name="key">The key.</param>
 1017        /// <returns>System.String.</returns>
 1018        private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
 1019        {
 1241020            if (tags is null)
 1021            {
 31022                return null;
 1023            }
 1024
 1211025            tags.TryGetValue(key, out var val);
 1026
 1211027            return val;
 1028        }
 1029
 1030        private string ParseChannelLayout(string input)
 1031        {
 111032            if (string.IsNullOrEmpty(input))
 1033            {
 11034                return null;
 1035            }
 1036
 101037            return input.AsSpan().LeftPart('(').ToString();
 1038        }
 1039
 1040        private string GetAspectRatio(MediaStreamInfo info)
 1041        {
 121042            var original = info.DisplayAspectRatio;
 1043
 121044            var parts = (original ?? string.Empty).Split(':');
 121045            if (!(parts.Length == 2
 121046                    && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
 121047                    && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
 121048                    && width > 0
 121049                    && height > 0))
 1050            {
 31051                width = info.Width;
 31052                height = info.Height;
 1053            }
 1054
 121055            if (width > 0 && height > 0)
 1056            {
 121057                double ratio = width;
 121058                ratio /= height;
 1059
 121060                if (IsClose(ratio, 1.777777778, .03))
 1061                {
 71062                    return "16:9";
 1063                }
 1064
 51065                if (IsClose(ratio, 1.3333333333, .05))
 1066                {
 11067                    return "4:3";
 1068                }
 1069
 41070                if (IsClose(ratio, 1.41))
 1071                {
 01072                    return "1.41:1";
 1073                }
 1074
 41075                if (IsClose(ratio, 1.5))
 1076                {
 11077                    return "1.5:1";
 1078                }
 1079
 31080                if (IsClose(ratio, 1.6))
 1081                {
 01082                    return "1.6:1";
 1083                }
 1084
 31085                if (IsClose(ratio, 1.66666666667))
 1086                {
 01087                    return "5:3";
 1088                }
 1089
 31090                if (IsClose(ratio, 1.85, .02))
 1091                {
 01092                    return "1.85:1";
 1093                }
 1094
 31095                if (IsClose(ratio, 2.35, .025))
 1096                {
 01097                    return "2.35:1";
 1098                }
 1099
 31100                if (IsClose(ratio, 2.4, .025))
 1101                {
 11102                    return "2.40:1";
 1103                }
 1104            }
 1105
 21106            return original;
 1107        }
 1108
 1109        private bool IsClose(double d1, double d2, double variance = .005)
 1110        {
 401111            return Math.Abs(d1 - d2) <= variance;
 1112        }
 1113
 1114        /// <summary>
 1115        /// Gets a frame rate from a string value in ffprobe output
 1116        /// This could be a number or in the format of 2997/125.
 1117        /// </summary>
 1118        /// <param name="value">The value.</param>
 1119        /// <returns>System.Nullable{System.Single}.</returns>
 1120        internal static float? GetFrameRate(ReadOnlySpan<char> value)
 1121        {
 331122            if (value.IsEmpty)
 1123            {
 01124                return null;
 1125            }
 1126
 331127            int index = value.IndexOf('/');
 331128            if (index == -1)
 1129            {
 01130                return null;
 1131            }
 1132
 331133            if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
 331134                || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var div
 1135            {
 01136                return null;
 1137            }
 1138
 331139            return divisor == 0f ? null : dividend / divisor;
 1140        }
 1141
 1142        private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
 1143        {
 1144            // Get the first info stream
 21145            var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
 21146            if (stream is null)
 1147            {
 01148                return;
 1149            }
 1150
 1151            // Get duration from stream properties
 21152            var duration = stream.Duration;
 1153
 1154            // If it's not there go into format properties
 21155            if (string.IsNullOrEmpty(duration))
 1156            {
 01157                duration = result.Format.Duration;
 1158            }
 1159
 1160            // If we got something, parse it
 21161            if (!string.IsNullOrEmpty(duration))
 1162            {
 21163                data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
 1164            }
 21165        }
 1166
 1167        private int? GetBPSFromTags(MediaStreamInfo streamInfo)
 1168        {
 71169            if (streamInfo?.Tags is null)
 1170            {
 01171                return null;
 1172            }
 1173
 71174            var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
 71175            if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
 1176            {
 21177                return parsedBps;
 1178            }
 1179
 51180            return null;
 1181        }
 1182
 1183        private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
 1184        {
 61185            if (streamInfo?.Tags is null)
 1186            {
 01187                return null;
 1188            }
 1189
 61190            var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "D
 61191            if (TimeSpan.TryParse(duration, out var parsedDuration))
 1192            {
 11193                return parsedDuration.TotalSeconds;
 1194            }
 1195
 51196            return null;
 1197        }
 1198
 1199        private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
 1200        {
 61201            if (streamInfo?.Tags is null)
 1202            {
 01203                return null;
 1204            }
 1205
 61206            var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
 61207                                ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
 61208            if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
 1209            {
 11210                return parsedBytes;
 1211            }
 1212
 51213            return null;
 1214        }
 1215
 1216        private void SetSize(InternalMediaInfoResult data, MediaInfo info)
 1217        {
 111218            if (data.Format is null)
 1219            {
 11220                return;
 1221            }
 1222
 101223            info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.Invaria
 101224        }
 1225
 1226        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
 1227        {
 21228            var people = new List<BaseItemPerson>();
 21229            if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
 1230            {
 121231                foreach (var person in Split(composer, false))
 1232                {
 41233                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
 1234                }
 1235            }
 1236
 21237            if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
 1238            {
 01239                foreach (var person in Split(conductor, false))
 1240                {
 01241                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
 1242                }
 1243            }
 1244
 21245            if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
 1246            {
 81247                foreach (var person in Split(lyricist, false))
 1248                {
 21249                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
 1250                }
 1251            }
 1252
 21253            if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
 1254            {
 501255                foreach (var person in Split(performer, false))
 1256                {
 231257                    Match match = PerformerRegex().Match(person);
 1258
 1259                    // If the performer doesn't have any instrument/role associated, it won't match. In that case, chanc
 231260                    if (match.Success)
 1261                    {
 221262                        people.Add(new BaseItemPerson
 221263                        {
 221264                            Name = match.Groups["name"].Value,
 221265                            Type = PersonKind.Actor,
 221266                            Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
 221267                        });
 1268                    }
 1269                }
 1270            }
 1271
 1272            // In cases where there isn't sufficient information as to which role a writer performed on a recording, tag
 21273            if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
 1274            {
 01275                foreach (var person in Split(writer, false))
 1276                {
 01277                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
 1278                }
 1279            }
 1280
 21281            if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
 1282            {
 121283                foreach (var person in Split(arranger, false))
 1284                {
 41285                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
 1286                }
 1287            }
 1288
 21289            if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
 1290            {
 01291                foreach (var person in Split(engineer, false))
 1292                {
 01293                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
 1294                }
 1295            }
 1296
 21297            if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
 1298            {
 81299                foreach (var person in Split(mixer, false))
 1300                {
 21301                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
 1302                }
 1303            }
 1304
 21305            if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
 1306            {
 01307                foreach (var person in Split(remixer, false))
 1308                {
 01309                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
 1310                }
 1311            }
 1312
 21313            audio.People = people.ToArray();
 1314
 1315            // Set album artist
 21316            var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
 21317            audio.AlbumArtists = albumArtist is not null
 21318                ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
 21319                : Array.Empty<string>();
 1320
 1321            // Set album artist to artist if empty
 21322            if (audio.AlbumArtists.Length == 0)
 1323            {
 01324                audio.AlbumArtists = audio.Artists;
 1325            }
 1326
 1327            // Track number
 21328            audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
 1329
 1330            // Disc number
 21331            audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
 1332
 1333            // There's several values in tags may or may not be present
 21334            FetchStudios(audio, tags, "organization");
 21335            FetchStudios(audio, tags, "ensemble");
 21336            FetchStudios(audio, tags, "publisher");
 21337            FetchStudios(audio, tags, "label");
 1338
 1339            // These support multiple values, but for now we only store the first.
 21340            var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
 21341                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
 21342            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
 1343
 21344            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
 21345                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
 21346            audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
 1347
 21348            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
 21349                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
 21350            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
 1351
 21352            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
 21353                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
 21354            audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
 1355
 21356            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
 21357                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
 21358            audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
 21359        }
 1360
 1361        private string GetMultipleMusicBrainzId(string value)
 1362        {
 201363            if (string.IsNullOrWhiteSpace(value))
 1364            {
 101365                return null;
 1366            }
 1367
 101368            return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
 101369                .FirstOrDefault();
 1370        }
 1371
 1372        /// <summary>
 1373        /// Splits the specified val.
 1374        /// </summary>
 1375        /// <param name="val">The val.</param>
 1376        /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
 1377        /// <returns>System.String[][].</returns>
 1378        private string[] Split(string val, bool allowCommaDelimiter)
 1379        {
 1380            // Only use the comma as a delimiter if there are no slashes or pipes.
 1381            // We want to be careful not to split names that have commas in them
 141382            return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
 141383                val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
 141384                val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1385        }
 1386
 1387        private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
 1388        {
 51389            if (splitFeaturing)
 1390            {
 31391                val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
 31392                    .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
 1393            }
 1394
 51395            var artistsFound = new List<string>();
 1396
 3001397            foreach (var whitelistArtist in SplitWhitelist)
 1398            {
 1451399                var originalVal = val;
 1451400                val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
 1401
 1451402                if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
 1403                {
 01404                    artistsFound.Add(whitelistArtist);
 1405                }
 1406            }
 1407
 51408            var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1409
 51410            artistsFound.AddRange(artists);
 51411            return artistsFound.DistinctNames();
 1412        }
 1413
 1414        /// <summary>
 1415        /// Gets the studios from the tags collection.
 1416        /// </summary>
 1417        /// <param name="info">The info.</param>
 1418        /// <param name="tags">The tags.</param>
 1419        /// <param name="tagName">Name of the tag.</param>
 1420        private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
 1421        {
 171422            var val = tags.GetValueOrDefault(tagName);
 1423
 171424            if (string.IsNullOrEmpty(val))
 1425            {
 151426                return;
 1427            }
 1428
 21429            var studios = Split(val, true);
 21430            var studioList = new List<string>();
 1431
 81432            foreach (var studio in studios)
 1433            {
 21434                if (string.IsNullOrWhiteSpace(studio))
 1435                {
 1436                    continue;
 1437                }
 1438
 1439                // Don't add artist/album artist name to studios, even if it's listed there
 21440                if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
 21441                    || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
 1442                {
 1443                    continue;
 1444                }
 1445
 21446                studioList.Add(studio);
 1447            }
 1448
 21449            info.Studios = studioList
 21450                .Distinct(StringComparer.OrdinalIgnoreCase)
 21451                .ToArray();
 21452        }
 1453
 1454        /// <summary>
 1455        /// Gets the genres from the tags collection.
 1456        /// </summary>
 1457        /// <param name="info">The information.</param>
 1458        /// <param name="tags">The tags.</param>
 1459        private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
 1460        {
 111461            var genreVal = tags.GetValueOrDefault("genre");
 111462            if (string.IsNullOrEmpty(genreVal))
 1463            {
 91464                return;
 1465            }
 1466
 21467            var genres = new List<string>(info.Genres);
 201468            foreach (var genre in Split(genreVal, true))
 1469            {
 81470                if (string.IsNullOrEmpty(genre))
 1471                {
 1472                    continue;
 1473                }
 1474
 81475                genres.Add(genre);
 1476            }
 1477
 21478            info.Genres = genres
 21479                .Distinct(StringComparer.OrdinalIgnoreCase)
 21480                .ToArray();
 21481        }
 1482
 1483        /// <summary>
 1484        /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
 1485        /// </summary>
 1486        /// <param name="tags">The tags.</param>
 1487        /// <param name="tagName">Name of the tag.</param>
 1488        /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
 1489        private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
 1490        {
 41491            var disc = tags.GetValueOrDefault(tagName);
 1492
 41493            if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
 1494            {
 41495                return discNum;
 1496            }
 1497
 01498            return null;
 1499        }
 1500
 1501        private static ChapterInfo GetChapterInfo(MediaChapter chapter)
 1502        {
 01503            var info = new ChapterInfo();
 1504
 01505            if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
 1506            {
 01507                info.Name = name;
 1508            }
 1509
 1510            // Limit accuracy to milliseconds to match xml saving
 01511            var secondsString = chapter.StartTime;
 1512
 01513            if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
 1514            {
 01515                var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
 01516                info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
 1517            }
 1518
 01519            return info;
 1520        }
 1521
 1522        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
 1523        {
 91524            var tags = data.Format?.Tags;
 1525
 91526            if (tags is null)
 1527            {
 31528                return;
 1529            }
 1530
 61531            if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
 1532            {
 01533                var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries | StringSpli
 1534
 1535                // If this is empty then don't overwrite genres that might have been fetched earlier
 01536                if (genreList.Length > 0)
 1537                {
 01538                    video.Genres = genreList;
 1539                }
 1540            }
 1541
 61542            if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRati
 1543            {
 01544                video.OfficialRating = officialRating;
 1545            }
 1546
 61547            if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
 1548            {
 01549                video.People = Array.ConvertAll(
 01550                    people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntr
 01551                    i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
 1552            }
 1553
 61554            if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, Cul
 1555            {
 01556                video.ProductionYear = parsedYear;
 1557            }
 1558
 1559            // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1560            // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
 61561            if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(y
 1562            {
 01563                video.PremiereDate = parsedDate;
 1564            }
 1565
 61566            var description = tags.GetValueOrDefault("WM/SubTitleDescription");
 1567
 61568            var subTitle = tags.GetValueOrDefault("WM/SubTitle");
 1569
 1570            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1571
 1572            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, ex
 1573            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
 1574            // OR -> COMMENT. SUBTITLE: DESCRIPTION
 1575            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the 
 1576            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in t
 61577            if (string.IsNullOrWhiteSpace(subTitle)
 61578                && !string.IsNullOrWhiteSpace(description)
 61579                && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains
 1580            {
 01581                string[] descriptionParts = description.Split(':');
 01582                if (descriptionParts.Length > 0)
 1583                {
 01584                    string subtitle = descriptionParts[0];
 1585                    try
 1586                    {
 1587                        // Check if it contains a episode number and season number
 01588                        if (subtitle.Contains('/', StringComparison.Ordinal))
 1589                        {
 01590                            string[] subtitleParts = subtitle.Split(' ');
 01591                            string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Spl
 01592                            video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
 1593                            // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
 1594
 1595                            // Skip the numbers, concatenate the rest, trim and set as new description
 01596                            description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1597                        }
 01598                        else if (subtitle.Contains('.', StringComparison.Ordinal))
 1599                        {
 01600                            var subtitleParts = subtitle.Split('.');
 01601                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1602                        }
 1603                        else
 1604                        {
 01605                            description = subtitle.Trim();
 1606                        }
 01607                    }
 01608                    catch (Exception ex)
 1609                    {
 01610                        _logger.LogError(ex, "Error while parsing subtitle field");
 1611
 1612                        // Fallback to default parsing
 01613                        if (subtitle.Contains('.', StringComparison.Ordinal))
 1614                        {
 01615                            var subtitleParts = subtitle.Split('.');
 01616                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1617                        }
 1618                        else
 1619                        {
 01620                            description = subtitle.Trim();
 1621                        }
 01622                    }
 1623                }
 1624            }
 1625
 61626            if (!string.IsNullOrWhiteSpace(description))
 1627            {
 01628                video.Overview = description;
 1629            }
 61630        }
 1631
 1632        private void ExtractTimestamp(MediaInfo video)
 1633        {
 91634            if (video.VideoType != VideoType.VideoFile)
 1635            {
 01636                return;
 1637            }
 1638
 91639            if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
 91640                && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
 91641                && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
 1642            {
 81643                return;
 1644            }
 1645
 1646            try
 1647            {
 11648                video.Timestamp = GetMpegTimestamp(video.Path);
 01649                _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
 01650            }
 11651            catch (Exception ex)
 1652            {
 11653                video.Timestamp = null;
 11654                _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
 11655            }
 11656        }
 1657
 1658        // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
 1659        private TransportStreamTimestamp GetMpegTimestamp(string path)
 1660        {
 11661            var packetBuffer = new byte[197];
 1662
 11663            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
 1664            {
 01665                fs.ReadExactly(packetBuffer);
 01666            }
 1667
 01668            if (packetBuffer[0] == 71)
 1669            {
 01670                return TransportStreamTimestamp.None;
 1671            }
 1672
 01673            if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
 1674            {
 01675                return TransportStreamTimestamp.None;
 1676            }
 1677
 01678            if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
 1679            {
 01680                return TransportStreamTimestamp.Zero;
 1681            }
 1682
 01683            return TransportStreamTimestamp.Valid;
 1684        }
 1685
 1686        [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
 1687        private static partial Regex PerformerRegex();
 1688    }
 1689}

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)