ProbeResultNormalizer.cs 59 KB

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