ProbeResultNormalizer.cs 65 KB

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