ProbeResultNormalizer.cs 56 KB

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