2
0

ProbeResultNormalizer.cs 45 KB

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