ProbeResultNormalizer.cs 65 KB

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