ProbeResultNormalizer.cs 62 KB

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