FFProbeVideoInfoProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Controller.Providers.MediaInfo
  17. {
  18. /// <summary>
  19. /// Extracts video information using ffprobe
  20. /// </summary>
  21. public class FFProbeVideoInfoProvider : BaseFFProbeProvider<Video>
  22. {
  23. public FFProbeVideoInfoProvider(IIsoManager isoManager, IBlurayExaminer blurayExaminer, IJsonSerializer jsonSerializer, ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder)
  24. : base(logManager, configurationManager, mediaEncoder, jsonSerializer)
  25. {
  26. if (isoManager == null)
  27. {
  28. throw new ArgumentNullException("isoManager");
  29. }
  30. if (blurayExaminer == null)
  31. {
  32. throw new ArgumentNullException("blurayExaminer");
  33. }
  34. _blurayExaminer = blurayExaminer;
  35. _isoManager = isoManager;
  36. BdInfoCache = new FileSystemRepository(Path.Combine(ConfigurationManager.ApplicationPaths.CachePath, "bdinfo"));
  37. }
  38. /// <summary>
  39. /// Gets or sets the bd info cache.
  40. /// </summary>
  41. /// <value>The bd info cache.</value>
  42. private FileSystemRepository BdInfoCache { get; set; }
  43. /// <summary>
  44. /// Gets or sets the bluray examiner.
  45. /// </summary>
  46. /// <value>The bluray examiner.</value>
  47. private readonly IBlurayExaminer _blurayExaminer;
  48. /// <summary>
  49. /// The _iso manager
  50. /// </summary>
  51. private readonly IIsoManager _isoManager;
  52. /// <summary>
  53. /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
  54. /// </summary>
  55. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  56. protected override bool RefreshOnFileSystemStampChange
  57. {
  58. get
  59. {
  60. return true;
  61. }
  62. }
  63. /// <summary>
  64. /// Supports video files and dvd structures
  65. /// </summary>
  66. /// <param name="item">The item.</param>
  67. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  68. public override bool Supports(BaseItem item)
  69. {
  70. if (item.LocationType != LocationType.FileSystem)
  71. {
  72. return false;
  73. }
  74. var video = item as Video;
  75. if (video != null)
  76. {
  77. if (video.VideoType == VideoType.Iso)
  78. {
  79. return _isoManager.CanMount(item.Path);
  80. }
  81. return video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay;
  82. }
  83. return false;
  84. }
  85. /// <summary>
  86. /// Called when [pre fetch].
  87. /// </summary>
  88. /// <param name="item">The item.</param>
  89. /// <param name="mount">The mount.</param>
  90. protected override void OnPreFetch(Video item, IIsoMount mount)
  91. {
  92. if (item.VideoType == VideoType.Iso)
  93. {
  94. item.IsoType = DetermineIsoType(mount);
  95. }
  96. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  97. {
  98. PopulateDvdStreamFiles(item, mount);
  99. }
  100. base.OnPreFetch(item, mount);
  101. }
  102. /// <summary>
  103. /// Mounts the iso if needed.
  104. /// </summary>
  105. /// <param name="item">The item.</param>
  106. /// <param name="cancellationToken">The cancellation token.</param>
  107. /// <returns>IsoMount.</returns>
  108. protected override Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  109. {
  110. if (item.VideoType == VideoType.Iso)
  111. {
  112. return _isoManager.Mount(item.Path, cancellationToken);
  113. }
  114. return base.MountIsoIfNeeded(item, cancellationToken);
  115. }
  116. /// <summary>
  117. /// Determines the type of the iso.
  118. /// </summary>
  119. /// <param name="isoMount">The iso mount.</param>
  120. /// <returns>System.Nullable{IsoType}.</returns>
  121. private IsoType? DetermineIsoType(IIsoMount isoMount)
  122. {
  123. var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  124. if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
  125. {
  126. return IsoType.Dvd;
  127. }
  128. if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  129. {
  130. return IsoType.BluRay;
  131. }
  132. return null;
  133. }
  134. /// <summary>
  135. /// Finds vob files and populates the dvd stream file properties
  136. /// </summary>
  137. /// <param name="video">The video.</param>
  138. /// <param name="isoMount">The iso mount.</param>
  139. private void PopulateDvdStreamFiles(Video video, IIsoMount isoMount)
  140. {
  141. // min size 300 mb
  142. const long minPlayableSize = 314572800;
  143. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  144. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  145. // Once we reach a file that is at least the minimum, return all subsequent ones
  146. var files = Directory.EnumerateFiles(root, "*.vob", SearchOption.AllDirectories).SkipWhile(f => new FileInfo(f).Length < minPlayableSize).ToList();
  147. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  148. if (files.Count > 0)
  149. {
  150. var parts = Path.GetFileNameWithoutExtension(files[0]).Split('_');
  151. if (parts.Length == 3)
  152. {
  153. var title = parts[1];
  154. files = files.TakeWhile(f =>
  155. {
  156. var fileParts = Path.GetFileNameWithoutExtension(f).Split('_');
  157. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  158. }).ToList();
  159. }
  160. }
  161. video.PlayableStreamFileNames = files.Select(Path.GetFileName).ToList();
  162. }
  163. /// <summary>
  164. /// Fetches the specified video.
  165. /// </summary>
  166. /// <param name="video">The video.</param>
  167. /// <param name="cancellationToken">The cancellation token.</param>
  168. /// <param name="data">The data.</param>
  169. /// <param name="isoMount">The iso mount.</param>
  170. /// <returns>Task.</returns>
  171. protected override void Fetch(Video video, CancellationToken cancellationToken, MediaInfoResult data, IIsoMount isoMount)
  172. {
  173. if (data.format != null)
  174. {
  175. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  176. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  177. if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
  178. {
  179. video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, UsCulture)).Ticks;
  180. }
  181. }
  182. if (data.streams != null)
  183. {
  184. video.MediaStreams = data.streams.Select(s => GetMediaStream(s, data.format)).ToList();
  185. }
  186. if (data.Chapters != null)
  187. {
  188. video.Chapters = data.Chapters;
  189. }
  190. if (video.Chapters == null || video.Chapters.Count == 0)
  191. {
  192. AddDummyChapters(video);
  193. }
  194. if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
  195. {
  196. var inputPath = isoMount != null ? isoMount.MountedPath : video.Path;
  197. FetchBdInfo(video, inputPath, BdInfoCache, cancellationToken);
  198. }
  199. AddExternalSubtitles(video);
  200. }
  201. /// <summary>
  202. /// Adds the external subtitles.
  203. /// </summary>
  204. /// <param name="video">The video.</param>
  205. private void AddExternalSubtitles(Video video)
  206. {
  207. var useParent = (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso) && !(video is Movie);
  208. if (useParent && video.Parent == null)
  209. {
  210. return;
  211. }
  212. var fileSystemChildren = useParent
  213. ? video.Parent.ResolveArgs.FileSystemChildren
  214. : video.ResolveArgs.FileSystemChildren;
  215. var startIndex = video.MediaStreams == null ? 0 : video.MediaStreams.Count;
  216. var streams = new List<MediaStream>();
  217. foreach (var file in fileSystemChildren.Where(f => !f.Attributes.HasFlag(FileAttributes.Directory)))
  218. {
  219. var fullName = file.FullName;
  220. var extension = Path.GetExtension(fullName);
  221. if (string.Equals(extension, ".srt", StringComparison.OrdinalIgnoreCase))
  222. {
  223. if (video.VideoType == VideoType.VideoFile)
  224. {
  225. // For video files the subtitle filename must match video filename
  226. if (!string.Equals(Path.GetFileNameWithoutExtension(video.Path), Path.GetFileNameWithoutExtension(fullName)))
  227. {
  228. continue;
  229. }
  230. }
  231. streams.Add(new MediaStream
  232. {
  233. Index = startIndex++,
  234. Type = MediaStreamType.Subtitle,
  235. IsExternal = true,
  236. Path = fullName,
  237. Codec = "srt"
  238. });
  239. }
  240. }
  241. if (video.MediaStreams == null)
  242. {
  243. video.MediaStreams = new List<MediaStream>();
  244. }
  245. video.MediaStreams.AddRange(streams);
  246. }
  247. /// <summary>
  248. /// The dummy chapter duration
  249. /// </summary>
  250. private readonly long DummyChapterDuration = TimeSpan.FromMinutes(10).Ticks;
  251. /// <summary>
  252. /// Adds the dummy chapters.
  253. /// </summary>
  254. /// <param name="video">The video.</param>
  255. private void AddDummyChapters(Video video)
  256. {
  257. var runtime = video.RunTimeTicks ?? 0;
  258. if (runtime < DummyChapterDuration)
  259. {
  260. return;
  261. }
  262. long currentChapterTicks = 0;
  263. var index = 1;
  264. var chapters = new List<ChapterInfo>();
  265. while (currentChapterTicks < runtime)
  266. {
  267. chapters.Add(new ChapterInfo
  268. {
  269. Name = "Chapter " + index,
  270. StartPositionTicks = currentChapterTicks
  271. });
  272. index++;
  273. currentChapterTicks += DummyChapterDuration;
  274. }
  275. video.Chapters = chapters;
  276. }
  277. /// <summary>
  278. /// Fetches the bd info.
  279. /// </summary>
  280. /// <param name="item">The item.</param>
  281. /// <param name="inputPath">The input path.</param>
  282. /// <param name="bdInfoCache">The bd info cache.</param>
  283. /// <param name="cancellationToken">The cancellation token.</param>
  284. private void FetchBdInfo(BaseItem item, string inputPath, FileSystemRepository bdInfoCache, CancellationToken cancellationToken)
  285. {
  286. var video = (Video)item;
  287. // Get the path to the cache file
  288. var cacheName = item.Id + "_" + item.DateModified.Ticks;
  289. var cacheFile = bdInfoCache.GetResourcePath(cacheName, ".js");
  290. BlurayDiscInfo result;
  291. try
  292. {
  293. result = JsonSerializer.DeserializeFromFile<BlurayDiscInfo>(cacheFile);
  294. }
  295. catch (FileNotFoundException)
  296. {
  297. result = GetBDInfo(inputPath);
  298. JsonSerializer.SerializeToFile(result, cacheFile);
  299. }
  300. cancellationToken.ThrowIfCancellationRequested();
  301. int? currentHeight = null;
  302. int? currentWidth = null;
  303. int? currentBitRate = null;
  304. var videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  305. // Grab the values that ffprobe recorded
  306. if (videoStream != null)
  307. {
  308. currentBitRate = videoStream.BitRate;
  309. currentWidth = videoStream.Width;
  310. currentHeight = videoStream.Height;
  311. }
  312. // Fill video properties from the BDInfo result
  313. Fetch(video, result);
  314. videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  315. // Use the ffprobe values if these are empty
  316. if (videoStream != null)
  317. {
  318. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  319. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  320. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  321. }
  322. }
  323. /// <summary>
  324. /// Determines whether the specified num is empty.
  325. /// </summary>
  326. /// <param name="num">The num.</param>
  327. /// <returns><c>true</c> if the specified num is empty; otherwise, <c>false</c>.</returns>
  328. private bool IsEmpty(int? num)
  329. {
  330. return !num.HasValue || num.Value == 0;
  331. }
  332. /// <summary>
  333. /// Fills video properties from the VideoStream of the largest playlist
  334. /// </summary>
  335. /// <param name="video">The video.</param>
  336. /// <param name="stream">The stream.</param>
  337. private void Fetch(Video video, BlurayDiscInfo stream)
  338. {
  339. // Check all input for null/empty/zero
  340. video.MediaStreams = stream.MediaStreams;
  341. if (stream.RunTimeTicks.HasValue && stream.RunTimeTicks.Value > 0)
  342. {
  343. video.RunTimeTicks = stream.RunTimeTicks;
  344. }
  345. video.PlayableStreamFileNames = stream.Files.ToList();
  346. if (stream.Chapters != null)
  347. {
  348. video.Chapters = stream.Chapters.Select(c => new ChapterInfo
  349. {
  350. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  351. }).ToList();
  352. }
  353. }
  354. /// <summary>
  355. /// Gets information about the longest playlist on a bdrom
  356. /// </summary>
  357. /// <param name="path">The path.</param>
  358. /// <returns>VideoStream.</returns>
  359. private BlurayDiscInfo GetBDInfo(string path)
  360. {
  361. return _blurayExaminer.GetDiscInfo(path);
  362. }
  363. }
  364. }