ProbeResultNormalizer.cs 62 KB

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