ProbeResultNormalizer.cs 65 KB

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