ProbeResultNormalizer.cs 53 KB

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