ProbeResultNormalizer.cs 64 KB

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