ProbeResultNormalizer.cs 60 KB

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