FFProbeVideoInfoProvider.cs 15 KB

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