ProbeResultNormalizer.cs 68 KB

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