FFProbeVideoInfo.cs 23 KB

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