ProbeResultNormalizer.cs 62 KB

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