ProbeResultNormalizer.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. using MediaBrowser.Model.Dto;
  2. using MediaBrowser.Model.Entities;
  3. using MediaBrowser.Model.Extensions;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Xml;
  11. using CommonIO;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.MediaInfo;
  14. namespace MediaBrowser.MediaEncoding.Probing
  15. {
  16. public class ProbeResultNormalizer
  17. {
  18. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  19. private readonly ILogger _logger;
  20. private readonly IFileSystem _fileSystem;
  21. public ProbeResultNormalizer(ILogger logger, IFileSystem fileSystem)
  22. {
  23. _logger = logger;
  24. _fileSystem = fileSystem;
  25. }
  26. public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType videoType, bool isAudio, string path, MediaProtocol protocol)
  27. {
  28. var info = new MediaInfo
  29. {
  30. Path = path,
  31. Protocol = protocol
  32. };
  33. FFProbeHelpers.NormalizeFFProbeResult(data);
  34. SetSize(data, info);
  35. var internalStreams = data.streams ?? new MediaStreamInfo[] { };
  36. info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.format))
  37. .Where(i => i != null)
  38. .ToList();
  39. if (data.format != null)
  40. {
  41. info.Container = data.format.format_name;
  42. if (!string.IsNullOrEmpty(data.format.bit_rate))
  43. {
  44. int value;
  45. if (int.TryParse(data.format.bit_rate, NumberStyles.Any, _usCulture, out value))
  46. {
  47. info.Bitrate = value;
  48. }
  49. }
  50. }
  51. var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  52. var tagStreamType = isAudio ? "audio" : "video";
  53. if (data.streams != null)
  54. {
  55. var tagStream = data.streams.FirstOrDefault(i => string.Equals(i.codec_type, tagStreamType, StringComparison.OrdinalIgnoreCase));
  56. if (tagStream != null && tagStream.tags != null)
  57. {
  58. foreach (var pair in tagStream.tags)
  59. {
  60. tags[pair.Key] = pair.Value;
  61. }
  62. }
  63. }
  64. if (data.format != null && data.format.tags != null)
  65. {
  66. foreach (var pair in data.format.tags)
  67. {
  68. tags[pair.Key] = pair.Value;
  69. }
  70. }
  71. FetchGenres(info, tags);
  72. var shortOverview = FFProbeHelpers.GetDictionaryValue(tags, "description");
  73. var overview = FFProbeHelpers.GetDictionaryValue(tags, "synopsis");
  74. if (string.IsNullOrWhiteSpace(overview))
  75. {
  76. overview = shortOverview;
  77. shortOverview = null;
  78. }
  79. if (string.IsNullOrWhiteSpace(overview))
  80. {
  81. overview = FFProbeHelpers.GetDictionaryValue(tags, "desc");
  82. }
  83. if (!string.IsNullOrWhiteSpace(overview))
  84. {
  85. info.Overview = overview;
  86. }
  87. if (!string.IsNullOrWhiteSpace(shortOverview))
  88. {
  89. info.ShortOverview = shortOverview;
  90. }
  91. var title = FFProbeHelpers.GetDictionaryValue(tags, "title");
  92. if (!string.IsNullOrWhiteSpace(title))
  93. {
  94. info.Name = title;
  95. }
  96. info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
  97. // Several different forms of retaildate
  98. info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
  99. FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
  100. FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
  101. FFProbeHelpers.GetDictionaryDateTime(tags, "date");
  102. if (isAudio)
  103. {
  104. SetAudioRuntimeTicks(data, info);
  105. // tags are normally located under data.format, but we've seen some cases with ogg where they're part of the info stream
  106. // so let's create a combined list of both
  107. SetAudioInfoFromTags(info, tags);
  108. }
  109. else
  110. {
  111. FetchStudios(info, tags, "copyright");
  112. var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC");
  113. if (!string.IsNullOrWhiteSpace(iTunEXTC))
  114. {
  115. var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
  116. // Example
  117. // mpaa|G|100|For crude humor
  118. if (parts.Length > 1)
  119. {
  120. info.OfficialRating = parts[1];
  121. if (parts.Length > 3)
  122. {
  123. info.OfficialRatingDescription = parts[3];
  124. }
  125. }
  126. }
  127. var itunesXml = FFProbeHelpers.GetDictionaryValue(tags, "iTunMOVI");
  128. if (!string.IsNullOrWhiteSpace(itunesXml))
  129. {
  130. FetchFromItunesInfo(itunesXml, info);
  131. }
  132. if (data.format != null && !string.IsNullOrEmpty(data.format.duration))
  133. {
  134. info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
  135. }
  136. FetchWtvInfo(info, data);
  137. if (data.Chapters != null)
  138. {
  139. info.Chapters = data.Chapters.Select(GetChapterInfo).ToList();
  140. }
  141. ExtractTimestamp(info);
  142. }
  143. return info;
  144. }
  145. private void FetchFromItunesInfo(string xml, MediaInfo info)
  146. {
  147. // Make things simpler and strip out the dtd
  148. xml = xml.Substring(xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase));
  149. xml = "<?xml version=\"1.0\"?>" + xml;
  150. // <?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
  151. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
  152. {
  153. using (var streamReader = new StreamReader(stream))
  154. {
  155. // Use XmlReader for best performance
  156. using (var reader = XmlReader.Create(streamReader))
  157. {
  158. reader.MoveToContent();
  159. // Loop through each element
  160. while (reader.Read())
  161. {
  162. if (reader.NodeType == XmlNodeType.Element)
  163. {
  164. switch (reader.Name)
  165. {
  166. case "dict":
  167. using (var subtree = reader.ReadSubtree())
  168. {
  169. ReadFromDictNode(subtree, info);
  170. }
  171. break;
  172. default:
  173. reader.Skip();
  174. break;
  175. }
  176. }
  177. }
  178. }
  179. }
  180. }
  181. }
  182. private void ReadFromDictNode(XmlReader reader, MediaInfo info)
  183. {
  184. reader.MoveToContent();
  185. string currentKey = null;
  186. List<NameValuePair> pairs = new List<NameValuePair>();
  187. // Loop through each element
  188. while (reader.Read())
  189. {
  190. if (reader.NodeType == XmlNodeType.Element)
  191. {
  192. switch (reader.Name)
  193. {
  194. case "key":
  195. if (!string.IsNullOrWhiteSpace(currentKey))
  196. {
  197. ProcessPairs(currentKey, pairs, info);
  198. }
  199. currentKey = reader.ReadElementContentAsString();
  200. pairs = new List<NameValuePair>();
  201. break;
  202. case "string":
  203. var value = reader.ReadElementContentAsString();
  204. if (!string.IsNullOrWhiteSpace(value))
  205. {
  206. pairs.Add(new NameValuePair
  207. {
  208. Name = value,
  209. Value = value
  210. });
  211. }
  212. break;
  213. case "array":
  214. if (!string.IsNullOrWhiteSpace(currentKey))
  215. {
  216. using (var subtree = reader.ReadSubtree())
  217. {
  218. pairs.AddRange(ReadValueArray(subtree));
  219. }
  220. }
  221. break;
  222. default:
  223. reader.Skip();
  224. break;
  225. }
  226. }
  227. }
  228. }
  229. private List<NameValuePair> ReadValueArray(XmlReader reader)
  230. {
  231. reader.MoveToContent();
  232. List<NameValuePair> pairs = new List<NameValuePair>();
  233. // Loop through each element
  234. while (reader.Read())
  235. {
  236. if (reader.NodeType == XmlNodeType.Element)
  237. {
  238. switch (reader.Name)
  239. {
  240. case "dict":
  241. using (var subtree = reader.ReadSubtree())
  242. {
  243. var dict = GetNameValuePair(subtree);
  244. if (dict != null)
  245. {
  246. pairs.Add(dict);
  247. }
  248. }
  249. break;
  250. default:
  251. reader.Skip();
  252. break;
  253. }
  254. }
  255. }
  256. return pairs;
  257. }
  258. private void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
  259. {
  260. if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
  261. {
  262. foreach (var pair in pairs)
  263. {
  264. info.Studios.Add(pair.Value);
  265. }
  266. info.Studios = info.Studios
  267. .Where(i => !string.IsNullOrWhiteSpace(i))
  268. .Distinct(StringComparer.OrdinalIgnoreCase)
  269. .ToList();
  270. }
  271. else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
  272. {
  273. foreach (var pair in pairs)
  274. {
  275. info.People.Add(new BaseItemPerson
  276. {
  277. Name = pair.Value,
  278. Type = PersonType.Writer
  279. });
  280. }
  281. }
  282. else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
  283. {
  284. foreach (var pair in pairs)
  285. {
  286. info.People.Add(new BaseItemPerson
  287. {
  288. Name = pair.Value,
  289. Type = PersonType.Producer
  290. });
  291. }
  292. }
  293. else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
  294. {
  295. foreach (var pair in pairs)
  296. {
  297. info.People.Add(new BaseItemPerson
  298. {
  299. Name = pair.Value,
  300. Type = PersonType.Director
  301. });
  302. }
  303. }
  304. }
  305. private NameValuePair GetNameValuePair(XmlReader reader)
  306. {
  307. reader.MoveToContent();
  308. string name = null;
  309. string value = null;
  310. // Loop through each element
  311. while (reader.Read())
  312. {
  313. if (reader.NodeType == XmlNodeType.Element)
  314. {
  315. switch (reader.Name)
  316. {
  317. case "key":
  318. name = reader.ReadElementContentAsString();
  319. break;
  320. case "string":
  321. value = reader.ReadElementContentAsString();
  322. break;
  323. default:
  324. reader.Skip();
  325. break;
  326. }
  327. }
  328. }
  329. if (string.IsNullOrWhiteSpace(name) ||
  330. string.IsNullOrWhiteSpace(value))
  331. {
  332. return null;
  333. }
  334. return new NameValuePair
  335. {
  336. Name = name,
  337. Value = value
  338. };
  339. }
  340. /// <summary>
  341. /// Converts ffprobe stream info to our MediaStream class
  342. /// </summary>
  343. /// <param name="isAudio">if set to <c>true</c> [is info].</param>
  344. /// <param name="streamInfo">The stream info.</param>
  345. /// <param name="formatInfo">The format info.</param>
  346. /// <returns>MediaStream.</returns>
  347. private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  348. {
  349. // These are mp4 chapters
  350. if (string.Equals(streamInfo.codec_name, "mov_text", StringComparison.OrdinalIgnoreCase))
  351. {
  352. return null;
  353. }
  354. var stream = new MediaStream
  355. {
  356. Codec = streamInfo.codec_name,
  357. Profile = streamInfo.profile,
  358. Level = streamInfo.level,
  359. Index = streamInfo.index,
  360. PixelFormat = streamInfo.pix_fmt,
  361. NalLengthSize = streamInfo.nal_length_size
  362. };
  363. if (string.Equals(streamInfo.is_avc, "true", StringComparison.OrdinalIgnoreCase) ||
  364. string.Equals(streamInfo.is_avc, "1", StringComparison.OrdinalIgnoreCase))
  365. {
  366. stream.IsAVC = true;
  367. }
  368. else if (string.Equals(streamInfo.is_avc, "false", StringComparison.OrdinalIgnoreCase) ||
  369. string.Equals(streamInfo.is_avc, "0", StringComparison.OrdinalIgnoreCase))
  370. {
  371. stream.IsAVC = false;
  372. }
  373. // Filter out junk
  374. if (!string.IsNullOrWhiteSpace(streamInfo.codec_tag_string) && streamInfo.codec_tag_string.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
  375. {
  376. stream.CodecTag = streamInfo.codec_tag_string;
  377. }
  378. if (streamInfo.tags != null)
  379. {
  380. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  381. stream.Comment = GetDictionaryValue(streamInfo.tags, "comment");
  382. stream.Title = GetDictionaryValue(streamInfo.tags, "title");
  383. }
  384. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  385. {
  386. stream.Type = MediaStreamType.Audio;
  387. stream.Channels = streamInfo.channels;
  388. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  389. {
  390. int value;
  391. if (int.TryParse(streamInfo.sample_rate, NumberStyles.Any, _usCulture, out value))
  392. {
  393. stream.SampleRate = value;
  394. }
  395. }
  396. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  397. if (streamInfo.bits_per_sample > 0)
  398. {
  399. stream.BitDepth = streamInfo.bits_per_sample;
  400. }
  401. else if (streamInfo.bits_per_raw_sample > 0)
  402. {
  403. stream.BitDepth = streamInfo.bits_per_raw_sample;
  404. }
  405. }
  406. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  407. {
  408. stream.Type = MediaStreamType.Subtitle;
  409. }
  410. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  411. {
  412. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  413. ? MediaStreamType.EmbeddedImage
  414. : MediaStreamType.Video;
  415. stream.Width = streamInfo.width;
  416. stream.Height = streamInfo.height;
  417. stream.AspectRatio = GetAspectRatio(streamInfo);
  418. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  419. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  420. if (streamInfo.bits_per_sample > 0)
  421. {
  422. stream.BitDepth = streamInfo.bits_per_sample;
  423. }
  424. else if (streamInfo.bits_per_raw_sample > 0)
  425. {
  426. stream.BitDepth = streamInfo.bits_per_raw_sample;
  427. }
  428. //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  429. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  430. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  431. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  432. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  433. if (streamInfo.refs > 0)
  434. {
  435. stream.RefFrames = streamInfo.refs;
  436. }
  437. }
  438. else
  439. {
  440. return null;
  441. }
  442. // Get stream bitrate
  443. var bitrate = 0;
  444. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  445. {
  446. int value;
  447. if (int.TryParse(streamInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  448. {
  449. bitrate = value;
  450. }
  451. }
  452. if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  453. {
  454. // If the stream info doesn't have a bitrate get the value from the media format info
  455. int value;
  456. if (int.TryParse(formatInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  457. {
  458. bitrate = value;
  459. }
  460. }
  461. if (bitrate > 0)
  462. {
  463. stream.BitRate = bitrate;
  464. }
  465. if (streamInfo.disposition != null)
  466. {
  467. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  468. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  469. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  470. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  471. }
  472. NormalizeStreamTitle(stream);
  473. return stream;
  474. }
  475. private void NormalizeStreamTitle(MediaStream stream)
  476. {
  477. if (string.Equals(stream.Title, "sdh", StringComparison.OrdinalIgnoreCase))
  478. {
  479. stream.Title = null;
  480. }
  481. if (stream.Type == MediaStreamType.EmbeddedImage)
  482. {
  483. stream.Title = null;
  484. }
  485. }
  486. /// <summary>
  487. /// Gets a string from an FFProbeResult tags dictionary
  488. /// </summary>
  489. /// <param name="tags">The tags.</param>
  490. /// <param name="key">The key.</param>
  491. /// <returns>System.String.</returns>
  492. private string GetDictionaryValue(Dictionary<string, string> tags, string key)
  493. {
  494. if (tags == null)
  495. {
  496. return null;
  497. }
  498. string val;
  499. tags.TryGetValue(key, out val);
  500. return val;
  501. }
  502. private string ParseChannelLayout(string input)
  503. {
  504. if (string.IsNullOrEmpty(input))
  505. {
  506. return input;
  507. }
  508. return input.Split('(').FirstOrDefault();
  509. }
  510. private string GetAspectRatio(MediaStreamInfo info)
  511. {
  512. var original = info.display_aspect_ratio;
  513. int height;
  514. int width;
  515. var parts = (original ?? string.Empty).Split(':');
  516. if (!(parts.Length == 2 &&
  517. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out width) &&
  518. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out height) &&
  519. width > 0 &&
  520. height > 0))
  521. {
  522. width = info.width;
  523. height = info.height;
  524. }
  525. if (width > 0 && height > 0)
  526. {
  527. double ratio = width;
  528. ratio /= height;
  529. if (IsClose(ratio, 1.777777778, .03))
  530. {
  531. return "16:9";
  532. }
  533. if (IsClose(ratio, 1.3333333333, .05))
  534. {
  535. return "4:3";
  536. }
  537. if (IsClose(ratio, 1.41))
  538. {
  539. return "1.41:1";
  540. }
  541. if (IsClose(ratio, 1.5))
  542. {
  543. return "1.5:1";
  544. }
  545. if (IsClose(ratio, 1.6))
  546. {
  547. return "1.6:1";
  548. }
  549. if (IsClose(ratio, 1.66666666667))
  550. {
  551. return "5:3";
  552. }
  553. if (IsClose(ratio, 1.85, .02))
  554. {
  555. return "1.85:1";
  556. }
  557. if (IsClose(ratio, 2.35, .025))
  558. {
  559. return "2.35:1";
  560. }
  561. if (IsClose(ratio, 2.4, .025))
  562. {
  563. return "2.40:1";
  564. }
  565. }
  566. return original;
  567. }
  568. private bool IsClose(double d1, double d2, double variance = .005)
  569. {
  570. return Math.Abs(d1 - d2) <= variance;
  571. }
  572. /// <summary>
  573. /// Gets a frame rate from a string value in ffprobe output
  574. /// This could be a number or in the format of 2997/125.
  575. /// </summary>
  576. /// <param name="value">The value.</param>
  577. /// <returns>System.Nullable{System.Single}.</returns>
  578. private float? GetFrameRate(string value)
  579. {
  580. if (!string.IsNullOrEmpty(value))
  581. {
  582. var parts = value.Split('/');
  583. float result;
  584. if (parts.Length == 2)
  585. {
  586. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  587. }
  588. else
  589. {
  590. result = float.Parse(parts[0], _usCulture);
  591. }
  592. return float.IsNaN(result) ? (float?)null : result;
  593. }
  594. return null;
  595. }
  596. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  597. {
  598. if (result.streams != null)
  599. {
  600. // Get the first info stream
  601. var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  602. if (stream != null)
  603. {
  604. // Get duration from stream properties
  605. var duration = stream.duration;
  606. // If it's not there go into format properties
  607. if (string.IsNullOrEmpty(duration))
  608. {
  609. duration = result.format.duration;
  610. }
  611. // If we got something, parse it
  612. if (!string.IsNullOrEmpty(duration))
  613. {
  614. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  615. }
  616. }
  617. }
  618. }
  619. private void SetSize(InternalMediaInfoResult data, Model.MediaInfo.MediaInfo info)
  620. {
  621. if (data.format != null)
  622. {
  623. if (!string.IsNullOrEmpty(data.format.size))
  624. {
  625. info.Size = long.Parse(data.format.size, _usCulture);
  626. }
  627. else
  628. {
  629. info.Size = null;
  630. }
  631. }
  632. }
  633. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  634. {
  635. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  636. if (!string.IsNullOrWhiteSpace(composer))
  637. {
  638. foreach (var person in Split(composer, false))
  639. {
  640. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  641. }
  642. }
  643. var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  644. if (!string.IsNullOrWhiteSpace(conductor))
  645. {
  646. foreach (var person in Split(conductor, false))
  647. {
  648. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  649. }
  650. }
  651. var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  652. if (!string.IsNullOrWhiteSpace(lyricist))
  653. {
  654. foreach (var person in Split(lyricist, false))
  655. {
  656. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  657. }
  658. }
  659. // Check for writer some music is tagged that way as alternative to composer/lyricist
  660. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  661. if (!string.IsNullOrWhiteSpace(writer))
  662. {
  663. foreach (var person in Split(writer, false))
  664. {
  665. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  666. }
  667. }
  668. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  669. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  670. if (!string.IsNullOrWhiteSpace(artists))
  671. {
  672. audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
  673. .Distinct(StringComparer.OrdinalIgnoreCase)
  674. .ToList();
  675. }
  676. else
  677. {
  678. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  679. if (string.IsNullOrWhiteSpace(artist))
  680. {
  681. audio.Artists.Clear();
  682. }
  683. else
  684. {
  685. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  686. .Distinct(StringComparer.OrdinalIgnoreCase)
  687. .ToList();
  688. }
  689. }
  690. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  691. if (string.IsNullOrWhiteSpace(albumArtist))
  692. {
  693. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  694. }
  695. if (string.IsNullOrWhiteSpace(albumArtist))
  696. {
  697. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  698. }
  699. if (string.IsNullOrWhiteSpace(albumArtist))
  700. {
  701. audio.AlbumArtists = new List<string>();
  702. }
  703. else
  704. {
  705. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  706. .Distinct(StringComparer.OrdinalIgnoreCase)
  707. .ToList();
  708. }
  709. if (audio.AlbumArtists.Count == 0)
  710. {
  711. audio.AlbumArtists = audio.Artists.Take(1).ToList();
  712. }
  713. // Track number
  714. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  715. // Disc number
  716. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  717. // If we don't have a ProductionYear try and get it from PremiereDate
  718. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  719. {
  720. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  721. }
  722. // There's several values in tags may or may not be present
  723. FetchStudios(audio, tags, "organization");
  724. FetchStudios(audio, tags, "ensemble");
  725. FetchStudios(audio, tags, "publisher");
  726. FetchStudios(audio, tags, "label");
  727. // These support mulitple values, but for now we only store the first.
  728. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  729. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  730. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);
  731. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  732. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  733. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);
  734. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  735. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  736. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);
  737. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  738. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  739. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);
  740. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
  741. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  742. audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
  743. }
  744. private string GetMultipleMusicBrainzId(string value)
  745. {
  746. if (string.IsNullOrWhiteSpace(value))
  747. {
  748. return null;
  749. }
  750. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  751. .Select(i => i.Trim())
  752. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  753. }
  754. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  755. /// <summary>
  756. /// Splits the specified val.
  757. /// </summary>
  758. /// <param name="val">The val.</param>
  759. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  760. /// <returns>System.String[][].</returns>
  761. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  762. {
  763. // Only use the comma as a delimeter if there are no slashes or pipes.
  764. // We want to be careful not to split names that have commas in them
  765. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  766. _nameDelimiters :
  767. new[] { ',' };
  768. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  769. .Where(i => !string.IsNullOrWhiteSpace(i))
  770. .Select(i => i.Trim());
  771. }
  772. private const string ArtistReplaceValue = " | ";
  773. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  774. {
  775. if (splitFeaturing)
  776. {
  777. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  778. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  779. }
  780. var artistsFound = new List<string>();
  781. foreach (var whitelistArtist in GetSplitWhitelist())
  782. {
  783. var originalVal = val;
  784. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  785. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  786. {
  787. artistsFound.Add(whitelistArtist);
  788. }
  789. }
  790. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  791. .Where(i => !string.IsNullOrWhiteSpace(i))
  792. .Select(i => i.Trim());
  793. artistsFound.AddRange(artists);
  794. return artistsFound;
  795. }
  796. private List<string> _splitWhiteList = null;
  797. private IEnumerable<string> GetSplitWhitelist()
  798. {
  799. if (_splitWhiteList == null)
  800. {
  801. var file = GetType().Namespace + ".whitelist.txt";
  802. using (var stream = GetType().Assembly.GetManifestResourceStream(file))
  803. {
  804. using (var reader = new StreamReader(stream))
  805. {
  806. var list = new List<string>();
  807. while (!reader.EndOfStream)
  808. {
  809. var val = reader.ReadLine();
  810. if (!string.IsNullOrWhiteSpace(val))
  811. {
  812. list.Add(val);
  813. }
  814. }
  815. _splitWhiteList = list;
  816. }
  817. }
  818. }
  819. return _splitWhiteList;
  820. }
  821. /// <summary>
  822. /// Gets the studios from the tags collection
  823. /// </summary>
  824. /// <param name="info">The info.</param>
  825. /// <param name="tags">The tags.</param>
  826. /// <param name="tagName">Name of the tag.</param>
  827. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  828. {
  829. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  830. if (!string.IsNullOrEmpty(val))
  831. {
  832. var studios = Split(val, true);
  833. foreach (var studio in studios)
  834. {
  835. // Sometimes the artist name is listed here, account for that
  836. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  837. {
  838. continue;
  839. }
  840. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  841. {
  842. continue;
  843. }
  844. info.Studios.Add(studio);
  845. }
  846. info.Studios = info.Studios
  847. .Where(i => !string.IsNullOrWhiteSpace(i))
  848. .Distinct(StringComparer.OrdinalIgnoreCase)
  849. .ToList();
  850. }
  851. }
  852. /// <summary>
  853. /// Gets the genres from the tags collection
  854. /// </summary>
  855. /// <param name="info">The information.</param>
  856. /// <param name="tags">The tags.</param>
  857. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  858. {
  859. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  860. if (!string.IsNullOrEmpty(val))
  861. {
  862. foreach (var genre in Split(val, true))
  863. {
  864. info.Genres.Add(genre);
  865. }
  866. info.Genres = info.Genres
  867. .Where(i => !string.IsNullOrWhiteSpace(i))
  868. .Distinct(StringComparer.OrdinalIgnoreCase)
  869. .ToList();
  870. }
  871. }
  872. /// <summary>
  873. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  874. /// </summary>
  875. /// <param name="tags">The tags.</param>
  876. /// <param name="tagName">Name of the tag.</param>
  877. /// <returns>System.Nullable{System.Int32}.</returns>
  878. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  879. {
  880. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  881. if (!string.IsNullOrEmpty(disc))
  882. {
  883. disc = disc.Split('/')[0];
  884. int num;
  885. if (int.TryParse(disc, out num))
  886. {
  887. return num;
  888. }
  889. }
  890. return null;
  891. }
  892. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  893. {
  894. var info = new ChapterInfo();
  895. if (chapter.tags != null)
  896. {
  897. string name;
  898. if (chapter.tags.TryGetValue("title", out name))
  899. {
  900. info.Name = name;
  901. }
  902. }
  903. // Limit accuracy to milliseconds to match xml saving
  904. var secondsString = chapter.start_time;
  905. double seconds;
  906. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
  907. {
  908. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  909. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  910. }
  911. return info;
  912. }
  913. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  914. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  915. {
  916. if (data.format == null || data.format.tags == null)
  917. {
  918. return;
  919. }
  920. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
  921. if (!string.IsNullOrWhiteSpace(genres))
  922. {
  923. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  924. .Where(i => !string.IsNullOrWhiteSpace(i))
  925. .Select(i => i.Trim())
  926. .ToList();
  927. // If this is empty then don't overwrite genres that might have been fetched earlier
  928. if (genreList.Count > 0)
  929. {
  930. video.Genres = genreList;
  931. }
  932. }
  933. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  934. if (!string.IsNullOrWhiteSpace(officialRating))
  935. {
  936. video.OfficialRating = officialRating;
  937. }
  938. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  939. if (!string.IsNullOrEmpty(people))
  940. {
  941. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  942. .Where(i => !string.IsNullOrWhiteSpace(i))
  943. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  944. .ToList();
  945. }
  946. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  947. if (!string.IsNullOrWhiteSpace(year))
  948. {
  949. int val;
  950. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  951. {
  952. video.ProductionYear = val;
  953. }
  954. }
  955. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
  956. if (!string.IsNullOrWhiteSpace(premiereDateString))
  957. {
  958. DateTime val;
  959. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  960. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  961. if (DateTime.TryParse(year, null, DateTimeStyles.None, out val))
  962. {
  963. video.PremiereDate = val.ToUniversalTime();
  964. }
  965. }
  966. var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  967. var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
  968. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  969. // 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
  970. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  971. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  972. // 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]
  973. // 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]
  974. if (String.IsNullOrWhiteSpace(subTitle) && !String.IsNullOrWhiteSpace(description) && description.Substring(0, Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)).Contains(":")) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
  975. {
  976. string[] parts = description.Split(':');
  977. if (parts.Length > 0)
  978. {
  979. string subtitle = parts[0];
  980. try
  981. {
  982. if (subtitle.Contains("/")) // It contains a episode number and season number
  983. {
  984. string[] numbers = subtitle.Split(' ');
  985. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  986. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  987. description = String.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  988. }
  989. else
  990. throw new Exception(); // Switch to default parsing
  991. }
  992. catch // Default parsing
  993. {
  994. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  995. description = String.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  996. else
  997. description = subtitle.Trim(); // Clean up whitespaces and save it
  998. }
  999. }
  1000. }
  1001. if (!string.IsNullOrWhiteSpace(description))
  1002. {
  1003. video.Overview = description;
  1004. }
  1005. }
  1006. private void ExtractTimestamp(MediaInfo video)
  1007. {
  1008. if (video.VideoType == VideoType.VideoFile)
  1009. {
  1010. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  1011. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  1012. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. try
  1015. {
  1016. video.Timestamp = GetMpegTimestamp(video.Path);
  1017. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  1018. }
  1019. catch (Exception ex)
  1020. {
  1021. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  1022. video.Timestamp = null;
  1023. }
  1024. }
  1025. }
  1026. }
  1027. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1028. {
  1029. var packetBuffer = new byte['Å'];
  1030. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  1031. {
  1032. fs.Read(packetBuffer, 0, packetBuffer.Length);
  1033. }
  1034. if (packetBuffer[0] == 71)
  1035. {
  1036. return TransportStreamTimestamp.None;
  1037. }
  1038. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  1039. {
  1040. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1041. {
  1042. return TransportStreamTimestamp.Zero;
  1043. }
  1044. return TransportStreamTimestamp.Valid;
  1045. }
  1046. return TransportStreamTimestamp.None;
  1047. }
  1048. }
  1049. }