ProbeResultNormalizer.cs 52 KB

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