FFProbeVideoInfoProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 void Fetch(Video video, CancellationToken cancellationToken, FFProbeResult data, IIsoMount isoMount)
  166. {
  167. if (data.format != null)
  168. {
  169. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  170. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  171. if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
  172. {
  173. video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, UsCulture)).Ticks;
  174. }
  175. }
  176. if (data.streams != null)
  177. {
  178. video.MediaStreams = data.streams.Select(s => GetMediaStream(s, data.format)).ToList();
  179. }
  180. if (data.Chapters != null)
  181. {
  182. video.Chapters = data.Chapters;
  183. }
  184. if (video.Chapters == null || video.Chapters.Count == 0)
  185. {
  186. AddDummyChapters(video);
  187. }
  188. if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
  189. {
  190. var inputPath = isoMount != null ? isoMount.MountedPath : video.Path;
  191. FetchBdInfo(video, inputPath, BdInfoCache, cancellationToken);
  192. }
  193. AddExternalSubtitles(video);
  194. }
  195. /// <summary>
  196. /// Adds the external subtitles.
  197. /// </summary>
  198. /// <param name="video">The video.</param>
  199. private void AddExternalSubtitles(Video video)
  200. {
  201. var useParent = (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso) && !(video is Movie);
  202. if (useParent && video.Parent == null)
  203. {
  204. return;
  205. }
  206. var fileSystemChildren = useParent
  207. ? video.Parent.ResolveArgs.FileSystemChildren
  208. : video.ResolveArgs.FileSystemChildren;
  209. var startIndex = video.MediaStreams == null ? 0 : video.MediaStreams.Count;
  210. var streams = new List<MediaStream>();
  211. foreach (var file in fileSystemChildren.Where(f => !f.IsDirectory))
  212. {
  213. var extension = Path.GetExtension(file.Path);
  214. if (string.Equals(extension, ".srt", StringComparison.OrdinalIgnoreCase))
  215. {
  216. if (video.VideoType == VideoType.VideoFile)
  217. {
  218. // For video files the subtitle filename must match video filename
  219. if (!string.Equals(Path.GetFileNameWithoutExtension(video.Path), Path.GetFileNameWithoutExtension(file.Path)))
  220. {
  221. continue;
  222. }
  223. }
  224. streams.Add(new MediaStream
  225. {
  226. Index = startIndex++,
  227. Type = MediaStreamType.Subtitle,
  228. IsExternal = true,
  229. Path = file.Path,
  230. Codec = "srt"
  231. });
  232. }
  233. }
  234. if (video.MediaStreams == null)
  235. {
  236. video.MediaStreams = new List<MediaStream>();
  237. }
  238. video.MediaStreams.AddRange(streams);
  239. }
  240. /// <summary>
  241. /// The dummy chapter duration
  242. /// </summary>
  243. private readonly long DummyChapterDuration = TimeSpan.FromMinutes(10).Ticks;
  244. /// <summary>
  245. /// Adds the dummy chapters.
  246. /// </summary>
  247. /// <param name="video">The video.</param>
  248. private void AddDummyChapters(Video video)
  249. {
  250. var runtime = video.RunTimeTicks ?? 0;
  251. if (runtime < DummyChapterDuration)
  252. {
  253. return;
  254. }
  255. long currentChapterTicks = 0;
  256. var index = 1;
  257. var chapters = new List<ChapterInfo> { };
  258. while (currentChapterTicks < runtime)
  259. {
  260. chapters.Add(new ChapterInfo
  261. {
  262. Name = "Chapter " + index,
  263. StartPositionTicks = currentChapterTicks
  264. });
  265. index++;
  266. currentChapterTicks += DummyChapterDuration;
  267. }
  268. video.Chapters = chapters;
  269. }
  270. /// <summary>
  271. /// Fetches the bd info.
  272. /// </summary>
  273. /// <param name="item">The item.</param>
  274. /// <param name="inputPath">The input path.</param>
  275. /// <param name="bdInfoCache">The bd info cache.</param>
  276. /// <param name="cancellationToken">The cancellation token.</param>
  277. private void FetchBdInfo(BaseItem item, string inputPath, FileSystemRepository bdInfoCache, CancellationToken cancellationToken)
  278. {
  279. var video = (Video)item;
  280. // Get the path to the cache file
  281. var cacheName = item.Id + "_" + item.DateModified.Ticks;
  282. var cacheFile = bdInfoCache.GetResourcePath(cacheName, ".pb");
  283. BlurayDiscInfo result;
  284. try
  285. {
  286. result = _protobufSerializer.DeserializeFromFile<BlurayDiscInfo>(cacheFile);
  287. }
  288. catch (FileNotFoundException)
  289. {
  290. result = GetBDInfo(inputPath);
  291. _protobufSerializer.SerializeToFile(result, cacheFile);
  292. }
  293. cancellationToken.ThrowIfCancellationRequested();
  294. int? currentHeight = null;
  295. int? currentWidth = null;
  296. int? currentBitRate = null;
  297. var videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  298. // Grab the values that ffprobe recorded
  299. if (videoStream != null)
  300. {
  301. currentBitRate = videoStream.BitRate;
  302. currentWidth = videoStream.Width;
  303. currentHeight = videoStream.Height;
  304. }
  305. // Fill video properties from the BDInfo result
  306. Fetch(video, inputPath, result);
  307. videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  308. // Use the ffprobe values if these are empty
  309. if (videoStream != null)
  310. {
  311. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  312. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  313. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  314. }
  315. }
  316. /// <summary>
  317. /// Determines whether the specified num is empty.
  318. /// </summary>
  319. /// <param name="num">The num.</param>
  320. /// <returns><c>true</c> if the specified num is empty; otherwise, <c>false</c>.</returns>
  321. private bool IsEmpty(int? num)
  322. {
  323. return !num.HasValue || num.Value == 0;
  324. }
  325. /// <summary>
  326. /// Fills video properties from the VideoStream of the largest playlist
  327. /// </summary>
  328. /// <param name="video">The video.</param>
  329. /// <param name="inputPath">The input path.</param>
  330. /// <param name="stream">The stream.</param>
  331. private void Fetch(Video video, string inputPath, BlurayDiscInfo stream)
  332. {
  333. // Check all input for null/empty/zero
  334. video.MediaStreams = stream.MediaStreams;
  335. if (stream.RunTimeTicks.HasValue && stream.RunTimeTicks.Value > 0)
  336. {
  337. video.RunTimeTicks = stream.RunTimeTicks;
  338. }
  339. video.PlayableStreamFileNames = stream.Files.ToList();
  340. if (stream.Chapters != null)
  341. {
  342. video.Chapters = stream.Chapters.Select(c => new ChapterInfo
  343. {
  344. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  345. }).ToList();
  346. }
  347. }
  348. /// <summary>
  349. /// Gets information about the longest playlist on a bdrom
  350. /// </summary>
  351. /// <param name="path">The path.</param>
  352. /// <returns>VideoStream.</returns>
  353. private BlurayDiscInfo GetBDInfo(string path)
  354. {
  355. return _blurayExaminer.GetDiscInfo(path);
  356. }
  357. /// <summary>
  358. /// Releases unmanaged and - optionally - managed resources.
  359. /// </summary>
  360. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  361. protected override void Dispose(bool dispose)
  362. {
  363. if (dispose)
  364. {
  365. BdInfoCache.Dispose();
  366. }
  367. base.Dispose(dispose);
  368. }
  369. }
  370. }