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.

Size limit: refuse what no engine fitted, one capped video encode, decimal MB

cre8ive-marketing87cfb1e20691
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index fc742a82..2129554a 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -83,6 +83,7 @@
"error.ocr_needs_tesseract": "Apple Vision kann diese Sprache nicht lesen. Installiere Tesseract unter Einstellungen → Module",
"error.too_many_frames": "Zu viele Einzelbilder zum Speichern. Erhöhe den Wert für „Jedes n-te Einzelbild“",
"error.too_many_pictures": "Zu viele Bilder für ein Video. Teile sie auf mehrere Videos auf",
+ "error.over_size_limit": "Es lässt sich nicht klein genug für das Größenlimit machen",
"error.not_enough_space": "Nicht genügend freier Speicherplatz für die Bilder",
"error.no_motion_photo": "Dieses Foto enthält kein für Filee lesbares Video (Android Motion Photo oder iPhone Live Photo mit zugehöriger MOV-Datei im selben Ordner)",
"error.live_photo_start": "Der Clip beginnt nach dem Ende dieses Videos. Wähle einen früheren „Clipbeginn“",
@@ -342,6 +343,10 @@
"preset.motion_photo_android": "Motion Photo (Android)",
"preset.compress_image": "Bild komprimieren",
"preset.compress_video": "Video komprimieren",
+ "preset.for_email": "Video für E-Mail (unter 18 MB)",
+ "preset.for_discord": "Video für Discord (unter 10 MB)",
+ "preset.for_whatsapp": "Video für WhatsApp (720p, unter 16 MB)",
+ "preset.for_instagram": "Foto für Instagram (JPG, 1080 px breit)",
"preset.video_from_images": "Video aus Bildern",
"preset.extract_audio": "Ton extrahieren",
"preset.merge_videos": "Videos zusammenführen",
@@ -570,6 +575,8 @@
"tags.remove": "Entfernen",
"presets.title": "Vorlagen",
"presets.add": "Neu",
+ "presets.add_empty": "Leere Vorlage",
+ "presets.add_ready": "Fertig, je nachdem, wohin die Datei geht:",
"presets.duplicate": "Duplizieren",
"presets.delete": "Löschen",
"presets.save": "Speichern",
@@ -696,6 +703,9 @@
"presets.media_quality.Small": "Klein (zum Teilen)",
"presets.max_height": "Maximale Höhe",
"presets.max_height.original": "Original",
+ "presets.max_size": "Größenlimit (MB)",
+ "presets.max_size_hint_image": "0 = kein Limit. Ein größeres Bild wird erneut gespeichert, zuerst mit geringerer Qualität, dann kleiner, bis es passt.",
+ "presets.max_size_hint_video": "0 = kein Limit. Ein größeres Video wird mit der Bitrate kodiert, die seine Länge zulässt.",
"presets.audio_bitrate": "Audio-Bitrate",
"presets.audio_bitrate.auto": "Automatisch",
"presets.remove_audio": "Ton entfernen",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index b570b0b5..40ef6bc9 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -614,7 +614,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowMediaQuality => TargetIsLossyMedia;
public bool ShowMaxHeight => TargetIsVideo;
/// <summary>A size limit for a converted video; a clip is cut, not fitted.</summary>
- public bool ShowVideoMaxSize => TargetCategory == FormatCategory.Video && !_original.IsClipTool;
+ public bool ShowVideoMaxSize => TargetCategory == FormatCategory.Video && !_original.IsClipTool
+ // Not where nothing fits it: a join or slideshow, or VOB and DV, which have a fixed bitrate.
+ && !_original.Media.JoinIntoOne && !_isSlideshow && TargetId is not ("vob" or "dv");
public bool ShowAudioBitrate => TargetIsLossyMedia;
public bool ShowRemoveAudio => TargetIsVideo;
public bool ShowArchive => TargetCategory == FormatCategory.Archive;
diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml b/src/Filee.App/Views/Pages/PresetsPage.axaml
index 70116c84..f0e7c968 100644
--- a/src/Filee.App/Views/Pages/PresetsPage.axaml
+++ b/src/Filee.App/Views/Pages/PresetsPage.axaml
@@ -19,14 +19,11 @@
<TextBlock Text="{DynamicResource presets.add}" />
</StackPanel>
<Button.Flyout>
+ <!-- The ready-made presets are added below the heading from PlacePresets (code-behind). -->
<MenuFlyout Placement="BottomEdgeAlignedLeft">
<MenuItem Header="{DynamicResource presets.add_empty}" Command="{Binding AddCommand}" />
<Separator />
<MenuItem Header="{DynamicResource presets.add_ready}" IsEnabled="False" />
- <MenuItem Header="{Binding PlacePresets[0].Name}" Command="{Binding AddPlaceCommand}" CommandParameter="{Binding PlacePresets[0].Preset}" />
- <MenuItem Header="{Binding PlacePresets[1].Name}" Command="{Binding AddPlaceCommand}" CommandParameter="{Binding PlacePresets[1].Preset}" />
- <MenuItem Header="{Binding PlacePresets[2].Name}" Command="{Binding AddPlaceCommand}" CommandParameter="{Binding PlacePresets[2].Preset}" />
- <MenuItem Header="{Binding PlacePresets[3].Name}" Command="{Binding AddPlaceCommand}" CommandParameter="{Binding PlacePresets[3].Preset}" />
</MenuFlyout>
</Button.Flyout>
</Button>
diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml.cs b/src/Filee.App/Views/Pages/PresetsPage.axaml.cs
index 82fddc4f..37d49788 100644
--- a/src/Filee.App/Views/Pages/PresetsPage.axaml.cs
+++ b/src/Filee.App/Views/Pages/PresetsPage.axaml.cs
@@ -1,8 +1,27 @@
using Avalonia.Controls;
+using Filee.App.ViewModels.Pages;
namespace Filee.App.Views.Pages;
public partial class PresetsPage : UserControl
{
- public PresetsPage() => InitializeComponent();
+ private const int FixedMenuItems = 3; // "Empty preset", the separator and the heading
+
+ public PresetsPage()
+ {
+ InitializeComponent();
+ DataContextChanged += (_, _) => FillAddMenu();
+ }
+
+ /// <summary>One "New" menu item per ready-made preset, so the menu follows the list (#553).</summary>
+ private void FillAddMenu()
+ {
+ var menu = (MenuFlyout)AddPresetButton.Flyout!; // a flyout isn't in the page's name scope
+ while (menu.Items.Count > FixedMenuItems)
+ menu.Items.RemoveAt(menu.Items.Count - 1);
+ if (DataContext is not PresetsPageViewModel vm)
+ return;
+ foreach (var place in vm.PlacePresets)
+ menu.Items.Add(new MenuItem { Header = place.Name, Command = vm.AddPlaceCommand, CommandParameter = place.Preset });
+ }
}
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 92c726b4..3babce30 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -460,6 +460,7 @@ public sealed class JobQueue : IAsyncDisposable
try
{
await _mediaJoiner!.JoinAsync(inputs, output, target.Id, job.Preset, workDir, progress, job.CancellationToken);
+ SizeLimit.Check(job.Preset, [output]); // joins aren't fitted: one over the limit is refused (#553)
first.Outputs.Add(output);
foreach (var f in joined)
{
@@ -802,6 +803,9 @@ public sealed class JobQueue : IAsyncDisposable
// Watermark, page numbers, password: on every PDF this file became, from whichever engine.
if (finalOutput && job.Preset.TargetFormat == "pdf")
await FinishPdfsAsync(job.Preset, inputs, ct);
+ // The size limit (#553): a result the engine couldn't fit (HEIC, a render, an animation) isn't handed over.
+ if (finalOutput)
+ SizeLimit.Check(job.Preset, inputs);
if (zipResult && inputs.Count > 0)
inputs = PackZip(job, file, index, inputs, ct);
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index dcd2db28..ea4d79a6 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -312,8 +312,8 @@ public sealed class ImageOptions
public int Quality { get; set; } = 90;
/// <summary>
- /// Keep each picture under this many MB (e.g. for email); 0 = no limit. A larger one is saved again at a lower
- /// quality, then smaller, until it fits (#553).
+ /// Keep each picture under this many MB of 1,000,000 bytes; 0 = no limit. A larger one is saved again at a lower
+ /// quality, then smaller (down to a long edge of 640 px), until it fits (#553).
/// </summary>
public double MaxSizeMb { get; set; }
@@ -610,8 +610,8 @@ public sealed class MediaOptions
public int MaxHeight { get; set; }
/// <summary>
- /// Keep each video under this many MB (WhatsApp 16, Discord 10, email 20 …); 0 = no limit. A larger one is
- /// encoded again at the bitrate its length allows (#553).
+ /// Keep each video under this many MB of 1,000,000 bytes (WhatsApp 16, Discord 10, email 18 …); 0 = no limit. Its
+ /// bitrate is capped at what its length allows, and it is encoded once more if it still misses (#553).
/// </summary>
public double MaxSizeMb { get; set; }
diff --git a/src/Filee.Core/Presets/SizeLimit.cs b/src/Filee.Core/Presets/SizeLimit.cs
new file mode 100644
index 00000000..ea9fb1fa
--- /dev/null
+++ b/src/Filee.Core/Presets/SizeLimit.cs
@@ -0,0 +1,39 @@
+// "Size limit" (#553): megabytes as Filee shows sizes and as mail and chat services count them, and the check that
+// no result over a preset's limit is handed over.
+
+using System.Globalization;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+
+namespace Filee.Core.Presets;
+
+public static class SizeLimit
+{
+ /// <summary>Megabytes of 1,000,000 bytes.</summary>
+ public static long Bytes(double megabytes) => (long)(megabytes * 1_000_000);
+
+ /// <summary>"12.3 MB > 10 MB", in the same megabytes.</summary>
+ public static string Describe(long size, long limit) =>
+ string.Create(CultureInfo.InvariantCulture, $"{size / 1e6:0.##} MB > {limit / 1e6:0.##} MB");
+
+ /// <summary>The limit for a result of <paramref name="path"/>'s kind: pictures and videos have their own; 0 = none.</summary>
+ public static long For(Preset preset, string path) => FormatRegistry.Detect(path)?.Category switch
+ {
+ FormatCategory.Image when preset.Image.MaxSizeMb > 0 => Bytes(preset.Image.MaxSizeMb),
+ FormatCategory.Video when preset.Media.MaxSizeMb > 0 => Bytes(preset.Media.MaxSizeMb),
+ _ => 0,
+ };
+
+ /// <summary>
+ /// Refuses when a result is over its limit. The engines fit pictures and videos where they can; this catches the
+ /// routes they don't (HEIC, CAD and 3D renders, animations and pages, joined videos, "Remove metadata").
+ /// </summary>
+ public static void Check(Preset preset, IEnumerable<string> outputs)
+ {
+ foreach (var output in outputs)
+ {
+ if (For(preset, output) is > 0 and var limit && File.Exists(output) && new FileInfo(output).Length is var size && size > limit)
+ throw new ConversionRefusedException("error.over_size_limit", Describe(size, limit));
+ }
+ }
+}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
index b1359444..1296655a 100644
--- a/src/Filee.Engines/Magick/ImageEncoder.cs
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -415,18 +415,22 @@ internal static class ImageEncoder
if (path is null)
continue;
frames[i].Write(path, format);
- // shortcut: only single pictures are fitted to the size limit, not animations or multi-page files written above.
+ // Animations and multi-page files written above aren't fitted: the queue refuses them when they're too large.
if (options is { MaxSizeMb: > 0 })
- FitToSize(frames[i], path, format, (long)(options.MaxSizeMb * 1024 * 1024));
+ FitToSize(frames[i], path, format, SizeLimit.Bytes(options.MaxSizeMb));
written.Add(path);
}
return written;
}
+ /// <summary>A fitted picture is never made smaller than this long edge (nor than its own): below it, it's a thumbnail.</summary>
+ internal const int MinFittedLongEdge = 640;
+
/// <summary>
/// Saves <paramref name="image"/> again until <paramref name="path"/> is at most <paramref name="limit"/> bytes: a
- /// lower quality first (down to 50, where a lossy format still looks fine), then fewer pixels. Refuses when even a
- /// tiny picture is too big, rather than handing over a file that breaks the limit.
+ /// lower quality first (down to 50, where a lossy format still looks fine), then fewer pixels, but never below a
+ /// long edge of <see cref="MinFittedLongEdge"/>. Refuses when it still doesn't fit, rather than hand over a file
+ /// that breaks the limit or a thumbnail.
/// </summary>
internal static void FitToSize(IMagickImage<byte> image, string path, MagickFormat format, long limit)
{
@@ -435,21 +439,25 @@ internal static class ImageEncoder
return;
using var copy = image.Clone();
var lossy = format is MagickFormat.Jpeg or MagickFormat.WebP or MagickFormat.Avif or MagickFormat.Jxl or MagickFormat.Jp2;
- for (var attempt = 0; attempt < 12 && size > limit; attempt++)
+ var floor = Math.Min(MinFittedLongEdge, Math.Max(copy.Width, copy.Height));
+ while (size > limit)
{
if (lossy && copy.Quality > 50)
copy.Quality = Math.Max(50, copy.Quality - 10);
else
{
- // The file shrinks about as the pixel count does: aim a little under the limit.
- var scale = Math.Clamp(Math.Sqrt((double)limit / size) * 0.95, 0.3, 0.9);
- copy.Resize(new MagickGeometry((uint)Math.Max(1, copy.Width * scale), (uint)Math.Max(1, copy.Height * scale)));
+ var longEdge = Math.Max(copy.Width, copy.Height);
+ if (longEdge <= floor)
+ break;
+ // The file shrinks about as the pixel count does: aim a little under the limit, but not below the floor.
+ var scale = Math.Max(Math.Clamp(Math.Sqrt((double)limit / size) * 0.95, 0.3, 0.9), (double)floor / longEdge);
+ copy.Resize(new MagickGeometry((uint)Math.Max(1, Math.Round(copy.Width * scale)), (uint)Math.Max(1, Math.Round(copy.Height * scale))));
}
copy.Write(path, format);
size = new FileInfo(path).Length;
}
if (size > limit)
- throw new ConversionRefusedException("error.over_size_limit", $"{size / 1048576.0:0.##} MB > {limit / 1048576.0:0.##} MB");
+ throw new ConversionRefusedException("error.over_size_limit", SizeLimit.Describe(size, limit));
}
/// <summary>Writes one image as <paramref name="targetFormat"/> (APNG through <see cref="Apng"/>).</summary>
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index 0ab60772..a712cf16 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -168,6 +168,17 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
return [output];
}
+ // The size limit (#553): refused before anything is encoded when not even a low bitrate fits, else one encode with
+ // the bitrate capped at what fits (MediaEncoding.ForSizeLimit), and another at that bitrate only if it missed.
+ var limit = !still && media.MaxSizeMb > 0 && MediaEncoding.VideoTargets.ContainsKey(step.To) ? SizeLimit.Bytes(media.MaxSizeMb) : 0;
+ var kbps = 0;
+ if (limit > 0)
+ {
+ (media, kbps) = MediaEncoding.ForSizeLimit(media, info, limit);
+ if (kbps == 0 && info.Duration is { TotalSeconds: > 0 })
+ throw new ConversionRefusedException("error.over_size_limit", $"{info.Duration.Value.TotalSeconds:0} s in {media.MaxSizeMb:0.##} MB");
+ }
+
var encoders = still ? null : EncodersOf(ffmpeg);
// Hardware encoding (preset option): the first GPU encoder that passes its test encode, if any.
HardwareEncoder? hardware = null;
@@ -185,15 +196,17 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
? MediaEncoding.PlanStill(input, output, step.To, media, info)
: 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 passes = kbps > 0 ? MediaEncoding.WithMaxRate(Plan(hardware), kbps) : Plan(hardware);
// FFmpeg reports the position in the output, which a speed change makes longer or shorter.
var duration = still ? MediaEncoding.StillDuration : info.Duration / speed;
+ // With a size limit the first encode takes most of the bar, a second one (if needed) the rest.
+ var encoding = limit > 0 && progress is not null ? new Progress<double>(p => progress.Report(p * 0.9)) : progress;
try
{
await RunWithFallbackAsync(passes, hardware, Plan,
- planned => RunPassesAsync(ffmpeg, planned, output, duration, progress, cancellationToken), output, _logger, cancellationToken);
- if (!still && media.MaxSizeMb > 0 && MediaEncoding.VideoTargets.ContainsKey(step.To))
- await FitToSizeAsync(ffmpeg, step, input, output, info, encoders, cover, cancellationToken);
+ planned => RunPassesAsync(ffmpeg, planned, output, duration, encoding, cancellationToken), output, _logger, cancellationToken);
+ if (limit > 0)
+ await FitAgainAsync(ffmpeg, step, input, output, media, info, encoders, cover, limit, kbps, progress, cancellationToken);
}
catch
{
@@ -207,32 +220,25 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
}
/// <summary>
- /// The size limit (#553): a video over it is encoded again from the source at the bitrate its length allows, in
- /// software (every encoder takes -b:v) with the sound at 96 kbit/s at most. A bitrate is an average, so a second try
- /// aims lower by as much as the first one missed. Refuses when it can't fit, rather than hand over a file too large.
+ /// The size limit (#553), after the capped encode: usually it fits. A bitrate is an average, so when it missed, the
+ /// video is encoded once more at a bitrate as much lower as it missed by, on the rest of the progress bar. Refuses
+ /// when that still doesn't fit (or the length is unknown), rather than hand over a file too large.
/// </summary>
- private static async Task FitToSizeAsync(string ffmpeg, ConversionStep step, string input, string output, MediaInfo info,
- IReadOnlySet<string>? encoders, CoverExtras? cover, CancellationToken cancellationToken)
+ private static async Task FitAgainAsync(string ffmpeg, ConversionStep step, string input, string output, MediaOptions fitting,
+ MediaInfo info, IReadOnlySet<string>? encoders, CoverExtras? cover, long limit, int kbps, IProgress<double>? progress,
+ CancellationToken cancellationToken)
{
- var limit = (long)(step.Preset.Media.MaxSizeMb * 1024 * 1024);
var size = new FileInfo(output).Length;
- if (size <= limit)
- return;
- var fitting = step.Preset.Clone().Media;
- fitting.Quality = MediaQuality.Small; // never copies the video stream as it is
- fitting.HardwareEncoding = false;
- fitting.AudioBitrateKbps = fitting.AudioBitrateKbps is > 0 and < 96 ? fitting.AudioBitrateKbps : 96;
- var audio = fitting.RemoveAudio ? 0 : fitting.AudioBitrateKbps * info.AudioTracks.Count;
- var kbps = info.Duration is { TotalSeconds: > 0 } length ? MediaEncoding.FitBitrateKbps(limit, length.TotalSeconds, audio) : 0;
- for (var attempt = 0; attempt < 2 && kbps > 0 && size > limit; attempt++)
+ if (size > limit && kbps > 0)
{
+ kbps = (int)(kbps * (double)limit / size * 0.95);
+ var again = progress is null ? null : new Progress<double>(p => progress.Report(0.9 + p * 0.1));
var passes = MediaEncoding.AtBitrate(MediaEncoding.Plan(input, output, step.To, fitting, info, step.WorkDirectory, cover, encoders, null, 1), kbps);
- await RunPassesAsync(ffmpeg, passes, output, info.Duration, null, cancellationToken);
+ await RunPassesAsync(ffmpeg, passes, output, info.Duration, again, cancellationToken);
size = new FileInfo(output).Length;
- kbps = (int)(kbps * (double)limit / size * 0.95);
}
if (size > limit)
- throw new ConversionRefusedException("error.over_size_limit", $"{size / 1048576.0:0.##} MB > {limit / 1048576.0:0.##} MB");
+ throw new ConversionRefusedException("error.over_size_limit", SizeLimit.Describe(size, limit));
}
/// <remarks>
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index 55734dca..f433d5dc 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -382,7 +382,8 @@ internal static partial class MediaEncoding
/// </summary>
internal static bool CanCopyVideo(string target, VideoStreamInfo video, MediaOptions options)
{
- if (options.Quality == MediaQuality.Small || options.MaxHeight > 0 && video.DisplayHeight > Math.Max(16, options.MaxHeight)
+ // A size limit encodes the video, so its bitrate can be capped (ForSizeLimit).
+ if (options.Quality == MediaQuality.Small || options.MaxSizeMb > 0 || options.MaxHeight > 0 && video.DisplayHeight > Math.Max(16, options.MaxHeight)
|| video.Codec is not { } codec || !Remuxable.TryGetValue(target, out var codecs))
return false;
var takes = MediaCodecs.Effective(target, options.VideoCodec) switch
@@ -465,6 +466,48 @@ internal static partial class MediaEncoding
return video >= 100 ? video : 0;
}
+ /// <summary>
+ /// The options a video with a size limit is encoded with, and the video bitrate that fits (0 when the length is
+ /// unknown or nothing fits): the video is never copied as it is (<see cref="CanCopyVideo"/>), the sound is at most
+ /// 96 kbit/s a track, and no graphics chip encodes, since software rate control keeps to the cap.
+ /// </summary>
+ internal static (MediaOptions Options, int Kbps) ForSizeLimit(MediaOptions media, MediaInfo info, long limitBytes)
+ {
+ var fitting = new Preset { Media = media }.Clone().Media;
+ fitting.HardwareEncoding = false;
+ fitting.AudioBitrateKbps = fitting.AudioBitrateKbps is > 0 and < 96 ? fitting.AudioBitrateKbps : 96;
+ var audio = fitting.RemoveAudio ? 0 : fitting.AudioBitrateKbps * info.AudioTracks.Count;
+ var kbps = info.Duration is { TotalSeconds: > 0 } length ? FitBitrateKbps(limitBytes, length.TotalSeconds, audio) : 0;
+ return (fitting, kbps);
+ }
+
+ /// <summary>
+ /// The passes with the video's peaks capped at <paramref name="kbps"/> next to its constant quality: one encode,
+ /// never larger than without the cap and usually within the size limit. VP9 and libaom's "-b:v 0" becomes the cap.
+ /// </summary>
+ internal static IReadOnlyList<FfmpegPass> WithMaxRate(IReadOnlyList<FfmpegPass> passes, int kbps) =>
+ [.. passes.Select(pass => pass with { Arguments = WithMaxRate(pass.Arguments, kbps) })];
+
+ private static List<string> WithMaxRate(IReadOnlyList<string> args, int kbps)
+ {
+ var result = new List<string>();
+ for (var i = 0; i < args.Count; i++)
+ {
+ if (args[i] == "-b:v" && i + 1 < args.Count && args[i + 1] == "0")
+ {
+ result.AddRange(["-b:v", $"{kbps}k"]);
+ i++;
+ continue;
+ }
+ result.Add(args[i]);
+ if (args[i] is "-crf" or "-q:v" && i + 1 < args.Count)
+ {
+ result.AddRange([args[++i], "-maxrate", $"{kbps}k", "-bufsize", $"{kbps * 2}k"]);
+ }
+ }
+ return result;
+ }
+
/// <summary>The passes with the video at <paramref name="kbps"/> instead of a constant quality (CRF or quantizer).</summary>
internal static IReadOnlyList<FfmpegPass> AtBitrate(IReadOnlyList<FfmpegPass> passes, int kbps) =>
[.. passes.Select(pass => pass with { Arguments = AtBitrate(pass.Arguments, kbps) })];
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 54811ece..5412324c 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -481,6 +481,13 @@ public class RenderTests
Assert.Equal(25, added[^1].Media.MaxSizeMb);
Assert.Equal(16, whatsapp.Media.MaxSizeMb);
+ // Not where nothing could fit it: VOB and DV have a fixed bitrate.
+ editor.Target = editor.Targets.Single(t => t.Value == "vob");
+ Assert.False(editor.ShowVideoMaxSize);
+ editor.Target = editor.Targets.Single(t => t.Value == "mp4");
+ Assert.True(editor.ShowVideoMaxSize);
+ Assert.False(new PresetEditorViewModel(Filee.Core.Presets.BuiltInData.CreatePresets().First(p => p.JoinsIntoOneMedia), loc).ShowVideoMaxSize);
+
// A cleared box is no limit; a JPG target shows its own box, and a limit left behind by MP4 isn't kept.
editor.VideoMaxSizeMb = null;
editor.Target = editor.Targets.Single(t => t.Value == "jpg");
diff --git a/tests/Filee.Core.Tests/SizeLimitTests.cs b/tests/Filee.Core.Tests/SizeLimitTests.cs
index ffd89d7a..6289be76 100644
--- a/tests/Filee.Core.Tests/SizeLimitTests.cs
+++ b/tests/Filee.Core.Tests/SizeLimitTests.cs
@@ -27,6 +27,41 @@ public class SizeLimitTests
Assert.Equal(2, preset.Image.MaxSizeMb); // the user's preset itself is never changed
}
+ [Fact]
+ public async Task A_result_no_engine_fitted_is_refused_rather_than_handed_over_too_large()
+ {
+ // The fake engine writes its result as it is (like HEIC, a CAD render or an animation): the queue checks it.
+ using var dir = new TempDir();
+ var photo = dir.File("photo.jpg");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+ var job = new ConversionJob([photo], new Preset { TargetFormat = "png", Image = { MaxSizeMb = 0.000001 } }, "PNG");
+
+ await queue.RunAsync(job);
+
+ var file = Assert.Single(job.Files);
+ Assert.Equal(FileState.Failed, file.State);
+ Assert.Equal("error.over_size_limit", file.ErrorKey);
+ Assert.Empty(job.Outputs);
+ Assert.Equal([photo], Directory.GetFiles(dir.Path)); // nothing too large is left behind
+ }
+
+ [Fact]
+ public async Task A_result_within_the_limit_or_without_one_is_kept()
+ {
+ using var dir = new TempDir();
+ var photo = dir.File("photo.jpg");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+
+ var fits = new ConversionJob([photo], new Preset { TargetFormat = "png", Image = { MaxSizeMb = 1 } }, "PNG");
+ await queue.RunAsync(fits);
+ // A video limit says nothing about a picture.
+ var other = new ConversionJob([photo], new Preset { TargetFormat = "png", Media = { MaxSizeMb = 0.000001 }, Output = { FileNamePattern = "{name}_2" } }, "PNG");
+ await queue.RunAsync(other);
+
+ Assert.Equal(JobState.Completed, fits.State);
+ Assert.Equal(JobState.Completed, other.State);
+ }
+
[Fact]
public void The_presets_for_where_a_file_goes_are_offered_but_not_installed()
{
diff --git a/tests/Filee.Engines.Tests/SizeLimitTests.cs b/tests/Filee.Engines.Tests/SizeLimitTests.cs
index e1833865..43ce69ef 100644
--- a/tests/Filee.Engines.Tests/SizeLimitTests.cs
+++ b/tests/Filee.Engines.Tests/SizeLimitTests.cs
@@ -70,13 +70,64 @@ public class SizeLimitTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal("error.over_size_limit", refused.ErrorKey);
}
+ [Fact]
+ public void A_picture_is_never_made_a_thumbnail_to_fit()
+ {
+ // A tight limit for a big photo: it stops at a long edge of 640 px and refuses, instead of shrinking on.
+ var path = Path.Combine(fx.NewFolder(), "noise.jpg");
+ using var image = Noisy(2400, 1600);
+ image.Quality = 95;
+ image.Write(path, MagickFormat.Jpeg);
+
+ Assert.Throws<ConversionRefusedException>(() => ImageEncoder.FitToSize(image, path, MagickFormat.Jpeg, 20_000));
+ using var last = new MagickImage(path);
+ Assert.Equal((uint)ImageEncoder.MinFittedLongEdge, Math.Max(last.Width, last.Height));
+ }
+
+ [Fact]
+ public void Megabytes_are_a_million_bytes_as_the_services_count_them()
+ {
+ Assert.Equal(18_000_000, SizeLimit.Bytes(18));
+ Assert.Equal("18.87 MB > 18 MB", SizeLimit.Describe(18_874_368, 18_000_000));
+ }
+
[Fact]
public void The_bitrate_that_fits_leaves_room_for_the_sound_and_the_container()
{
- // 16 MB over 60 s with 96 kbit/s of sound: 16 × 1024² × 8 × 0.95 / 1000 / 60 = 2125 kbit/s, less 96.
- Assert.Equal(2029, MediaEncoding.FitBitrateKbps(16L * 1024 * 1024, 60, 96));
+ // 16 MB over 60 s with 96 kbit/s of sound: 16,000,000 × 8 × 0.95 / 1000 / 60 = 2026 kbit/s, less 96.
+ Assert.Equal(1930, MediaEncoding.FitBitrateKbps(SizeLimit.Bytes(16), 60, 96));
// An hour in 10 MB would be a smear: refused instead.
- Assert.Equal(0, MediaEncoding.FitBitrateKbps(10L * 1024 * 1024, 3600, 96));
+ Assert.Equal(0, MediaEncoding.FitBitrateKbps(SizeLimit.Bytes(10), 3600, 96));
+ }
+
+ [Fact]
+ public void The_first_encode_caps_the_bitrate_next_to_the_constant_quality()
+ {
+ FfmpegPass[] passes = [new(["-c:v", "libx264", "-crf", "23", "-c:a", "aac", "out.mp4"], 1),
+ new(["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "32", "out.webm"], 1)];
+
+ var capped = MediaEncoding.WithMaxRate(passes, 800);
+
+ Assert.Equal(["-c:v", "libx264", "-crf", "23", "-maxrate", "800k", "-bufsize", "1600k", "-c:a", "aac", "out.mp4"], capped[0].Arguments);
+ // VP9's constrained quality: CRF with the cap as its bitrate.
+ Assert.Equal(["-c:v", "libvpx-vp9", "-b:v", "800k", "-crf", "32", "-maxrate", "800k", "-bufsize", "1600k", "out.webm"], capped[1].Arguments);
+ }
+
+ [Fact]
+ public void A_size_limit_never_copies_the_video_or_uses_the_graphics_chip()
+ {
+ var video = new VideoStreamInfo(1920, 1080, 1, 0, 30, "h264", "yuv420p");
+ var info = new MediaInfo(TimeSpan.FromSeconds(60), video, new AudioStreamInfo(2, 48000, "aac"), null);
+ var media = new MediaOptions { MaxSizeMb = 16, HardwareEncoding = true };
+
+ var (fitting, kbps) = MediaEncoding.ForSizeLimit(media, info, SizeLimit.Bytes(16));
+
+ Assert.False(MediaEncoding.CanCopyVideo("mp4", video, fitting));
+ Assert.True(MediaEncoding.CanCopyVideo("mp4", video, new MediaOptions()));
+ Assert.False(fitting.HardwareEncoding);
+ Assert.Equal(96, fitting.AudioBitrateKbps);
+ Assert.Equal(1930, kbps);
+ Assert.True(media.HardwareEncoding); // the preset's own options are left alone
}
[Fact]
@@ -117,7 +168,7 @@ public class SizeLimitTests(EngineFixture fx) : IClassFixture<EngineFixture>
var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "mp4", Media = { MaxSizeMb = 1 }, Output = { FileNamePattern = "{name}_fit" } });
Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
- Assert.InRange(new FileInfo(Assert.Single(job.Outputs)).Length, 1, 1024 * 1024);
+ Assert.InRange(new FileInfo(Assert.Single(job.Outputs)).Length, 1, 1_000_000);
}
[Fact]
@@ -128,7 +179,10 @@ public class SizeLimitTests(EngineFixture fx) : IClassFixture<EngineFixture>
var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "mp4", Media = { MaxSizeMb = 0.05 }, Output = { FileNamePattern = "{name}_fit" } });
- Assert.Equal("error.over_size_limit", Assert.Single(job.Files).ErrorKey);
+ // Refused before encoding: 8 s in 50 KB leaves no bitrate for the picture.
+ var file = Assert.Single(job.Files);
+ Assert.Equal("error.over_size_limit", file.ErrorKey);
+ Assert.Equal("8 s in 0.05 MB", file.ErrorDetail);
Assert.Empty(job.Outputs);
}
}