< 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: 116
Coverable lines: 124
Total lines: 318
Line coverage: 6.4%
Branch coverage
0%
Covered branches: 0
Total branches: 56
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/12/2026 - 12:15:57 AM Line coverage: 6.6% (8/120) Branch coverage: 0% (0/54) Total lines: 31110/29/2026 - 12:17:11 AM Line coverage: 6.4% (8/124) Branch coverage: 0% (0/56) Total lines: 318 5/12/2026 - 12:15:57 AM Line coverage: 6.6% (8/120) Branch coverage: 0% (0/54) Total lines: 31110/29/2026 - 12:17:11 AM Line coverage: 6.4% (8/124) Branch coverage: 0% (0/56) Total lines: 318

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%11100%
IsEligibleForChapterImageExtraction(...)0%110100%
GetAverageDurationBetweenChapters(...)0%2040%
RefreshChapterImages()0%1056320%
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    {
 2759        _logger = logger;
 2760        _fileSystem = fileSystem;
 2761        _encoder = encoder;
 2762        _chapterRepository = chapterRepository;
 2763        _libraryManager = libraryManager;
 2764        _pathManager = pathManager;
 2765    }
 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;
 0140        var extractedCount = 0;
 141
 0142        var runtimeTicks = video.RunTimeTicks ?? 0;
 143
 0144        var currentImages = GetSavedChapterImages(video, directoryService);
 145
 0146        foreach (var chapter in chapters)
 147        {
 0148            if (chapter.StartPositionTicks >= runtimeTicks)
 149            {
 0150                _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position 
 0151                break;
 152            }
 153
 0154            var path = _pathManager.GetChapterImagePath(video, chapter.StartPositionTicks);
 155
 0156            if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
 157            {
 0158                if (extractImages)
 159                {
 0160                    cancellationToken.ThrowIfCancellationRequested();
 161
 162                    try
 163                    {
 164                        // Add some time for the first chapter to make sure we don't end up with a black image
 0165                        var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, vid
 166
 0167                        var inputPath = video.Path;
 0168                        var directoryPath = Path.GetDirectoryName(path);
 0169                        if (!string.IsNullOrEmpty(directoryPath))
 170                        {
 0171                            Directory.CreateDirectory(directoryPath);
 172                        }
 173
 0174                        var container = video.Container;
 0175                        var mediaSource = new MediaSourceInfo
 0176                        {
 0177                            VideoType = video.VideoType,
 0178                            IsoType = video.IsoType,
 0179                            Protocol = video.PathProtocol ?? MediaProtocol.File,
 0180                        };
 181
 0182                        _logger.LogDebug("Extracting chapter image for {Name} at {Time}", video.Name, time);
 0183                        var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefa
 0184                        File.Copy(tempFile, path, true);
 185
 186                        try
 187                        {
 0188                            _fileSystem.DeleteFile(tempFile);
 0189                        }
 0190                        catch (IOException ex)
 191                        {
 0192                            _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile
 0193                        }
 194
 0195                        chapter.ImagePath = path;
 0196                        chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
 0197                        changesMade = true;
 0198                        extractedCount++;
 0199                    }
 0200                    catch (Exception ex)
 201                    {
 0202                        _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
 0203                        success = false;
 0204                        break;
 205                    }
 206                }
 0207                else if (!string.IsNullOrEmpty(chapter.ImagePath))
 208                {
 0209                    chapter.ImagePath = null;
 0210                    changesMade = true;
 211                }
 212            }
 0213            else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
 214            {
 0215                chapter.ImagePath = path;
 0216                chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
 0217                changesMade = true;
 218            }
 0219            else if (libraryOptions?.EnableChapterImageExtraction != true)
 220            {
 221                // We have an image for the current chapter but the user has disabled chapter image extraction -> delete
 0222                chapter.ImagePath = null;
 0223                changesMade = true;
 224            }
 0225        }
 226
 0227        if (extractedCount > 0)
 228        {
 0229            _logger.LogInformation("Extracted {Count} chapter images for {Name} at {Path}", extractedCount, video.Name, 
 230        }
 231
 0232        if (saveChapters && changesMade)
 233        {
 0234            SaveChapters(video, chapters);
 235        }
 236
 0237        DeleteDeadImages(currentImages, chapters);
 238
 0239        return success;
 0240    }
 241
 242    /// <inheritdoc />
 243    public bool Supports(BaseItem item)
 0244        => item is Video or Audio;
 245
 246    /// <inheritdoc />
 247    public void SaveChapters(BaseItem item, IReadOnlyList<ChapterInfo> chapters)
 248    {
 0249        if (!Supports(item))
 250        {
 0251            _logger.LogWarning("Attempted to save chapters for unsupported item type {Type}: {Name} ({Id})", item.GetTyp
 0252            return;
 253        }
 254
 255        // Remove any chapters that are outside of the runtime of the item
 0256        var validChapters = chapters.Where(c => c.StartPositionTicks < item.RunTimeTicks).ToList();
 0257        _chapterRepository.SaveChapters(item.Id, validChapters);
 0258    }
 259
 260    /// <inheritdoc />
 261    public ChapterInfo? GetChapter(Guid baseItemId, int index)
 262    {
 0263        return _chapterRepository.GetChapter(baseItemId, index);
 264    }
 265
 266    /// <inheritdoc />
 267    public IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId)
 268    {
 6269        return _chapterRepository.GetChapters(baseItemId);
 270    }
 271
 272    /// <inheritdoc />
 273    public async Task DeleteChapterDataAsync(Guid itemId, CancellationToken cancellationToken)
 274    {
 0275        await _chapterRepository.DeleteChaptersAsync(itemId, cancellationToken).ConfigureAwait(false);
 0276    }
 277
 278    private IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
 279    {
 0280        var path = _pathManager.GetChapterImageFolderPath(video);
 0281        if (!Directory.Exists(path))
 282        {
 0283            return [];
 284        }
 285
 286        try
 287        {
 0288            return directoryService.GetFilePaths(path);
 289        }
 0290        catch (IOException)
 291        {
 0292            return [];
 293        }
 0294    }
 295
 296    private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
 297    {
 0298        var existingImages = chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i));
 0299        var deadImages = images
 0300            .Except(existingImages, StringComparer.OrdinalIgnoreCase)
 0301            .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.Ordin
 0302            .ToList();
 303
 0304        foreach (var image in deadImages)
 305        {
 0306            _logger.LogDebug("Deleting dead chapter image {Path}", image);
 307
 308            try
 309            {
 0310                _fileSystem.DeleteFile(image!);
 0311            }
 0312            catch (IOException ex)
 313            {
 0314                _logger.LogError(ex, "Error deleting {Path}.", image);
 0315            }
 316        }
 0317    }
 318}