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