ProbeResultNormalizer.cs 47 KB

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