ProbeResultNormalizer.cs 63 KB

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