ProbeResultNormalizer.cs 59 KB

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