ProbeResultNormalizer.cs 51 KB

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