Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

Video -> image sequence: add support for saving every frame with interval control

pleguene79541ced43f
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 0508e507..96a51ef1 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -295,6 +295,9 @@
"presets.webp_lossless": "Lossless WEBP",
"presets.multipage_tiff": "Put every file into one multi-page TIFF",
"presets.multipage_tiff_hint": "Each image, each PDF page and each page of a TIFF becomes a page, in order. One PDF is enough for a multi-page TIFF.",
+ "presets.save_every_frame": "Save every frame as images",
+ "presets.save_every_frame_hint": "When converting from video: extracts all frames to a dedicated subfolder instead of saving a single still frame.",
+ "presets.frame_interval": "Every Nth frame",
"presets.ico_sizes": "Icon sizes",
"presets.group.pdf": "PDF",
"presets.merge": "Merge all files into one PDF",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 9fb135f1..b54dd0bb 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -295,6 +295,9 @@
"presets.webp_lossless": "무손실 WEBP",
"presets.multipage_tiff": "모든 파일을 여러 페이지짜리 TIFF 하나로 합치기",
"presets.multipage_tiff_hint": "이미지 한 장, PDF 한 페이지, TIFF의 각 페이지가 순서대로 한 페이지씩 들어가요. PDF 하나만 넣어도 여러 페이지 TIFF가 돼요.",
+ "presets.save_every_frame": "모든 프레임을 이미지로 저장",
+ "presets.save_every_frame_hint": "동영상 변환 시: 단일 정지 이미지를 저장하는 대신 전용 하위 폴더에 모든 프레임을 추출합니다.",
+ "presets.frame_interval": "N번째 프레임마다",
"presets.ico_sizes": "아이콘 크기",
"presets.group.pdf": "PDF",
"presets.merge": "모든 파일을 하나의 PDF로 합치기",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index f10a1c16..3734bd92 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -295,6 +295,9 @@
"presets.webp_lossless": "无损 WEBP",
"presets.multipage_tiff": "将所有文件合并为一个多页 TIFF",
"presets.multipage_tiff_hint": "每张图片、每个 PDF 页面以及 TIFF 的每一页都会按顺序成为一页。只放一个 PDF 也能得到多页 TIFF。",
+ "presets.save_every_frame": "将所有帧保存为图像",
+ "presets.save_every_frame_hint": "从视频转换时:将所有帧提取到专用子文件夹中,而不是仅保存单张静态图像。",
+ "presets.frame_interval": "每 N 帧",
"presets.ico_sizes": "图标尺寸",
"presets.group.pdf": "PDF",
"presets.merge": "将所有文件合并为一个 PDF",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 1e61ab63..29fd16a0 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -89,6 +89,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_wavFormat = WavFormats.First(f => f.Value == _edit.Media.WavFormat);
_archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level);
_combineIntoOne = _edit.Archive.CombineIntoOne;
+ _saveEveryFrame = _edit.Media.SaveEveryFrame;
+ _frameInterval = _edit.Media.FrameInterval > 0 ? _edit.Media.FrameInterval : 1;
_quality = _edit.Image.Quality;
_resizePercent = _edit.Image.ResizePercent;
_longEdge = _edit.Image.LongEdge;
@@ -141,7 +143,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
nameof(ShowAudioChannels), nameof(ShowWav),
- nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote))]
+ nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote),
+ nameof(ShowSaveEveryFrame))]
private Choice<string> _target;
[ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge), nameof(ShowWidth))]
@@ -212,6 +215,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private bool _removeAudio;
[ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;
[ObservableProperty] private bool _combineIntoOne;
+ [ObservableProperty] private bool _saveEveryFrame;
+ [ObservableProperty] private int _frameInterval = 1;
private string TargetId => Target.Value;
private FormatCategory? TargetCategory => FormatRegistry.FindById(TargetId)?.Category;
@@ -247,6 +252,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowArchiveOptions => ShowArchive && TargetId != FormatRegistry.Folder;
/// <summary>"Extract" has nothing to set; a line says what it does instead.</summary>
public bool ShowExtractNote => TargetId == FormatRegistry.Folder;
+ public bool ShowSaveEveryFrame => TargetId is "jpg" or "jpeg" or "png";
public bool ShowPercent => Resize.Value == ResizeMode.Percent;
public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge;
public bool ShowWidth => Resize.Value == ResizeMode.Width;
@@ -310,6 +316,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
media.AudioChannels = AudioChannels.Value;
media.AudioSampleRate = SampleRate.Value;
media.WavFormat = WavFormat.Value;
+ media.SaveEveryFrame = SaveEveryFrame;
+ media.FrameInterval = Math.Clamp(FrameInterval, 1, 1000);
_original.Archive.Level = ArchiveLevel.Value;
_original.Archive.CombineIntoOne = CombineIntoOne;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 19447e9c..ebeb2bbd 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -93,6 +93,14 @@
</Grid>
<CheckBox Content="{DynamicResource presets.multipage_tiff}" IsChecked="{Binding MultiPageTiff}" IsVisible="{Binding ShowMultiPageTiff}"
ToolTip.Tip="{DynamicResource presets.multipage_tiff_hint}" />
+ <StackPanel Spacing="6" IsVisible="{Binding ShowSaveEveryFrame}">
+ <CheckBox Content="{DynamicResource presets.save_every_frame}" IsChecked="{Binding SaveEveryFrame}"
+ ToolTip.Tip="{DynamicResource presets.save_every_frame_hint}" />
+ <Grid ColumnDefinitions="Auto,12,120" Margin="28,0,0,0" IsVisible="{Binding SaveEveryFrame}">
+ <TextBlock Classes="label" VerticalAlignment="Center" Text="{DynamicResource presets.frame_interval}" />
+ <NumericUpDown Grid.Column="2" Value="{Binding FrameInterval}" Minimum="1" Maximum="1000" Increment="1" FormatString="0" />
+ </Grid>
+ </StackPanel>
</StackPanel>
</Border>
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 497ad947..0a270d60 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -228,6 +228,15 @@ public sealed class MediaOptions
/// <summary>How a WAV file stores its samples.</summary>
public WavSampleFormat WavFormat { get; set; } = WavSampleFormat.Pcm16;
+ /// <summary>Video → image: save every frame as an individual image instead of a single still frame.</summary>
+ public bool SaveEveryFrame { get; set; }
+
+ /// <summary>With <see cref="SaveEveryFrame"/>: extract every Nth frame (1 = every frame).</summary>
+ public int FrameInterval { get; set; } = 1;
+
+ /// <summary>With <see cref="SaveEveryFrame"/>: target frames per second (0 = keep source rate).</summary>
+ public double FramesPerSecond { get; set; }
+
public MediaOptions Clone() => (MediaOptions)MemberwiseClone();
}
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index 46760f81..616b6316 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -103,7 +103,7 @@ public sealed partial class FfmpegConverter : IConverter
// Throws for a missing stream before anything is written (an existing file of that name stays untouched).
var passes = still
? MediaEncoding.PlanStill(input, output, step.To, step.Preset.Media, info)
- : MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover);
+ : MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover, step.Preset.Image.Quality);
var duration = still ? MediaEncoding.StillDuration : info.Duration;
try
{
@@ -194,6 +194,9 @@ public sealed partial class FfmpegConverter : IConverter
private static bool IsVideoFrameSplitting(ConversionStep step, MediaInfo info, out string imageExt)
{
imageExt = "";
+ if (!step.Preset.Media.SaveEveryFrame)
+ return false;
+
var isSourceVideo = (FormatRegistry.FindById(step.From)?.Category == FormatCategory.Video)
|| (FormatRegistry.Detect(step.InputPath)?.Category == FormatCategory.Video)
|| VideoExtensions.Contains(Path.GetExtension(step.InputPath))
@@ -243,14 +246,26 @@ public sealed partial class FfmpegConverter : IConverter
return [];
var outputDirectory = Path.GetDirectoryName(allocated)!;
- var videoFilename = FormatRegistry.NameWithoutExtension(step.InputPath);
+ 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})");
- if (!Directory.Exists(framesSubfolder))
- Directory.CreateDirectory(framesSubfolder);
+ Directory.CreateDirectory(framesSubfolder);
var outputPattern = Path.Combine(framesSubfolder, $"frame_%04d.{imageExt}");
- var args = MediaEncoding.FrameSequence(input, outputPattern, 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
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index 7cca9982..736ec9c9 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -119,14 +119,14 @@ internal static class MediaEncoding
/// <param name="cover">The source's cover for targets FFmpeg can't put a picture stream into (<see cref="CoverArt"/>).</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)
+ CoverExtras? cover = null, int imageQuality = 90)
{
if (target == "gif")
return AnimatedGif(input, output, options, info, workDirectory);
if (target is "jpg" or "jpeg")
- return [new FfmpegPass(FrameSequence(input, output, "jpg"), 1)];
+ return [new FfmpegPass(PosterFrame(input, output, info, "mjpeg", imageQuality), 1)];
if (target == "png")
- return [new FfmpegPass(PosterFrame(input, output, info), 1)];
+ return [new FfmpegPass(PosterFrame(input, output, info, "png"), 1)];
if (VideoTargets.TryGetValue(target, out var video))
return [new FfmpegPass(Video(input, output, target, video, options, info), 1)];
if (AudioTargets.TryGetValue(target, out var audio))
@@ -135,14 +135,47 @@ internal static class MediaEncoding
}
/// <summary>
- /// Slices every frame of a video into an image sequence in <paramref name="outputPattern"/>
+ /// Maps preset image quality (1..100, 100 best) to FFmpeg's mjpeg -q:v parameter (1..31, 1 best, 2..3 visually lossless).
+ /// </summary>
+ public static int QualityToQv(int quality)
+ {
+ var clamped = Math.Clamp(quality, 1, 100);
+ return Math.Clamp((int)Math.Round(2.0 + (100 - clamped) * 29.0 / 99.0), 1, 31);
+ }
+
+ /// <summary>
+ /// Slices frames of a video into an image sequence in <paramref name="outputPattern"/>
/// for focus stacking and photography analysis.
/// </summary>
- public static List<string> FrameSequence(string input, string outputPattern, string imageExt)
+ public static List<string> FrameSequence(
+ string input,
+ string outputPattern,
+ string imageExt,
+ VideoStreamInfo? video = null,
+ int quality = 90,
+ int frameInterval = 1,
+ double fps = 0)
{
List<string> args = [.. Common, "-i", input];
+
+ var filters = new List<string>();
+ if (video is not null && Math.Abs(video.SampleAspect - 1) > 0.01)
+ filters.Add("scale=w='trunc(iw*sar/2)*2':h=ih,setsar=1");
+
+ if (frameInterval > 1)
+ filters.Add($"select='not(mod(n\\,{frameInterval}))'");
+ else if (fps > 0)
+ filters.Add($"fps={fps.ToString(CultureInfo.InvariantCulture)}");
+
+ if (filters.Count > 0)
+ args.AddRange(["-vf", string.Join(",", filters)]);
+
+ if (frameInterval > 1)
+ args.AddRange(["-fps_mode", "vfr"]);
+
if (imageExt is "jpg" or "jpeg")
- args.AddRange(["-q:v", "2"]);
+ args.AddRange(["-q:v", QualityToQv(quality).ToString(CultureInfo.InvariantCulture)]);
+
args.AddRange(["-progress", "pipe:1", outputPattern]);
return args;
}
@@ -544,20 +577,26 @@ internal static class MediaEncoding
// ───────────────────────── Still frame ─────────────────────────
/// <summary>
- /// One full-size PNG frame from a tenth into the video (the first frames are often black), the start for video →
+ /// One full-size frame from a tenth into the video (the first frames are often black), the start for video →
/// image conversions (the image engines take it from there). Without this edge the route planner would reach
/// images through an animated GIF of the whole video.
/// </summary>
- private static List<string> PosterFrame(string input, string output, MediaInfo info)
+ private static List<string> PosterFrame(string input, string output, MediaInfo info, string format = "png", int quality = 90)
{
var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");
var seconds = (info.Duration?.TotalSeconds ?? 0) / 10;
- return
+ List<string> args =
[
.. Common, "-ss", seconds.ToString("0.###", CultureInfo.InvariantCulture), "-i", input, "-map", "0:V:0",
- "-vf", SquarePixels(video) + "null", "-frames:v", "1", "-update", "1", "-c:v", "png", "-f", "image2",
- "-progress", "pipe:1", output,
+ "-vf", SquarePixels(video) + "null", "-frames:v", "1", "-update", "1",
];
+ if (format is "jpg" or "jpeg" or "mjpeg")
+ args.AddRange(["-c:v", "mjpeg", "-q:v", QualityToQv(quality).ToString(CultureInfo.InvariantCulture), "-f", "image2"]);
+ else
+ args.AddRange(["-c:v", "png", "-f", "image2"]);
+
+ args.AddRange(["-progress", "pipe:1", output]);
+ return args;
}
// ───────────────────────── Still picture → video ─────────────────────────
diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.cs
index 11100161..d11c1a8d 100644
--- a/tests/Filee.Engines.Tests/MediaTests.cs
+++ b/tests/Filee.Engines.Tests/MediaTests.cs
@@ -581,21 +581,45 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
[Fact]
- public async Task Video_to_image_slices_frames_to_dedicated_subfolder()
+ public async Task Video_gives_a_still_frame_for_images()
{
SkipUnlessInstalled();
var folder = fx.NewFolder();
- var source = await MakeClipAsync(folder, "still.mkv", seconds: 2, size: "640x360");
+ // Anamorphic 4:3 DV-style video: 720×480 pixels that are shown narrower than they are stored.
+ var source = await MakeClipAsync(folder, "still.mkv", seconds: 3, size: "720x480", extra: ["-vf", "setsar=8/9"]);
- var pngFolder = await ConvertAsync(source, "png");
- Assert.True(Directory.Exists(pngFolder));
- Assert.Equal(Path.Combine(folder, "still_frames"), pngFolder);
- var pngFiles = Directory.GetFiles(pngFolder, "frame_*.png");
- Assert.NotEmpty(pngFiles);
+ var png = await ProbeAsync(await ConvertAsync(source, "png"));
+ Assert.Equal("png", png.Video?.Codec);
+ Assert.Equal((640, 480), (png.Video!.Width, png.Video.Height)); // square pixels
- var jpgFolder = await ConvertAsync(source, "jpg");
+ var jpg = await ConvertAsync(source, "jpg");
+ using var image = new ImageMagick.MagickImage(jpg);
+ Assert.Equal((640u, 480u), (image.Width, image.Height));
+ }
+
+ [Fact]
+ public async Task Video_to_image_slices_frames_to_unique_subfolders()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "seq.mkv", seconds: 2, size: "640x360");
+
+ var options = new MediaOptions { SaveEveryFrame = true };
+ var pngFolder1 = await ConvertAsync(source, "png", options);
+ Assert.True(Directory.Exists(pngFolder1));
+ Assert.Equal(Path.Combine(folder, "seq_frames"), pngFolder1);
+ Assert.NotEmpty(Directory.GetFiles(pngFolder1, "frame_*.png"));
+
+ // A second run creates a unique folder seq_frames (2) instead of writing into an existing one.
+ var pngFolder2 = await ConvertAsync(source, "png", options);
+ Assert.True(Directory.Exists(pngFolder2));
+ Assert.Equal(Path.Combine(folder, "seq_frames (2)"), pngFolder2);
+ Assert.NotEmpty(Directory.GetFiles(pngFolder2, "frame_*.png"));
+
+ // JPG sequence extraction also creates unique folder and valid images
+ var jpgFolder = await ConvertAsync(source, "jpg", options);
Assert.True(Directory.Exists(jpgFolder));
- Assert.Equal(Path.Combine(folder, "still_frames"), jpgFolder);
+ Assert.Equal(Path.Combine(folder, "seq_frames (3)"), jpgFolder);
var jpgFiles = Directory.GetFiles(jpgFolder, "frame_*.jpg");
Assert.NotEmpty(jpgFiles);
using var image = new ImageMagick.MagickImage(jpgFiles.First());
@@ -605,13 +629,21 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public void Video_frame_sequence_arguments_use_proper_flags()
{
- var jpg = MediaEncoding.FrameSequence("in.mp4", "out_frames/frame_%04d.jpg", "jpg");
+ var video = new VideoStreamInfo(720, 480, 8.0 / 9.0, 0, 30);
+ var jpg = MediaEncoding.FrameSequence("in.mp4", "out_frames/frame_%04d.jpg", "jpg", video, quality: 100, frameInterval: 5);
Assert.Contains("-q:v", jpg);
Assert.Equal("2", After(jpg, "-q:v"));
+ Assert.Contains("-vf", jpg);
+ var vf = After(jpg, "-vf");
+ Assert.Contains("scale=w='trunc(iw*sar/2)*2':h=ih,setsar=1", vf);
+ Assert.Contains("select='not(mod(n\\,5))'", vf);
+ Assert.Contains("-fps_mode", jpg);
+ Assert.Equal("vfr", After(jpg, "-fps_mode"));
Assert.Equal("out_frames/frame_%04d.jpg", jpg[^1]);
- var png = MediaEncoding.FrameSequence("in.mp4", "out_frames/frame_%04d.png", "png");
+ var png = MediaEncoding.FrameSequence("in.mp4", "out_frames/frame_%04d.png", "png", fps: 10);
Assert.DoesNotContain("-q:v", png);
+ Assert.Contains("fps=10", After(png, "-vf"));
Assert.Equal("out_frames/frame_%04d.png", png[^1]);
}