FFProbeVideoInfoProvider.cs 15 KB

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