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.

JPEG XR: release WIC objects once, not finally

KnifeLemoneffa5cc31380
diff --git a/src/Filee.Engines/Wic/WicNative.cs b/src/Filee.Engines/Wic/WicNative.cs
index bb91f981..919d0228 100644
--- a/src/Filee.Engines/Wic/WicNative.cs
+++ b/src/Filee.Engines/Wic/WicNative.cs
@@ -39,11 +39,17 @@ internal static class WicNative
(IWICImagingFactory)(Activator.CreateInstance(Type.GetTypeFromCLSID(ImagingFactoryClsid, throwOnError: true)!)
?? throw new InvalidOperationException("The Windows Imaging Component is not available."));
- /// <summary>Releases a COM object now instead of when the garbage collector gets to it (a decoder keeps its file open).</summary>
+ /// <summary>
+ /// Releases this caller's reference to a COM object now instead of when the garbage collector gets to it (a decoder
+ /// keeps its file open). Once, not FinalReleaseComObject: WIC hands every caller the same cached component info
+ /// for a pixel format, and .NET one wrapper per COM object, so two conversions at once share it; a final release
+ /// on one thread cut the other's wrapper off in the middle of its calls ("COM object that has been separated from
+ /// its underlying RCW").
+ /// </summary>
public static void Release(object? comObject)
{
if (comObject is not null && Marshal.IsComObject(comObject))
- Marshal.FinalReleaseComObject(comObject);
+ Marshal.ReleaseComObject(comObject);
}
[StructLayout(LayoutKind.Sequential)]
diff --git a/tests/Filee.Engines.Tests/JpegXrTests.cs b/tests/Filee.Engines.Tests/JpegXrTests.cs
index ccc7fcda..0bea56a3 100644
--- a/tests/Filee.Engines.Tests/JpegXrTests.cs
+++ b/tests/Filee.Engines.Tests/JpegXrTests.cs
@@ -68,6 +68,32 @@ public class JpegXrTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
}
+ [Fact]
+ public async Task Several_jpeg_xr_pictures_are_read_at_once()
+ {
+ // WIC gives every reader of a pixel format the same component info, and .NET one wrapper for it: a reader
+ // that made a final release of it cut the others off ("COM object that has been separated from its RCW").
+ Assert.SkipUnless(OperatingSystem.IsWindows(), "JPEG XR is read with the Windows Imaging Component.");
+ var dir = fx.NewFolder();
+ var sdr = Path.Combine(dir, "photo.jxr");
+ JpegXrBuilder.WriteBgr(sdr, 64, 48, (x, y) => ((byte)x, (byte)y, 128));
+ var hdr = Path.Combine(dir, "screenshot.jxr");
+ JpegXrBuilder.WriteHdr(hdr, 64, 48, (x, _) => (x / 32f, 0.5f, 0.25f));
+
+ var readers = Enumerable.Range(0, 8).Select(reader => Task.Run(() =>
+ {
+ if (!OperatingSystem.IsWindows())
+ return;
+ for (var i = 0; i < 40; i++)
+ {
+ using var image = WicImageReader.Read((reader + i) % 2 == 0 ? sdr : hdr);
+ Assert.Equal((64u, 48u), (image.Width, image.Height));
+ }
+ }, TestContext.Current.CancellationToken));
+
+ await Task.WhenAll(readers);
+ }
+
[Fact]
public async Task An_hdr_screenshot_of_sdr_content_comes_out_as_it_was_drawn()
{
diff --git a/tests/Filee.Engines.Tests/NativeMemoryStressTests.cs b/tests/Filee.Engines.Tests/NativeMemoryStressTests.cs
index 59969fc2..092e5912 100644
--- a/tests/Filee.Engines.Tests/NativeMemoryStressTests.cs
+++ b/tests/Filee.Engines.Tests/NativeMemoryStressTests.cs
@@ -14,6 +14,8 @@ namespace Filee.Engines.Tests;
public class NativeMemoryStressTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
+ private const int Workers = 3;
+
private static TimeSpan Duration =>
TimeSpan.FromSeconds(int.TryParse(Environment.GetEnvironmentVariable("FILEE_STRESS_SECONDS"), out var s) && s > 0 ? s : 6);
@@ -39,21 +41,23 @@ public class NativeMemoryStressTests(EngineFixture fx) : IClassFixture<EngineFix
if (fx.Catalog.StatusOf(fx.Converters.Single(c => c.Id == "unhwp")).IsAvailable)
routes.Add((await fx.MakeHwpxAsync(fx.NewFolder()), "md"));
+ // Every worker goes through every route at least once, however slow the machine; then until the time is up.
using var stop = new CancellationTokenSource(Duration);
+ var done = false;
var compactions = 0;
var compactor = Task.Run(() =>
{
- while (!stop.IsCancellationRequested)
+ while (!Volatile.Read(ref done))
{
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);
compactions++;
- Thread.Sleep(2);
+ Thread.Sleep(20);
}
}, TestContext.Current.CancellationToken);
var releaser = Task.Run(() =>
{
- while (!stop.IsCancellationRequested)
+ while (!Volatile.Read(ref done))
{
EngineCaches.Release();
GC.WaitForPendingFinalizers();
@@ -62,14 +66,14 @@ public class NativeMemoryStressTests(EngineFixture fx) : IClassFixture<EngineFix
}, TestContext.Current.CancellationToken);
var runs = 0;
- var workers = Enumerable.Range(0, 4).Select(worker => Task.Run(async () =>
+ var workers = Enumerable.Range(0, Workers).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++)
+ for (var i = 0; i < mine.Count || !stop.IsCancellationRequested; i++)
{
- var (source, target) = mine[i % mine.Count];
+ var (source, target) = mine[(worker + 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}");
@@ -78,8 +82,16 @@ public class NativeMemoryStressTests(EngineFixture fx) : IClassFixture<EngineFix
}
}, TestContext.Current.CancellationToken)).ToArray();
- await Task.WhenAll([.. workers, compactor, releaser]);
- Assert.True(runs >= routes.Count, $"only {runs} conversions ran");
+ try
+ {
+ await Task.WhenAll(workers);
+ }
+ finally
+ {
+ Volatile.Write(ref done, true);
+ await Task.WhenAll(compactor, releaser);
+ }
+ Assert.True(runs >= Workers * routes.Count);
Assert.True(compactions > 0);
}