ProbeResultNormalizer.cs 56 KB

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