< 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: 574
Uncovered lines: 145
Coverable lines: 719
Total lines: 1675
Line coverage: 79.8%
Branch coverage
74%
Covered branches: 441
Total branches: 590
Branch coverage: 74.7%
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.33%73.897292.85%
NormalizeFormat(...)85.71%14.471486.66%
GetEstimatedAudioBitrate(...)50%61.652662.5%
FetchFromItunesInfo(...)83.33%13.771276.92%
ReadFromDictNode(...)90%20.862087.09%
ReadValueArray(...)83.33%13.581277.77%
ProcessPairs(...)64.28%46.931444.82%
GetNameValuePair(...)92.85%14.151490.9%
NormalizeSubtitleCodec(...)62.5%10.37866.66%
GetMediaAttachment(...)90%1010100%
GetMediaStream(...)79.68%167.3312886.61%
NormalizeStreamTitle(...)100%44100%
GetDictionaryValue(...)100%22100%
ParseChannelLayout(...)100%22100%
GetAspectRatio(...)85.29%38.853483.87%
IsClose(...)100%11100%
GetFrameRate(...)60%13.711066.66%
SetAudioRuntimeTicks(...)62.5%8.7877.77%
GetBPSFromTags(...)62.5%10.37866.66%
GetRuntimeSecondsFromTags(...)62.5%10.37866.66%
GetNumberOfBytesFromTags(...)62.5%9.49871.42%
SetSize(...)75%44100%
SetAudioInfoFromTags(...)80%83.657085.93%
GetMultipleMusicBrainzId(...)100%22100%
Split(...)100%44100%
SplitDistinctArtists(...)83.33%6.02691.66%
FetchStudios(...)100%1010100%
FetchGenres(...)100%66100%
GetDictionaryTrackOrDiscNumber(...)50%2.06275%
GetChapterInfo(...)0%4260%
FetchWtvInfo(...)50%564.754233.33%
ExtractTimestamp(...)87.5%8.63878.57%
GetMpegTimestamp(...)0%121.361418.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.Library;
 14using MediaBrowser.Model.Dto;
 15using MediaBrowser.Model.Entities;
 16using MediaBrowser.Model.Globalization;
 17using MediaBrowser.Model.MediaInfo;
 18using Microsoft.Extensions.Logging;
 19
 20namespace MediaBrowser.MediaEncoding.Probing
 21{
 22    /// <summary>
 23    /// Class responsible for normalizing FFprobe output.
 24    /// </summary>
 25    public partial class ProbeResultNormalizer
 26    {
 27        // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
 28        private const int MaxSubtitleDescriptionExtractionLength = 100;
 29
 30        private const string ArtistReplaceValue = " | ";
 31
 2032        private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
 2033        private readonly string[] _webmVideoCodecs = { "av1", "vp8", "vp9" };
 2034        private readonly string[] _webmAudioCodecs = { "opus", "vorbis" };
 35
 36        private readonly ILogger _logger;
 37        private readonly ILocalizationManager _localization;
 38
 39        private string[] _splitWhiteList;
 40
 41        /// <summary>
 42        /// Initializes a new instance of the <see cref="ProbeResultNormalizer"/> class.
 43        /// </summary>
 44        /// <param name="logger">The <see cref="ILogger{ProbeResultNormalizer}"/> for use with the <see cref="ProbeResul
 45        /// <param name="localization">The <see cref="ILocalizationManager"/> for use with the <see cref="ProbeResultNor
 46        public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
 47        {
 2048            _logger = logger;
 2049            _localization = localization;
 2050        }
 51
 552        private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
 553        {
 554            "AC/DC",
 555            "A/T/O/S",
 556            "As/Hi Soundworks",
 557            "Au/Ra",
 558            "Bremer/McCoy",
 559            "b/bqスタヂオ",
 560            "DOV/S",
 561            "DJ'TEKINA//SOMETHING",
 562            "IX/ON",
 563            "J-CORE SLi//CER",
 564            "M(a/u)SH",
 565            "Kaoru/Brilliance",
 566            "signum/ii",
 567            "Richiter(LORB/DUGEM DI BARAT)",
 568            "이달의 소녀 1/3",
 569            "R!N / Gemie",
 570            "LOONA 1/3",
 571            "LOONA / yyxy",
 572            "LOONA / ODD EYE CIRCLE",
 573            "K/DA",
 574            "22/7",
 575            "諭吉佳作/men",
 576            "//dARTH nULL",
 577            "Phantom/Ghost",
 578            "She/Her/Hers",
 579            "5/8erl in Ehr'n",
 580            "Smith/Kotzen",
 581            "We;Na",
 582            "LSR/CITY",
 583        };
 84
 85        /// <summary>
 86        /// Transforms a FFprobe response into its <see cref="MediaInfo"/> equivalent.
 87        /// </summary>
 88        /// <param name="data">The <see cref="InternalMediaInfoResult"/>.</param>
 89        /// <param name="videoType">The <see cref="VideoType"/>.</param>
 90        /// <param name="isAudio">A boolean indicating whether the media is audio.</param>
 91        /// <param name="path">Path to media file.</param>
 92        /// <param name="protocol">Path media protocol.</param>
 93        /// <returns>The <see cref="MediaInfo"/>.</returns>
 94        public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, Med
 95        {
 1096            var info = new MediaInfo
 1097            {
 1098                Path = path,
 1099                Protocol = protocol,
 10100                VideoType = videoType
 10101            };
 102
 10103            FFProbeHelpers.NormalizeFFProbeResult(data);
 10104            SetSize(data, info);
 105
 10106            var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
 107
 10108            info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format))
 10109                .Where(i => i is not null)
 10110                // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know
 10111                .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
 10112                .ToList();
 113
 10114            info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
 10115                .Where(i => i is not null)
 10116                .ToList();
 117
 10118            if (data.Format is not null)
 119            {
 9120                info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
 121
 9122                if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
 123                {
 9124                    info.Bitrate = value;
 125                }
 126            }
 127
 10128            var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 10129            var tagStreamType = isAudio ? CodecType.Audio : CodecType.Video;
 130
 10131            var tagStream = data.Streams?.FirstOrDefault(i => i.CodecType == tagStreamType);
 132
 10133            if (tagStream?.Tags is not null)
 134            {
 48135                foreach (var (key, value) in tagStream.Tags)
 136                {
 17137                    tags[key] = value;
 138                }
 139            }
 140
 10141            if (data.Format?.Tags is not null)
 142            {
 246143                foreach (var (key, value) in data.Format.Tags)
 144                {
 116145                    tags[key] = value;
 146                }
 147            }
 148
 10149            FetchGenres(info, tags);
 150
 10151            info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
 10152            info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
 10153            info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc");
 154
 10155            info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort");
 10156            info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
 10157            info.ShowName = tags.GetValueOrDefault("show_name");
 10158            info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
 159
 160            // Several different forms of retail/premiere date
 10161            info.PremiereDate =
 10162                FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
 10163                FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
 10164                FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
 10165                FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
 10166                FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
 10167                FFProbeHelpers.GetDictionaryDateTime(tags, "date") ??
 10168                FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time");
 169
 170            // Set common metadata for music (audio) and music videos (video)
 10171            info.Album = tags.GetValueOrDefault("album");
 172
 10173            if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
 174            {
 2175                info.Artists = SplitDistinctArtists(artists, new[] { '/', ';' }, false).ToArray();
 176            }
 177            else
 178            {
 8179                var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
 8180                info.Artists = artist is null
 8181                    ? Array.Empty<string>()
 8182                    : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
 183            }
 184
 185            // Guess ProductionYear from PremiereDate if missing
 10186            if (!info.ProductionYear.HasValue && info.PremiereDate.HasValue)
 187            {
 5188                info.ProductionYear = info.PremiereDate.Value.Year;
 189            }
 190
 191            // Set mediaType-specific metadata
 10192            if (isAudio)
 193            {
 2194                SetAudioRuntimeTicks(data, info);
 195
 196                // tags are normally located under data.format, but we've seen some cases with ogg where they're part of
 197                // so let's create a combined list of both
 198
 2199                SetAudioInfoFromTags(info, tags);
 200            }
 201            else
 202            {
 8203                FetchStudios(info, tags, "copyright");
 204
 8205                var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
 8206                if (iTunExtc is not null)
 207                {
 0208                    var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
 209                    // Example
 210                    // mpaa|G|100|For crude humor
 0211                    if (parts.Length > 1)
 212                    {
 0213                        info.OfficialRating = parts[1];
 214
 0215                        if (parts.Length > 3)
 216                        {
 0217                            info.OfficialRatingDescription = parts[3];
 218                        }
 219                    }
 220                }
 221
 8222                var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
 8223                if (iTunXml is not null)
 224                {
 1225                    FetchFromItunesInfo(iTunXml, info);
 226                }
 227
 8228                if (data.Format is not null && !string.IsNullOrEmpty(data.Format.Duration))
 229                {
 7230                    info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCul
 231                }
 232
 8233                FetchWtvInfo(info, data);
 234
 8235                if (data.Chapters is not null)
 236                {
 2237                    info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
 238                }
 239
 8240                ExtractTimestamp(info);
 241
 8242                if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", Strin
 243                {
 0244                    info.Video3DFormat = Video3DFormat.FullSideBySide;
 245                }
 246
 54247                foreach (var mediaStream in info.MediaStreams)
 248                {
 19249                    if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
 250                    {
 3251                        mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Channels);
 252                    }
 253                }
 254
 8255                var videoStreamsBitrate = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).Select(i => i.Bi
 256                // If ffprobe reported the container bitrate as being the same as the video stream bitrate, then it's wr
 8257                if (videoStreamsBitrate == (info.Bitrate ?? 0))
 258                {
 4259                    info.InferTotalBitrate(true);
 260                }
 261            }
 262
 10263            return info;
 264        }
 265
 266        private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
 267        {
 9268            if (string.IsNullOrWhiteSpace(format))
 269            {
 0270                return null;
 271            }
 272
 273            // Input can be a list of multiple, comma-delimited formats - each of them needs to be checked
 9274            var splitFormat = format.Split(',');
 72275            for (var i = 0; i < splitFormat.Length; i++)
 276            {
 277                // Handle MPEG-1 container
 27278                if (string.Equals(splitFormat[i], "mpegvideo", StringComparison.OrdinalIgnoreCase))
 279                {
 0280                    splitFormat[i] = "mpeg";
 281                }
 282
 283                // Handle MPEG-TS container
 27284                else if (string.Equals(splitFormat[i], "mpegts", StringComparison.OrdinalIgnoreCase))
 285                {
 1286                    splitFormat[i] = "ts";
 287                }
 288
 289                // Handle matroska container
 26290                else if (string.Equals(splitFormat[i], "matroska", StringComparison.OrdinalIgnoreCase))
 291                {
 3292                    splitFormat[i] = "mkv";
 293                }
 294
 295                // Handle WebM
 23296                else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
 297                {
 298                    // Limit WebM to supported codecs
 3299                    if (mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contains(s
 3300                        || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringCompa
 301                    {
 2302                        splitFormat[i] = string.Empty;
 303                    }
 304                }
 305            }
 306
 9307            return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
 308        }
 309
 310        private int? GetEstimatedAudioBitrate(string codec, int? channels)
 311        {
 3312            if (!channels.HasValue)
 313            {
 0314                return null;
 315            }
 316
 3317            var channelsValue = channels.Value;
 318
 3319            if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase)
 3320                || string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
 321            {
 322                switch (channelsValue)
 323                {
 324                    case <= 2:
 1325                        return 192000;
 326                    case >= 5:
 0327                        return 320000;
 328                }
 329            }
 330
 2331            if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase)
 2332                || string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
 333            {
 334                switch (channelsValue)
 335                {
 336                    case <= 2:
 0337                        return 192000;
 338                    case >= 5:
 0339                        return 640000;
 340                }
 341            }
 342
 2343            if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase)
 2344                || string.Equals(codec, "alac", StringComparison.OrdinalIgnoreCase))
 345            {
 346                switch (channelsValue)
 347                {
 348                    case <= 2:
 0349                        return 960000;
 350                    case >= 5:
 0351                        return 2880000;
 352                }
 353            }
 354
 2355            return null;
 356        }
 357
 358        private void FetchFromItunesInfo(string xml, MediaInfo info)
 359        {
 360            // Make things simpler and strip out the dtd
 1361            var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
 362
 1363            if (plistIndex != -1)
 364            {
 1365                xml = xml.Substring(plistIndex);
 366            }
 367
 1368            xml = "<?xml version=\"1.0\"?>" + xml;
 369
 370            // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http
 1371            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
 1372            using (var streamReader = new StreamReader(stream))
 373            {
 374                try
 375                {
 1376                    using (var reader = XmlReader.Create(streamReader))
 377                    {
 1378                        reader.MoveToContent();
 1379                        reader.Read();
 380
 381                        // Loop through each element
 4382                        while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 383                        {
 3384                            if (reader.NodeType == XmlNodeType.Element)
 385                            {
 1386                                switch (reader.Name)
 387                                {
 388                                    case "dict":
 1389                                        if (reader.IsEmptyElement)
 390                                        {
 0391                                            reader.Read();
 0392                                            continue;
 393                                        }
 394
 1395                                        using (var subtree = reader.ReadSubtree())
 396                                        {
 1397                                            ReadFromDictNode(subtree, info);
 1398                                        }
 399
 400                                        break;
 401                                    default:
 0402                                        reader.Skip();
 0403                                        break;
 404                                }
 405                            }
 406                            else
 407                            {
 2408                                reader.Read();
 409                            }
 410                        }
 1411                    }
 1412                }
 0413                catch (XmlException)
 414                {
 415                    // I've seen probe examples where the iTunMOVI value is just "<"
 416                    // So we should not allow this to fail the entire probing operation
 0417                }
 418            }
 1419        }
 420
 421        private void ReadFromDictNode(XmlReader reader, MediaInfo info)
 422        {
 1423            string currentKey = null;
 1424            var pairs = new List<NameValuePair>();
 425
 1426            reader.MoveToContent();
 1427            reader.Read();
 428
 429            // Loop through each element
 19430            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 431            {
 18432                if (reader.NodeType == XmlNodeType.Element)
 433                {
 12434                    switch (reader.Name)
 435                    {
 436                        case "key":
 6437                            if (!string.IsNullOrWhiteSpace(currentKey))
 438                            {
 5439                                ProcessPairs(currentKey, pairs, info);
 440                            }
 441
 6442                            currentKey = reader.ReadElementContentAsString();
 6443                            pairs = new List<NameValuePair>();
 6444                            break;
 445                        case "string":
 1446                            var value = reader.ReadElementContentAsString();
 1447                            if (!string.IsNullOrWhiteSpace(value))
 448                            {
 1449                                pairs.Add(new NameValuePair
 1450                                {
 1451                                    Name = value,
 1452                                    Value = value
 1453                                });
 454                            }
 455
 1456                            break;
 457                        case "array":
 5458                            if (reader.IsEmptyElement)
 459                            {
 0460                                reader.Read();
 0461                                continue;
 462                            }
 463
 5464                            using (var subtree = reader.ReadSubtree())
 465                            {
 5466                                if (!string.IsNullOrWhiteSpace(currentKey))
 467                                {
 5468                                    pairs.AddRange(ReadValueArray(subtree));
 469                                }
 5470                            }
 471
 472                            break;
 473                        default:
 0474                            reader.Skip();
 0475                            break;
 476                    }
 477                }
 478                else
 479                {
 6480                    reader.Read();
 481                }
 482            }
 1483        }
 484
 485        private List<NameValuePair> ReadValueArray(XmlReader reader)
 486        {
 5487            var pairs = new List<NameValuePair>();
 488
 5489            reader.MoveToContent();
 5490            reader.Read();
 491
 492            // Loop through each element
 20493            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 494            {
 15495                if (reader.NodeType == XmlNodeType.Element)
 496                {
 5497                    switch (reader.Name)
 498                    {
 499                        case "dict":
 500
 5501                            if (reader.IsEmptyElement)
 502                            {
 0503                                reader.Read();
 0504                                continue;
 505                            }
 506
 5507                            using (var subtree = reader.ReadSubtree())
 508                            {
 5509                                var dict = GetNameValuePair(subtree);
 5510                                if (dict is not null)
 511                                {
 1512                                    pairs.Add(dict);
 513                                }
 5514                            }
 515
 516                            break;
 517                        default:
 0518                            reader.Skip();
 0519                            break;
 520                    }
 521                }
 522                else
 523                {
 10524                    reader.Read();
 525                }
 526            }
 527
 5528            return pairs;
 529        }
 530
 531        private void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
 532        {
 5533            List<BaseItemPerson> peoples = new List<BaseItemPerson>();
 5534            if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
 535            {
 1536                info.Studios = pairs.Select(p => p.Value)
 1537                    .Where(i => !string.IsNullOrWhiteSpace(i))
 1538                    .Distinct(StringComparer.OrdinalIgnoreCase)
 1539                    .ToArray();
 540            }
 4541            else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
 542            {
 0543                foreach (var pair in pairs)
 544                {
 0545                    peoples.Add(new BaseItemPerson
 0546                    {
 0547                        Name = pair.Value,
 0548                        Type = PersonKind.Writer
 0549                    });
 550                }
 551            }
 4552            else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
 553            {
 2554                foreach (var pair in pairs)
 555                {
 0556                    peoples.Add(new BaseItemPerson
 0557                    {
 0558                        Name = pair.Value,
 0559                        Type = PersonKind.Producer
 0560                    });
 561                }
 562            }
 3563            else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
 564            {
 2565                foreach (var pair in pairs)
 566                {
 0567                    peoples.Add(new BaseItemPerson
 0568                    {
 0569                        Name = pair.Value,
 0570                        Type = PersonKind.Director
 0571                    });
 572                }
 573            }
 574
 5575            info.People = peoples.ToArray();
 5576        }
 577
 578        private NameValuePair GetNameValuePair(XmlReader reader)
 579        {
 5580            string name = null;
 5581            string value = null;
 582
 5583            reader.MoveToContent();
 5584            reader.Read();
 585
 586            // Loop through each element
 20587            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 588            {
 15589                if (reader.NodeType == XmlNodeType.Element)
 590                {
 10591                    switch (reader.Name)
 592                    {
 593                        case "key":
 5594                            name = reader.ReadElementContentAsString();
 5595                            break;
 596                        case "string":
 5597                            value = reader.ReadElementContentAsString();
 5598                            break;
 599                        default:
 0600                            reader.Skip();
 0601                            break;
 602                    }
 603                }
 604                else
 605                {
 5606                    reader.Read();
 607                }
 608            }
 609
 5610            if (string.IsNullOrWhiteSpace(name)
 5611                || string.IsNullOrWhiteSpace(value))
 612            {
 4613                return null;
 614            }
 615
 1616            return new NameValuePair
 1617            {
 1618                Name = name,
 1619                Value = value
 1620            };
 621        }
 622
 623        private string NormalizeSubtitleCodec(string codec)
 624        {
 3625            if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
 626            {
 0627                codec = "DVBSUB";
 628            }
 3629            else if (string.Equals(codec, "dvb_teletext", StringComparison.OrdinalIgnoreCase))
 630            {
 0631                codec = "DVBTXT";
 632            }
 3633            else if (string.Equals(codec, "dvd_subtitle", StringComparison.OrdinalIgnoreCase))
 634            {
 1635                codec = "DVDSUB"; // .sub+.idx
 636            }
 2637            else if (string.Equals(codec, "hdmv_pgs_subtitle", StringComparison.OrdinalIgnoreCase))
 638            {
 0639                codec = "PGSSUB"; // .sup
 640            }
 641
 3642            return codec;
 643        }
 644
 645        /// <summary>
 646        /// Converts ffprobe stream info to our MediaAttachment class.
 647        /// </summary>
 648        /// <param name="streamInfo">The stream info.</param>
 649        /// <returns>MediaAttachments.</returns>
 650        private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
 651        {
 23652            if (streamInfo.CodecType != CodecType.Attachment
 23653                && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
 654            {
 21655                return null;
 656            }
 657
 2658            var attachment = new MediaAttachment
 2659            {
 2660                Codec = streamInfo.CodecName,
 2661                Index = streamInfo.Index
 2662            };
 663
 2664            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
 665            {
 2666                attachment.CodecTag = streamInfo.CodecTagString;
 667            }
 668
 2669            if (streamInfo.Tags is not null)
 670            {
 2671                attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
 2672                attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
 2673                attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 674            }
 675
 2676            return attachment;
 677        }
 678
 679        /// <summary>
 680        /// Converts ffprobe stream info to our MediaStream class.
 681        /// </summary>
 682        /// <param name="isAudio">if set to <c>true</c> [is info].</param>
 683        /// <param name="streamInfo">The stream info.</param>
 684        /// <param name="formatInfo">The format info.</param>
 685        /// <returns>MediaStream.</returns>
 686        private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
 687        {
 688            // These are mp4 chapters
 23689            if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
 690            {
 691                // Edit: but these are also sometimes subtitles?
 692                // return null;
 693            }
 694
 23695            var stream = new MediaStream
 23696            {
 23697                Codec = streamInfo.CodecName,
 23698                Profile = streamInfo.Profile,
 23699                Level = streamInfo.Level,
 23700                Index = streamInfo.Index,
 23701                PixelFormat = streamInfo.PixelFormat,
 23702                NalLengthSize = streamInfo.NalLengthSize,
 23703                TimeBase = streamInfo.TimeBase,
 23704                CodecTimeBase = streamInfo.CodecTimeBase,
 23705                IsAVC = streamInfo.IsAvc
 23706            };
 707
 708            // Filter out junk
 23709            if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", Stri
 710            {
 10711                stream.CodecTag = streamInfo.CodecTagString;
 712            }
 713
 23714            if (streamInfo.Tags is not null)
 715            {
 19716                stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
 19717                stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
 19718                stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
 719            }
 720
 23721            if (streamInfo.CodecType == CodecType.Audio)
 722            {
 10723                stream.Type = MediaStreamType.Audio;
 10724                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 10725                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 726
 10727                stream.Channels = streamInfo.Channels;
 728
 10729                if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
 730                {
 10731                    stream.SampleRate = sampleRate;
 732                }
 733
 10734                stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
 735
 10736                if (streamInfo.BitsPerSample > 0)
 737                {
 0738                    stream.BitDepth = streamInfo.BitsPerSample;
 739                }
 10740                else if (streamInfo.BitsPerRawSample > 0)
 741                {
 3742                    stream.BitDepth = streamInfo.BitsPerRawSample;
 743                }
 744
 10745                if (string.IsNullOrEmpty(stream.Title))
 746                {
 747                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 10748                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 10749                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComparis
 750                    {
 3751                        stream.Title = handlerName;
 752                    }
 753                }
 754            }
 13755            else if (streamInfo.CodecType == CodecType.Subtitle)
 756            {
 3757                stream.Type = MediaStreamType.Subtitle;
 3758                stream.Codec = NormalizeSubtitleCodec(stream.Codec);
 3759                stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
 3760                stream.LocalizedDefault = _localization.GetLocalizedString("Default");
 3761                stream.LocalizedForced = _localization.GetLocalizedString("Forced");
 3762                stream.LocalizedExternal = _localization.GetLocalizedString("External");
 3763                stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
 764
 765                // Graphical subtitle may have width and height info
 3766                stream.Width = streamInfo.Width;
 3767                stream.Height = streamInfo.Height;
 768
 3769                if (string.IsNullOrEmpty(stream.Title))
 770                {
 771                    // mp4 missing track title workaround: fall back to handler_name if populated and not the default "S
 3772                    string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
 3773                    if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringCompa
 774                    {
 1775                        stream.Title = handlerName;
 776                    }
 777                }
 778            }
 10779            else if (streamInfo.CodecType == CodecType.Video)
 780            {
 10781                stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
 10782                stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
 783
 10784                stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
 10785                    && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
 786
 10787                if (isAudio
 10788                    || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
 10789                    || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
 10790                    || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
 10791                    || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
 792                {
 2793                    stream.Type = MediaStreamType.EmbeddedImage;
 794                }
 8795                else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 796                {
 797                    // How to differentiate between video and embedded image?
 798                    // The only difference I've seen thus far is presence of codec tag, also embedded images have high (
 0799                    if (!string.IsNullOrWhiteSpace(stream.CodecTag))
 800                    {
 0801                        stream.Type = MediaStreamType.Video;
 802                    }
 803                    else
 804                    {
 0805                        stream.Type = MediaStreamType.EmbeddedImage;
 806                    }
 807                }
 808                else
 809                {
 8810                    stream.Type = MediaStreamType.Video;
 811                }
 812
 10813                stream.Width = streamInfo.Width;
 10814                stream.Height = streamInfo.Height;
 10815                stream.AspectRatio = GetAspectRatio(streamInfo);
 816
 10817                if (streamInfo.BitsPerSample > 0)
 818                {
 0819                    stream.BitDepth = streamInfo.BitsPerSample;
 820                }
 10821                else if (streamInfo.BitsPerRawSample > 0)
 822                {
 9823                    stream.BitDepth = streamInfo.BitsPerRawSample;
 824                }
 825
 10826                if (!stream.BitDepth.HasValue)
 827                {
 1828                    if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
 829                    {
 1830                        if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
 1831                            || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
 832                        {
 1833                            stream.BitDepth = 8;
 834                        }
 0835                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase
 0836                                 || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreC
 837                        {
 0838                            stream.BitDepth = 10;
 839                        }
 0840                        else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase
 0841                                 || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreC
 842                        {
 0843                            stream.BitDepth = 12;
 844                        }
 845                    }
 846                }
 847
 848                // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIg
 849                //    string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
 850                //    string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
 851
 852                // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
 10853                stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreC
 854
 10855                if (streamInfo.Refs > 0)
 856                {
 10857                    stream.RefFrames = streamInfo.Refs;
 858                }
 859
 10860                if (!string.IsNullOrEmpty(streamInfo.ColorRange))
 861                {
 4862                    stream.ColorRange = streamInfo.ColorRange;
 863                }
 864
 10865                if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
 866                {
 4867                    stream.ColorSpace = streamInfo.ColorSpace;
 868                }
 869
 10870                if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
 871                {
 2872                    stream.ColorTransfer = streamInfo.ColorTransfer;
 873                }
 874
 10875                if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
 876                {
 2877                    stream.ColorPrimaries = streamInfo.ColorPrimaries;
 878                }
 879
 10880                if (streamInfo.SideDataList is not null)
 881                {
 6882                    foreach (var data in streamInfo.SideDataList)
 883                    {
 884                        // Parse Dolby Vision metadata from side_data
 2885                        if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnore
 886                        {
 1887                            stream.DvVersionMajor = data.DvVersionMajor;
 1888                            stream.DvVersionMinor = data.DvVersionMinor;
 1889                            stream.DvProfile = data.DvProfile;
 1890                            stream.DvLevel = data.DvLevel;
 1891                            stream.RpuPresentFlag = data.RpuPresentFlag;
 1892                            stream.ElPresentFlag = data.ElPresentFlag;
 1893                            stream.BlPresentFlag = data.BlPresentFlag;
 1894                            stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
 895                        }
 896
 897                        // Parse video rotation metadata from side_data
 1898                        else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
 899                        {
 1900                            stream.Rotation = data.Rotation;
 901                        }
 902                    }
 903                }
 904            }
 0905            else if (streamInfo.CodecType == CodecType.Data)
 906            {
 0907                stream.Type = MediaStreamType.Data;
 908            }
 909            else
 910            {
 0911                return null;
 912            }
 913
 914            // Get stream bitrate
 23915            var bitrate = 0;
 916
 23917            if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
 918            {
 12919                bitrate = value;
 920            }
 921
 922            // The bitrate info of FLAC musics and some videos is included in formatInfo.
 23923            if (bitrate == 0
 23924                && formatInfo is not null
 23925                && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
 926            {
 927                // If the stream info doesn't have a bitrate get the value from the media format info
 6928                if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
 929                {
 6930                    bitrate = value;
 931                }
 932            }
 933
 23934            if (bitrate > 0)
 935            {
 18936                stream.BitRate = bitrate;
 937            }
 938
 939            // Extract bitrate info from tag "BPS" if possible.
 23940            if (!stream.BitRate.HasValue
 23941                && (streamInfo.CodecType == CodecType.Audio
 23942                    || streamInfo.CodecType == CodecType.Video))
 943            {
 5944                var bps = GetBPSFromTags(streamInfo);
 5945                if (bps > 0)
 946                {
 0947                    stream.BitRate = bps;
 948                }
 949                else
 950                {
 951                    // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
 5952                    var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
 5953                    var bytes = GetNumberOfBytesFromTags(streamInfo);
 5954                    if (durationInSeconds is not null && bytes is not null)
 955                    {
 0956                        bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
 0957                        if (bps > 0)
 958                        {
 0959                            stream.BitRate = bps;
 960                        }
 961                    }
 962                }
 963            }
 964
 23965            var disposition = streamInfo.Disposition;
 23966            if (disposition is not null)
 967            {
 23968                if (disposition.GetValueOrDefault("default") == 1)
 969                {
 13970                    stream.IsDefault = true;
 971                }
 972
 23973                if (disposition.GetValueOrDefault("forced") == 1)
 974                {
 0975                    stream.IsForced = true;
 976                }
 977
 23978                if (disposition.GetValueOrDefault("hearing_impaired") == 1)
 979                {
 1980                    stream.IsHearingImpaired = true;
 981                }
 982            }
 983
 23984            NormalizeStreamTitle(stream);
 985
 23986            return stream;
 987        }
 988
 989        private void NormalizeStreamTitle(MediaStream stream)
 990        {
 23991            if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
 23992                || stream.Type == MediaStreamType.EmbeddedImage)
 993            {
 2994                stream.Title = null;
 995            }
 23996        }
 997
 998        /// <summary>
 999        /// Gets a string from an FFProbeResult tags dictionary.
 1000        /// </summary>
 1001        /// <param name="tags">The tags.</param>
 1002        /// <param name="key">The key.</param>
 1003        /// <returns>System.String.</returns>
 1004        private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
 1005        {
 1061006            if (tags is null)
 1007            {
 31008                return null;
 1009            }
 1010
 1031011            tags.TryGetValue(key, out var val);
 1012
 1031013            return val;
 1014        }
 1015
 1016        private string ParseChannelLayout(string input)
 1017        {
 101018            if (string.IsNullOrEmpty(input))
 1019            {
 11020                return null;
 1021            }
 1022
 91023            return input.AsSpan().LeftPart('(').ToString();
 1024        }
 1025
 1026        private string GetAspectRatio(MediaStreamInfo info)
 1027        {
 101028            var original = info.DisplayAspectRatio;
 1029
 101030            var parts = (original ?? string.Empty).Split(':');
 101031            if (!(parts.Length == 2
 101032                    && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
 101033                    && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
 101034                    && width > 0
 101035                    && height > 0))
 1036            {
 31037                width = info.Width;
 31038                height = info.Height;
 1039            }
 1040
 101041            if (width > 0 && height > 0)
 1042            {
 101043                double ratio = width;
 101044                ratio /= height;
 1045
 101046                if (IsClose(ratio, 1.777777778, .03))
 1047                {
 51048                    return "16:9";
 1049                }
 1050
 51051                if (IsClose(ratio, 1.3333333333, .05))
 1052                {
 11053                    return "4:3";
 1054                }
 1055
 41056                if (IsClose(ratio, 1.41))
 1057                {
 01058                    return "1.41:1";
 1059                }
 1060
 41061                if (IsClose(ratio, 1.5))
 1062                {
 11063                    return "1.5:1";
 1064                }
 1065
 31066                if (IsClose(ratio, 1.6))
 1067                {
 01068                    return "1.6:1";
 1069                }
 1070
 31071                if (IsClose(ratio, 1.66666666667))
 1072                {
 01073                    return "5:3";
 1074                }
 1075
 31076                if (IsClose(ratio, 1.85, .02))
 1077                {
 01078                    return "1.85:1";
 1079                }
 1080
 31081                if (IsClose(ratio, 2.35, .025))
 1082                {
 01083                    return "2.35:1";
 1084                }
 1085
 31086                if (IsClose(ratio, 2.4, .025))
 1087                {
 11088                    return "2.40:1";
 1089                }
 1090            }
 1091
 21092            return original;
 1093        }
 1094
 1095        private bool IsClose(double d1, double d2, double variance = .005)
 1096        {
 381097            return Math.Abs(d1 - d2) <= variance;
 1098        }
 1099
 1100        /// <summary>
 1101        /// Gets a frame rate from a string value in ffprobe output
 1102        /// This could be a number or in the format of 2997/125.
 1103        /// </summary>
 1104        /// <param name="value">The value.</param>
 1105        /// <returns>System.Nullable{System.Single}.</returns>
 1106        internal static float? GetFrameRate(ReadOnlySpan<char> value)
 1107        {
 291108            if (value.IsEmpty)
 1109            {
 01110                return null;
 1111            }
 1112
 291113            int index = value.IndexOf('/');
 291114            if (index == -1)
 1115            {
 01116                return null;
 1117            }
 1118
 291119            if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
 291120                || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var div
 1121            {
 01122                return null;
 1123            }
 1124
 291125            return divisor == 0f ? null : dividend / divisor;
 1126        }
 1127
 1128        private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
 1129        {
 1130            // Get the first info stream
 21131            var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
 21132            if (stream is null)
 1133            {
 01134                return;
 1135            }
 1136
 1137            // Get duration from stream properties
 21138            var duration = stream.Duration;
 1139
 1140            // If it's not there go into format properties
 21141            if (string.IsNullOrEmpty(duration))
 1142            {
 01143                duration = result.Format.Duration;
 1144            }
 1145
 1146            // If we got something, parse it
 21147            if (!string.IsNullOrEmpty(duration))
 1148            {
 21149                data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
 1150            }
 21151        }
 1152
 1153        private int? GetBPSFromTags(MediaStreamInfo streamInfo)
 1154        {
 51155            if (streamInfo?.Tags is null)
 1156            {
 01157                return null;
 1158            }
 1159
 51160            var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
 51161            if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
 1162            {
 01163                return parsedBps;
 1164            }
 1165
 51166            return null;
 1167        }
 1168
 1169        private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
 1170        {
 51171            if (streamInfo?.Tags is null)
 1172            {
 01173                return null;
 1174            }
 1175
 51176            var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "D
 51177            if (TimeSpan.TryParse(duration, out var parsedDuration))
 1178            {
 01179                return parsedDuration.TotalSeconds;
 1180            }
 1181
 51182            return null;
 1183        }
 1184
 1185        private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
 1186        {
 51187            if (streamInfo?.Tags is null)
 1188            {
 01189                return null;
 1190            }
 1191
 51192            var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
 51193                                ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
 51194            if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
 1195            {
 01196                return parsedBytes;
 1197            }
 1198
 51199            return null;
 1200        }
 1201
 1202        private void SetSize(InternalMediaInfoResult data, MediaInfo info)
 1203        {
 101204            if (data.Format is null)
 1205            {
 11206                return;
 1207            }
 1208
 91209            info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.Invaria
 91210        }
 1211
 1212        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
 1213        {
 21214            var people = new List<BaseItemPerson>();
 21215            if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
 1216            {
 121217                foreach (var person in Split(composer, false))
 1218                {
 41219                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
 1220                }
 1221            }
 1222
 21223            if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
 1224            {
 01225                foreach (var person in Split(conductor, false))
 1226                {
 01227                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
 1228                }
 1229            }
 1230
 21231            if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
 1232            {
 81233                foreach (var person in Split(lyricist, false))
 1234                {
 21235                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
 1236                }
 1237            }
 1238
 21239            if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
 1240            {
 501241                foreach (var person in Split(performer, false))
 1242                {
 231243                    Match match = PerformerRegex().Match(person);
 1244
 1245                    // If the performer doesn't have any instrument/role associated, it won't match. In that case, chanc
 231246                    if (match.Success)
 1247                    {
 221248                        people.Add(new BaseItemPerson
 221249                        {
 221250                            Name = match.Groups["name"].Value,
 221251                            Type = PersonKind.Actor,
 221252                            Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
 221253                        });
 1254                    }
 1255                }
 1256            }
 1257
 1258            // In cases where there isn't sufficient information as to which role a writer performed on a recording, tag
 21259            if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
 1260            {
 01261                foreach (var person in Split(writer, false))
 1262                {
 01263                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
 1264                }
 1265            }
 1266
 21267            if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
 1268            {
 121269                foreach (var person in Split(arranger, false))
 1270                {
 41271                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
 1272                }
 1273            }
 1274
 21275            if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
 1276            {
 01277                foreach (var person in Split(engineer, false))
 1278                {
 01279                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
 1280                }
 1281            }
 1282
 21283            if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
 1284            {
 81285                foreach (var person in Split(mixer, false))
 1286                {
 21287                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
 1288                }
 1289            }
 1290
 21291            if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
 1292            {
 01293                foreach (var person in Split(remixer, false))
 1294                {
 01295                    people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
 1296                }
 1297            }
 1298
 21299            audio.People = people.ToArray();
 1300
 1301            // Set album artist
 21302            var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
 21303            audio.AlbumArtists = albumArtist is not null
 21304                ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
 21305                : Array.Empty<string>();
 1306
 1307            // Set album artist to artist if empty
 21308            if (audio.AlbumArtists.Length == 0)
 1309            {
 01310                audio.AlbumArtists = audio.Artists;
 1311            }
 1312
 1313            // Track number
 21314            audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
 1315
 1316            // Disc number
 21317            audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
 1318
 1319            // There's several values in tags may or may not be present
 21320            FetchStudios(audio, tags, "organization");
 21321            FetchStudios(audio, tags, "ensemble");
 21322            FetchStudios(audio, tags, "publisher");
 21323            FetchStudios(audio, tags, "label");
 1324
 1325            // These support multiple values, but for now we only store the first.
 21326            var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
 21327                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
 21328            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
 1329
 21330            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
 21331                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
 21332            audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
 1333
 21334            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
 21335                ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
 21336            audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
 1337
 21338            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
 21339                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
 21340            audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
 1341
 21342            mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
 21343                 ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
 21344            audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
 21345        }
 1346
 1347        private string GetMultipleMusicBrainzId(string value)
 1348        {
 201349            if (string.IsNullOrWhiteSpace(value))
 1350            {
 101351                return null;
 1352            }
 1353
 101354            return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
 101355                .FirstOrDefault();
 1356        }
 1357
 1358        /// <summary>
 1359        /// Splits the specified val.
 1360        /// </summary>
 1361        /// <param name="val">The val.</param>
 1362        /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
 1363        /// <returns>System.String[][].</returns>
 1364        private string[] Split(string val, bool allowCommaDelimiter)
 1365        {
 1366            // Only use the comma as a delimiter if there are no slashes or pipes.
 1367            // We want to be careful not to split names that have commas in them
 141368            return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
 141369                val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
 141370                val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1371        }
 1372
 1373        private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
 1374        {
 51375            if (splitFeaturing)
 1376            {
 31377                val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
 31378                    .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
 1379            }
 1380
 51381            var artistsFound = new List<string>();
 1382
 3001383            foreach (var whitelistArtist in SplitWhitelist)
 1384            {
 1451385                var originalVal = val;
 1451386                val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
 1387
 1451388                if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
 1389                {
 01390                    artistsFound.Add(whitelistArtist);
 1391                }
 1392            }
 1393
 51394            var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 1395
 51396            artistsFound.AddRange(artists);
 51397            return artistsFound.DistinctNames();
 1398        }
 1399
 1400        /// <summary>
 1401        /// Gets the studios from the tags collection.
 1402        /// </summary>
 1403        /// <param name="info">The info.</param>
 1404        /// <param name="tags">The tags.</param>
 1405        /// <param name="tagName">Name of the tag.</param>
 1406        private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
 1407        {
 161408            var val = tags.GetValueOrDefault(tagName);
 1409
 161410            if (string.IsNullOrEmpty(val))
 1411            {
 141412                return;
 1413            }
 1414
 21415            var studios = Split(val, true);
 21416            var studioList = new List<string>();
 1417
 81418            foreach (var studio in studios)
 1419            {
 21420                if (string.IsNullOrWhiteSpace(studio))
 1421                {
 1422                    continue;
 1423                }
 1424
 1425                // Don't add artist/album artist name to studios, even if it's listed there
 21426                if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
 21427                    || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
 1428                {
 1429                    continue;
 1430                }
 1431
 21432                studioList.Add(studio);
 1433            }
 1434
 21435            info.Studios = studioList
 21436                .Distinct(StringComparer.OrdinalIgnoreCase)
 21437                .ToArray();
 21438        }
 1439
 1440        /// <summary>
 1441        /// Gets the genres from the tags collection.
 1442        /// </summary>
 1443        /// <param name="info">The information.</param>
 1444        /// <param name="tags">The tags.</param>
 1445        private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
 1446        {
 101447            var genreVal = tags.GetValueOrDefault("genre");
 101448            if (string.IsNullOrEmpty(genreVal))
 1449            {
 81450                return;
 1451            }
 1452
 21453            var genres = new List<string>(info.Genres);
 201454            foreach (var genre in Split(genreVal, true))
 1455            {
 81456                if (string.IsNullOrWhiteSpace(genre))
 1457                {
 1458                    continue;
 1459                }
 1460
 81461                genres.Add(genre);
 1462            }
 1463
 21464            info.Genres = genres
 21465                .Distinct(StringComparer.OrdinalIgnoreCase)
 21466                .ToArray();
 21467        }
 1468
 1469        /// <summary>
 1470        /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
 1471        /// </summary>
 1472        /// <param name="tags">The tags.</param>
 1473        /// <param name="tagName">Name of the tag.</param>
 1474        /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
 1475        private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
 1476        {
 41477            var disc = tags.GetValueOrDefault(tagName);
 1478
 41479            if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
 1480            {
 41481                return discNum;
 1482            }
 1483
 01484            return null;
 1485        }
 1486
 1487        private static ChapterInfo GetChapterInfo(MediaChapter chapter)
 1488        {
 01489            var info = new ChapterInfo();
 1490
 01491            if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
 1492            {
 01493                info.Name = name;
 1494            }
 1495
 1496            // Limit accuracy to milliseconds to match xml saving
 01497            var secondsString = chapter.StartTime;
 1498
 01499            if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
 1500            {
 01501                var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
 01502                info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
 1503            }
 1504
 01505            return info;
 1506        }
 1507
 1508        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
 1509        {
 81510            var tags = data.Format?.Tags;
 1511
 81512            if (tags is null)
 1513            {
 31514                return;
 1515            }
 1516
 51517            if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
 1518            {
 01519                var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries | StringSpli
 1520
 1521                // If this is empty then don't overwrite genres that might have been fetched earlier
 01522                if (genreList.Length > 0)
 1523                {
 01524                    video.Genres = genreList;
 1525                }
 1526            }
 1527
 51528            if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRati
 1529            {
 01530                video.OfficialRating = officialRating;
 1531            }
 1532
 51533            if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
 1534            {
 01535                video.People = Array.ConvertAll(
 01536                    people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntr
 01537                    i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
 1538            }
 1539
 51540            if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, Cul
 1541            {
 01542                video.ProductionYear = parsedYear;
 1543            }
 1544
 1545            // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1546            // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
 51547            if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(y
 1548            {
 01549                video.PremiereDate = parsedDate;
 1550            }
 1551
 51552            var description = tags.GetValueOrDefault("WM/SubTitleDescription");
 1553
 51554            var subTitle = tags.GetValueOrDefault("WM/SubTitle");
 1555
 1556            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
 1557
 1558            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, ex
 1559            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
 1560            // OR -> COMMENT. SUBTITLE: DESCRIPTION
 1561            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the 
 1562            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in t
 51563            if (string.IsNullOrWhiteSpace(subTitle)
 51564                && !string.IsNullOrWhiteSpace(description)
 51565                && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains
 1566            {
 01567                string[] descriptionParts = description.Split(':');
 01568                if (descriptionParts.Length > 0)
 1569                {
 01570                    string subtitle = descriptionParts[0];
 1571                    try
 1572                    {
 1573                        // Check if it contains a episode number and season number
 01574                        if (subtitle.Contains('/', StringComparison.Ordinal))
 1575                        {
 01576                            string[] subtitleParts = subtitle.Split(' ');
 01577                            string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Spl
 01578                            video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
 1579                            // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
 1580
 1581                            // Skip the numbers, concatenate the rest, trim and set as new description
 01582                            description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1583                        }
 01584                        else if (subtitle.Contains('.', StringComparison.Ordinal))
 1585                        {
 01586                            var subtitleParts = subtitle.Split('.');
 01587                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1588                        }
 1589                        else
 1590                        {
 01591                            description = subtitle.Trim();
 1592                        }
 01593                    }
 01594                    catch (Exception ex)
 1595                    {
 01596                        _logger.LogError(ex, "Error while parsing subtitle field");
 1597
 1598                        // Fallback to default parsing
 01599                        if (subtitle.Contains('.', StringComparison.Ordinal))
 1600                        {
 01601                            var subtitleParts = subtitle.Split('.');
 01602                            description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
 1603                        }
 1604                        else
 1605                        {
 01606                            description = subtitle.Trim();
 1607                        }
 01608                    }
 1609                }
 1610            }
 1611
 51612            if (!string.IsNullOrWhiteSpace(description))
 1613            {
 01614                video.Overview = description;
 1615            }
 51616        }
 1617
 1618        private void ExtractTimestamp(MediaInfo video)
 1619        {
 81620            if (video.VideoType != VideoType.VideoFile)
 1621            {
 01622                return;
 1623            }
 1624
 81625            if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
 81626                && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
 81627                && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
 1628            {
 71629                return;
 1630            }
 1631
 1632            try
 1633            {
 11634                video.Timestamp = GetMpegTimestamp(video.Path);
 01635                _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
 01636            }
 11637            catch (Exception ex)
 1638            {
 11639                video.Timestamp = null;
 11640                _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
 11641            }
 11642        }
 1643
 1644        // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
 1645        private TransportStreamTimestamp GetMpegTimestamp(string path)
 1646        {
 11647            var packetBuffer = new byte[197];
 1648
 11649            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
 1650            {
 01651                fs.Read(packetBuffer);
 01652            }
 1653
 01654            if (packetBuffer[0] == 71)
 1655            {
 01656                return TransportStreamTimestamp.None;
 1657            }
 1658
 01659            if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
 1660            {
 01661                return TransportStreamTimestamp.None;
 1662            }
 1663
 01664            if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
 1665            {
 01666                return TransportStreamTimestamp.Zero;
 1667            }
 1668
 01669            return TransportStreamTimestamp.Valid;
 1670        }
 1671
 1672        [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
 1673        private static partial Regex PerformerRegex();
 1674    }
 1675}

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)
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)