< 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
6%
Covered lines: 8
Uncovered lines: 112
Coverable lines: 120
Total lines: 311
Line coverage: 6.6%
Branch coverage
0%
Covered branches: 0
Total branches: 54
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 1/23/2026 - 12:11:06 AM Line coverage: 14.5% (7/48) Branch coverage: 0% (0/18) Total lines: 3004/19/2026 - 12:14:27 AM Line coverage: 6% (7/116) Branch coverage: 0% (0/46) Total lines: 3005/4/2026 - 12:15:16 AM Line coverage: 6.6% (8/120) Branch coverage: 0% (0/52) Total lines: 3115/5/2026 - 12:15:44 AM Line coverage: 6.6% (8/120) Branch coverage: 0% (0/54) Total lines: 311 1/23/2026 - 12:11:06 AM Line coverage: 14.5% (7/48) Branch coverage: 0% (0/18) Total lines: 3004/19/2026 - 12:14:27 AM Line coverage: 6% (7/116) Branch coverage: 0% (0/46) Total lines: 3005/4/2026 - 12:15:16 AM Line coverage: 6.6% (8/120) Branch coverage: 0% (0/52) Total lines: 3115/5/2026 - 12:15:44 AM Line coverage: 6.6% (8/120) Branch coverage: 0% (0/54) Total lines: 311

Coverage delta

