ChapterManager.cs 11 KB

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