ProbeResultNormalizer.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  1. #nullable disable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Xml;
  10. using Jellyfin.Data.Enums;
  11. using Jellyfin.Extensions;
  12. using MediaBrowser.Controller.Extensions;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Globalization;
  17. using MediaBrowser.Model.MediaInfo;
  18. using Microsoft.Extensions.Logging;
  19. namespace MediaBrowser.MediaEncoding.Probing
  20. {
  21. /// <summary>
  22. /// Class responsible for normalizing FFprobe output.
  23. /// </summary>
  24. public partial class ProbeResultNormalizer
  25. {
  26. // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  27. private const int MaxSubtitleDescriptionExtractionLength = 100;
  28. private const string ArtistReplaceValue = " | ";
  29. private static readonly char[] _basicDelimiters = ['/', ';'];
  30. private static readonly char[] _nameDelimiters = [.. _basicDelimiters, '|', '\\'];
  31. private static readonly char[] _genreDelimiters = [.. _basicDelimiters, ','];
  32. private static readonly string[] _webmVideoCodecs = ["av1", "vp8", "vp9"];
  33. private static readonly string[] _webmAudioCodecs = ["opus", "vorbis"];
  34. private readonly ILogger _logger;
  35. private readonly ILocalizationManager _localization;
  36. private string[] _splitWhiteList;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="ProbeResultNormalizer"/> class.
  39. /// </summary>
  40. /// <param name="logger">The <see cref="ILogger{ProbeResultNormalizer}"/> for use with the <see cref="ProbeResultNormalizer"/> instance.</param>
  41. /// <param name="localization">The <see cref="ILocalizationManager"/> for use with the <see cref="ProbeResultNormalizer"/> instance.</param>
  42. public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
  43. {
  44. _logger = logger;
  45. _localization = localization;
  46. }
  47. private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
  48. {
  49. "AC/DC",
  50. "A/T/O/S",
  51. "As/Hi Soundworks",
  52. "Au/Ra",
  53. "Bremer/McCoy",
  54. "b/bqスタヂオ",
  55. "DOV/S",
  56. "DJ'TEKINA//SOMETHING",
  57. "IX/ON",
  58. "J-CORE SLi//CER",
  59. "M(a/u)SH",
  60. "Kaoru/Brilliance",
  61. "signum/ii",
  62. "Richiter(LORB/DUGEM DI BARAT)",
  63. "이달의 소녀 1/3",
  64. "R!N / Gemie",
  65. "LOONA 1/3",
  66. "LOONA / yyxy",
  67. "LOONA / ODD EYE CIRCLE",
  68. "K/DA",
  69. "22/7",
  70. "諭吉佳作/men",
  71. "//dARTH nULL",
  72. "Phantom/Ghost",
  73. "She/Her/Hers",
  74. "5/8erl in Ehr'n",
  75. "Smith/Kotzen",
  76. "We;Na",
  77. "LSR/CITY",
  78. };
  79. /// <summary>
  80. /// Transforms a FFprobe response into its <see cref="MediaInfo"/> equivalent.
  81. /// </summary>
  82. /// <param name="data">The <see cref="InternalMediaInfoResult"/>.</param>
  83. /// <param name="videoType">The <see cref="VideoType"/>.</param>
  84. /// <param name="isAudio">A boolean indicating whether the media is audio.</param>
  85. /// <param name="path">Path to media file.</param>
  86. /// <param name="protocol">Path media protocol.</param>
  87. /// <returns>The <see cref="MediaInfo"/>.</returns>
  88. public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, MediaProtocol protocol)
  89. {
  90. var info = new MediaInfo
  91. {
  92. Path = path,
  93. Protocol = protocol,
  94. VideoType = videoType
  95. };
  96. FFProbeHelpers.NormalizeFFProbeResult(data);
  97. SetSize(data, info);
  98. var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
  99. var internalFrames = data.Frames ?? Array.Empty<MediaFrameInfo>();
  100. info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format, internalFrames))
  101. .Where(i => i is not null)
  102. // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know how to handle them
  103. .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
  104. .ToList();
  105. info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
  106. .Where(i => i is not null)
  107. .ToList();
  108. if (data.Format is not null)
  109. {
  110. info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
  111. if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
  112. {
  113. info.Bitrate = value;
  114. }
  115. }
  116. var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  117. var tagStreamType = isAudio ? CodecType.Audio : CodecType.Video;
  118. var tagStream = data.Streams?.FirstOrDefault(i => i.CodecType == tagStreamType);
  119. if (tagStream?.Tags is not null)
  120. {
  121. foreach (var (key, value) in tagStream.Tags)
  122. {
  123. tags[key] = value;
  124. }
  125. }
  126. if (data.Format?.Tags is not null)
  127. {
  128. foreach (var (key, value) in data.Format.Tags)
  129. {
  130. tags[key] = value;
  131. }
  132. }
  133. FetchGenres(info, tags);
  134. info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
  135. info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
  136. info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc");
  137. info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort");
  138. info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
  139. info.ShowName = tags.GetValueOrDefault("show_name");
  140. info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
  141. // Several different forms of retail/premiere date
  142. info.PremiereDate =
  143. FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
  144. FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
  145. FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
  146. FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
  147. FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
  148. FFProbeHelpers.GetDictionaryDateTime(tags, "date") ??
  149. FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time");
  150. // Set common metadata for music (audio) and music videos (video)
  151. info.Album = tags.GetValueOrDefault("album");
  152. if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
  153. {
  154. info.Artists = SplitDistinctArtists(artists, _basicDelimiters, false).ToArray();
  155. }
  156. else
  157. {
  158. var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
  159. info.Artists = artist is null
  160. ? Array.Empty<string>()
  161. : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
  162. }
  163. // Guess ProductionYear from PremiereDate if missing
  164. if (!info.ProductionYear.HasValue && info.PremiereDate.HasValue)
  165. {
  166. info.ProductionYear = info.PremiereDate.Value.Year;
  167. }
  168. // Set mediaType-specific metadata
  169. if (isAudio)
  170. {
  171. SetAudioRuntimeTicks(data, info);
  172. // tags are normally located under data.format, but we've seen some cases with ogg where they're part of the info stream
  173. // so let's create a combined list of both
  174. SetAudioInfoFromTags(info, tags);
  175. }
  176. else
  177. {
  178. FetchStudios(info, tags, "copyright");
  179. var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
  180. if (iTunExtc is not null)
  181. {
  182. var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
  183. // Example
  184. // mpaa|G|100|For crude humor
  185. if (parts.Length > 1)
  186. {
  187. info.OfficialRating = parts[1];
  188. if (parts.Length > 3)
  189. {
  190. info.OfficialRatingDescription = parts[3];
  191. }
  192. }
  193. }
  194. var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
  195. if (iTunXml is not null)
  196. {
  197. FetchFromItunesInfo(iTunXml, info);
  198. }
  199. if (data.Format is not null && !string.IsNullOrEmpty(data.Format.Duration))
  200. {
  201. info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCulture)).Ticks;
  202. }
  203. FetchWtvInfo(info, data);
  204. if (data.Chapters is not null)
  205. {
  206. info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
  207. }
  208. ExtractTimestamp(info);
  209. if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", StringComparison.OrdinalIgnoreCase))
  210. {
  211. info.Video3DFormat = Video3DFormat.FullSideBySide;
  212. }
  213. foreach (var mediaStream in info.MediaStreams)
  214. {
  215. if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
  216. {
  217. mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Channels);
  218. }
  219. }
  220. var videoStreamsBitrate = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).Select(i => i.BitRate ?? 0).Sum();
  221. // If ffprobe reported the container bitrate as being the same as the video stream bitrate, then it's wrong
  222. if (videoStreamsBitrate == (info.Bitrate ?? 0))
  223. {
  224. info.InferTotalBitrate(true);
  225. }
  226. }
  227. return info;
  228. }
  229. private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
  230. {
  231. if (string.IsNullOrWhiteSpace(format))
  232. {
  233. return null;
  234. }
  235. // Input can be a list of multiple, comma-delimited formats - each of them needs to be checked
  236. var splitFormat = format.Split(',');
  237. for (var i = 0; i < splitFormat.Length; i++)
  238. {
  239. // Handle MPEG-1 container
  240. if (string.Equals(splitFormat[i], "mpegvideo", StringComparison.OrdinalIgnoreCase))
  241. {
  242. splitFormat[i] = "mpeg";
  243. }
  244. // Handle MPEG-TS container
  245. else if (string.Equals(splitFormat[i], "mpegts", StringComparison.OrdinalIgnoreCase))
  246. {
  247. splitFormat[i] = "ts";
  248. }
  249. // Handle matroska container
  250. else if (string.Equals(splitFormat[i], "matroska", StringComparison.OrdinalIgnoreCase))
  251. {
  252. splitFormat[i] = "mkv";
  253. }
  254. // Handle WebM
  255. else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
  256. {
  257. // Limit WebM to supported codecs
  258. if (mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contains(stream.Codec, StringComparison.OrdinalIgnoreCase))
  259. || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringComparison.OrdinalIgnoreCase))))
  260. {
  261. splitFormat[i] = string.Empty;
  262. }
  263. }
  264. }
  265. return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
  266. }
  267. private static int? GetEstimatedAudioBitrate(string codec, int? channels)
  268. {
  269. if (!channels.HasValue)
  270. {
  271. return null;
  272. }
  273. var channelsValue = channels.Value;
  274. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase)
  275. || string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  276. {
  277. switch (channelsValue)
  278. {
  279. case <= 2:
  280. return 192000;
  281. case >= 5:
  282. return 320000;
  283. }
  284. }
  285. if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase)
  286. || string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  287. {
  288. switch (channelsValue)
  289. {
  290. case <= 2:
  291. return 192000;
  292. case >= 5:
  293. return 640000;
  294. }
  295. }
  296. if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase)
  297. || string.Equals(codec, "alac", StringComparison.OrdinalIgnoreCase))
  298. {
  299. switch (channelsValue)
  300. {
  301. case <= 2:
  302. return 960000;
  303. case >= 5:
  304. return 2880000;
  305. }
  306. }
  307. return null;
  308. }
  309. private void FetchFromItunesInfo(string xml, MediaInfo info)
  310. {
  311. // Make things simpler and strip out the dtd
  312. var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
  313. if (plistIndex != -1)
  314. {
  315. xml = xml.Substring(plistIndex);
  316. }
  317. xml = "<?xml version=\"1.0\"?>" + xml;
  318. // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>cast</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Blender Foundation</string>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Janus Bager Kristensen</string>\n\t\t</dict>\n\t</array>\n\t<key>directors</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Sacha Goedegebure</string>\n\t\t</dict>\n\t</array>\n\t<key>studio</key>\n\t<string>Blender Foundation</string>\n</dict>\n</plist>\n
  319. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
  320. using (var streamReader = new StreamReader(stream))
  321. {
  322. try
  323. {
  324. using (var reader = XmlReader.Create(streamReader))
  325. {
  326. reader.MoveToContent();
  327. reader.Read();
  328. // Loop through each element
  329. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  330. {
  331. if (reader.NodeType == XmlNodeType.Element)
  332. {
  333. switch (reader.Name)
  334. {
  335. case "dict":
  336. if (reader.IsEmptyElement)
  337. {
  338. reader.Read();
  339. continue;
  340. }
  341. using (var subtree = reader.ReadSubtree())
  342. {
  343. ReadFromDictNode(subtree, info);
  344. }
  345. break;
  346. default:
  347. reader.Skip();
  348. break;
  349. }
  350. }
  351. else
  352. {
  353. reader.Read();
  354. }
  355. }
  356. }
  357. }
  358. catch (XmlException)
  359. {
  360. // I've seen probe examples where the iTunMOVI value is just "<"
  361. // So we should not allow this to fail the entire probing operation
  362. }
  363. }
  364. }
  365. private void ReadFromDictNode(XmlReader reader, MediaInfo info)
  366. {
  367. string currentKey = null;
  368. var pairs = new List<NameValuePair>();
  369. reader.MoveToContent();
  370. reader.Read();
  371. // Loop through each element
  372. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  373. {
  374. if (reader.NodeType == XmlNodeType.Element)
  375. {
  376. switch (reader.Name)
  377. {
  378. case "key":
  379. if (!string.IsNullOrWhiteSpace(currentKey))
  380. {
  381. ProcessPairs(currentKey, pairs, info);
  382. }
  383. currentKey = reader.ReadElementContentAsString();
  384. pairs = new List<NameValuePair>();
  385. break;
  386. case "string":
  387. var value = reader.ReadElementContentAsString();
  388. if (!string.IsNullOrWhiteSpace(value))
  389. {
  390. pairs.Add(new NameValuePair
  391. {
  392. Name = value,
  393. Value = value
  394. });
  395. }
  396. break;
  397. case "array":
  398. if (reader.IsEmptyElement)
  399. {
  400. reader.Read();
  401. continue;
  402. }
  403. using (var subtree = reader.ReadSubtree())
  404. {
  405. if (!string.IsNullOrWhiteSpace(currentKey))
  406. {
  407. pairs.AddRange(ReadValueArray(subtree));
  408. }
  409. }
  410. break;
  411. default:
  412. reader.Skip();
  413. break;
  414. }
  415. }
  416. else
  417. {
  418. reader.Read();
  419. }
  420. }
  421. }
  422. private List<NameValuePair> ReadValueArray(XmlReader reader)
  423. {
  424. var pairs = new List<NameValuePair>();
  425. reader.MoveToContent();
  426. reader.Read();
  427. // Loop through each element
  428. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  429. {
  430. if (reader.NodeType == XmlNodeType.Element)
  431. {
  432. switch (reader.Name)
  433. {
  434. case "dict":
  435. if (reader.IsEmptyElement)
  436. {
  437. reader.Read();
  438. continue;
  439. }
  440. using (var subtree = reader.ReadSubtree())
  441. {
  442. var dict = GetNameValuePair(subtree);
  443. if (dict is not null)
  444. {
  445. pairs.Add(dict);
  446. }
  447. }
  448. break;
  449. default:
  450. reader.Skip();
  451. break;
  452. }
  453. }
  454. else
  455. {
  456. reader.Read();
  457. }
  458. }
  459. return pairs;
  460. }
  461. private static void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
  462. {
  463. List<BaseItemPerson> peoples = new List<BaseItemPerson>();
  464. var distinctPairs = pairs.Select(p => p.Value)
  465. .Where(i => !string.IsNullOrWhiteSpace(i))
  466. .Trimmed()
  467. .Distinct(StringComparer.OrdinalIgnoreCase);
  468. if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
  469. {
  470. info.Studios = distinctPairs.ToArray();
  471. }
  472. else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
  473. {
  474. foreach (var pair in distinctPairs)
  475. {
  476. peoples.Add(new BaseItemPerson
  477. {
  478. Name = pair,
  479. Type = PersonKind.Writer
  480. });
  481. }
  482. }
  483. else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
  484. {
  485. foreach (var pair in distinctPairs)
  486. {
  487. peoples.Add(new BaseItemPerson
  488. {
  489. Name = pair,
  490. Type = PersonKind.Producer
  491. });
  492. }
  493. }
  494. else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
  495. {
  496. foreach (var pair in distinctPairs)
  497. {
  498. peoples.Add(new BaseItemPerson
  499. {
  500. Name = pair,
  501. Type = PersonKind.Director
  502. });
  503. }
  504. }
  505. info.People = peoples.ToArray();
  506. }
  507. private static NameValuePair GetNameValuePair(XmlReader reader)
  508. {
  509. string name = null;
  510. string value = null;
  511. reader.MoveToContent();
  512. reader.Read();
  513. // Loop through each element
  514. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  515. {
  516. if (reader.NodeType == XmlNodeType.Element)
  517. {
  518. switch (reader.Name)
  519. {
  520. case "key":
  521. name = reader.ReadNormalizedString();
  522. break;
  523. case "string":
  524. value = reader.ReadNormalizedString();
  525. break;
  526. default:
  527. reader.Skip();
  528. break;
  529. }
  530. }
  531. else
  532. {
  533. reader.Read();
  534. }
  535. }
  536. if (string.IsNullOrEmpty(name)
  537. || string.IsNullOrEmpty(value))
  538. {
  539. return null;
  540. }
  541. return new NameValuePair
  542. {
  543. Name = name,
  544. Value = value
  545. };
  546. }
  547. private static string NormalizeSubtitleCodec(string codec)
  548. {
  549. if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
  550. {
  551. codec = "DVBSUB";
  552. }
  553. else if (string.Equals(codec, "dvb_teletext", StringComparison.OrdinalIgnoreCase))
  554. {
  555. codec = "DVBTXT";
  556. }
  557. else if (string.Equals(codec, "dvd_subtitle", StringComparison.OrdinalIgnoreCase))
  558. {
  559. codec = "DVDSUB"; // .sub+.idx
  560. }
  561. else if (string.Equals(codec, "hdmv_pgs_subtitle", StringComparison.OrdinalIgnoreCase))
  562. {
  563. codec = "PGSSUB"; // .sup
  564. }
  565. return codec;
  566. }
  567. /// <summary>
  568. /// Converts ffprobe stream info to our MediaAttachment class.
  569. /// </summary>
  570. /// <param name="streamInfo">The stream info.</param>
  571. /// <returns>MediaAttachments.</returns>
  572. private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
  573. {
  574. if (streamInfo.CodecType != CodecType.Attachment
  575. && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
  576. {
  577. return null;
  578. }
  579. var attachment = new MediaAttachment
  580. {
  581. Codec = streamInfo.CodecName,
  582. Index = streamInfo.Index
  583. };
  584. if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
  585. {
  586. attachment.CodecTag = streamInfo.CodecTagString;
  587. }
  588. if (streamInfo.Tags is not null)
  589. {
  590. attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
  591. attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
  592. attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
  593. }
  594. return attachment;
  595. }
  596. /// <summary>
  597. /// Converts ffprobe stream info to our MediaStream class.
  598. /// </summary>
  599. /// <param name="isAudio">if set to <c>true</c> [is info].</param>
  600. /// <param name="streamInfo">The stream info.</param>
  601. /// <param name="formatInfo">The format info.</param>
  602. /// <param name="frameInfoList">The frame info.</param>
  603. /// <returns>MediaStream.</returns>
  604. private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo, IReadOnlyList<MediaFrameInfo> frameInfoList)
  605. {
  606. // These are mp4 chapters
  607. if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
  608. {
  609. // Edit: but these are also sometimes subtitles?
  610. // return null;
  611. }
  612. var stream = new MediaStream
  613. {
  614. Codec = streamInfo.CodecName,
  615. Profile = streamInfo.Profile,
  616. Level = streamInfo.Level,
  617. Index = streamInfo.Index,
  618. PixelFormat = streamInfo.PixelFormat,
  619. NalLengthSize = streamInfo.NalLengthSize,
  620. TimeBase = streamInfo.TimeBase,
  621. CodecTimeBase = streamInfo.CodecTimeBase,
  622. IsAVC = streamInfo.IsAvc
  623. };
  624. // Filter out junk
  625. if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", StringComparison.OrdinalIgnoreCase))
  626. {
  627. stream.CodecTag = streamInfo.CodecTagString;
  628. }
  629. if (streamInfo.Tags is not null)
  630. {
  631. stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
  632. stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
  633. stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
  634. }
  635. if (streamInfo.CodecType == CodecType.Audio)
  636. {
  637. stream.Type = MediaStreamType.Audio;
  638. stream.LocalizedDefault = _localization.GetLocalizedString("Default");
  639. stream.LocalizedExternal = _localization.GetLocalizedString("External");
  640. stream.Channels = streamInfo.Channels;
  641. if (int.TryParse(streamInfo.SampleRate, CultureInfo.InvariantCulture, out var sampleRate))
  642. {
  643. stream.SampleRate = sampleRate;
  644. }
  645. stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
  646. if (streamInfo.BitsPerSample > 0)
  647. {
  648. stream.BitDepth = streamInfo.BitsPerSample;
  649. }
  650. else if (streamInfo.BitsPerRawSample > 0)
  651. {
  652. stream.BitDepth = streamInfo.BitsPerRawSample;
  653. }
  654. if (string.IsNullOrEmpty(stream.Title))
  655. {
  656. // mp4 missing track title workaround: fall back to handler_name if populated and not the default "SoundHandler"
  657. string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
  658. if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SoundHandler", StringComparison.OrdinalIgnoreCase))
  659. {
  660. stream.Title = handlerName;
  661. }
  662. }
  663. }
  664. else if (streamInfo.CodecType == CodecType.Subtitle)
  665. {
  666. stream.Type = MediaStreamType.Subtitle;
  667. stream.Codec = NormalizeSubtitleCodec(stream.Codec);
  668. stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
  669. stream.LocalizedDefault = _localization.GetLocalizedString("Default");
  670. stream.LocalizedForced = _localization.GetLocalizedString("Forced");
  671. stream.LocalizedExternal = _localization.GetLocalizedString("External");
  672. stream.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
  673. // Graphical subtitle may have width and height info
  674. stream.Width = streamInfo.Width;
  675. stream.Height = streamInfo.Height;
  676. if (string.IsNullOrEmpty(stream.Title))
  677. {
  678. // mp4 missing track title workaround: fall back to handler_name if populated and not the default "SubtitleHandler"
  679. string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
  680. if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringComparison.OrdinalIgnoreCase))
  681. {
  682. stream.Title = handlerName;
  683. }
  684. }
  685. }
  686. else if (streamInfo.CodecType == CodecType.Video)
  687. {
  688. stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
  689. stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
  690. stream.IsInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
  691. && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
  692. if (isAudio
  693. || string.Equals(stream.Codec, "bmp", StringComparison.OrdinalIgnoreCase)
  694. || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
  695. || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  696. || string.Equals(stream.Codec, "webp", StringComparison.OrdinalIgnoreCase))
  697. {
  698. stream.Type = MediaStreamType.EmbeddedImage;
  699. }
  700. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  701. {
  702. // How to differentiate between video and embedded image?
  703. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  704. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  705. {
  706. stream.Type = MediaStreamType.Video;
  707. }
  708. else
  709. {
  710. stream.Type = MediaStreamType.EmbeddedImage;
  711. }
  712. }
  713. else
  714. {
  715. stream.Type = MediaStreamType.Video;
  716. }
  717. stream.Width = streamInfo.Width;
  718. stream.Height = streamInfo.Height;
  719. stream.AspectRatio = GetAspectRatio(streamInfo);
  720. if (streamInfo.BitsPerSample > 0)
  721. {
  722. stream.BitDepth = streamInfo.BitsPerSample;
  723. }
  724. else if (streamInfo.BitsPerRawSample > 0)
  725. {
  726. stream.BitDepth = streamInfo.BitsPerRawSample;
  727. }
  728. if (!stream.BitDepth.HasValue)
  729. {
  730. if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
  731. {
  732. if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
  733. || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
  734. {
  735. stream.BitDepth = 8;
  736. }
  737. else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase)
  738. || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreCase))
  739. {
  740. stream.BitDepth = 10;
  741. }
  742. else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase)
  743. || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreCase))
  744. {
  745. stream.BitDepth = 12;
  746. }
  747. }
  748. }
  749. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  750. if (string.Equals(streamInfo.SampleAspectRatio, "1:1", StringComparison.Ordinal))
  751. {
  752. stream.IsAnamorphic = false;
  753. }
  754. else if (!string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.Ordinal))
  755. {
  756. stream.IsAnamorphic = true;
  757. }
  758. else if (string.Equals(streamInfo.DisplayAspectRatio, "0:1", StringComparison.Ordinal))
  759. {
  760. stream.IsAnamorphic = false;
  761. }
  762. else if (!string.Equals(
  763. streamInfo.DisplayAspectRatio,
  764. // Force GetAspectRatio() to derive ratio from Width/Height directly by using null DAR
  765. GetAspectRatio(new MediaStreamInfo
  766. {
  767. Width = streamInfo.Width,
  768. Height = streamInfo.Height,
  769. DisplayAspectRatio = null
  770. }),
  771. StringComparison.Ordinal))
  772. {
  773. stream.IsAnamorphic = true;
  774. }
  775. else
  776. {
  777. stream.IsAnamorphic = false;
  778. }
  779. if (streamInfo.Refs > 0)
  780. {
  781. stream.RefFrames = streamInfo.Refs;
  782. }
  783. if (!string.IsNullOrEmpty(streamInfo.ColorRange))
  784. {
  785. stream.ColorRange = streamInfo.ColorRange;
  786. }
  787. if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
  788. {
  789. stream.ColorSpace = streamInfo.ColorSpace;
  790. }
  791. if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
  792. {
  793. stream.ColorTransfer = streamInfo.ColorTransfer;
  794. }
  795. if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
  796. {
  797. stream.ColorPrimaries = streamInfo.ColorPrimaries;
  798. }
  799. if (streamInfo.SideDataList is not null)
  800. {
  801. foreach (var data in streamInfo.SideDataList)
  802. {
  803. // Parse Dolby Vision metadata from side_data
  804. if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnoreCase))
  805. {
  806. stream.DvVersionMajor = data.DvVersionMajor;
  807. stream.DvVersionMinor = data.DvVersionMinor;
  808. stream.DvProfile = data.DvProfile;
  809. stream.DvLevel = data.DvLevel;
  810. stream.RpuPresentFlag = data.RpuPresentFlag;
  811. stream.ElPresentFlag = data.ElPresentFlag;
  812. stream.BlPresentFlag = data.BlPresentFlag;
  813. stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
  814. }
  815. // Parse video rotation metadata from side_data
  816. else if (string.Equals(data.SideDataType, "Display Matrix", StringComparison.OrdinalIgnoreCase))
  817. {
  818. stream.Rotation = data.Rotation;
  819. }
  820. }
  821. }
  822. var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
  823. if (frameInfo?.SideDataList is not null
  824. && frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE2094-40 (HDR10+)", StringComparison.OrdinalIgnoreCase)))
  825. {
  826. stream.Hdr10PlusPresentFlag = true;
  827. }
  828. }
  829. else if (streamInfo.CodecType == CodecType.Data)
  830. {
  831. stream.Type = MediaStreamType.Data;
  832. }
  833. else
  834. {
  835. return null;
  836. }
  837. // Get stream bitrate
  838. var bitrate = 0;
  839. if (int.TryParse(streamInfo.BitRate, CultureInfo.InvariantCulture, out var value))
  840. {
  841. bitrate = value;
  842. }
  843. // The bitrate info of FLAC musics and some videos is included in formatInfo.
  844. if (bitrate == 0
  845. && formatInfo is not null
  846. && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
  847. {
  848. // If the stream info doesn't have a bitrate get the value from the media format info
  849. if (int.TryParse(formatInfo.BitRate, CultureInfo.InvariantCulture, out value))
  850. {
  851. bitrate = value;
  852. }
  853. }
  854. if (bitrate > 0)
  855. {
  856. stream.BitRate = bitrate;
  857. }
  858. // Extract bitrate info from tag "BPS" if possible.
  859. if (!stream.BitRate.HasValue
  860. && (streamInfo.CodecType == CodecType.Audio
  861. || streamInfo.CodecType == CodecType.Video))
  862. {
  863. var bps = GetBPSFromTags(streamInfo);
  864. if (bps > 0)
  865. {
  866. stream.BitRate = bps;
  867. }
  868. else
  869. {
  870. // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
  871. var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
  872. var bytes = GetNumberOfBytesFromTags(streamInfo);
  873. if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
  874. {
  875. bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
  876. if (bps > 0)
  877. {
  878. stream.BitRate = bps;
  879. }
  880. }
  881. }
  882. }
  883. var disposition = streamInfo.Disposition;
  884. if (disposition is not null)
  885. {
  886. if (disposition.GetValueOrDefault("default") == 1)
  887. {
  888. stream.IsDefault = true;
  889. }
  890. if (disposition.GetValueOrDefault("forced") == 1)
  891. {
  892. stream.IsForced = true;
  893. }
  894. if (disposition.GetValueOrDefault("hearing_impaired") == 1)
  895. {
  896. stream.IsHearingImpaired = true;
  897. }
  898. }
  899. NormalizeStreamTitle(stream);
  900. return stream;
  901. }
  902. private static void NormalizeStreamTitle(MediaStream stream)
  903. {
  904. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)
  905. || stream.Type == MediaStreamType.EmbeddedImage)
  906. {
  907. stream.Title = null;
  908. }
  909. }
  910. /// <summary>
  911. /// Gets a string from an FFProbeResult tags dictionary.
  912. /// </summary>
  913. /// <param name="tags">The tags.</param>
  914. /// <param name="key">The key.</param>
  915. /// <returns>System.String.</returns>
  916. private static string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
  917. {
  918. if (tags is null)
  919. {
  920. return null;
  921. }
  922. tags.TryGetValue(key, out var val);
  923. return val;
  924. }
  925. private static string ParseChannelLayout(string input)
  926. {
  927. if (string.IsNullOrEmpty(input))
  928. {
  929. return null;
  930. }
  931. return input.AsSpan().LeftPart('(').ToString();
  932. }
  933. private static string GetAspectRatio(MediaStreamInfo info)
  934. {
  935. var original = info.DisplayAspectRatio;
  936. var parts = (original ?? string.Empty).Split(':');
  937. if (!(parts.Length == 2
  938. && int.TryParse(parts[0], CultureInfo.InvariantCulture, out var width)
  939. && int.TryParse(parts[1], CultureInfo.InvariantCulture, out var height)
  940. && width > 0
  941. && height > 0))
  942. {
  943. width = info.Width;
  944. height = info.Height;
  945. }
  946. if (width > 0 && height > 0)
  947. {
  948. double ratio = width;
  949. ratio /= height;
  950. if (IsClose(ratio, 1.777777778, .03))
  951. {
  952. return "16:9";
  953. }
  954. if (IsClose(ratio, 1.3333333333, .05))
  955. {
  956. return "4:3";
  957. }
  958. if (IsClose(ratio, 1.41))
  959. {
  960. return "1.41:1";
  961. }
  962. if (IsClose(ratio, 1.5))
  963. {
  964. return "1.5:1";
  965. }
  966. if (IsClose(ratio, 1.6))
  967. {
  968. return "1.6:1";
  969. }
  970. if (IsClose(ratio, 1.66666666667))
  971. {
  972. return "5:3";
  973. }
  974. if (IsClose(ratio, 1.85, .02))
  975. {
  976. return "1.85:1";
  977. }
  978. if (IsClose(ratio, 2.35, .025))
  979. {
  980. return "2.35:1";
  981. }
  982. if (IsClose(ratio, 2.4, .025))
  983. {
  984. return "2.40:1";
  985. }
  986. }
  987. return original;
  988. }
  989. private static bool IsClose(double d1, double d2, double variance = .005)
  990. {
  991. return Math.Abs(d1 - d2) <= variance;
  992. }
  993. /// <summary>
  994. /// Gets a frame rate from a string value in ffprobe output
  995. /// This could be a number or in the format of 2997/125.
  996. /// </summary>
  997. /// <param name="value">The value.</param>
  998. /// <returns>System.Nullable{System.Single}.</returns>
  999. internal static float? GetFrameRate(ReadOnlySpan<char> value)
  1000. {
  1001. if (value.IsEmpty)
  1002. {
  1003. return null;
  1004. }
  1005. int index = value.IndexOf('/');
  1006. if (index == -1)
  1007. {
  1008. return null;
  1009. }
  1010. if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
  1011. || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var divisor))
  1012. {
  1013. return null;
  1014. }
  1015. return divisor == 0f ? null : dividend / divisor;
  1016. }
  1017. private static void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  1018. {
  1019. // Get the first info stream
  1020. var stream = result.Streams?.FirstOrDefault(s => s.CodecType == CodecType.Audio);
  1021. if (stream is null)
  1022. {
  1023. return;
  1024. }
  1025. // Get duration from stream properties
  1026. var duration = stream.Duration;
  1027. // If it's not there go into format properties
  1028. if (string.IsNullOrEmpty(duration))
  1029. {
  1030. duration = result.Format.Duration;
  1031. }
  1032. // If we got something, parse it
  1033. if (!string.IsNullOrEmpty(duration))
  1034. {
  1035. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
  1036. }
  1037. }
  1038. private static int? GetBPSFromTags(MediaStreamInfo streamInfo)
  1039. {
  1040. if (streamInfo?.Tags is null)
  1041. {
  1042. return null;
  1043. }
  1044. var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
  1045. if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
  1046. {
  1047. return parsedBps;
  1048. }
  1049. return null;
  1050. }
  1051. private static double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
  1052. {
  1053. if (streamInfo?.Tags is null)
  1054. {
  1055. return null;
  1056. }
  1057. var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION");
  1058. if (TimeSpan.TryParse(duration, out var parsedDuration))
  1059. {
  1060. return parsedDuration.TotalSeconds;
  1061. }
  1062. return null;
  1063. }
  1064. private static long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
  1065. {
  1066. if (streamInfo?.Tags is null)
  1067. {
  1068. return null;
  1069. }
  1070. var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
  1071. ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
  1072. if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
  1073. {
  1074. return parsedBytes;
  1075. }
  1076. return null;
  1077. }
  1078. private static void SetSize(InternalMediaInfoResult data, MediaInfo info)
  1079. {
  1080. if (data.Format is null)
  1081. {
  1082. return;
  1083. }
  1084. info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.InvariantCulture);
  1085. }
  1086. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  1087. {
  1088. var people = new List<BaseItemPerson>();
  1089. if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
  1090. {
  1091. foreach (var person in Split(composer, false))
  1092. {
  1093. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Composer });
  1094. }
  1095. }
  1096. if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
  1097. {
  1098. foreach (var person in Split(conductor, false))
  1099. {
  1100. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Conductor });
  1101. }
  1102. }
  1103. if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
  1104. {
  1105. foreach (var person in Split(lyricist, false))
  1106. {
  1107. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Lyricist });
  1108. }
  1109. }
  1110. if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
  1111. {
  1112. foreach (var person in Split(performer, false))
  1113. {
  1114. Match match = PerformerRegex().Match(person);
  1115. // If the performer doesn't have any instrument/role associated, it won't match. In that case, chances are it's simply a band name, so we skip it.
  1116. if (match.Success)
  1117. {
  1118. people.Add(new BaseItemPerson
  1119. {
  1120. Name = match.Groups["name"].Value,
  1121. Type = PersonKind.Actor,
  1122. Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
  1123. });
  1124. }
  1125. }
  1126. }
  1127. // In cases where there isn't sufficient information as to which role a writer performed on a recording, tagging software uses the "writer" tag.
  1128. if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
  1129. {
  1130. foreach (var person in Split(writer, false))
  1131. {
  1132. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Writer });
  1133. }
  1134. }
  1135. if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
  1136. {
  1137. foreach (var person in Split(arranger, false))
  1138. {
  1139. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Arranger });
  1140. }
  1141. }
  1142. if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
  1143. {
  1144. foreach (var person in Split(engineer, false))
  1145. {
  1146. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Engineer });
  1147. }
  1148. }
  1149. if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
  1150. {
  1151. foreach (var person in Split(mixer, false))
  1152. {
  1153. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Mixer });
  1154. }
  1155. }
  1156. if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
  1157. {
  1158. foreach (var person in Split(remixer, false))
  1159. {
  1160. people.Add(new BaseItemPerson { Name = person, Type = PersonKind.Remixer });
  1161. }
  1162. }
  1163. audio.People = people.ToArray();
  1164. // Set album artist
  1165. var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
  1166. audio.AlbumArtists = albumArtist is not null
  1167. ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
  1168. : Array.Empty<string>();
  1169. // Set album artist to artist if empty
  1170. if (audio.AlbumArtists.Length == 0)
  1171. {
  1172. audio.AlbumArtists = audio.Artists;
  1173. }
  1174. // Track number
  1175. audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
  1176. // Disc number
  1177. audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
  1178. // There's several values in tags may or may not be present
  1179. FetchStudios(audio, tags, "organization");
  1180. FetchStudios(audio, tags, "ensemble");
  1181. FetchStudios(audio, tags, "publisher");
  1182. FetchStudios(audio, tags, "label");
  1183. // These support multiple values, but for now we only store the first.
  1184. var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
  1185. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
  1186. audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
  1187. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
  1188. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
  1189. audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, mb);
  1190. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
  1191. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
  1192. audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
  1193. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
  1194. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
  1195. audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
  1196. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
  1197. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
  1198. audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, mb);
  1199. }
  1200. private static string GetMultipleMusicBrainzId(string value)
  1201. {
  1202. if (string.IsNullOrWhiteSpace(value))
  1203. {
  1204. return null;
  1205. }
  1206. return value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
  1207. .FirstOrDefault();
  1208. }
  1209. /// <summary>
  1210. /// Splits the specified val.
  1211. /// </summary>
  1212. /// <param name="val">The val.</param>
  1213. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  1214. /// <returns>System.String[][].</returns>
  1215. private string[] Split(string val, bool allowCommaDelimiter)
  1216. {
  1217. // Only use the comma as a delimiter if there are no slashes or pipes.
  1218. // We want to be careful not to split names that have commas in them
  1219. return !allowCommaDelimiter || _nameDelimiters.Any(i => val.Contains(i, StringComparison.Ordinal)) ?
  1220. val.Split(_nameDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) :
  1221. val.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  1222. }
  1223. private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
  1224. {
  1225. if (splitFeaturing)
  1226. {
  1227. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  1228. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  1229. }
  1230. var artistsFound = new List<string>();
  1231. foreach (var whitelistArtist in SplitWhitelist)
  1232. {
  1233. var originalVal = val;
  1234. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  1235. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  1236. {
  1237. artistsFound.Add(whitelistArtist);
  1238. }
  1239. }
  1240. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  1241. artistsFound.AddRange(artists);
  1242. return artistsFound.DistinctNames();
  1243. }
  1244. /// <summary>
  1245. /// Gets the studios from the tags collection.
  1246. /// </summary>
  1247. /// <param name="info">The info.</param>
  1248. /// <param name="tags">The tags.</param>
  1249. /// <param name="tagName">Name of the tag.</param>
  1250. private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
  1251. {
  1252. var val = tags.GetValueOrDefault(tagName);
  1253. if (string.IsNullOrEmpty(val))
  1254. {
  1255. return;
  1256. }
  1257. var studios = Split(val, true);
  1258. var studioList = new List<string>();
  1259. foreach (var studio in studios)
  1260. {
  1261. if (string.IsNullOrWhiteSpace(studio))
  1262. {
  1263. continue;
  1264. }
  1265. // Don't add artist/album artist name to studios, even if it's listed there
  1266. if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
  1267. || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
  1268. {
  1269. continue;
  1270. }
  1271. studioList.Add(studio);
  1272. }
  1273. info.Studios = studioList
  1274. .Distinct(StringComparer.OrdinalIgnoreCase)
  1275. .ToArray();
  1276. }
  1277. /// <summary>
  1278. /// Gets the genres from the tags collection.
  1279. /// </summary>
  1280. /// <param name="info">The information.</param>
  1281. /// <param name="tags">The tags.</param>
  1282. private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
  1283. {
  1284. var genreVal = tags.GetValueOrDefault("genre");
  1285. if (string.IsNullOrEmpty(genreVal))
  1286. {
  1287. return;
  1288. }
  1289. var genres = new List<string>(info.Genres);
  1290. foreach (var genre in Split(genreVal, true))
  1291. {
  1292. if (string.IsNullOrEmpty(genre))
  1293. {
  1294. continue;
  1295. }
  1296. genres.Add(genre);
  1297. }
  1298. info.Genres = genres
  1299. .Distinct(StringComparer.OrdinalIgnoreCase)
  1300. .ToArray();
  1301. }
  1302. /// <summary>
  1303. /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
  1304. /// </summary>
  1305. /// <param name="tags">The tags.</param>
  1306. /// <param name="tagName">Name of the tag.</param>
  1307. /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
  1308. private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
  1309. {
  1310. var disc = tags.GetValueOrDefault(tagName);
  1311. if (int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
  1312. {
  1313. return discNum;
  1314. }
  1315. return null;
  1316. }
  1317. private static ChapterInfo GetChapterInfo(MediaChapter chapter)
  1318. {
  1319. var info = new ChapterInfo();
  1320. if (chapter.Tags is not null && chapter.Tags.TryGetValue("title", out string name))
  1321. {
  1322. info.Name = name;
  1323. }
  1324. // Limit accuracy to milliseconds to match xml saving
  1325. var secondsString = chapter.StartTime;
  1326. if (double.TryParse(secondsString, CultureInfo.InvariantCulture, out var seconds))
  1327. {
  1328. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  1329. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  1330. }
  1331. return info;
  1332. }
  1333. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1334. {
  1335. var tags = data.Format?.Tags;
  1336. if (tags is null)
  1337. {
  1338. return;
  1339. }
  1340. if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
  1341. {
  1342. var genreList = genres.Split(_genreDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  1343. // If this is empty then don't overwrite genres that might have been fetched earlier
  1344. if (genreList.Length > 0)
  1345. {
  1346. video.Genres = genreList;
  1347. }
  1348. }
  1349. if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRating))
  1350. {
  1351. video.OfficialRating = officialRating;
  1352. }
  1353. if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
  1354. {
  1355. video.People = Array.ConvertAll(
  1356. people.Split(_basicDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
  1357. i => new BaseItemPerson { Name = i, Type = PersonKind.Actor });
  1358. }
  1359. if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear))
  1360. {
  1361. video.ProductionYear = parsedYear;
  1362. }
  1363. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1364. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1365. if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(year, null, DateTimeStyles.AdjustToUniversal, out var parsedDate))
  1366. {
  1367. video.PremiereDate = parsedDate;
  1368. }
  1369. var description = tags.GetValueOrDefault("WM/SubTitleDescription");
  1370. var subTitle = tags.GetValueOrDefault("WM/SubTitle");
  1371. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1372. // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, extract if possible. See ticket https://mcebuddy2x.codeplex.com/workitem/1910
  1373. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1374. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1375. // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the Doctor puts Amy, Rory and his beloved TARDIS in grave danger. Also in HD. [AD,S]
  1376. // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in the middle of the big city. Some of Abney and Teal's favourite objects are missing. [S]
  1377. if (string.IsNullOrWhiteSpace(subTitle)
  1378. && !string.IsNullOrWhiteSpace(description)
  1379. && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains(':')) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
  1380. {
  1381. string[] descriptionParts = description.Split(':');
  1382. if (descriptionParts.Length > 0)
  1383. {
  1384. string subtitle = descriptionParts[0];
  1385. try
  1386. {
  1387. // Check if it contains a episode number and season number
  1388. if (subtitle.Contains('/', StringComparison.Ordinal))
  1389. {
  1390. string[] subtitleParts = subtitle.Split(' ');
  1391. string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/');
  1392. video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
  1393. // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
  1394. // Skip the numbers, concatenate the rest, trim and set as new description
  1395. description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1396. }
  1397. else if (subtitle.Contains('.', StringComparison.Ordinal))
  1398. {
  1399. var subtitleParts = subtitle.Split('.');
  1400. description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1401. }
  1402. else
  1403. {
  1404. description = subtitle.Trim();
  1405. }
  1406. }
  1407. catch (Exception ex)
  1408. {
  1409. _logger.LogError(ex, "Error while parsing subtitle field");
  1410. // Fallback to default parsing
  1411. if (subtitle.Contains('.', StringComparison.Ordinal))
  1412. {
  1413. var subtitleParts = subtitle.Split('.');
  1414. description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1415. }
  1416. else
  1417. {
  1418. description = subtitle.Trim();
  1419. }
  1420. }
  1421. }
  1422. }
  1423. if (!string.IsNullOrWhiteSpace(description))
  1424. {
  1425. video.Overview = description;
  1426. }
  1427. }
  1428. private void ExtractTimestamp(MediaInfo video)
  1429. {
  1430. if (video.VideoType != VideoType.VideoFile)
  1431. {
  1432. return;
  1433. }
  1434. if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
  1435. && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
  1436. && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1437. {
  1438. return;
  1439. }
  1440. try
  1441. {
  1442. video.Timestamp = GetMpegTimestamp(video.Path);
  1443. _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
  1444. }
  1445. catch (Exception ex)
  1446. {
  1447. video.Timestamp = null;
  1448. _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
  1449. }
  1450. }
  1451. // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
  1452. private static TransportStreamTimestamp GetMpegTimestamp(string path)
  1453. {
  1454. var packetBuffer = new byte[197];
  1455. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
  1456. {
  1457. fs.ReadExactly(packetBuffer);
  1458. }
  1459. if (packetBuffer[0] == 71)
  1460. {
  1461. return TransportStreamTimestamp.None;
  1462. }
  1463. if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
  1464. {
  1465. return TransportStreamTimestamp.None;
  1466. }
  1467. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1468. {
  1469. return TransportStreamTimestamp.Zero;
  1470. }
  1471. return TransportStreamTimestamp.Valid;
  1472. }
  1473. [GeneratedRegex("(?<name>.*) \\((?<instrument>.*)\\)")]
  1474. private static partial Regex PerformerRegex();
  1475. }
  1476. }