ProbeResultNormalizer.cs 67 KB

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