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
Read JPEG XR on Windows with WIC and tone-map HDR screenshots (#150)
KnifeLemon8f6af7172fd1
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 7a0f9ab5..c73d5b77 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -85,6 +85,7 @@"engine.reason.unsupported_platform": "Not available on this platform","engine.reason.needs_package": "Needs {0}. Install it in Settings → Engines","engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, camera RAW and more.\nQuality, size and DPI follow your preset.",+ "engine.wic.description": "JPEG XR pictures (.jxr, .wdp, .hdp), such as HDR screenshots of Windows, to PNG, JPG and other images, with Windows' own codec.\nHDR is tone-mapped so highlights keep their detail.","engine.pdfium.description": "Renders PDF pages to PNG, JPG and TIFF (also multi-page TIFF and GIF) at the preset's resolution.","engine.pdfsharp.description": "Makes PDFs from images and merges, splits or cuts page ranges out of PDFs.\nAlso makes PDFs smaller by scaling down their pictures.","engine.rhwp.description": "Renders HWP/HWPX to PDF and converts HWP ↔ HWPX.\nIt also draws documents that reach PDF through HWPX (DOCX, XLSX, PPTX, e-books…).",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 5e168e02..bada021d 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -78,6 +78,7 @@"engine.reason.unsupported_platform": "No disponible en esta plataforma","engine.reason.needs_package": "Necesita {0}. Instálalo en Ajustes → Motores","engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, RAW de cámara y más.\nLa calidad, el tamaño y los DPI siguen tu ajuste preestablecido.",+ "engine.wic.description": "Imágenes JPEG XR (.jxr, .wdp, .hdp), como las capturas HDR de Windows, a PNG, JPG y otras imágenes, con el códec de Windows.\nEl HDR se adapta para que las luces conserven su detalle.","engine.pdfium.description": "Convierte páginas PDF a PNG, JPG y TIFF (también TIFF multipágina y GIF) en la resolución del ajuste preestablecido.","engine.pdfsharp.description": "Crea PDF a partir de imágenes y combina, divide o extrae rangos de páginas de PDF.\nTambién reduce el tamaño de los PDF reduciendo sus imágenes.","engine.rhwp.description": "Renderiza HWP/HWPX a PDF y convierte HWP ↔ HWPX.\nTambién dibuja en PDF los documentos que llegan a PDF a través de HWPX (DOCX, XLSX, PPTX, libros electrónicos…).",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 923542c3..4a06fe7e 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -85,6 +85,7 @@"engine.reason.unsupported_platform": "이 플랫폼에서는 사용할 수 없음","engine.reason.needs_package": "{0} 필요 (설정 → 변환 엔진에서 설치)","engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, 카메라 RAW 등 이미지를 변환해요.\n품질·크기·DPI는 프리셋대로 맞춰요.",+ "engine.wic.description": "JPEG XR 이미지(.jxr, .wdp, .hdp), 예를 들어 Windows HDR 스크린샷을 Windows 내장 코덱으로 PNG, JPG 등으로 바꿔요.\nHDR은 톤 매핑해서 밝은 부분의 디테일을 살려요.","engine.pdfium.description": "PDF 페이지를 PNG, JPG, TIFF(여러 페이지 TIFF·GIF 포함)로 프리셋 해상도에 맞춰 그려요.","engine.pdfsharp.description": "이미지로 PDF를 만들고, PDF를 합치거나 나누거나 원하는 페이지만 잘라내요.\nPDF 속 이미지를 줄여 파일을 작게 만들기도 해요.","engine.rhwp.description": "HWP/HWPX를 PDF로 그리고, HWP ↔ HWPX를 바꿔요.\nHWPX를 거쳐 PDF가 되는 문서(DOCX, XLSX, PPTX, 전자책 등)도 그려요.",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex ec2d5a7e..3cfe002b 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -85,6 +85,7 @@"engine.reason.unsupported_platform": "Niedostępne na tej platformie","engine.reason.needs_package": "Wymaga {0}. Zainstaluj w Ustawienia → Silniki","engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, RAW z aparatów i inne.\nJakość, rozmiar i DPI zgodnie z ustawieniem.",+ "engine.wic.description": "Obrazy JPEG XR (.jxr, .wdp, .hdp), np. zrzuty ekranu HDR z Windows, do PNG, JPG i innych formatów, kodekiem wbudowanym w Windows.\nHDR jest mapowany tonalnie, więc jasne miejsca zachowują szczegóły.","engine.pdfium.description": "Renderuje strony PDF do PNG, JPG i TIFF (także wielostronicowy TIFF i GIF) w rozdzielczości z ustawienia.","engine.pdfsharp.description": "Tworzy PDF z obrazów oraz łączy, dzieli i wycina zakresy stron z plików PDF.","engine.rhwp.description": "Renderuje HWP/HWPX do PDF i konwertuje HWP ↔ HWPX.\nRysuje też dokumenty, które trafiają do PDF przez HWPX (DOCX, XLSX, PPTX, e-booki…).",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 5f1f8504..4406bcad 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -85,6 +85,7 @@"engine.reason.unsupported_platform": "此平台不可用","engine.reason.needs_package": "需要 {0},请在“设置 → 转换引擎”中安装","engine.magick.description": "JPG、PNG、WEBP、AVIF、HEIC、TIFF、GIF、APNG、PSD、相机 RAW 等图片。\n质量、尺寸和 DPI 按预设处理。",+ "engine.wic.description": "用 Windows 自带的编解码器把 JPEG XR 图片(.jxr、.wdp、.hdp,如 Windows 的 HDR 截图)转为 PNG、JPG 等图片。\nHDR 经过色调映射,高光保留细节。","engine.pdfium.description": "按预设分辨率将 PDF 页面渲染为 PNG、JPG、TIFF(也支持多页 TIFF 和 GIF)。","engine.pdfsharp.description": "用图片生成 PDF,合并、拆分 PDF 或截取指定页码。\n还能缩小 PDF 中的图片来减小文件。","engine.rhwp.description": "将 HWP/HWPX 渲染为 PDF,并在 HWP ↔ HWPX 之间转换。\n经 HWPX 转为 PDF 的文档(DOCX、XLSX、PPTX、电子书等)也由它渲染。",diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.csindex 23e928ce..5bd0644d 100644--- a/src/Filee.Cli/Cli.cs+++ b/src/Filee.Cli/Cli.cs@@ -312,7 +312,10 @@ internal static class Clireturn UsageError;}var installed = host.Catalog.CreatePlanner();- var everything = host.Catalog.CreatePlanner(host.Catalog.All.Select(c => c.Id).ToList());+ // Engines a download would add, not those this platform lacks (JPEG XR is read with Windows' own codec).+ var everything = host.Catalog.CreatePlanner(host.Catalog.All+ .Where(c => host.Catalog.StatusOf(c).ReasonKey != "engine.reason.unsupported_platform")+ .Select(c => c.Id).ToList());var targets = FormatRegistry.Known.Where(t => t.Writable && t.Id != from.Id && t.Id != FormatRegistry.Folder).ToList();var now = targets.Where(t => installed.CanConvert(from.Id, t.Id)).Select(t => t.Id).ToList();var later = targets.Where(t => !now.Contains(t.Id) && everything.CanConvert(from.Id, t.Id)).Select(t => t.Id).ToList();diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex de25f16c..6ea92f6a 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -47,6 +47,8 @@ public static class FormatRegistrynew("pcd", "Photo CD", FormatCategory.Image, ["pcd"], Writable: false),new("exr", "OpenEXR", FormatCategory.Image, ["exr"], Writable: false),new("hdr", "Radiance HDR", FormatCategory.Image, ["hdr"], Writable: false),+ // Read on Windows only, with its own codec (HDR screenshots of Windows are JPEG XR).+ new("jxr", "JPEG XR", FormatCategory.Image, ["jxr", "wdp", "hdp"], Writable: false),new("xcf", "XCF", FormatCategory.Image, ["xcf"], Writable: false),new("raw", "RAW", FormatCategory.Image,["dng", "cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "orf", "rw2", "raf", "pef", "dcr", "kdc",diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex f1fde541..22baf9ad 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -64,7 +64,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 20;+ public const int CurrentSchemaVersion = 21;public int SchemaVersion { get; set; } = CurrentSchemaVersion;@@ -107,8 +107,8 @@ public sealed class AppSettingspublic List<string> EnginePriority { get; set; } =["magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",- "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg",- "pandoc", "ghostscript", "calibre", "libreoffice",+ "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook",+ "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice",];/// <summary>Set once the first-run welcome has been shown.</summary>diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 44dd6d23..3e22ef67 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -318,6 +318,12 @@ internal static class SettingsMigrationsInsertBefore(settings.EnginePriority, "pdf-slides", "pandoc");}+ // v21: built-in "wic" engine (JPEG XR through the Windows Imaging Component), after the other built-in engines:+ // no other engine reads JPEG XR, and higher up it would push the HWPX writer out of the ranks that win+ // ties. (Schema 21 may be renumbered if another change takes it first.)+ if (settings.SchemaVersion < 21)+ InsertBefore(settings.EnginePriority, "wic", settings.EnginePriority.Contains("ffmpeg") ? "ffmpeg" : "pandoc");+if (settings.Triggers.Count == 0)settings.Triggers = TriggerGesture.Defaults();@@ -549,6 +555,10 @@ internal static class SettingsMigrationschanged = true;}}+ // v21: JPEG XR (.jxr, .wdp, .hdp; HDR screenshots of Windows): the images donut learns the extensions unless+ // another donut already has them. (Schema 21 may be renumbered if another change takes it first.)+ if (from < 21)+ changed |= LearnExtensions(profiles, out _, ["jxr", "wdp", "hdp"]);return changed;}@@ -633,7 +643,8 @@ internal static class SettingsMigrations/// Adds the default extensions of the built-in donuts that no donut of the user takes yet./// </summary>/// <param name="claimed">Every extension a donut takes afterwards.</param>- private static bool LearnExtensions(List<ToolbarProfile> profiles, out HashSet<string> claimed)+ /// <param name="only">Learn only these (the ones a version added), not others the user removed from a donut since.</param>+ private static bool LearnExtensions(List<ToolbarProfile> profiles, out HashSet<string> claimed, IReadOnlyCollection<string>? only = null){var changed = false;// Extensions checked on a mixed-selection profile only limit that profile; they don't claim files.@@ -641,7 +652,7 @@ internal static class SettingsMigrationsvar defaults = BuiltInData.CreateProfiles().ToDictionary(p => p.Id);foreach (var profile in profiles.Where(p => !p.IsFallback && defaults.ContainsKey(p.Id))){- foreach (var extension in defaults[profile.Id].Extensions.Where(claimed.Add))+ foreach (var extension in defaults[profile.Id].Extensions.Where(e => only is null || only.Contains(e)).Where(claimed.Add)){profile.Extensions.Add(extension);changed = true;diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.csindex 6601f925..57659ee3 100644--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@ -19,6 +19,7 @@ using Filee.Engines.Pdf;using Filee.Engines.Subtitles;using Filee.Engines.Text;using Filee.Engines.Vector;+using Filee.Engines.Wic;using Microsoft.Extensions.Logging;namespace Filee.Engines;@@ -56,6 +57,7 @@ public static class EngineRegistrynew EmlConverter(),new DataConverter(),new SubtitleConverter(),+ new WicImageConverter(),new FfmpegConverter(loggers?.CreateLogger<FfmpegConverter>()),new CadConverter(),new ModelConverter(),diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.csindex 7085d339..8a6e4ac9 100644--- a/src/Filee.Engines/Magick/MagickImageConverter.cs+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs@@ -72,20 +72,31 @@ public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransf// Animated PNGs are often saved as .png: read them as APNG, so they stay animated as GIF or WebP.var from = step.From == "png" && Apng.IsAnimated(step.InputPath) ? "apng" : step.From;using var images = ImageReader.Read(step.InputPath, from, step.Preset);- cancellationToken.ThrowIfCancellationRequested();- progress?.Report(0.3);+ return Write(images, from, step, progress, cancellationToken);+ }, cancellationToken);- var frames = ImageEncoder.SelectFrames(images, from, step.To);- foreach (var frame in frames)- {- cancellationToken.ThrowIfCancellationRequested();- ImageEncoder.ApplyOptions(frame, step.Preset.Image, step.To);- }- progress?.Report(0.7);+ /// <summary>+ /// The rest of a conversion once the picture is read (also for pictures another engine decoded, see+ /// Wic/WicImageConverter): the frames kept for the target, the preset's options, the files.+ /// </summary>+ /// <param name="from">Format the frames were read from (animations and icons keep different frames).</param>+ internal static IReadOnlyList<string> Write(MagickImageCollection images, string from, ConversionStep step,+ IProgress<double>? progress, CancellationToken cancellationToken)+ {+ cancellationToken.ThrowIfCancellationRequested();+ progress?.Report(0.3);- var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath,- ImageEncoder.KeepsAnimation(from, step.To));- progress?.Report(1);- return written;- }, cancellationToken);+ var frames = ImageEncoder.SelectFrames(images, from, step.To);+ foreach (var frame in frames)+ {+ cancellationToken.ThrowIfCancellationRequested();+ ImageEncoder.ApplyOptions(frame, step.Preset.Image, step.To);+ }+ progress?.Report(0.7);++ var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath,+ ImageEncoder.KeepsAnimation(from, step.To));+ progress?.Report(1);+ return written;+ }}diff --git a/src/Filee.Engines/Wic/HdrToneMap.cs b/src/Filee.Engines/Wic/HdrToneMap.csnew file mode 100644index 00000000..0a746164--- /dev/null+++ b/src/Filee.Engines/Wic/HdrToneMap.cs@@ -0,0 +1,108 @@+// HDR → SDR for linear scRGB pictures, the float JPEG XR files Windows saves for screenshots on an HDR display (Xbox+// Game Bar, Win + Alt + PrtScn, Snipping Tool). In scRGB 1.0 is SDR white at 80 nits, but Windows draws SDR content+// (the desktop, windows, a game's menus) at the "SDR content brightness" of the display, 80 to 480 nits (1.0 to 6.0),+// and HDR highlights go well beyond that. Clipping at 1.0 blows out every picture taken with SDR brightness above the+// minimum; dividing by the brightest pixel makes the picture dark when a small highlight is very bright.+//+// So, simple and predictable:+// 1. Reference white: the luminance 99 % of the pixels stay below, at least 1.0 (scRGB's own SDR white) and at most+// 4.0 (320 nits). The white of a desktop screenshot lands there (SDR brightness up to 320 nits), so its SDR parts+// come out as they were drawn; in a game, the brightest 1 % is treated as white. Pixels are divided by it.+// 2. Up to 80 % of that white nothing changes. Above it an extended Reinhard shoulder takes the range up to the+// brightest pixel smoothly into the last 20 %: highlights keep their detail instead of clipping, and a picture+// without anything brighter than white is left as it is. The curve works on the largest of R, G and B and scales+// the three by the same factor, so colours keep their hue and nothing clips.+// 3. Negative values (colours outside the sRGB gamut) are clipped to 0, then the sRGB transfer curve and 8 bits.++namespace Filee.Engines.Wic;++/// <summary>Maps linear scRGB pixels to 8-bit sRGB.</summary>+internal sealed class HdrToneMap+{+ /// <summary>The share of pixels at or below the reference white.</summary>+ public const double WhitePercentile = 0.99;++ /// <summary>Highest reference white, in scRGB (4.0 = 320 nits).</summary>+ public const float MaxWhite = 4f;++ /// <summary>Where the shoulder starts, as a fraction of the reference white.</summary>+ public const float Knee = 0.8f;++ /// <summary>At most this many luminance samples choose the reference white.</summary>+ private const int MaxSamples = 1 << 16;++ private readonly float _white;+ private readonly float _range;++ /// <param name="white">Reference white (scRGB), see <see cref="ReferenceWhite"/>.</param>+ /// <param name="peak">Largest R, G or B value of the picture (scRGB).</param>+ public HdrToneMap(float white, float peak)+ {+ _white = white;+ // The shoulder's end in its own units (0 at the knee, 1 at white): extended Reinhard maps it exactly to 1.+ _range = Math.Max(1, (peak / white - Knee) / (1 - Knee));+ }++ /// <summary>+ /// The reference white of a picture from the luminance of (a sample of) its pixels, between 1 and <see cref="MaxWhite"/>.+ /// </summary>+ public static float ReferenceWhite(IReadOnlyList<float> luminances)+ {+ if (luminances.Count == 0)+ return 1;+ var sorted = luminances.ToArray();+ Array.Sort(sorted);+ var white = sorted[(int)Math.Round(WhitePercentile * (sorted.Length - 1))];+ return float.IsNaN(white) ? 1 : Math.Clamp(white, 1, MaxWhite);+ }++ /// <summary>How many pixels to skip between two luminance samples of a <paramref name="pixels"/> pixel picture.</summary>+ public static long SampleStep(long pixels) => Math.Max(1, (pixels + MaxSamples - 1) / MaxSamples);++ /// <summary>Rec. 709 / sRGB luminance of a linear pixel, its negative (out of gamut) channels taken as 0.</summary>+ public static float Luminance(float r, float g, float b) =>+ 0.2126f * Positive(r) + 0.7152f * Positive(g) + 0.0722f * Positive(b);++ /// <summary>Largest channel of a linear pixel, at least 0.</summary>+ public static float MaxChannel(float r, float g, float b) => Math.Max(Positive(r), Math.Max(Positive(g), Positive(b)));++ /// <summary>Tone curve on values relative to the reference white: the identity up to the knee, then the shoulder.</summary>+ public float Curve(float relative)+ {+ if (relative <= Knee)+ return relative;+ var x = (relative - Knee) / (1 - Knee);+ var shoulder = x * (1 + x / (_range * _range)) / (1 + x);+ return Math.Min(1, Knee + (1 - Knee) * shoulder);+ }++ /// <summary>Maps one linear RGBA pixel to 8-bit sRGB RGBA.</summary>+ public void Map(float r, float g, float b, float a, Span<byte> rgba)+ {+ r = Positive(r) / _white;+ g = Positive(g) / _white;+ b = Positive(b) / _white;+ var max = Math.Max(r, Math.Max(g, b));+ var scale = max > Knee ? Curve(max) / max : 1;+ rgba[0] = Encode(r * scale);+ rgba[1] = Encode(g * scale);+ rgba[2] = Encode(b * scale);+ rgba[3] = (byte)Math.Round(Math.Clamp(float.IsNaN(a) ? 1 : a, 0, 1) * 255);+ }++ /// <summary>sRGB transfer curve (IEC 61966-2-1) and 8 bits, from a table: a 4K screenshot has 25 million values.</summary>+ public static byte Encode(float linear) => EncodeTable[(int)(Math.Clamp(linear, 0, 1) * (EncodeTable.Length - 1) + 0.5f)];++ /// <summary>+ /// 8-bit sRGB of 65,536 linear steps. The darkest step is 1/20 of an 8-bit level, so the table loses nothing.+ /// </summary>+ private static readonly byte[] EncodeTable = [.. Enumerable.Range(0, 65536).Select(i =>+ {+ var linear = i / 65535.0;+ var encoded = linear <= 0.0031308 ? 12.92 * linear : 1.055 * Math.Pow(linear, 1 / 2.4) - 0.055;+ return (byte)Math.Round(encoded * 255);+ })];++ /// <summary>The value, 0 for negative values and NaN, at most the largest half float (infinity included).</summary>+ private static float Positive(float value) => value > 0 ? Math.Min(value, 65504f) : 0;+}diff --git a/src/Filee.Engines/Wic/WicImageConverter.cs b/src/Filee.Engines/Wic/WicImageConverter.csnew file mode 100644index 00000000..285ec412--- /dev/null+++ b/src/Filee.Engines/Wic/WicImageConverter.cs@@ -0,0 +1,46 @@+// JPEG XR → images with the Windows Imaging Component, part of Windows (nothing to install or ship). WIC decodes,+// ImageMagick does the rest as for any other picture (preset options, every image format it writes). PDF, ICNS,+// HEIC and traced SVG follow through PNG.++using Filee.Core.Conversion;+using Filee.Engines.Magick;++namespace Filee.Engines.Wic;++/// <summary>Reads JPEG XR (HDR screenshots of Windows included) on Windows.</summary>+public sealed class WicImageConverter : IConverter, IImageTransformer+{+ public string Id => "wic";+ public string DisplayName => "Windows Imaging Component";+ public int MaxParallelism => 0;++ public bool Transforms(string from, string to) => true;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ ImageEncoder.Writable.Select(target => ImageEncoder.Edge("jxr", target)).ToList();++ public EngineStatus GetStatus()+ {+ if (!OperatingSystem.IsWindows())+ return EngineStatus.Unavailable("engine.reason.unsupported_platform");+ try+ {+ // Every Windows 10 and 11 has the JPEG XR codec; a stripped-down installation might not.+ WicNative.Release(Activator.CreateInstance(Type.GetTypeFromCLSID(WicNative.JpegXrDecoderClsid, throwOnError: true)!));+ }+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or TypeLoadException)+ {+ return EngineStatus.Unavailable("engine.reason.not_installed", "JPEG XR codec: " + ex.Message);+ }+ return EngineStatus.Available("JPEG XR (JXR, WDP, HDP) → images", $"Windows {Environment.OSVersion.Version}");+ }++ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>+ Task.Run(() =>+ {+ if (!OperatingSystem.IsWindows())+ throw new PlatformNotSupportedException("JPEG XR is read with the Windows Imaging Component, on Windows only.");+ using var images = new ImageMagick.MagickImageCollection { WicImageReader.Read(step.InputPath) };+ return MagickImageConverter.Write(images, step.From, step, progress, cancellationToken);+ }, cancellationToken);+}diff --git a/src/Filee.Engines/Wic/WicImageReader.cs b/src/Filee.Engines/Wic/WicImageReader.csnew file mode 100644index 00000000..f347ea98--- /dev/null+++ b/src/Filee.Engines/Wic/WicImageReader.cs@@ -0,0 +1,142 @@+// Reads JPEG XR (.jxr, .wdp, .hdp) with Windows' own codec through WIC. ImageMagick has no JPEG XR coder on any+// platform, so this is the only reader. The picture becomes an ordinary 8-bit sRGB MagickImage; resizing, rotating+// and encoding are then ImageMagick's, as for every other image.+//+// Pixel formats with integer channels (8 or 16 bits, grey, RGB, CMYK) are converted by WIC to 8-bit BGRA. Fixed-point+// and float ones are linear scRGB with values above 1.0 (HDR screenshots are 64-bit half floats): WIC's converter would+// clip them, so they are read as 128-bit floats and tone-mapped by HdrToneMap.++using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using ImageMagick;+using static Filee.Engines.Wic.WicNative;++namespace Filee.Engines.Wic;++[SupportedOSPlatform("windows")]+internal static class WicImageReader+{+ /// <summary>Rows read at once from an HDR picture: about 4 MB of floats.</summary>+ private const int BandBytes = 4 << 20;++ /// <summary>Decodes the first frame of <paramref name="path"/> (a JPEG XR file has one picture).</summary>+ public static MagickImage Read(string path)+ {+ IWICImagingFactory? factory = null;+ IWICBitmapDecoder? decoder = null;+ IWICBitmapFrameDecode? frame = null;+ IWICComponentInfo? info = null;+ IWICFormatConverter? converter = null;+ try+ {+ factory = CreateFactory();+ decoder = factory.CreateDecoderFromFilename(path, IntPtr.Zero, GenericRead, DecodeMetadataCacheOnDemand);+ if (decoder.GetFrameCount() == 0)+ throw new InvalidDataException("The file holds no picture.");+ frame = decoder.GetFrame(0);+ frame.GetSize(out var width, out var height);+ if (width == 0 || height == 0)+ throw new InvalidDataException("The picture is empty.");+ if ((long)width * height * 4 > Array.MaxLength)+ throw new InvalidDataException($"A {width} × {height} picture is too large to convert.");++ var format = frame.GetPixelFormat();+ info = factory.CreateComponentInfo(ref format);+ var pixelFormat = (IWICPixelFormatInfo2)info;+ var hdr = pixelFormat.GetNumericRepresentation() is NumericRepresentationFloat or NumericRepresentationFixed;++ converter = factory.CreateFormatConverter();+ var target = hdr ? PixelFormat128bppRgbaFloat : PixelFormat32bppBgra;+ converter.Initialize((IWICBitmapSource)frame, ref target, BitmapDitherTypeNone, IntPtr.Zero, 0, BitmapPaletteTypeCustom);++ var pixels = hdr ? ToneMapped(converter, (int)width, (int)height) : Bgra(converter, (int)width, (int)height);+ var image = new MagickImage();+ image.ReadPixels(pixels, new PixelReadSettings(width, height, StorageType.Char, hdr ? PixelMapping.RGBA : PixelMapping.BGRA));+ // HDR screenshots carry an alpha channel that is opaque everywhere: a PNG of them needs none.+ if (!pixelFormat.SupportsTransparency() || IsOpaque(pixels))+ image.Alpha(AlphaOption.Off);++ frame.GetResolution(out var dpiX, out var dpiY);+ if (dpiX is > 0 and < 100_000 && dpiY is > 0 and < 100_000)+ image.Density = new Density(dpiX, dpiY, DensityUnit.PixelsPerInch);+ return image;+ }+ catch (COMException ex)+ {+ throw new InvalidOperationException(ex.HResult == ComponentNotFound+ ? "Windows can't read this file: it is not a JPEG XR picture, or Windows' JPEG XR codec is missing."+ : $"Windows couldn't decode this JPEG XR picture (0x{ex.HResult:X8}): {ex.Message}", ex);+ }+ finally+ {+ // The decoder keeps the file open until it is released.+ Release(converter);+ Release(info);+ Release(frame);+ Release(decoder);+ Release(factory);+ }+ }++ /// <summary>True when every pixel of 8-bit RGBA or BGRA <paramref name="pixels"/> is opaque.</summary>+ private static bool IsOpaque(byte[] pixels)+ {+ for (var i = 3; i < pixels.Length; i += 4)+ {+ if (pixels[i] != 255)+ return false;+ }+ return true;+ }++ /// <summary>The whole picture as 8-bit BGRA.</summary>+ private static byte[] Bgra(IWICFormatConverter converter, int width, int height)+ {+ var pixels = GC.AllocateUninitializedArray<byte>(width * height * 4, pinned: true);+ var rect = new WicRect { Width = width, Height = height };+ converter.CopyPixels(ref rect, (uint)width * 4, (uint)pixels.Length, Marshal.UnsafeAddrOfPinnedArrayElement(pixels, 0));+ return pixels;+ }++ /// <summary>+ /// The picture as tone-mapped 8-bit RGBA. Read top to bottom in bands of floats, kept as half floats (the precision+ /// HDR screenshots have) while the reference white and the peak are found, then mapped.+ /// </summary>+ private static byte[] ToneMapped(IWICFormatConverter converter, int width, int height)+ {+ var stride = width * 4;+ var bandRows = Math.Clamp(BandBytes / (stride * sizeof(float)), 1, height);+ var band = GC.AllocateUninitializedArray<float>(bandRows * stride, pinned: true);+ var linear = GC.AllocateUninitializedArray<Half>(stride * height);+ var sampleStep = HdrToneMap.SampleStep((long)width * height);+ var luminances = new List<float>();+ var peak = 0f;+ long pixel = 0;++ for (var y = 0; y < height; y += bandRows)+ {+ var rows = Math.Min(bandRows, height - y);+ var rect = new WicRect { Y = y, Width = width, Height = rows };+ converter.CopyPixels(ref rect, (uint)(stride * sizeof(float)), (uint)(rows * stride * sizeof(float)),+ Marshal.UnsafeAddrOfPinnedArrayElement(band, 0));+ var offset = y * stride;+ for (var i = 0; i < rows * stride; i += 4, pixel++)+ {+ float r = band[i], g = band[i + 1], b = band[i + 2];+ peak = Math.Max(peak, HdrToneMap.MaxChannel(r, g, b));+ if (pixel % sampleStep == 0)+ luminances.Add(HdrToneMap.Luminance(r, g, b));+ linear[offset + i] = (Half)r;+ linear[offset + i + 1] = (Half)g;+ linear[offset + i + 2] = (Half)b;+ linear[offset + i + 3] = (Half)band[i + 3];+ }+ }++ var toneMap = new HdrToneMap(HdrToneMap.ReferenceWhite(luminances), peak);+ var rgba = GC.AllocateUninitializedArray<byte>(linear.Length);+ for (var i = 0; i < linear.Length; i += 4)+ toneMap.Map((float)linear[i], (float)linear[i + 1], (float)linear[i + 2], (float)linear[i + 3], rgba.AsSpan(i, 4));+ return rgba;+ }+}diff --git a/src/Filee.Engines/Wic/WicNative.cs b/src/Filee.Engines/Wic/WicNative.csnew file mode 100644index 00000000..bb91f981--- /dev/null+++ b/src/Filee.Engines/Wic/WicNative.cs@@ -0,0 +1,150 @@+// Windows Imaging Component (WIC) through COM, the part Filee needs to decode a picture: a decoder for a file, its+// first frame, the frame's pixel format and a format converter to read the pixels in a known layout.++using System.Runtime.InteropServices;+using System.Runtime.Versioning;++namespace Filee.Engines.Wic;++[SupportedOSPlatform("windows")]+internal static class WicNative+{+ /// <summary>CLSID_WICImagingFactory.</summary>+ private static readonly Guid ImagingFactoryClsid = new("cacaf262-9370-4615-a13b-9f5539da4c0a");++ /// <summary>CLSID_WICWmpDecoder: the JPEG XR (Windows Media Photo) decoder every Windows 10 and 11 has.</summary>+ public static readonly Guid JpegXrDecoderClsid = new("a26cec36-234c-4950-ae16-e34aace71d0d");++ /// <summary>GUID_WICPixelFormat32bppBGRA: 8 bits per channel, sRGB, straight alpha.</summary>+ public static readonly Guid PixelFormat32bppBgra = new("6fddc324-4e03-4bfe-b185-3d77768dc90f");++ /// <summary>GUID_WICPixelFormat128bppRGBAFloat: linear scRGB floats (1.0 is SDR white), straight alpha.</summary>+ public static readonly Guid PixelFormat128bppRgbaFloat = new("6fddc324-4e03-4bfe-b185-3d77768dc919");++ public const uint GenericRead = 0x80000000;+ public const int DecodeMetadataCacheOnDemand = 0;+ public const int BitmapDitherTypeNone = 0;+ public const int BitmapPaletteTypeCustom = 0;++ /// <summary>WICPixelFormatNumericRepresentationFixed: fixed-point channels, linear like the float ones.</summary>+ public const int NumericRepresentationFixed = 4;++ /// <summary>WICPixelFormatNumericRepresentationFloat: half or full floats (scRGB), or RGBE.</summary>+ public const int NumericRepresentationFloat = 5;++ /// <summary>WINCODEC_ERR_COMPONENTNOTFOUND: no installed decoder takes the file.</summary>+ public const int ComponentNotFound = unchecked((int)0x88982F50);++ public static IWICImagingFactory CreateFactory() =>+ (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>+ public static void Release(object? comObject)+ {+ if (comObject is not null && Marshal.IsComObject(comObject))+ Marshal.FinalReleaseComObject(comObject);+ }++ [StructLayout(LayoutKind.Sequential)]+ public struct WicRect+ {+ public int X;+ public int Y;+ public int Width;+ public int Height;+ }++ // Only the methods Filee calls are typed; the slots before them keep the vtable order and are never called.++ [ComImport, Guid("ec5ec8a9-c395-4314-9c77-54d7a935ff70"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICImagingFactory+ {+ IWICBitmapDecoder CreateDecoderFromFilename([MarshalAs(UnmanagedType.LPWStr)] string fileName, IntPtr vendor,+ uint desiredAccess, int metadataOptions);++ void CreateDecoderFromStream();+ void CreateDecoderFromFileHandle();+ IWICComponentInfo CreateComponentInfo(ref Guid component);+ void CreateDecoder();+ void CreateEncoder();+ void CreatePalette();+ IWICFormatConverter CreateFormatConverter();+ }++ [ComImport, Guid("9edde9e7-8dee-47ea-99df-e6faf2ed44bf"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICBitmapDecoder+ {+ void QueryCapability();+ void Initialize();+ void GetContainerFormat();+ void GetDecoderInfo();+ void CopyPalette();+ void GetMetadataQueryReader();+ void GetPreview();+ void GetColorContexts();+ void GetThumbnail();+ uint GetFrameCount();+ IWICBitmapFrameDecode GetFrame(uint index);+ }++ [ComImport, Guid("00000120-a8f2-4877-ba0a-fd2b6645fb94"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICBitmapSource+ {+ void GetSize(out uint width, out uint height);+ Guid GetPixelFormat();+ void GetResolution(out double dpiX, out double dpiY);+ void CopyPalette();+ void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, IntPtr buffer);+ }++ /// <summary>A frame is a bitmap source: these are IWICBitmapSource's slots.</summary>+ [ComImport, Guid("3b16811b-6a43-4ec9-a813-3d930c13b940"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICBitmapFrameDecode+ {+ void GetSize(out uint width, out uint height);+ Guid GetPixelFormat();+ void GetResolution(out double dpiX, out double dpiY);+ }++ /// <summary>A converter is a bitmap source too: its own methods follow IWICBitmapSource's.</summary>+ [ComImport, Guid("00000301-a8f2-4877-ba0a-fd2b6645fb94"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICFormatConverter+ {+ void GetSize(out uint width, out uint height);+ Guid GetPixelFormat();+ void GetResolution(out double dpiX, out double dpiY);+ void CopyPalette();+ void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, IntPtr buffer);++ void Initialize(IWICBitmapSource source, ref Guid destinationFormat, int dither, IntPtr palette,+ double alphaThresholdPercent, int paletteTranslate);+ }++ [ComImport, Guid("23bc3f0a-698b-4357-886b-f24d50671334"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICComponentInfo;++ /// <summary>What a pixel format holds; the first eight slots are IWICComponentInfo's, the next five IWICPixelFormatInfo's.</summary>+ [ComImport, Guid("a9db33a2-af5f-43c7-b679-74f5984b5aa4"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IWICPixelFormatInfo2+ {+ void GetComponentType();+ void GetCLSID();+ void GetSigningStatus();+ void GetAuthor();+ void GetVendorGUID();+ void GetVersion();+ void GetSpecVersion();+ void GetFriendlyName();+ void GetFormatGUID();+ void GetColorContext();+ void GetBitsPerPixel();+ void GetChannelCount();+ void GetChannelMask();++ [return: MarshalAs(UnmanagedType.Bool)]+ bool SupportsTransparency();++ int GetNumericRepresentation();+ }+}diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.csindex 7d2c6af6..3300a6e8 100644--- a/tests/Filee.Cli.Tests/CliTests.cs+++ b/tests/Filee.Cli.Tests/CliTests.cs@@ -193,6 +193,17 @@ public sealed class CliTests : IDisposableAssert.Contains("to-png", output);}+ [Fact]+ public async Task Jpeg_xr_converts_on_windows_and_is_no_download_away_elsewhere()+ {+ var (code, output, _) = await Run("formats", "jxr");++ Assert.Equal(Cli.Success, code);+ Assert.Equal(OperatingSystem.IsWindows(), output.Contains("png, jpg", StringComparison.Ordinal));+ // Elsewhere no download would help (on Windows, FFmpeg adds HEIC and video).+ Assert.Equal(OperatingSystem.IsWindows(), output.Contains("optional engines", StringComparison.Ordinal));+ }+/// <summary>Adds presets to the settings folder the CLI runs with.</summary>private void AddPresets(params Preset[] presets){diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 5b3d34fe..3ff957ca 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -176,7 +176,7 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);}@@ -228,7 +228,7 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);var ids = store.Profiles.Select(p => p.Id).ToList();Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));@@ -401,8 +401,8 @@ public class UserDataStoreTestsstore.Load();// ... and, from schema 15, the 3D model engine before Pandoc (no CAD or archive engine in this list), from- // schema 18 the PDF slides engine there too (no PDF text engine).- Assert.Equal(["magick", "email", "data", "vector", "model3d", "pdf-slides", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ // schema 18 the PDF slides engine there too (no PDF text engine), from schema 21 the WIC engine (no FFmpeg).+ Assert.Equal(["magick", "email", "data", "vector", "model3d", "pdf-slides", "wic", "pandoc", "libreoffice"], store.Settings.EnginePriority);}[Fact]@@ -641,10 +641,44 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "pdfium", "docx-writer", "pdf-text", "pdf-slides", "email", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "pdfium", "docx-writer", "pdf-text", "pdf-slides", "email", "wic", "pandoc", "libreoffice"], store.Settings.EnginePriority);Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);}+ [Fact]+ public void Version_20_settings_get_the_wic_engine_after_the_other_built_in_engines()+ {+ using var dir = new TempDir();+ File.WriteAllText(Path.Combine(dir.Path, "settings.json"),+ """{ "schemaVersion": 20, "enginePriority": ["magick", "pdfium", "hwpx-writer", "subtitle", "ffmpeg", "pandoc", "libreoffice"] }""");++ var store = new UserDataStore(dir.Path);+ store.Load();++ // Not near the top: the HWPX writer stays among the ranks that win ties (see EbookTests).+ Assert.Equal(["magick", "pdfium", "hwpx-writer", "subtitle", "wic", "ffmpeg", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);+ }++ [Fact]+ public void Version_20_libraries_open_jpeg_xr_on_the_images_donut()+ {+ // As written with schema 20: no JPEG XR yet; the user took PSD off the images donut and has a donut for .wdp.+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles();+ var images = profiles.Single(p => p.Id == "images");+ images.Extensions.RemoveAll(e => e is "jxr" or "wdp" or "hdp" or "psd");+ profiles.Insert(0, new ToolbarProfile { Id = "photos", Name = "Windows Photo Gallery", Extensions = ["wdp"] });++ Assert.True(SettingsMigrations.ApplyToLibrary(20, presets, profiles));++ Assert.Contains("jxr", images.Extensions);+ Assert.Contains("hdp", images.Extensions);+ Assert.DoesNotContain("wdp", images.Extensions);+ Assert.DoesNotContain("psd", images.Extensions); // only the new extensions are learnt+ Assert.False(SettingsMigrations.ApplyToLibrary(20, presets, profiles)); // once only+ }+[Fact]public void The_close_action_is_saved_and_one_from_a_newer_Filee_reads_as_ask(){diff --git a/tests/Filee.Engines.Tests/JpegXrBuilder.cs b/tests/Filee.Engines.Tests/JpegXrBuilder.csnew file mode 100644index 00000000..9fb5e070--- /dev/null+++ b/tests/Filee.Engines.Tests/JpegXrBuilder.cs@@ -0,0 +1,153 @@+// Writes JPEG XR test pictures with Windows' own encoder (WIC), the codec that saves HDR screenshots on Windows.++using System.Runtime.InteropServices;++namespace Filee.Engines.Tests;++internal static class JpegXrBuilder+{+ /// <summary>GUID_WICPixelFormat24bppBGR: 8-bit SDR pixels.</summary>+ public static readonly Guid Bgr24 = new("6fddc324-4e03-4bfe-b185-3d77768dc90c");++ /// <summary>GUID_WICPixelFormat64bppRGBAHalf: linear scRGB half floats, what Windows writes for HDR screenshots.</summary>+ public static readonly Guid RgbaHalf64 = new("6fddc324-4e03-4bfe-b185-3d77768dc93a");++ private static readonly Guid ImagingFactoryClsid = new("cacaf262-9370-4615-a13b-9f5539da4c0a");+ private static readonly Guid ContainerFormatWmp = new("57a37caa-367a-4540-916b-f183c5093a4b");+ private const uint GenericWrite = 0x40000000;+ private const int EncoderNoCache = 2;++ /// <summary>Writes a <paramref name="width"/> × <paramref name="height"/> picture of 8-bit B, G, R pixels.</summary>+ public static void WriteBgr(string path, int width, int height, Func<int, int, (byte R, byte G, byte B)> pixel)+ {+ var pixels = new byte[width * height * 3];+ for (var y = 0; y < height; y++)+ {+ for (var x = 0; x < width; x++)+ {+ var (r, g, b) = pixel(x, y);+ var i = (y * width + x) * 3;+ (pixels[i], pixels[i + 1], pixels[i + 2]) = (b, g, r);+ }+ }+ Write(path, width, height, Bgr24, pixels, width * 3);+ }++ /// <summary>Writes an HDR picture of opaque linear scRGB values (1.0 = 80 nits) as half floats.</summary>+ public static void WriteHdr(string path, int width, int height, Func<int, int, (float R, float G, float B)> pixel)+ {+ var halves = new Half[width * height * 4];+ for (var y = 0; y < height; y++)+ {+ for (var x = 0; x < width; x++)+ {+ var (r, g, b) = pixel(x, y);+ var i = (y * width + x) * 4;+ (halves[i], halves[i + 1], halves[i + 2], halves[i + 3]) = ((Half)r, (Half)g, (Half)b, (Half)1f);+ }+ }+ Write(path, width, height, RgbaHalf64, MemoryMarshal.AsBytes(halves.AsSpan()).ToArray(), width * 8);+ }++ private static void Write(string path, int width, int height, Guid pixelFormat, byte[] pixels, int stride)+ {+ if (!OperatingSystem.IsWindows())+ throw new PlatformNotSupportedException("WIC is part of Windows.");+ var factory = (IWICImagingFactory)Activator.CreateInstance(Type.GetTypeFromCLSID(ImagingFactoryClsid, throwOnError: true)!)!;+ IWICStream? stream = null;+ IWICBitmapEncoder? encoder = null;+ IWICBitmapFrameEncode? frame = null;+ try+ {+ stream = factory.CreateStream();+ stream.InitializeFromFilename(path, GenericWrite);+ var container = ContainerFormatWmp;+ encoder = factory.CreateEncoder(ref container, IntPtr.Zero);+ encoder.Initialize(stream, EncoderNoCache);+ encoder.CreateNewFrame(out frame, IntPtr.Zero);+ frame.Initialize(IntPtr.Zero);+ frame.SetSize((uint)width, (uint)height);+ var format = pixelFormat;+ frame.SetPixelFormat(ref format);+ Assert.Equal(pixelFormat, format); // the encoder takes these formats as they are+ frame.WritePixels((uint)height, (uint)stride, (uint)pixels.Length, pixels);+ frame.Commit();+ encoder.Commit();+ }+ finally+ {+ foreach (var comObject in new object?[] { frame, encoder, stream, factory })+ {+ if (comObject is not null)+ Marshal.FinalReleaseComObject(comObject);+ }+ }+ }++ // Only the methods the tests call are typed; the slots before them keep the vtable order and are never called.++ [ComImport, Guid("ec5ec8a9-c395-4314-9c77-54d7a935ff70"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IWICImagingFactory+ {+ void CreateDecoderFromFilename();+ void CreateDecoderFromStream();+ void CreateDecoderFromFileHandle();+ void CreateComponentInfo();+ void CreateDecoder();+ IWICBitmapEncoder CreateEncoder(ref Guid containerFormat, IntPtr vendor);+ void CreatePalette();+ void CreateFormatConverter();+ void CreateBitmapScaler();+ void CreateBitmapClipper();+ void CreateBitmapFlipRotator();+ IWICStream CreateStream();+ }++ /// <summary>IStream's eleven slots, then IWICStream's own.</summary>+ [ComImport, Guid("135ff860-22b7-4ddf-b0f6-218f4f299a43"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IWICStream+ {+ void Read();+ void Write();+ void Seek();+ void SetSize();+ void CopyTo();+ void Commit();+ void Revert();+ void LockRegion();+ void UnlockRegion();+ void Stat();+ void Clone();+ void InitializeFromIStream();+ void InitializeFromFilename([MarshalAs(UnmanagedType.LPWStr)] string fileName, uint desiredAccess);+ }++ [ComImport, Guid("00000103-a8f2-4877-ba0a-fd2b6645fb94"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IWICBitmapEncoder+ {+ void Initialize(IWICStream stream, int cacheOption);+ void GetContainerFormat();+ void GetEncoderInfo();+ void SetColorContexts();+ void SetPalette();+ void SetThumbnail();+ void SetPreview();+ void CreateNewFrame(out IWICBitmapFrameEncode frame, IntPtr encoderOptions);+ void Commit();+ }++ [ComImport, Guid("00000105-a8f2-4877-ba0a-fd2b6645fb94"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IWICBitmapFrameEncode+ {+ void Initialize(IntPtr encoderOptions);+ void SetSize(uint width, uint height);+ void SetResolution();+ void SetPixelFormat(ref Guid pixelFormat);+ void SetColorContexts();+ void SetPalette();+ void SetThumbnail();+ void WritePixels(uint lineCount, uint stride, uint bufferSize, [MarshalAs(UnmanagedType.LPArray)] byte[] pixels);+ void WriteSource();+ void Commit();+ }+}diff --git a/tests/Filee.Engines.Tests/JpegXrTests.cs b/tests/Filee.Engines.Tests/JpegXrTests.csnew file mode 100644index 00000000..ccc7fcda--- /dev/null+++ b/tests/Filee.Engines.Tests/JpegXrTests.cs@@ -0,0 +1,160 @@+// JPEG XR (.jxr) through the Windows Imaging Component: 8-bit pictures and HDR screenshots (half-float scRGB, tone-mapped+// to SDR). The pictures are written in the tests with Windows' own JPEG XR encoder.++using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Wic;+using ImageMagick;++namespace Filee.Engines.Tests;++public class JpegXrTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ /// <summary>SDR white of the test screenshots: 200 nits (scRGB 1.0 = 80 nits).</summary>+ private const float White = 2.5f;++ /// <summary>Linear value of sRGB 128 (middle grey on screen).</summary>+ private const float Grey = 0.2158f;++ private static void AssertDone(ConversionJob job)+ {+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");+ }++ private static IMagickColor<byte> Pixel(IMagickImage<byte> image, int x, int y) =>+ image.GetPixels().GetPixel(x, y).ToColor()!;++ [Fact]+ public void Jpeg_xr_is_read_with_the_windows_codec_and_on_windows_only()+ {+ // No ImageMagick build has a JPEG XR coder (it would need jxrlib); with one, other platforms could read it too.+ Assert.DoesNotContain(Enum.GetNames<MagickFormat>(), name => name is "Jxr" or "Wdp" or "Hdp");++ var status = fx.Catalog.StatusOf(fx.Converters.Single(c => c is WicImageConverter));+ Assert.Equal(OperatingSystem.IsWindows(), status.IsAvailable);+ if (!OperatingSystem.IsWindows())+ Assert.Equal("engine.reason.unsupported_platform", status.ReasonKey);+ var planner = fx.Catalog.CreatePlanner();+ Assert.Equal(OperatingSystem.IsWindows(), planner.CanConvert("jxr", "png"));+ if (!OperatingSystem.IsWindows())+ return;+ // Targets other engines write are reached through a lossless PNG.+ foreach (var target in new[] { "pdf", "icns", "svg" })+ Assert.Equal(("wic", "png"), planner.Plan("jxr", target)!.Steps.Select(s => (s.Converter.Id, s.To)).First());+ Assert.Equal(("wic", "png"), fx.Catalog.CreatePlanner(["ffmpeg"]).Plan("jxr", "heic")!.Steps.Select(s => (s.Converter.Id, s.To)).First());+ }++ [Fact]+ public async Task An_8_bit_jpeg_xr_converts_to_png_and_jpg()+ {+ Assert.SkipUnless(OperatingSystem.IsWindows(), "JPEG XR is read with the Windows Imaging Component.");+ var dir = fx.NewFolder();+ var jxr = Path.Combine(dir, "photo.jxr");+ JpegXrBuilder.WriteBgr(jxr, 64, 48, (x, _) => x < 32 ? ((byte)230, (byte)40, (byte)30) : ((byte)20, (byte)60, (byte)200));++ foreach (var target in new[] { "png", "jpg" })+ {+ var job = await fx.ConvertAsync([jxr], new Preset { TargetFormat = target });++ AssertDone(job);+ using var image = new MagickImage(job.Outputs.Single());+ Assert.Equal((64u, 48u), (image.Width, image.Height));+ Assert.False(image.HasAlpha);+ var left = Pixel(image, 8, 24);+ var right = Pixel(image, 56, 24);+ Assert.True(Math.Abs(left.R - 230) < 12 && Math.Abs(left.G - 40) < 12 && Math.Abs(left.B - 30) < 12, $"{target} left: {left}");+ Assert.True(Math.Abs(right.R - 20) < 12 && Math.Abs(right.G - 60) < 12 && Math.Abs(right.B - 200) < 12, $"{target} right: {right}");+ }+ }++ [Fact]+ public async Task An_hdr_screenshot_of_sdr_content_comes_out_as_it_was_drawn()+ {+ Assert.SkipUnless(OperatingSystem.IsWindows(), "JPEG XR is read with the Windows Imaging Component.");+ var dir = fx.NewFolder();+ var jxr = Path.Combine(dir, "desktop.jxr");+ // A desktop at 200 nits SDR brightness: white windows and a grey panel, nothing brighter than SDR white.+ JpegXrBuilder.WriteHdr(jxr, 100, 100, (x, y) => x < 50 && y < 50 ? (Grey * White, Grey * White, Grey * White) : (White, White, White));++ var job = await fx.ConvertAsync([jxr], new Preset { TargetFormat = "png", Image = { Resize = ResizeMode.Percent, ResizePercent = 50 } });++ AssertDone(job);+ using var image = new MagickImage(job.Outputs.Single());+ Assert.Equal((50u, 50u), (image.Width, image.Height)); // the preset applies as to any picture+ Assert.False(image.HasAlpha); // the half-float alpha channel is opaque everywhere+ // Clipping at scRGB 1.0 would make the grey 194 and the white 255; divided by the white level it is 128 again.+ Assert.InRange(Pixel(image, 10, 10).R, 124, 132);+ Assert.InRange(Pixel(image, 40, 40).R, 253, 255);+ }++ [Fact]+ public async Task Hdr_highlights_are_rolled_off_instead_of_clipping_or_darkening_the_picture()+ {+ Assert.SkipUnless(OperatingSystem.IsWindows(), "JPEG XR is read with the Windows Imaging Component.");+ var dir = fx.NewFolder();+ var jxr = Path.Combine(dir, "game.jxr");+ // The same desktop with a small 1000-nit highlight (scRGB 12.5) and a 400-nit one next to it.+ JpegXrBuilder.WriteHdr(jxr, 100, 100, (x, y) => (x, y) switch+ {+ ( < 50, < 50) => (Grey * White, Grey * White, Grey * White),+ ( >= 80 and < 85, >= 80 and < 85) => (12.5f, 12.5f, 12.5f),+ ( >= 90 and < 95, >= 80 and < 85) => (5f, 5f, 5f),+ _ => (White, White, White),+ });++ var job = await fx.ConvertAsync([jxr], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using var image = new MagickImage(job.Outputs.Single());+ var grey = Pixel(image, 20, 20).R;+ var white = Pixel(image, 70, 20).R;+ var bright = Pixel(image, 92, 82).R;+ var brightest = Pixel(image, 82, 82).R;+ Assert.InRange(grey, 122, 134); // below the shoulder: unchanged, not darkened by the 1000-nit peak+ Assert.InRange(white, 232, 250); // white gives up a little room to the highlights+ Assert.True(white < bright && bright <= brightest, $"white {white}, 400 nits {bright}, 1000 nits {brightest}");+ Assert.InRange(brightest, 250, 255);+ }++ [Fact]+ public void The_tone_curve_keeps_sdr_values_and_rolls_highlights_off_to_white()+ {+ // Nothing above white: the identity, so SDR content comes out unchanged.+ var sdr = new HdrToneMap(White, White);+ Assert.Equal(0.5f, sdr.Curve(0.5f));+ Assert.Equal(1f, sdr.Curve(1f), 4);++ // With a peak of 10× white: the identity up to the knee, then rising smoothly to exactly 1 at the peak.+ var hdr = new HdrToneMap(White, 10 * White);+ Assert.Equal(HdrToneMap.Knee, hdr.Curve(HdrToneMap.Knee));+ var previous = HdrToneMap.Knee;+ for (var value = HdrToneMap.Knee + 0.1f; value <= 10; value += 0.1f)+ {+ var mapped = hdr.Curve(value);+ Assert.True(mapped > previous && mapped <= 1, $"{value} → {mapped}");+ previous = mapped;+ }+ Assert.Equal(1f, hdr.Curve(10), 4);+ Assert.Equal(1f, hdr.Curve(50));++ // Hue is kept: a bright orange stays orange (R > G > B) instead of clipping towards yellow.+ Span<byte> rgba = stackalloc byte[4];+ hdr.Map(20, 10, 2, 1, rgba);+ Assert.True(rgba[0] > rgba[1] && rgba[1] > rgba[2], $"{rgba[0]} {rgba[1]} {rgba[2]}");+ hdr.Map(-0.5f, float.NaN, float.PositiveInfinity, float.NaN, rgba);+ Assert.Equal(new byte[] { 0, 0, 255, 255 }, rgba.ToArray());+ }++ [Fact]+ public void The_reference_white_is_the_99th_percentile_between_1_and_4()+ {+ float[] Picture(float common, float rare, int rarePerMille) =>+ [.. Enumerable.Range(0, 1000).Select(i => i < rarePerMille ? rare : common)];++ Assert.Equal(White, HdrToneMap.ReferenceWhite(Picture(White, 12.5f, 5))); // a small highlight is not white+ Assert.Equal(4f, HdrToneMap.ReferenceWhite(Picture(White, 12.5f, 300))); // a large bright area is, up to 320 nits+ Assert.Equal(1f, HdrToneMap.ReferenceWhite(Picture(0.4f, 0.2f, 500))); // a dim picture keeps scRGB's own white+ Assert.Equal(1f, HdrToneMap.ReferenceWhite([]));+ }+}