FFProbeVideoInfoProvider.cs 18 KB

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