ProbeResultNormalizer.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. }
  383. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  384. {
  385. stream.Type = MediaStreamType.Audio;
  386. stream.Channels = streamInfo.channels;
  387. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  388. {
  389. int value;
  390. if (int.TryParse(streamInfo.sample_rate, NumberStyles.Any, _usCulture, out value))
  391. {
  392. stream.SampleRate = value;
  393. }
  394. }
  395. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  396. if (streamInfo.bits_per_sample > 0)
  397. {
  398. stream.BitDepth = streamInfo.bits_per_sample;
  399. }
  400. else if (streamInfo.bits_per_raw_sample > 0)
  401. {
  402. stream.BitDepth = streamInfo.bits_per_raw_sample;
  403. }
  404. }
  405. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  406. {
  407. stream.Type = MediaStreamType.Subtitle;
  408. }
  409. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  410. {
  411. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  412. ? MediaStreamType.EmbeddedImage
  413. : MediaStreamType.Video;
  414. stream.Width = streamInfo.width;
  415. stream.Height = streamInfo.height;
  416. stream.AspectRatio = GetAspectRatio(streamInfo);
  417. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  418. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  419. if (streamInfo.bits_per_sample > 0)
  420. {
  421. stream.BitDepth = streamInfo.bits_per_sample;
  422. }
  423. else if (streamInfo.bits_per_raw_sample > 0)
  424. {
  425. stream.BitDepth = streamInfo.bits_per_raw_sample;
  426. }
  427. //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  428. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  429. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  430. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  431. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  432. if (streamInfo.refs > 0)
  433. {
  434. stream.RefFrames = streamInfo.refs;
  435. }
  436. }
  437. else
  438. {
  439. return null;
  440. }
  441. // Get stream bitrate
  442. var bitrate = 0;
  443. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  444. {
  445. int value;
  446. if (int.TryParse(streamInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  447. {
  448. bitrate = value;
  449. }
  450. }
  451. if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  452. {
  453. // If the stream info doesn't have a bitrate get the value from the media format info
  454. int value;
  455. if (int.TryParse(formatInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  456. {
  457. bitrate = value;
  458. }
  459. }
  460. if (bitrate > 0)
  461. {
  462. stream.BitRate = bitrate;
  463. }
  464. if (streamInfo.disposition != null)
  465. {
  466. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  467. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  468. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  469. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  470. }
  471. return stream;
  472. }
  473. /// <summary>
  474. /// Gets a string from an FFProbeResult tags dictionary
  475. /// </summary>
  476. /// <param name="tags">The tags.</param>
  477. /// <param name="key">The key.</param>
  478. /// <returns>System.String.</returns>
  479. private string GetDictionaryValue(Dictionary<string, string> tags, string key)
  480. {
  481. if (tags == null)
  482. {
  483. return null;
  484. }
  485. string val;
  486. tags.TryGetValue(key, out val);
  487. return val;
  488. }
  489. private string ParseChannelLayout(string input)
  490. {
  491. if (string.IsNullOrEmpty(input))
  492. {
  493. return input;
  494. }
  495. return input.Split('(').FirstOrDefault();
  496. }
  497. private string GetAspectRatio(MediaStreamInfo info)
  498. {
  499. var original = info.display_aspect_ratio;
  500. int height;
  501. int width;
  502. var parts = (original ?? string.Empty).Split(':');
  503. if (!(parts.Length == 2 &&
  504. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out width) &&
  505. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out height) &&
  506. width > 0 &&
  507. height > 0))
  508. {
  509. width = info.width;
  510. height = info.height;
  511. }
  512. if (width > 0 && height > 0)
  513. {
  514. double ratio = width;
  515. ratio /= height;
  516. if (IsClose(ratio, 1.777777778, .03))
  517. {
  518. return "16:9";
  519. }
  520. if (IsClose(ratio, 1.3333333333, .05))
  521. {
  522. return "4:3";
  523. }
  524. if (IsClose(ratio, 1.41))
  525. {
  526. return "1.41:1";
  527. }
  528. if (IsClose(ratio, 1.5))
  529. {
  530. return "1.5:1";
  531. }
  532. if (IsClose(ratio, 1.6))
  533. {
  534. return "1.6:1";
  535. }
  536. if (IsClose(ratio, 1.66666666667))
  537. {
  538. return "5:3";
  539. }
  540. if (IsClose(ratio, 1.85, .02))
  541. {
  542. return "1.85:1";
  543. }
  544. if (IsClose(ratio, 2.35, .025))
  545. {
  546. return "2.35:1";
  547. }
  548. if (IsClose(ratio, 2.4, .025))
  549. {
  550. return "2.40:1";
  551. }
  552. }
  553. return original;
  554. }
  555. private bool IsClose(double d1, double d2, double variance = .005)
  556. {
  557. return Math.Abs(d1 - d2) <= variance;
  558. }
  559. /// <summary>
  560. /// Gets a frame rate from a string value in ffprobe output
  561. /// This could be a number or in the format of 2997/125.
  562. /// </summary>
  563. /// <param name="value">The value.</param>
  564. /// <returns>System.Nullable{System.Single}.</returns>
  565. private float? GetFrameRate(string value)
  566. {
  567. if (!string.IsNullOrEmpty(value))
  568. {
  569. var parts = value.Split('/');
  570. float result;
  571. if (parts.Length == 2)
  572. {
  573. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  574. }
  575. else
  576. {
  577. result = float.Parse(parts[0], _usCulture);
  578. }
  579. return float.IsNaN(result) ? (float?)null : result;
  580. }
  581. return null;
  582. }
  583. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  584. {
  585. if (result.streams != null)
  586. {
  587. // Get the first info stream
  588. var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  589. if (stream != null)
  590. {
  591. // Get duration from stream properties
  592. var duration = stream.duration;
  593. // If it's not there go into format properties
  594. if (string.IsNullOrEmpty(duration))
  595. {
  596. duration = result.format.duration;
  597. }
  598. // If we got something, parse it
  599. if (!string.IsNullOrEmpty(duration))
  600. {
  601. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  602. }
  603. }
  604. }
  605. }
  606. private void SetSize(InternalMediaInfoResult data, Model.MediaInfo.MediaInfo info)
  607. {
  608. if (data.format != null)
  609. {
  610. if (!string.IsNullOrEmpty(data.format.size))
  611. {
  612. info.Size = long.Parse(data.format.size, _usCulture);
  613. }
  614. else
  615. {
  616. info.Size = null;
  617. }
  618. }
  619. }
  620. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  621. {
  622. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  623. if (!string.IsNullOrWhiteSpace(composer))
  624. {
  625. foreach (var person in Split(composer, false))
  626. {
  627. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  628. }
  629. }
  630. var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  631. if (!string.IsNullOrWhiteSpace(conductor))
  632. {
  633. foreach (var person in Split(conductor, false))
  634. {
  635. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  636. }
  637. }
  638. var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  639. if (!string.IsNullOrWhiteSpace(lyricist))
  640. {
  641. foreach (var person in Split(lyricist, false))
  642. {
  643. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  644. }
  645. }
  646. // Check for writer some music is tagged that way as alternative to composer/lyricist
  647. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  648. if (!string.IsNullOrWhiteSpace(writer))
  649. {
  650. foreach (var person in Split(writer, false))
  651. {
  652. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  653. }
  654. }
  655. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  656. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  657. if (!string.IsNullOrWhiteSpace(artists))
  658. {
  659. audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
  660. .Distinct(StringComparer.OrdinalIgnoreCase)
  661. .ToList();
  662. }
  663. else
  664. {
  665. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  666. if (string.IsNullOrWhiteSpace(artist))
  667. {
  668. audio.Artists.Clear();
  669. }
  670. else
  671. {
  672. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  673. .Distinct(StringComparer.OrdinalIgnoreCase)
  674. .ToList();
  675. }
  676. }
  677. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  678. if (string.IsNullOrWhiteSpace(albumArtist))
  679. {
  680. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  681. }
  682. if (string.IsNullOrWhiteSpace(albumArtist))
  683. {
  684. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  685. }
  686. if (string.IsNullOrWhiteSpace(albumArtist))
  687. {
  688. audio.AlbumArtists = new List<string>();
  689. }
  690. else
  691. {
  692. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  693. .Distinct(StringComparer.OrdinalIgnoreCase)
  694. .ToList();
  695. }
  696. if (audio.AlbumArtists.Count == 0)
  697. {
  698. audio.AlbumArtists = audio.Artists.Take(1).ToList();
  699. }
  700. // Track number
  701. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  702. // Disc number
  703. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  704. // If we don't have a ProductionYear try and get it from PremiereDate
  705. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  706. {
  707. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  708. }
  709. // There's several values in tags may or may not be present
  710. FetchStudios(audio, tags, "organization");
  711. FetchStudios(audio, tags, "ensemble");
  712. FetchStudios(audio, tags, "publisher");
  713. FetchStudios(audio, tags, "label");
  714. // These support mulitple values, but for now we only store the first.
  715. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  716. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  717. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);
  718. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  719. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  720. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);
  721. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  722. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  723. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);
  724. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  725. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  726. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);
  727. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
  728. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  729. audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
  730. }
  731. private string GetMultipleMusicBrainzId(string value)
  732. {
  733. if (string.IsNullOrWhiteSpace(value))
  734. {
  735. return null;
  736. }
  737. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  738. .Select(i => i.Trim())
  739. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  740. }
  741. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  742. /// <summary>
  743. /// Splits the specified val.
  744. /// </summary>
  745. /// <param name="val">The val.</param>
  746. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  747. /// <returns>System.String[][].</returns>
  748. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  749. {
  750. // Only use the comma as a delimeter if there are no slashes or pipes.
  751. // We want to be careful not to split names that have commas in them
  752. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  753. _nameDelimiters :
  754. new[] { ',' };
  755. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  756. .Where(i => !string.IsNullOrWhiteSpace(i))
  757. .Select(i => i.Trim());
  758. }
  759. private const string ArtistReplaceValue = " | ";
  760. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  761. {
  762. if (splitFeaturing)
  763. {
  764. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  765. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  766. }
  767. var artistsFound = new List<string>();
  768. foreach (var whitelistArtist in GetSplitWhitelist())
  769. {
  770. var originalVal = val;
  771. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  772. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  773. {
  774. artistsFound.Add(whitelistArtist);
  775. }
  776. }
  777. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  778. .Where(i => !string.IsNullOrWhiteSpace(i))
  779. .Select(i => i.Trim());
  780. artistsFound.AddRange(artists);
  781. return artistsFound;
  782. }
  783. private List<string> _splitWhiteList = null;
  784. private IEnumerable<string> GetSplitWhitelist()
  785. {
  786. if (_splitWhiteList == null)
  787. {
  788. var file = GetType().Namespace + ".whitelist.txt";
  789. using (var stream = GetType().Assembly.GetManifestResourceStream(file))
  790. {
  791. using (var reader = new StreamReader(stream))
  792. {
  793. var list = new List<string>();
  794. while (!reader.EndOfStream)
  795. {
  796. var val = reader.ReadLine();
  797. if (!string.IsNullOrWhiteSpace(val))
  798. {
  799. list.Add(val);
  800. }
  801. }
  802. _splitWhiteList = list;
  803. }
  804. }
  805. }
  806. return _splitWhiteList;
  807. }
  808. /// <summary>
  809. /// Gets the studios from the tags collection
  810. /// </summary>
  811. /// <param name="info">The info.</param>
  812. /// <param name="tags">The tags.</param>
  813. /// <param name="tagName">Name of the tag.</param>
  814. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  815. {
  816. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  817. if (!string.IsNullOrEmpty(val))
  818. {
  819. var studios = Split(val, true);
  820. foreach (var studio in studios)
  821. {
  822. // Sometimes the artist name is listed here, account for that
  823. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  824. {
  825. continue;
  826. }
  827. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  828. {
  829. continue;
  830. }
  831. info.Studios.Add(studio);
  832. }
  833. info.Studios = info.Studios
  834. .Where(i => !string.IsNullOrWhiteSpace(i))
  835. .Distinct(StringComparer.OrdinalIgnoreCase)
  836. .ToList();
  837. }
  838. }
  839. /// <summary>
  840. /// Gets the genres from the tags collection
  841. /// </summary>
  842. /// <param name="info">The information.</param>
  843. /// <param name="tags">The tags.</param>
  844. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  845. {
  846. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  847. if (!string.IsNullOrEmpty(val))
  848. {
  849. foreach (var genre in Split(val, true))
  850. {
  851. info.Genres.Add(genre);
  852. }
  853. info.Genres = info.Genres
  854. .Where(i => !string.IsNullOrWhiteSpace(i))
  855. .Distinct(StringComparer.OrdinalIgnoreCase)
  856. .ToList();
  857. }
  858. }
  859. /// <summary>
  860. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  861. /// </summary>
  862. /// <param name="tags">The tags.</param>
  863. /// <param name="tagName">Name of the tag.</param>
  864. /// <returns>System.Nullable{System.Int32}.</returns>
  865. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  866. {
  867. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  868. if (!string.IsNullOrEmpty(disc))
  869. {
  870. disc = disc.Split('/')[0];
  871. int num;
  872. if (int.TryParse(disc, out num))
  873. {
  874. return num;
  875. }
  876. }
  877. return null;
  878. }
  879. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  880. {
  881. var info = new ChapterInfo();
  882. if (chapter.tags != null)
  883. {
  884. string name;
  885. if (chapter.tags.TryGetValue("title", out name))
  886. {
  887. info.Name = name;
  888. }
  889. }
  890. // Limit accuracy to milliseconds to match xml saving
  891. var secondsString = chapter.start_time;
  892. double seconds;
  893. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
  894. {
  895. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  896. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  897. }
  898. return info;
  899. }
  900. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  901. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  902. {
  903. if (data.format == null || data.format.tags == null)
  904. {
  905. return;
  906. }
  907. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
  908. if (!string.IsNullOrWhiteSpace(genres))
  909. {
  910. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  911. .Where(i => !string.IsNullOrWhiteSpace(i))
  912. .Select(i => i.Trim())
  913. .ToList();
  914. // If this is empty then don't overwrite genres that might have been fetched earlier
  915. if (genreList.Count > 0)
  916. {
  917. video.Genres = genreList;
  918. }
  919. }
  920. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  921. if (!string.IsNullOrWhiteSpace(officialRating))
  922. {
  923. video.OfficialRating = officialRating;
  924. }
  925. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  926. if (!string.IsNullOrEmpty(people))
  927. {
  928. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  929. .Where(i => !string.IsNullOrWhiteSpace(i))
  930. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  931. .ToList();
  932. }
  933. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  934. if (!string.IsNullOrWhiteSpace(year))
  935. {
  936. int val;
  937. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  938. {
  939. video.ProductionYear = val;
  940. }
  941. }
  942. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
  943. if (!string.IsNullOrWhiteSpace(premiereDateString))
  944. {
  945. DateTime val;
  946. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  947. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  948. if (DateTime.TryParse(year, null, DateTimeStyles.None, out val))
  949. {
  950. video.PremiereDate = val.ToUniversalTime();
  951. }
  952. }
  953. var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  954. var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
  955. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  956. // 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
  957. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  958. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  959. // 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]
  960. // 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]
  961. 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
  962. {
  963. string[] parts = description.Split(':');
  964. if (parts.Length > 0)
  965. {
  966. string subtitle = parts[0];
  967. try
  968. {
  969. if (subtitle.Contains("/")) // It contains a episode number and season number
  970. {
  971. string[] numbers = subtitle.Split(' ');
  972. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  973. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  974. description = String.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  975. }
  976. else
  977. throw new Exception(); // Switch to default parsing
  978. }
  979. catch // Default parsing
  980. {
  981. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  982. description = String.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  983. else
  984. description = subtitle.Trim(); // Clean up whitespaces and save it
  985. }
  986. }
  987. }
  988. if (!string.IsNullOrWhiteSpace(description))
  989. {
  990. video.Overview = description;
  991. }
  992. }
  993. private void ExtractTimestamp(MediaInfo video)
  994. {
  995. if (video.VideoType == VideoType.VideoFile)
  996. {
  997. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  998. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  999. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1000. {
  1001. try
  1002. {
  1003. video.Timestamp = GetMpegTimestamp(video.Path);
  1004. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  1005. }
  1006. catch (Exception ex)
  1007. {
  1008. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  1009. video.Timestamp = null;
  1010. }
  1011. }
  1012. }
  1013. }
  1014. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1015. {
  1016. var packetBuffer = new byte['Å'];
  1017. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  1018. {
  1019. fs.Read(packetBuffer, 0, packetBuffer.Length);
  1020. }
  1021. if (packetBuffer[0] == 71)
  1022. {
  1023. return TransportStreamTimestamp.None;
  1024. }
  1025. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  1026. {
  1027. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1028. {
  1029. return TransportStreamTimestamp.Zero;
  1030. }
  1031. return TransportStreamTimestamp.Valid;
  1032. }
  1033. return TransportStreamTimestamp.None;
  1034. }
  1035. }
  1036. }