2
0

ProbeResultNormalizer.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  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 CultureInfo _usCulture = new ("en-US");
  28. private readonly ILogger _logger;
  29. private readonly ILocalizationManager _localization;
  30. private string[] _splitWhiteList;
  31. public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
  32. {
  33. _logger = logger;
  34. _localization = localization;
  35. }
  36. private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
  37. {
  38. "AC/DC",
  39. "Au/Ra",
  40. "이달의 소녀 1/3",
  41. "LOONA 1/3",
  42. "LOONA / yyxy",
  43. "LOONA / ODD EYE CIRCLE",
  44. "K/DA"
  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, _usCulture, 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, _usCulture)).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, _usCulture, 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. }
  596. else if (string.Equals(streamInfo.CodecType, "subtitle", StringComparison.OrdinalIgnoreCase))
  597. {
  598. stream.Type = MediaStreamType.Subtitle;
  599. stream.Codec = NormalizeSubtitleCodec(stream.Codec);
  600. stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
  601. stream.LocalizedDefault = _localization.GetLocalizedString("Default");
  602. stream.LocalizedForced = _localization.GetLocalizedString("Forced");
  603. }
  604. else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))
  605. {
  606. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  607. ? MediaStreamType.EmbeddedImage
  608. : MediaStreamType.Video;
  609. stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
  610. stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
  611. if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
  612. string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
  613. {
  614. stream.Type = MediaStreamType.EmbeddedImage;
  615. }
  616. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  617. {
  618. // How to differentiate between video and embedded image?
  619. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  620. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  621. {
  622. stream.Type = MediaStreamType.Video;
  623. }
  624. else
  625. {
  626. stream.Type = MediaStreamType.EmbeddedImage;
  627. }
  628. }
  629. else
  630. {
  631. stream.Type = MediaStreamType.Video;
  632. }
  633. stream.Width = streamInfo.Width;
  634. stream.Height = streamInfo.Height;
  635. stream.AspectRatio = GetAspectRatio(streamInfo);
  636. if (streamInfo.BitsPerSample > 0)
  637. {
  638. stream.BitDepth = streamInfo.BitsPerSample;
  639. }
  640. else if (streamInfo.BitsPerRawSample > 0)
  641. {
  642. stream.BitDepth = streamInfo.BitsPerRawSample;
  643. }
  644. if (!stream.BitDepth.HasValue)
  645. {
  646. if (!string.IsNullOrEmpty(streamInfo.PixelFormat)
  647. && streamInfo.PixelFormat.Contains("p10", StringComparison.OrdinalIgnoreCase))
  648. {
  649. stream.BitDepth = 10;
  650. }
  651. if (!string.IsNullOrEmpty(streamInfo.Profile)
  652. && (streamInfo.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
  653. || streamInfo.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase)
  654. || streamInfo.Profile.Contains("Profile 2", StringComparison.OrdinalIgnoreCase)))
  655. {
  656. stream.BitDepth = 10;
  657. }
  658. }
  659. // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  660. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  661. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  662. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  663. stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase);
  664. if (streamInfo.Refs > 0)
  665. {
  666. stream.RefFrames = streamInfo.Refs;
  667. }
  668. if (!string.IsNullOrEmpty(streamInfo.ColorRange))
  669. {
  670. stream.ColorRange = streamInfo.ColorRange;
  671. }
  672. if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
  673. {
  674. stream.ColorSpace = streamInfo.ColorSpace;
  675. }
  676. if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
  677. {
  678. stream.ColorTransfer = streamInfo.ColorTransfer;
  679. }
  680. if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
  681. {
  682. stream.ColorPrimaries = streamInfo.ColorPrimaries;
  683. }
  684. }
  685. else
  686. {
  687. return null;
  688. }
  689. // Get stream bitrate
  690. var bitrate = 0;
  691. if (!string.IsNullOrEmpty(streamInfo.BitRate))
  692. {
  693. if (int.TryParse(streamInfo.BitRate, NumberStyles.Any, _usCulture, out var value))
  694. {
  695. bitrate = value;
  696. }
  697. }
  698. // The bitrate info of FLAC musics and some videos is included in formatInfo.
  699. if (bitrate == 0
  700. && formatInfo != null
  701. && !string.IsNullOrEmpty(formatInfo.BitRate)
  702. && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
  703. {
  704. // If the stream info doesn't have a bitrate get the value from the media format info
  705. if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, _usCulture, out var value))
  706. {
  707. bitrate = value;
  708. }
  709. }
  710. if (bitrate > 0)
  711. {
  712. stream.BitRate = bitrate;
  713. }
  714. // Extract bitrate info from tag "BPS" if possible.
  715. if (!stream.BitRate.HasValue
  716. && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
  717. || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
  718. {
  719. var bps = GetBPSFromTags(streamInfo);
  720. if (bps > 0)
  721. {
  722. stream.BitRate = bps;
  723. }
  724. }
  725. // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
  726. if (!stream.BitRate.HasValue
  727. && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
  728. || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
  729. {
  730. var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
  731. var bytes = GetNumberOfBytesFromTags(streamInfo);
  732. if (durationInSeconds != null && bytes != null)
  733. {
  734. var bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
  735. if (bps > 0)
  736. {
  737. stream.BitRate = bps;
  738. }
  739. }
  740. }
  741. var disposition = streamInfo.Disposition;
  742. if (disposition != null)
  743. {
  744. if (disposition.GetValueOrDefault("default") == 1)
  745. {
  746. stream.IsDefault = true;
  747. }
  748. if (disposition.GetValueOrDefault("forced") == 1)
  749. {
  750. stream.IsForced = true;
  751. }
  752. }
  753. NormalizeStreamTitle(stream);
  754. return stream;
  755. }
  756. private void NormalizeStreamTitle(MediaStream stream)
  757. {
  758. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase))
  759. {
  760. stream.Title = null;
  761. }
  762. if (stream.Type == MediaStreamType.EmbeddedImage)
  763. {
  764. stream.Title = null;
  765. }
  766. }
  767. /// <summary>
  768. /// Gets a string from an FFProbeResult tags dictionary.
  769. /// </summary>
  770. /// <param name="tags">The tags.</param>
  771. /// <param name="key">The key.</param>
  772. /// <returns>System.String.</returns>
  773. private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
  774. {
  775. if (tags == null)
  776. {
  777. return null;
  778. }
  779. tags.TryGetValue(key, out var val);
  780. return val;
  781. }
  782. private string ParseChannelLayout(string input)
  783. {
  784. if (string.IsNullOrEmpty(input))
  785. {
  786. return null;
  787. }
  788. return input.Split('(').FirstOrDefault();
  789. }
  790. private string GetAspectRatio(MediaStreamInfo info)
  791. {
  792. var original = info.DisplayAspectRatio;
  793. var parts = (original ?? string.Empty).Split(':');
  794. if (!(parts.Length == 2 &&
  795. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out var width) &&
  796. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out var height) &&
  797. width > 0 &&
  798. height > 0))
  799. {
  800. width = info.Width;
  801. height = info.Height;
  802. }
  803. if (width > 0 && height > 0)
  804. {
  805. double ratio = width;
  806. ratio /= height;
  807. if (IsClose(ratio, 1.777777778, .03))
  808. {
  809. return "16:9";
  810. }
  811. if (IsClose(ratio, 1.3333333333, .05))
  812. {
  813. return "4:3";
  814. }
  815. if (IsClose(ratio, 1.41))
  816. {
  817. return "1.41:1";
  818. }
  819. if (IsClose(ratio, 1.5))
  820. {
  821. return "1.5:1";
  822. }
  823. if (IsClose(ratio, 1.6))
  824. {
  825. return "1.6:1";
  826. }
  827. if (IsClose(ratio, 1.66666666667))
  828. {
  829. return "5:3";
  830. }
  831. if (IsClose(ratio, 1.85, .02))
  832. {
  833. return "1.85:1";
  834. }
  835. if (IsClose(ratio, 2.35, .025))
  836. {
  837. return "2.35:1";
  838. }
  839. if (IsClose(ratio, 2.4, .025))
  840. {
  841. return "2.40:1";
  842. }
  843. }
  844. return original;
  845. }
  846. private bool IsClose(double d1, double d2, double variance = .005)
  847. {
  848. return Math.Abs(d1 - d2) <= variance;
  849. }
  850. /// <summary>
  851. /// Gets a frame rate from a string value in ffprobe output
  852. /// This could be a number or in the format of 2997/125.
  853. /// </summary>
  854. /// <param name="value">The value.</param>
  855. /// <returns>System.Nullable{System.Single}.</returns>
  856. private float? GetFrameRate(string value)
  857. {
  858. if (string.IsNullOrEmpty(value))
  859. {
  860. return null;
  861. }
  862. var parts = value.Split('/');
  863. float result;
  864. if (parts.Length == 2)
  865. {
  866. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  867. }
  868. else
  869. {
  870. result = float.Parse(parts[0], _usCulture);
  871. }
  872. return float.IsNaN(result) ? null : result;
  873. }
  874. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  875. {
  876. // Get the first info stream
  877. var stream = result.Streams?.FirstOrDefault(s => string.Equals(s.CodecType, "audio", StringComparison.OrdinalIgnoreCase));
  878. if (stream == null)
  879. {
  880. return;
  881. }
  882. // Get duration from stream properties
  883. var duration = stream.Duration;
  884. // If it's not there go into format properties
  885. if (string.IsNullOrEmpty(duration))
  886. {
  887. duration = result.Format.Duration;
  888. }
  889. // If we got something, parse it
  890. if (!string.IsNullOrEmpty(duration))
  891. {
  892. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  893. }
  894. }
  895. private int? GetBPSFromTags(MediaStreamInfo streamInfo)
  896. {
  897. if (streamInfo?.Tags == null)
  898. {
  899. return null;
  900. }
  901. var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
  902. if (!string.IsNullOrEmpty(bps)
  903. && int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
  904. {
  905. return parsedBps;
  906. }
  907. return null;
  908. }
  909. private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
  910. {
  911. if (streamInfo?.Tags == null)
  912. {
  913. return null;
  914. }
  915. var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION");
  916. if (!string.IsNullOrEmpty(duration) && TimeSpan.TryParse(duration, out var parsedDuration))
  917. {
  918. return parsedDuration.TotalSeconds;
  919. }
  920. return null;
  921. }
  922. private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
  923. {
  924. if (streamInfo?.Tags == null)
  925. {
  926. return null;
  927. }
  928. var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
  929. ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
  930. if (!string.IsNullOrEmpty(numberOfBytes)
  931. && long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
  932. {
  933. return parsedBytes;
  934. }
  935. return null;
  936. }
  937. private void SetSize(InternalMediaInfoResult data, MediaInfo info)
  938. {
  939. if (data.Format == null)
  940. {
  941. return;
  942. }
  943. info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, _usCulture);
  944. }
  945. private void SetAudioInfoFromTags(MediaInfo audio, IReadOnlyDictionary<string, string> tags)
  946. {
  947. var people = new List<BaseItemPerson>();
  948. if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
  949. {
  950. foreach (var person in Split(composer, false))
  951. {
  952. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  953. }
  954. }
  955. if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
  956. {
  957. foreach (var person in Split(conductor, false))
  958. {
  959. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  960. }
  961. }
  962. if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
  963. {
  964. foreach (var person in Split(lyricist, false))
  965. {
  966. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  967. }
  968. }
  969. if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
  970. {
  971. foreach (var person in Split(performer, false))
  972. {
  973. Match match = _performerPattern.Match(person);
  974. // 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.
  975. if (match.Success)
  976. {
  977. people.Add(new BaseItemPerson
  978. {
  979. Name = match.Groups["name"].Value,
  980. Type = PersonType.Actor,
  981. Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
  982. });
  983. }
  984. }
  985. }
  986. // In cases where there isn't sufficient information as to which role a writer performed on a recording, tagging software uses the "writer" tag.
  987. if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
  988. {
  989. foreach (var person in Split(writer, false))
  990. {
  991. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  992. }
  993. }
  994. if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
  995. {
  996. foreach (var person in Split(arranger, false))
  997. {
  998. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Arranger });
  999. }
  1000. }
  1001. if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
  1002. {
  1003. foreach (var person in Split(engineer, false))
  1004. {
  1005. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Engineer });
  1006. }
  1007. }
  1008. if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
  1009. {
  1010. foreach (var person in Split(mixer, false))
  1011. {
  1012. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Mixer });
  1013. }
  1014. }
  1015. if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
  1016. {
  1017. foreach (var person in Split(remixer, false))
  1018. {
  1019. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Remixer });
  1020. }
  1021. }
  1022. audio.People = people.ToArray();
  1023. // Set album artist
  1024. var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
  1025. audio.AlbumArtists = albumArtist != null
  1026. ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
  1027. : Array.Empty<string>();
  1028. // Set album artist to artist if empty
  1029. if (audio.AlbumArtists.Length == 0)
  1030. {
  1031. audio.AlbumArtists = audio.Artists;
  1032. }
  1033. // Track number
  1034. audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
  1035. // Disc number
  1036. audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
  1037. // There's several values in tags may or may not be present
  1038. FetchStudios(audio, tags, "organization");
  1039. FetchStudios(audio, tags, "ensemble");
  1040. FetchStudios(audio, tags, "publisher");
  1041. FetchStudios(audio, tags, "label");
  1042. // These support multiple values, but for now we only store the first.
  1043. var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
  1044. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
  1045. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
  1046. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
  1047. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
  1048. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb);
  1049. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
  1050. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
  1051. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
  1052. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
  1053. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
  1054. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
  1055. mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
  1056. ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
  1057. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb);
  1058. }
  1059. private string GetMultipleMusicBrainzId(string value)
  1060. {
  1061. if (string.IsNullOrWhiteSpace(value))
  1062. {
  1063. return null;
  1064. }
  1065. return value.Split('/', StringSplitOptions.RemoveEmptyEntries)
  1066. .Select(i => i.Trim())
  1067. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1068. }
  1069. /// <summary>
  1070. /// Splits the specified val.
  1071. /// </summary>
  1072. /// <param name="val">The val.</param>
  1073. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  1074. /// <returns>System.String[][].</returns>
  1075. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  1076. {
  1077. // Only use the comma as a delimiter if there are no slashes or pipes.
  1078. // We want to be careful not to split names that have commas in them
  1079. var delimiter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i, StringComparison.Ordinal) != -1) ?
  1080. _nameDelimiters :
  1081. new[] { ',' };
  1082. return val.Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
  1083. .Where(i => !string.IsNullOrWhiteSpace(i))
  1084. .Select(i => i.Trim());
  1085. }
  1086. private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
  1087. {
  1088. if (splitFeaturing)
  1089. {
  1090. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  1091. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  1092. }
  1093. var artistsFound = new List<string>();
  1094. foreach (var whitelistArtist in SplitWhitelist)
  1095. {
  1096. var originalVal = val;
  1097. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  1098. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  1099. {
  1100. artistsFound.Add(whitelistArtist);
  1101. }
  1102. }
  1103. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  1104. .Where(i => !string.IsNullOrWhiteSpace(i))
  1105. .Select(i => i.Trim());
  1106. artistsFound.AddRange(artists);
  1107. return artistsFound.DistinctNames();
  1108. }
  1109. /// <summary>
  1110. /// Gets the studios from the tags collection.
  1111. /// </summary>
  1112. /// <param name="info">The info.</param>
  1113. /// <param name="tags">The tags.</param>
  1114. /// <param name="tagName">Name of the tag.</param>
  1115. private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
  1116. {
  1117. var val = tags.GetValueOrDefault(tagName);
  1118. if (string.IsNullOrEmpty(val))
  1119. {
  1120. return;
  1121. }
  1122. var studios = Split(val, true);
  1123. var studioList = new List<string>();
  1124. foreach (var studio in studios)
  1125. {
  1126. if (string.IsNullOrWhiteSpace(studio))
  1127. {
  1128. continue;
  1129. }
  1130. // Don't add artist/album artist name to studios, even if it's listed there
  1131. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase)
  1132. || info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  1133. {
  1134. continue;
  1135. }
  1136. studioList.Add(studio);
  1137. }
  1138. info.Studios = studioList
  1139. .Distinct(StringComparer.OrdinalIgnoreCase)
  1140. .ToArray();
  1141. }
  1142. /// <summary>
  1143. /// Gets the genres from the tags collection.
  1144. /// </summary>
  1145. /// <param name="info">The information.</param>
  1146. /// <param name="tags">The tags.</param>
  1147. private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
  1148. {
  1149. var genreVal = tags.GetValueOrDefault("genre");
  1150. if (string.IsNullOrEmpty(genreVal))
  1151. {
  1152. return;
  1153. }
  1154. var genres = new List<string>(info.Genres);
  1155. foreach (var genre in Split(genreVal, true))
  1156. {
  1157. if (string.IsNullOrWhiteSpace(genre))
  1158. {
  1159. continue;
  1160. }
  1161. genres.Add(genre);
  1162. }
  1163. info.Genres = genres
  1164. .Distinct(StringComparer.OrdinalIgnoreCase)
  1165. .ToArray();
  1166. }
  1167. /// <summary>
  1168. /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
  1169. /// </summary>
  1170. /// <param name="tags">The tags.</param>
  1171. /// <param name="tagName">Name of the tag.</param>
  1172. /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
  1173. private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
  1174. {
  1175. var disc = tags.GetValueOrDefault(tagName);
  1176. if (!string.IsNullOrEmpty(disc) && int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
  1177. {
  1178. return discNum;
  1179. }
  1180. return null;
  1181. }
  1182. private static ChapterInfo GetChapterInfo(MediaChapter chapter)
  1183. {
  1184. var info = new ChapterInfo();
  1185. if (chapter.Tags != null && chapter.Tags.TryGetValue("title", out string name))
  1186. {
  1187. info.Name = name;
  1188. }
  1189. // Limit accuracy to milliseconds to match xml saving
  1190. var secondsString = chapter.StartTime;
  1191. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
  1192. {
  1193. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  1194. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  1195. }
  1196. return info;
  1197. }
  1198. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1199. {
  1200. var tags = data.Format?.Tags;
  1201. if (tags == null)
  1202. {
  1203. return;
  1204. }
  1205. if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
  1206. {
  1207. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  1208. .Where(i => !string.IsNullOrWhiteSpace(i))
  1209. .Select(i => i.Trim())
  1210. .ToList();
  1211. // If this is empty then don't overwrite genres that might have been fetched earlier
  1212. if (genreList.Count > 0)
  1213. {
  1214. video.Genres = genreList.ToArray();
  1215. }
  1216. }
  1217. if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRating))
  1218. {
  1219. video.OfficialRating = officialRating;
  1220. }
  1221. if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
  1222. {
  1223. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  1224. .Where(i => !string.IsNullOrWhiteSpace(i))
  1225. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  1226. .ToArray();
  1227. }
  1228. if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, _usCulture, out var parsedYear))
  1229. {
  1230. video.ProductionYear = parsedYear;
  1231. }
  1232. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1233. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1234. if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(year, null, DateTimeStyles.None, out var parsedDate))
  1235. {
  1236. video.PremiereDate = parsedDate.ToUniversalTime();
  1237. }
  1238. var description = tags.GetValueOrDefault("WM/SubTitleDescription");
  1239. var subTitle = tags.GetValueOrDefault("WM/SubTitle");
  1240. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1241. // 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
  1242. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1243. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1244. // 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]
  1245. // 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]
  1246. if (string.IsNullOrWhiteSpace(subTitle)
  1247. && !string.IsNullOrWhiteSpace(description)
  1248. && description.AsSpan()[0..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].IndexOf(':') != -1) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
  1249. {
  1250. string[] descriptionParts = description.Split(':');
  1251. if (descriptionParts.Length > 0)
  1252. {
  1253. string subtitle = descriptionParts[0];
  1254. try
  1255. {
  1256. // Check if it contains a episode number and season number
  1257. if (subtitle.Contains('/', StringComparison.Ordinal))
  1258. {
  1259. string[] subtitleParts = subtitle.Split(' ');
  1260. string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/');
  1261. video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
  1262. // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
  1263. // Skip the numbers, concatenate the rest, trim and set as new description
  1264. description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1265. }
  1266. else if (subtitle.Contains('.', StringComparison.Ordinal))
  1267. {
  1268. var subtitleParts = subtitle.Split('.');
  1269. description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1270. }
  1271. else
  1272. {
  1273. description = subtitle.Trim();
  1274. }
  1275. }
  1276. catch (Exception ex)
  1277. {
  1278. _logger.LogError(ex, "Error while parsing subtitle field");
  1279. // Fallback to default parsing
  1280. if (subtitle.Contains('.', StringComparison.Ordinal))
  1281. {
  1282. var subtitleParts = subtitle.Split('.');
  1283. description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
  1284. }
  1285. else
  1286. {
  1287. description = subtitle.Trim();
  1288. }
  1289. }
  1290. }
  1291. }
  1292. if (!string.IsNullOrWhiteSpace(description))
  1293. {
  1294. video.Overview = description;
  1295. }
  1296. }
  1297. private void ExtractTimestamp(MediaInfo video)
  1298. {
  1299. if (video.VideoType != VideoType.VideoFile)
  1300. {
  1301. return;
  1302. }
  1303. if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
  1304. && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
  1305. && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1306. {
  1307. return;
  1308. }
  1309. try
  1310. {
  1311. video.Timestamp = GetMpegTimestamp(video.Path);
  1312. _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
  1313. }
  1314. catch (Exception ex)
  1315. {
  1316. video.Timestamp = null;
  1317. _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
  1318. }
  1319. }
  1320. // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
  1321. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1322. {
  1323. var packetBuffer = new byte[197];
  1324. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
  1325. {
  1326. fs.Read(packetBuffer);
  1327. }
  1328. if (packetBuffer[0] == 71)
  1329. {
  1330. return TransportStreamTimestamp.None;
  1331. }
  1332. if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
  1333. {
  1334. return TransportStreamTimestamp.None;
  1335. }
  1336. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1337. {
  1338. return TransportStreamTimestamp.Zero;
  1339. }
  1340. return TransportStreamTimestamp.Valid;
  1341. }
  1342. }
  1343. }