ProbeResultNormalizer.cs 54 KB

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