ProbeResultNormalizer.cs 47 KB

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