ProbeResultNormalizer.cs 64 KB

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