FFProbeVideoInfoProvider.cs 16 KB

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