ProbeResultNormalizer.cs 50 KB

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