ProbeResultNormalizer.cs 62 KB

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