ProbeResultNormalizer.cs 59 KB

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