FFProbeVideoInfoProvider.cs 15 KB

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