ProbeResultNormalizer.cs 57 KB

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