ProbeResultNormalizer.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  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. // Filter out junk
  469. if (!string.IsNullOrWhiteSpace(streamInfo.codec_tag_string) && streamInfo.codec_tag_string.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
  470. {
  471. attachment.CodecTag = streamInfo.codec_tag_string;
  472. }
  473. if (streamInfo.tags != null)
  474. {
  475. attachment.Filename = GetDictionaryValue(streamInfo.tags, "filename");
  476. attachment.MIMEType = GetDictionaryValue(streamInfo.tags, "mimetype");
  477. attachment.Comment = GetDictionaryValue(streamInfo.tags, "comment");
  478. }
  479. return attachment;
  480. }
  481. /// <summary>
  482. /// Converts ffprobe stream info to our MediaStream class
  483. /// </summary>
  484. /// <param name="isAudio">if set to <c>true</c> [is info].</param>
  485. /// <param name="streamInfo">The stream info.</param>
  486. /// <param name="formatInfo">The format info.</param>
  487. /// <returns>MediaStream.</returns>
  488. private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  489. {
  490. // These are mp4 chapters
  491. if (string.Equals(streamInfo.codec_name, "mov_text", StringComparison.OrdinalIgnoreCase))
  492. {
  493. // Edit: but these are also sometimes subtitles?
  494. //return null;
  495. }
  496. var stream = new MediaStream
  497. {
  498. Codec = streamInfo.codec_name,
  499. Profile = streamInfo.profile,
  500. Level = streamInfo.level,
  501. Index = streamInfo.index,
  502. PixelFormat = streamInfo.pix_fmt,
  503. NalLengthSize = streamInfo.nal_length_size,
  504. TimeBase = streamInfo.time_base,
  505. CodecTimeBase = streamInfo.codec_time_base
  506. };
  507. if (string.Equals(streamInfo.is_avc, "true", StringComparison.OrdinalIgnoreCase) ||
  508. string.Equals(streamInfo.is_avc, "1", StringComparison.OrdinalIgnoreCase))
  509. {
  510. stream.IsAVC = true;
  511. }
  512. else if (string.Equals(streamInfo.is_avc, "false", StringComparison.OrdinalIgnoreCase) ||
  513. string.Equals(streamInfo.is_avc, "0", StringComparison.OrdinalIgnoreCase))
  514. {
  515. stream.IsAVC = false;
  516. }
  517. if (!string.IsNullOrWhiteSpace(streamInfo.field_order) && !string.Equals(streamInfo.field_order, "progressive", StringComparison.OrdinalIgnoreCase))
  518. {
  519. stream.IsInterlaced = true;
  520. }
  521. // Filter out junk
  522. if (!string.IsNullOrWhiteSpace(streamInfo.codec_tag_string) && streamInfo.codec_tag_string.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
  523. {
  524. stream.CodecTag = streamInfo.codec_tag_string;
  525. }
  526. if (streamInfo.tags != null)
  527. {
  528. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  529. stream.Comment = GetDictionaryValue(streamInfo.tags, "comment");
  530. stream.Title = GetDictionaryValue(streamInfo.tags, "title");
  531. }
  532. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  533. {
  534. stream.Type = MediaStreamType.Audio;
  535. stream.Channels = streamInfo.channels;
  536. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  537. {
  538. if (int.TryParse(streamInfo.sample_rate, NumberStyles.Any, _usCulture, out var value))
  539. {
  540. stream.SampleRate = value;
  541. }
  542. }
  543. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  544. if (streamInfo.bits_per_sample > 0)
  545. {
  546. stream.BitDepth = streamInfo.bits_per_sample;
  547. }
  548. else if (streamInfo.bits_per_raw_sample > 0)
  549. {
  550. stream.BitDepth = streamInfo.bits_per_raw_sample;
  551. }
  552. }
  553. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  554. {
  555. stream.Type = MediaStreamType.Subtitle;
  556. stream.Codec = NormalizeSubtitleCodec(stream.Codec);
  557. stream.localizedUndefined = _localization.GetLocalizedString("Undefined");
  558. stream.localizedDefault = _localization.GetLocalizedString("Default");
  559. stream.localizedForced = _localization.GetLocalizedString("Forced");
  560. }
  561. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  562. {
  563. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  564. ? MediaStreamType.EmbeddedImage
  565. : MediaStreamType.Video;
  566. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  567. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  568. if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
  569. string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
  570. {
  571. stream.Type = MediaStreamType.EmbeddedImage;
  572. }
  573. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  574. {
  575. // How to differentiate between video and embedded image?
  576. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  577. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  578. {
  579. stream.Type = MediaStreamType.Video;
  580. }
  581. else
  582. {
  583. stream.Type = MediaStreamType.EmbeddedImage;
  584. }
  585. }
  586. else
  587. {
  588. stream.Type = MediaStreamType.Video;
  589. }
  590. stream.Width = streamInfo.width;
  591. stream.Height = streamInfo.height;
  592. stream.AspectRatio = GetAspectRatio(streamInfo);
  593. if (streamInfo.bits_per_sample > 0)
  594. {
  595. stream.BitDepth = streamInfo.bits_per_sample;
  596. }
  597. else if (streamInfo.bits_per_raw_sample > 0)
  598. {
  599. stream.BitDepth = streamInfo.bits_per_raw_sample;
  600. }
  601. //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  602. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  603. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  604. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  605. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  606. if (streamInfo.refs > 0)
  607. {
  608. stream.RefFrames = streamInfo.refs;
  609. }
  610. }
  611. else
  612. {
  613. return null;
  614. }
  615. // Get stream bitrate
  616. var bitrate = 0;
  617. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  618. {
  619. if (int.TryParse(streamInfo.bit_rate, NumberStyles.Any, _usCulture, out var value))
  620. {
  621. bitrate = value;
  622. }
  623. }
  624. if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  625. {
  626. // If the stream info doesn't have a bitrate get the value from the media format info
  627. if (int.TryParse(formatInfo.bit_rate, NumberStyles.Any, _usCulture, out var value))
  628. {
  629. bitrate = value;
  630. }
  631. }
  632. if (bitrate > 0)
  633. {
  634. stream.BitRate = bitrate;
  635. }
  636. if (streamInfo.disposition != null)
  637. {
  638. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  639. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  640. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  641. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  642. }
  643. NormalizeStreamTitle(stream);
  644. return stream;
  645. }
  646. private void NormalizeStreamTitle(MediaStream stream)
  647. {
  648. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase))
  649. {
  650. stream.Title = null;
  651. }
  652. if (stream.Type == MediaStreamType.EmbeddedImage)
  653. {
  654. stream.Title = null;
  655. }
  656. }
  657. /// <summary>
  658. /// Gets a string from an FFProbeResult tags dictionary
  659. /// </summary>
  660. /// <param name="tags">The tags.</param>
  661. /// <param name="key">The key.</param>
  662. /// <returns>System.String.</returns>
  663. private string GetDictionaryValue(Dictionary<string, string> tags, string key)
  664. {
  665. if (tags == null)
  666. {
  667. return null;
  668. }
  669. tags.TryGetValue(key, out var val);
  670. return val;
  671. }
  672. private string ParseChannelLayout(string input)
  673. {
  674. if (string.IsNullOrEmpty(input))
  675. {
  676. return input;
  677. }
  678. return input.Split('(').FirstOrDefault();
  679. }
  680. private string GetAspectRatio(MediaStreamInfo info)
  681. {
  682. var original = info.display_aspect_ratio;
  683. var parts = (original ?? string.Empty).Split(':');
  684. if (!(parts.Length == 2 &&
  685. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out var width) &&
  686. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out var height) &&
  687. width > 0 &&
  688. height > 0))
  689. {
  690. width = info.width;
  691. height = info.height;
  692. }
  693. if (width > 0 && height > 0)
  694. {
  695. double ratio = width;
  696. ratio /= height;
  697. if (IsClose(ratio, 1.777777778, .03))
  698. {
  699. return "16:9";
  700. }
  701. if (IsClose(ratio, 1.3333333333, .05))
  702. {
  703. return "4:3";
  704. }
  705. if (IsClose(ratio, 1.41))
  706. {
  707. return "1.41:1";
  708. }
  709. if (IsClose(ratio, 1.5))
  710. {
  711. return "1.5:1";
  712. }
  713. if (IsClose(ratio, 1.6))
  714. {
  715. return "1.6:1";
  716. }
  717. if (IsClose(ratio, 1.66666666667))
  718. {
  719. return "5:3";
  720. }
  721. if (IsClose(ratio, 1.85, .02))
  722. {
  723. return "1.85:1";
  724. }
  725. if (IsClose(ratio, 2.35, .025))
  726. {
  727. return "2.35:1";
  728. }
  729. if (IsClose(ratio, 2.4, .025))
  730. {
  731. return "2.40:1";
  732. }
  733. }
  734. return original;
  735. }
  736. private bool IsClose(double d1, double d2, double variance = .005)
  737. {
  738. return Math.Abs(d1 - d2) <= variance;
  739. }
  740. /// <summary>
  741. /// Gets a frame rate from a string value in ffprobe output
  742. /// This could be a number or in the format of 2997/125.
  743. /// </summary>
  744. /// <param name="value">The value.</param>
  745. /// <returns>System.Nullable{System.Single}.</returns>
  746. private float? GetFrameRate(string value)
  747. {
  748. if (!string.IsNullOrEmpty(value))
  749. {
  750. var parts = value.Split('/');
  751. float result;
  752. if (parts.Length == 2)
  753. {
  754. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  755. }
  756. else
  757. {
  758. result = float.Parse(parts[0], _usCulture);
  759. }
  760. return float.IsNaN(result) ? (float?)null : result;
  761. }
  762. return null;
  763. }
  764. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  765. {
  766. if (result.streams != null)
  767. {
  768. // Get the first info stream
  769. var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  770. if (stream != null)
  771. {
  772. // Get duration from stream properties
  773. var duration = stream.duration;
  774. // If it's not there go into format properties
  775. if (string.IsNullOrEmpty(duration))
  776. {
  777. duration = result.format.duration;
  778. }
  779. // If we got something, parse it
  780. if (!string.IsNullOrEmpty(duration))
  781. {
  782. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  783. }
  784. }
  785. }
  786. }
  787. private void SetSize(InternalMediaInfoResult data, MediaInfo info)
  788. {
  789. if (data.format != null)
  790. {
  791. if (!string.IsNullOrEmpty(data.format.size))
  792. {
  793. info.Size = long.Parse(data.format.size, _usCulture);
  794. }
  795. else
  796. {
  797. info.Size = null;
  798. }
  799. }
  800. }
  801. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  802. {
  803. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  804. if (!string.IsNullOrWhiteSpace(composer))
  805. {
  806. var peoples = new List<BaseItemPerson>();
  807. foreach (var person in Split(composer, false))
  808. {
  809. peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  810. }
  811. audio.People = peoples.ToArray();
  812. }
  813. //var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  814. //if (!string.IsNullOrWhiteSpace(conductor))
  815. //{
  816. // foreach (var person in Split(conductor, false))
  817. // {
  818. // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  819. // }
  820. //}
  821. //var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  822. //if (!string.IsNullOrWhiteSpace(lyricist))
  823. //{
  824. // foreach (var person in Split(lyricist, false))
  825. // {
  826. // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  827. // }
  828. //}
  829. // Check for writer some music is tagged that way as alternative to composer/lyricist
  830. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  831. if (!string.IsNullOrWhiteSpace(writer))
  832. {
  833. var peoples = new List<BaseItemPerson>();
  834. foreach (var person in Split(writer, false))
  835. {
  836. peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  837. }
  838. audio.People = peoples.ToArray();
  839. }
  840. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  841. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  842. if (!string.IsNullOrWhiteSpace(artists))
  843. {
  844. audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
  845. .DistinctNames()
  846. .ToArray();
  847. }
  848. else
  849. {
  850. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  851. if (string.IsNullOrWhiteSpace(artist))
  852. {
  853. audio.Artists = new string[] { };
  854. }
  855. else
  856. {
  857. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  858. .DistinctNames()
  859. .ToArray();
  860. }
  861. }
  862. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  863. if (string.IsNullOrWhiteSpace(albumArtist))
  864. {
  865. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  866. }
  867. if (string.IsNullOrWhiteSpace(albumArtist))
  868. {
  869. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  870. }
  871. if (string.IsNullOrWhiteSpace(albumArtist))
  872. {
  873. audio.AlbumArtists = new string[] { };
  874. }
  875. else
  876. {
  877. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  878. .DistinctNames()
  879. .ToArray();
  880. }
  881. if (audio.AlbumArtists.Length == 0)
  882. {
  883. audio.AlbumArtists = audio.Artists;
  884. }
  885. // Track number
  886. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  887. // Disc number
  888. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  889. // If we don't have a ProductionYear try and get it from PremiereDate
  890. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  891. {
  892. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  893. }
  894. // There's several values in tags may or may not be present
  895. FetchStudios(audio, tags, "organization");
  896. FetchStudios(audio, tags, "ensemble");
  897. FetchStudios(audio, tags, "publisher");
  898. FetchStudios(audio, tags, "label");
  899. // These support mulitple values, but for now we only store the first.
  900. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  901. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  902. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);
  903. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  904. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  905. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);
  906. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  907. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  908. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);
  909. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  910. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  911. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);
  912. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
  913. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  914. audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
  915. }
  916. private string GetMultipleMusicBrainzId(string value)
  917. {
  918. if (string.IsNullOrWhiteSpace(value))
  919. {
  920. return null;
  921. }
  922. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  923. .Select(i => i.Trim())
  924. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  925. }
  926. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  927. /// <summary>
  928. /// Splits the specified val.
  929. /// </summary>
  930. /// <param name="val">The val.</param>
  931. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  932. /// <returns>System.String[][].</returns>
  933. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  934. {
  935. // Only use the comma as a delimeter if there are no slashes or pipes.
  936. // We want to be careful not to split names that have commas in them
  937. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  938. _nameDelimiters :
  939. new[] { ',' };
  940. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  941. .Where(i => !string.IsNullOrWhiteSpace(i))
  942. .Select(i => i.Trim());
  943. }
  944. private const string ArtistReplaceValue = " | ";
  945. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  946. {
  947. if (splitFeaturing)
  948. {
  949. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  950. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  951. }
  952. var artistsFound = new List<string>();
  953. foreach (var whitelistArtist in GetSplitWhitelist())
  954. {
  955. var originalVal = val;
  956. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  957. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  958. {
  959. artistsFound.Add(whitelistArtist);
  960. }
  961. }
  962. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  963. .Where(i => !string.IsNullOrWhiteSpace(i))
  964. .Select(i => i.Trim());
  965. artistsFound.AddRange(artists);
  966. return artistsFound;
  967. }
  968. private List<string> _splitWhiteList = null;
  969. private IEnumerable<string> GetSplitWhitelist()
  970. {
  971. if (_splitWhiteList == null)
  972. {
  973. _splitWhiteList = new List<string>
  974. {
  975. "AC/DC"
  976. };
  977. }
  978. return _splitWhiteList;
  979. }
  980. /// <summary>
  981. /// Gets the studios from the tags collection
  982. /// </summary>
  983. /// <param name="info">The info.</param>
  984. /// <param name="tags">The tags.</param>
  985. /// <param name="tagName">Name of the tag.</param>
  986. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  987. {
  988. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  989. if (!string.IsNullOrEmpty(val))
  990. {
  991. var studios = Split(val, true);
  992. var studioList = new List<string>();
  993. foreach (var studio in studios)
  994. {
  995. // Sometimes the artist name is listed here, account for that
  996. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  997. {
  998. continue;
  999. }
  1000. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  1001. {
  1002. continue;
  1003. }
  1004. studioList.Add(studio);
  1005. }
  1006. info.Studios = studioList
  1007. .Where(i => !string.IsNullOrWhiteSpace(i))
  1008. .Distinct(StringComparer.OrdinalIgnoreCase)
  1009. .ToArray();
  1010. }
  1011. }
  1012. /// <summary>
  1013. /// Gets the genres from the tags collection
  1014. /// </summary>
  1015. /// <param name="info">The information.</param>
  1016. /// <param name="tags">The tags.</param>
  1017. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  1018. {
  1019. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  1020. if (!string.IsNullOrEmpty(val))
  1021. {
  1022. var genres = new List<string>(info.Genres);
  1023. foreach (var genre in Split(val, true))
  1024. {
  1025. genres.Add(genre);
  1026. }
  1027. info.Genres = genres
  1028. .Where(i => !string.IsNullOrWhiteSpace(i))
  1029. .Distinct(StringComparer.OrdinalIgnoreCase)
  1030. .ToArray();
  1031. }
  1032. }
  1033. /// <summary>
  1034. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  1035. /// </summary>
  1036. /// <param name="tags">The tags.</param>
  1037. /// <param name="tagName">Name of the tag.</param>
  1038. /// <returns>System.Nullable{System.Int32}.</returns>
  1039. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  1040. {
  1041. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  1042. if (!string.IsNullOrEmpty(disc))
  1043. {
  1044. disc = disc.Split('/')[0];
  1045. if (int.TryParse(disc, out var num))
  1046. {
  1047. return num;
  1048. }
  1049. }
  1050. return null;
  1051. }
  1052. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  1053. {
  1054. var info = new ChapterInfo();
  1055. if (chapter.tags != null)
  1056. {
  1057. if (chapter.tags.TryGetValue("title", out string name))
  1058. {
  1059. info.Name = name;
  1060. }
  1061. }
  1062. // Limit accuracy to milliseconds to match xml saving
  1063. var secondsString = chapter.start_time;
  1064. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
  1065. {
  1066. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  1067. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  1068. }
  1069. return info;
  1070. }
  1071. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  1072. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1073. {
  1074. if (data.format == null || data.format.tags == null)
  1075. {
  1076. return;
  1077. }
  1078. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
  1079. if (!string.IsNullOrWhiteSpace(genres))
  1080. {
  1081. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  1082. .Where(i => !string.IsNullOrWhiteSpace(i))
  1083. .Select(i => i.Trim())
  1084. .ToList();
  1085. // If this is empty then don't overwrite genres that might have been fetched earlier
  1086. if (genreList.Count > 0)
  1087. {
  1088. video.Genres = genreList.ToArray();
  1089. }
  1090. }
  1091. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  1092. if (!string.IsNullOrWhiteSpace(officialRating))
  1093. {
  1094. video.OfficialRating = officialRating;
  1095. }
  1096. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  1097. if (!string.IsNullOrEmpty(people))
  1098. {
  1099. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  1100. .Where(i => !string.IsNullOrWhiteSpace(i))
  1101. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  1102. .ToArray();
  1103. }
  1104. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  1105. if (!string.IsNullOrWhiteSpace(year))
  1106. {
  1107. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out var val))
  1108. {
  1109. video.ProductionYear = val;
  1110. }
  1111. }
  1112. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
  1113. if (!string.IsNullOrWhiteSpace(premiereDateString))
  1114. {
  1115. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1116. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1117. if (DateTime.TryParse(year, null, DateTimeStyles.None, out var val))
  1118. {
  1119. video.PremiereDate = val.ToUniversalTime();
  1120. }
  1121. }
  1122. var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  1123. var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
  1124. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1125. // 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
  1126. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1127. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1128. // 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]
  1129. // 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]
  1130. 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
  1131. {
  1132. string[] parts = description.Split(':');
  1133. if (parts.Length > 0)
  1134. {
  1135. string subtitle = parts[0];
  1136. try
  1137. {
  1138. if (subtitle.Contains("/")) // It contains a episode number and season number
  1139. {
  1140. string[] numbers = subtitle.Split(' ');
  1141. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  1142. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  1143. description = string.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  1144. }
  1145. else
  1146. throw new Exception(); // Switch to default parsing
  1147. }
  1148. catch // Default parsing
  1149. {
  1150. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  1151. description = string.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  1152. else
  1153. description = subtitle.Trim(); // Clean up whitespaces and save it
  1154. }
  1155. }
  1156. }
  1157. if (!string.IsNullOrWhiteSpace(description))
  1158. {
  1159. video.Overview = description;
  1160. }
  1161. }
  1162. private void ExtractTimestamp(MediaInfo video)
  1163. {
  1164. if (video.VideoType == VideoType.VideoFile)
  1165. {
  1166. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  1167. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  1168. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1169. {
  1170. try
  1171. {
  1172. video.Timestamp = GetMpegTimestamp(video.Path);
  1173. _logger.LogDebug("Video has {timestamp} timestamp", video.Timestamp);
  1174. }
  1175. catch (Exception ex)
  1176. {
  1177. _logger.LogError(ex, "Error extracting timestamp info from {path}", video.Path);
  1178. video.Timestamp = null;
  1179. }
  1180. }
  1181. }
  1182. }
  1183. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1184. {
  1185. var packetBuffer = new byte['Å'];
  1186. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  1187. {
  1188. fs.Read(packetBuffer, 0, packetBuffer.Length);
  1189. }
  1190. if (packetBuffer[0] == 71)
  1191. {
  1192. return TransportStreamTimestamp.None;
  1193. }
  1194. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  1195. {
  1196. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1197. {
  1198. return TransportStreamTimestamp.Zero;
  1199. }
  1200. return TransportStreamTimestamp.Valid;
  1201. }
  1202. return TransportStreamTimestamp.None;
  1203. }
  1204. }
  1205. }