ProbeResultNormalizer.cs 65 KB

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