FFProbeVideoInfoProvider.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using System.Globalization;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Movies;
  8. using MediaBrowser.Controller.Localization;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.MediaInfo;
  12. using MediaBrowser.Model.Serialization;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Providers.MediaInfo
  20. {
  21. /// <summary>
  22. /// Extracts video information using ffprobe
  23. /// </summary>
  24. public class FFProbeVideoInfoProvider : BaseFFProbeProvider<Video>
  25. {
  26. public FFProbeVideoInfoProvider(IIsoManager isoManager, IBlurayExaminer blurayExaminer, IJsonSerializer jsonSerializer, ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, ILocalizationManager localization)
  27. : base(logManager, configurationManager, mediaEncoder, jsonSerializer)
  28. {
  29. if (isoManager == null)
  30. {
  31. throw new ArgumentNullException("isoManager");
  32. }
  33. if (blurayExaminer == null)
  34. {
  35. throw new ArgumentNullException("blurayExaminer");
  36. }
  37. _blurayExaminer = blurayExaminer;
  38. _localization = localization;
  39. _isoManager = isoManager;
  40. }
  41. /// <summary>
  42. /// Gets or sets the bluray examiner.
  43. /// </summary>
  44. /// <value>The bluray examiner.</value>
  45. private readonly IBlurayExaminer _blurayExaminer;
  46. /// <summary>
  47. /// The _iso manager
  48. /// </summary>
  49. private readonly IIsoManager _isoManager;
  50. private readonly ILocalizationManager _localization;
  51. /// <summary>
  52. /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
  53. /// </summary>
  54. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  55. protected override bool RefreshOnFileSystemStampChange
  56. {
  57. get
  58. {
  59. // Need this in case external subtitle files change
  60. return true;
  61. }
  62. }
  63. /// <summary>
  64. /// Gets the filestamp extensions.
  65. /// </summary>
  66. /// <value>The filestamp extensions.</value>
  67. protected override string[] FilestampExtensions
  68. {
  69. get
  70. {
  71. return new[] { ".srt" };
  72. }
  73. }
  74. /// <summary>
  75. /// Supports video files and dvd structures
  76. /// </summary>
  77. /// <param name="item">The item.</param>
  78. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  79. public override bool Supports(BaseItem item)
  80. {
  81. if (item.LocationType != LocationType.FileSystem)
  82. {
  83. return false;
  84. }
  85. var video = item as Video;
  86. if (video != null)
  87. {
  88. if (video.VideoType == VideoType.Iso)
  89. {
  90. return _isoManager.CanMount(item.Path);
  91. }
  92. return video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay;
  93. }
  94. return false;
  95. }
  96. /// <summary>
  97. /// Called when [pre fetch].
  98. /// </summary>
  99. /// <param name="item">The item.</param>
  100. /// <param name="mount">The mount.</param>
  101. protected override void OnPreFetch(Video item, IIsoMount mount)
  102. {
  103. if (item.VideoType == VideoType.Iso)
  104. {
  105. item.IsoType = DetermineIsoType(mount);
  106. }
  107. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  108. {
  109. PopulateDvdStreamFiles(item, mount);
  110. }
  111. base.OnPreFetch(item, mount);
  112. }
  113. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  114. {
  115. var myItem = (Video)item;
  116. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  117. try
  118. {
  119. OnPreFetch(myItem, isoMount);
  120. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  121. cancellationToken.ThrowIfCancellationRequested();
  122. NormalizeFFProbeResult(result);
  123. cancellationToken.ThrowIfCancellationRequested();
  124. await Fetch(myItem, cancellationToken, result, isoMount).ConfigureAwait(false);
  125. SetLastRefreshed(item, DateTime.UtcNow);
  126. }
  127. finally
  128. {
  129. if (isoMount != null)
  130. {
  131. isoMount.Dispose();
  132. }
  133. }
  134. return true;
  135. }
  136. /// <summary>
  137. /// Mounts the iso if needed.
  138. /// </summary>
  139. /// <param name="item">The item.</param>
  140. /// <param name="cancellationToken">The cancellation token.</param>
  141. /// <returns>IsoMount.</returns>
  142. protected override Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  143. {
  144. if (item.VideoType == VideoType.Iso)
  145. {
  146. return _isoManager.Mount(item.Path, cancellationToken);
  147. }
  148. return base.MountIsoIfNeeded(item, cancellationToken);
  149. }
  150. /// <summary>
  151. /// Determines the type of the iso.
  152. /// </summary>
  153. /// <param name="isoMount">The iso mount.</param>
  154. /// <returns>System.Nullable{IsoType}.</returns>
  155. private IsoType? DetermineIsoType(IIsoMount isoMount)
  156. {
  157. var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  158. if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
  159. {
  160. return IsoType.Dvd;
  161. }
  162. if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  163. {
  164. return IsoType.BluRay;
  165. }
  166. return null;
  167. }
  168. /// <summary>
  169. /// Finds vob files and populates the dvd stream file properties
  170. /// </summary>
  171. /// <param name="video">The video.</param>
  172. /// <param name="isoMount">The iso mount.</param>
  173. private void PopulateDvdStreamFiles(Video video, IIsoMount isoMount)
  174. {
  175. // min size 300 mb
  176. const long minPlayableSize = 314572800;
  177. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  178. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  179. // Once we reach a file that is at least the minimum, return all subsequent ones
  180. var files = Directory.EnumerateFiles(root, "*.vob", SearchOption.AllDirectories).SkipWhile(f => new FileInfo(f).Length < minPlayableSize).ToList();
  181. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  182. if (files.Count > 0)
  183. {
  184. var parts = Path.GetFileNameWithoutExtension(files[0]).Split('_');
  185. if (parts.Length == 3)
  186. {
  187. var title = parts[1];
  188. files = files.TakeWhile(f =>
  189. {
  190. var fileParts = Path.GetFileNameWithoutExtension(f).Split('_');
  191. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  192. }).ToList();
  193. }
  194. }
  195. video.PlayableStreamFileNames = files.Select(Path.GetFileName).ToList();
  196. }
  197. /// <summary>
  198. /// Fetches the specified video.
  199. /// </summary>
  200. /// <param name="video">The video.</param>
  201. /// <param name="cancellationToken">The cancellation token.</param>
  202. /// <param name="data">The data.</param>
  203. /// <param name="isoMount">The iso mount.</param>
  204. /// <returns>Task.</returns>
  205. protected async Task Fetch(Video video, CancellationToken cancellationToken, MediaInfoResult data, IIsoMount isoMount)
  206. {
  207. if (data.format != null)
  208. {
  209. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  210. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  211. if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
  212. {
  213. video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, UsCulture)).Ticks;
  214. }
  215. }
  216. if (data.streams != null)
  217. {
  218. video.MediaStreams = data.streams.Select(s => GetMediaStream(s, data.format))
  219. .Where(i => i != null)
  220. .ToList();
  221. }
  222. var chapters = data.Chapters ?? new List<ChapterInfo>();
  223. if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
  224. {
  225. var inputPath = isoMount != null ? isoMount.MountedPath : video.Path;
  226. FetchBdInfo(video, chapters, inputPath, cancellationToken);
  227. }
  228. AddExternalSubtitles(video);
  229. FetchWtvInfo(video, data);
  230. if (chapters.Count == 0)
  231. {
  232. AddDummyChapters(video, chapters);
  233. }
  234. await Kernel.Instance.FFMpegManager.PopulateChapterImages(video, chapters, false, true, cancellationToken).ConfigureAwait(false);
  235. }
  236. /// <summary>
  237. /// Fetches the WTV info.
  238. /// </summary>
  239. /// <param name="video">The video.</param>
  240. /// <param name="data">The data.</param>
  241. private void FetchWtvInfo(Video video, MediaInfoResult data)
  242. {
  243. if (data.format == null || data.format.tags == null)
  244. {
  245. return;
  246. }
  247. var genres = GetDictionaryValue(data.format.tags, "genre");
  248. if (!string.IsNullOrEmpty(genres))
  249. {
  250. video.Genres = genres.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  251. .Where(i => !string.IsNullOrWhiteSpace(i))
  252. .Select(i => i.Trim())
  253. .ToList();
  254. }
  255. var overview = GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  256. if (!string.IsNullOrWhiteSpace(overview))
  257. {
  258. video.Overview = overview;
  259. }
  260. var officialRating = GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  261. if (!string.IsNullOrWhiteSpace(officialRating))
  262. {
  263. video.OfficialRating = officialRating;
  264. }
  265. var people = GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  266. if (!string.IsNullOrEmpty(people))
  267. {
  268. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  269. .Where(i => !string.IsNullOrWhiteSpace(i))
  270. .Select(i => new PersonInfo { Name = i.Trim(), Type = PersonType.Actor })
  271. .ToList();
  272. }
  273. var year = GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  274. if (!string.IsNullOrWhiteSpace(year))
  275. {
  276. int val;
  277. if (int.TryParse(year, NumberStyles.Integer, UsCulture, out val))
  278. {
  279. video.ProductionYear = val;
  280. }
  281. }
  282. }
  283. /// <summary>
  284. /// Adds the external subtitles.
  285. /// </summary>
  286. /// <param name="video">The video.</param>
  287. private void AddExternalSubtitles(Video video)
  288. {
  289. var useParent = (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso) && !(video is Movie) && !(video is MusicVideo);
  290. if (useParent && video.Parent == null)
  291. {
  292. return;
  293. }
  294. var fileSystemChildren = useParent
  295. ? video.Parent.ResolveArgs.FileSystemChildren
  296. : video.ResolveArgs.FileSystemChildren;
  297. var startIndex = video.MediaStreams == null ? 0 : video.MediaStreams.Count;
  298. var streams = new List<MediaStream>();
  299. var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(video.Path);
  300. foreach (var file in fileSystemChildren
  301. .Where(f => !f.Attributes.HasFlag(FileAttributes.Directory) && string.Equals(Path.GetExtension(f.FullName), ".srt", StringComparison.OrdinalIgnoreCase)))
  302. {
  303. var fullName = file.FullName;
  304. var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);
  305. // If the subtitle file matches the video file name
  306. if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
  307. {
  308. streams.Add(new MediaStream
  309. {
  310. Index = startIndex++,
  311. Type = MediaStreamType.Subtitle,
  312. IsExternal = true,
  313. Path = fullName,
  314. Codec = "srt"
  315. });
  316. }
  317. else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
  318. {
  319. // Support xbmc naming conventions - 300.spanish.srt
  320. var language = fileNameWithoutExtension.Split('.').LastOrDefault();
  321. // Try to translate to three character code
  322. // Be flexible and check against both the full and three character versions
  323. var culture = _localization.GetCultures()
  324. .FirstOrDefault(i => string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.ThreeLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));
  325. if (culture != null)
  326. {
  327. language = culture.ThreeLetterISOLanguageName;
  328. }
  329. streams.Add(new MediaStream
  330. {
  331. Index = startIndex++,
  332. Type = MediaStreamType.Subtitle,
  333. IsExternal = true,
  334. Path = fullName,
  335. Codec = "srt",
  336. Language = language
  337. });
  338. }
  339. }
  340. if (video.MediaStreams == null)
  341. {
  342. video.MediaStreams = new List<MediaStream>();
  343. }
  344. video.MediaStreams.AddRange(streams);
  345. }
  346. /// <summary>
  347. /// The dummy chapter duration
  348. /// </summary>
  349. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  350. /// <summary>
  351. /// Adds the dummy chapters.
  352. /// </summary>
  353. /// <param name="video">The video.</param>
  354. /// <param name="chapters">The chapters.</param>
  355. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  356. {
  357. var runtime = video.RunTimeTicks ?? 0;
  358. if (runtime < _dummyChapterDuration)
  359. {
  360. return;
  361. }
  362. long currentChapterTicks = 0;
  363. var index = 1;
  364. while (currentChapterTicks < runtime)
  365. {
  366. chapters.Add(new ChapterInfo
  367. {
  368. Name = "Chapter " + index,
  369. StartPositionTicks = currentChapterTicks
  370. });
  371. index++;
  372. currentChapterTicks += _dummyChapterDuration;
  373. }
  374. }
  375. /// <summary>
  376. /// Fetches the bd info.
  377. /// </summary>
  378. /// <param name="item">The item.</param>
  379. /// <param name="chapters">The chapters.</param>
  380. /// <param name="inputPath">The input path.</param>
  381. /// <param name="cancellationToken">The cancellation token.</param>
  382. private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, string inputPath, CancellationToken cancellationToken)
  383. {
  384. var video = (Video)item;
  385. var result = GetBDInfo(inputPath);
  386. cancellationToken.ThrowIfCancellationRequested();
  387. int? currentHeight = null;
  388. int? currentWidth = null;
  389. int? currentBitRate = null;
  390. var videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  391. // Grab the values that ffprobe recorded
  392. if (videoStream != null)
  393. {
  394. currentBitRate = videoStream.BitRate;
  395. currentWidth = videoStream.Width;
  396. currentHeight = videoStream.Height;
  397. }
  398. // Fill video properties from the BDInfo result
  399. Fetch(video, result, chapters);
  400. videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  401. // Use the ffprobe values if these are empty
  402. if (videoStream != null)
  403. {
  404. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  405. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  406. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  407. }
  408. }
  409. /// <summary>
  410. /// Determines whether the specified num is empty.
  411. /// </summary>
  412. /// <param name="num">The num.</param>
  413. /// <returns><c>true</c> if the specified num is empty; otherwise, <c>false</c>.</returns>
  414. private bool IsEmpty(int? num)
  415. {
  416. return !num.HasValue || num.Value == 0;
  417. }
  418. /// <summary>
  419. /// Fills video properties from the VideoStream of the largest playlist
  420. /// </summary>
  421. /// <param name="video">The video.</param>
  422. /// <param name="stream">The stream.</param>
  423. /// <param name="chapters">The chapters.</param>
  424. private void Fetch(Video video, BlurayDiscInfo stream, List<ChapterInfo> chapters)
  425. {
  426. // Check all input for null/empty/zero
  427. video.MediaStreams = stream.MediaStreams;
  428. if (stream.RunTimeTicks.HasValue && stream.RunTimeTicks.Value > 0)
  429. {
  430. video.RunTimeTicks = stream.RunTimeTicks;
  431. }
  432. video.PlayableStreamFileNames = stream.Files.ToList();
  433. if (stream.Chapters != null)
  434. {
  435. chapters.Clear();
  436. chapters.AddRange(stream.Chapters.Select(c => new ChapterInfo
  437. {
  438. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  439. }));
  440. }
  441. }
  442. /// <summary>
  443. /// Gets information about the longest playlist on a bdrom
  444. /// </summary>
  445. /// <param name="path">The path.</param>
  446. /// <returns>VideoStream.</returns>
  447. private BlurayDiscInfo GetBDInfo(string path)
  448. {
  449. return _blurayExaminer.GetDiscInfo(path);
  450. }
  451. }
  452. }