ProbeResultNormalizer.cs 61 KB

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