ProbeResultNormalizer.cs 59 KB

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