FFProbeVideoInfoProvider.cs 15 KB

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