ProbeResultNormalizer.cs 62 KB

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