ProbeResultNormalizer.cs 62 KB

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