FFProbeVideoInfo.cs 27 KB

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