ProbeResultNormalizer.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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. // Filter out junk
  453. if (!string.IsNullOrWhiteSpace(streamInfo.codec_tag_string) && streamInfo.codec_tag_string.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
  454. {
  455. stream.CodecTag = streamInfo.codec_tag_string;
  456. }
  457. if (streamInfo.tags != null)
  458. {
  459. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  460. stream.Comment = GetDictionaryValue(streamInfo.tags, "comment");
  461. stream.Title = GetDictionaryValue(streamInfo.tags, "title");
  462. }
  463. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  464. {
  465. stream.Type = MediaStreamType.Audio;
  466. stream.Channels = streamInfo.channels;
  467. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  468. {
  469. int value;
  470. if (int.TryParse(streamInfo.sample_rate, NumberStyles.Any, _usCulture, out value))
  471. {
  472. stream.SampleRate = value;
  473. }
  474. }
  475. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  476. if (streamInfo.bits_per_sample > 0)
  477. {
  478. stream.BitDepth = streamInfo.bits_per_sample;
  479. }
  480. else if (streamInfo.bits_per_raw_sample > 0)
  481. {
  482. stream.BitDepth = streamInfo.bits_per_raw_sample;
  483. }
  484. }
  485. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  486. {
  487. stream.Type = MediaStreamType.Subtitle;
  488. stream.Codec = NormalizeSubtitleCodec(stream.Codec);
  489. }
  490. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  491. {
  492. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  493. ? MediaStreamType.EmbeddedImage
  494. : MediaStreamType.Video;
  495. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  496. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  497. if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
  498. string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
  499. {
  500. stream.Type = MediaStreamType.EmbeddedImage;
  501. }
  502. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  503. {
  504. // How to differentiate between video and embedded image?
  505. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  506. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  507. {
  508. stream.Type = MediaStreamType.Video;
  509. }
  510. else
  511. {
  512. stream.Type = MediaStreamType.EmbeddedImage;
  513. }
  514. }
  515. else
  516. {
  517. stream.Type = MediaStreamType.Video;
  518. }
  519. stream.Width = streamInfo.width;
  520. stream.Height = streamInfo.height;
  521. stream.AspectRatio = GetAspectRatio(streamInfo);
  522. if (streamInfo.bits_per_sample > 0)
  523. {
  524. stream.BitDepth = streamInfo.bits_per_sample;
  525. }
  526. else if (streamInfo.bits_per_raw_sample > 0)
  527. {
  528. stream.BitDepth = streamInfo.bits_per_raw_sample;
  529. }
  530. //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  531. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  532. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  533. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  534. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  535. if (streamInfo.refs > 0)
  536. {
  537. stream.RefFrames = streamInfo.refs;
  538. }
  539. }
  540. else
  541. {
  542. return null;
  543. }
  544. // Get stream bitrate
  545. var bitrate = 0;
  546. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  547. {
  548. int value;
  549. if (int.TryParse(streamInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  550. {
  551. bitrate = value;
  552. }
  553. }
  554. if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  555. {
  556. // If the stream info doesn't have a bitrate get the value from the media format info
  557. int value;
  558. if (int.TryParse(formatInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  559. {
  560. bitrate = value;
  561. }
  562. }
  563. if (bitrate > 0)
  564. {
  565. stream.BitRate = bitrate;
  566. }
  567. if (streamInfo.disposition != null)
  568. {
  569. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  570. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  571. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  572. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  573. }
  574. NormalizeStreamTitle(stream);
  575. return stream;
  576. }
  577. private void NormalizeStreamTitle(MediaStream stream)
  578. {
  579. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase))
  580. {
  581. stream.Title = null;
  582. }
  583. if (stream.Type == MediaStreamType.EmbeddedImage)
  584. {
  585. stream.Title = null;
  586. }
  587. }
  588. /// <summary>
  589. /// Gets a string from an FFProbeResult tags dictionary
  590. /// </summary>
  591. /// <param name="tags">The tags.</param>
  592. /// <param name="key">The key.</param>
  593. /// <returns>System.String.</returns>
  594. private string GetDictionaryValue(Dictionary<string, string> tags, string key)
  595. {
  596. if (tags == null)
  597. {
  598. return null;
  599. }
  600. string val;
  601. tags.TryGetValue(key, out val);
  602. return val;
  603. }
  604. private string ParseChannelLayout(string input)
  605. {
  606. if (string.IsNullOrEmpty(input))
  607. {
  608. return input;
  609. }
  610. return input.Split('(').FirstOrDefault();
  611. }
  612. private string GetAspectRatio(MediaStreamInfo info)
  613. {
  614. var original = info.display_aspect_ratio;
  615. int height;
  616. int width;
  617. var parts = (original ?? string.Empty).Split(':');
  618. if (!(parts.Length == 2 &&
  619. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out width) &&
  620. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out height) &&
  621. width > 0 &&
  622. height > 0))
  623. {
  624. width = info.width;
  625. height = info.height;
  626. }
  627. if (width > 0 && height > 0)
  628. {
  629. double ratio = width;
  630. ratio /= height;
  631. if (IsClose(ratio, 1.777777778, .03))
  632. {
  633. return "16:9";
  634. }
  635. if (IsClose(ratio, 1.3333333333, .05))
  636. {
  637. return "4:3";
  638. }
  639. if (IsClose(ratio, 1.41))
  640. {
  641. return "1.41:1";
  642. }
  643. if (IsClose(ratio, 1.5))
  644. {
  645. return "1.5:1";
  646. }
  647. if (IsClose(ratio, 1.6))
  648. {
  649. return "1.6:1";
  650. }
  651. if (IsClose(ratio, 1.66666666667))
  652. {
  653. return "5:3";
  654. }
  655. if (IsClose(ratio, 1.85, .02))
  656. {
  657. return "1.85:1";
  658. }
  659. if (IsClose(ratio, 2.35, .025))
  660. {
  661. return "2.35:1";
  662. }
  663. if (IsClose(ratio, 2.4, .025))
  664. {
  665. return "2.40:1";
  666. }
  667. }
  668. return original;
  669. }
  670. private bool IsClose(double d1, double d2, double variance = .005)
  671. {
  672. return Math.Abs(d1 - d2) <= variance;
  673. }
  674. /// <summary>
  675. /// Gets a frame rate from a string value in ffprobe output
  676. /// This could be a number or in the format of 2997/125.
  677. /// </summary>
  678. /// <param name="value">The value.</param>
  679. /// <returns>System.Nullable{System.Single}.</returns>
  680. private float? GetFrameRate(string value)
  681. {
  682. if (!string.IsNullOrEmpty(value))
  683. {
  684. var parts = value.Split('/');
  685. float result;
  686. if (parts.Length == 2)
  687. {
  688. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  689. }
  690. else
  691. {
  692. result = float.Parse(parts[0], _usCulture);
  693. }
  694. return float.IsNaN(result) ? (float?)null : result;
  695. }
  696. return null;
  697. }
  698. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  699. {
  700. if (result.streams != null)
  701. {
  702. // Get the first info stream
  703. var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  704. if (stream != null)
  705. {
  706. // Get duration from stream properties
  707. var duration = stream.duration;
  708. // If it's not there go into format properties
  709. if (string.IsNullOrEmpty(duration))
  710. {
  711. duration = result.format.duration;
  712. }
  713. // If we got something, parse it
  714. if (!string.IsNullOrEmpty(duration))
  715. {
  716. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  717. }
  718. }
  719. }
  720. }
  721. private void SetSize(InternalMediaInfoResult data, Model.MediaInfo.MediaInfo info)
  722. {
  723. if (data.format != null)
  724. {
  725. if (!string.IsNullOrEmpty(data.format.size))
  726. {
  727. info.Size = long.Parse(data.format.size, _usCulture);
  728. }
  729. else
  730. {
  731. info.Size = null;
  732. }
  733. }
  734. }
  735. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  736. {
  737. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  738. if (!string.IsNullOrWhiteSpace(composer))
  739. {
  740. foreach (var person in Split(composer, false))
  741. {
  742. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  743. }
  744. }
  745. //var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  746. //if (!string.IsNullOrWhiteSpace(conductor))
  747. //{
  748. // foreach (var person in Split(conductor, false))
  749. // {
  750. // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  751. // }
  752. //}
  753. //var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  754. //if (!string.IsNullOrWhiteSpace(lyricist))
  755. //{
  756. // foreach (var person in Split(lyricist, false))
  757. // {
  758. // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  759. // }
  760. //}
  761. // Check for writer some music is tagged that way as alternative to composer/lyricist
  762. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  763. if (!string.IsNullOrWhiteSpace(writer))
  764. {
  765. foreach (var person in Split(writer, false))
  766. {
  767. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  768. }
  769. }
  770. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  771. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  772. if (!string.IsNullOrWhiteSpace(artists))
  773. {
  774. audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
  775. .DistinctNames()
  776. .ToList();
  777. }
  778. else
  779. {
  780. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  781. if (string.IsNullOrWhiteSpace(artist))
  782. {
  783. audio.Artists.Clear();
  784. }
  785. else
  786. {
  787. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  788. .DistinctNames()
  789. .ToList();
  790. }
  791. }
  792. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  793. if (string.IsNullOrWhiteSpace(albumArtist))
  794. {
  795. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  796. }
  797. if (string.IsNullOrWhiteSpace(albumArtist))
  798. {
  799. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  800. }
  801. if (string.IsNullOrWhiteSpace(albumArtist))
  802. {
  803. audio.AlbumArtists = new List<string>();
  804. }
  805. else
  806. {
  807. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  808. .DistinctNames()
  809. .ToList();
  810. }
  811. if (audio.AlbumArtists.Count == 0)
  812. {
  813. audio.AlbumArtists = audio.Artists.Take(1).ToList();
  814. }
  815. // Track number
  816. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  817. // Disc number
  818. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  819. // If we don't have a ProductionYear try and get it from PremiereDate
  820. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  821. {
  822. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  823. }
  824. // There's several values in tags may or may not be present
  825. FetchStudios(audio, tags, "organization");
  826. FetchStudios(audio, tags, "ensemble");
  827. FetchStudios(audio, tags, "publisher");
  828. FetchStudios(audio, tags, "label");
  829. // These support mulitple values, but for now we only store the first.
  830. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  831. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  832. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);
  833. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  834. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  835. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);
  836. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  837. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  838. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);
  839. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  840. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  841. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);
  842. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
  843. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  844. audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
  845. }
  846. private string GetMultipleMusicBrainzId(string value)
  847. {
  848. if (string.IsNullOrWhiteSpace(value))
  849. {
  850. return null;
  851. }
  852. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  853. .Select(i => i.Trim())
  854. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  855. }
  856. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  857. /// <summary>
  858. /// Splits the specified val.
  859. /// </summary>
  860. /// <param name="val">The val.</param>
  861. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  862. /// <returns>System.String[][].</returns>
  863. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  864. {
  865. // Only use the comma as a delimeter if there are no slashes or pipes.
  866. // We want to be careful not to split names that have commas in them
  867. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  868. _nameDelimiters :
  869. new[] { ',' };
  870. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  871. .Where(i => !string.IsNullOrWhiteSpace(i))
  872. .Select(i => i.Trim());
  873. }
  874. private const string ArtistReplaceValue = " | ";
  875. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  876. {
  877. if (splitFeaturing)
  878. {
  879. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  880. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  881. }
  882. var artistsFound = new List<string>();
  883. foreach (var whitelistArtist in GetSplitWhitelist())
  884. {
  885. var originalVal = val;
  886. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  887. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  888. {
  889. artistsFound.Add(whitelistArtist);
  890. }
  891. }
  892. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  893. .Where(i => !string.IsNullOrWhiteSpace(i))
  894. .Select(i => i.Trim());
  895. artistsFound.AddRange(artists);
  896. return artistsFound;
  897. }
  898. private List<string> _splitWhiteList = null;
  899. private IEnumerable<string> GetSplitWhitelist()
  900. {
  901. if (_splitWhiteList == null)
  902. {
  903. _splitWhiteList = new List<string>
  904. {
  905. "AC/DC"
  906. };
  907. }
  908. return _splitWhiteList;
  909. }
  910. /// <summary>
  911. /// Gets the studios from the tags collection
  912. /// </summary>
  913. /// <param name="info">The info.</param>
  914. /// <param name="tags">The tags.</param>
  915. /// <param name="tagName">Name of the tag.</param>
  916. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  917. {
  918. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  919. if (!string.IsNullOrEmpty(val))
  920. {
  921. var studios = Split(val, true);
  922. foreach (var studio in studios)
  923. {
  924. // Sometimes the artist name is listed here, account for that
  925. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  926. {
  927. continue;
  928. }
  929. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  930. {
  931. continue;
  932. }
  933. info.Studios.Add(studio);
  934. }
  935. info.Studios = info.Studios
  936. .Where(i => !string.IsNullOrWhiteSpace(i))
  937. .Distinct(StringComparer.OrdinalIgnoreCase)
  938. .ToList();
  939. }
  940. }
  941. /// <summary>
  942. /// Gets the genres from the tags collection
  943. /// </summary>
  944. /// <param name="info">The information.</param>
  945. /// <param name="tags">The tags.</param>
  946. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  947. {
  948. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  949. if (!string.IsNullOrEmpty(val))
  950. {
  951. foreach (var genre in Split(val, true))
  952. {
  953. info.Genres.Add(genre);
  954. }
  955. info.Genres = info.Genres
  956. .Where(i => !string.IsNullOrWhiteSpace(i))
  957. .Distinct(StringComparer.OrdinalIgnoreCase)
  958. .ToList();
  959. }
  960. }
  961. /// <summary>
  962. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  963. /// </summary>
  964. /// <param name="tags">The tags.</param>
  965. /// <param name="tagName">Name of the tag.</param>
  966. /// <returns>System.Nullable{System.Int32}.</returns>
  967. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  968. {
  969. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  970. if (!string.IsNullOrEmpty(disc))
  971. {
  972. disc = disc.Split('/')[0];
  973. int num;
  974. if (int.TryParse(disc, out num))
  975. {
  976. return num;
  977. }
  978. }
  979. return null;
  980. }
  981. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  982. {
  983. var info = new ChapterInfo();
  984. if (chapter.tags != null)
  985. {
  986. string name;
  987. if (chapter.tags.TryGetValue("title", out name))
  988. {
  989. info.Name = name;
  990. }
  991. }
  992. // Limit accuracy to milliseconds to match xml saving
  993. var secondsString = chapter.start_time;
  994. double seconds;
  995. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
  996. {
  997. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  998. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  999. }
  1000. return info;
  1001. }
  1002. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  1003. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1004. {
  1005. if (data.format == null || data.format.tags == null)
  1006. {
  1007. return;
  1008. }
  1009. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
  1010. if (!string.IsNullOrWhiteSpace(genres))
  1011. {
  1012. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  1013. .Where(i => !string.IsNullOrWhiteSpace(i))
  1014. .Select(i => i.Trim())
  1015. .ToList();
  1016. // If this is empty then don't overwrite genres that might have been fetched earlier
  1017. if (genreList.Count > 0)
  1018. {
  1019. video.Genres = genreList;
  1020. }
  1021. }
  1022. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  1023. if (!string.IsNullOrWhiteSpace(officialRating))
  1024. {
  1025. video.OfficialRating = officialRating;
  1026. }
  1027. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  1028. if (!string.IsNullOrEmpty(people))
  1029. {
  1030. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  1031. .Where(i => !string.IsNullOrWhiteSpace(i))
  1032. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  1033. .ToList();
  1034. }
  1035. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  1036. if (!string.IsNullOrWhiteSpace(year))
  1037. {
  1038. int val;
  1039. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  1040. {
  1041. video.ProductionYear = val;
  1042. }
  1043. }
  1044. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
  1045. if (!string.IsNullOrWhiteSpace(premiereDateString))
  1046. {
  1047. DateTime val;
  1048. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1049. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1050. if (DateTime.TryParse(year, null, DateTimeStyles.None, out val))
  1051. {
  1052. video.PremiereDate = val.ToUniversalTime();
  1053. }
  1054. }
  1055. var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  1056. var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
  1057. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1058. // 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
  1059. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1060. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1061. // 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]
  1062. // 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]
  1063. 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
  1064. {
  1065. string[] parts = description.Split(':');
  1066. if (parts.Length > 0)
  1067. {
  1068. string subtitle = parts[0];
  1069. try
  1070. {
  1071. if (subtitle.Contains("/")) // It contains a episode number and season number
  1072. {
  1073. string[] numbers = subtitle.Split(' ');
  1074. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  1075. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  1076. description = String.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  1077. }
  1078. else
  1079. throw new Exception(); // Switch to default parsing
  1080. }
  1081. catch // Default parsing
  1082. {
  1083. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  1084. description = String.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  1085. else
  1086. description = subtitle.Trim(); // Clean up whitespaces and save it
  1087. }
  1088. }
  1089. }
  1090. if (!string.IsNullOrWhiteSpace(description))
  1091. {
  1092. video.Overview = description;
  1093. }
  1094. }
  1095. private void ExtractTimestamp(MediaInfo video)
  1096. {
  1097. if (video.VideoType == VideoType.VideoFile)
  1098. {
  1099. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  1100. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  1101. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1102. {
  1103. try
  1104. {
  1105. video.Timestamp = GetMpegTimestamp(video.Path);
  1106. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  1107. }
  1108. catch (Exception ex)
  1109. {
  1110. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  1111. video.Timestamp = null;
  1112. }
  1113. }
  1114. }
  1115. }
  1116. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1117. {
  1118. var packetBuffer = new byte['Å'];
  1119. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  1120. {
  1121. fs.Read(packetBuffer, 0, packetBuffer.Length);
  1122. }
  1123. if (packetBuffer[0] == 71)
  1124. {
  1125. return TransportStreamTimestamp.None;
  1126. }
  1127. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  1128. {
  1129. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1130. {
  1131. return TransportStreamTimestamp.Zero;
  1132. }
  1133. return TransportStreamTimestamp.Valid;
  1134. }
  1135. return TransportStreamTimestamp.None;
  1136. }
  1137. }
  1138. }