ProbeResultNormalizer.cs 64 KB

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