< 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: 592
Uncovered lines: 152
Coverable lines: 744
Total lines: 1713
Line coverage: 79.5%
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
.cctor()100%11100%
.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%26614682.2%
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
 133        private static readonly char[] _basicDelimiters = ['/', ';'];
 134        private static readonly char[] _nameDelimiters = [.. _basicDelimiters, '|', '\\'];
 135        private static readonly char[] _genreDelimiters = [.. _basicDelimiters, ','];
 136        private static readonly string[] _webmVideoCodecs = ["av1", "vp8", "vp9"];
 137        private static readonly string[] _webmAudioCodecs = ["opus", "vorbis"];
 38
 39        private readonly ILogger _logger;
 40        private readonly ILocalizationManager _localization;
 41
 42        private string[] _splitWhiteList;
 43
 44        /// <summary>
 45        /// Initializes a new instance of the <see cref="ProbeResultNormalizer"/> class.
 46        /// </summary>
 47        /// <param name="logger">The <see cref="ILogger{ProbeResultNormalizer}"/> for use with the <see cref="ProbeResul
 48        /// <param name="localization">The <see cref="ILocalizationManager"/> for use with the <see cref="ProbeResultNor
 49        public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
 50        {
 2151            _logger = logger;
 2152            _localization = localization;
 2153        }
 54
 555        private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
 556        {
 557            "AC/DC",
 558            "A/T/O/S",
 559            "As/Hi Soundworks",
 560            "Au/Ra",
 561            "Bremer/McCoy",
 562            "b/bqスタヂオ",
 563            "DOV/S",
 564            "DJ'TEKINA//SOMETHING",
 565            "IX/ON",
 566            "J-CORE SLi//CER",
 567            "M(a/u)SH",
 568            "Kaoru/Brilliance",
 569            "signum/ii",
 570            "Richiter(LORB/DUGEM DI BARAT)",
 571            "이달의 소녀 1/3",
 572            "R!N / Gemie",
 573            "LOONA 1/3",
 574            "LOONA / yyxy",
 575            "LOONA / ODD EYE CIRCLE",
 576            "K/DA",
 577            "22/7",
 578            "諭吉佳作/men",
 579            "//dARTH nULL",
 580            "Phantom/Ghost",
 581            "She/Her/Hers",
 582            "5/8erl in Ehr'n",
 583            "Smith/Kotzen",
 584            "We;Na",
 585            "LSR/CITY",
 586        };
 87
 88        /// <summary>
 89        /// Transforms a FFprobe response into its <see cref="MediaInfo"/> equivalent.
 90        /// </summary>
 91        /// <param name="data">The <see cref="InternalMediaInfoResult"/>.</param>
 92        /// <param name="videoType">The <see cref="VideoType"/>.</param>
 93        /// <param name="isAudio">A boolean indicating whether the media is audio.</param>
 94        /// <param name="path">Path to media file.</param>
 95        /// <param name="protocol">Path media protocol.</param>
 96        /// <returns>The <see cref="MediaInfo"/>.</returns>
 97        public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, Med
 98        {
 1199            var info = new MediaInfo
 11100            {
 11101                Path = path,
 11102                Protocol = protocol,
 11103                VideoType = videoType
 11104            };
 105
 11106            FFProbeHelpers.NormalizeFFProbeResult(data);
 11107            SetSize(data, info);
 108
 11109            var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
 11110            var internalFrames = data.Frames ?? Array.Empty<MediaFrameInfo>();
 111
 11112            info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format, internalFrames))
 11113                .Where(i => i is not null)
 11114                // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know
 11115                .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
 11116                .ToList();
 117
 11118            info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
 11119                .Where(i => i is not null)
 11120                .ToList();
 121
 11122            if (data.Format is not null)
 123            {
 10124                info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
 125
 10126                if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
 127                {
 10128                    info.Bitrate = value;
 129                }
 130            }
 131
 11132            var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 11133            var tagStreamType = isAudio ? CodecType.Audio : CodecType.Video;
 134
 11135            var tagStream = data.Streams?.FirstOrDefault(i => i.CodecType == tagStreamType);
 136
 11137            if (tagStream?.Tags is not null)
 138            {
 70139                foreach (var (key, value) in tagStream.Tags)
 140                {
 27141                    tags[key] = value;
 142                }
 143            }
 144
 11145            if (data.Format?.Tags is not null)
 146            {
 274147                foreach (var (key, value) in data.Format.Tags)
 148                {
 129149                    tags[key] = value;
 150                }
 151            }
 152
 11153            FetchGenres(info, tags);
 154
 11155            info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
 11156            info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
 11157            info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc");
 158
 11159            info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort");
 11160            info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
 11161            info.ShowName = tags.GetValueOrDefault("show_name");
 11162            info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
 163
 164            // Several different forms of retail/premiere date
 11165            info.PremiereDate =
 11166                FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
 11167                FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
 11168                FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
 11169                FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
 11170                FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
 11171                FFProbeHelpers.GetDictionaryDateTime(tags, "date") ??
 11172                FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time");
 173
 174            // Set common metadata for music (audio) and music videos (video)
 11175            info.Album = tags.GetValueOrDefault("album");
 176
 11177            if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
 178            {
 2179                info.Artists = SplitDistinctArtists(artists, _basicDelimiters, false).ToArray();
 180            }
 181            else
 182            {
 9183                var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
 9184                info.Artists = artist is null
 9185                    ? Array.Empty<string>()
 9186                    : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
 187            }
 188
 189            // Guess ProductionYear from PremiereDate if missing
 11190            if (!info.ProductionYear.HasValue && info.PremiereDate.HasValue)
 191            {
 5192                info.ProductionYear = info.PremiereDate.Value.Year;
 193            }
 194
 195            // Set mediaType-specific metadata
 11196            if (isAudio)
 197            {
 2198                SetAudioRuntimeTicks(data, info);
 199
 200                // tags are normally located under data.format, but we've seen some cases with ogg where they're part of
 201                // so let's create a combined list of both
 202
 2203                SetAudioInfoFromTags(info, tags);
 204            }
 205            else
 206            {
 9207                FetchStudios(info, tags, "copyright");
 208
 9209                var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
 9210                if (iTunExtc is not null)
 211                {
 0212                    var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
 213                    // Example
 214                    // mpaa|G|100|For crude humor
 0215                    if (parts.Length > 1)
 216                    {
 0217                        info.OfficialRating = parts[1];
 218
 0219                        if (parts.Length > 3)
 220                        {
 0221                            info.OfficialRatingDescription = parts[3];
 222                        }
 223                    }
 224                }
 225
 9226                var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
 9227                if (iTunXml is not null)
 228                {
 1229                    FetchFromItunesInfo(iTunXml, info);
 230                }
 231
 9232                if (data.Format is not null && !string.IsNullOrEmpty(data.Format.Duration))
 233                {
 8234                    info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCul
 235                }
 236
 9237                FetchWtvInfo(info, data);
 238
 9239                if (data.Chapters is not null)
 240                {
 3241                    info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
 242                }
 243
 9244                ExtractTimestamp(info);
 245
 9246                if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", Strin
 247                {
 0248                    info.Video3DFormat = Video3DFormat.FullSideBySide;
 249                }
 250
 62251                foreach (var mediaStream in info.MediaStreams)
 252                {
 22253                    if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
 254                    {
 3255                        mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Channels);
 256                    }
 257                }
 258
 9259                var videoStreamsBitrate = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).Select(i => i.Bi
 260                // If ffprobe reported the container bitrate as being the same as the video stream bitrate, then it's wr
 9261                if (videoStreamsBitrate == (info.Bitrate ?? 0))
 262                {
 5263                    info.InferTotalBitrate(true);
 264                }
 265            }
 266
 11267            return info;
 268        }
 269
 270        private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
 271        {
 10272            if (string.IsNullOrWhiteSpace(format))
 273            {
 0274                return null;
 275            }
 276
 277            // Input can be a list of multiple, comma-delimited formats - each of them needs to be checked
 10278            var splitFormat = format.Split(',');
 78279            for (var i = 0; i < splitFormat.Length; i++)
 280            {
 281                // Handle MPEG-1 container
 29282                if (string.Equals(splitFormat[i], "mpegvideo", StringComparison.OrdinalIgnoreCase))
 283                {
 0284                    splitFormat[i] = "mpeg";
 285                }
 286
 287                // Handle MPEG-TS container
 29288                else if (string.Equals(splitFormat[i], "mpegts", StringComparison.OrdinalIgnoreCase))
 289                {
 1290                    splitFormat[i] = "ts";
 291                }
 292
 293                // Handle matroska container
 28294                else if (string.Equals(splitFormat[i], "matroska", StringComparison.OrdinalIgnoreCase))
 295                {
 4296                    splitFormat[i] = "mkv";
 297                }
 298
 299                // Handle WebM
 24300                else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
 301                {
 302                    // Limit WebM to supported codecs
 4303                    if (mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contains(s
 4304                        || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringCompa
 305                    {
 3306                        splitFormat[i] = string.Empty;
 307                    }
 308                }
 309            }
 310
 10311            return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
 312        }
 313
 314        private static int? GetEstimatedAudioBitrate(string codec, int? channels)
 315        {
 3316            if (!channels.HasValue)
 317            {
 0318                return null;
 319            }
 320
 3321            var channelsValue = channels.Value;
 322
 3323            if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase)
 3324                || string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
 325            {
 326                switch (channelsValue)
 327                {
 328                    case <= 2:
 1329                        return 192000;
 330                    case >= 5:
 0331                        return 320000;
 332                }
 333            }
 334
 2335            if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase)
 2336                || string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
 337            {
 338                switch (channelsValue)
 339                {
 340                    case <= 2:
 0341                        return 192000;
 342                    case >= 5:
 0343                        return 640000;
 344                }
 345            }
 346
 2347            if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase)
 2348                || string.Equals(codec, "alac", StringComparison.OrdinalIgnoreCase))
 349            {
 350                switch (channelsValue)
 351                {
 352                    case <= 2:
 0353                        return 960000;
 354                    case >= 5:
 0355                        return 2880000;
 356                }
 357            }
 358
 2359            return null;
 360        }
 361
 362        private void FetchFromItunesInfo(string xml, MediaInfo info)
 363        {
 364            // Make things simpler and strip out the dtd
 1365            var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
 366
 1367            if (plistIndex != -1)
 368            {
 1369                xml = xml.Substring(plistIndex);
 370            }
 371
 1372            xml = "<?xml version=\"1.0\"?>" + xml;
 373
 374            // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http
 1375            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
 1376            using (var streamReader = new StreamReader(stream))
 377            {
 378                try
 379                {
 1380                    using (var reader = XmlReader.Create(streamReader))
 381                    {
 1382                        reader.MoveToContent();
 1383                        reader.Read();
 384
 385                        // Loop through each element
 4386                        while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 387                        {
 3388                            if (reader.NodeType == XmlNodeType.Element)
 389                            {
 1390                                switch (reader.Name)
 391                                {
 392                                    case "dict":
 1393                                        if (reader.IsEmptyElement)
 394                                        {
 0395                                            reader.Read();
 0396                                            continue;
 397                                        }
 398
 1399                                        using (var subtree = reader.ReadSubtree())
 400                                        {
 1401                                            ReadFromDictNode(subtree, info);
 1402                                        }
 403
 404                                        break;
 405                                    default:
 0406                                        reader.Skip();
 0407                                        break;
 408                                }
 409                            }
 410                            else
 411                            {
 2412                                reader.Read();
 413                            }
 414                        }
 1415                    }
 1416                }
 0417                catch (XmlException)
 418                {
 419                    // I've seen probe examples where the iTunMOVI value is just "<"
 420                    // So we should not allow this to fail the entire probing operation
 0421                }
 422            }
 1423        }
 424
 425        private void ReadFromDictNode(XmlReader reader, MediaInfo info)
 426        {
 1427            string currentKey = null;
 1428            var pairs = new List<NameValuePair>();
 429
 1430            reader.MoveToContent();
 1431            reader.Read();
 432
 433            // Loop through each element
 19434            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 435            {
 18436                if (reader.NodeType == XmlNodeType.Element)
 437                {
 12438                    switch (reader.Name)
 439                    {
 440                        case "key":
 6441                            if (!string.IsNullOrWhiteSpace(currentKey))
 442                            {
 5443                                ProcessPairs(currentKey, pairs, info);
 444                            }
 445
 6446                            currentKey = reader.ReadElementContentAsString();
 6447                            pairs = new List<NameValuePair>();
 6448                            break;
 449                        case "string":
 1450                            var value = reader.ReadElementContentAsString();
 1451                            if (!string.IsNullOrWhiteSpace(value))
 452                            {
 1453                                pairs.Add(new NameValuePair
 1454                                {
 1455                                    Name = value,
 1456                                    Value = value
 1457                                });
 458                            }
 459
 1460                            break;
 461                        case "array":
 5462                            if (reader.IsEmptyElement)
 463                            {
 0464                                reader.Read();
 0465                                continue;
 466                            }
 467
 5468                            using (var subtree = reader.ReadSubtree())
 469                            {
 5470                                if (!string.IsNullOrWhiteSpace(currentKey))
 471                                {
 5472                                    pairs.AddRange(ReadValueArray(subtree));
 473                                }
 5474                            }
 475
 476                            break;
 477                        default:
 0478                            reader.Skip();
 0479                            break;
 480                    }
 481                }
 482                else
 483                {
 6484                    reader.Read();
 485                }
 486            }
 1487        }
 488
 489        private List<NameValuePair> ReadValueArray(XmlReader reader)
 490        {
 5491            var pairs = new List<NameValuePair>();
 492
 5493            reader.MoveToContent();
 5494            reader.Read();
 495
 496            // Loop through each element
 20497            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 498            {
 15499                if (reader.NodeType == XmlNodeType.Element)
 500                {
 5501                    switch (reader.Name)
 502                    {
 503                        case "dict":
 504
 5505                            if (reader.IsEmptyElement)
 506                            {
 0507                                reader.Read();
 0508                                continue;
 509                            }
 510
 5511                            using (var subtree = reader.ReadSubtree())
 512                            {
 5513                                var dict = GetNameValuePair(subtree);
 5514                                if (dict is not null)
 515                                {
 1516                                    pairs.Add(dict);
 517                                }
 5518                            }
 519
 520                            break;
 521                        default:
 0522                            reader.Skip();
 0523                            break;
 524                    }
 525                }
 526                else
 527                {
 10528                    reader.Read();
 529                }
 530            }
 531
 5532            return pairs;
 533        }
 534
 535        private static void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
 536        {
 5537            List<BaseItemPerson> peoples = new List<BaseItemPerson>();
 5538            var distinctPairs = pairs.Select(p => p.Value)
 5539                    .Where(i => !string.IsNullOrWhiteSpace(i))
 5540                    .Trimmed()
 5541                    .Distinct(StringComparer.OrdinalIgnoreCase);
 542
 5543            if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
 544            {
 1545                info.Studios = distinctPairs.ToArray();
 546            }
 4547            else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
 548            {
 0549                foreach (var pair in distinctPairs)
 550                {
 0551                    peoples.Add(new BaseItemPerson
 0552                    {
 0553                        Name = pair,
 0554                        Type = PersonKind.Writer
 0555                    });
 556                }
 557            }
 4558            else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
 559            {
 2560                foreach (var pair in distinctPairs)
 561                {
 0562                    peoples.Add(new BaseItemPerson
 0563                    {
 0564                        Name = pair,
 0565                        Type = PersonKind.Producer
 0566                    });
 567                }
 568            }
 3569            else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
 570            {
 2571                foreach (var pair in distinctPairs)
 572                {
 0573                    peoples.Add(new BaseItemPerson
 0574                    {
 0575                        Name = pair,
 0576                        Type = PersonKind.Director
 0577                    });
 578                }
 579            }
 580
 5581            info.People = peoples.ToArray();
 5582        }
 583
 584        private static NameValuePair GetNameValuePair(XmlReader reader)
 585        {
 5586            string name = null;
 5587            string value = null;
 588
 5589            reader.MoveToContent();
 5590            reader.Read();
 591
 592            // Loop through each element
 20593            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 594            {
 15595                if (reader.NodeType == XmlNodeType.Element)
 596                {
 10597                    switch (reader.Name)
 598                    {
 599                        case "key":
 5600                            name = reader.ReadNormalizedString();
 5601                            break;
 602                        case "string":
 5603                            value = reader.ReadNormalizedString();
 5604                            break;
 605                        default:
 0606                            reader.Skip();
 0607                            break;
 608                    }
 609                }
 610                else
 611                {
 5612                    reader.Read();
 613                }
 614            }
 615
 5616            if (string.IsNullOrEmpty(name)
 5617                || string.IsNullOrEmpty(value))
 618            {
 4619                return null;
 620            }
 621
 1622            return new NameValuePair
 1623            {
 1624                Name = name,
 1625                Value = value
 1626            };
 627        }
 628
 629        private static string NormalizeSubtitleCodec(string codec)
 630        {
 3631            if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
 632            {
 0633                codec = "DVBSUB";
 634            }
 3635            else if (string.Equals(codec, "dvb_teletext", StringComparison.OrdinalIgnoreCase))
 636            {
 0637                codec = "DVBTXT";
 638            }
 3639            else if (string.Equals(codec, "dvd_subtitle", StringComparison.OrdinalIgnoreCase))
 640            {
 1641                codec = "DVDSUB"; // .sub+.idx
 642            }
 2643            else if (string.Equals(codec, "hdmv_pgs_subtitle", StringComparison.OrdinalIgnoreCase))
 644            {
 0645                codec = "PGSSUB"; // .sup
 646            }
 647
 3648            return codec;
 649        }
 650
 651        /// <summary>
 652        /// Converts ffprobe stream info to our MediaAttachment class.
 653        /// </summary>
 654        /// <param name="streamInfo">The stream info.</param>
 655        /// <returns>MediaAttachments.</returns>
 656        private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
 657        {
 26658            if (streamInfo.CodecType != CodecType.Attachment
 26659                && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
 660            {
 24661                return null;
 662            }
 663
 2664            var attachment = new MediaAttachment
 2665            {
 2666                Codec = streamInfo.CodecName,
 2667                Index = streamInfo.Index
 2668            };
 669
 2670            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
 671            {
 2672                attachment.CodecTag = streamInfo.CodecTagString;
 673            }
 674
 2675            if (streamInfo.Tags is not null)
 676            {
 2677                attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
 2678                attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
 2679                attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 680            }
 681
 2682            return attachment;
 683        }
 684
 685        /// <summary>
 686        /// Converts ffprobe stream info to our MediaStream class.
 687        /// </summary>
 688        /// <param name="isAudio">if set to <c>true</c> [is info].</param>
 689        /// <param name="streamInfo">The stream info.</param>
 690        /// <param name="formatInfo">The format info.</param>
 691        /// <param name="frameInfoList">The frame info.</param>
 692        /// <returns>MediaStream.</returns>
 693        private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo, IReadOn
 694        {
 695            // These are mp4 chapters
 26696            if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
 697            {
 698                // Edit: but these are also sometimes subtitles?
 699                // return null;
 700            }
 701
 26702            var stream = new MediaStream
 26703            {
 26704                Codec = streamInfo.CodecName,
 26705                Profile = streamInfo.Profile,
 26706                Level = streamInfo.Level,
 26707                Index = streamInfo.Index,
 26708                PixelFormat = streamInfo.PixelFormat,
 26709                NalLengthSize = streamInfo.NalLengthSize,
 26710                TimeBase = streamInfo.TimeBase,
 26711                CodecTimeBase = streamInfo.CodecTimeBase,
 26712                IsAVC = streamInfo.IsAvc
 26713            };
 714
 715            // Filter out junk
 26716            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", Stri
 717            {
 10718                stream.CodecTag = streamInfo.CodecTagString;
 719            }
 720
 26721            if (streamInfo.Tags is not null)
 722            {
 22723                stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
 22724                stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 22725                stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
 726            }
 727
 26728            if (streamInfo.CodecType == CodecType.Audio)
 729            {
 11730                stream.Type = MediaStreamType.Audio;
 11731                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 11732                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 733
 11734                stream.Channels = streamInfo.Channels;
 735
 11736                if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
 737                {
 11738                    stream.SampleRate = sampleRate;
 739                }
 740
 11741                stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
 742
 11743                if (streamInfo.BitsPerSample > 0)
 744                {
 0745                    stream.BitDepth = streamInfo.BitsPerSample;
 746                }
 11747                else if (streamInfo.BitsPerRawSample > 0)
 748                {
 3749                    stream.BitDepth = streamInfo.BitsPerRawSample;
 750                }
 751
 11752                if (string.IsNullOrEmpty(stream.Title))
 753                {
 754                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 11755                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 11756                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComparis
 757                    {
 3758                        stream.Title = handlerName;
 759                    }
 760                }
 761            }
 15762            else if (streamInfo.CodecType == CodecType.Subtitle)
 763            {
 3764                stream.Type = MediaStreamType.Subtitle;
 3765                stream.Codec = NormalizeSubtitleCodec(stream.Codec);
 3766                stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
 3767                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 3768                stream.LocalizedForced = _localization.GetLocalizedString("Forced");
 3769                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 3770                stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
 771
 772                // Graphical subtitle may have width and height info
 3773                stream.Width = streamInfo.Width;
 3774                stream.Height = streamInfo.Height;
 775
 3776                if (string.IsNullOrEmpty(stream.Title))
 777                {
 778                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 3779                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 3780                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringCompa
 781                    {
 1782                        stream.Title = handlerName;
 783                    }
 784                }
 785            }
 12786            else if (streamInfo.CodecType == CodecType.Video)
 787            {
 12788                stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
 12789                stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
 790
 12791                stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
 12792                    && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
 793
 12794                if (isAudio
 12795                    || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
 12796                    || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
 12797                    || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
 12798                    || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
 799                {
 2800                    stream.Type = MediaStreamType.EmbeddedImage;
 801                }
 10802                else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 803                {
 804                    // How to differentiate between video and embedded image?
 805                    // The only difference I've seen thus far is presence of codec tag, also embedded images have high (
 1806                    if (!string.IsNullOrWhiteSpace(stream.CodecTag))
 807                    {
 0808                        stream.Type = MediaStreamType.Video;
 809                    }
 810                    else
 811                    {
 1812                        stream.Type = MediaStreamType.EmbeddedImage;
 813                    }
 814                }
 815                else
 816                {
 9817                    stream.Type = MediaStreamType.Video;
 818                }
 819
 12820                stream.Width = streamInfo.Width;
 12821                stream.Height = streamInfo.Height;
 12822                stream.AspectRatio = GetAspectRatio(streamInfo);
 823
 12824                if (streamInfo.BitsPerSample > 0)
 825                {
 0826                    stream.BitDepth = streamInfo.BitsPerSample;
 827                }
 12828                else if (streamInfo.BitsPerRawSample > 0)
 829                {
 11830                    stream.BitDepth = streamInfo.BitsPerRawSample;
 831                }
 832
 12833                if (!stream.BitDepth.HasValue)
 834                {
 1835                    if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
 836                    {
 1837                        if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
 1838                            || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
 839                        {
 1840                            stream.BitDepth = 8;
 841                        }
 0842                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase
 0843                                 || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreC
 844                        {
 0845                            stream.BitDepth = 10;
 846                        }
 0847                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase
 0848                                 || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreC
 849                        {
 0850                            stream.BitDepth = 12;
 851                        }
 852                    }
 853                }
 854
 855                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 12856                if (string.Equals(streamInfo.SampleAspectRatio, "1:1", StringComparison.Ordinal))
 857                {
 8858                    stream.IsAnamorphic = false;
 859                }
 4860                else if (!string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.Ordinal))
 861                {
 3862                    stream.IsAnamorphic = true;
 863                }
 1864                else if (string.Equals(streamInfo.DisplayAspectRatio, "0:1", StringComparison.Ordinal))
 865                {
 1866                    stream.IsAnamorphic = false;
 867                }
 0868                else if (!string.Equals(
 0869                             streamInfo.DisplayAspectRatio,
 0870                             // Force GetAspectRatio() to derive ratio from Width/Height directly by using null DAR
 0871                             GetAspectRatio(new MediaStreamInfo
 0872                             {
 0873                                 Width = streamInfo.Width,
 0874                                 Height = streamInfo.Height,
 0875                                 DisplayAspectRatio = null
 0876                             }),
 0877                             StringComparison.Ordinal))
 878                {
 0879                    stream.IsAnamorphic = true;
 880                }
 881                else
 882                {
 0883                    stream.IsAnamorphic = false;
 884                }
 885
 12886                if (streamInfo.Refs > 0)
 887                {
 12888                    stream.RefFrames = streamInfo.Refs;
 889                }
 890
 12891                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 892                {
 5893                    stream.ColorRange = streamInfo.ColorRange;
 894                }
 895
 12896                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 897                {
 5898                    stream.ColorSpace = streamInfo.ColorSpace;
 899                }
 900
 12901                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 902                {
 2903                    stream.ColorTransfer = streamInfo.ColorTransfer;
 904                }
 905
 12906                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 907                {
 2908                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 909                }
 910
 12911                if (streamInfo.SideDataList is not null)
 912                {
 6913                    foreach (var data in streamInfo.SideDataList)
 914                    {
 915                        // Parse Dolby Vision metadata from side_data
 2916                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 917                        {
 1918                            stream.DvVersionMajor = data.DvVersionMajor;
 1919                            stream.DvVersionMinor = data.DvVersionMinor;
 1920                            stream.DvProfile = data.DvProfile;
 1921                            stream.DvLevel = data.DvLevel;
 1922                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1923                            stream.ElPresentFlag = data.ElPresentFlag;
 1924                            stream.BlPresentFlag = data.BlPresentFlag;
 1925                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 926                        }
 927
 928                        // Parse video rotation metadata from side_data
 1929                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 930                        {
 1931                            stream.Rotation = data.Rotation;
 932                        }
 933                    }
 934                }
 935
 12936                var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
 12937                if (frameInfo?.SideDataList is not null
 12938                    && frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE20
 939                {
 0940                    stream.Hdr10PlusPresentFlag = true;
 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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(_genreDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOption
 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(_basicDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntrie
 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 static 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

.cctor()
.ctor(Microsoft.Extensions.Logging.ILogger,MediaBrowser.Model.Globalization.ILocalizationManager)
get_SplitWhitelist()
GetMediaInfo(MediaBrowser.MediaEncoding.Probing.InternalMediaInfoResult,System.Nullable`1<MediaBrowser.Model.Entities.VideoType>,System.Boolean,System.String,MediaBrowser.Model.MediaInfo.MediaProtocol)
NormalizeFormat(System.String,System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Model.Entities.MediaStream>)
GetEstimatedAudioBitrate(System.String,System.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)