FFProbeVideoInfoProvider.cs 15 KB

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