2
0

ProbeResultNormalizer.cs 53 KB

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