FFProbeVideoInfoProvider.cs 15 KB

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