FFProbeVideoInfoProvider.cs 23 KB

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