ProbeResultNormalizer.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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. if (!string.IsNullOrWhiteSpace(streamInfo.FieldOrder) && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase))
  593. {
  594. stream.IsInterlaced = true;
  595. }
  596. // Filter out junk
  597. if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", StringComparison.OrdinalIgnoreCase))
  598. {
  599. stream.CodecTag = streamInfo.CodecTagString;
  600. }
  601. if (streamInfo.Tags != null)
  602. {
  603. stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
  604. stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
  605. stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
  606. }
  607. if (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase))
  608. {
  609. stream.Type = MediaStreamType.Audio;
  610. stream.Channels = streamInfo.Channels;
  611. if (!string.IsNullOrEmpty(streamInfo.SampleRate))
  612. {
  613. if (int.TryParse(streamInfo.SampleRate, NumberStyles.Any, _usCulture, out var value))
  614. {
  615. stream.SampleRate = value;
  616. }
  617. }
  618. stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
  619. if (streamInfo.BitsPerSample > 0)
  620. {
  621. stream.BitDepth = streamInfo.BitsPerSample;
  622. }
  623. else if (streamInfo.BitsPerRawSample > 0)
  624. {
  625. stream.BitDepth = streamInfo.BitsPerRawSample;
  626. }
  627. }
  628. else if (string.Equals(streamInfo.CodecType, "subtitle", StringComparison.OrdinalIgnoreCase))
  629. {
  630. stream.Type = MediaStreamType.Subtitle;
  631. stream.Codec = NormalizeSubtitleCodec(stream.Codec);
  632. stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
  633. stream.LocalizedDefault = _localization.GetLocalizedString("Default");
  634. stream.LocalizedForced = _localization.GetLocalizedString("Forced");
  635. }
  636. else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))
  637. {
  638. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  639. ? MediaStreamType.EmbeddedImage
  640. : MediaStreamType.Video;
  641. stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
  642. stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
  643. if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
  644. string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
  645. {
  646. stream.Type = MediaStreamType.EmbeddedImage;
  647. }
  648. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  649. {
  650. // How to differentiate between video and embedded image?
  651. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  652. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  653. {
  654. stream.Type = MediaStreamType.Video;
  655. }
  656. else
  657. {
  658. stream.Type = MediaStreamType.EmbeddedImage;
  659. }
  660. }
  661. else
  662. {
  663. stream.Type = MediaStreamType.Video;
  664. }
  665. stream.Width = streamInfo.Width;
  666. stream.Height = streamInfo.Height;
  667. stream.AspectRatio = GetAspectRatio(streamInfo);
  668. if (streamInfo.BitsPerSample > 0)
  669. {
  670. stream.BitDepth = streamInfo.BitsPerSample;
  671. }
  672. else if (streamInfo.BitsPerRawSample > 0)
  673. {
  674. stream.BitDepth = streamInfo.BitsPerRawSample;
  675. }
  676. // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  677. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  678. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  679. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  680. stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase);
  681. if (streamInfo.Refs > 0)
  682. {
  683. stream.RefFrames = streamInfo.Refs;
  684. }
  685. if (!string.IsNullOrEmpty(streamInfo.ColorRange))
  686. {
  687. stream.ColorRange = streamInfo.ColorRange;
  688. }
  689. if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
  690. {
  691. stream.ColorSpace = streamInfo.ColorSpace;
  692. }
  693. if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
  694. {
  695. stream.ColorTransfer = streamInfo.ColorTransfer;
  696. }
  697. if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
  698. {
  699. stream.ColorPrimaries = streamInfo.ColorPrimaries;
  700. }
  701. }
  702. else
  703. {
  704. return null;
  705. }
  706. // Get stream bitrate
  707. var bitrate = 0;
  708. if (!string.IsNullOrEmpty(streamInfo.BitRate))
  709. {
  710. if (int.TryParse(streamInfo.BitRate, NumberStyles.Any, _usCulture, out var value))
  711. {
  712. bitrate = value;
  713. }
  714. }
  715. // The bitrate info of FLAC musics and some videos is included in formatInfo.
  716. if (bitrate == 0
  717. && formatInfo != null
  718. && !string.IsNullOrEmpty(formatInfo.BitRate)
  719. && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
  720. {
  721. // If the stream info doesn't have a bitrate get the value from the media format info
  722. if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, _usCulture, out var value))
  723. {
  724. bitrate = value;
  725. }
  726. }
  727. if (bitrate > 0)
  728. {
  729. stream.BitRate = bitrate;
  730. }
  731. // Extract bitrate info from tag "BPS" if possible.
  732. if (!stream.BitRate.HasValue
  733. && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
  734. || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
  735. {
  736. var bps = GetBPSFromTags(streamInfo);
  737. if (bps != null && bps > 0)
  738. {
  739. stream.BitRate = bps;
  740. }
  741. }
  742. // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
  743. if (!stream.BitRate.HasValue
  744. && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
  745. || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
  746. {
  747. var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
  748. var bytes = GetNumberOfBytesFromTags(streamInfo);
  749. if (durationInSeconds != null && bytes != null)
  750. {
  751. var bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
  752. if (bps > 0)
  753. {
  754. stream.BitRate = bps;
  755. }
  756. }
  757. }
  758. var disposition = streamInfo.Disposition;
  759. if (disposition != null)
  760. {
  761. if (disposition.GetValueOrDefault("default") == 1)
  762. {
  763. stream.IsDefault = true;
  764. }
  765. if (disposition.GetValueOrDefault("forced") == 1)
  766. {
  767. stream.IsForced = true;
  768. }
  769. }
  770. NormalizeStreamTitle(stream);
  771. return stream;
  772. }
  773. private void NormalizeStreamTitle(MediaStream stream)
  774. {
  775. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase))
  776. {
  777. stream.Title = null;
  778. }
  779. if (stream.Type == MediaStreamType.EmbeddedImage)
  780. {
  781. stream.Title = null;
  782. }
  783. }
  784. /// <summary>
  785. /// Gets a string from an FFProbeResult tags dictionary.
  786. /// </summary>
  787. /// <param name="tags">The tags.</param>
  788. /// <param name="key">The key.</param>
  789. /// <returns>System.String.</returns>
  790. private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
  791. {
  792. if (tags == null)
  793. {
  794. return null;
  795. }
  796. tags.TryGetValue(key, out var val);
  797. return val;
  798. }
  799. private string ParseChannelLayout(string input)
  800. {
  801. if (string.IsNullOrEmpty(input))
  802. {
  803. return input;
  804. }
  805. return input.Split('(').FirstOrDefault();
  806. }
  807. private string GetAspectRatio(MediaStreamInfo info)
  808. {
  809. var original = info.DisplayAspectRatio;
  810. var parts = (original ?? string.Empty).Split(':');
  811. if (!(parts.Length == 2 &&
  812. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out var width) &&
  813. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out var height) &&
  814. width > 0 &&
  815. height > 0))
  816. {
  817. width = info.Width;
  818. height = info.Height;
  819. }
  820. if (width > 0 && height > 0)
  821. {
  822. double ratio = width;
  823. ratio /= height;
  824. if (IsClose(ratio, 1.777777778, .03))
  825. {
  826. return "16:9";
  827. }
  828. if (IsClose(ratio, 1.3333333333, .05))
  829. {
  830. return "4:3";
  831. }
  832. if (IsClose(ratio, 1.41))
  833. {
  834. return "1.41:1";
  835. }
  836. if (IsClose(ratio, 1.5))
  837. {
  838. return "1.5:1";
  839. }
  840. if (IsClose(ratio, 1.6))
  841. {
  842. return "1.6:1";
  843. }
  844. if (IsClose(ratio, 1.66666666667))
  845. {
  846. return "5:3";
  847. }
  848. if (IsClose(ratio, 1.85, .02))
  849. {
  850. return "1.85:1";
  851. }
  852. if (IsClose(ratio, 2.35, .025))
  853. {
  854. return "2.35:1";
  855. }
  856. if (IsClose(ratio, 2.4, .025))
  857. {
  858. return "2.40:1";
  859. }
  860. }
  861. return original;
  862. }
  863. private bool IsClose(double d1, double d2, double variance = .005)
  864. {
  865. return Math.Abs(d1 - d2) <= variance;
  866. }
  867. /// <summary>
  868. /// Gets a frame rate from a string value in ffprobe output
  869. /// This could be a number or in the format of 2997/125.
  870. /// </summary>
  871. /// <param name="value">The value.</param>
  872. /// <returns>System.Nullable{System.Single}.</returns>
  873. private float? GetFrameRate(string value)
  874. {
  875. if (!string.IsNullOrEmpty(value))
  876. {
  877. var parts = value.Split('/');
  878. float result;
  879. if (parts.Length == 2)
  880. {
  881. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  882. }
  883. else
  884. {
  885. result = float.Parse(parts[0], _usCulture);
  886. }
  887. return float.IsNaN(result) ? (float?)null : result;
  888. }
  889. return null;
  890. }
  891. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  892. {
  893. if (result.Streams != null)
  894. {
  895. // Get the first info stream
  896. var stream = result.Streams.FirstOrDefault(s => string.Equals(s.CodecType, "audio", StringComparison.OrdinalIgnoreCase));
  897. if (stream != null)
  898. {
  899. // Get duration from stream properties
  900. var duration = stream.Duration;
  901. // If it's not there go into format properties
  902. if (string.IsNullOrEmpty(duration))
  903. {
  904. duration = result.Format.Duration;
  905. }
  906. // If we got something, parse it
  907. if (!string.IsNullOrEmpty(duration))
  908. {
  909. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  910. }
  911. }
  912. }
  913. }
  914. private int? GetBPSFromTags(MediaStreamInfo streamInfo)
  915. {
  916. if (streamInfo != null && streamInfo.Tags != null)
  917. {
  918. var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
  919. if (!string.IsNullOrEmpty(bps)
  920. && int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
  921. {
  922. return parsedBps;
  923. }
  924. }
  925. return null;
  926. }
  927. private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
  928. {
  929. if (streamInfo != null && streamInfo.Tags != null)
  930. {
  931. var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION");
  932. if (!string.IsNullOrEmpty(duration) && TimeSpan.TryParse(duration, out var parsedDuration))
  933. {
  934. return parsedDuration.TotalSeconds;
  935. }
  936. }
  937. return null;
  938. }
  939. private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
  940. {
  941. if (streamInfo != null && streamInfo.Tags != null)
  942. {
  943. var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng") ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
  944. if (!string.IsNullOrEmpty(numberOfBytes)
  945. && long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
  946. {
  947. return parsedBytes;
  948. }
  949. }
  950. return null;
  951. }
  952. private void SetSize(InternalMediaInfoResult data, MediaInfo info)
  953. {
  954. if (data.Format != null)
  955. {
  956. if (!string.IsNullOrEmpty(data.Format.Size))
  957. {
  958. info.Size = long.Parse(data.Format.Size, _usCulture);
  959. }
  960. else
  961. {
  962. info.Size = null;
  963. }
  964. }
  965. }
  966. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  967. {
  968. var people = new List<BaseItemPerson>();
  969. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  970. if (!string.IsNullOrWhiteSpace(composer))
  971. {
  972. foreach (var person in Split(composer, false))
  973. {
  974. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  975. }
  976. }
  977. var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  978. if (!string.IsNullOrWhiteSpace(conductor))
  979. {
  980. foreach (var person in Split(conductor, false))
  981. {
  982. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  983. }
  984. }
  985. var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  986. if (!string.IsNullOrWhiteSpace(lyricist))
  987. {
  988. foreach (var person in Split(lyricist, false))
  989. {
  990. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  991. }
  992. }
  993. // Check for writer some music is tagged that way as alternative to composer/lyricist
  994. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  995. if (!string.IsNullOrWhiteSpace(writer))
  996. {
  997. foreach (var person in Split(writer, false))
  998. {
  999. people.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  1000. }
  1001. }
  1002. audio.People = people.ToArray();
  1003. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  1004. if (string.IsNullOrWhiteSpace(albumArtist))
  1005. {
  1006. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  1007. }
  1008. if (string.IsNullOrWhiteSpace(albumArtist))
  1009. {
  1010. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  1011. }
  1012. if (string.IsNullOrWhiteSpace(albumArtist))
  1013. {
  1014. audio.AlbumArtists = Array.Empty<string>();
  1015. }
  1016. else
  1017. {
  1018. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  1019. .DistinctNames()
  1020. .ToArray();
  1021. }
  1022. if (audio.AlbumArtists.Length == 0)
  1023. {
  1024. audio.AlbumArtists = audio.Artists;
  1025. }
  1026. // Track number
  1027. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  1028. // Disc number
  1029. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  1030. // There's several values in tags may or may not be present
  1031. FetchStudios(audio, tags, "organization");
  1032. FetchStudios(audio, tags, "ensemble");
  1033. FetchStudios(audio, tags, "publisher");
  1034. FetchStudios(audio, tags, "label");
  1035. // These support mulitple values, but for now we only store the first.
  1036. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"))
  1037. ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  1038. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
  1039. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"))
  1040. ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  1041. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb);
  1042. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"))
  1043. ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  1044. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
  1045. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"))
  1046. ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  1047. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
  1048. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"))
  1049. ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  1050. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb);
  1051. }
  1052. private string GetMultipleMusicBrainzId(string value)
  1053. {
  1054. if (string.IsNullOrWhiteSpace(value))
  1055. {
  1056. return null;
  1057. }
  1058. return value.Split('/', StringSplitOptions.RemoveEmptyEntries)
  1059. .Select(i => i.Trim())
  1060. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1061. }
  1062. /// <summary>
  1063. /// Splits the specified val.
  1064. /// </summary>
  1065. /// <param name="val">The val.</param>
  1066. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  1067. /// <returns>System.String[][].</returns>
  1068. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  1069. {
  1070. // Only use the comma as a delimeter if there are no slashes or pipes.
  1071. // We want to be careful not to split names that have commas in them
  1072. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i, StringComparison.Ordinal) != -1) ?
  1073. _nameDelimiters :
  1074. new[] { ',' };
  1075. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  1076. .Where(i => !string.IsNullOrWhiteSpace(i))
  1077. .Select(i => i.Trim());
  1078. }
  1079. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  1080. {
  1081. if (splitFeaturing)
  1082. {
  1083. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  1084. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  1085. }
  1086. var artistsFound = new List<string>();
  1087. foreach (var whitelistArtist in SplitWhitelist)
  1088. {
  1089. var originalVal = val;
  1090. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  1091. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  1092. {
  1093. artistsFound.Add(whitelistArtist);
  1094. }
  1095. }
  1096. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  1097. .Where(i => !string.IsNullOrWhiteSpace(i))
  1098. .Select(i => i.Trim());
  1099. artistsFound.AddRange(artists);
  1100. return artistsFound;
  1101. }
  1102. /// <summary>
  1103. /// Gets the studios from the tags collection.
  1104. /// </summary>
  1105. /// <param name="info">The info.</param>
  1106. /// <param name="tags">The tags.</param>
  1107. /// <param name="tagName">Name of the tag.</param>
  1108. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  1109. {
  1110. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  1111. if (!string.IsNullOrEmpty(val))
  1112. {
  1113. var studios = Split(val, true);
  1114. var studioList = new List<string>();
  1115. foreach (var studio in studios)
  1116. {
  1117. // Sometimes the artist name is listed here, account for that
  1118. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  1119. {
  1120. continue;
  1121. }
  1122. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  1123. {
  1124. continue;
  1125. }
  1126. studioList.Add(studio);
  1127. }
  1128. info.Studios = studioList
  1129. .Where(i => !string.IsNullOrWhiteSpace(i))
  1130. .Distinct(StringComparer.OrdinalIgnoreCase)
  1131. .ToArray();
  1132. }
  1133. }
  1134. /// <summary>
  1135. /// Gets the genres from the tags collection.
  1136. /// </summary>
  1137. /// <param name="info">The information.</param>
  1138. /// <param name="tags">The tags.</param>
  1139. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  1140. {
  1141. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  1142. if (!string.IsNullOrEmpty(val))
  1143. {
  1144. var genres = new List<string>(info.Genres);
  1145. foreach (var genre in Split(val, true))
  1146. {
  1147. genres.Add(genre);
  1148. }
  1149. info.Genres = genres
  1150. .Where(i => !string.IsNullOrWhiteSpace(i))
  1151. .Distinct(StringComparer.OrdinalIgnoreCase)
  1152. .ToArray();
  1153. }
  1154. }
  1155. /// <summary>
  1156. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'.
  1157. /// </summary>
  1158. /// <param name="tags">The tags.</param>
  1159. /// <param name="tagName">Name of the tag.</param>
  1160. /// <returns>System.Nullable{System.Int32}.</returns>
  1161. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  1162. {
  1163. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  1164. if (!string.IsNullOrEmpty(disc))
  1165. {
  1166. disc = disc.Split('/')[0];
  1167. if (int.TryParse(disc, out var num))
  1168. {
  1169. return num;
  1170. }
  1171. }
  1172. return null;
  1173. }
  1174. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  1175. {
  1176. var info = new ChapterInfo();
  1177. if (chapter.Tags != null)
  1178. {
  1179. if (chapter.Tags.TryGetValue("title", out string name))
  1180. {
  1181. info.Name = name;
  1182. }
  1183. }
  1184. // Limit accuracy to milliseconds to match xml saving
  1185. var secondsString = chapter.StartTime;
  1186. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
  1187. {
  1188. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  1189. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  1190. }
  1191. return info;
  1192. }
  1193. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1194. {
  1195. if (data.Format == null || data.Format.Tags == null)
  1196. {
  1197. return;
  1198. }
  1199. var genres = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/Genre");
  1200. if (!string.IsNullOrWhiteSpace(genres))
  1201. {
  1202. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  1203. .Where(i => !string.IsNullOrWhiteSpace(i))
  1204. .Select(i => i.Trim())
  1205. .ToList();
  1206. // If this is empty then don't overwrite genres that might have been fetched earlier
  1207. if (genreList.Count > 0)
  1208. {
  1209. video.Genres = genreList.ToArray();
  1210. }
  1211. }
  1212. var officialRating = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/ParentalRating");
  1213. if (!string.IsNullOrWhiteSpace(officialRating))
  1214. {
  1215. video.OfficialRating = officialRating;
  1216. }
  1217. var people = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/MediaCredits");
  1218. if (!string.IsNullOrEmpty(people))
  1219. {
  1220. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  1221. .Where(i => !string.IsNullOrWhiteSpace(i))
  1222. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  1223. .ToArray();
  1224. }
  1225. var year = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/OriginalReleaseTime");
  1226. if (!string.IsNullOrWhiteSpace(year))
  1227. {
  1228. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out var val))
  1229. {
  1230. video.ProductionYear = val;
  1231. }
  1232. }
  1233. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/MediaOriginalBroadcastDateTime");
  1234. if (!string.IsNullOrWhiteSpace(premiereDateString))
  1235. {
  1236. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1237. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1238. if (DateTime.TryParse(year, null, DateTimeStyles.None, out var val))
  1239. {
  1240. video.PremiereDate = val.ToUniversalTime();
  1241. }
  1242. }
  1243. var description = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/SubTitleDescription");
  1244. var subTitle = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/SubTitle");
  1245. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1246. // 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
  1247. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1248. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1249. // 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]
  1250. // 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]
  1251. if (string.IsNullOrWhiteSpace(subTitle)
  1252. && !string.IsNullOrWhiteSpace(description)
  1253. && 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
  1254. {
  1255. string[] parts = description.Split(':');
  1256. if (parts.Length > 0)
  1257. {
  1258. string subtitle = parts[0];
  1259. try
  1260. {
  1261. if (subtitle.Contains('/', StringComparison.Ordinal)) // It contains a episode number and season number
  1262. {
  1263. string[] numbers = subtitle.Split(' ');
  1264. video.IndexNumber = int.Parse(numbers[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/')[0], CultureInfo.InvariantCulture);
  1265. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/')[1], CultureInfo.InvariantCulture);
  1266. description = string.Join(' ', numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  1267. }
  1268. else
  1269. {
  1270. // Switch to default parsing
  1271. if (subtitle.Contains('.', StringComparison.Ordinal))
  1272. {
  1273. // skip the comment, keep the subtitle
  1274. description = string.Join('.', subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  1275. }
  1276. else
  1277. {
  1278. description = subtitle.Trim(); // Clean up whitespaces and save it
  1279. }
  1280. }
  1281. }
  1282. catch (Exception ex)
  1283. {
  1284. _logger.LogError(ex, "Error while parsing subtitle field");
  1285. // Default parsing
  1286. if (subtitle.Contains('.', StringComparison.Ordinal))
  1287. {
  1288. // skip the comment, keep the subtitle
  1289. description = string.Join('.', subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  1290. }
  1291. else
  1292. {
  1293. description = subtitle.Trim(); // Clean up whitespaces and save it
  1294. }
  1295. }
  1296. }
  1297. }
  1298. if (!string.IsNullOrWhiteSpace(description))
  1299. {
  1300. video.Overview = description;
  1301. }
  1302. }
  1303. private void ExtractTimestamp(MediaInfo video)
  1304. {
  1305. if (video.VideoType == VideoType.VideoFile)
  1306. {
  1307. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  1308. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  1309. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1310. {
  1311. try
  1312. {
  1313. video.Timestamp = GetMpegTimestamp(video.Path);
  1314. _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
  1315. }
  1316. catch (Exception ex)
  1317. {
  1318. _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
  1319. video.Timestamp = null;
  1320. }
  1321. }
  1322. }
  1323. }
  1324. // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
  1325. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1326. {
  1327. var packetBuffer = new byte[197];
  1328. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  1329. {
  1330. fs.Read(packetBuffer);
  1331. }
  1332. if (packetBuffer[0] == 71)
  1333. {
  1334. return TransportStreamTimestamp.None;
  1335. }
  1336. if ((packetBuffer[4] == 71) && (packetBuffer[196] == 71))
  1337. {
  1338. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1339. {
  1340. return TransportStreamTimestamp.Zero;
  1341. }
  1342. return TransportStreamTimestamp.Valid;
  1343. }
  1344. return TransportStreamTimestamp.None;
  1345. }
  1346. }
  1347. }