ProbeResultNormalizer.cs 54 KB

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