ChapterManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Extensions;
  8. using MediaBrowser.Controller.Chapters;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.IO;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.MediaEncoding;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.MediaInfo;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.Chapters;
  22. /// <summary>
  23. /// The chapter manager.
  24. /// </summary>
  25. public class ChapterManager : IChapterManager
  26. {
  27. private readonly IFileSystem _fileSystem;
  28. private readonly ILogger<ChapterManager> _logger;
  29. private readonly IMediaEncoder _encoder;
  30. private readonly IChapterRepository _chapterRepository;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly IPathManager _pathManager;
  33. /// <summary>
  34. /// The first chapter ticks.
  35. /// </summary>
  36. private static readonly long _firstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="ChapterManager"/> class.
  39. /// </summary>
  40. /// <param name="logger">The <see cref="ILogger{ChapterManager}"/>.</param>
  41. /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
  42. /// <param name="encoder">The <see cref="IMediaEncoder"/>.</param>
  43. /// <param name="chapterRepository">The <see cref="IChapterRepository"/>.</param>
  44. /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
  45. /// <param name="pathManager">The <see cref="IPathManager"/>.</param>
  46. public ChapterManager(
  47. ILogger<ChapterManager> logger,
  48. IFileSystem fileSystem,
  49. IMediaEncoder encoder,
  50. IChapterRepository chapterRepository,
  51. ILibraryManager libraryManager,
  52. IPathManager pathManager)
  53. {
  54. _logger = logger;
  55. _fileSystem = fileSystem;
  56. _encoder = encoder;
  57. _chapterRepository = chapterRepository;
  58. _libraryManager = libraryManager;
  59. _pathManager = pathManager;
  60. }
  61. /// <summary>
  62. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  63. /// </summary>
  64. /// <param name="video">The video.</param>
  65. /// <param name="libraryOptions">The library options for the video.</param>
  66. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  67. private bool IsEligibleForChapterImageExtraction(Video video, LibraryOptions libraryOptions)
  68. {
  69. if (video.IsPlaceHolder)
  70. {
  71. return false;
  72. }
  73. if (libraryOptions is null || !libraryOptions.EnableChapterImageExtraction)
  74. {
  75. return false;
  76. }
  77. if (video.IsShortcut)
  78. {
  79. return false;
  80. }
  81. if (!video.IsCompleteMedia)
  82. {
  83. return false;
  84. }
  85. // Can't extract images if there are no video streams
  86. return video.DefaultVideoStreamIndex.HasValue;
  87. }
  88. private long GetAverageDurationBetweenChapters(IReadOnlyList<ChapterInfo> chapters)
  89. {
  90. if (chapters.Count < 2)
  91. {
  92. return 0;
  93. }
  94. long sum = 0;
  95. for (int i = 1; i < chapters.Count; i++)
  96. {
  97. sum += chapters[i].StartPositionTicks - chapters[i - 1].StartPositionTicks;
  98. }
  99. return sum / chapters.Count;
  100. }
  101. /// <inheritdoc />
  102. public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  103. {
  104. if (chapters.Count == 0)
  105. {
  106. return true;
  107. }
  108. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  109. if (!IsEligibleForChapterImageExtraction(video, libraryOptions))
  110. {
  111. extractImages = false;
  112. }
  113. var averageChapterDuration = GetAverageDurationBetweenChapters(chapters);
  114. var threshold = TimeSpan.FromSeconds(1).Ticks;
  115. if (averageChapterDuration < threshold)
  116. {
  117. _logger.LogInformation("Skipping chapter image extraction for {Video} as the average chapter duration {AverageDuration} was lower than the minimum threshold {Threshold}", video.Name, averageChapterDuration, threshold);
  118. extractImages = false;
  119. }
  120. var success = true;
  121. var changesMade = false;
  122. var runtimeTicks = video.RunTimeTicks ?? 0;
  123. var currentImages = GetSavedChapterImages(video, directoryService);
  124. foreach (var chapter in chapters)
  125. {
  126. if (chapter.StartPositionTicks >= runtimeTicks)
  127. {
  128. _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  129. break;
  130. }
  131. var path = _pathManager.GetChapterImagePath(video, chapter.StartPositionTicks);
  132. if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
  133. {
  134. if (extractImages)
  135. {
  136. cancellationToken.ThrowIfCancellationRequested();
  137. try
  138. {
  139. // Add some time for the first chapter to make sure we don't end up with a black image
  140. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  141. var inputPath = video.Path;
  142. var directoryPath = Path.GetDirectoryName(path);
  143. if (!string.IsNullOrEmpty(directoryPath))
  144. {
  145. Directory.CreateDirectory(directoryPath);
  146. }
  147. var container = video.Container;
  148. var mediaSource = new MediaSourceInfo
  149. {
  150. VideoType = video.VideoType,
  151. IsoType = video.IsoType,
  152. Protocol = video.PathProtocol ?? MediaProtocol.File,
  153. };
  154. _logger.LogInformation("Extracting chapter image for {Name} at {Path}", video.Name, inputPath);
  155. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  156. File.Copy(tempFile, path, true);
  157. try
  158. {
  159. _fileSystem.DeleteFile(tempFile);
  160. }
  161. catch (IOException ex)
  162. {
  163. _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
  164. }
  165. chapter.ImagePath = path;
  166. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  167. changesMade = true;
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
  172. success = false;
  173. break;
  174. }
  175. }
  176. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  177. {
  178. chapter.ImagePath = null;
  179. changesMade = true;
  180. }
  181. }
  182. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  183. {
  184. chapter.ImagePath = path;
  185. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  186. changesMade = true;
  187. }
  188. else if (libraryOptions?.EnableChapterImageExtraction != true)
  189. {
  190. // We have an image for the current chapter but the user has disabled chapter image extraction -> delete this chapter's image
  191. chapter.ImagePath = null;
  192. changesMade = true;
  193. }
  194. }
  195. if (saveChapters && changesMade)
  196. {
  197. _chapterRepository.SaveChapters(video.Id, chapters);
  198. }
  199. DeleteDeadImages(currentImages, chapters);
  200. return success;
  201. }
  202. /// <inheritdoc />
  203. public void SaveChapters(Video video, IReadOnlyList<ChapterInfo> chapters)
  204. {
  205. _chapterRepository.SaveChapters(video.Id, chapters);
  206. }
  207. /// <inheritdoc />
  208. public ChapterInfo? GetChapter(Guid baseItemId, int index)
  209. {
  210. return _chapterRepository.GetChapter(baseItemId, index);
  211. }
  212. /// <inheritdoc />
  213. public IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId)
  214. {
  215. return _chapterRepository.GetChapters(baseItemId);
  216. }
  217. /// <inheritdoc />
  218. public async Task DeleteChapterDataAsync(Guid itemId, CancellationToken cancellationToken)
  219. {
  220. await _chapterRepository.DeleteChaptersAsync(itemId, cancellationToken).ConfigureAwait(false);
  221. }
  222. private IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
  223. {
  224. var path = _pathManager.GetChapterImageFolderPath(video);
  225. if (!Directory.Exists(path))
  226. {
  227. return [];
  228. }
  229. try
  230. {
  231. return directoryService.GetFilePaths(path);
  232. }
  233. catch (IOException)
  234. {
  235. return [];
  236. }
  237. }
  238. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  239. {
  240. var existingImages = chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i));
  241. var deadImages = images
  242. .Except(existingImages, StringComparer.OrdinalIgnoreCase)
  243. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.OrdinalIgnoreCase))
  244. .ToList();
  245. foreach (var image in deadImages)
  246. {
  247. _logger.LogDebug("Deleting dead chapter image {Path}", image);
  248. try
  249. {
  250. _fileSystem.DeleteFile(image!);
  251. }
  252. catch (IOException ex)
  253. {
  254. _logger.LogError(ex, "Error deleting {Path}.", image);
  255. }
  256. }
  257. }
  258. }