< Summary - Jellyfin

Information
Class: MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor
Assembly: MediaBrowser.MediaEncoding
File(s): /srv/git/jellyfin/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
Line coverage
7%
Covered lines: 13
Uncovered lines: 172
Coverable lines: 185
Total lines: 384
Line coverage: 7%
Branch coverage
0%
Covered branches: 0
Total branches: 68
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/31/2026 - 12:15:44 AM Line coverage: 7.3% (13/177) Branch coverage: 0% (0/60) Total lines: 3726/4/2026 - 12:15:59 AM Line coverage: 5.1% (13/253) Branch coverage: 0% (0/90) Total lines: 5057/22/2026 - 12:16:22 AM Line coverage: 5% (13/255) Branch coverage: 0% (0/92) Total lines: 50810/29/2026 - 12:17:11 AM Line coverage: 5% (13/255) Branch coverage: 0% (0/92) Total lines: 50711/13/2026 - 12:19:51 AM Line coverage: 7% (13/185) Branch coverage: 0% (0/68) Total lines: 384 5/31/2026 - 12:15:44 AM Line coverage: 7.3% (13/177) Branch coverage: 0% (0/60) Total lines: 3726/4/2026 - 12:15:59 AM Line coverage: 5.1% (13/253) Branch coverage: 0% (0/90) Total lines: 5057/22/2026 - 12:16:22 AM Line coverage: 5% (13/255) Branch coverage: 0% (0/92) Total lines: 50810/29/2026 - 12:17:11 AM Line coverage: 5% (13/255) Branch coverage: 0% (0/92) Total lines: 50711/13/2026 - 12:19:51 AM Line coverage: 7% (13/185) Branch coverage: 0% (0/68) Total lines: 384

Coverage delta

Coverage delta 3 -3

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
GetAttachment()0%7280%
ExtractAllAttachments()100%210%
ExtractAllAttachmentsIndividuallyInternal()0%1190340%
GetAttachmentStream()100%210%
ExtractAttachment()0%7280%
ExtractAttachmentInternal()0%342180%
Dispose()100%11100%

File(s)

