FFProbeVideoInfoProvider.cs 15 KB

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