ProbeResultNormalizer.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.MediaInfo;
  3. using MediaBrowser.Model.Dto;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Extensions;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.MediaInfo;
  13. namespace MediaBrowser.MediaEncoding.Probing
  14. {
  15. public class ProbeResultNormalizer
  16. {
  17. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  18. private readonly ILogger _logger;
  19. private readonly IFileSystem _fileSystem;
  20. public ProbeResultNormalizer(ILogger logger, IFileSystem fileSystem)
  21. {
  22. _logger = logger;
  23. _fileSystem = fileSystem;
  24. }
  25. public Model.MediaInfo.MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType videoType, bool isAudio, string path, MediaProtocol protocol)
  26. {
  27. var info = new Model.MediaInfo.MediaInfo
  28. {
  29. Path = path,
  30. Protocol = protocol
  31. };
  32. FFProbeHelpers.NormalizeFFProbeResult(data);
  33. SetSize(data, info);
  34. var internalStreams = data.streams ?? new MediaStreamInfo[] { };
  35. info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.format))
  36. .Where(i => i != null)
  37. .ToList();
  38. if (data.format != null)
  39. {
  40. info.Container = data.format.format_name;
  41. if (!string.IsNullOrEmpty(data.format.bit_rate))
  42. {
  43. info.Bitrate = int.Parse(data.format.bit_rate, _usCulture);
  44. }
  45. }
  46. if (isAudio)
  47. {
  48. SetAudioRuntimeTicks(data, info);
  49. var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  50. // tags are normally located under data.format, but we've seen some cases with ogg where they're part of the audio stream
  51. // so let's create a combined list of both
  52. if (data.streams != null)
  53. {
  54. var audioStream = data.streams.FirstOrDefault(i => string.Equals(i.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  55. if (audioStream != null && audioStream.tags != null)
  56. {
  57. foreach (var pair in audioStream.tags)
  58. {
  59. tags[pair.Key] = pair.Value;
  60. }
  61. }
  62. }
  63. if (data.format != null && data.format.tags != null)
  64. {
  65. foreach (var pair in data.format.tags)
  66. {
  67. tags[pair.Key] = pair.Value;
  68. }
  69. }
  70. SetAudioInfoFromTags(info, tags);
  71. }
  72. else
  73. {
  74. if (data.format != null && !string.IsNullOrEmpty(data.format.duration))
  75. {
  76. info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
  77. }
  78. FetchWtvInfo(info, data);
  79. if (data.Chapters != null)
  80. {
  81. info.Chapters = data.Chapters.Select(GetChapterInfo).ToList();
  82. }
  83. ExtractTimestamp(info);
  84. var videoStream = info.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  85. if (videoStream != null && videoType == VideoType.VideoFile)
  86. {
  87. UpdateFromMediaInfo(info, videoStream);
  88. }
  89. }
  90. return info;
  91. }
  92. /// <summary>
  93. /// Converts ffprobe stream info to our MediaStream class
  94. /// </summary>
  95. /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
  96. /// <param name="streamInfo">The stream info.</param>
  97. /// <param name="formatInfo">The format info.</param>
  98. /// <returns>MediaStream.</returns>
  99. private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  100. {
  101. // These are mp4 chapters
  102. if (string.Equals(streamInfo.codec_name, "mov_text", StringComparison.OrdinalIgnoreCase))
  103. {
  104. return null;
  105. }
  106. var stream = new MediaStream
  107. {
  108. Codec = streamInfo.codec_name,
  109. Profile = streamInfo.profile,
  110. Level = streamInfo.level,
  111. Index = streamInfo.index,
  112. PixelFormat = streamInfo.pix_fmt
  113. };
  114. if (streamInfo.tags != null)
  115. {
  116. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  117. }
  118. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  119. {
  120. stream.Type = MediaStreamType.Audio;
  121. stream.Channels = streamInfo.channels;
  122. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  123. {
  124. stream.SampleRate = int.Parse(streamInfo.sample_rate, _usCulture);
  125. }
  126. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  127. }
  128. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  129. {
  130. stream.Type = MediaStreamType.Subtitle;
  131. }
  132. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  133. {
  134. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)
  135. ? MediaStreamType.EmbeddedImage
  136. : MediaStreamType.Video;
  137. stream.Width = streamInfo.width;
  138. stream.Height = streamInfo.height;
  139. stream.AspectRatio = GetAspectRatio(streamInfo);
  140. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  141. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  142. stream.BitDepth = GetBitDepth(stream.PixelFormat);
  143. //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  144. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  145. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  146. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  147. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  148. }
  149. else
  150. {
  151. return null;
  152. }
  153. // Get stream bitrate
  154. var bitrate = 0;
  155. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  156. {
  157. bitrate = int.Parse(streamInfo.bit_rate, _usCulture);
  158. }
  159. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  160. {
  161. // If the stream info doesn't have a bitrate get the value from the media format info
  162. bitrate = int.Parse(formatInfo.bit_rate, _usCulture);
  163. }
  164. if (bitrate > 0)
  165. {
  166. stream.BitRate = bitrate;
  167. }
  168. if (streamInfo.disposition != null)
  169. {
  170. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  171. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  172. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  173. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  174. }
  175. return stream;
  176. }
  177. private int? GetBitDepth(string pixelFormat)
  178. {
  179. var eightBit = new List<string>
  180. {
  181. "yuv420p",
  182. "yuv411p",
  183. "yuvj420p",
  184. "uyyvyy411",
  185. "nv12",
  186. "nv21",
  187. "rgb444le",
  188. "rgb444be",
  189. "bgr444le",
  190. "bgr444be",
  191. "yuvj411p"
  192. };
  193. if (!string.IsNullOrEmpty(pixelFormat))
  194. {
  195. if (eightBit.Contains(pixelFormat, StringComparer.OrdinalIgnoreCase))
  196. {
  197. return 8;
  198. }
  199. }
  200. return null;
  201. }
  202. /// <summary>
  203. /// Gets a string from an FFProbeResult tags dictionary
  204. /// </summary>
  205. /// <param name="tags">The tags.</param>
  206. /// <param name="key">The key.</param>
  207. /// <returns>System.String.</returns>
  208. private string GetDictionaryValue(Dictionary<string, string> tags, string key)
  209. {
  210. if (tags == null)
  211. {
  212. return null;
  213. }
  214. string val;
  215. tags.TryGetValue(key, out val);
  216. return val;
  217. }
  218. private string ParseChannelLayout(string input)
  219. {
  220. if (string.IsNullOrEmpty(input))
  221. {
  222. return input;
  223. }
  224. return input.Split('(').FirstOrDefault();
  225. }
  226. private string GetAspectRatio(MediaStreamInfo info)
  227. {
  228. var original = info.display_aspect_ratio;
  229. int height;
  230. int width;
  231. var parts = (original ?? string.Empty).Split(':');
  232. if (!(parts.Length == 2 &&
  233. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out width) &&
  234. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out height) &&
  235. width > 0 &&
  236. height > 0))
  237. {
  238. width = info.width;
  239. height = info.height;
  240. }
  241. if (width > 0 && height > 0)
  242. {
  243. double ratio = width;
  244. ratio /= height;
  245. if (IsClose(ratio, 1.777777778, .03))
  246. {
  247. return "16:9";
  248. }
  249. if (IsClose(ratio, 1.3333333333, .05))
  250. {
  251. return "4:3";
  252. }
  253. if (IsClose(ratio, 1.41))
  254. {
  255. return "1.41:1";
  256. }
  257. if (IsClose(ratio, 1.5))
  258. {
  259. return "1.5:1";
  260. }
  261. if (IsClose(ratio, 1.6))
  262. {
  263. return "1.6:1";
  264. }
  265. if (IsClose(ratio, 1.66666666667))
  266. {
  267. return "5:3";
  268. }
  269. if (IsClose(ratio, 1.85, .02))
  270. {
  271. return "1.85:1";
  272. }
  273. if (IsClose(ratio, 2.35, .025))
  274. {
  275. return "2.35:1";
  276. }
  277. if (IsClose(ratio, 2.4, .025))
  278. {
  279. return "2.40:1";
  280. }
  281. }
  282. return original;
  283. }
  284. private bool IsClose(double d1, double d2, double variance = .005)
  285. {
  286. return Math.Abs(d1 - d2) <= variance;
  287. }
  288. /// <summary>
  289. /// Gets a frame rate from a string value in ffprobe output
  290. /// This could be a number or in the format of 2997/125.
  291. /// </summary>
  292. /// <param name="value">The value.</param>
  293. /// <returns>System.Nullable{System.Single}.</returns>
  294. private float? GetFrameRate(string value)
  295. {
  296. if (!string.IsNullOrEmpty(value))
  297. {
  298. var parts = value.Split('/');
  299. float result;
  300. if (parts.Length == 2)
  301. {
  302. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  303. }
  304. else
  305. {
  306. result = float.Parse(parts[0], _usCulture);
  307. }
  308. return float.IsNaN(result) ? (float?)null : result;
  309. }
  310. return null;
  311. }
  312. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, Model.MediaInfo.MediaInfo data)
  313. {
  314. if (result.streams != null)
  315. {
  316. // Get the first audio stream
  317. var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  318. if (stream != null)
  319. {
  320. // Get duration from stream properties
  321. var duration = stream.duration;
  322. // If it's not there go into format properties
  323. if (string.IsNullOrEmpty(duration))
  324. {
  325. duration = result.format.duration;
  326. }
  327. // If we got something, parse it
  328. if (!string.IsNullOrEmpty(duration))
  329. {
  330. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  331. }
  332. }
  333. }
  334. }
  335. private void SetSize(InternalMediaInfoResult data, Model.MediaInfo.MediaInfo info)
  336. {
  337. if (data.format != null)
  338. {
  339. if (!string.IsNullOrEmpty(data.format.size))
  340. {
  341. info.Size = long.Parse(data.format.size, _usCulture);
  342. }
  343. else
  344. {
  345. info.Size = null;
  346. }
  347. }
  348. }
  349. private void SetAudioInfoFromTags(Model.MediaInfo.MediaInfo audio, Dictionary<string, string> tags)
  350. {
  351. var title = FFProbeHelpers.GetDictionaryValue(tags, "title");
  352. // Only set Name if title was found in the dictionary
  353. if (!string.IsNullOrEmpty(title))
  354. {
  355. audio.Title = title;
  356. }
  357. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  358. if (!string.IsNullOrWhiteSpace(composer))
  359. {
  360. foreach (var person in Split(composer, false))
  361. {
  362. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  363. }
  364. }
  365. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  366. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  367. if (!string.IsNullOrWhiteSpace(artists))
  368. {
  369. audio.Artists = SplitArtists(artists, new[] { '/' }, false)
  370. .Distinct(StringComparer.OrdinalIgnoreCase)
  371. .ToList();
  372. }
  373. else
  374. {
  375. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  376. if (string.IsNullOrWhiteSpace(artist))
  377. {
  378. audio.Artists.Clear();
  379. }
  380. else
  381. {
  382. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  383. .Distinct(StringComparer.OrdinalIgnoreCase)
  384. .ToList();
  385. }
  386. }
  387. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  388. if (string.IsNullOrWhiteSpace(albumArtist))
  389. {
  390. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  391. }
  392. if (string.IsNullOrWhiteSpace(albumArtist))
  393. {
  394. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  395. }
  396. if (string.IsNullOrWhiteSpace(albumArtist))
  397. {
  398. audio.AlbumArtists = new List<string>();
  399. }
  400. else
  401. {
  402. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  403. .Distinct(StringComparer.OrdinalIgnoreCase)
  404. .ToList();
  405. }
  406. // Track number
  407. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  408. // Disc number
  409. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  410. audio.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
  411. // Several different forms of retaildate
  412. audio.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
  413. FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
  414. FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
  415. FFProbeHelpers.GetDictionaryDateTime(tags, "date");
  416. // If we don't have a ProductionYear try and get it from PremiereDate
  417. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  418. {
  419. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  420. }
  421. FetchGenres(audio, tags);
  422. // There's several values in tags may or may not be present
  423. FetchStudios(audio, tags, "organization");
  424. FetchStudios(audio, tags, "ensemble");
  425. FetchStudios(audio, tags, "publisher");
  426. FetchStudios(audio, tags, "label");
  427. // These support mulitple values, but for now we only store the first.
  428. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id")));
  429. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id")));
  430. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id")));
  431. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id")));
  432. audio.SetProviderId(MetadataProviders.MusicBrainzTrack, GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id")));
  433. }
  434. private string GetMultipleMusicBrainzId(string value)
  435. {
  436. if (string.IsNullOrWhiteSpace(value))
  437. {
  438. return null;
  439. }
  440. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  441. .Select(i => i.Trim())
  442. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  443. }
  444. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  445. /// <summary>
  446. /// Splits the specified val.
  447. /// </summary>
  448. /// <param name="val">The val.</param>
  449. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  450. /// <returns>System.String[][].</returns>
  451. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  452. {
  453. // Only use the comma as a delimeter if there are no slashes or pipes.
  454. // We want to be careful not to split names that have commas in them
  455. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  456. _nameDelimiters :
  457. new[] { ',' };
  458. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  459. .Where(i => !string.IsNullOrWhiteSpace(i))
  460. .Select(i => i.Trim());
  461. }
  462. private const string ArtistReplaceValue = " | ";
  463. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  464. {
  465. if (splitFeaturing)
  466. {
  467. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  468. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  469. }
  470. var artistsFound = new List<string>();
  471. foreach (var whitelistArtist in GetSplitWhitelist())
  472. {
  473. var originalVal = val;
  474. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  475. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  476. {
  477. artistsFound.Add(whitelistArtist);
  478. }
  479. }
  480. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  481. .Where(i => !string.IsNullOrWhiteSpace(i))
  482. .Select(i => i.Trim());
  483. artistsFound.AddRange(artists);
  484. return artistsFound;
  485. }
  486. private List<string> _splitWhiteList = null;
  487. private IEnumerable<string> GetSplitWhitelist()
  488. {
  489. if (_splitWhiteList == null)
  490. {
  491. var file = GetType().Namespace + ".whitelist.txt";
  492. using (var stream = GetType().Assembly.GetManifestResourceStream(file))
  493. {
  494. using (var reader = new StreamReader(stream))
  495. {
  496. var list = new List<string>();
  497. while (!reader.EndOfStream)
  498. {
  499. var val = reader.ReadLine();
  500. if (!string.IsNullOrWhiteSpace(val))
  501. {
  502. list.Add(val);
  503. }
  504. }
  505. _splitWhiteList = list;
  506. }
  507. }
  508. }
  509. return _splitWhiteList;
  510. }
  511. /// <summary>
  512. /// Gets the studios from the tags collection
  513. /// </summary>
  514. /// <param name="audio">The audio.</param>
  515. /// <param name="tags">The tags.</param>
  516. /// <param name="tagName">Name of the tag.</param>
  517. private void FetchStudios(Model.MediaInfo.MediaInfo audio, Dictionary<string, string> tags, string tagName)
  518. {
  519. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  520. if (!string.IsNullOrEmpty(val))
  521. {
  522. var studios = Split(val, true);
  523. foreach (var studio in studios)
  524. {
  525. // Sometimes the artist name is listed here, account for that
  526. if (audio.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  527. {
  528. continue;
  529. }
  530. if (audio.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  531. {
  532. continue;
  533. }
  534. audio.Studios.Add(studio);
  535. }
  536. audio.Studios = audio.Studios
  537. .Where(i => !string.IsNullOrWhiteSpace(i))
  538. .Distinct(StringComparer.OrdinalIgnoreCase)
  539. .ToList();
  540. }
  541. }
  542. /// <summary>
  543. /// Gets the genres from the tags collection
  544. /// </summary>
  545. /// <param name="info">The information.</param>
  546. /// <param name="tags">The tags.</param>
  547. private void FetchGenres(Model.MediaInfo.MediaInfo info, Dictionary<string, string> tags)
  548. {
  549. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  550. if (!string.IsNullOrEmpty(val))
  551. {
  552. foreach (var genre in Split(val, true))
  553. {
  554. info.Genres.Add(genre);
  555. }
  556. info.Genres = info.Genres
  557. .Where(i => !string.IsNullOrWhiteSpace(i))
  558. .Distinct(StringComparer.OrdinalIgnoreCase)
  559. .ToList();
  560. }
  561. }
  562. /// <summary>
  563. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  564. /// </summary>
  565. /// <param name="tags">The tags.</param>
  566. /// <param name="tagName">Name of the tag.</param>
  567. /// <returns>System.Nullable{System.Int32}.</returns>
  568. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  569. {
  570. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  571. if (!string.IsNullOrEmpty(disc))
  572. {
  573. disc = disc.Split('/')[0];
  574. int num;
  575. if (int.TryParse(disc, out num))
  576. {
  577. return num;
  578. }
  579. }
  580. return null;
  581. }
  582. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  583. {
  584. var info = new ChapterInfo();
  585. if (chapter.tags != null)
  586. {
  587. string name;
  588. if (chapter.tags.TryGetValue("title", out name))
  589. {
  590. info.Name = name;
  591. }
  592. }
  593. // Limit accuracy to milliseconds to match xml saving
  594. var secondsString = chapter.start_time;
  595. double seconds;
  596. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
  597. {
  598. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  599. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  600. }
  601. return info;
  602. }
  603. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  604. private void FetchWtvInfo(Model.MediaInfo.MediaInfo video, InternalMediaInfoResult data)
  605. {
  606. if (data.format == null || data.format.tags == null)
  607. {
  608. return;
  609. }
  610. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
  611. if (!string.IsNullOrWhiteSpace(genres))
  612. {
  613. //genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "genre");
  614. }
  615. if (!string.IsNullOrWhiteSpace(genres))
  616. {
  617. video.Genres = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  618. .Where(i => !string.IsNullOrWhiteSpace(i))
  619. .Select(i => i.Trim())
  620. .ToList();
  621. }
  622. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  623. if (!string.IsNullOrWhiteSpace(officialRating))
  624. {
  625. video.OfficialRating = officialRating;
  626. }
  627. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  628. if (!string.IsNullOrEmpty(people))
  629. {
  630. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  631. .Where(i => !string.IsNullOrWhiteSpace(i))
  632. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  633. .ToList();
  634. }
  635. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  636. if (!string.IsNullOrWhiteSpace(year))
  637. {
  638. int val;
  639. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  640. {
  641. video.ProductionYear = val;
  642. }
  643. }
  644. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
  645. if (!string.IsNullOrWhiteSpace(premiereDateString))
  646. {
  647. DateTime val;
  648. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  649. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  650. if (DateTime.TryParse(year, null, DateTimeStyles.None, out val))
  651. {
  652. video.PremiereDate = val.ToUniversalTime();
  653. }
  654. }
  655. var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  656. var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
  657. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  658. // 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
  659. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  660. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  661. // 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]
  662. // 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]
  663. 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
  664. {
  665. string[] parts = description.Split(':');
  666. if (parts.Length > 0)
  667. {
  668. string subtitle = parts[0];
  669. try
  670. {
  671. if (subtitle.Contains("/")) // It contains a episode number and season number
  672. {
  673. string[] numbers = subtitle.Split(' ');
  674. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  675. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  676. description = String.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  677. }
  678. else
  679. throw new Exception(); // Switch to default parsing
  680. }
  681. catch // Default parsing
  682. {
  683. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  684. description = String.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  685. else
  686. description = subtitle.Trim(); // Clean up whitespaces and save it
  687. }
  688. }
  689. }
  690. if (!string.IsNullOrWhiteSpace(description))
  691. {
  692. video.Overview = description;
  693. }
  694. }
  695. private void ExtractTimestamp(Model.MediaInfo.MediaInfo video)
  696. {
  697. if (video.VideoType == VideoType.VideoFile)
  698. {
  699. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  700. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  701. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  702. {
  703. try
  704. {
  705. video.Timestamp = GetMpegTimestamp(video.Path);
  706. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  707. }
  708. catch (Exception ex)
  709. {
  710. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  711. video.Timestamp = null;
  712. }
  713. }
  714. }
  715. }
  716. private TransportStreamTimestamp GetMpegTimestamp(string path)
  717. {
  718. var packetBuffer = new byte['Å'];
  719. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  720. {
  721. fs.Read(packetBuffer, 0, packetBuffer.Length);
  722. }
  723. if (packetBuffer[0] == 71)
  724. {
  725. return TransportStreamTimestamp.None;
  726. }
  727. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  728. {
  729. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  730. {
  731. return TransportStreamTimestamp.Zero;
  732. }
  733. return TransportStreamTimestamp.Valid;
  734. }
  735. return TransportStreamTimestamp.None;
  736. }
  737. private void UpdateFromMediaInfo(MediaSourceInfo video, MediaStream videoStream)
  738. {
  739. if (video.Protocol == MediaProtocol.File)
  740. {
  741. if (videoStream != null)
  742. {
  743. try
  744. {
  745. _logger.Debug("Running MediaInfo against {0}", video.Path);
  746. var result = new MediaInfoLib().GetVideoInfo(video.Path);
  747. videoStream.IsCabac = result.IsCabac ?? videoStream.IsCabac;
  748. videoStream.IsInterlaced = result.IsInterlaced ?? videoStream.IsInterlaced;
  749. videoStream.BitDepth = result.BitDepth ?? videoStream.BitDepth;
  750. videoStream.RefFrames = result.RefFrames;
  751. }
  752. catch (Exception ex)
  753. {
  754. _logger.ErrorException("Error running MediaInfo on {0}", ex, video.Path);
  755. }
  756. }
  757. }
  758. }
  759. }
  760. }