2
0

ProbeResultNormalizer.cs 64 KB

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