Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Change the playback speed of animations when converting (#158)
KnifeLemon5188bb9cac5f
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 36e232b3..bbaf0c89 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -106,6 +106,16 @@ pinned source in `build/build-linux-native.py` like rhwp (PR #113 did this for S- **Animations.** An animated GIF, WebP, APNG or MNG keeps every frame and its timing when converted to one of these(animated GIF ↔ animated WebP ↔ APNG ↔ MNG, WebP lossy or lossless as the preset says) and becomes a multi-page TIFF;other targets get the first frame. Multi-page TIFFs and PDFs stay one image per page in WebP.+- **Playback speed** (preset option *Playback speed*, `ImageOptions.AnimationSpeed`: 0.25×, 0.5×, 0.75×, 1×, 1.5×,+ 2×, 4×; shown for GIF, WebP, APNG, MNG and "same as source") rewrites the frame delays of an animation that stays+ animated (`Magick/AnimationTiming.cs`). Delays are divided by the speed in the target's own units (hundredths of a+ second for GIF and MNG, milliseconds for WebP and APNG) and rounded on the running total, so the whole animation+ keeps its new length. Players show a frame of 10 ms or less for 100 ms, so no delay goes below 20 ms (50 frames a+ second): a frame that would start sooner than that after the one before is dropped and its time goes to that one,+ which leaves frames out evenly. Source delays of 10 ms or less count as the 100 ms players show. Loop count and+ disposal stay; 1× (also every preset saved before the option) leaves the timing untouched. Video → GIF / APNG+ (FFmpeg) puts `setpts=PTS/<speed>` before the `fps` filter, so the frame rate limits stay. The speed changes only in+ the step that writes the output (`JobQueue`), never twice on a longer route.- **APNG** (`Magick/Apng.cs`) is Filee's own code, written from the APNG specification: ImageMagick reads only anAPNG's default image and writes APNG through an external FFmpeg. Every frame is an ordinary PNG decoded or encoded byImageMagick; Filee handles the chunks around them.@@ -929,8 +939,8 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on| OGV | Theora + Vorbis || DV | DV25 with the same NTSC/PAL frames as VOB, 48 kHz stereo PCM || MXF | OP1a with long-GOP MPEG-2 + 48 kHz PCM |- | GIF | two passes: palettegen over the whole clip, then paletteuse; 15/12/10 fps and at most 640/480/320 px wide (High/Balanced/Small) |- | APNG | one pass with the `apng` encoder (24-bit RGB, mixed prediction) and muxer, looping; the same frame rates and widths as GIF |+ | GIF | two passes: palettegen over the whole clip, then paletteuse; 15/12/10 fps and at most 640/480/320 px wide (High/Balanced/Small); *Playback speed* adds `setpts=PTS/<speed>` before the frame rate |+ | APNG | one pass with the `apng` encoder (24-bit RGB, mixed prediction) and muxer, looping; the same frame rates, widths and playback speed as GIF || MP4, M4V, MKV with *Video codec* HEVC · MOV with HEVC | x265 (preset medium, `hvc1` tag in MP4/M4V/MOV) + AAC || MP4, M4V, MKV, WEBM with *Video codec* AV1 | SVT-AV1 (preset 8), or libaom-av1 (cpu-used 6, row multithreading) with an FFmpeg that lacks SVT-AV1 || MP3 · M4A/M4B · AAC · OGG · OPUS · WEBA · MKA · WMA · MP2 · AC3 · E-AC3 · AMR | LAME VBR (V0/V2/V5) or CBR · AAC, or ALAC with *Audio codec* ALAC · AAC (ADTS) · Vorbis · Opus · Opus · Opus · WMA 2 · MP2 · AC-3 · E-AC-3 · AMR-NB 12.2k (8 kHz mono) |diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.csindex 5edecdae..2ecb659a 100644--- a/src/Filee.Core/Conversion/JobQueue.cs+++ b/src/Filee.Core/Conversion/JobQueue.cs@@ -398,6 +398,10 @@ public sealed class JobQueue : IAsyncDisposable// Turned once, in step turnAt: every other step gets the preset without rotation and flip,// also one before it whose engine applies image options but doesn't say it turns.var preset = s == turnAt ? job.Preset : unturned;+ // Playback speed changes once, in the step that writes the output: an animation passed from one+ // engine to another would otherwise change speed in both.+ if (preset.Image.ChangesSpeed && !(isLast && finalOutput))+ preset = AtOriginalSpeed(preset);var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir, step.FrameSequence,key => file.NoticeKey = key);outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct));@@ -446,6 +450,13 @@ public sealed class JobQueue : IAsyncDisposablereturn copy;}+ static Preset AtOriginalSpeed(Preset preset)+ {+ var copy = preset.Clone();+ copy.Image.AnimationSpeed = 1;+ return copy;+ }+IReadOnlyList<string> Fail(FileResult f, string key, string? detail){f.State = FileState.Failed;diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.csindex 305d9b27..987a8f14 100644--- a/src/Filee.Core/Presets/Preset.cs+++ b/src/Filee.Core/Presets/Preset.cs@@ -270,6 +270,26 @@ public sealed class ImageOptions/// <summary>Icon sizes embedded in an ICO file.</summary>public List<int> IcoSizes { get; set; } = [256, 128, 64, 48, 32, 16];+ /// <summary>The playback speeds the preset editor offers (<see cref="AnimationSpeed"/>).</summary>+ public static readonly double[] AnimationSpeeds = [0.25, 0.5, 0.75, 1, 1.5, 2, 4];++ /// <summary>+ /// Plays an animation (GIF, WebP, APNG, MNG; video → GIF or APNG) this many times as fast: 2 halves every frame+ /// delay, 0.5 doubles it. 1 (the default, also for presets saved before the option) leaves the timing as it is.+ /// </summary>+ public double AnimationSpeed { get; set; } = 1;++ /// <summary>+ /// <see cref="AnimationSpeed"/> as the engines use it: between 0.1 and 10, and 1 for a value that makes no sense+ /// (zero, negative; a hand-edited preset file).+ /// </summary>+ [JsonIgnore]+ public double PlaybackSpeed => double.IsFinite(AnimationSpeed) && AnimationSpeed > 0 ? Math.Clamp(AnimationSpeed, 0.1, 10) : 1;++ /// <summary>True when animations are played faster or slower than they were made (<see cref="PlaybackSpeed"/>).</summary>+ [JsonIgnore]+ public bool ChangesSpeed => PlaybackSpeed != 1;+public ImageOptions Clone(){var copy = (ImageOptions)MemberwiseClone();diff --git a/src/Filee.Engines/Magick/AnimationTiming.cs b/src/Filee.Engines/Magick/AnimationTiming.csnew file mode 100644index 00000000..4b18db45--- /dev/null+++ b/src/Filee.Engines/Magick/AnimationTiming.cs@@ -0,0 +1,78 @@+// Playback speed of animations (preset option ImageOptions.AnimationSpeed): rewrites the frame delays of an animation+// written as GIF, WebP, APNG or MNG, and drops frames where a delay would get shorter than players show it.++using ImageMagick;++namespace Filee.Engines.Magick;++/// <summary>Plays animation frames faster or slower by changing their delays.</summary>+internal static class AnimationTiming+{+ /// <summary>+ /// Shortest delay written, in milliseconds (2 hundredths of a second, 50 frames a second). Browsers show a frame+ /// that asks for 10 ms or less for 100 ms (GIF, APNG and WebP alike), so a shorter delay would play slower, not faster.+ /// </summary>+ public const int MinDelayMs = 20;++ /// <summary>How long players show a frame whose delay is 10 ms or less (<see cref="MinDelayMs"/>).</summary>+ private const int ShortDelayShownMs = 100;++ /// <summary>The largest delay GIF and MNG store (16 bits of hundredths of a second, about 11 minutes).</summary>+ private const int MaxHundredths = ushort.MaxValue;++ /// <summary>The ticks per second delays are written in: hundredths for GIF and MNG, milliseconds for WebP and APNG.</summary>+ public static int TicksPerSecond(string targetFormat) => targetFormat is "webp" or "apng" ? 1000 : 100;++ /// <summary>+ /// The frames to write, playing <paramref name="speed"/> times as fast: every delay divided by+ /// <paramref name="speed"/> in the units of <paramref name="targetFormat"/>, rounded on the running total so the+ /// whole animation keeps its new length. A frame that would start less than <see cref="MinDelayMs"/> after the one+ /// before is dropped (its time goes to the frame before it): fast animations sped up lose frames evenly instead of+ /// getting delays that players would stretch to 100 ms. Delays of 10 ms or less count as the 100 ms players show+ /// them for. Loop count and disposal of the frames stay as they were.+ /// </summary>+ /// <param name="frames">Coalesced frames (every frame a whole picture), so any of them can be dropped.</param>+ public static List<IMagickImage<byte>> ChangeSpeed(IReadOnlyList<IMagickImage<byte>> frames, double speed, string targetFormat)+ {+ if (frames.Count < 2 || !double.IsFinite(speed) || speed <= 0 || speed == 1)+ return [.. frames];++ var ticks = TicksPerSecond(targetFormat);+ var minTicks = MinDelayMs * ticks / 1000;+ var starts = new double[frames.Count + 1];+ for (var i = 0; i < frames.Count; i++)+ starts[i + 1] = starts[i] + DelayMs(frames[i]) * ticks / 1000.0 / speed;++ var kept = new List<(int Index, long Start)>();+ for (var i = 0; i < frames.Count; i++)+ {+ var start = (long)Math.Round(starts[i], MidpointRounding.AwayFromZero);+ if (kept.Count == 0 || start - kept[^1].Start >= minTicks)+ kept.Add((i, start));+ }+ var end = (long)Math.Round(starts[^1], MidpointRounding.AwayFromZero);+ // The last frame needs its time too: when it is too short, the frame before it stays up until the end instead.+ if (kept.Count > 1 && end - kept[^1].Start < minTicks)+ kept.RemoveAt(kept.Count - 1);++ var result = new List<IMagickImage<byte>>(kept.Count);+ for (var k = 0; k < kept.Count; k++)+ {+ var frame = frames[kept[k].Index];+ var next = k + 1 < kept.Count ? kept[k + 1].Start : end;+ var delay = Math.Max(minTicks, next - kept[k].Start);+ frame.AnimationTicksPerSecond = ticks;+ frame.AnimationDelay = (uint)(ticks == 100 ? Math.Min(delay, MaxHundredths) : Math.Min(delay, int.MaxValue));+ result.Add(frame);+ }+ return result;+ }++ /// <summary>A frame's delay in milliseconds as players show it.</summary>+ private static double DelayMs(IMagickImage<byte> frame)+ {+ var ticks = frame.AnimationTicksPerSecond > 0 ? frame.AnimationTicksPerSecond : 100;+ var ms = frame.AnimationDelay * 1000.0 / ticks;+ return ms <= 10 ? ShortDelayShownMs : ms;+ }+}diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.csindex 7085d339..77e1acc8 100644--- a/src/Filee.Engines/Magick/MagickImageConverter.cs+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs@@ -75,7 +75,11 @@ public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransfcancellationToken.ThrowIfCancellationRequested();progress?.Report(0.3);+ var animation = ImageEncoder.KeepsAnimation(from, step.To);var frames = ImageEncoder.SelectFrames(images, from, step.To);+ // Before the options: frames dropped for speed aren't resized for nothing.+ if (animation && step.Preset.Image.ChangesSpeed)+ frames = AnimationTiming.ChangeSpeed(frames, step.Preset.Image.PlaybackSpeed, step.To);foreach (var frame in frames){cancellationToken.ThrowIfCancellationRequested();@@ -83,8 +87,7 @@ public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransf}progress?.Report(0.7);- var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath,- ImageEncoder.KeepsAnimation(from, step.To));+ var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath, animation);progress?.Report(1);return written;}, cancellationToken);diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.csindex 029416ca..4a51d87f 100644--- a/src/Filee.Engines/Media/FfmpegConverter.cs+++ b/src/Filee.Engines/Media/FfmpegConverter.cs@@ -140,12 +140,15 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter: await HardwareProbe.SelectAsync(ffmpeg, codec, tenBit, encoders, _logger, cancellationToken);}+ // Video → animated GIF / APNG can play faster or slower (the image options' playback speed).+ var speed = step.To is "gif" or "apng" ? step.Preset.Image.PlaybackSpeed : 1;IReadOnlyList<FfmpegPass> Plan(HardwareEncoder? encoder) => still? MediaEncoding.PlanStill(input, output, step.To, media, info)- : MediaEncoding.Plan(input, output, step.To, media, info, step.WorkDirectory, cover, encoders, encoder);+ : MediaEncoding.Plan(input, output, step.To, media, info, step.WorkDirectory, cover, encoders, encoder, speed);// Throws for a missing stream before anything is written (an existing file of that name stays untouched).var passes = Plan(hardware);- var duration = still ? MediaEncoding.StillDuration : info.Duration;+ // FFmpeg reports the position in the output, which a speed change makes longer or shorter.+ var duration = still ? MediaEncoding.StillDuration : info.Duration / speed;try{await RunWithFallbackAsync(passes, hardware, Plan,diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.csindex c4f949bd..9336056f 100644--- a/src/Filee.Engines/Media/MediaEncoding.cs+++ b/src/Filee.Engines/Media/MediaEncoding.cs@@ -145,14 +145,15 @@ internal static class MediaEncoding/// The hardware encoder that passed its probe for <see cref="HardwareCodec"/> of this file; null encodes with x264 //// x265 (also the retry after a hardware encode failed)./// </param>+ /// <param name="animationSpeed">Playback speed of an animated GIF or APNG (ImageOptions.PlaybackSpeed); 1 keeps the video's.</param>/// <exception cref="InvalidOperationException">The file lacks the stream the target needs (e.g. no audio track).</exception>public static IReadOnlyList<FfmpegPass> Plan(string input, string output, string target, MediaOptions options, MediaInfo info, string workDirectory,- CoverExtras? cover = null, IReadOnlySet<string>? encoders = null, HardwareEncoder? hardware = null)+ CoverExtras? cover = null, IReadOnlySet<string>? encoders = null, HardwareEncoder? hardware = null, double animationSpeed = 1){if (target == "gif")- return AnimatedGif(input, output, options, info, workDirectory);+ return AnimatedGif(input, output, options, info, workDirectory, animationSpeed);if (target == "apng")- return [new FfmpegPass(AnimatedPng(input, output, options, info), 1)];+ return [new FfmpegPass(AnimatedPng(input, output, options, info, animationSpeed), 1)];if (target == "png")return [new FfmpegPass(PosterFrame(input, output, info), 1)];if (VideoTargets.TryGetValue(target, out var video))@@ -702,11 +703,11 @@ internal static class MediaEncoding/// the palette in the same run would keep every frame in memory until the end. Frame rate and width are limited/// by the quality setting because GIF stores every frame uncompressed-ish and grows fast./// </summary>- private static List<FfmpegPass> AnimatedGif(string input, string output, MediaOptions options, MediaInfo info, string workDirectory)+ private static List<FfmpegPass> AnimatedGif(string input, string output, MediaOptions options, MediaInfo info, string workDirectory, double speed){var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");var quality = options.Quality;- var chain = GifFrames(video, options.MaxHeight, fps: Choose(quality, 15, 12, 10), maxWidth: Choose(quality, 640, 480, 320));+ var chain = GifFrames(video, options.MaxHeight, fps: Choose(quality, 15, 12, 10), maxWidth: Choose(quality, 640, 480, 320), speed);var palette = Path.Combine(workDirectory, $"palette-{Guid.NewGuid():N}.png");var colors = Choose(quality, 256, 256, 128);// Error diffusion looks best; ordered (Bayer) dithering compresses much better because it does not flicker.@@ -734,11 +735,11 @@ internal static class MediaEncoding/// Animated PNG with FFmpeg's APNG encoder and muxer: full colour (24-bit RGB, no palette pass), looping, with the/// frame rate and width limits of GIF, since every frame is stored losslessly./// </summary>- private static List<string> AnimatedPng(string input, string output, MediaOptions options, MediaInfo info)+ private static List<string> AnimatedPng(string input, string output, MediaOptions options, MediaInfo info, double speed){var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");var quality = options.Quality;- var chain = GifFrames(video, options.MaxHeight, fps: Choose(quality, 15, 12, 10), maxWidth: Choose(quality, 640, 480, 320));+ var chain = GifFrames(video, options.MaxHeight, fps: Choose(quality, 15, 12, 10), maxWidth: Choose(quality, 640, 480, 320), speed);return[.. Common, "-i", input, "-map", "0:V:0", "-vf", chain, "-an",@@ -746,11 +747,18 @@ internal static class MediaEncoding];}- /// <summary>Frame rate, square pixels and size of the GIF frames (never upscaled).</summary>- private static string GifFrames(VideoStreamInfo video, int maxHeight, int fps, int maxWidth)+ /// <summary>+ /// Playback speed, frame rate, square pixels and size of the GIF frames (never upscaled). The speed changes the+ /// timestamps before the frame rate is taken, so a faster clip keeps the frame rate by leaving frames out, and a+ /// slower one repeats frames where the video has too few.+ /// </summary>+ private static string GifFrames(VideoStreamInfo video, int maxHeight, int fps, int maxWidth, double speed){var height = maxHeight > 0 ? $"'min(ih,{Math.Max(16, maxHeight)})'" : "ih";- return $"fps={fps},{SquarePixels(video)}scale=w='min(iw,{maxWidth})':h={height}:force_original_aspect_ratio=decrease:flags=lanczos";+ var timing = double.IsFinite(speed) && speed is > 0 and not 1+ ? $"setpts=PTS/{speed.ToString("0.###", CultureInfo.InvariantCulture)},"+ : "";+ return $"{timing}fps={fps},{SquarePixels(video)}scale=w='min(iw,{maxWidth})':h={height}:force_original_aspect_ratio=decrease:flags=lanczos";}/// <summary>Images have no pixel aspect ratio: anamorphic video (DV, DVD) is stretched to square pixels first.</summary>diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.csindex 7889ae38..c3103a20 100644--- a/tests/Filee.Core.Tests/FakeConverter.cs+++ b/tests/Filee.Core.Tests/FakeConverter.cs@@ -81,6 +81,9 @@ internal sealed class FakeRecorder(string id, params ConversionEdge[] edges) : I/// <summary>The steps it was asked for: (from, to, every frame).</summary>public List<(string From, string To, bool FrameSequence)> Steps { get; } = [];+ /// <summary>The animation speed each step was asked for: (to, speed).</summary>+ public List<(string To, double Speed)> Speeds { get; } = [];+public EngineStatus GetStatus() => EngineStatus.Available();public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)@@ -89,6 +92,7 @@ internal sealed class FakeRecorder(string id, params ConversionEdge[] edges) : I{Asked.Add((step.To, step.Preset.Image.Rotation));Steps.Add((step.From, step.To, step.FrameSequence));+ Speeds.Add((step.To, step.Preset.Image.AnimationSpeed));}return _writer.ConvertAsync(step, progress, cancellationToken);}diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.csindex f4e20cb2..a39a1221 100644--- a/tests/Filee.Core.Tests/JobQueueTests.cs+++ b/tests/Filee.Core.Tests/JobQueueTests.cs@@ -115,6 +115,25 @@ public class JobQueueTestsAssert.Equal([("heic", ImageRotation.Left90)], heic.Asked);}+ [Fact]+ public async Task Playback_speed_changes_only_in_the_step_that_writes_the_output()+ {+ // MP4 → GIF → WebP: both engines keep the animation, only the last one may change its speed (not 2 × 2 = 4×).+ using var dir = new TempDir();+ var video = dir.File("clip.mp4");+ var ffmpeg = new FakeRecorder("ffmpeg", new ConversionEdge("mp4", "gif"));+ var magick = new FakeRecorder("magick", new ConversionEdge("gif", "webp"));+ await using var queue = new JobQueue(new ConverterCatalog([ffmpeg, magick]));+ var preset = new Preset { TargetFormat = "webp", Image = { AnimationSpeed = 2 } };++ var job = await Run(queue, [video], preset);++ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal([("gif", 1.0)], ffmpeg.Speeds);+ Assert.Equal([("webp", 2.0)], magick.Speeds);+ Assert.Equal(2, preset.Image.AnimationSpeed); // the job's preset itself is left alone+ }+[Fact]public async Task Keep_dates_gives_outputs_the_dates_of_their_source(){diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 5b3d34fe..8939d56b 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -146,6 +146,38 @@ public class UserDataStoreTestsAssert.False(reloaded.FindPreset("old")!.Media.HardwareEncoding);}+ [Fact]+ public void Animation_speed_is_saved_and_is_the_original_speed_for_presets_from_before_it()+ {+ using var dir = new TempDir();+ var store = new UserDataStore(dir.Path);+ store.Load();+ Assert.All(store.Presets, p => Assert.Equal(1, p.Image.AnimationSpeed)); // no built-in preset changes it+ store.Presets.Add(new Preset { Id = "slow", Name = "Slow", TargetFormat = "gif", Image = { AnimationSpeed = 0.5 } });+ store.Presets.Add(new Preset { Id = "old", Name = "Old", TargetFormat = "gif" });+ store.Presets.Add(new Preset { Id = "odd", Name = "Odd", TargetFormat = "gif" });+ store.SaveLibrary();++ // A Filee from before the option saved no "animationSpeed"; a hand-edited file may hold anything.+ var path = Path.Combine(dir.Path, "presets.json");+ var presets = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(path))!.AsArray();+ Assert.Equal(0.5, (double)presets.Single(p => (string?)p!["id"] == "slow")!["image"]!["animationSpeed"]!);+ Assert.True(presets.Single(p => (string?)p!["id"] == "old")!["image"]!.AsObject().Remove("animationSpeed"));+ presets.Single(p => (string?)p!["id"] == "odd")!["image"]!["animationSpeed"] = -3;+ File.WriteAllText(path, presets.ToJsonString());++ var reloaded = new UserDataStore(dir.Path);+ reloaded.Load();++ var slow = reloaded.FindPreset("slow")!;+ Assert.Equal(0.5, slow.Image.AnimationSpeed);+ Assert.Equal(0.5, slow.Clone().Image.AnimationSpeed);+ Assert.True(slow.Image.ChangesSpeed);+ Assert.Equal(1, reloaded.FindPreset("old")!.Image.AnimationSpeed);+ Assert.False(reloaded.FindPreset("old")!.Image.ChangesSpeed);+ Assert.Equal(1, reloaded.FindPreset("odd")!.Image.PlaybackSpeed); // a speed that makes no sense plays as made+ }+[Fact]public void History_is_kept_until_turned_off_and_can_be_cleared(){diff --git a/tests/Filee.Engines.Tests/AnimationSpeedTests.cs b/tests/Filee.Engines.Tests/AnimationSpeedTests.csnew file mode 100644index 00000000..cf03572e--- /dev/null+++ b/tests/Filee.Engines.Tests/AnimationSpeedTests.cs@@ -0,0 +1,176 @@+// Playback speed of animations (ImageOptions.AnimationSpeed): frame delays rewritten in each format's units, frames+// dropped where a delay would get shorter than players show. Animations are generated in the tests.++using System.Buffers.Binary;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Magick;+using Filee.Engines.Media;+using ImageMagick;++namespace Filee.Engines.Tests;++public class AnimationSpeedTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static void AssertDone(ConversionJob job)+ {+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");+ }++ /// <summary>A frame of its own colour for every delay (hundredths of a second), playing <paramref name="loops"/> times.</summary>+ private static string MakeGif(string folder, uint[] delays, uint loops = 3, string name = "anim.gif")+ {+ using var frames = new MagickImageCollection();+ for (var i = 0; i < delays.Length; i++)+ frames.Add(new MagickImage(Colour(i), 32, 24) { AnimationDelay = delays[i], AnimationIterations = loops });+ var path = Path.Combine(folder, name);+ frames.Write(path, MagickFormat.Gif);+ return path;+ }++ private static MagickColor Colour(int i) => new((byte)(i * 30 % 256), (byte)(255 - i * 30 % 256), (byte)(i * 70 % 256));++ private static bool IsColour(IMagickImage<byte> frame, int i)+ {+ var pixel = frame.GetPixels().GetPixel(16, 12).ToColor()!;+ var expected = Colour(i);+ return Math.Abs(pixel.R - expected.R) < 12 && Math.Abs(pixel.G - expected.G) < 12 && Math.Abs(pixel.B - expected.B) < 12;+ }++ private static Preset Speed(string target, double speed) =>+ new() { TargetFormat = target, Image = { AnimationSpeed = speed }, Output = { FileNamePattern = "{name}_" + speed } };++ /// <summary>The duration of every ANMF chunk of an animated WebP, in milliseconds.</summary>+ private static List<int> WebpDurations(string path)+ {+ var file = File.ReadAllBytes(path);+ Assert.Equal("RIFF", Encoding.ASCII.GetString(file, 0, 4));+ var durations = new List<int>();+ for (var position = 12; position + 8 <= file.Length;)+ {+ var type = Encoding.ASCII.GetString(file, position, 4);+ var size = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(position + 4));+ if (type == "ANMF")+ durations.Add(file[position + 20] | file[position + 21] << 8 | file[position + 22] << 16);+ position += 8 + size + (size & 1);+ }+ return durations;+ }++ [Theory]+ [InlineData(2.0, new uint[] { 5, 10, 15, 20 })]+ [InlineData(0.5, new uint[] { 20, 40, 60, 80 })]+ [InlineData(1.0, new uint[] { 10, 20, 30, 40 })]+ public async Task Gif_frame_delays_follow_the_speed(double speed, uint[] expected)+ {+ var dir = fx.NewFolder();+ var gif = MakeGif(dir, [10, 20, 30, 40]);++ var job = await fx.ConvertAsync([gif], Speed("gif", speed));++ AssertDone(job);+ using var frames = new MagickImageCollection(job.Outputs.Single());+ Assert.Equal(expected, frames.Select(f => f.AnimationDelay));+ Assert.All(frames, f => Assert.Equal(3u, f.AnimationIterations)); // the loop count stays+ Assert.True(IsColour(frames[3], 3), "every frame is kept, in order");+ }++ [Fact]+ public async Task Webp_and_apng_get_the_speed_in_milliseconds()+ {+ var dir = fx.NewFolder();+ var gif = MakeGif(dir, [10, 20, 30, 40]);++ // 1.5×: 66.7, 133.3, 200, 266.7 ms, rounded on the running total so the animation lasts 667 ms.+ var webp = await fx.ConvertAsync([gif], Speed("webp", 1.5));+ AssertDone(webp);+ Assert.Equal([67, 133, 200, 267], WebpDurations(webp.Outputs.Single()));++ // 0.75×: 133.3, 266.7, 400, 533.3 ms.+ var apng = await fx.ConvertAsync([gif], Speed("apng", 0.75));+ AssertDone(apng);+ var chunks = ApngBuilder.Chunks(File.ReadAllBytes(apng.Outputs.Single()));+ var delays = chunks.Where(c => c.Type == "fcTL")+ .Select(c => (BinaryPrimitives.ReadUInt16BigEndian(c.Data.AsSpan(20)), BinaryPrimitives.ReadUInt16BigEndian(c.Data.AsSpan(22))))+ .ToList();+ Assert.Equal([((ushort)133, (ushort)1000), ((ushort)267, (ushort)1000), ((ushort)400, (ushort)1000), ((ushort)533, (ushort)1000)], delays);+ Assert.Equal(3u, BinaryPrimitives.ReadUInt32BigEndian(chunks.Single(c => c.Type == "acTL").Data.AsSpan(4)));+ }++ [Fact]+ public async Task Sped_up_frames_shorter_than_players_show_are_dropped_evenly()+ {+ var dir = fx.NewFolder();+ // Eight frames of 4/100 s at 4×: 1/100 s each, which browsers would show for 10/100 s. Every other frame is+ // dropped instead and the rest get 2/100 s: the animation still lasts 8/100 s.+ var gif = MakeGif(dir, [4, 4, 4, 4, 4, 4, 4, 4]);++ var job = await fx.ConvertAsync([gif], Speed("gif", 4));++ AssertDone(job);+ using var frames = new MagickImageCollection(job.Outputs.Single());+ Assert.Equal([2u, 2u, 2u, 2u], frames.Select(f => f.AnimationDelay));+ for (var i = 0; i < frames.Count; i++)+ Assert.True(IsColour(frames[i], i * 2), $"frame {i} is the source's frame {i * 2}");++ // WebP keeps milliseconds, with the same 20 ms floor: 40 ms frames at 4× become 20 ms, every other one dropped.+ var webp = await fx.ConvertAsync([gif], Speed("webp", 4));+ AssertDone(webp);+ Assert.Equal([20, 20, 20, 20], WebpDurations(webp.Outputs.Single()));+ }++ [Fact]+ public void Delays_are_rounded_on_the_running_total_and_short_ones_count_as_players_show_them()+ {+ using var images = new MagickImageCollection();+ // 0 and 1 hundredths are shown for 10/100 s by browsers: that is what gets sped up.+ foreach (var delay in new uint[] { 0, 1, 3, 3, 3 })+ images.Add(new MagickImage(MagickColors.Red, 4, 4) { AnimationDelay = delay, AnimationTicksPerSecond = 100 });+ var frames = images.ToList();++ var fast = AnimationTiming.ChangeSpeed(frames, 2, "gif");++ // 5, 5, 1.5, 1.5, 1.5 → starts 0, 5, 10, 11.5 (12), 13, end 14.5 (15): the last frame would start 1/100 s+ // after the one before, so it is dropped and that one stays up until the end.+ Assert.Equal([5u, 5u, 2u, 3u], fast.Select(f => f.AnimationDelay));+ Assert.All(fast, f => Assert.Equal(100, f.AnimationTicksPerSecond));+ Assert.Same(frames[3], fast[3]);++ // One frame, or speed 1: nothing to do.+ Assert.Equal(frames, AnimationTiming.ChangeSpeed(frames, 1, "gif"));+ Assert.Single(AnimationTiming.ChangeSpeed([frames[0]], 3, "webp"));+ }++ [Fact]+ public async Task A_still_target_takes_the_first_frame_whatever_the_speed()+ {+ var dir = fx.NewFolder();+ var gif = MakeGif(dir, [10, 20, 30, 40]);++ var job = await fx.ConvertAsync([gif], Speed("png", 2));++ AssertDone(job);+ using var png = new MagickImage(job.Outputs.Single());+ Assert.True(IsColour(png, 0));+ }++ [Fact]+ public void Video_to_gif_and_apng_changes_the_timestamps_before_the_frame_rate()+ {+ var info = new MediaInfo(TimeSpan.FromSeconds(3), new VideoStreamInfo(1920, 1080, 1, 0, 29.97), null, null);++ var gif = MediaEncoding.Plan("in.mp4", "out.gif", "gif", new MediaOptions(), info, "work", animationSpeed: 2);+ Assert.All(gif, pass => Assert.Contains("[0:V:0]setpts=PTS/2,fps=12,", After(pass.Arguments, "-filter_complex")));++ var apng = MediaEncoding.Plan("in.mp4", "out.apng", "apng", new MediaOptions { Quality = MediaQuality.High }, info, "work",+ animationSpeed: 0.75).Single();+ Assert.StartsWith("setpts=PTS/0.75,fps=15,", After(apng.Arguments, "-vf"));++ var normal = MediaEncoding.Plan("in.mp4", "out.apng", "apng", new MediaOptions(), info, "work").Single();+ Assert.StartsWith("fps=", After(normal.Arguments, "-vf"));+ }++ private static string After(IReadOnlyList<string> args, string option) => args[args.ToList().IndexOf(option) + 1];+}