ProbeResultNormalizer.cs 66 KB

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