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.

Every frame: refuse more than 100,000 pictures or more than the disk holds

KnifeLemon21a321a803bc
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 7fe4d5f6..5ccb641f 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -58,6 +58,8 @@
"error.unsupported_source": "This file type isn't supported",
"error.no_route": "No engine can do this conversion",
"error.cannot_turn": "Rotate and flip work on images only",
+ "error.too_many_frames": "Too many frames to save as pictures, raise \"Every Nth frame\"",
+ "error.not_enough_space": "Not enough free disk space for the pictures",
"error.conversion_failed": "The engine reported an error",
"engine.reason.not_installed": "Not installed",
@@ -370,6 +372,7 @@
"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.frame_estimate": "One minute of 30 fps video gives {0} pictures, at most {1} per video.",
"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 a573ba06..b986463e 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -58,6 +58,8 @@
"error.unsupported_source": "지원하지 않는 파일 형식이에요",
"error.no_route": "이 변환을 할 수 있는 엔진이 없어요",
"error.cannot_turn": "회전·반전은 이미지에만 할 수 있어요",
+ "error.too_many_frames": "프레임이 너무 많아요. 'N번째 프레임마다' 값을 늘려 주세요",
+ "error.not_enough_space": "이미지를 저장할 디스크 공간이 부족해요",
"error.conversion_failed": "엔진에서 오류가 발생했어요",
"engine.reason.not_installed": "설치되지 않음",
@@ -370,6 +372,7 @@
"presets.save_every_frame": "모든 프레임을 이미지로 저장",
"presets.save_every_frame_hint": "동영상 변환 시: 단일 정지 이미지를 저장하는 대신 전용 하위 폴더에 모든 프레임을 추출합니다.",
"presets.frame_interval": "N번째 프레임마다",
+ "presets.frame_estimate": "30fps 동영상 1분이면 이미지 {0}장이 생겨요. 동영상 하나에 최대 {1}장까지예요.",
"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 9e48eeab..077ee01b 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -58,6 +58,8 @@
"error.unsupported_source": "不支持此文件类型",
"error.no_route": "没有引擎可以完成此转换",
"error.cannot_turn": "只能旋转和翻转图片",
+ "error.too_many_frames": "帧数太多,请调大“每 N 帧”",
+ "error.not_enough_space": "磁盘空间不足,无法保存这些图片",
"error.conversion_failed": "转换引擎出错",
"engine.reason.not_installed": "未安装",
@@ -370,6 +372,7 @@
"presets.save_every_frame": "将所有帧保存为图像",
"presets.save_every_frame_hint": "从视频转换时:将所有帧提取到专用子文件夹中,而不是仅保存单张静态图像。",
"presets.frame_interval": "每 N 帧",
+ "presets.frame_estimate": "30 fps 的视频每分钟生成 {0} 张图片,每个视频最多 {1} 张。",
"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 69102d39..6cb71104 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -287,7 +287,13 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;
[ObservableProperty] private bool _combineIntoOne;
[ObservableProperty] private bool _saveEveryFrame;
- [ObservableProperty] private int _frameInterval = 1;
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(FrameEstimate))]
+ private int _frameInterval = 1;
+
+ /// <summary>How many pictures a minute of 30 fps video gives at the chosen interval, and the limit per video.</summary>
+ public string FrameEstimate => _loc.Format("presets.frame_estimate",
+ (int)Math.Ceiling(1800.0 / Math.Clamp(FrameInterval, 1, 1000)), MediaOptions.MaxFrames.ToString("N0", System.Globalization.CultureInfo.InvariantCulture));
[ObservableProperty, NotifyPropertyChangedFor(nameof(ShowTraceColors))]
private Choice<TracingMode> _traceMode;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 94bfb6e6..184dd5ce 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -118,10 +118,13 @@
<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 Spacing="4" Margin="28,0,0,0" IsVisible="{Binding SaveEveryFrame}">
+ <Grid ColumnDefinitions="Auto,12,120">
+ <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>
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding FrameEstimate}" />
+ </StackPanel>
</StackPanel>
</StackPanel>
</Border>
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index 86e6a0e5..3bb5d7fb 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -31,6 +31,20 @@ public readonly record struct ConversionEdge(
string From, string To, int Cost = 10, bool ImageSourcesOnly = false, bool NotForImageSources = false,
bool FrameSequence = false);
+/// <summary>
+/// A conversion an engine refuses with a reason the user can act on, shown in their language (the file's
+/// <see cref="FileResult.ErrorKey"/>) instead of "The engine reported an error".
+/// </summary>
+/// <param name="errorKey">Localization key of the reason, e.g. <c>error.too_many_frames</c>.</param>
+/// <param name="detail">Non-localized detail shown after it in brackets (numbers, a name), or null.</param>
+public sealed class ConversionRefusedException(string errorKey, string? detail = null)
+ : Exception(detail is null ? errorKey : $"{errorKey} ({detail})")
+{
+ public string ErrorKey { get; } = errorKey;
+
+ public string? Detail { get; } = detail;
+}
+
/// <summary>Whether an engine can currently be used.</summary>
/// <param name="IsAvailable">True if conversions can run.</param>
/// <param name="ReasonKey">Localization key explaining why the engine is unavailable (e.g. <c>engine.reason.not_installed</c>).</param>
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index d9005ead..ce58d87e 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -408,6 +408,11 @@ public sealed class JobQueue : IAsyncDisposable
Notify(job);
return [];
}
+ catch (ConversionRefusedException ex)
+ {
+ _log.LogInformation("Converting {File} was refused: {Reason}", file.SourcePath, ex.Message);
+ return Fail(file, ex.ErrorKey, ex.Detail);
+ }
catch (Exception ex)
{
_log.LogWarning(ex, "Converting {File} failed", file.SourcePath);
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index c533c9a0..63fd1408 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -389,6 +389,12 @@ public sealed class MediaOptions
/// <summary>With <see cref="SaveEveryFrame"/>: extract every Nth frame (1 = every frame).</summary>
public int FrameInterval { get; set; } = 1;
+ /// <summary>
+ /// Most pictures one video may become (<see cref="SaveEveryFrame"/>): about an hour at 30 fps, already more than
+ /// anyone looks through. A longer video needs a larger <see cref="FrameInterval"/>.
+ /// </summary>
+ public const long MaxFrames = 100_000;
+
/// <summary>With <see cref="SaveEveryFrame"/>: target frames per second (0 = keep source rate).</summary>
public double FramesPerSecond { get; set; }
diff --git a/src/Filee.Engines/Media/FrameSequenceWriter.cs b/src/Filee.Engines/Media/FrameSequenceWriter.cs
index 8cb1c9b8..0a9de35a 100644
--- a/src/Filee.Engines/Media/FrameSequenceWriter.cs
+++ b/src/Filee.Engines/Media/FrameSequenceWriter.cs
@@ -2,8 +2,10 @@
// 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 System.Globalization;
using Filee.Core.Conversion;
using Filee.Core.Formats;
+using Filee.Core.Presets;
using Filee.Engines.Archives;
namespace Filee.Engines.Media;
@@ -23,10 +25,22 @@ internal static class FrameSequenceWriter
IProgress<double>? progress, CancellationToken cancellationToken)
{
var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");
+ var extension = FormatRegistry.Get(step.To).PrimaryExtension;
+ var interval = Math.Max(1, step.Preset.Media.FrameInterval);
+ var frameCount = EstimatedFrames(info, interval);
+ if (frameCount > MediaOptions.MaxFrames)
+ {
+ throw new ConversionRefusedException("error.too_many_frames",
+ string.Create(CultureInfo.InvariantCulture, $"{frameCount:N0} > {MediaOptions.MaxFrames:N0}"));
+ }
+
var output = step.Output.Allocate("", FolderSuffix);
if (output is null)
return [];
+ if (frameCount is { } count && FreeSpace(output) is { } free && EstimatedBytes(video, extension, count) is var needed && needed > free)
+ throw new ConversionRefusedException("error.not_enough_space", $"{Gigabytes(needed)} > {Gigabytes(free)}");
+
// 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]}");
@@ -34,11 +48,10 @@ internal static class FrameSequenceWriter
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);
+ interval, step.Preset.Media.FramesPerSecond);
await FfmpegConverter.RunPassAsync(ffmpeg, new FfmpegPass(arguments, 1), info.Duration, progress, 0, cancellationToken);
if (!Directory.EnumerateFiles(frames).Any())
@@ -54,4 +67,37 @@ internal static class FrameSequenceWriter
ArchiveFiles.TryDeleteFolder(staging);
}
}
+
+ /// <summary>Pictures the video gives: duration × frame rate ÷ interval; null when the file doesn't say.</summary>
+ internal static long? EstimatedFrames(MediaInfo info, int interval) =>
+ info.Duration is { TotalSeconds: > 0 } duration && info.Video is { FrameRate: > 0 } video
+ ? (long)Math.Ceiling(duration.TotalSeconds * video.FrameRate / Math.Max(1, interval))
+ : null;
+
+ /// <summary>
+ /// A generous guess of the pictures' size on disk: PNG about half of raw RGB (twice that for 10-bit video, which
+ /// becomes 16-bit PNG), JPG about a quarter byte per pixel at the usual qualities.
+ /// </summary>
+ internal static long EstimatedBytes(VideoStreamInfo video, string extension, long frames)
+ {
+ var pixels = (double)Math.Max(1, video.Width * video.SampleAspect) * Math.Max(1, video.Height);
+ var perPicture = extension == "png" ? pixels * 1.5 * (video.IsHighBitDepth ? 2 : 1) : pixels * 0.25;
+ return (long)Math.Min(perPicture * frames, long.MaxValue);
+ }
+
+ /// <summary>Free bytes on the drive of <paramref name="path"/>; null where that can't be read (some network shares).</summary>
+ private static long? FreeSpace(string path)
+ {
+ try
+ {
+ return Path.GetPathRoot(Path.GetFullPath(path)) is { Length: > 0 } root ? new DriveInfo(root).AvailableFreeSpace : null;
+ }
+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
+ private static string Gigabytes(long bytes) =>
+ string.Create(CultureInfo.InvariantCulture, $"{bytes / 1e9:0.0} GB");
}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index c2a123d1..7e3e765d 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -671,6 +671,8 @@ public class RenderTests
var vm = new PresetEditorViewModel(preset, loc);
Assert.True(vm.ShowSaveEveryFrame);
vm.SaveEveryFrame = true;
+ vm.FrameInterval = 5;
+ Assert.Equal("One minute of 30 fps video gives 360 pictures, at most 100,000 per video.", vm.FrameEstimate);
vm.FrameInterval = 5000; // out of range: clamped
Assert.True(vm.Apply());
Assert.True(preset.Media.SaveEveryFrame);
diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.cs
index 26119397..7889ae38 100644
--- a/tests/Filee.Core.Tests/FakeConverter.cs
+++ b/tests/Filee.Core.Tests/FakeConverter.cs
@@ -16,12 +16,17 @@ internal sealed class FakeConverter(string id, params ConversionEdge[] edges) :
public bool Throw { get; set; }
+ /// <summary>Thrown instead of converting, when set.</summary>
+ public Exception? Failure { get; set; }
+
public EngineStatus GetStatus() => Available ? EngineStatus.Available() : EngineStatus.Unavailable("engine.reason.not_installed");
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
{
if (Throw)
throw new InvalidOperationException("boom");
+ if (Failure is not null)
+ throw Failure;
var written = new List<string>();
for (var i = 0; i < OutputsPerInput; i++)
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index 7cfb7334..b5317989 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -132,6 +132,24 @@ public class JobQueueTests
Assert.Equal([("mp4", "png", false)], ffmpeg.Steps);
}
+ [Fact]
+ public async Task A_refused_conversion_says_why_in_the_users_language()
+ {
+ using var dir = new TempDir();
+ var video = dir.File("long.mp4");
+ var ffmpeg = new FakeConverter("ffmpeg", new ConversionEdge("mp4", "png", FrameSequence: true))
+ {
+ Failure = new ConversionRefusedException("error.too_many_frames", "216,000 > 100,000"),
+ };
+ await using var queue = new JobQueue(new ConverterCatalog([ffmpeg]));
+
+ var job = await Run(queue, [video], new Preset { TargetFormat = "png", Media = { SaveEveryFrame = true } });
+
+ var file = job.Files.Single();
+ Assert.Equal(FileState.Failed, file.State);
+ Assert.Equal(("error.too_many_frames", "216,000 > 100,000"), (file.ErrorKey, file.ErrorDetail));
+ }
+
[Fact]
public async Task Multi_step_route_keeps_intermediates_out_of_the_output_folder()
{
diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.cs
index 9a89d434..5976c89e 100644
--- a/tests/Filee.Engines.Tests/MediaTests.cs
+++ b/tests/Filee.Engines.Tests/MediaTests.cs
@@ -924,6 +924,25 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal("out_frames/frame_%06d.png", png[^1]);
}
+ [Fact]
+ public void Every_frame_is_estimated_before_anything_is_written()
+ {
+ var hd = new VideoStreamInfo(1920, 1080, 1, 0, 30);
+ var hour = new MediaInfo(TimeSpan.FromHours(1), hd, null, null);
+ // An hour at 30 fps: 108,000 pictures, over the limit; every second frame is fine.
+ Assert.Equal(108_000, FrameSequenceWriter.EstimatedFrames(hour, 1));
+ Assert.Equal(54_000, FrameSequenceWriter.EstimatedFrames(hour, 2));
+ Assert.True(FrameSequenceWriter.EstimatedFrames(hour, 1) > MediaOptions.MaxFrames);
+ // Unknown duration or frame rate: no estimate, no refusal.
+ Assert.Null(FrameSequenceWriter.EstimatedFrames(hour with { Duration = null }, 1));
+ Assert.Null(FrameSequenceWriter.EstimatedFrames(hour with { Video = hd with { FrameRate = 0 } }, 1));
+
+ // Full HD: about 3 MB a PNG, half a MB a JPG; 10-bit video becomes 16-bit PNG, twice the size.
+ Assert.Equal(3_110_400, FrameSequenceWriter.EstimatedBytes(hd, "png", 1));
+ Assert.Equal(518_400, FrameSequenceWriter.EstimatedBytes(hd, "jpg", 1));
+ Assert.Equal(6_220_800, FrameSequenceWriter.EstimatedBytes(hd with { PixelFormat = "yuv420p10le" }, "png", 1));
+ }
+
[Fact]
public async Task Every_frame_of_a_variable_frame_rate_video_is_saved_once()
{