ProbeResultNormalizer.cs 67 KB

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