FFProbeVideoInfoProvider.cs 20 KB

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