FFProbeVideoInfo.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. #pragma warning disable CA1068, CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Extensions;
  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.MediaInfo;
  26. using MediaBrowser.Model.Providers;
  27. using Microsoft.Extensions.Logging;
  28. namespace MediaBrowser.Providers.MediaInfo
  29. {
  30. public class FFProbeVideoInfo
  31. {
  32. private readonly ILogger<FFProbeVideoInfo> _logger;
  33. private readonly IMediaSourceManager _mediaSourceManager;
  34. private readonly IMediaEncoder _mediaEncoder;
  35. private readonly IBlurayExaminer _blurayExaminer;
  36. private readonly ILocalizationManager _localization;
  37. private readonly IChapterManager _chapterManager;
  38. private readonly IServerConfigurationManager _config;
  39. private readonly ISubtitleManager _subtitleManager;
  40. private readonly ILibraryManager _libraryManager;
  41. private readonly AudioResolver _audioResolver;
  42. private readonly SubtitleResolver _subtitleResolver;
  43. private readonly IMediaAttachmentRepository _mediaAttachmentRepository;
  44. private readonly IMediaStreamRepository _mediaStreamRepository;
  45. public FFProbeVideoInfo(
  46. ILogger<FFProbeVideoInfo> logger,
  47. IMediaSourceManager mediaSourceManager,
  48. IMediaEncoder mediaEncoder,
  49. IBlurayExaminer blurayExaminer,
  50. ILocalizationManager localization,
  51. IChapterManager chapterManager,
  52. IServerConfigurationManager config,
  53. ISubtitleManager subtitleManager,
  54. ILibraryManager libraryManager,
  55. AudioResolver audioResolver,
  56. SubtitleResolver subtitleResolver,
  57. IMediaAttachmentRepository mediaAttachmentRepository,
  58. IMediaStreamRepository mediaStreamRepository)
  59. {
  60. _logger = logger;
  61. _mediaSourceManager = mediaSourceManager;
  62. _mediaEncoder = mediaEncoder;
  63. _blurayExaminer = blurayExaminer;
  64. _localization = localization;
  65. _chapterManager = chapterManager;
  66. _config = config;
  67. _subtitleManager = subtitleManager;
  68. _libraryManager = libraryManager;
  69. _audioResolver = audioResolver;
  70. _subtitleResolver = subtitleResolver;
  71. _mediaAttachmentRepository = mediaAttachmentRepository;
  72. _mediaStreamRepository = mediaStreamRepository;
  73. _mediaStreamRepository = mediaStreamRepository;
  74. }
  75. public async Task<ItemUpdateType> ProbeVideo<T>(
  76. T item,
  77. MetadataRefreshOptions options,
  78. CancellationToken cancellationToken)
  79. where T : Video
  80. {
  81. BlurayDiscInfo? blurayDiscInfo = null;
  82. Model.MediaInfo.MediaInfo? mediaInfoResult = null;
  83. if (!item.IsShortcut || options.EnableRemoteContentProbe)
  84. {
  85. if (item.VideoType == VideoType.Dvd)
  86. {
  87. // Get list of playable .vob files
  88. var vobs = _mediaEncoder.GetPrimaryPlaylistVobFiles(item.Path, null);
  89. // Return if no playable .vob files are found
  90. if (vobs.Count == 0)
  91. {
  92. _logger.LogError("No playable .vob files found in DVD structure, skipping FFprobe.");
  93. return ItemUpdateType.MetadataImport;
  94. }
  95. // Fetch metadata of first .vob file
  96. mediaInfoResult = await GetMediaInfo(
  97. new Video
  98. {
  99. Path = vobs[0]
  100. },
  101. cancellationToken).ConfigureAwait(false);
  102. // Sum up the runtime of all .vob files skipping the first .vob
  103. for (var i = 1; i < vobs.Count; i++)
  104. {
  105. var tmpMediaInfo = await GetMediaInfo(
  106. new Video
  107. {
  108. Path = vobs[i]
  109. },
  110. cancellationToken).ConfigureAwait(false);
  111. mediaInfoResult.RunTimeTicks += tmpMediaInfo.RunTimeTicks;
  112. }
  113. }
  114. else if (item.VideoType == VideoType.BluRay)
  115. {
  116. // Get BD disc information
  117. blurayDiscInfo = GetBDInfo(item.Path);
  118. // Return if no playable .m2ts files are found
  119. if (blurayDiscInfo is null || blurayDiscInfo.Files.Length == 0)
  120. {
  121. _logger.LogError("No playable .m2ts files found in Blu-ray structure, skipping FFprobe.");
  122. return ItemUpdateType.MetadataImport;
  123. }
  124. // Fetch metadata of first .m2ts file
  125. mediaInfoResult = await GetMediaInfo(
  126. new Video
  127. {
  128. Path = blurayDiscInfo.Files[0]
  129. },
  130. cancellationToken).ConfigureAwait(false);
  131. }
  132. else
  133. {
  134. mediaInfoResult = await GetMediaInfo(item, cancellationToken).ConfigureAwait(false);
  135. }
  136. cancellationToken.ThrowIfCancellationRequested();
  137. }
  138. await Fetch(item, cancellationToken, mediaInfoResult, blurayDiscInfo, options).ConfigureAwait(false);
  139. return ItemUpdateType.MetadataImport;
  140. }
  141. private Task<Model.MediaInfo.MediaInfo> GetMediaInfo(
  142. Video item,
  143. CancellationToken cancellationToken)
  144. {
  145. cancellationToken.ThrowIfCancellationRequested();
  146. var path = item.Path;
  147. var protocol = item.PathProtocol ?? MediaProtocol.File;
  148. if (item.IsShortcut)
  149. {
  150. path = item.ShortcutPath;
  151. protocol = _mediaSourceManager.GetPathProtocol(path);
  152. }
  153. return _mediaEncoder.GetMediaInfo(
  154. new MediaInfoRequest
  155. {
  156. ExtractChapters = true,
  157. MediaType = DlnaProfileType.Video,
  158. MediaSource = new MediaSourceInfo
  159. {
  160. Path = path,
  161. Protocol = protocol,
  162. VideoType = item.VideoType,
  163. IsoType = item.IsoType
  164. }
  165. },
  166. cancellationToken);
  167. }
  168. protected async Task Fetch(
  169. Video video,
  170. CancellationToken cancellationToken,
  171. Model.MediaInfo.MediaInfo? mediaInfo,
  172. BlurayDiscInfo? blurayInfo,
  173. MetadataRefreshOptions options)
  174. {
  175. List<MediaStream> mediaStreams = new List<MediaStream>();
  176. IReadOnlyList<MediaAttachment> mediaAttachments;
  177. ChapterInfo[] chapters;
  178. // Add external streams before adding the streams from the file to preserve stream IDs on remote videos
  179. await AddExternalSubtitlesAsync(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
  180. await AddExternalAudioAsync(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
  181. var startIndex = mediaStreams.Count == 0 ? 0 : (mediaStreams.Max(i => i.Index) + 1);
  182. if (mediaInfo is not null)
  183. {
  184. foreach (var mediaStream in mediaInfo.MediaStreams)
  185. {
  186. mediaStream.Index = startIndex++;
  187. mediaStreams.Add(mediaStream);
  188. }
  189. mediaAttachments = mediaInfo.MediaAttachments;
  190. video.TotalBitrate = mediaInfo.Bitrate;
  191. video.RunTimeTicks = mediaInfo.RunTimeTicks;
  192. video.Container = mediaInfo.Container;
  193. var videoType = video.VideoType;
  194. if (videoType == VideoType.BluRay || videoType == VideoType.Dvd)
  195. {
  196. video.Size = mediaInfo.Size;
  197. }
  198. chapters = mediaInfo.Chapters ?? [];
  199. if (blurayInfo is not null)
  200. {
  201. FetchBdInfo(video, ref chapters, mediaStreams, blurayInfo);
  202. }
  203. }
  204. else
  205. {
  206. foreach (var mediaStream in video.GetMediaStreams())
  207. {
  208. if (!mediaStream.IsExternal)
  209. {
  210. mediaStream.Index = startIndex++;
  211. mediaStreams.Add(mediaStream);
  212. }
  213. }
  214. mediaAttachments = [];
  215. chapters = [];
  216. }
  217. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  218. if (mediaInfo is not null)
  219. {
  220. FetchEmbeddedInfo(video, mediaInfo, options, libraryOptions);
  221. FetchPeople(video, mediaInfo, options);
  222. video.Timestamp = mediaInfo.Timestamp;
  223. video.Video3DFormat ??= mediaInfo.Video3DFormat;
  224. }
  225. if (libraryOptions.AllowEmbeddedSubtitles == EmbeddedSubtitleOptions.AllowText || libraryOptions.AllowEmbeddedSubtitles == EmbeddedSubtitleOptions.AllowNone)
  226. {
  227. _logger.LogDebug("Disabling embedded image subtitles for {Path} due to DisableEmbeddedImageSubtitles setting", video.Path);
  228. mediaStreams.RemoveAll(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal && !i.IsTextSubtitleStream);
  229. }
  230. if (libraryOptions.AllowEmbeddedSubtitles == EmbeddedSubtitleOptions.AllowImage || libraryOptions.AllowEmbeddedSubtitles == EmbeddedSubtitleOptions.AllowNone)
  231. {
  232. _logger.LogDebug("Disabling embedded text subtitles for {Path} due to DisableEmbeddedTextSubtitles setting", video.Path);
  233. mediaStreams.RemoveAll(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal && i.IsTextSubtitleStream);
  234. }
  235. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  236. video.Height = videoStream?.Height ?? 0;
  237. video.Width = videoStream?.Width ?? 0;
  238. video.DefaultVideoStreamIndex = videoStream?.Index;
  239. video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
  240. _mediaStreamRepository.SaveMediaStreams(video.Id, mediaStreams, cancellationToken);
  241. if (mediaAttachments.Any())
  242. {
  243. _mediaAttachmentRepository.SaveMediaAttachments(video.Id, mediaAttachments, cancellationToken);
  244. }
  245. if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh
  246. || options.MetadataRefreshMode == MetadataRefreshMode.Default)
  247. {
  248. if (_config.Configuration.DummyChapterDuration > 0 && chapters.Length == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
  249. {
  250. chapters = CreateDummyChapters(video);
  251. }
  252. NormalizeChapterNames(chapters);
  253. var extractDuringScan = false;
  254. if (libraryOptions is not null)
  255. {
  256. extractDuringScan = libraryOptions.ExtractChapterImagesDuringLibraryScan;
  257. }
  258. await _chapterManager.RefreshChapterImages(video, options.DirectoryService, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);
  259. _chapterManager.SaveChapters(video, chapters);
  260. }
  261. }
  262. private void NormalizeChapterNames(ChapterInfo[] chapters)
  263. {
  264. for (int i = 0; i < chapters.Length; i++)
  265. {
  266. string? name = chapters[i].Name;
  267. // Check if the name is empty and/or if the name is a time
  268. // Some ripping programs do that.
  269. if (string.IsNullOrWhiteSpace(name)
  270. || TimeSpan.TryParse(name, out _))
  271. {
  272. chapters[i].Name = string.Format(
  273. CultureInfo.InvariantCulture,
  274. _localization.GetLocalizedString("ChapterNameValue"),
  275. (i + 1).ToString(CultureInfo.InvariantCulture));
  276. }
  277. }
  278. }
  279. private void FetchBdInfo(Video video, ref ChapterInfo[] chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
  280. {
  281. var ffmpegVideoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  282. var externalStreams = mediaStreams.Where(s => s.IsExternal).ToList();
  283. // Fill video properties from the BDInfo result
  284. mediaStreams.Clear();
  285. // Rebuild the list with external streams first
  286. int index = 0;
  287. foreach (var stream in externalStreams.Concat(blurayInfo.MediaStreams))
  288. {
  289. stream.Index = index++;
  290. mediaStreams.Add(stream);
  291. }
  292. if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
  293. {
  294. video.RunTimeTicks = blurayInfo.RunTimeTicks;
  295. }
  296. if (blurayInfo.Chapters is not null)
  297. {
  298. double[] brChapter = blurayInfo.Chapters;
  299. chapters = new ChapterInfo[brChapter.Length];
  300. for (int i = 0; i < brChapter.Length; i++)
  301. {
  302. chapters[i] = new ChapterInfo
  303. {
  304. StartPositionTicks = TimeSpan.FromSeconds(brChapter[i]).Ticks
  305. };
  306. }
  307. }
  308. var blurayVideoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  309. // Use the ffprobe values if these are empty
  310. if (blurayVideoStream is not null && ffmpegVideoStream is not null)
  311. {
  312. // Always use ffmpeg's detected codec since that is what the rest of the codebase expects.
  313. blurayVideoStream.Codec = ffmpegVideoStream.Codec;
  314. blurayVideoStream.BitRate = blurayVideoStream.BitRate.GetValueOrDefault() == 0 ? ffmpegVideoStream.BitRate : blurayVideoStream.BitRate;
  315. blurayVideoStream.Width = blurayVideoStream.Width.GetValueOrDefault() == 0 ? ffmpegVideoStream.Width : blurayVideoStream.Width;
  316. blurayVideoStream.Height = blurayVideoStream.Height.GetValueOrDefault() == 0 ? ffmpegVideoStream.Height : blurayVideoStream.Height;
  317. blurayVideoStream.ColorRange = ffmpegVideoStream.ColorRange;
  318. blurayVideoStream.ColorSpace = ffmpegVideoStream.ColorSpace;
  319. blurayVideoStream.ColorTransfer = ffmpegVideoStream.ColorTransfer;
  320. blurayVideoStream.ColorPrimaries = ffmpegVideoStream.ColorPrimaries;
  321. }
  322. }
  323. /// <summary>
  324. /// Gets information about the longest playlist on a bdrom.
  325. /// </summary>
  326. /// <param name="path">The path.</param>
  327. /// <returns>VideoStream.</returns>
  328. private BlurayDiscInfo? GetBDInfo(string path)
  329. {
  330. ArgumentException.ThrowIfNullOrEmpty(path);
  331. try
  332. {
  333. return _blurayExaminer.GetDiscInfo(path);
  334. }
  335. catch (Exception ex)
  336. {
  337. _logger.LogError(ex, "Error getting BDInfo");
  338. return null;
  339. }
  340. }
  341. private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions refreshOptions, LibraryOptions libraryOptions)
  342. {
  343. var replaceData = refreshOptions.ReplaceAllMetadata;
  344. if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.OfficialRating))
  345. {
  346. if (string.IsNullOrWhiteSpace(video.OfficialRating) || replaceData)
  347. {
  348. video.OfficialRating = data.OfficialRating;
  349. }
  350. }
  351. if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Genres))
  352. {
  353. if (video.Genres.Length == 0 || replaceData)
  354. {
  355. video.Genres = [];
  356. foreach (var genre in data.Genres.Trimmed())
  357. {
  358. video.AddGenre(genre);
  359. }
  360. }
  361. }
  362. if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Studios))
  363. {
  364. if (video.Studios.Length == 0 || replaceData)
  365. {
  366. video.SetStudios(data.Studios);
  367. }
  368. }
  369. if (!video.IsLocked && video is MusicVideo musicVideo)
  370. {
  371. if (string.IsNullOrEmpty(musicVideo.Album) || replaceData)
  372. {
  373. musicVideo.Album = data.Album;
  374. }
  375. if (musicVideo.Artists.Count == 0 || replaceData)
  376. {
  377. musicVideo.Artists = data.Artists;
  378. }
  379. }
  380. if (data.ProductionYear.HasValue)
  381. {
  382. if (!video.ProductionYear.HasValue || replaceData)
  383. {
  384. video.ProductionYear = data.ProductionYear;
  385. }
  386. }
  387. if (data.PremiereDate.HasValue)
  388. {
  389. if (!video.PremiereDate.HasValue || replaceData)
  390. {
  391. video.PremiereDate = data.PremiereDate;
  392. }
  393. }
  394. if (data.IndexNumber.HasValue)
  395. {
  396. if (!video.IndexNumber.HasValue || replaceData)
  397. {
  398. video.IndexNumber = data.IndexNumber;
  399. }
  400. }
  401. if (data.ParentIndexNumber.HasValue)
  402. {
  403. if (!video.ParentIndexNumber.HasValue || replaceData)
  404. {
  405. video.ParentIndexNumber = data.ParentIndexNumber;
  406. }
  407. }
  408. if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Name))
  409. {
  410. if (!string.IsNullOrWhiteSpace(data.Name) && libraryOptions.EnableEmbeddedTitles)
  411. {
  412. // Separate option to use the embedded name for extras because it will often be the same name as the movie
  413. if (!video.ExtraType.HasValue || libraryOptions.EnableEmbeddedExtrasTitles)
  414. {
  415. video.Name = data.Name;
  416. }
  417. }
  418. if (!string.IsNullOrWhiteSpace(data.ForcedSortName))
  419. {
  420. video.ForcedSortName = data.ForcedSortName;
  421. }
  422. }
  423. // If we don't have a ProductionYear try and get it from PremiereDate
  424. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  425. {
  426. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  427. }
  428. if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Overview))
  429. {
  430. if (string.IsNullOrWhiteSpace(video.Overview) || replaceData)
  431. {
  432. video.Overview = data.Overview;
  433. }
  434. }
  435. }
  436. private void FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  437. {
  438. if (video.IsLocked
  439. || video.LockedFields.Contains(MetadataField.Cast)
  440. || data.People.Length == 0)
  441. {
  442. return;
  443. }
  444. if (options.ReplaceAllMetadata || _libraryManager.GetPeople(video).Count == 0)
  445. {
  446. var people = new List<PersonInfo>();
  447. foreach (var person in data.People)
  448. {
  449. PeopleHelper.AddPerson(people, new PersonInfo
  450. {
  451. Name = person.Name.Trim(),
  452. Type = person.Type,
  453. Role = person.Role.Trim()
  454. });
  455. }
  456. _libraryManager.UpdatePeople(video, people);
  457. }
  458. }
  459. /// <summary>
  460. /// Adds the external subtitles.
  461. /// </summary>
  462. /// <param name="video">The video.</param>
  463. /// <param name="currentStreams">The current streams.</param>
  464. /// <param name="options">The refreshOptions.</param>
  465. /// <param name="cancellationToken">The cancellation token.</param>
  466. /// <returns>Task.</returns>
  467. private async Task AddExternalSubtitlesAsync(
  468. Video video,
  469. List<MediaStream> currentStreams,
  470. MetadataRefreshOptions options,
  471. CancellationToken cancellationToken)
  472. {
  473. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  474. var externalSubtitleStreams = await _subtitleResolver.GetExternalStreamsAsync(video, startIndex, options.DirectoryService, false, cancellationToken).ConfigureAwait(false);
  475. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  476. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  477. var subtitleOptions = _config.GetConfiguration<SubtitleOptions>("subtitles");
  478. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  479. string[] subtitleDownloadLanguages;
  480. bool skipIfEmbeddedSubtitlesPresent;
  481. bool skipIfAudioTrackMatches;
  482. bool requirePerfectMatch;
  483. bool enabled;
  484. if (libraryOptions.SubtitleDownloadLanguages is null)
  485. {
  486. subtitleDownloadLanguages = subtitleOptions.DownloadLanguages;
  487. skipIfEmbeddedSubtitlesPresent = subtitleOptions.SkipIfEmbeddedSubtitlesPresent;
  488. skipIfAudioTrackMatches = subtitleOptions.SkipIfAudioTrackMatches;
  489. requirePerfectMatch = subtitleOptions.RequirePerfectMatch;
  490. enabled = (subtitleOptions.DownloadEpisodeSubtitles &&
  491. video is Episode) ||
  492. (subtitleOptions.DownloadMovieSubtitles &&
  493. video is Movie);
  494. }
  495. else
  496. {
  497. subtitleDownloadLanguages = libraryOptions.SubtitleDownloadLanguages;
  498. skipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
  499. skipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
  500. requirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
  501. enabled = true;
  502. }
  503. if (enableSubtitleDownloading && enabled)
  504. {
  505. var downloadedLanguages = await new SubtitleDownloader(
  506. _logger,
  507. _subtitleManager).DownloadSubtitles(
  508. video,
  509. currentStreams.Concat(externalSubtitleStreams).ToList(),
  510. skipIfEmbeddedSubtitlesPresent,
  511. skipIfAudioTrackMatches,
  512. requirePerfectMatch,
  513. subtitleDownloadLanguages,
  514. libraryOptions.DisabledSubtitleFetchers,
  515. libraryOptions.SubtitleFetcherOrder,
  516. true,
  517. cancellationToken).ConfigureAwait(false);
  518. // Rescan
  519. if (downloadedLanguages.Count > 0)
  520. {
  521. externalSubtitleStreams = await _subtitleResolver.GetExternalStreamsAsync(video, startIndex, options.DirectoryService, true, cancellationToken).ConfigureAwait(false);
  522. }
  523. }
  524. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).Distinct().ToArray();
  525. currentStreams.AddRange(externalSubtitleStreams);
  526. }
  527. /// <summary>
  528. /// Adds the external audio.
  529. /// </summary>
  530. /// <param name="video">The video.</param>
  531. /// <param name="currentStreams">The current streams.</param>
  532. /// <param name="options">The refreshOptions.</param>
  533. /// <param name="cancellationToken">The cancellation token.</param>
  534. private async Task AddExternalAudioAsync(
  535. Video video,
  536. List<MediaStream> currentStreams,
  537. MetadataRefreshOptions options,
  538. CancellationToken cancellationToken)
  539. {
  540. var startIndex = currentStreams.Count == 0 ? 0 : currentStreams.Max(i => i.Index) + 1;
  541. var externalAudioStreams = await _audioResolver.GetExternalStreamsAsync(video, startIndex, options.DirectoryService, false, cancellationToken).ConfigureAwait(false);
  542. video.AudioFiles = externalAudioStreams.Select(i => i.Path).Distinct().ToArray();
  543. currentStreams.AddRange(externalAudioStreams);
  544. }
  545. /// <summary>
  546. /// Creates dummy chapters.
  547. /// </summary>
  548. /// <param name="video">The video.</param>
  549. /// <returns>An array of dummy chapters.</returns>
  550. internal ChapterInfo[] CreateDummyChapters(Video video)
  551. {
  552. var runtime = video.RunTimeTicks.GetValueOrDefault();
  553. // Only process files with a runtime greater than 0 and less than 12h. The latter are likely corrupted.
  554. if (runtime < 0 || runtime > TimeSpan.FromHours(12).Ticks)
  555. {
  556. throw new ArgumentException(
  557. string.Format(
  558. CultureInfo.InvariantCulture,
  559. "{0} has an invalid runtime of {1} minutes",
  560. video.Name,
  561. TimeSpan.FromTicks(runtime).TotalMinutes));
  562. }
  563. long dummyChapterDuration = TimeSpan.FromSeconds(_config.Configuration.DummyChapterDuration).Ticks;
  564. if (runtime <= dummyChapterDuration)
  565. {
  566. return [];
  567. }
  568. int chapterCount = (int)(runtime / dummyChapterDuration);
  569. var chapters = new ChapterInfo[chapterCount];
  570. long currentChapterTicks = 0;
  571. for (int i = 0; i < chapterCount; i++)
  572. {
  573. chapters[i] = new ChapterInfo
  574. {
  575. StartPositionTicks = currentChapterTicks
  576. };
  577. currentChapterTicks += dummyChapterDuration;
  578. }
  579. return chapters;
  580. }
  581. }
  582. }