ProbeResultNormalizer.cs 64 KB

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