FFProbeVideoInfoProvider.cs 22 KB

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