feat(video): managed encoder provider for MJPEG-AVI, image sequences, GIF and APNG

Sessions write to a temporary file or folder that Complete renames into
place and Dispose deletes; constant-rate outputs repeat held frames.
Adds AVI/GIF/APNG readers used to verify rendered outputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:42:05 +00:00
1 parent 33d7284c25
commit b3801961aa
4 files changed
+934

No files matched your search

@@ -0,0 +1,64 @@
namespace Titano.Core.Video.Managed;
/// <summary>
/// The encoders every platform has (BRIEF §11.3): MJPEG in AVI, JPEG / PNG (8 or 16-bit) / TIFF-16 / linear DNG image
/// sequences, animated GIF and APNG, all written by the in-house codecs. Frames are linear-light buffers at the output
/// size. Single files are written to a temporary sibling and renamed on <see cref="IVideoEncoderSession.Complete"/>;
/// sequences go to a temporary folder renamed the same way, so a cancelled or failed encode leaves nothing behind.
/// AVI and image sequences are constant frame rate: a frame lasting several periods is repeated.
/// </summary>
public sealed class ManagedEncoderProvider : IVideoEncoderProvider
{
public const string ProviderName = "managed";
/// <summary>Largest width or height of any managed output (JPEG, GIF and AVI headers use 16-bit sizes).</summary>
public const int MaxDimension = 65535;
public string Name => ProviderName;
public IReadOnlyList<EncoderCapability> Capabilities { get; } =
[
new(VideoCodec.Mjpeg, "Managed MJPEG", false, MaxDimension, MaxDimension, false),
new(VideoCodec.JpegSequence, "Managed JPEG sequence", false, MaxDimension, MaxDimension, false),
new(VideoCodec.PngSequence, "Managed PNG sequence", false, MaxDimension, MaxDimension, true),
new(VideoCodec.Tiff16Sequence, "Managed TIFF sequence", false, MaxDimension, MaxDimension, true),
new(VideoCodec.LinearDngSequence, "Managed linear DNG sequence", false, MaxDimension, MaxDimension, true),
new(VideoCodec.Gif, "Managed GIF", false, MaxDimension, MaxDimension, false),
new(VideoCodec.Apng, "Managed APNG", false, MaxDimension, MaxDimension, false),
];
/// <summary>Bit depths each managed codec writes.</summary>
public static IReadOnlyList<int> BitDepths(VideoCodec codec) => codec switch
{
VideoCodec.PngSequence => [8, 16],
VideoCodec.Tiff16Sequence => [16, 8],
VideoCodec.LinearDngSequence => [16],
VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif or VideoCodec.Apng => [8],
_ => [],
};
public bool CanEncode(EncodeSettings settings) => Problem(settings) is null;
public IVideoEncoderSession Open(EncodeSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
if (Problem(settings) is { } problem) throw new NotSupportedException(problem);
var name = Capabilities.First(c => c.Codec == settings.Codec).Name;
return settings.Codec switch
{
VideoCodec.Mjpeg => new AviMjpegSession(settings, name),
VideoCodec.Gif => new GifSession(settings, name),
VideoCodec.Apng => new ApngSession(settings, name),
_ => new ImageSequenceSession(settings, name),
};
}
private static string? Problem(EncodeSettings s)
{
if (!VideoCodecInfo.IsManaged(s.Codec)) return $"{s.Codec} needs a platform encoder";
if (s.Width is <= 0 or > MaxDimension || s.Height is <= 0 or > MaxDimension) return $"{s.Width}×{s.Height} is outside 1–{MaxDimension}";
if (s.FrameRate.Numerator <= 0 || s.FrameRate.Denominator <= 0) return "The frame rate must be positive";
if (!BitDepths(s.Codec).Contains(s.BitDepth)) return $"{s.Codec} cannot be written with {s.BitDepth}-bit samples";
return string.IsNullOrWhiteSpace(s.OutputPath) ? "No output path" : null;
}
}
@@ -0,0 +1,270 @@
using System.IO.Compression;
using Titano.Core.Codecs.Apng;
using Titano.Core.Codecs.Dng;
using Titano.Core.Codecs.Gif;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Png;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Diagnostics;
using Titano.Core.Imaging;
using Titano.Core.IO;
using Titano.Core.Video.Avi;
namespace Titano.Core.Video.Managed;
/// <summary>Lifecycle shared by the managed sessions: validation, completion, and deletion of partial output on dispose.</summary>
internal abstract class ManagedSession(EncodeSettings settings, string encoderName) : IVideoEncoderSession
{
protected const string LogCategory = "ManagedEncoder";
private bool _completed;
private bool _disposed;
private int _frames;
public string EncoderName { get; } = encoderName;
public bool IsHardware => false;
protected EncodeSettings Settings { get; } = settings;
public void WriteFrame(ImageBuffer frame, long duration90k)
{
ArgumentNullException.ThrowIfNull(frame);
ObjectDisposedException.ThrowIf(_disposed, this);
if (_completed) throw new InvalidOperationException("The session is complete");
if (frame.Width != Settings.Width || frame.Height != Settings.Height) throw new ArgumentException("Frame size differs from the encode size", nameof(frame));
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration90k);
Write(frame, duration90k);
_frames++;
}
public void Complete()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_completed) throw new InvalidOperationException("The session is already complete");
if (_frames == 0) throw new InvalidOperationException("No frames were written");
Commit();
_completed = true;
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
if (!_completed) Discard();
}
protected abstract void Write(ImageBuffer frame, long duration90k);
/// <summary>Finishes the container and moves it to <see cref="EncodeSettings.OutputPath"/>.</summary>
protected abstract void Commit();
/// <summary>Closes and deletes everything written so far.</summary>
protected abstract void Discard();
protected static JpegEncodeOptions JpegOptions(int quality) => new()
{
Quality = int.Clamp(quality, 1, 100),
Subsampling = quality >= 90 ? JpegSubsampling.Yuv444 : JpegSubsampling.Yuv420,
OptimizeHuffman = true,
};
}
/// <summary>Maps variable frame durations onto a constant-rate grid: a frame is repeated for every period it covers
/// (rounded on the cumulative timeline, so the total stays exact).</summary>
internal sealed class ConstantRateClock(Rational frameRate)
{
private long _ticks;
private long _periods;
/// <summary>Periods the next frame of <paramref name="duration90k"/> ticks occupies (0 when it is shorter than the grid allows).</summary>
public int Advance(long duration90k)
{
_ticks += duration90k;
var end = (_ticks * frameRate.Numerator * 2 + 90000L * frameRate.Denominator) / (2 * 90000L * frameRate.Denominator);
var periods = (int)(end - _periods);
_periods = end;
return periods;
}
}
/// <summary>A single output file written to a temporary sibling and renamed into place.</summary>
internal abstract class SingleFileSession : ManagedSession
{
private readonly string _tempPath;
protected SingleFileSession(EncodeSettings settings, string encoderName) : base(settings, encoderName)
{
_tempPath = AtomicFile.TempPathFor(settings.OutputPath);
File = new FileStream(_tempPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 1 << 20);
}
protected FileStream File { get; }
protected abstract void Finish();
protected override void Commit()
{
Finish();
File.Flush(flushToDisk: true);
File.Dispose();
AtomicFile.Commit(_tempPath, Settings.OutputPath);
}
protected override void Discard()
{
File.Dispose();
try
{
System.IO.File.Delete(_tempPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning(LogCategory, "Could not delete the partial output " + _tempPath, ex);
}
}
}
internal sealed class AviMjpegSession : SingleFileSession
{
private readonly AviMjpegWriter _writer;
private readonly ConstantRateClock _clock;
private readonly JpegEncodeOptions _jpeg;
public AviMjpegSession(EncodeSettings settings, string encoderName) : base(settings, encoderName)
{
try
{
_writer = new AviMjpegWriter(File, settings.Width, settings.Height, settings.FrameRate);
}
catch
{
Discard();
throw;
}
_clock = new ConstantRateClock(settings.FrameRate);
_jpeg = JpegOptions(settings.Quality);
}
protected override void Write(ImageBuffer frame, long duration90k)
{
var repeats = _clock.Advance(duration90k);
if (repeats == 0) return;
var jpeg = JpegEncoder.Encode(frame, _jpeg);
for (var i = 0; i < repeats; i++) _writer.WriteFrame(jpeg);
}
protected override void Finish() => _writer.Complete();
}
internal sealed class GifSession : SingleFileSession
{
private readonly GifEncoder _encoder;
public GifSession(EncodeSettings settings, string encoderName) : base(settings, encoderName)
{
try
{
_encoder = new GifEncoder(File, settings.Width, settings.Height);
}
catch
{
Discard();
throw;
}
}
protected override void Write(ImageBuffer frame, long duration90k) => _encoder.AddFrame(frame, duration90k);
protected override void Finish() => _encoder.Complete();
}
internal sealed class ApngSession : SingleFileSession
{
private readonly ApngEncoder _encoder;
public ApngSession(EncodeSettings settings, string encoderName) : base(settings, encoderName)
{
try
{
_encoder = new ApngEncoder(File, settings.Width, settings.Height, new ApngEncoderOptions { CompressionLevel = CompressionLevel.Optimal });
}
catch
{
Discard();
throw;
}
}
protected override void Write(ImageBuffer frame, long duration90k) => _encoder.AddFrame(frame, duration90k);
protected override void Finish() => _encoder.Complete();
}
/// <summary>
/// Numbered image files (<c>&lt;folder name&gt;_000001.ext</c>, 1-based, six digits) in the output folder. Files are written
/// (and flushed) into a hidden temporary sibling folder that is renamed to the output folder on completion.
/// </summary>
internal sealed class ImageSequenceSession : ManagedSession
{
private readonly string _folder;
private readonly string _temp;
private readonly string _stem;
private readonly string _extension;
private readonly ConstantRateClock _clock;
private int _index;
public ImageSequenceSession(EncodeSettings settings, string encoderName) : base(settings, encoderName)
{
_folder = Path.GetFullPath(settings.OutputPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (Directory.Exists(_folder) || System.IO.File.Exists(_folder)) throw new IOException($"The output \"{_folder}\" already exists");
var parent = Path.GetDirectoryName(_folder) ?? throw new ArgumentException("The output folder needs a parent", nameof(settings));
_stem = Path.GetFileName(_folder);
_extension = VideoCodecInfo.FileExtension(settings.Codec);
Directory.CreateDirectory(parent);
_temp = Path.Combine(parent, "." + _stem + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp");
Directory.CreateDirectory(_temp);
_clock = new ConstantRateClock(settings.FrameRate);
}
/// <summary>File name of the 1-based frame <paramref name="number"/> inside a sequence folder named <paramref name="stem"/>.</summary>
public static string FrameName(string stem, int number, string extension) =>
string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem}_{number:D6}{extension}");
protected override void Write(ImageBuffer frame, long duration90k)
{
var repeats = _clock.Advance(duration90k);
if (repeats == 0) return;
var bytes = Encode(frame);
for (var i = 0; i < repeats; i++)
{
_index++;
using var file = new FileStream(Path.Combine(_temp, FrameName(_stem, _index, _extension)), FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16);
file.Write(bytes);
file.Flush(flushToDisk: true);
}
}
protected override void Commit() => Directory.Move(_temp, _folder);
protected override void Discard()
{
try
{
Directory.Delete(_temp, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning(LogCategory, "Could not delete the partial sequence " + _temp, ex);
}
}
private byte[] Encode(ImageBuffer frame) => Settings.Codec switch
{
VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality)),
VideoCodec.PngSequence => PngEncoder.Encode(frame, Settings.BitDepth == 16 ? 16 : 8, CompressionLevel.Optimal),
VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16 }),
VideoCodec.LinearDngSequence => LinearDngWriter.Write(frame),
_ => throw new NotSupportedException($"{Settings.Codec} is not an image sequence"),
};
}