ProbeResultNormalizer.cs 62 KB

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