ProbeResultNormalizer.cs 47 KB

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