< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Chapters.ChapterManager
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Chapters/ChapterManager.cs
Line coverage
12%
Covered lines: 7
Uncovered lines: 50
Coverable lines: 57
Total lines: 313
Line coverage: 12.2%
Branch coverage
0%
Covered branches: 0
Total branches: 20
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%11100%
IsEligibleForChapterImageExtraction(...)0%110100%
GetAverageDurationBetweenChapters(...)0%2040%
SaveChapters(...)100%210%
GetChapter(...)100%210%
GetChapters(...)100%210%
DeleteChapterImages(...)0%620%
GetSavedChapterImages(...)0%620%
DeleteDeadImages(...)0%620%

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/Chapters/ChapterManager.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IO;
 5using System.Linq;
 6using System.Threading;
 7using System.Threading.Tasks;
 8using Jellyfin.Extensions;
 9using MediaBrowser.Controller.Chapters;
 10using MediaBrowser.Controller.Entities;
 11using MediaBrowser.Controller.IO;
 12using MediaBrowser.Controller.Library;
 13using MediaBrowser.Controller.MediaEncoding;
 14using MediaBrowser.Controller.Persistence;
 15using MediaBrowser.Controller.Providers;
 16using MediaBrowser.Model.Configuration;
 17using MediaBrowser.Model.Dto;
 18using MediaBrowser.Model.Entities;
 19using MediaBrowser.Model.IO;
 20using MediaBrowser.Model.MediaInfo;
 21using Microsoft.Extensions.Logging;
 22
 23namespace Emby.Server.Implementations.Chapters;
 24
 25/// <summary>
 26/// The chapter manager.
 27/// </summary>
 28public 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>
 040    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    {
 2159        _logger = logger;
 2160        _fileSystem = fileSystem;
 2161        _encoder = encoder;
 2162        _chapterRepository = chapterRepository;
 2163        _libraryManager = libraryManager;
 2164        _pathManager = pathManager;
 2165    }
 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    {
 075        if (video.IsPlaceHolder)
 76        {
 077            return false;
 78        }
 79
 080        if (libraryOptions is null || !libraryOptions.EnableChapterImageExtraction)
 81        {
 082            return false;
 83        }
 84
 085        if (video.IsShortcut)
 86        {
 087            return false;
 88        }
 89
 090        if (!video.IsCompleteMedia)
 91        {
 092            return false;
 93        }
 94
 95        // Can't extract images if there are no video streams
 096        return video.DefaultVideoStreamIndex.HasValue;
 97    }
 98
 99    private long GetAverageDurationBetweenChapters(IReadOnlyList<ChapterInfo> chapters)
 100    {
 0101        if (chapters.Count < 2)
 102        {
 0103            return 0;
 104        }
 105
 0106        long sum = 0;
 0107        for (int i = 1; i < chapters.Count; i++)
 108        {
 0109            sum += chapters[i].StartPositionTicks - chapters[i - 1].StartPositionTicks;
 110        }
 111
 0112        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    {
 0238        _chapterRepository.SaveChapters(video.Id, chapters);
 0239    }
 240
 241    /// <inheritdoc />
 242    public ChapterInfo? GetChapter(Guid baseItemId, int index)
 243    {
 0244        return _chapterRepository.GetChapter(baseItemId, index);
 245    }
 246
 247    /// <inheritdoc />
 248    public IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId)
 249    {
 0250        return _chapterRepository.GetChapters(baseItemId);
 251    }
 252
 253    /// <inheritdoc />
 254    public void DeleteChapterImages(Video video)
 255    {
 0256        var path = _pathManager.GetChapterImageFolderPath(video);
 257        try
 258        {
 0259            if (Directory.Exists(path))
 260            {
 0261                _logger.LogInformation("Removing chapter images for {Name} [{Id}]", video.Name, video.Id);
 0262                Directory.Delete(path, true);
 263            }
 0264        }
 0265        catch (Exception ex)
 266        {
 0267            _logger.LogWarning("Failed to remove chapter image folder for {Item}: {Exception}", video.Id, ex);
 0268        }
 269
 0270        _chapterRepository.DeleteChapters(video.Id);
 0271    }
 272
 273    private IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
 274    {
 0275        var path = _pathManager.GetChapterImageFolderPath(video);
 0276        if (!Directory.Exists(path))
 277        {
 0278            return [];
 279        }
 280
 281        try
 282        {
 0283            return directoryService.GetFilePaths(path);
 284        }
 0285        catch (IOException)
 286        {
 0287            return [];
 288        }
 0289    }
 290
 291    private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
 292    {
 0293        var existingImages = chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i));
 0294        var deadImages = images
 0295            .Except(existingImages, StringComparer.OrdinalIgnoreCase)
 0296            .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.Ordin
 0297            .ToList();
 298
 0299        foreach (var image in deadImages)
 300        {
 0301            _logger.LogDebug("Deleting dead chapter image {Path}", image);
 302
 303            try
 304            {
 0305                _fileSystem.DeleteFile(image!);
 0306            }
 0307            catch (IOException ex)
 308            {
 0309                _logger.LogError(ex, "Error deleting {Path}.", image);
 0310            }
 311        }
 0312    }
 313}