ProbeResultNormalizer.cs 62 KB

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