FFProbeVideoInfoProvider.cs 15 KB

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