ProbeResultNormalizer.cs 58 KB

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