ProbeResultNormalizer.cs 47 KB

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