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