ProbeResultNormalizer.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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. stream.LocalizedHearingImpaired = _localization.GetLocalizedString("Hearing Impaired");
  636. if (string.IsNullOrEmpty(stream.Title))
  637. {
  638. // mp4 missing track title workaround: fall back to handler_name if populated and not the default "SubtitleHandler"
  639. string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
  640. if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringComparison.OrdinalIgnoreCase))
  641. {
  642. stream.Title = handlerName;
  643. }
  644. }
  645. }
  646. else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))
  647. {
  648. stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
  649. stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
  650. bool videoInterlaced = !string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
  651. && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase);
  652. // Some interlaced H.264 files in mp4 containers using MBAFF coding aren't flagged as being interlaced by FFprobe,
  653. // so for H.264 files we also calculate the frame rate from the codec time base and check if it is double the reported
  654. // frame rate to determine if the file is interlaced
  655. bool h264MbaffCoded = string.Equals(stream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  656. && string.IsNullOrWhiteSpace(streamInfo.FieldOrder)
  657. && IsCodecTimeBaseDoubleTheFrameRate(stream.AverageFrameRate, stream.CodecTimeBase);
  658. if (videoInterlaced || h264MbaffCoded)
  659. {
  660. stream.IsInterlaced = true;
  661. }
  662. if (isAudio
  663. || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)
  664. || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
  665. || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
  666. {
  667. stream.Type = MediaStreamType.EmbeddedImage;
  668. }
  669. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  670. {
  671. // How to differentiate between video and embedded image?
  672. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  673. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  674. {
  675. stream.Type = MediaStreamType.Video;
  676. }
  677. else
  678. {
  679. stream.Type = MediaStreamType.EmbeddedImage;
  680. }
  681. }
  682. else
  683. {
  684. stream.Type = MediaStreamType.Video;
  685. }
  686. stream.Width = streamInfo.Width;
  687. stream.Height = streamInfo.Height;
  688. stream.AspectRatio = GetAspectRatio(streamInfo);
  689. if (streamInfo.BitsPerSample > 0)
  690. {
  691. stream.BitDepth = streamInfo.BitsPerSample;
  692. }
  693. else if (streamInfo.BitsPerRawSample > 0)
  694. {
  695. stream.BitDepth = streamInfo.BitsPerRawSample;
  696. }
  697. if (!stream.BitDepth.HasValue)
  698. {
  699. if (!string.IsNullOrEmpty(streamInfo.PixelFormat))
  700. {
  701. if (string.Equals(streamInfo.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
  702. || string.Equals(streamInfo.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
  703. {
  704. stream.BitDepth = 8;
  705. }
  706. else if (string.Equals(streamInfo.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase)
  707. || string.Equals(streamInfo.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreCase))
  708. {
  709. stream.BitDepth = 10;
  710. }
  711. else if (string.Equals(streamInfo.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase)
  712. || string.Equals(streamInfo.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreCase))
  713. {
  714. stream.BitDepth = 12;
  715. }
  716. }
  717. }
  718. // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  719. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  720. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  721. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  722. stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase);
  723. if (streamInfo.Refs > 0)
  724. {
  725. stream.RefFrames = streamInfo.Refs;
  726. }
  727. if (!string.IsNullOrEmpty(streamInfo.ColorRange))
  728. {
  729. stream.ColorRange = streamInfo.ColorRange;
  730. }
  731. if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
  732. {
  733. stream.ColorSpace = streamInfo.ColorSpace;
  734. }
  735. if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
  736. {
  737. stream.ColorTransfer = streamInfo.ColorTransfer;
  738. }
  739. if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
  740. {
  741. stream.ColorPrimaries = streamInfo.ColorPrimaries;
  742. }
  743. if (streamInfo.SideDataList != null)
  744. {
  745. foreach (var data in streamInfo.SideDataList)
  746. {
  747. // Parse Dolby Vision metadata from side_data
  748. if (string.Equals(data.SideDataType, "DOVI configuration record", StringComparison.OrdinalIgnoreCase))
  749. {
  750. stream.DvVersionMajor = data.DvVersionMajor;
  751. stream.DvVersionMinor = data.DvVersionMinor;
  752. stream.DvProfile = data.DvProfile;
  753. stream.DvLevel = data.DvLevel;
  754. stream.RpuPresentFlag = data.RpuPresentFlag;
  755. stream.ElPresentFlag = data.ElPresentFlag;
  756. stream.BlPresentFlag = data.BlPresentFlag;
  757. stream.DvBlSignalCompatibilityId = data.DvBlSignalCompatibilityId;
  758. break;
  759. }
  760. }
  761. }
  762. }
  763. else if (string.Equals(streamInfo.CodecType, "data", StringComparison.OrdinalIgnoreCase))
  764. {
  765. stream.Type = MediaStreamType.Data;
  766. }
  767. else
  768. {
  769. _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);
  770. return null;
  771. }
  772. // Get stream bitrate
  773. var bitrate = 0;
  774. if (!string.IsNullOrEmpty(streamInfo.BitRate))
  775. {
  776. if (int.TryParse(streamInfo.BitRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
  777. {
  778. bitrate = value;
  779. }
  780. }
  781. // The bitrate info of FLAC musics and some videos is included in formatInfo.
  782. if (bitrate == 0
  783. && formatInfo != null
  784. && !string.IsNullOrEmpty(formatInfo.BitRate)
  785. && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
  786. {
  787. // If the stream info doesn't have a bitrate get the value from the media format info
  788. if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
  789. {
  790. bitrate = value;
  791. }
  792. }
  793. if (bitrate > 0)
  794. {
  795. stream.BitRate = bitrate;
  796. }
  797. // Extract bitrate info from tag "BPS" if possible.
  798. if (!stream.BitRate.HasValue
  799. && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
  800. || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
  801. {
  802. var bps = GetBPSFromTags(streamInfo);
  803. if (bps > 0)
  804. {
  805. stream.BitRate = bps;
  806. }
  807. }
  808. // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
  809. if (!stream.BitRate.HasValue
  810. && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
  811. || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
  812. {
  813. var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
  814. var bytes = GetNumberOfBytesFromTags(streamInfo);
  815. if (durationInSeconds != null && bytes != null)
  816. {
  817. var bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
  818. if (bps > 0)
  819. {
  820. stream.BitRate = bps;
  821. }
  822. }
  823. }
  824. var disposition = streamInfo.Disposition;
  825. if (disposition != null)
  826. {
  827. if (disposition.GetValueOrDefault("default") == 1)
  828. {
  829. stream.IsDefault = true;
  830. }
  831. if (disposition.GetValueOrDefault("forced") == 1)
  832. {
  833. stream.IsForced = true;
  834. }
  835. if (disposition.GetValueOrDefault("hearing_impaired") == 1)
  836. {
  837. stream.IsHearingImpaired = true;
  838. }
  839. }
  840. NormalizeStreamTitle(stream);
  841. return stream;
  842. }
  843. private void NormalizeStreamTitle(MediaStream stream)
  844. {
  845. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase))
  846. {
  847. stream.Title = null;
  848. }
  849. if (stream.Type == MediaStreamType.EmbeddedImage)
  850. {
  851. stream.Title = null;
  852. }
  853. }
  854. /// <summary>
  855. /// Gets a string from an FFProbeResult tags dictionary.
  856. /// </summary>
  857. /// <param name="tags">The tags.</param>
  858. /// <param name="key">The key.</param>
  859. /// <returns>System.String.</returns>
  860. private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
  861. {
  862. if (tags == null)
  863. {
  864. return null;
  865. }
  866. tags.TryGetValue(key, out var val);
  867. return val;
  868. }
  869. private string ParseChannelLayout(string input)
  870. {
  871. if (string.IsNullOrEmpty(input))
  872. {
  873. return null;
  874. }
  875. return input.Split('(').FirstOrDefault();
  876. }
  877. private string GetAspectRatio(MediaStreamInfo info)
  878. {
  879. var original = info.DisplayAspectRatio;
  880. var parts = (original ?? string.Empty).Split(':');
  881. if (!(parts.Length == 2 &&
  882. int.TryParse(parts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out var width) &&
  883. int.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out var height) &&
  884. width > 0 &&
  885. height > 0))
  886. {
  887. width = info.Width;
  888. height = info.Height;
  889. }
  890. if (width > 0 && height > 0)
  891. {
  892. double ratio = width;
  893. ratio /= height;
  894. if (IsClose(ratio, 1.777777778, .03))
  895. {
  896. return "16:9";
  897. }
  898. if (IsClose(ratio, 1.3333333333, .05))
  899. {
  900. return "4:3";
  901. }
  902. if (IsClose(ratio, 1.41))
  903. {
  904. return "1.41:1";
  905. }
  906. if (IsClose(ratio, 1.5))
  907. {
  908. return "1.5:1";
  909. }
  910. if (IsClose(ratio, 1.6))
  911. {
  912. return "1.6:1";
  913. }
  914. if (IsClose(ratio, 1.66666666667))
  915. {
  916. return "5:3";
  917. }
  918. if (IsClose(ratio, 1.85, .02))
  919. {
  920. return "1.85:1";
  921. }
  922. if (IsClose(ratio, 2.35, .025))
  923. {
  924. return "2.35:1";
  925. }
  926. if (IsClose(ratio, 2.4, .025))
  927. {
  928. return "2.40:1";
  929. }
  930. }
  931. return original;
  932. }
  933. private bool IsClose(double d1, double d2, double variance = .005)
  934. {
  935. return Math.Abs(d1 - d2) <= variance;
  936. }
  937. /// <summary>
  938. /// Gets a frame rate from a string value in ffprobe output
  939. /// This could be a number or in the format of 2997/125.
  940. /// </summary>
  941. /// <param name="value">The value.</param>
  942. /// <returns>System.Nullable{System.Single}.</returns>
  943. internal static float? GetFrameRate(ReadOnlySpan<char> value)
  944. {
  945. if (value.IsEmpty)
  946. {
  947. return null;
  948. }
  949. int index = value.IndexOf('/');
  950. if (index == -1)
  951. {
  952. // REVIEW: is this branch actually required? (i.e. does ffprobe ever output something other than a fraction?)
  953. if (float.TryParse(value, NumberStyles.AllowThousands | NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
  954. {
  955. return result;
  956. }
  957. return null;
  958. }
  959. if (!float.TryParse(value[..index], NumberStyles.Integer, CultureInfo.InvariantCulture, out var dividend)
  960. || !float.TryParse(value[(index + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var divisor))
  961. {
  962. return null;
  963. }
  964. return divisor == 0f ? null : dividend / divisor;
  965. }
  966. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  967. {
  968. // Get the first info stream
  969. var stream = result.Streams?.FirstOrDefault(s => string.Equals(s.CodecType, "audio", StringComparison.OrdinalIgnoreCase));
  970. if (stream == null)
  971. {
  972. return;
  973. }
  974. // Get duration from stream properties
  975. var duration = stream.Duration;
  976. // If it's not there go into format properties
  977. if (string.IsNullOrEmpty(duration))
  978. {
  979. duration = result.Format.Duration;
  980. }
  981. // If we got something, parse it
  982. if (!string.IsNullOrEmpty(duration))
  983. {
  984. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
  985. }
  986. }
  987. private int? GetBPSFromTags(MediaStreamInfo streamInfo)
  988. {
  989. if (streamInfo?.Tags == null)
  990. {
  991. return null;
  992. }
  993. var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
  994. if (!string.IsNullOrEmpty(bps)
  995. && int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
  996. {
  997. return parsedBps;
  998. }
  999. return null;
  1000. }
  1001. private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
  1002. {
  1003. if (streamInfo?.Tags == null)
  1004. {
  1005. return null;
  1006. }
  1007. var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION");
  1008. if (!string.IsNullOrEmpty(duration) && TimeSpan.TryParse(duration, out var parsedDuration))
  1009. {
  1010. return parsedDuration.TotalSeconds;
  1011. }
  1012. return null;
  1013. }
  1014. private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
  1015. {
  1016. if (streamInfo?.Tags == null)
  1017. {
  1018. return null;
  1019. }
  1020. var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
  1021. ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
  1022. if (!string.IsNullOrEmpty(numberOfBytes)
  1023. && long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
  1024. {
  1025. return parsedBytes;
  1026. }
  1027. return null;
  1028. }
  1029. private void SetSize(InternalMediaInfoResult data, MediaInfo info)
  1030. {
  1031. if (data.Format == null)
  1032. {
  1033. return;
  1034. }
  1035. info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.InvariantCulture);
  1036. }
  1037. private void SetAudioInfoFromTags(MediaInfo audio, IReadOnlyDictionary<string, string> tags)
  1038. {
  1039. var people = new List<BaseItemPerson>();
  1040. if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
  1041. {
  1042. foreach (var person in Split(composer, false))
  1043. {
  1044. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  1045. }
  1046. }
  1047. if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
  1048. {
  1049. foreach (var person in Split(conductor, false))
  1050. {
  1051. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  1052. }
  1053. }
  1054. if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
  1055. {
  1056. foreach (var person in Split(lyricist, false))
  1057. {
  1058. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  1059. }
  1060. }
  1061. if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
  1062. {
  1063. foreach (var person in Split(performer, false))
  1064. {
  1065. Match match = _performerPattern.Match(person);
  1066. // 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.
  1067. if (match.Success)
  1068. {
  1069. people.Add(new BaseItemPerson
  1070. {
  1071. Name = match.Groups["name"].Value,
  1072. Type = PersonType.Actor,
  1073. Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
  1074. });
  1075. }
  1076. }
  1077. }
  1078. // In cases where there isn't sufficient information as to which role a writer performed on a recording, tagging software uses the "writer" tag.
  1079. if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
  1080. {
  1081. foreach (var person in Split(writer, false))
  1082. {
  1083. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  1084. }
  1085. }
  1086. if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
  1087. {
  1088. foreach (var person in Split(arranger, false))
  1089. {
  1090. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Arranger });
  1091. }
  1092. }
  1093. if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
  1094. {
  1095. foreach (var person in Split(engineer, false))
  1096. {
  1097. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Engineer });
  1098. }
  1099. }
  1100. if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
  1101. {
  1102. foreach (var person in Split(mixer, false))
  1103. {
  1104. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Mixer });
  1105. }
  1106. }
  1107. if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
  1108. {
  1109. foreach (var person in Split(remixer, false))
  1110. {
  1111. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Remixer });
  1112. }
  1113. }
  1114. audio.People = people.ToArray();
  1115. // Set album artist
  1116. var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
  1117. audio.AlbumArtists = albumArtist != null
  1118. ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
  1119. : Array.Empty<string>();
  1120. // Set album artist to artist if empty
  1121. if (audio.AlbumArtists.Length == 0)
  1122. {
  1123. audio.AlbumArtists = audio.Artists;
  1124. }
  1125. // Track number
  1126. audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
  1127. // Disc number
  1128. audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
  1129. // There's several values in tags may or may not be present
  1130. FetchStudios(audio, tags, "organization");
  1131. FetchStudios(audio, tags, "ensemble");
  1132. FetchStudios(audio, tags, "publisher");
  1133. FetchStudios(audio, tags, "label");
  1134. // These support multiple values, but for now we only store the first.
  1135. var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
  1136. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
  1137. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
  1138. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
  1139. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
  1140. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb);
  1141. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
  1142. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
  1143. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
  1144. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
  1145. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
  1146. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
  1147. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
  1148. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
  1149. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb);
  1150. }
  1151. private string GetMultipleMusicBrainzId(string value)
  1152. {
  1153. if (string.IsNullOrWhiteSpace(value))
  1154. {
  1155. return null;
  1156. }
  1157. return value.Split('/', StringSplitOptions.RemoveEmptyEntries)
  1158. .Select(i => i.Trim())
  1159. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1160. }
  1161. /// <summary>
  1162. /// Splits the specified val.
  1163. /// </summary>
  1164. /// <param name="val">The val.</param>
  1165. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  1166. /// <returns>System.String[][].</returns>
  1167. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  1168. {
  1169. // Only use the comma as a delimiter if there are no slashes or pipes.
  1170. // We want to be careful not to split names that have commas in them
  1171. var delimiter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i, StringComparison.Ordinal) != -1) ?
  1172. _nameDelimiters :
  1173. new[] { ',' };
  1174. return val.Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
  1175. .Where(i => !string.IsNullOrWhiteSpace(i))
  1176. .Select(i => i.Trim());
  1177. }
  1178. private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
  1179. {
  1180. if (splitFeaturing)
  1181. {
  1182. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  1183. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  1184. }
  1185. var artistsFound = new List<string>();
  1186. foreach (var whitelistArtist in SplitWhitelist)
  1187. {
  1188. var originalVal = val;
  1189. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  1190. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  1191. {
  1192. artistsFound.Add(whitelistArtist);
  1193. }
  1194. }
  1195. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  1196. .Where(i => !string.IsNullOrWhiteSpace(i))
  1197. .Select(i => i.Trim());
  1198. artistsFound.AddRange(artists);
  1199. return artistsFound.DistinctNames();
  1200. }
  1201. /// <summary>
  1202. /// Gets the studios from the tags collection.
  1203. /// </summary>
  1204. /// <param name="info">The info.</param>
  1205. /// <param name="tags">The tags.</param>
  1206. /// <param name="tagName">Name of the tag.</param>
  1207. private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
  1208. {
  1209. var val = tags.GetValueOrDefault(tagName);
  1210. if (string.IsNullOrEmpty(val))
  1211. {
  1212. return;
  1213. }
  1214. var studios = Split(val, true);
  1215. var studioList = new List<string>();
  1216. foreach (var studio in studios)
  1217. {
  1218. if (string.IsNullOrWhiteSpace(studio))
  1219. {
  1220. continue;
  1221. }
  1222. // Don't add artist/album artist name to studios, even if it's listed there
  1223. if (info.Artists.Contains(studio, StringComparison.OrdinalIgnoreCase)
  1224. || info.AlbumArtists.Contains(studio, StringComparison.OrdinalIgnoreCase))
  1225. {
  1226. continue;
  1227. }
  1228. studioList.Add(studio);
  1229. }
  1230. info.Studios = studioList
  1231. .Distinct(StringComparer.OrdinalIgnoreCase)
  1232. .ToArray();
  1233. }
  1234. /// <summary>
  1235. /// Gets the genres from the tags collection.
  1236. /// </summary>
  1237. /// <param name="info">The information.</param>
  1238. /// <param name="tags">The tags.</param>
  1239. private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
  1240. {
  1241. var genreVal = tags.GetValueOrDefault("genre");
  1242. if (string.IsNullOrEmpty(genreVal))
  1243. {
  1244. return;
  1245. }
  1246. var genres = new List<string>(info.Genres);
  1247. foreach (var genre in Split(genreVal, true))
  1248. {
  1249. if (string.IsNullOrWhiteSpace(genre))
  1250. {
  1251. continue;
  1252. }
  1253. genres.Add(genre);
  1254. }
  1255. info.Genres = genres
  1256. .Distinct(StringComparer.OrdinalIgnoreCase)
  1257. .ToArray();
  1258. }
  1259. /// <summary>
  1260. /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
  1261. /// </summary>
  1262. /// <param name="tags">The tags.</param>
  1263. /// <param name="tagName">Name of the tag.</param>
  1264. /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
  1265. private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
  1266. {
  1267. var disc = tags.GetValueOrDefault(tagName);
  1268. if (!string.IsNullOrEmpty(disc) && int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
  1269. {
  1270. return discNum;
  1271. }
  1272. return null;
  1273. }
  1274. private static ChapterInfo GetChapterInfo(MediaChapter chapter)
  1275. {
  1276. var info = new ChapterInfo();
  1277. if (chapter.Tags != null && chapter.Tags.TryGetValue("title", out string name))
  1278. {
  1279. info.Name = name;
  1280. }
  1281. // Limit accuracy to milliseconds to match xml saving
  1282. var secondsString = chapter.StartTime;
  1283. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
  1284. {
  1285. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  1286. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  1287. }
  1288. return info;
  1289. }
  1290. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1291. {
  1292. var tags = data.Format?.Tags;
  1293. if (tags == null)
  1294. {
  1295. return;
  1296. }
  1297. if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
  1298. {
  1299. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  1300. .Where(i => !string.IsNullOrWhiteSpace(i))
  1301. .Select(i => i.Trim())
  1302. .ToList();
  1303. // If this is empty then don't overwrite genres that might have been fetched earlier
  1304. if (genreList.Count > 0)
  1305. {
  1306. video.Genres = genreList.ToArray();
  1307. }
  1308. }
  1309. if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRating))
  1310. {
  1311. video.OfficialRating = officialRating;
  1312. }
  1313. if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
  1314. {
  1315. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  1316. .Where(i => !string.IsNullOrWhiteSpace(i))
  1317. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  1318. .ToArray();
  1319. }
  1320. if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear))
  1321. {
  1322. video.ProductionYear = parsedYear;
  1323. }
  1324. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1325. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1326. if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(year, null, DateTimeStyles.AdjustToUniversal, out var parsedDate))
  1327. {
  1328. video.PremiereDate = parsedDate;
  1329. }
  1330. var description = tags.GetValueOrDefault("WM/SubTitleDescription");
  1331. var subTitle = tags.GetValueOrDefault("WM/SubTitle");
  1332. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1333. // 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
  1334. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1335. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1336. // 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]
  1337. // 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]
  1338. if (string.IsNullOrWhiteSpace(subTitle)
  1339. && !string.IsNullOrWhiteSpace(description)
  1340. && 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
  1341. {
  1342. string[] descriptionParts = description.Split(':');
  1343. if (descriptionParts.Length > 0)
  1344. {
  1345. string subtitle = descriptionParts[0];
  1346. try
  1347. {
  1348. // Check if it contains a episode number and season number
  1349. if (subtitle.Contains('/', StringComparison.Ordinal))
  1350. {
  1351. string[] subtitleParts = subtitle.Split(' ');
  1352. string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/');
  1353. video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
  1354. // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
  1355. // Skip the numbers, concatenate the rest, trim and set as new description
  1356. description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1357. }
  1358. else if (subtitle.Contains('.', StringComparison.Ordinal))
  1359. {
  1360. var subtitleParts = subtitle.Split('.');
  1361. description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1362. }
  1363. else
  1364. {
  1365. description = subtitle.Trim();
  1366. }
  1367. }
  1368. catch (Exception ex)
  1369. {
  1370. _logger.LogError(ex, "Error while parsing subtitle field");
  1371. // Fallback to default parsing
  1372. if (subtitle.Contains('.', StringComparison.Ordinal))
  1373. {
  1374. var subtitleParts = subtitle.Split('.');
  1375. description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1376. }
  1377. else
  1378. {
  1379. description = subtitle.Trim();
  1380. }
  1381. }
  1382. }
  1383. }
  1384. if (!string.IsNullOrWhiteSpace(description))
  1385. {
  1386. video.Overview = description;
  1387. }
  1388. }
  1389. private void ExtractTimestamp(MediaInfo video)
  1390. {
  1391. if (video.VideoType != VideoType.VideoFile)
  1392. {
  1393. return;
  1394. }
  1395. if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
  1396. && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
  1397. && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1398. {
  1399. return;
  1400. }
  1401. try
  1402. {
  1403. video.Timestamp = GetMpegTimestamp(video.Path);
  1404. _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
  1405. }
  1406. catch (Exception ex)
  1407. {
  1408. video.Timestamp = null;
  1409. _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
  1410. }
  1411. }
  1412. // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
  1413. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1414. {
  1415. var packetBuffer = new byte[197];
  1416. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
  1417. {
  1418. fs.Read(packetBuffer);
  1419. }
  1420. if (packetBuffer[0] == 71)
  1421. {
  1422. return TransportStreamTimestamp.None;
  1423. }
  1424. if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
  1425. {
  1426. return TransportStreamTimestamp.None;
  1427. }
  1428. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1429. {
  1430. return TransportStreamTimestamp.Zero;
  1431. }
  1432. return TransportStreamTimestamp.Valid;
  1433. }
  1434. }
  1435. }