ProbeResultNormalizer.cs 65 KB

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