ProbeResultNormalizer.cs 49 KB

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