ProbeResultNormalizer.cs 60 KB

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