ProbeResultNormalizer.cs 65 KB

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