ProbeResultNormalizer.cs 45 KB

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