/srv/git/jellyfin/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.Globalization;
 5using System.IO;
 6using System.Linq;
 7using System.Text;
 8using System.Threading;
 9using System.Threading.Tasks;
 10using AsyncKeyedLock;
 11using Jellyfin.Extensions;
 12using MediaBrowser.Common.Extensions;
 13using MediaBrowser.Controller.Entities;
 14using MediaBrowser.Controller.IO;
 15using MediaBrowser.Controller.Library;
 16using MediaBrowser.Controller.MediaEncoding;
 17using MediaBrowser.Model.Dto;
 18using MediaBrowser.Model.Entities;
 19using MediaBrowser.Model.IO;
 20using Microsoft.Extensions.Logging;
 21
 22namespace MediaBrowser.MediaEncoding.Attachments
 23{
 24    /// <inheritdoc cref="IAttachmentExtractor"/>
 25    public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
 26    {
 27        private readonly ILogger<AttachmentExtractor> _logger;
 28        private readonly IFileSystem _fileSystem;
 29        private readonly IMediaEncoder _mediaEncoder;
 30        private readonly IMediaSourceManager _mediaSourceManager;
 31        private readonly IPathManager _pathManager;
 32
 233        private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
 234        {
 235            o.PoolSize = 20;
 236            o.PoolInitialFill = 1;
 237        });
 38
 39        /// <summary>
 40        /// Initializes a new instance of the <see cref="AttachmentExtractor"/> class.
 41        /// </summary>
 42        /// <param name="logger">The <see cref="ILogger{AttachmentExtractor}"/>.</param>
 43        /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
 44        /// <param name="mediaEncoder">The <see cref="IMediaEncoder"/>.</param>
 45        /// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/>.</param>
 46        /// <param name="pathManager">The <see cref="IPathManager"/>.</param>
 47        public AttachmentExtractor(
 48            ILogger<AttachmentExtractor> logger,
 49            IFileSystem fileSystem,
 50            IMediaEncoder mediaEncoder,
 51            IMediaSourceManager mediaSourceManager,
 52            IPathManager pathManager)
 53        {
 254            _logger = logger;
 255            _fileSystem = fileSystem;
 256            _mediaEncoder = mediaEncoder;
 257            _mediaSourceManager = mediaSourceManager;
 258            _pathManager = pathManager;
 259        }
 60
 61        /// <inheritdoc />
 62        public async Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(BaseItem item, string mediaSourceId
 63        {
 064            ArgumentNullException.ThrowIfNull(item);
 65
 066            if (string.IsNullOrWhiteSpace(mediaSourceId))
 67            {
 068                throw new ArgumentNullException(nameof(mediaSourceId));
 69            }
 70
 071            var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationTo
 072            var mediaSource = mediaSources
 073                .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
 074            if (mediaSource is null)
 75            {
 076                throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
 77            }
 78
 079            var mediaAttachment = mediaSource.MediaAttachments
 080                .FirstOrDefault(i => i.Index == attachmentStreamIndex);
 081            if (mediaAttachment is null)
 82            {
 083                throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {a
 84            }
 85
 086            if (string.Equals(mediaAttachment.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 87            {
 088                throw new ResourceNotFoundException($"Attachment with stream index {attachmentStreamIndex} can't be extr
 89            }
 90
 091            var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
 092                    .ConfigureAwait(false);
 93
 094            return (mediaAttachment, attachmentStream);
 095        }
 96
 97        /// <inheritdoc />
 98        public async Task ExtractAllAttachments(
 99            string inputFile,
 100            MediaSourceInfo mediaSource,
 101            CancellationToken cancellationToken)
 102        {
 0103            await ExtractAllAttachmentsIndividuallyInternal(
 0104                inputFile,
 0105                mediaSource,
 0106                cancellationToken).ConfigureAwait(false);
 0107        }
 108
 109        private async Task ExtractAllAttachmentsIndividuallyInternal(
 110            string inputFile,
 111            MediaSourceInfo mediaSource,
 112            CancellationToken cancellationToken)
 113        {
 0114            var inputPath = _mediaEncoder.GetInputArgument(inputFile, mediaSource);
 115
 0116            ArgumentException.ThrowIfNullOrEmpty(inputPath);
 117
 0118            var outputFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
 0119            if (outputFolder is null)
 120            {
 0121                _logger.LogDebug("Skipping attachment extraction for input {InputFile}: MediaSource Id is not a GUID.", 
 0122                return;
 123            }
 124
 0125            using (await _semaphoreLocks.LockAsync(outputFolder, cancellationToken).ConfigureAwait(false))
 126            {
 0127                Directory.CreateDirectory(outputFolder);
 128
 0129                var dumpArgs = new StringBuilder();
 0130                var missingPaths = new List<string>();
 0131                foreach (var attachment in mediaSource.MediaAttachments)
 132                {
 0133                    if (string.Equals(attachment.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
 134                    {
 135                        continue;
 136                    }
 137
 0138                    var indexName = attachment.Index.ToString(CultureInfo.InvariantCulture);
 0139                    var attachmentPath = _pathManager.GetAttachmentPath(mediaSource.Id, attachment.FileName ?? indexName
 0140                                         ?? _pathManager.GetAttachmentPath(mediaSource.Id, indexName)!;
 0141                    if (File.Exists(attachmentPath))
 142                    {
 143                        continue;
 144                    }
 145
 0146                    dumpArgs.AppendFormat(
 0147                        CultureInfo.InvariantCulture,
 0148                        "-dump_attachment:{0} \"{1}\" ",
 0149                        attachment.Index,
 0150                        attachmentPath.EscapeProcessArgument());
 0151                    missingPaths.Add(attachmentPath);
 152                }
 153
 0154                if (missingPaths.Count == 0)
 155                {
 156                    // Skip extraction if all files already exist
 0157                    return;
 158                }
 159
 0160                var hasVideoOrAudioStream = mediaSource.MediaStreams
 0161                    .Any(s => s.Type == MediaStreamType.Video || s.Type == MediaStreamType.Audio);
 0162                var processArgs = string.Format(
 0163                    CultureInfo.InvariantCulture,
 0164                    "{0}{1} -i {2} {3}",
 0165                    dumpArgs,
 0166                    inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.E
 0167                    inputPath,
 0168                    hasVideoOrAudioStream ? "-t 0 -f null null" : string.Empty);
 169
 170                int exitCode;
 171
 0172                using (var process = new Process
 0173                {
 0174                    StartInfo = new ProcessStartInfo
 0175                    {
 0176                        Arguments = processArgs,
 0177                        FileName = _mediaEncoder.EncoderPath,
 0178                        UseShellExecute = false,
 0179                        CreateNoWindow = true,
 0180                        WindowStyle = ProcessWindowStyle.Hidden,
 0181                        ErrorDialog = false
 0182                    },
 0183                    EnableRaisingEvents = true
 0184                })
 185                {
 0186                    _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments
 187
 0188                    process.Start();
 189
 190                    try
 191                    {
 0192                        await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
 0193                        exitCode = process.ExitCode;
 0194                    }
 0195                    catch (OperationCanceledException)
 196                    {
 0197                        process.Kill(true);
 0198                        exitCode = -1;
 0199                    }
 0200                }
 201
 0202                var failed = false;
 203
 0204                if (exitCode != 0 && (hasVideoOrAudioStream || exitCode != 1))
 205                {
 0206                    failed = true;
 207
 0208                    foreach (var path in missingPaths)
 209                    {
 0210                        if (!File.Exists(path))
 211                        {
 212                            continue;
 213                        }
 214
 215                        try
 216                        {
 0217                            _fileSystem.DeleteFile(path);
 0218                        }
 0219                        catch (IOException ex)
 220                        {
 0221                            _logger.LogError(ex, "Error deleting extracted attachment {Path}", path);
 0222                        }
 223                    }
 224                }
 225
 0226                if (!failed && missingPaths.Exists(p => !File.Exists(p)))
 227                {
 0228                    failed = true;
 229                }
 230
 0231                if (failed)
 232                {
 0233                    _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, o
 234
 0235                    throw new InvalidOperationException(
 0236                        string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}"
 237                }
 238
 0239                _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPa
 0240            }
 0241        }
 242
 243        private async Task<Stream> GetAttachmentStream(
 244            MediaSourceInfo mediaSource,
 245            MediaAttachment mediaAttachment,
 246            CancellationToken cancellationToken)
 247        {
 0248            var attachmentPath = await ExtractAttachment(mediaSource.Path, mediaSource, mediaAttachment, cancellationTok
 0249                .ConfigureAwait(false);
 0250            return AsyncFile.OpenRead(attachmentPath);
 0251        }
 252
 253        private async Task<string> ExtractAttachment(
 254            string inputFile,
 255            MediaSourceInfo mediaSource,
 256            MediaAttachment mediaAttachment,
 257            CancellationToken cancellationToken)
 258        {
 0259            var attachmentFolderPath = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
 0260            if (attachmentFolderPath is null)
 261            {
 0262                throw new ResourceNotFoundException($"MediaSource {mediaSource.Id} has no attachment cache (non-GUID Id,
 263            }
 264
 0265            using (await _semaphoreLocks.LockAsync(attachmentFolderPath, cancellationToken).ConfigureAwait(false))
 266            {
 0267                var indexName = mediaAttachment.Index.ToString(CultureInfo.InvariantCulture);
 0268                var attachmentPath = _pathManager.GetAttachmentPath(mediaSource.Id, mediaAttachment.FileName ?? indexNam
 0269                                     ?? _pathManager.GetAttachmentPath(mediaSource.Id, indexName)!;
 0270                if (!File.Exists(attachmentPath))
 271                {
 0272                    await ExtractAttachmentInternal(
 0273                        _mediaEncoder.GetInputArgument(inputFile, mediaSource),
 0274                        mediaSource,
 0275                        mediaAttachment.Index,
 0276                        attachmentPath,
 0277                        cancellationToken).ConfigureAwait(false);
 278                }
 279
 0280                return attachmentPath;
 281            }
 0282        }
 283
 284        private async Task ExtractAttachmentInternal(
 285            string inputPath,
 286            MediaSourceInfo mediaSource,
 287            int attachmentStreamIndex,
 288            string outputPath,
 289            CancellationToken cancellationToken)
 290        {
 0291            ArgumentException.ThrowIfNullOrEmpty(inputPath);
 292
 0293            ArgumentException.ThrowIfNullOrEmpty(outputPath);
 294
 0295            Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a 
 296
 0297            var hasVideoOrAudioStream = mediaSource.MediaStreams
 0298                .Any(s => s.Type == MediaStreamType.Video || s.Type == MediaStreamType.Audio);
 0299            var processArgs = string.Format(
 0300                CultureInfo.InvariantCulture,
 0301                "-dump_attachment:{1} \"{2}\" -i {0} {3}",
 0302                inputPath,
 0303                attachmentStreamIndex,
 0304                outputPath.EscapeProcessArgument(),
 0305                hasVideoOrAudioStream ? "-t 0 -f null null" : string.Empty);
 306
 307            int exitCode;
 308
 0309            using (var process = new Process
 0310            {
 0311                StartInfo = new ProcessStartInfo
 0312                {
 0313                    Arguments = processArgs,
 0314                    FileName = _mediaEncoder.EncoderPath,
 0315                    UseShellExecute = false,
 0316                    CreateNoWindow = true,
 0317                    WindowStyle = ProcessWindowStyle.Hidden,
 0318                    ErrorDialog = false
 0319                },
 0320                EnableRaisingEvents = true
 0321            })
 322            {
 0323                _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
 324
 0325                process.Start();
 326
 327                try
 328                {
 0329                    await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
 0330                    exitCode = process.ExitCode;
 0331                }
 0332                catch (OperationCanceledException)
 333                {
 0334                    process.Kill(true);
 0335                    exitCode = -1;
 0336                }
 0337            }
 338
 0339            var failed = false;
 340
 0341            if (exitCode != 0)
 342            {
 0343                if (hasVideoOrAudioStream || exitCode != 1)
 344                {
 0345                    failed = true;
 346
 0347                    _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, ex
 348                    try
 349                    {
 0350                        if (File.Exists(outputPath))
 351                        {
 0352                            _fileSystem.DeleteFile(outputPath);
 353                        }
 0354                    }
 0355                    catch (IOException ex)
 356                    {
 0357                        _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
 0358                    }
 359                }
 360            }
 361
 0362            if (!failed && !File.Exists(outputPath))
 363            {
 0364                failed = true;
 365            }
 366
 0367            if (failed)
 368            {
 0369                _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outpu
 370
 0371                throw new InvalidOperationException(
 0372                    string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", in
 373            }
 374
 0375            _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, 
 0376        }
 377
 378        /// <inheritdoc />
 379        public void Dispose()
 380        {
 2381            _semaphoreLocks.Dispose();
 2382        }
 383    }
 384}