Coverage delta 9 -9

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%11100%
IsEligibleForChapterImageExtraction(...)0%110100%
GetAverageDurationBetweenChapters(...)0%2040%
RefreshChapterImages()0%930300%
Supports(...)0%2040%
SaveChapters(...)0%620%
GetChapter(...)100%210%
GetChapters(...)100%11100%
DeleteChapterDataAsync()100%210%
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.IO;
 4using System.Linq;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using Jellyfin.Extensions;
 8using MediaBrowser.Controller.Chapters;
 9using MediaBrowser.Controller.Entities;
 10using MediaBrowser.Controller.Entities.Audio;
 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    {
 0118        if (chapters.Count == 0)
 119        {
 0120            return true;
 121        }
 122
 0123        var libraryOptions = _libraryManager.GetLibraryOptions(video);
 124
 0125        if (!IsEligibleForChapterImageExtraction(video, libraryOptions))
 126        {
 0127            extractImages = false;
 128        }
 129
 0130        var averageChapterDuration = GetAverageDurationBetweenChapters(chapters);
 0131        var threshold = TimeSpan.FromSeconds(1).Ticks;
 0132        if (chapters.Count >= 2 && averageChapterDuration < threshold)
 133        {
 0134            _logger.LogInformation("Skipping chapter image extraction for {Video} as the average chapter duration {Avera
 0135            extractImages = false;
 136        }
 137
 0138        var success = true;
 0139        var changesMade = false;
 140
 0141        var runtimeTicks = video.RunTimeTicks ?? 0;
 142
 0143        var currentImages = GetSavedChapterImages(video, directoryService);
 144
 0145        foreach (var chapter in chapters)
 146        {
 0147            if (chapter.StartPositionTicks >= runtimeTicks)
 148            {
 0149                _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position 
 0150                break;
 151            }
 152
 0153            var path = _pathManager.GetChapterImagePath(video, chapter.StartPositionTicks);
 154
 0155            if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
 156            {
 0157                if (extractImages)
 158                {
 0159                    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
 0164                        var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, vid
 165
 0166                        var inputPath = video.Path;
 0167                        var directoryPath = Path.GetDirectoryName(path);
 0168                        if (!string.IsNullOrEmpty(directoryPath))
 169                        {
 0170                            Directory.CreateDirectory(directoryPath);
 171                        }
 172
 0173                        var container = video.Container;
 0174                        var mediaSource = new MediaSourceInfo
 0175                        {
 0176                            VideoType = video.VideoType,
 0177                            IsoType = video.IsoType,
 0178                            Protocol = video.PathProtocol ?? MediaProtocol.File,
 0179                        };
 180
 0181                        _logger.LogInformation("Extracting chapter image for {Name} at {Path}", video.Name, inputPath);
 0182                        var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefa
 0183                        File.Copy(tempFile, path, true);
 184
 185                        try
 186                        {
 0187                            _fileSystem.DeleteFile(tempFile);
 0188                        }
 0189                        catch (IOException ex)
 190                        {
 0191                            _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile
 0192                        }
 193
 0194                        chapter.ImagePath = path;
 0195                        chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
 0196                        changesMade = true;
 0197                    }
 0198                    catch (Exception ex)
 199                    {
 0200                        _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
 0201                        success = false;
 0202                        break;
 203                    }
 204                }
 0205                else if (!string.IsNullOrEmpty(chapter.ImagePath))
 206                {
 0207                    chapter.ImagePath = null;
 0208                    changesMade = true;
 209                }
 210            }
 0211            else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
 212            {
 0213                chapter.ImagePath = path;
 0214                chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
 0215                changesMade = true;
 216            }
 0217            else if (libraryOptions?.EnableChapterImageExtraction != true)
 218            {
 219                // We have an image for the current chapter but the user has disabled chapter image extraction -> delete
 0220                chapter.ImagePath = null;
 0221                changesMade = true;
 222            }
 0223        }
 224
 0225        if (saveChapters && changesMade)
 226        {
 0227            SaveChapters(video, chapters);
 228        }
 229
 0230        DeleteDeadImages(currentImages, chapters);
 231
 0232        return success;
 0233    }
 234
 235    /// <inheritdoc />
 236    public bool Supports(BaseItem item)
 0237        => item is Video or Audio;
 238
 239    /// <inheritdoc />
 240    public void SaveChapters(BaseItem item, IReadOnlyList<ChapterInfo> chapters)
 241    {
 0242        if (!Supports(item))
 243       {
 0244          _logger.LogWarning("Attempted to save chapters for unsupported item type {Type}: {Name} ({Id})", item.GetType(
 0245          return;
 246       }
 247
 248        // Remove any chapters that are outside of the runtime of the item
 0249        var validChapters = chapters.Where(c => c.StartPositionTicks < item.RunTimeTicks).ToList();
 0250        _chapterRepository.SaveChapters(item.Id, validChapters);
 0251}
 252
 253    /// <inheritdoc />
 254    public ChapterInfo? GetChapter(Guid baseItemId, int index)
 255    {
 0256        return _chapterRepository.GetChapter(baseItemId, index);
 257    }
 258
 259    /// <inheritdoc />
 260    public IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId)
 261    {
 6262        return _chapterRepository.GetChapters(baseItemId);
 263    }
 264
 265    /// <inheritdoc />
 266    public async Task DeleteChapterDataAsync(Guid itemId, CancellationToken cancellationToken)
 267    {
 0268        await _chapterRepository.DeleteChaptersAsync(itemId, cancellationToken).ConfigureAwait(false);
 0269    }
 270
 271    private IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
 272    {
 0273        var path = _pathManager.GetChapterImageFolderPath(video);
 0274        if (!Directory.Exists(path))
 275        {
 0276            return [];
 277        }
 278
 279        try
 280        {
 0281            return directoryService.GetFilePaths(path);
 282        }
 0283        catch (IOException)
 284        {
 0285            return [];
 286        }
 0287    }
 288
 289    private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
 290    {
 0291        var existingImages = chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i));
 0292        var deadImages = images
 0293            .Except(existingImages, StringComparer.OrdinalIgnoreCase)
 0294            .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.Ordin
 0295            .ToList();
 296
 0297        foreach (var image in deadImages)
 298        {
 0299            _logger.LogDebug("Deleting dead chapter image {Path}", image);
 300
 301            try
 302            {
 0303                _fileSystem.DeleteFile(image!);
 0304            }
 0305            catch (IOException ex)
 306            {
 0307                _logger.LogError(ex, "Error deleting {Path}.", image);
 0308            }
 309        }
 0310    }
 311}