ProbeResultNormalizer.cs 49 KB

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