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