ProbeResultNormalizer.cs 61 KB

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