ProbeResultNormalizer.cs 52 KB

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