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
Native memory audit: keep shared typefaces alive, stress tests under compaction
KnifeLemon68abb37085c6
diff --git a/src/Filee.App/Services/MemoryTrimmer.cs b/src/Filee.App/Services/MemoryTrimmer.csindex 85f94a38..6692529f 100644--- a/src/Filee.App/Services/MemoryTrimmer.cs+++ b/src/Filee.App/Services/MemoryTrimmer.cs@@ -74,7 +74,7 @@ public sealed class MemoryTrimmer : IDisposableInterlocked.Increment(ref _trims);}- /// <summary>Drops the engines' caches, collects and compacts every heap, then trims the working set (Windows).</summary>+ /// <summary>Drops the engines' caches, collects every generation, then trims the working set (Windows).</summary>internal static void Trim(ILogger log){try@@ -82,9 +82,11 @@ public sealed class MemoryTrimmer : IDisposablevar watch = Stopwatch.StartNew();var before = PrivateMegabytes();EngineCaches.Release();- // Without compacting: a compacting collection moves old objects, and native code (the UI's Skia renderer)- // can hold pointers into them; the test run crashed in Skia half a minute after such a trim. Garbage is- // freed and empty heap regions are decommitted all the same.+ // Without compacting: garbage is freed and empty heap regions are decommitted all the same. Compaction was+ // once blamed for a CI crash in Skia (sk_pngencoder_encode) after a trim; the cause was tests that let a+ // captured frame be collected while Avalonia encoded it (WriteableBitmap.Save encodes a snapshot that+ // doesn't own the pixels, and the finalizers this trim runs freed them). Nothing in Filee leaves native+ // code with a pointer into managed memory: NativeMemoryStressTests converts under constant compaction.GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: false);GC.WaitForPendingFinalizers();GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: false);diff --git a/src/Filee.Engines/Hwp/RhwpFonts.cs b/src/Filee.Engines/Hwp/RhwpFonts.csindex ed191e19..db11f4a5 100644--- a/src/Filee.Engines/Hwp/RhwpFonts.cs+++ b/src/Filee.Engines/Hwp/RhwpFonts.cs@@ -197,7 +197,9 @@ internal static class RhwpFontscontinue;if (OperatingSystem.IsWindows() || string.Equals(typeface.FamilyName, candidate, StringComparison.OrdinalIgnoreCase))return new InstalledFont(IsUsable(typeface), codePoint => typeface.GetGlyph(codePoint) != 0);- typeface.Dispose();+ // Not disposed: SkiaSharp hands out one wrapper per native typeface, so this may be the very object the+ // CAD font cache, Svg.Skia or the UI's font manager still draws with. Disposing it would leave them a+ // null handle (a native crash on their next call); the finalizer releases it once nobody uses it.}return null;});diff --git a/src/Filee.Engines/Infrastructure/EngineCaches.cs b/src/Filee.Engines/Infrastructure/EngineCaches.csindex 0e84003f..2045f502 100644--- a/src/Filee.Engines/Infrastructure/EngineCaches.cs+++ b/src/Filee.Engines/Infrastructure/EngineCaches.cs@@ -10,8 +10,10 @@ namespace Filee.Engines.Infrastructure;public static class EngineCaches{/// <summary>- /// Drops what the engines cache between conversions. Call only while no conversion runs: the next one looks- /// everything up again.+ /// Drops what the engines cache between conversions; the next one looks everything up again. Meant for idle+ /// times, but safe while a conversion runs (the trim's busy check can't stop one from starting right after it):+ /// the caches only forget references, nothing still in use is disposed, and each thread disposes its own+ /// measuring fonts the next time it measures. NativeMemoryStressTests releases them during conversions./// </summary>public static void Release(){diff --git a/tests/Filee.App.Tests/NativeMemoryRenderTests.cs b/tests/Filee.App.Tests/NativeMemoryRenderTests.csnew file mode 100644index 00000000..3efcd7b6--- /dev/null+++ b/tests/Filee.App.Tests/NativeMemoryRenderTests.cs@@ -0,0 +1,94 @@+// The UI's Skia rendering and the idle memory trim at the same time. The crop canvas swaps its preview and disposes+// the old one (as the crop overlay does), the donut redraws, and each frame is captured and encoded as PNG, while+// another thread runs MemoryTrimmer.Trim (engine caches released, every generation collected, finalizers run, working+// set trimmed) with compacting collections in between. Native code left with a pointer into moved or freed memory+// crashes the test host. FILEE_STRESS_SECONDS runs it longer.++using System.Runtime;+using Avalonia.Controls;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Media.Imaging;+using Avalonia.Threading;+using Filee.App.Controls;+using Filee.App.Services;+using ImageMagick;+using Microsoft.Extensions.Logging.Abstractions;++namespace Filee.App.Tests;++public class NativeMemoryRenderTests+{+ private static TimeSpan Duration =>+ TimeSpan.FromSeconds(int.TryParse(Environment.GetEnvironmentVariable("FILEE_STRESS_SECONDS"), out var s) && s > 0 ? s : 5);++ [AvaloniaFact]+ public async Task Rendering_and_saving_frames_survive_idle_trims_and_compacting_collections()+ {+ TestServices.EnsureInitialized("en");+ var folder = Directory.CreateTempSubdirectory("filee-native-render-").FullName;+ try+ {+ var pictures = new[] { MagickColors.Coral, MagickColors.Teal }.Select((color, i) =>+ {+ var path = Path.Combine(folder, $"picture{i}.png");+ using var image = new MagickImage(color, 640, 400);+ image.Write(path, MagickFormat.Png);+ return path;+ }).ToArray();++ var canvas = new CropCanvas { Width = 640, Height = 400 };+ var donut = new DonutMenu+ {+ Items = new[] { "PNG", "JPG", "WEBP", "PDF", "TIFF", "BMP" }.Select(l => new DonutItem { Id = l, Label = l }).ToList(),+ };+ var window = new Window { Content = new StackPanel { Children = { canvas, donut } }, SizeToContent = SizeToContent.WidthAndHeight };+ window.Show();+ Dispatcher.UIThread.RunJobs();++ using var stop = new CancellationTokenSource(Duration);+ var trims = 0;+ var trimmer = Task.Run(() =>+ {+ while (!stop.IsCancellationRequested)+ {+ MemoryTrimmer.Trim(NullLogger.Instance);+ GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;+ GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);+ trims++;+ Thread.Sleep(10);+ }+ }, TestContext.Current.CancellationToken);++ var frames = 0;+ while (!stop.IsCancellationRequested)+ {+ var (preview, _, _) = await CropService.LoadPreviewAsync(pictures[frames % pictures.Length]);+ var old = canvas.SourceImage;+ canvas.SourceImage = preview;+ old?.Dispose();+ donut.InvalidateVisual();+ Dispatcher.UIThread.RunJobs();+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();++ // Disposed at the end: Avalonia encodes a snapshot that doesn't own the frame's pixels, so the frame+ // must stay alive until Save returns.+ using var frame = window.CaptureRenderedFrame()!;+ using var png = new MemoryStream();+ frame.Save(png, new PngBitmapEncoderOptions());+ Assert.True(png.Length > 1000);+ frames++;+ }+ await trimmer;+ window.Close();+ canvas.SourceImage?.Dispose();++ Assert.True(frames > 0);+ Assert.True(trims > 0);+ }+ finally+ {+ try { Directory.Delete(folder, true); } catch (IOException) { }+ }+ }+}diff --git a/tests/Filee.Engines.Tests/NativeMemoryStressTests.cs b/tests/Filee.Engines.Tests/NativeMemoryStressTests.csnew file mode 100644index 00000000..59969fc2--- /dev/null+++ b/tests/Filee.Engines.Tests/NativeMemoryStressTests.cs@@ -0,0 +1,109 @@+// Engine paths that hand memory to native code (PDFium, Skia, HarfBuzz, ImageMagick, WIC, unhwp) run on several+// threads while another thread keeps compacting the managed heap and a third drops the engines' caches the way the+// idle memory trim does. Native code that keeps a pointer into an unpinned managed buffer, a callback whose delegate+// was collected, or a cache release that frees something still in use crashes the test host or corrupts the output.+// FILEE_STRESS_SECONDS runs it longer (the default keeps CI time low).++using System.Runtime;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;+using ImageMagick;++namespace Filee.Engines.Tests;++public class NativeMemoryStressTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static TimeSpan Duration =>+ TimeSpan.FromSeconds(int.TryParse(Environment.GetEnvironmentVariable("FILEE_STRESS_SECONDS"), out var s) && s > 0 ? s : 6);++ [Fact]+ public async Task Native_conversions_survive_a_compacting_collector_and_cache_releases()+ {+ var dir = fx.NewFolder();+ var routes = new List<(string Source, string Target)>+ {+ (Pdf(dir), "png"), // PDFium into SKBitmap, Skia PNG encoder, ImageMagick+ (Write(dir, "drawing.svg", GraphicsBuilders.Svg), "pdf"), // Svg.Skia, HarfBuzz outlines, Skia PDF+ (Write(dir, "drawing2.svg", GraphicsBuilders.Svg), "png"),+ (CadBuilder.SaveDxf(CadBuilder.Sample(), dir, "도면.dxf"), "png"), // CAD typefaces (released by the trim)+ (ModelBuilders.Save(ModelBuilders.Cube(), dir, "cube", "glb"), "png"), // software renderer → SKImage+ (EngineFixture.MakeImage(dir, "photo.png", MagickFormat.Png), "webp"),+ };+ if (OperatingSystem.IsWindows())+ {+ var jxr = Path.Combine(dir, "photo.jxr");+ JpegXrBuilder.WriteBgr(jxr, 96, 64, (x, y) => ((byte)x, (byte)y, 128)); // WIC CopyPixels into a pinned array+ routes.Add((jxr, "png"));+ }+ if (fx.Catalog.StatusOf(fx.Converters.Single(c => c.Id == "unhwp")).IsAvailable)+ routes.Add((await fx.MakeHwpxAsync(fx.NewFolder()), "md"));++ using var stop = new CancellationTokenSource(Duration);+ var compactions = 0;+ var compactor = Task.Run(() =>+ {+ while (!stop.IsCancellationRequested)+ {+ GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;+ GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);+ compactions++;+ Thread.Sleep(2);+ }+ }, TestContext.Current.CancellationToken);+ var releaser = Task.Run(() =>+ {+ while (!stop.IsCancellationRequested)+ {+ EngineCaches.Release();+ GC.WaitForPendingFinalizers();+ Thread.Sleep(15);+ }+ }, TestContext.Current.CancellationToken);++ var runs = 0;+ var workers = Enumerable.Range(0, 4).Select(worker => Task.Run(async () =>+ {+ // Own copies, so the workers' outputs don't meet in one folder.+ var own = fx.NewFolder();+ var mine = routes.Select(r => (Source: CopyInto(own, r.Source), r.Target)).ToList();+ for (var i = worker; !stop.IsCancellationRequested; i++)+ {+ var (source, target) = mine[i % mine.Count];+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = target });+ var failures = string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));+ Assert.True(job.State == JobState.Completed, $"{Path.GetFileName(source)} → {target}: {failures}");+ Assert.True(new FileInfo(job.Outputs.Single()).Length > 0);+ Interlocked.Increment(ref runs);+ }+ }, TestContext.Current.CancellationToken)).ToArray();++ await Task.WhenAll([.. workers, compactor, releaser]);+ Assert.True(runs >= routes.Count, $"only {runs} conversions ran");+ Assert.True(compactions > 0);+ }++ private static string Pdf(string dir)+ {+ var pdf = new PdfBuilder().NewPage();+ var font = pdf.Font();+ for (var line = 0; line < 20; line++)+ pdf.Line($"Line {line}: PDFium renders this page into a Skia bitmap.", 12, font, 60, 80 + line * 18);+ pdf.Bar(60, 500, 300, 40, (30, 120, 200));+ return pdf.Save(Path.Combine(dir, "pages.pdf"));+ }++ private static string CopyInto(string folder, string file)+ {+ var copy = Path.Combine(folder, Path.GetFileName(file));+ File.Copy(file, copy);+ return copy;+ }++ private static string Write(string folder, string name, string text)+ {+ var path = Path.Combine(folder, name);+ File.WriteAllText(path, text);+ return path;+ }+}diff --git a/tests/Filee.Engines.Tests/RhwpFontsTests.cs b/tests/Filee.Engines.Tests/RhwpFontsTests.csindex d71c7e64..b8479c44 100644--- a/tests/Filee.Engines.Tests/RhwpFontsTests.cs+++ b/tests/Filee.Engines.Tests/RhwpFontsTests.cs@@ -121,6 +121,25 @@ public class RhwpFontsTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Null(RhwpInput.Prepare(hwpx, dir, _ => new InstalledFont(true, _ => true))); // nothing to replace: no copy}+ [Fact]+ public void Looking_up_a_missing_font_leaves_the_fallback_typeface_usable_for_others()+ {+ // fontconfig (and CoreText) answer an unknown family with some installed font; Windows answers null.+ const string missing = "Filee No Such Family";+ var fallback = SkiaSharp.SKFontManager.Default.MatchFamily(missing);+ Assert.SkipWhen(fallback is null, "this font manager has no fallback for unknown families");+ // SkiaSharp gives out one wrapper per native typeface: what Find gets is this very object.+ Assert.SkipUnless(ReferenceEquals(fallback, SkiaSharp.SKFontManager.Default.MatchFamily(missing)),+ "this font manager makes a new typeface per lookup");++ RhwpFonts.ReleaseCache();+ RhwpFonts.Find(missing);++ Assert.NotEqual(IntPtr.Zero, fallback.Handle);+ Assert.True(fallback.GlyphCount > 0);+ GC.KeepAlive(fallback);+ }+private static List<string> Faces(string hwpx){using var zip = ZipFile.OpenRead(hwpx);