ProbeResultNormalizer.cs 56 KB

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