ProbeResultNormalizer.cs 64 KB

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