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
feat(core): add video max size percentage option and calculation
Gian Abi Firdausb879cf0963f1
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.csindex 2c050611..aedba5da 100644--- a/src/Filee.Core/Conversion/JobQueue.cs+++ b/src/Filee.Core/Conversion/JobQueue.cs@@ -862,7 +862,7 @@ public sealed partial class JobQueue : IAsyncDisposableif (preset.Image.ChangesSpeed && !(isLast && finalOutput))preset = AtOriginalSpeed(preset);// Likewise the size limit: only the result has to fit, not a picture passed to the next engine.- if ((preset.Image.MaxSizeMb > 0 || preset.Image.MinSizeMb > 0 || preset.Media.MaxSizeMb > 0) && !(isLast && finalOutput))+ if ((preset.Image.MaxSizeMb > 0 || preset.Image.MinSizeMb > 0 || preset.Media.MaxSizeMb > 0 || preset.Media.MaxSizePercent > 0) && !(isLast && finalOutput))preset = WithoutSizeLimit(preset);var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir, step.FrameSequence,key => file.NoticeKey = key, step.MotionPhoto, step.LivePhoto, fonts =>@@ -894,7 +894,7 @@ public sealed partial class JobQueue : IAsyncDisposableawait FinishPdfsAsync(runWith, 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(runWith, inputs);+ SizeLimit.Check(runWith, inputs, file.SourcePath);// The minimum (#662), on the pictures themselves: after the source was copied over, before they go into a ZIP.if (finalOutput && SizeLimit.IsUnderMinimum(runWith, inputs))file.UnderMinimumSize = true;@@ -965,6 +965,7 @@ public sealed partial class JobQueue : IAsyncDisposablecopy.Image.MaxSizeMb = 0;copy.Image.MinSizeMb = 0;copy.Media.MaxSizeMb = 0;+ copy.Media.MaxSizePercent = 0;return copy;}diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.csindex 6183cc4e..7e6f7111 100644--- a/src/Filee.Core/Presets/Preset.cs+++ b/src/Filee.Core/Presets/Preset.cs@@ -916,6 +916,12 @@ public sealed class MediaOptions/// </summary>public double MaxSizeMb { get; set; }+ /// <summary>+ /// Keep each video under this percentage (1–99) of the original file's size (#680); 0 = off. One of+ /// <see cref="MaxSizeMb"/> and this is in use at a time.+ /// </summary>+ public int MaxSizePercent { get; set; }+/// <summary>Audio bitrate in kbit/s for lossy audio; 0 uses a good default for the format.</summary>public int AudioBitrateKbps { get; set; }diff --git a/src/Filee.Core/Presets/SizeLimit.cs b/src/Filee.Core/Presets/SizeLimit.csindex 709f6399..ac932ad1 100644--- a/src/Filee.Core/Presets/SizeLimit.cs+++ b/src/Filee.Core/Presets/SizeLimit.cs@@ -12,8 +12,11 @@ public static class SizeLimit/// <summary>Megabytes of 1,000,000 bytes.</summary>public static long Bytes(double megabytes) => (long)(megabytes * 1_000_000);+ /// <summary>A percentage (1–99) of an original file's size in bytes (#680).</summary>+ public static long Bytes(long sourceBytes, int percent) => (long)(sourceBytes * (percent / 100.0));+/// <summary>- /// Megabytes of 1,000,000 bytes, to the nearest byte: a minimum truncated like <see cref="Bytes"/> would let a+ /// Megabytes of 1,000,000 bytes, to the nearest byte: a minimum truncated like <see cref="Bytes(double)"/> would let a/// file one byte short through (1.001 MB is 1,000,999.9999… bytes as a double)./// </summary>public static long MinimumBytes(double megabytes) => (long)Math.Round(megabytes * 1_000_000, MidpointRounding.AwayFromZero);@@ -23,11 +26,31 @@ public static class SizeLimit? string.Create(CultureInfo.InvariantCulture, $"{size / 1e3:0.##} KB > {limit / 1e3:0.##} KB"): string.Create(CultureInfo.InvariantCulture, $"{size / 1e6:0.##} MB > {limit / 1e6:0.##} MB");+ /// <summary>The limit for a video target in bytes; 0 = none. Can come from <see cref="MediaOptions.MaxSizePercent"/> or <see cref="MediaOptions.MaxSizeMb"/>.</summary>+ public static long ForVideo(MediaOptions media, string? sourcePath = null)+ {+ if (media.MaxSizePercent > 0 && sourcePath is not null && File.Exists(sourcePath))+ return Bytes(new FileInfo(sourcePath).Length, media.MaxSizePercent);+ if (media.MaxSizeMb > 0)+ return Bytes(media.MaxSizeMb);+ return 0;+ }++ /// <summary>The limit for a video target in bytes; 0 = none.</summary>+ public static long ForVideo(MediaOptions media, long sourceBytes)+ {+ if (media.MaxSizePercent > 0 && sourceBytes > 0)+ return Bytes(sourceBytes, media.MaxSizePercent);+ if (media.MaxSizeMb > 0)+ return Bytes(media.MaxSizeMb);+ return 0;+ }+/// <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+ public static long For(Preset preset, string path, string? sourcePath = null) => 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),+ FormatCategory.Video => ForVideo(preset.Media, sourcePath),_ => 0,};@@ -35,11 +58,11 @@ public static class SizeLimit/// 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)+ public static void Check(Preset preset, IEnumerable<string> outputs, string? sourcePath = null){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)+ if (For(preset, output, sourcePath) 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, IsImage(output)));}}diff --git a/tests/Filee.Core.Tests/SizeLimitTests.cs b/tests/Filee.Core.Tests/SizeLimitTests.csindex d26d213c..a02568a2 100644--- a/tests/Filee.Core.Tests/SizeLimitTests.cs+++ b/tests/Filee.Core.Tests/SizeLimitTests.cs@@ -248,4 +248,70 @@ public class SizeLimitTests// A new list each time: adding one never changes the next.Assert.NotSame(places[0], BuiltInData.PlacePresets()[0]);}++ [Fact]+ public void A_percentage_limit_computes_correct_bytes()+ {+ Assert.Equal(25_000_000, SizeLimit.Bytes(100_000_000L, 25));+ Assert.Equal(5_000_000, SizeLimit.Bytes(10_000_000L, 50));+ Assert.Equal(12_345_678, SizeLimit.Bytes(123_456_789L, 10));+ }++ [Fact]+ public void ForVideo_calculates_limit_from_percent_or_megabytes()+ {+ var percentPreset = new MediaOptions { MaxSizePercent = 25 };+ Assert.Equal(25_000_000, SizeLimit.ForVideo(percentPreset, 100_000_000L));++ var mbPreset = new MediaOptions { MaxSizeMb = 10 };+ Assert.Equal(10_000_000, SizeLimit.ForVideo(mbPreset, 100_000_000L));++ var nonePreset = new MediaOptions();+ Assert.Equal(0, SizeLimit.ForVideo(nonePreset, 100_000_000L));++ using var dir = new TempDir();+ var video = dir.File("source.mp4", new string('v', 10_000));+ Assert.Equal(2_500, SizeLimit.ForVideo(percentPreset, video));+ }++ [Fact]+ public async Task Video_percentage_limit_clears_on_intermediate_steps()+ {+ using var dir = new TempDir();+ var clip = dir.File("clip.avi");+ var first = new FakeConverter("first", new ConversionEdge("avi", "mkv"));+ var second = new FakeConverter("second", new ConversionEdge("mkv", "mp4"));+ await using var queue = new JobQueue(new ConverterCatalog([first, second]));+ var preset = new Preset { TargetFormat = "mp4", Media = { MaxSizePercent = 50 } };++ await queue.RunAsync(new ConversionJob([clip], preset, "MP4"));++ var middle = Assert.Single(first.Presets);+ Assert.Equal(0, middle.Media.MaxSizePercent);+ var last = Assert.Single(second.Presets);+ Assert.Equal(50, last.Media.MaxSizePercent);+ Assert.Equal(50, preset.Media.MaxSizePercent);+ }++ [Fact]+ public async Task A_video_result_over_percentage_limit_is_refused()+ {+ using var dir = new TempDir();+ // Source is 10,000 bytes. With 20% limit, max allowed is 2,000 bytes.+ var source = dir.File("source.mp4", new string('a', 10_000));+ // FakeConverter writes 3,000 bytes output, which exceeds 2,000 bytes.+ var fake = new FakeConverter("ffmpeg", new ConversionEdge("mp4", "mp4"))+ {+ Content = _ => new string('x', 3_000),+ };+ await using var queue = new JobQueue(new ConverterCatalog([fake]));+ var job = new ConversionJob([source], new Preset { TargetFormat = "mp4", Media = { MaxSizePercent = 20 } }, "MP4");++ 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);+ }}