FFProbeVideoInfo.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using DvdLib.Ifo;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Controller.Chapters;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.Movies;
  14. using MediaBrowser.Controller.Entities.TV;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.MediaEncoding;
  17. using MediaBrowser.Controller.Persistence;
  18. using MediaBrowser.Controller.Providers;
  19. using MediaBrowser.Controller.Subtitles;
  20. using MediaBrowser.Model.Configuration;
  21. using MediaBrowser.Model.Dlna;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Entities;
  24. using MediaBrowser.Model.Globalization;
  25. using MediaBrowser.Model.IO;
  26. using MediaBrowser.Model.MediaInfo;
  27. using MediaBrowser.Model.Providers;
  28. using MediaBrowser.Model.Serialization;
  29. using Microsoft.Extensions.Logging;
  30. namespace MediaBrowser.Providers.MediaInfo
  31. {
  32. public class FFProbeVideoInfo
  33. {
  34. private readonly ILogger _logger;
  35. private readonly IIsoManager _isoManager;
  36. private readonly IMediaEncoder _mediaEncoder;
  37. private readonly IItemRepository _itemRepo;
  38. private readonly IBlurayExaminer _blurayExaminer;
  39. private readonly ILocalizationManager _localization;
  40. private readonly IApplicationPaths _appPaths;
  41. private readonly IJsonSerializer _json;
  42. private readonly IEncodingManager _encodingManager;
  43. private readonly IFileSystem _fileSystem;
  44. private readonly IServerConfigurationManager _config;
  45. private readonly ISubtitleManager _subtitleManager;
  46. private readonly IChapterManager _chapterManager;
  47. private readonly ILibraryManager _libraryManager;
  48. private readonly IMediaSourceManager _mediaSourceManager;
  49. public FFProbeVideoInfo(ILogger logger, IMediaSourceManager mediaSourceManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IBlurayExaminer blurayExaminer, ILocalizationManager localization, IApplicationPaths appPaths, IJsonSerializer json, IEncodingManager encodingManager, IFileSystem fileSystem, IServerConfigurationManager config, ISubtitleManager subtitleManager, IChapterManager chapterManager, ILibraryManager libraryManager)
  50. {
  51. _logger = logger;
  52. _isoManager = isoManager;
  53. _mediaEncoder = mediaEncoder;
  54. _itemRepo = itemRepo;
  55. _blurayExaminer = blurayExaminer;
  56. _localization = localization;
  57. _appPaths = appPaths;
  58. _json = json;
  59. _encodingManager = encodingManager;
  60. _fileSystem = fileSystem;
  61. _config = config;
  62. _subtitleManager = subtitleManager;
  63. _chapterManager = chapterManager;
  64. _libraryManager = libraryManager;
  65. _mediaSourceManager = mediaSourceManager;
  66. }
  67. public async Task<ItemUpdateType> ProbeVideo<T>(T item,
  68. MetadataRefreshOptions options,
  69. CancellationToken cancellationToken)
  70. where T : Video
  71. {
  72. BlurayDiscInfo blurayDiscInfo = null;
  73. Model.MediaInfo.MediaInfo mediaInfoResult = null;
  74. if (!item.IsShortcut || options.EnableRemoteContentProbe)
  75. {
  76. string[] streamFileNames = null;
  77. if (item.VideoType == VideoType.Dvd)
  78. {
  79. streamFileNames = FetchFromDvdLib(item);
  80. if (streamFileNames.Length == 0)
  81. {
  82. _logger.LogError("No playable vobs found in dvd structure, skipping ffprobe.");
  83. return ItemUpdateType.MetadataImport;
  84. }
  85. }
  86. else if (item.VideoType == VideoType.BluRay)
  87. {
  88. var inputPath = item.Path;
  89. blurayDiscInfo = GetBDInfo(inputPath);
  90. streamFileNames = blurayDiscInfo.Files;
  91. if (streamFileNames.Length == 0)
  92. {
  93. _logger.LogError("No playable vobs found in bluray structure, skipping ffprobe.");
  94. return ItemUpdateType.MetadataImport;
  95. }
  96. }
  97. if (streamFileNames == null)
  98. {
  99. streamFileNames = Array.Empty<string>();
  100. }
  101. mediaInfoResult = await GetMediaInfo(item, streamFileNames, cancellationToken).ConfigureAwait(false);
  102. cancellationToken.ThrowIfCancellationRequested();
  103. }
  104. await Fetch(item, cancellationToken, mediaInfoResult, blurayDiscInfo, options).ConfigureAwait(false);
  105. return ItemUpdateType.MetadataImport;
  106. }
  107. private Task<Model.MediaInfo.MediaInfo> GetMediaInfo(Video item,
  108. string[] streamFileNames,
  109. CancellationToken cancellationToken)
  110. {
  111. cancellationToken.ThrowIfCancellationRequested();
  112. var path = item.Path;
  113. var protocol = item.PathProtocol ?? MediaProtocol.File;
  114. if (item.IsShortcut)
  115. {
  116. path = item.ShortcutPath;
  117. protocol = _mediaSourceManager.GetPathProtocol(path);
  118. }
  119. return _mediaEncoder.GetMediaInfo(new MediaInfoRequest
  120. {
  121. PlayableStreamFileNames = streamFileNames,
  122. ExtractChapters = true,
  123. MediaType = DlnaProfileType.Video,
  124. MediaSource = new MediaSourceInfo
  125. {
  126. Path = path,
  127. Protocol = protocol,
  128. VideoType = item.VideoType
  129. }
  130. }, cancellationToken);
  131. }
  132. protected async Task Fetch(Video video,
  133. CancellationToken cancellationToken,
  134. Model.MediaInfo.MediaInfo mediaInfo,
  135. BlurayDiscInfo blurayInfo,
  136. MetadataRefreshOptions options)
  137. {
  138. List<MediaStream> mediaStreams;
  139. List<ChapterInfo> chapters;
  140. if (mediaInfo != null)
  141. {
  142. mediaStreams = mediaInfo.MediaStreams;
  143. video.TotalBitrate = mediaInfo.Bitrate;
  144. //video.FormatName = (mediaInfo.Container ?? string.Empty)
  145. // .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
  146. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  147. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  148. if (needToSetRuntime)
  149. {
  150. video.RunTimeTicks = mediaInfo.RunTimeTicks;
  151. }
  152. if (video.VideoType == VideoType.VideoFile)
  153. {
  154. var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');
  155. video.Container = extension;
  156. }
  157. else
  158. {
  159. video.Container = null;
  160. }
  161. video.Container = mediaInfo.Container;
  162. chapters = mediaInfo.Chapters == null ? new List<ChapterInfo>() : mediaInfo.Chapters.ToList();
  163. if (blurayInfo != null)
  164. {
  165. FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
  166. }
  167. }
  168. else
  169. {
  170. mediaStreams = new List<MediaStream>();
  171. chapters = new List<ChapterInfo>();
  172. }
  173. await AddExternalSubtitles(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
  174. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  175. if (mediaInfo != null)
  176. {
  177. FetchEmbeddedInfo(video, mediaInfo, options, libraryOptions);
  178. FetchPeople(video, mediaInfo, options);
  179. video.Timestamp = mediaInfo.Timestamp;
  180. video.Video3DFormat = video.Video3DFormat ?? mediaInfo.Video3DFormat;
  181. }
  182. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  183. video.Height = videoStream == null ? 0 : videoStream.Height ?? 0;
  184. video.Width = videoStream == null ? 0 : videoStream.Width ?? 0;
  185. video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;
  186. video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
  187. _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken);
  188. if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh ||
  189. options.MetadataRefreshMode == MetadataRefreshMode.Default)
  190. {
  191. if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
  192. {
  193. AddDummyChapters(video, chapters);
  194. }
  195. NormalizeChapterNames(chapters);
  196. var extractDuringScan = false;
  197. if (libraryOptions != null)
  198. {
  199. extractDuringScan = libraryOptions.ExtractChapterImagesDuringLibraryScan;
  200. }
  201. await _encodingManager.RefreshChapterImages(video, options.DirectoryService, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);
  202. _chapterManager.SaveChapters(video.Id.ToString(), chapters);
  203. }
  204. }
  205. private void NormalizeChapterNames(List<ChapterInfo> chapters)
  206. {
  207. var index = 1;
  208. foreach (var chapter in chapters)
  209. {
  210. // Check if the name is empty and/or if the name is a time
  211. // Some ripping programs do that.
  212. if (string.IsNullOrWhiteSpace(chapter.Name) ||
  213. TimeSpan.TryParse(chapter.Name, out var time))
  214. {
  215. chapter.Name = string.Format(_localization.GetLocalizedString("ChapterNameValue"), index.ToString(CultureInfo.InvariantCulture));
  216. }
  217. index++;
  218. }
  219. }
  220. private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
  221. {
  222. var video = (Video)item;
  223. //video.PlayableStreamFileNames = blurayInfo.Files.ToList();
  224. // Use BD Info if it has multiple m2ts. Otherwise, treat it like a video file and rely more on ffprobe output
  225. if (blurayInfo.Files.Length > 1)
  226. {
  227. int? currentHeight = null;
  228. int? currentWidth = null;
  229. int? currentBitRate = null;
  230. var videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  231. // Grab the values that ffprobe recorded
  232. if (videoStream != null)
  233. {
  234. currentBitRate = videoStream.BitRate;
  235. currentWidth = videoStream.Width;
  236. currentHeight = videoStream.Height;
  237. }
  238. // Fill video properties from the BDInfo result
  239. mediaStreams.Clear();
  240. mediaStreams.AddRange(blurayInfo.MediaStreams);
  241. if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
  242. {
  243. video.RunTimeTicks = blurayInfo.RunTimeTicks;
  244. }
  245. if (blurayInfo.Chapters != null)
  246. {
  247. chapters.Clear();
  248. chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
  249. {
  250. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  251. }));
  252. }
  253. videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  254. // Use the ffprobe values if these are empty
  255. if (videoStream != null)
  256. {
  257. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  258. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  259. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  260. }
  261. }
  262. }
  263. private bool IsEmpty(int? num)
  264. {
  265. return !num.HasValue || num.Value == 0;
  266. }
  267. /// <summary>
  268. /// Gets information about the longest playlist on a bdrom
  269. /// </summary>
  270. /// <param name="path">The path.</param>
  271. /// <returns>VideoStream.</returns>
  272. private BlurayDiscInfo GetBDInfo(string path)
  273. {
  274. if (string.IsNullOrWhiteSpace(path))
  275. {
  276. throw new ArgumentNullException(nameof(path));
  277. }
  278. try
  279. {
  280. return _blurayExaminer.GetDiscInfo(path);
  281. }
  282. catch (Exception ex)
  283. {
  284. _logger.LogError(ex, "Error getting BDInfo");
  285. return null;
  286. }
  287. }
  288. private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions refreshOptions, LibraryOptions libraryOptions)
  289. {
  290. var isFullRefresh = refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  291. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.OfficialRating))
  292. {
  293. if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
  294. {
  295. video.OfficialRating = data.OfficialRating;
  296. }
  297. }
  298. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Genres))
  299. {
  300. if (video.Genres.Length == 0 || isFullRefresh)
  301. {
  302. video.Genres = Array.Empty<string>();
  303. foreach (var genre in data.Genres)
  304. {
  305. video.AddGenre(genre);
  306. }
  307. }
  308. }
  309. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Studios))
  310. {
  311. if (video.Studios.Length == 0 || isFullRefresh)
  312. {
  313. video.SetStudios(data.Studios);
  314. }
  315. }
  316. if (data.ProductionYear.HasValue)
  317. {
  318. if (!video.ProductionYear.HasValue || isFullRefresh)
  319. {
  320. video.ProductionYear = data.ProductionYear;
  321. }
  322. }
  323. if (data.PremiereDate.HasValue)
  324. {
  325. if (!video.PremiereDate.HasValue || isFullRefresh)
  326. {
  327. video.PremiereDate = data.PremiereDate;
  328. }
  329. }
  330. if (data.IndexNumber.HasValue)
  331. {
  332. if (!video.IndexNumber.HasValue || isFullRefresh)
  333. {
  334. video.IndexNumber = data.IndexNumber;
  335. }
  336. }
  337. if (data.ParentIndexNumber.HasValue)
  338. {
  339. if (!video.ParentIndexNumber.HasValue || isFullRefresh)
  340. {
  341. video.ParentIndexNumber = data.ParentIndexNumber;
  342. }
  343. }
  344. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Name))
  345. {
  346. if (!string.IsNullOrWhiteSpace(data.Name) && libraryOptions.EnableEmbeddedTitles)
  347. {
  348. // Don't use the embedded name for extras because it will often be the same name as the movie
  349. if (!video.ExtraType.HasValue)
  350. {
  351. video.Name = data.Name;
  352. }
  353. }
  354. }
  355. // If we don't have a ProductionYear try and get it from PremiereDate
  356. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  357. {
  358. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  359. }
  360. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Overview))
  361. {
  362. if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
  363. {
  364. video.Overview = data.Overview;
  365. }
  366. }
  367. }
  368. private void FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  369. {
  370. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  371. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Cast))
  372. {
  373. if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
  374. {
  375. var people = new List<PersonInfo>();
  376. foreach (var person in data.People)
  377. {
  378. PeopleHelper.AddPerson(people, new PersonInfo
  379. {
  380. Name = person.Name,
  381. Type = person.Type,
  382. Role = person.Role
  383. });
  384. }
  385. _libraryManager.UpdatePeople(video, people);
  386. }
  387. }
  388. }
  389. private SubtitleOptions GetOptions()
  390. {
  391. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  392. }
  393. /// <summary>
  394. /// Adds the external subtitles.
  395. /// </summary>
  396. /// <param name="video">The video.</param>
  397. /// <param name="currentStreams">The current streams.</param>
  398. /// <param name="options">The refreshOptions.</param>
  399. /// <param name="cancellationToken">The cancellation token.</param>
  400. /// <returns>Task.</returns>
  401. private async Task AddExternalSubtitles(Video video,
  402. List<MediaStream> currentStreams,
  403. MetadataRefreshOptions options,
  404. CancellationToken cancellationToken)
  405. {
  406. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  407. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  408. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false);
  409. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  410. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  411. var subtitleOptions = GetOptions();
  412. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  413. string[] subtitleDownloadLanguages;
  414. bool SkipIfEmbeddedSubtitlesPresent;
  415. bool SkipIfAudioTrackMatches;
  416. bool RequirePerfectMatch;
  417. bool enabled;
  418. if (libraryOptions.SubtitleDownloadLanguages == null)
  419. {
  420. subtitleDownloadLanguages = subtitleOptions.DownloadLanguages;
  421. SkipIfEmbeddedSubtitlesPresent = subtitleOptions.SkipIfEmbeddedSubtitlesPresent;
  422. SkipIfAudioTrackMatches = subtitleOptions.SkipIfAudioTrackMatches;
  423. RequirePerfectMatch = subtitleOptions.RequirePerfectMatch;
  424. enabled = (subtitleOptions.DownloadEpisodeSubtitles &&
  425. video is Episode) ||
  426. (subtitleOptions.DownloadMovieSubtitles &&
  427. video is Movie);
  428. }
  429. else
  430. {
  431. subtitleDownloadLanguages = libraryOptions.SubtitleDownloadLanguages;
  432. SkipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
  433. SkipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
  434. RequirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
  435. enabled = true;
  436. }
  437. if (enableSubtitleDownloading && enabled)
  438. {
  439. var downloadedLanguages = await new SubtitleDownloader(_logger,
  440. _subtitleManager)
  441. .DownloadSubtitles(video,
  442. currentStreams.Concat(externalSubtitleStreams).ToList(),
  443. SkipIfEmbeddedSubtitlesPresent,
  444. SkipIfAudioTrackMatches,
  445. RequirePerfectMatch,
  446. subtitleDownloadLanguages,
  447. libraryOptions.DisabledSubtitleFetchers,
  448. libraryOptions.SubtitleFetcherOrder,
  449. cancellationToken).ConfigureAwait(false);
  450. // Rescan
  451. if (downloadedLanguages.Count > 0)
  452. {
  453. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true);
  454. }
  455. }
  456. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).ToArray();
  457. currentStreams.AddRange(externalSubtitleStreams);
  458. }
  459. /// <summary>
  460. /// The dummy chapter duration
  461. /// </summary>
  462. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  463. /// <summary>
  464. /// Adds the dummy chapters.
  465. /// </summary>
  466. /// <param name="video">The video.</param>
  467. /// <param name="chapters">The chapters.</param>
  468. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  469. {
  470. var runtime = video.RunTimeTicks ?? 0;
  471. if (runtime < 0)
  472. {
  473. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  474. }
  475. if (runtime < _dummyChapterDuration)
  476. {
  477. return;
  478. }
  479. long currentChapterTicks = 0;
  480. var index = 1;
  481. // Limit to 100 chapters just in case there's some incorrect metadata here
  482. while (currentChapterTicks < runtime && index < 100)
  483. {
  484. chapters.Add(new ChapterInfo
  485. {
  486. StartPositionTicks = currentChapterTicks
  487. });
  488. index++;
  489. currentChapterTicks += _dummyChapterDuration;
  490. }
  491. }
  492. private string[] FetchFromDvdLib(Video item)
  493. {
  494. var path = item.Path;
  495. var dvd = new Dvd(path, _fileSystem);
  496. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  497. byte? titleNumber = null;
  498. if (primaryTitle != null)
  499. {
  500. titleNumber = primaryTitle.VideoTitleSetNumber;
  501. item.RunTimeTicks = GetRuntime(primaryTitle);
  502. }
  503. return _mediaEncoder.GetPrimaryPlaylistVobFiles(item.Path, null, titleNumber)
  504. .Select(Path.GetFileName)
  505. .ToArray();
  506. }
  507. private long GetRuntime(Title title)
  508. {
  509. return title.ProgramChains
  510. .Select(i => (TimeSpan)i.PlaybackTime)
  511. .Select(i => i.Ticks)
  512. .Sum();
  513. }
  514. }
  515. }