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.

fix(video): fix percentage size limit handling, unit switching, and joins

Gian Abi Firdausca484bc98bf7
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 89ed3021..86f8c250 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -650,10 +650,14 @@ public sealed partial class PresetEditorViewModel : ObservableObject
{
if (Choices.Restore(oldValue, newValue, v => VideoSizeUnitChoice = v) || oldValue is null || oldValue.Value == newValue.Value)
return;
- OnPropertyChanged(nameof(VideoSizeMaximum));
+ var toPercent = newValue.Value == VideoSizeUnit.Percent;
+ if (!toPercent)
+ OnPropertyChanged(nameof(VideoSizeMaximum));
OnPropertyChanged(nameof(VideoSizeIncrement));
OnPropertyChanged(nameof(VideoSizeFormat));
OnPropertyChanged(nameof(VideoMaxSize));
+ if (toPercent)
+ OnPropertyChanged(nameof(VideoSizeMaximum));
}
/// <summary>
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index aedba5da..dfed43e5 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -539,7 +539,7 @@ public sealed partial class JobQueue : IAsyncDisposable
try
{
await write(output, progress);
- SizeLimit.Check(job.Preset, [output]); // joined media aren't fitted: one over the limit is refused (#553)
+ SizeLimit.Check(job.Preset, [output], joined.Select(f => f.SourcePath)); // joined media aren't fitted: one over the limit is refused (#553)
if (SizeLimit.IsUnderMinimum(job.Preset, [output]))
first.UnderMinimumSize = true;
first.Outputs.Add(output);
diff --git a/src/Filee.Core/Presets/SizeLimit.cs b/src/Filee.Core/Presets/SizeLimit.cs
index ac932ad1..ce975bac 100644
--- a/src/Filee.Core/Presets/SizeLimit.cs
+++ b/src/Filee.Core/Presets/SizeLimit.cs
@@ -29,8 +29,37 @@ public static class SizeLimit
/// <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))
+ if (media.MaxSizePercent > 0)
+ {
+ if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath))
+ throw new ConversionRefusedException("error.over_size_limit");
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. For joined sources, percentages apply to their combined size.</summary>
+ public static long ForVideo(MediaOptions media, IEnumerable<string>? sourcePaths)
+ {
+ if (media.MaxSizePercent > 0)
+ {
+ if (sourcePaths is null)
+ throw new ConversionRefusedException("error.over_size_limit");
+ long total = 0;
+ var any = false;
+ foreach (var path in sourcePaths)
+ {
+ if (string.IsNullOrEmpty(path) || !File.Exists(path))
+ throw new ConversionRefusedException("error.over_size_limit");
+ total += new FileInfo(path).Length;
+ any = true;
+ }
+ if (!any)
+ throw new ConversionRefusedException("error.over_size_limit");
+ return Bytes(total, media.MaxSizePercent);
+ }
if (media.MaxSizeMb > 0)
return Bytes(media.MaxSizeMb);
return 0;
@@ -39,8 +68,12 @@ public static class SizeLimit
/// <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)
+ if (media.MaxSizePercent > 0)
+ {
+ if (sourceBytes <= 0)
+ throw new ConversionRefusedException("error.over_size_limit");
return Bytes(sourceBytes, media.MaxSizePercent);
+ }
if (media.MaxSizeMb > 0)
return Bytes(media.MaxSizeMb);
return 0;
@@ -54,6 +87,14 @@ public static class SizeLimit
_ => 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, IEnumerable<string>? sourcePaths) => FormatRegistry.Detect(path)?.Category switch
+ {
+ FormatCategory.Image when preset.Image.MaxSizeMb > 0 => Bytes(preset.Image.MaxSizeMb),
+ FormatCategory.Video => ForVideo(preset.Media, sourcePaths),
+ _ => 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").
@@ -67,6 +108,18 @@ public static class SizeLimit
}
}
+ /// <summary>
+ /// Refuses when a result is over its limit. For joined sources, percentages apply to their combined size.
+ /// </summary>
+ public static void Check(Preset preset, IEnumerable<string> outputs, IEnumerable<string>? sourcePaths)
+ {
+ foreach (var output in outputs)
+ {
+ if (For(preset, output, sourcePaths) 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)));
+ }
+ }
+
/// <summary>A picture result's minimum in bytes (#662); 0 = none, also for anything that isn't a picture.</summary>
private static long Minimum(Preset preset, string path) =>
preset.Image.MinSizeMb > 0 && IsImage(path) ? MinimumBytes(preset.Image.MinSizeMb) : 0;
diff --git a/tests/Filee.App.Tests/PresetSizeRangeTests.cs b/tests/Filee.App.Tests/PresetSizeRangeTests.cs
index 4050440c..355588c4 100644
--- a/tests/Filee.App.Tests/PresetSizeRangeTests.cs
+++ b/tests/Filee.App.Tests/PresetSizeRangeTests.cs
@@ -232,17 +232,19 @@ public class PresetSizeRangeTests
Assert.Equal($"photo.jpg — {loc["notice.under_min_size"]}", job.Notices);
}
- [AvaloniaFact]
- public void Video_size_unit_switch_keeps_each_value_separately()
+ [AvaloniaTheory]
+ [InlineData(25)]
+ [InlineData(500)]
+ public void Video_size_unit_switch_keeps_each_value_separately(int initialMb)
{
TestServices.EnsureInitialized("en");
- var preset = new Preset { Name = "Video Preset", TargetFormat = "mp4", Media = { MaxSizeMb = 25 } };
+ var preset = new Preset { Name = "Video Preset", TargetFormat = "mp4", Media = { MaxSizeMb = initialMb } };
InEditor(preset, (editor, window) =>
{
Assert.Equal(VideoSizeUnit.MB, editor.VideoSizeUnitChoice.Value);
- Assert.Equal(25m, editor.VideoMaxSize);
+ Assert.Equal((decimal)initialMb, editor.VideoMaxSize);
- // Switch to percent: value should not turn into 25%, but be null or previous percent
+ // Switch to percent: value should not turn into 99% or initial MB, but be null or previous percent
editor.VideoSizeUnitChoice = editor.VideoSizeUnits.Single(u => u.Value == VideoSizeUnit.Percent);
Pump();
Assert.Null(editor.VideoMaxSize);
@@ -256,7 +258,7 @@ public class PresetSizeRangeTests
// Switch back to MB: original MB value is preserved
editor.VideoSizeUnitChoice = editor.VideoSizeUnits.Single(u => u.Value == VideoSizeUnit.MB);
Pump();
- Assert.Equal(25m, editor.VideoMaxSize);
+ Assert.Equal((decimal)initialMb, editor.VideoMaxSize);
Assert.Equal(4096m, editor.VideoSizeMaximum);
// Switch back to percent: percent value is preserved
diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.cs
index 3c2ed273..8dfd6d40 100644
--- a/tests/Filee.Core.Tests/FakeConverter.cs
+++ b/tests/Filee.Core.Tests/FakeConverter.cs
@@ -192,6 +192,8 @@ internal sealed class FakeJoiner : IMediaJoiner
/// <summary>Called when the join starts, before anything is written.</summary>
public Action? Joining { get; set; }
+ public int? OutputLength { get; set; }
+
public Task JoinAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Filee.Core.Presets.Preset preset,
string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken)
{
@@ -199,7 +201,10 @@ internal sealed class FakeJoiner : IMediaJoiner
if (Throw)
throw new InvalidOperationException("boom");
Inputs.AddRange(inputPaths);
- File.WriteAllText(outputPath, string.Join("|", inputPaths.Select(Path.GetFileName)));
+ if (OutputLength is { } length)
+ File.WriteAllBytes(outputPath, new byte[length]);
+ else
+ File.WriteAllText(outputPath, string.Join("|", inputPaths.Select(Path.GetFileName)));
return Task.CompletedTask;
}
}
diff --git a/tests/Filee.Core.Tests/MediaToolTests.cs b/tests/Filee.Core.Tests/MediaToolTests.cs
index 04a24f89..08d4107e 100644
--- a/tests/Filee.Core.Tests/MediaToolTests.cs
+++ b/tests/Filee.Core.Tests/MediaToolTests.cs
@@ -397,4 +397,44 @@ public class MediaToolTests
Assert.All(job.Files, f => Assert.Equal("error.conversion_failed", f.ErrorKey));
Assert.Empty(job.Outputs);
}
+
+ [Fact]
+ public async Task Merge_videos_over_percentage_limit_is_refused()
+ {
+ using var dir = new TempDir();
+ var first = dir.File("a.mp4", new string('a', 10_000));
+ var second = dir.File("b.mp4", new string('b', 10_000));
+ // Total source size is 20,000 bytes. With 25% limit, max allowed is 5,000 bytes.
+ // Joiner writes 8,000 bytes, which exceeds 5,000 bytes.
+ var joiner = new FakeJoiner { OutputLength = 8_000 };
+ await using var queue = new JobQueue(new ConverterCatalog([]), mediaJoiner: joiner);
+ var preset = BuiltIn("merge-videos").Clone();
+ preset.Media.MaxSizePercent = 25;
+
+ var job = await Run(queue, [first, second], preset);
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.All(job.Files, f => Assert.Equal("error.over_size_limit", f.ErrorKey));
+ Assert.Empty(job.Outputs);
+ }
+
+ [Fact]
+ public async Task Merge_videos_within_percentage_limit_succeeds()
+ {
+ using var dir = new TempDir();
+ var first = dir.File("a.mp4", new string('a', 10_000));
+ var second = dir.File("b.mp4", new string('b', 10_000));
+ // Total source size is 20,000 bytes. With 50% limit, max allowed is 10,000 bytes.
+ // Joiner writes 8,000 bytes, which fits within 10,000 bytes.
+ var joiner = new FakeJoiner { OutputLength = 8_000 };
+ await using var queue = new JobQueue(new ConverterCatalog([]), mediaJoiner: joiner);
+ var preset = BuiltIn("merge-videos").Clone();
+ preset.Media.MaxSizePercent = 50;
+
+ var job = await Run(queue, [first, second], preset);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.All(job.Files, f => Assert.Equal(FileState.Done, f.State));
+ Assert.Single(job.Outputs);
+ }
}
diff --git a/tests/Filee.Core.Tests/SizeLimitTests.cs b/tests/Filee.Core.Tests/SizeLimitTests.cs
index a02568a2..1285ee4c 100644
--- a/tests/Filee.Core.Tests/SizeLimitTests.cs
+++ b/tests/Filee.Core.Tests/SizeLimitTests.cs
@@ -274,6 +274,39 @@ public class SizeLimitTests
Assert.Equal(2_500, SizeLimit.ForVideo(percentPreset, video));
}
+ [Fact]
+ public void ForVideo_refuses_when_source_is_missing_or_cannot_be_measured()
+ {
+ var percentPreset = new MediaOptions { MaxSizePercent = 25 };
+ var exNull = Assert.Throws<ConversionRefusedException>(() => SizeLimit.ForVideo(percentPreset, (string?)null));
+ Assert.Equal("error.over_size_limit", exNull.ErrorKey);
+
+ var exMissing = Assert.Throws<ConversionRefusedException>(() => SizeLimit.ForVideo(percentPreset, "C:/does_not_exist.mp4"));
+ Assert.Equal("error.over_size_limit", exMissing.ErrorKey);
+
+ var exZero = Assert.Throws<ConversionRefusedException>(() => SizeLimit.ForVideo(percentPreset, 0L));
+ Assert.Equal("error.over_size_limit", exZero.ErrorKey);
+ }
+
+ [Fact]
+ public void ForVideo_calculates_combined_limit_for_joined_sources()
+ {
+ var percentPreset = new MediaOptions { MaxSizePercent = 50 };
+ using var dir = new TempDir();
+ var video1 = dir.File("video1.mp4", new string('a', 10_000));
+ var video2 = dir.File("video2.mp4", new string('b', 30_000));
+
+ // Total source size is 40,000 bytes. 50% = 20,000 bytes.
+ Assert.Equal(20_000, SizeLimit.ForVideo(percentPreset, [video1, video2]));
+
+ // Missing source among joined sources refuses
+ var ex = Assert.Throws<ConversionRefusedException>(() => SizeLimit.ForVideo(percentPreset, [video1, "C:/missing.mp4"]));
+ Assert.Equal("error.over_size_limit", ex.ErrorKey);
+
+ var exEmpty = Assert.Throws<ConversionRefusedException>(() => SizeLimit.ForVideo(percentPreset, (IEnumerable<string>?)null));
+ Assert.Equal("error.over_size_limit", exEmpty.ErrorKey);
+ }
+
[Fact]
public async Task Video_percentage_limit_clears_on_intermediate_steps()
{