ProbeResultNormalizer.cs 65 KB

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