jellyfin/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs

523 lines
19 KiB
C#
Raw Normal View History

#pragma warning disable CS1591
2019-10-18 11:52:32 +00:00
using System;
using System.Collections.Generic;
2020-03-24 15:12:06 +00:00
using System.Diagnostics;
2019-10-18 11:52:32 +00:00
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2024-01-03 15:47:25 +00:00
using AsyncKeyedLock;
using MediaBrowser.Common;
2019-10-18 11:52:32 +00:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.MediaEncoding.Encoder;
2019-10-18 11:52:32 +00:00
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Attachments
{
2024-01-03 15:47:25 +00:00
public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
2019-10-18 11:52:32 +00:00
{
2020-06-06 00:15:56 +00:00
private readonly ILogger<AttachmentExtractor> _logger;
2019-10-18 11:52:32 +00:00
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
private readonly IMediaEncoder _mediaEncoder;
private readonly IMediaSourceManager _mediaSourceManager;
2024-01-03 15:47:25 +00:00
private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
{
o.PoolSize = 20;
o.PoolInitialFill = 1;
});
2019-12-26 22:09:00 +00:00
2019-10-18 11:52:32 +00:00
public AttachmentExtractor(
2019-11-07 16:55:39 +00:00
ILogger<AttachmentExtractor> logger,
2019-10-18 11:52:32 +00:00
IApplicationPaths appPaths,
IFileSystem fileSystem,
IMediaEncoder mediaEncoder,
IMediaSourceManager mediaSourceManager)
2019-10-18 11:52:32 +00:00
{
2019-11-07 16:55:39 +00:00
_logger = logger;
2019-10-18 11:52:32 +00:00
_appPaths = appPaths;
_fileSystem = fileSystem;
_mediaEncoder = mediaEncoder;
_mediaSourceManager = mediaSourceManager;
}
2019-12-26 22:09:00 +00:00
/// <inheritdoc />
2021-12-24 21:18:24 +00:00
public async Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
2019-10-18 11:52:32 +00:00
{
ArgumentNullException.ThrowIfNull(item);
2019-10-18 11:52:32 +00:00
if (string.IsNullOrWhiteSpace(mediaSourceId))
{
throw new ArgumentNullException(nameof(mediaSourceId));
}
2020-01-10 23:08:47 +00:00
var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
var mediaSource = mediaSources
.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
2022-12-05 14:00:20 +00:00
if (mediaSource is null)
{
throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
}
2019-12-26 22:09:00 +00:00
var mediaAttachment = mediaSource.MediaAttachments
.FirstOrDefault(i => i.Index == attachmentStreamIndex);
2022-12-05 14:00:20 +00:00
if (mediaAttachment is null)
{
throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
}
2019-12-26 22:09:00 +00:00
2019-10-18 11:52:32 +00:00
var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
.ConfigureAwait(false);
return (mediaAttachment, attachmentStream);
}
public async Task ExtractAllAttachments(
string inputFile,
MediaSourceInfo mediaSource,
string outputPath,
CancellationToken cancellationToken)
{
2024-01-03 15:47:25 +00:00
using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
2022-03-12 20:46:29 +00:00
{
2022-03-13 10:20:09 +00:00
if (!Directory.Exists(outputPath))
{
await ExtractAllAttachmentsInternal(
_mediaEncoder.GetInputArgument(inputFile, mediaSource),
outputPath,
false,
cancellationToken).ConfigureAwait(false);
}
2022-03-13 10:20:09 +00:00
}
}
public async Task ExtractAllAttachmentsExternal(
string inputArgument,
string id,
string outputPath,
CancellationToken cancellationToken)
{
2024-01-03 15:47:25 +00:00
using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
2022-03-12 20:46:29 +00:00
{
2022-03-13 10:20:09 +00:00
if (!File.Exists(Path.Join(outputPath, id)))
{
await ExtractAllAttachmentsInternal(
inputArgument,
outputPath,
true,
cancellationToken).ConfigureAwait(false);
2022-03-13 10:20:09 +00:00
if (Directory.Exists(outputPath))
{
File.Create(Path.Join(outputPath, id));
}
}
}
}
private async Task ExtractAllAttachmentsInternal(
string inputPath,
string outputPath,
bool isExternal,
CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(inputPath);
ArgumentException.ThrowIfNullOrEmpty(outputPath);
2022-03-12 20:46:29 +00:00
Directory.CreateDirectory(outputPath);
var processArgs = string.Format(
CultureInfo.InvariantCulture,
"-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
inputPath);
int exitCode;
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
Arguments = processArgs,
FileName = _mediaEncoder.EncoderPath,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = outputPath,
ErrorDialog = false
},
EnableRaisingEvents = true
})
{
_logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
process.Start();
try
{
await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
exitCode = process.ExitCode;
}
catch (OperationCanceledException)
{
process.Kill(true);
exitCode = -1;
}
}
var failed = false;
if (exitCode != 0)
{
if (isExternal && exitCode == 1)
{
// ffmpeg returns exitCode 1 because there is no video or audio stream
// this can be ignored
}
else
{
failed = true;
_logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
try
{
Directory.Delete(outputPath);
}
catch (IOException ex)
{
_logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
}
}
}
else if (!Directory.Exists(outputPath))
{
failed = true;
}
if (failed)
{
_logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
}
2023-04-06 17:38:34 +00:00
_logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
}
2019-10-18 11:52:32 +00:00
private async Task<Stream> GetAttachmentStream(
MediaSourceInfo mediaSource,
MediaAttachment mediaAttachment,
CancellationToken cancellationToken)
{
var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
return AsyncFile.OpenRead(attachmentPath);
2019-10-18 11:52:32 +00:00
}
2019-12-26 22:09:00 +00:00
private async Task<string> GetReadableFile(
2019-10-18 11:52:32 +00:00
string mediaPath,
2019-12-26 22:09:00 +00:00
string inputFile,
MediaSourceInfo mediaSource,
2019-10-18 11:52:32 +00:00
MediaAttachment mediaAttachment,
CancellationToken cancellationToken)
{
await CacheAllAttachments(mediaPath, inputFile, mediaSource, cancellationToken).ConfigureAwait(false);
var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
2019-10-18 11:52:32 +00:00
.ConfigureAwait(false);
return outputPath;
2019-10-18 11:52:32 +00:00
}
private async Task CacheAllAttachments(
string mediaPath,
string inputFile,
MediaSourceInfo mediaSource,
CancellationToken cancellationToken)
{
2024-05-06 01:21:54 +00:00
var outputFileLocks = new List<IDisposable>();
var extractableAttachmentIds = new List<int>();
try
{
foreach (var attachment in mediaSource.MediaAttachments)
{
var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachment.Index);
2024-05-06 01:21:54 +00:00
var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false);
if (File.Exists(outputPath))
{
2024-05-06 01:21:54 +00:00
releaser.Dispose();
continue;
}
2024-05-06 01:21:54 +00:00
outputFileLocks.Add(releaser);
extractableAttachmentIds.Add(attachment.Index);
}
if (extractableAttachmentIds.Count > 0)
{
await CacheAllAttachmentsInternal(mediaPath, inputFile, mediaSource, extractableAttachmentIds, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Unable to cache media attachments for File:{File}", mediaPath);
}
finally
{
2024-05-06 01:21:54 +00:00
outputFileLocks.ForEach(x => x.Dispose());
}
}
private async Task CacheAllAttachmentsInternal(
string mediaPath,
string inputFile,
MediaSourceInfo mediaSource,
List<int> extractableAttachmentIds,
CancellationToken cancellationToken)
{
var outputPaths = new List<string>();
var processArgs = string.Empty;
foreach (var attachmentId in extractableAttachmentIds)
{
var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachmentId);
Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
outputPaths.Add(outputPath);
processArgs += string.Format(
CultureInfo.InvariantCulture,
" -dump_attachment:{0} \"{1}\"",
attachmentId,
EncodingUtils.NormalizePath(outputPath));
}
processArgs += string.Format(
CultureInfo.InvariantCulture,
" -i \"{0}\" -t 0 -f null null",
inputFile);
int exitCode;
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
Arguments = processArgs,
FileName = _mediaEncoder.EncoderPath,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false
},
EnableRaisingEvents = true
})
{
_logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
process.Start();
try
{
await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
exitCode = process.ExitCode;
}
catch (OperationCanceledException)
{
process.Kill(true);
exitCode = -1;
}
}
var failed = false;
if (exitCode == -1)
{
failed = true;
foreach (var outputPath in outputPaths)
{
try
{
_logger.LogWarning("Deleting extracted media attachment due to failure: {Path}", outputPath);
_fileSystem.DeleteFile(outputPath);
}
catch (FileNotFoundException)
{
// ffmpeg failed, so it is normal that one or more expected output files do not exist.
// There is no need to log anything for the user here.
}
catch (IOException ex)
{
_logger.LogError(ex, "Error deleting extracted media attachment {Path}", outputPath);
}
}
}
else
{
foreach (var outputPath in outputPaths)
{
if (!File.Exists(outputPath))
{
_logger.LogError("ffmpeg media attachment extraction failed for {InputPath} to {OutputPath}", inputFile, outputPath);
failed = true;
continue;
}
_logger.LogInformation("ffmpeg media attachment extraction completed for {InputPath} to {OutputPath}", inputFile, outputPath);
}
}
if (failed)
{
throw new FfmpegException(
string.Format(CultureInfo.InvariantCulture, "ffmpeg media attachment extraction failed for {0}", inputFile));
}
}
2019-10-18 11:52:32 +00:00
private async Task ExtractAttachment(
2019-12-26 22:09:00 +00:00
string inputFile,
MediaSourceInfo mediaSource,
2019-10-18 11:52:32 +00:00
int attachmentStreamIndex,
string outputPath,
CancellationToken cancellationToken)
{
2024-01-03 15:47:25 +00:00
using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
2019-10-18 11:52:32 +00:00
{
if (!File.Exists(outputPath))
{
2019-12-26 22:09:00 +00:00
await ExtractAttachmentInternal(
_mediaEncoder.GetInputArgument(inputFile, mediaSource),
2019-12-26 22:09:00 +00:00
attachmentStreamIndex,
outputPath,
cancellationToken).ConfigureAwait(false);
2019-10-18 11:52:32 +00:00
}
}
}
private async Task ExtractAttachmentInternal(
string inputPath,
int attachmentStreamIndex,
string outputPath,
CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(inputPath);
2019-10-18 11:52:32 +00:00
ArgumentException.ThrowIfNullOrEmpty(outputPath);
2019-10-18 11:52:32 +00:00
Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
2019-10-18 11:52:32 +00:00
var processArgs = string.Format(
CultureInfo.InvariantCulture,
"-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
inputPath,
attachmentStreamIndex,
EncodingUtils.NormalizePath(outputPath));
2019-10-18 11:52:32 +00:00
int exitCode;
2019-10-18 11:52:32 +00:00
using (var process = new Process
{
2020-04-11 17:46:31 +00:00
StartInfo = new ProcessStartInfo
{
Arguments = processArgs,
FileName = _mediaEncoder.EncoderPath,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false
},
EnableRaisingEvents = true
})
{
_logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
2019-10-18 11:52:32 +00:00
process.Start();
2019-10-18 11:52:32 +00:00
try
2019-10-18 11:52:32 +00:00
{
await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
exitCode = process.ExitCode;
}
catch (OperationCanceledException)
{
process.Kill(true);
exitCode = -1;
2019-10-18 11:52:32 +00:00
}
}
2020-01-10 23:08:47 +00:00
2019-10-18 11:52:32 +00:00
var failed = false;
if (exitCode != 0)
2019-10-18 11:52:32 +00:00
{
failed = true;
2019-11-04 16:16:57 +00:00
_logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
2019-10-18 11:52:32 +00:00
try
{
if (File.Exists(outputPath))
{
_fileSystem.DeleteFile(outputPath);
}
2019-10-18 11:52:32 +00:00
}
catch (IOException ex)
{
_logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
}
}
else if (!File.Exists(outputPath))
{
failed = true;
}
if (failed)
{
2021-11-09 21:29:33 +00:00
_logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
2019-10-18 11:52:32 +00:00
2021-11-09 21:29:33 +00:00
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
2019-10-18 11:52:32 +00:00
}
2023-04-06 17:38:34 +00:00
_logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
2019-10-18 11:52:32 +00:00
}
private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
2019-10-18 11:52:32 +00:00
{
string filename;
if (mediaSource.Protocol == MediaProtocol.File)
2019-10-18 11:52:32 +00:00
{
var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
2019-10-18 11:52:32 +00:00
}
else
{
filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
2019-10-18 11:52:32 +00:00
}
2019-12-26 22:09:00 +00:00
var prefix = filename.AsSpan(0, 1);
return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
2019-12-26 22:09:00 +00:00
}
2024-01-03 15:47:25 +00:00
/// <inheritdoc />
public void Dispose()
{
_semaphoreLocks.Dispose();
}
2019-10-18 11:52:32 +00:00
}
}