ProbeResultNormalizer.cs 52 KB

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