ProbeResultNormalizer.cs 52 KB

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