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
Every frame: a folder from the output rule, moved into place when done
KnifeLemon8e19e9edd130
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.csindex 8cb8de13..ac9125b0 100644--- a/src/Filee.Engines/Media/FfmpegConverter.cs+++ b/src/Filee.Engines/Media/FfmpegConverter.cs@@ -99,7 +99,7 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformerprogress?.Report(0.02);if (step.FrameSequence)- return await ExtractFramesAsync(ffmpeg, step, input, info, FormatRegistry.Get(step.To).PrimaryExtension, progress, cancellationToken);+ return await FrameSequenceWriter.ConvertAsync(ffmpeg, step, input, info, progress, cancellationToken);var output = step.Output.Allocate(FormatRegistry.Get(step.To).PrimaryExtension);if (output is null)@@ -141,7 +141,7 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformer}/// <summary>Runs one pass and maps FFmpeg's position (seconds) onto this pass' share of the progress.</summary>- private static async Task RunPassAsync(string ffmpeg, FfmpegPass pass, TimeSpan? duration, IProgress<double>? progress, double done, CancellationToken cancellationToken)+ internal static async Task RunPassAsync(string ffmpeg, FfmpegPass pass, TimeSpan? duration, IProgress<double>? progress, double done, CancellationToken cancellationToken){var total = duration?.TotalSeconds ?? 0;Action<double>? onPosition = progress is null || total <= 0@@ -236,70 +236,6 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformer}});- private static async Task<IReadOnlyList<string>> ExtractFramesAsync(- string ffmpeg,- ConversionStep step,- string input,- MediaInfo info,- string imageExt,- IProgress<double>? progress,- CancellationToken cancellationToken)- {- var allocated = step.Output.Allocate(imageExt);- if (allocated is null)- return [];-- var outputDirectory = Path.GetDirectoryName(allocated)!;- var videoFilename = Path.GetFileNameWithoutExtension(allocated);- if (string.IsNullOrEmpty(videoFilename))- videoFilename = FormatRegistry.NameWithoutExtension(step.InputPath);-- var framesSubfolder = Path.Combine(outputDirectory, $"{videoFilename}_frames");- for (var n = 2; Directory.Exists(framesSubfolder); n++)- framesSubfolder = Path.Combine(outputDirectory, $"{videoFilename}_frames ({n})");-- Directory.CreateDirectory(framesSubfolder);-- var outputPattern = Path.Combine(framesSubfolder, $"frame_%06d.{imageExt}");- var args = MediaEncoding.FrameSequence(- input,- outputPattern,- imageExt,- info.Video,- step.Preset.Image.Quality,- step.Preset.Media.FrameInterval,- step.Preset.Media.FramesPerSecond);-- var pass = new FfmpegPass(args, 1);-- try- {- await RunPassAsync(ffmpeg, pass, info.Duration, progress, done: 0, cancellationToken);-- if (!Directory.Exists(framesSubfolder) || !Directory.EnumerateFiles(framesSubfolder).Any())- throw new InvalidOperationException("FFmpeg did not write any frames.");- }- catch- {- TryDeleteDirectory(framesSubfolder);- throw;- }-- progress?.Report(1);- return [framesSubfolder];- }-- private static void TryDeleteDirectory(string path)- {- try- {- if (Directory.Exists(path))- Directory.Delete(path, recursive: true);- }- catch (IOException) { }- catch (UnauthorizedAccessException) { }- }-private static void TryDelete(string path){trydiff --git a/src/Filee.Engines/Media/FfmpegRunner.cs b/src/Filee.Engines/Media/FfmpegRunner.csindex b4cb60b4..7daefbc1 100644--- a/src/Filee.Engines/Media/FfmpegRunner.cs+++ b/src/Filee.Engines/Media/FfmpegRunner.cs@@ -149,12 +149,20 @@ internal static class FfmpegRunnerreturn line;}+ /// <summary>How long a killed FFmpeg may take to exit (and let go of its output) before the caller moves on.</summary>+ private static readonly TimeSpan ExitAfterKill = TimeSpan.FromSeconds(10);++ /// <summary>+ /// Kills FFmpeg and waits until it has exited: Kill only asks Windows to end it, and a process that still runs+ /// holds its output open, so the half-written file or folder of frames could not be deleted yet.+ /// </summary>private static void Kill(Process process){try{if (!process.HasExited)process.Kill(entireProcessTree: true);+ process.WaitForExit(ExitAfterKill);}catch (InvalidOperationException) { }catch (System.ComponentModel.Win32Exception) { }diff --git a/src/Filee.Engines/Media/FrameSequenceWriter.cs b/src/Filee.Engines/Media/FrameSequenceWriter.csnew file mode 100644index 00000000..8cb1c9b8--- /dev/null+++ b/src/Filee.Engines/Media/FrameSequenceWriter.cs@@ -0,0 +1,57 @@+// Video → every frame as a picture ("Save every frame", MediaOptions.SaveEveryFrame): numbered PNG or JPG files in+// one folder, for focus stacking or picking the sharpest shot. The pictures are written into a hidden folder next to+// the output and moved into place when FFmpeg is done, so a cancelled or failed run leaves nothing behind.++using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Engines.Archives;++namespace Filee.Engines.Media;++/// <summary>Writes the frames of a video as numbered pictures into a folder.</summary>+internal static class FrameSequenceWriter+{+ /// <summary>Name suffix of the output folder: "clip.mp4" → "clip_frames".</summary>+ public const string FolderSuffix = "_frames";++ /// <summary>+ /// Saves the frames of <paramref name="input"/> as <see cref="ConversionStep.To"/> pictures (frame_000001.png, …)+ /// into the folder the output rule names: "clip_frames", "clip_frames (2)" when that exists, or skipped, like any+ /// other output.+ /// </summary>+ public static async Task<IReadOnlyList<string>> ConvertAsync(string ffmpeg, ConversionStep step, string input, MediaInfo info,+ IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");+ var output = step.Output.Allocate("", FolderSuffix);+ if (output is null)+ return [];++ // Same folder as the output (same drive, so the move is instant); the frames go into a visible folder inside+ // it, which becomes the output.+ var staging = Path.Combine(Path.GetDirectoryName(output)!, $".{Path.GetFileName(output)}.filee-{Guid.NewGuid().ToString("N")[..8]}");+ Directory.CreateDirectory(staging).Attributes |= FileAttributes.Hidden;+ try+ {+ var frames = Directory.CreateDirectory(Path.Combine(staging, "frames")).FullName;+ var extension = FormatRegistry.Get(step.To).PrimaryExtension;+ // FFmpeg reads % in the whole path as part of the number pattern: a literal one is written %%.+ var pattern = Path.Combine(frames.Replace("%", "%%", StringComparison.Ordinal), $"frame_%06d.{extension}");+ var arguments = MediaEncoding.FrameSequence(input, pattern, extension, video, step.Preset.Image.Quality,+ step.Preset.Media.FrameInterval, step.Preset.Media.FramesPerSecond);++ await FfmpegConverter.RunPassAsync(ffmpeg, new FfmpegPass(arguments, 1), info.Duration, progress, 0, cancellationToken);+ if (!Directory.EnumerateFiles(frames).Any())+ throw new InvalidOperationException("FFmpeg did not write any frames.");++ ArchiveFiles.MoveFolder(frames, output);+ progress?.Report(1);+ return [output];+ }+ finally+ {+ // FFmpeg has exited by now (FfmpegRunner waits for it after killing it), so nothing holds these files.+ ArchiveFiles.TryDeleteFolder(staging);+ }+ }+}diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.csindex 8a88db27..9a89d434 100644--- a/tests/Filee.Engines.Tests/MediaTests.cs+++ b/tests/Filee.Engines.Tests/MediaTests.cs@@ -1091,7 +1091,7 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>public string? Allocate(string extension, string? suffix = null){- var path = Path.Combine(folder, $"out{suffix}.{extension}");+ var path = Path.Combine(folder, extension.Length == 0 ? $"out{suffix}" : $"out{suffix}.{extension}");Allocated.Add(path);return path;}@@ -1178,6 +1178,56 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.False(RunningFfmpeg(Tools.Value.Ffmpeg));}+ [Fact]+ public async Task Cancelling_every_frame_leaves_no_pictures_behind()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ var source = await MakeClipAsync(folder, "cancelframes.mp4", seconds: 60, size: "1280x720", audio: false,+ extra: ["-c:v", "libx264", "-preset", "ultrafast"]);+ using var cancellation = new CancellationTokenSource();+ var recorder = new Recorder(v =>+ {+ if (v > 0.05)+ cancellation.Cancel();+ });+ var converter = new FfmpegConverter();+ converter.GetStatus();+ var preset = new Preset { TargetFormat = "png", Media = { SaveEveryFrame = true } };+ var step = new ConversionStep(source, "mp4", "png", preset, new FolderAllocator(folder), folder, FrameSequence: true);+ cancellation.CancelAfter(TimeSpan.FromSeconds(30)); // in case no progress arrives at all++ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => converter.ConvertAsync(step, recorder, cancellation.Token));++ // Neither the output folder nor the hidden one the frames were written into is left, and FFmpeg has ended.+ Assert.Equal([Path.Combine(folder, "out_frames")], ((FolderAllocator)step.Output).Allocated);+ Assert.Equal([source], Directory.GetFileSystemEntries(folder));+ Assert.False(RunningFfmpeg(Tools!.Value.Ffmpeg));+ }++ [Fact]+ public async Task Every_frame_goes_into_its_own_folder_named_like_other_outputs()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ var source = await MakeClipAsync(folder, "100% clip.mkv", seconds: 1, size: "160x120", fps: 10, audio: false);+ var preset = new Preset { TargetFormat = "jpg", Media = { SaveEveryFrame = true } };++ var first = Assert.Single((await fx.ConvertAsync([source], preset)).Outputs);+ var second = Assert.Single((await fx.ConvertAsync([source], preset)).Outputs);+ preset.Output.Conflict = ConflictPolicy.Skip;+ var skipped = await fx.ConvertAsync([source], preset);++ Assert.Equal(Path.Combine(folder, "100% clip_frames"), first);+ Assert.Equal(Path.Combine(folder, "100% clip_frames (2)"), second);+ Assert.Empty(skipped.Outputs);+ Assert.Equal(FileState.Skipped, skipped.Files.Single().State);+ Assert.Equal(10, Directory.GetFiles(first, "frame_*.jpg").Length);+ Assert.False(new DirectoryInfo(first).Attributes.HasFlag(FileAttributes.Hidden));+ // Nothing else next to the source: no hidden folder left over.+ Assert.Equal(3, Directory.GetFileSystemEntries(folder).Length);+ }+/// <summary>/// True if a process started from <paramref name="exe"/> is running (tests of this class run one at a time, so/// it can only be the one that should have been killed).