Skip to content

Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.

C#

JPEG exports are 4:4:4: WIC called natively for its subsampling option, the in-house encoder too

Alexander Graeff6732d26ac39
diff --git a/CLAUDE.md b/CLAUDE.md
index 766c4dc..822e283 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -129,6 +129,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
- **Export**: field, intensity or both, a still of the shown frame, from the current run when fresh and full,
else a run is made first; PNG/JPEG sequences, MPEG-1, OpenDML AVI, H.264 MP4 via Media Foundation (the only
Windows-bound library piece besides WIC JPEG, which has an in-house fallback), QuickTime Animation MOV, and
+ **JPEG is 4:4:4 in both encoders** (2026-10-18: WIC called natively for its subsampling option, which WPF's
+ wrapper never set; 4:2:0 averaged the colour, where a wave picture's information is, into blocky fringes even
+ at quality 100; 4:4:4 at 90 beat it in every channel at half the size), and
**OpenEXR sequences or stills** (2026-10-18, the user's choice for data export to NumPy, MATLAB, Octave add-ons
and viewers such as DJV): the stored halves themselves, one uncompressed "Y" channel per file, no colours,
brightness, outline or boxes; a sink that `WantsHalves` gets the plane from the job unrendered. Harness
@@ -139,8 +142,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
GPU step at 1080p 0.25–0.5 ms, CPU 6–14 ms; OpenCL build 0.3 s; a full-HD run of 2500 steps 5.4 s in RAM, bound by
the GPU readback. Renderer per 2880×1080 layer on ten cores: 8-bit 1.0 ms, 16-bit 2.0; vector rows gain 2× per
-core over scalar. Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p: WIC 15 ms, in-house 5.4 ms on
-ten cores; MP4 job 16 ms a frame. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the ball
+core over scalar. Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a frame
+single-threaded (9 ms a frame in a sequence job on half the cores), in-house 9.8 ms on ten cores (15 in a job);
+MP4 job 16 ms a frame. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the ball
lens run 105 s full quality (disk-bound), 61 s at half resolution with every second frame, in RAM. Settled by these
numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Direct3D display path.
diff --git a/WaveDudeNext.WPF/App.xaml.cs b/WaveDudeNext.WPF/App.xaml.cs
index 37691d7..05c15d4 100644
--- a/WaveDudeNext.WPF/App.xaml.cs
+++ b/WaveDudeNext.WPF/App.xaml.cs
@@ -223,9 +223,6 @@ public partial class App : Application
PrepareSettings();
FrameCache.Sweep();
ColorSchemeCatalog.Instance.Load();
- // JPEG through the WIC codec of Windows, the in-house encoder as the fallback (2026-10-15)
- Export.ExportFormats.AlternativeJpeg = Rendering.WicJpeg.Encoder;
-
ThemeController.Instance.Current = Settings.Default.Theme;
ThemeController.Instance.PropertyChanged += (_, args) =>
{
diff --git a/WaveDudeNext.WPF/Rendering/WicJpeg.cs b/WaveDudeNext.WPF/Rendering/WicJpeg.cs
deleted file mode 100644
index db15177..0000000
--- a/WaveDudeNext.WPF/Rendering/WicJpeg.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-// SPDX-License-Identifier: GPL-3.0-or-later
-// Copyright (C) 2026 Alexander Graef <[email protected]>
-//
-// This file is part of WaveDude Next, a 2D wave simulator.
-//
-// Based on the work of
-// JJM Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
-// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
-// Manuel (0x23, Diffraction Limited), author of WaveSimulator2D
-// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
-//
-// WaveDude Next is free software: you can redistribute it and/or modify it under
-// the terms of the GNU General Public License as published by the Free Software
-// Foundation, either version 3 of the License, or (at your option) any later
-// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
-// <https://www.gnu.org/licenses/>.
-
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using WaveDudeNext.Export;
-
-namespace WaveDudeNext.WPF.Rendering;
-
-/// <summary>
-/// JPEG through the Windows Imaging Component (WIC), the codec that ships with Windows, reached through
-/// WPF's <see cref="JpegBitmapEncoder"/>: a SIMD encoder on the CPU, single-threaded per picture (it does
-/// not use the GPU). Installed at start-up as <see cref="ExportFormats.AlternativeJpeg"/>, so the export
-/// uses it and falls back to the in-house <see cref="JpegEncoder"/> when it throws (2026-10-15, the user's
-/// choice). The quality number is handed over unchanged: WIC scales the IJG tables like the in-house
-/// encoder does, which the bench confirms by size and PSNR at the same number; its one quirk is that it
-/// drops chroma subsampling above about 90, so files grow there, not a wrong picture. Any thread; the
-/// export's sink thread is a single-threaded apartment, which WPF's encoder does not need but is happy with.
-/// </summary>
-public static class WicJpeg
-{
- /// <summary>Makes the encoder for frames of one size and quality.</summary>
- /// <param name="width">Frame width in pixels.</param>
- /// <param name="height">Frame height in pixels.</param>
- /// <param name="quality">1..100, WPF's <see cref="JpegBitmapEncoder.QualityLevel"/>.</param>
- public static Action<Stream, ReadOnlyMemory<int>> Encoder(int width, int height, int quality)
- {
- int level = Math.Clamp(quality, 1, 100);
- return (stream, pixels) => Write(stream, pixels, width, height, level);
- }
-
- /// <summary>Writes one packed BGRA32 frame as a JPEG.</summary>
- public static void Write(Stream stream, ReadOnlyMemory<int> pixels, int width, int height, int quality)
- {
- // BitmapSource.Create takes an array; the sinks hand over heap arrays, so this is a view, not a copy
- if (!MemoryMarshal.TryGetArray(pixels, out ArraySegment<int> segment) || segment.Offset != 0)
- {
- segment = new ArraySegment<int>(pixels.ToArray());
- }
- BitmapSource source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgr32, null, segment.Array!, width * 4);
- var encoder = new JpegBitmapEncoder { QualityLevel = quality };
- encoder.Frames.Add(BitmapFrame.Create(source));
- encoder.Save(stream);
- }
-}
diff --git a/WaveDudeNext/Export/ExportFormat.cs b/WaveDudeNext/Export/ExportFormat.cs
index ef6fe8b..0a34a26 100644
--- a/WaveDudeNext/Export/ExportFormat.cs
+++ b/WaveDudeNext/Export/ExportFormat.cs
@@ -42,12 +42,23 @@ public static class ExportFormats
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
- /// An alternative JPEG encoder the application may install (the WIC codec of Windows through WPF,
- /// 2026-10-15): given the frame size and the quality 1..100, a writer of one packed BGRA32 frame to a
- /// stream. Null uses the in-house <see cref="JpegEncoder"/>; when the alternative throws, the sink logs
- /// it once and goes on with the in-house encoder.
+ /// The preferred JPEG encoder: given the frame size and the quality 1..100, a writer of one packed BGRA32
+ /// frame to a stream. On Windows the WIC codec (<see cref="WicJpegEncoder.Encoder"/>, 4:4:4 natively),
+ /// elsewhere null, which means the in-house <see cref="JpegEncoder"/>; when the preferred one throws, the
+ /// sink logs it once and goes on with the in-house encoder. The harness swaps it to prove that fallback and
+ /// to time the in-house encoder in a job (2026-10-18: until then the application installed WIC through a
+ /// public hook, which the library no longer needs now that it holds the WIC encoder itself).
/// </summary>
- public static Func<int, int, int, Action<Stream, ReadOnlyMemory<int>>>? AlternativeJpeg { get; set; }
+ internal static Func<int, int, int, Action<Stream, ReadOnlyMemory<int>>>? PreferredJpeg { get; set; } = DefaultPreferredJpeg();
+
+ private static Func<int, int, int, Action<Stream, ReadOnlyMemory<int>>>? DefaultPreferredJpeg()
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ return WicJpegEncoder.Encoder;
+ }
+ return null;
+ }
/// <summary>
/// Frames of a sequence encoded at once: half the cores for encoders that are single-threaded per picture
@@ -56,25 +67,25 @@ public static class ExportFormats
public static int SequenceWorkers(bool encoderIsParallel) => encoderIsParallel ? 1 : Math.Clamp(Environment.ProcessorCount / 2, 1, 8);
/// <summary>
- /// The JPEG writer for a size and quality: the alternative with the in-house fallback (the in-house encoder
- /// is only built when needed), or the in-house one. One writer per thread: neither is shareable.
+ /// The JPEG writer for a size and quality: the preferred encoder with the in-house fallback (the in-house
+ /// encoder is only built when needed), or the in-house one. One writer per thread: neither is shareable.
/// </summary>
private static Action<Stream, ReadOnlyMemory<int>> JpegWriter(int width, int height, int quality)
{
JpegEncoder? inHouse = null;
Action<Stream, ReadOnlyMemory<int>> InHouse() => (inHouse ??= new JpegEncoder(width, height, quality)).Write;
- if (AlternativeJpeg is not { } alternative)
+ if (PreferredJpeg is not { } make)
{
return InHouse();
}
Action<Stream, ReadOnlyMemory<int>> preferred;
try
{
- preferred = alternative(width, height, quality);
+ preferred = make(width, height, quality);
}
catch (Exception ex)
{
- Logger.Warn(ex, "The alternative JPEG encoder is not available ({Message}); using the in-house encoder", ex.Message);
+ Logger.Warn(ex, "The preferred JPEG encoder is not available ({Message}); using the in-house encoder", ex.Message);
return InHouse();
}
bool fallen = false;
@@ -91,7 +102,7 @@ public static class ExportFormats
catch (Exception ex)
{
fallen = true;
- Logger.Warn(ex, "The alternative JPEG encoder failed ({Message}); the in-house encoder takes over", ex.Message);
+ Logger.Warn(ex, "The preferred JPEG encoder failed ({Message}); the in-house encoder takes over", ex.Message);
if (stream.CanSeek)
{
stream.SetLength(start);
@@ -186,7 +197,7 @@ public static class ExportFormats
() => (stream, frame) => PngEncoder.Write(stream, frame.Span, width, height), SequenceWorkers(encoderIsParallel: false), plannedFrames);
case ExportFormat.Jpeg:
return new ImageSequenceSink(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), ".jpg", width, height,
- () => JpegWriter(width, height, quality), SequenceWorkers(encoderIsParallel: AlternativeJpeg == null), plannedFrames);
+ () => JpegWriter(width, height, quality), SequenceWorkers(encoderIsParallel: PreferredJpeg == null), plannedFrames);
case ExportFormat.Exr:
return ExrSink.Sequence(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), width, height, plannedFrames);
case ExportFormat.Mpeg1:
diff --git a/WaveDudeNext/Export/JpegEncoder.cs b/WaveDudeNext/Export/JpegEncoder.cs
index f48d3da..d8a9e87 100644
--- a/WaveDudeNext/Export/JpegEncoder.cs
+++ b/WaveDudeNext/Export/JpegEncoder.cs
@@ -22,10 +22,13 @@ using System.Runtime.Intrinsics;
namespace WaveDudeNext.Export;
/// <summary>
-/// Writes baseline JPEG files (JFIF, 4:2:0, the standard quantisation and Huffman tables of ITU-T T.81
+/// Writes baseline JPEG files (JFIF, 4:4:4, the standard quantisation and Huffman tables of ITU-T T.81
/// Annex K) from packed BGRA32 frames, in-house. The quality 1..100 scales the quantisation tables the way
-/// the Independent JPEG Group's library does (50 is the tables as printed, 100 nearly lossless). Every
-/// macroblock row is a restart interval (a DRI segment, RSTn markers between rows), so the rows are
+/// the Independent JPEG Group's library does (50 is the tables as printed, 100 nearly lossless). The chroma
+/// is not subsampled (2026-10-18): a wave picture's information is in its colour, and 4:2:0 averaged it
+/// over 2 × 2 pixels, blocky fringes even at quality 100; 4:4:4 at quality 90 beat that in every channel
+/// at half the size. Every band of 16 pixel rows (two rows of 8 × 8 MCUs) is a restart interval (a DRI
+/// segment, RSTn markers between bands), so the bands are
/// transformed, quantised and Huffman-coded in parallel, each into its own byte buffer, and concatenated.
/// The transform is the AAN factorisation on SSE registers (<see cref="Dct8x8.ForwardAan"/>, its scaling
/// folded into the quantiser divisors, which are kept in zig-zag order so the coefficients land there
@@ -42,6 +45,8 @@ public sealed class JpegEncoder
private readonly float[] _chromaDivisorsZ = new float[64];
private readonly RowBuffer[] _rows;
private readonly byte[] _header;
+ private readonly int _mcuColumns;
+ private readonly int _mcuRows;
/// <param name="width">Frame width in pixels.</param>
/// <param name="height">Frame height in pixels.</param>
@@ -51,13 +56,15 @@ public sealed class JpegEncoder
Width = width;
Height = height;
Quality = Math.Clamp(quality, 1, 100);
- _planes = new YuvPlanes(width, height, studioRange: false);
+ _planes = new YuvPlanes(width, height, studioRange: false, subsampled: false);
+ _mcuColumns = (width + 7) / 8;
+ _mcuRows = (height + 7) / 8;
ScaleTables(Quality, LumaBase, _lumaQuant, _lumaDivisorsZ);
ScaleTables(Quality, ChromaBase, _chromaQuant, _chromaDivisorsZ);
_rows = new RowBuffer[_planes.MacroblockRows];
for (int i = 0; i < _rows.Length; i++)
{
- _rows[i] = new RowBuffer(Math.Max(4096, _planes.MacroblockColumns * 96));
+ _rows[i] = new RowBuffer(Math.Max(4096, _mcuColumns * 96));
}
_header = BuildHeader();
}
@@ -125,7 +132,10 @@ public sealed class JpegEncoder
return stream.ToArray();
}
- /// <summary>One restart interval: the row's macroblocks (Y₀ Y₁ Y₂ Y₃ Cb Cr each) transformed, quantised and coded, the DC predictors starting at zero.</summary>
+ /// <summary>
+ /// One restart interval: the band's two MCU rows (the last band may have one), each MCU a Y, a Cb and a Cr
+ /// block of the same 8 × 8 pixels, transformed, quantised and coded, the DC predictors starting at zero.
+ /// </summary>
private void EncodeRow(int mbRow)
{
YuvPlanes planes = _planes;
@@ -138,32 +148,26 @@ public sealed class JpegEncoder
int predictorY = 0;
int predictorCb = 0;
int predictorCr = 0;
- for (int mbColumn = 0; mbColumn < planes.MacroblockColumns; mbColumn++)
+ int lastMcuRow = Math.Min(mbRow * 2 + 1, _mcuRows - 1);
+ for (int mcuRow = mbRow * 2; mcuRow <= lastMcuRow; mcuRow++)
{
- for (int blockIndex = 0; blockIndex < 6; blockIndex++)
+ for (int mcuColumn = 0; mcuColumn < _mcuColumns; mcuColumn++)
{
- if (blockIndex < 4)
- {
- YuvPlanes.CopyBlock(planes.Y, planes.PaddedWidth, mbColumn * 16 + (blockIndex & 1) * 8, mbRow * 16 + (blockIndex >> 1) * 8, 128f, block);
- }
- else
- {
- YuvPlanes.CopyBlock(blockIndex == 4 ? planes.Cb : planes.Cr, planes.ChromaWidth, mbColumn * 8, mbRow * 8, 128f, block);
- }
- Dct8x8.ForwardAan(block, dct);
- bool luma = blockIndex < 4;
- QuantiseZigZag(dct, luma ? _lumaDivisorsZ : _chromaDivisorsZ, quantised);
- if (luma)
- {
- EncodeBlock(ref bits, quantised, LumaDcCodes, LumaDcLengths, LumaAcCodes, LumaAcLengths, ref predictorY);
- }
- else if (blockIndex == 4)
- {
- EncodeBlock(ref bits, quantised, ChromaDcCodes, ChromaDcLengths, ChromaAcCodes, ChromaAcLengths, ref predictorCb);
- }
- else
+ for (int component = 0; component < 3; component++)
{
- EncodeBlock(ref bits, quantised, ChromaDcCodes, ChromaDcLengths, ChromaAcCodes, ChromaAcLengths, ref predictorCr);
+ byte[] plane = component == 0 ? planes.Y : component == 1 ? planes.Cb : planes.Cr;
+ YuvPlanes.CopyBlock(plane, planes.PaddedWidth, mcuColumn * 8, mcuRow * 8, 128f, block);
+ Dct8x8.ForwardAan(block, dct);
+ if (component == 0)
+ {
+ QuantiseZigZag(dct, _lumaDivisorsZ, quantised);
+ EncodeBlock(ref bits, quantised, LumaDcCodes, LumaDcLengths, LumaAcCodes, LumaAcLengths, ref predictorY);
+ }
+ else
+ {
+ QuantiseZigZag(dct, _chromaDivisorsZ, quantised);
+ EncodeBlock(ref bits, quantised, ChromaDcCodes, ChromaDcLengths, ChromaAcCodes, ChromaAcLengths, ref component == 1 ? ref predictorCb : ref predictorCr);
+ }
}
}
}
@@ -251,21 +255,21 @@ public sealed class JpegEncoder
quant[66 + i] = _chromaQuant[Dct8x8.ZigZag[i]];
}
Segment(stream, 0xDB, quant);
- // SOF0: 8 bits, three components, Y sampled 2 × 2 with table 0, Cb and Cr 1 × 1 with table 1
+ // SOF0: 8 bits, three components all sampled 1 × 1 (4:4:4), Y with table 0, Cb and Cr with table 1
var frame = new byte[15];
frame[0] = 8;
BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(1), (ushort)Height);
BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(3), (ushort)Width);
frame[5] = 3;
- frame[6] = 1; frame[7] = 0x22; frame[8] = 0;
+ frame[6] = 1; frame[7] = 0x11; frame[8] = 0;
frame[9] = 2; frame[10] = 0x11; frame[11] = 1;
frame[12] = 3; frame[13] = 0x11; frame[14] = 1;
Segment(stream, 0xC0, frame);
// DHT: the four standard tables
Segment(stream, 0xC4, [.. DhtSegment(0x00, LumaDcCounts, LumaDcSymbols), .. DhtSegment(0x10, LumaAcCounts, LumaAcSymbols), .. DhtSegment(0x01, ChromaDcCounts, ChromaDcSymbols), .. DhtSegment(0x11, ChromaAcCounts, ChromaAcSymbols)]);
- // DRI: a restart interval of one macroblock row
+ // DRI: a restart interval of one band, two MCU rows (the last interval may be shorter, which the standard allows)
var interval = new byte[2];
- BinaryPrimitives.WriteUInt16BigEndian(interval, (ushort)_planes.MacroblockColumns);
+ BinaryPrimitives.WriteUInt16BigEndian(interval, (ushort)(2 * _mcuColumns));
Segment(stream, 0xDD, interval);
// SOS: three components with their DC/AC table pairs, spectral selection 0..63, no successive approximation
Segment(stream, 0xDA, [3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0]);
diff --git a/WaveDudeNext/Export/Mp4Writer.cs b/WaveDudeNext/Export/Mp4Writer.cs
index b4fa1c6..be8aef0 100644
--- a/WaveDudeNext/Export/Mp4Writer.cs
+++ b/WaveDudeNext/Export/Mp4Writer.cs
@@ -79,7 +79,7 @@ public sealed class Mp4Writer : IFrameSink
{
_padded = new int[_encodedWidth * _encodedHeight];
}
- _planes = new YuvPlanes(_encodedWidth, _encodedHeight, studioRange: true);
+ _planes = new YuvPlanes(_encodedWidth, _encodedHeight, studioRange: true, subsampled: true);
if (File.Exists(path))
{
File.Delete(path); // the sink writer appends to nothing, but a stale file must not survive a failure
diff --git a/WaveDudeNext/Export/Mpeg1Writer.cs b/WaveDudeNext/Export/Mpeg1Writer.cs
index 2b833f0..f7c5fe7 100644
--- a/WaveDudeNext/Export/Mpeg1Writer.cs
+++ b/WaveDudeNext/Export/Mpeg1Writer.cs
@@ -69,7 +69,7 @@ public sealed class Mpeg1Writer : IFrameSink
_frameRateCode = NearestFrameRateCode(framesPerSecond);
FrameRate = FrameRates[_frameRateCode - 1];
_quantiserScale = QuantiserScaleFor(quality);
- _planes = new YuvPlanes(width, height, studioRange: true);
+ _planes = new YuvPlanes(width, height, studioRange: true, subsampled: true);
// the AC levels are 8 F / (scale × W), truncated: the decoder reconstructs 2 × level × scale × W / 16 (11172-2, 2.4.4.1)
for (int i = 0; i < 64; i++)
{
diff --git a/WaveDudeNext/Export/WicJpegEncoder.cs b/WaveDudeNext/Export/WicJpegEncoder.cs
new file mode 100644
index 0000000..77c40b1
--- /dev/null
+++ b/WaveDudeNext/Export/WicJpegEncoder.cs
@@ -0,0 +1,316 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Alexander Graef <[email protected]>
+//
+// This file is part of WaveDude Next, a 2D wave simulator.
+//
+// Based on the work of
+// JJM Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
+// Manuel (0x23, Diffraction Limited), author of WaveSimulator2D
+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
+//
+// WaveDude Next is free software: you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
+// <https://www.gnu.org/licenses/>.
+
+using System.Buffers;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.ComTypes;
+using System.Runtime.Versioning;
+
+namespace WaveDudeNext.Export;
+
+/// <summary>
+/// JPEG through the Windows Imaging Component (WIC), the codec that ships with Windows, called natively
+/// (hand-written COM interfaces in the vtable order of <c>wincodec.h</c>, unused slots as placeholders) so
+/// that its <c>JpegYCrCbSubsampling</c> option can be set to 4:4:4. WPF's <c>JpegBitmapEncoder</c> never
+/// sets it, so it wrote 4:2:0 at every quality: the colour averaged over 2 × 2 pixels, which on a wave
+/// picture, whose information is in the colour, showed as blocky fringes even at quality 100 (2026-10-18;
+/// a 4:4:4 file at quality 90 beat the old quality 100 in every channel at half the size). The quality
+/// 1..100 goes over as <c>ImageQuality</c> 0.01..1, the scale WPF used, so the number means the same as
+/// before; 4:4:4 costs about half again per frame. The frame is written to the sink's stream through an
+/// <see cref="IStream"/> adapter. Windows only: <see cref="ExportFormats"/> prefers <see cref="Encoder"/>
+/// there, the in-house <see cref="JpegEncoder"/> is the fallback and the encoder elsewhere.
+/// Reusable for frames of one size; one thread at a time.
+/// </summary>
+[SupportedOSPlatform("windows")]
+public sealed class WicJpegEncoder
+{
+ private const uint ClsctxInprocServer = 1;
+ private const uint EncoderNoCache = 2; // WICBitmapEncoderNoCache
+ private const byte Subsampling444 = 3; // WICJpegYCrCbSubsampling444
+ private const ushort VtR4 = 4;
+ private const ushort VtUi1 = 17;
+ private const uint Propbag2TypeData = 1;
+
+ private static readonly Guid ClsidImagingFactory = new("cacaf262-9370-4615-a13b-9f5539da4c0a");
+ private static readonly Guid IidImagingFactory = new("ec5ec8a9-c395-4314-9c77-54d7a935ff70");
+ private static readonly Guid ContainerFormatJpeg = new("19e4a5aa-5662-4fc5-a0c0-1758028e1057");
+ private static readonly Guid PixelFormat32bppBgr = new("6fddc324-4e03-4bfe-b185-3d77768dc90e");
+ private static readonly Guid PixelFormat24bppBgr = new("6fddc324-4e03-4bfe-b185-3d77768dc90c");
+
+ private readonly IWICImagingFactory _factory;
+ private readonly float _imageQuality;
+ private byte[]? _rgb;
+
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="quality">1 (smallest file) to 100 (best picture).</param>
+ /// <exception cref="COMException">WIC is not available.</exception>
+ public WicJpegEncoder(int width, int height, int quality)
+ {
+ Width = width;
+ Height = height;
+ Quality = Math.Clamp(quality, 1, 100);
+ _imageQuality = Quality / 100f;
+ MediaFoundation.Check(CoCreateInstance(ClsidImagingFactory, IntPtr.Zero, ClsctxInprocServer, IidImagingFactory, out IntPtr factory));
+ try
+ {
+ _factory = (IWICImagingFactory)Marshal.GetObjectForIUnknown(factory);
+ }
+ finally
+ {
+ Marshal.Release(factory);
+ }
+ }
+
+ /// <summary>Frame width in pixels.</summary>
+ public int Width { get; }
+
+ /// <summary>Frame height in pixels.</summary>
+ public int Height { get; }
+
+ /// <summary>The quality 1..100 handed to the codec.</summary>
+ public int Quality { get; }
+
+ /// <summary>
+ /// The writer <see cref="ExportFormats"/> prefers on Windows: an encoder for frames of one size and
+ /// quality, made on the calling thread and used there. Throws when WIC is not available, which the sink
+ /// logs before it falls back to the in-house encoder.
+ /// </summary>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="quality">1..100.</param>
+ public static Action<Stream, ReadOnlyMemory<int>> Encoder(int width, int height, int quality) => new WicJpegEncoder(width, height, quality).Write;
+
+ /// <summary>Writes one frame as a 4:4:4 JPEG to <paramref name="stream"/> (left open), from its current position.</summary>
+ /// <param name="stream">Destination; seeking is relative to where it stands.</param>
+ /// <param name="pixels">Packed BGRA32 pixels, row-major, at least width × height.</param>
+ public unsafe void Write(Stream stream, ReadOnlyMemory<int> pixels)
+ {
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the picture.", nameof(pixels));
+ }
+ MediaFoundation.Check(_factory.CreateEncoder(ContainerFormatJpeg, IntPtr.Zero, out IWICBitmapEncoder encoder));
+ IWICBitmapFrameEncode? frame = null;
+ IPropertyBag2? options = null;
+ try
+ {
+ MediaFoundation.Check(encoder.Initialize(new StreamAdapter(stream), EncoderNoCache));
+ MediaFoundation.Check(encoder.CreateNewFrame(out frame, ref options));
+ PROPBAG2[] names =
+ [
+ new() { dwType = Propbag2TypeData, vt = VtR4, pstrName = "ImageQuality" },
+ new() { dwType = Propbag2TypeData, vt = VtUi1, pstrName = "JpegYCrCbSubsampling" },
+ ];
+ Variant[] values =
+ [
+ new() { vt = VtR4, data = BitConverter.SingleToUInt32Bits(_imageQuality) },
+ new() { vt = VtUi1, data = Subsampling444 },
+ ];
+ MediaFoundation.Check(options!.Write((uint)names.Length, names, values));
+ MediaFoundation.Check(frame.Initialize(options));
+ MediaFoundation.Check(frame.SetSize((uint)Width, (uint)Height));
+ Guid format = PixelFormat32bppBgr;
+ MediaFoundation.Check(frame.SetPixelFormat(ref format));
+ if (format == PixelFormat32bppBgr)
+ {
+ using MemoryHandle handle = pixels.Pin();
+ MediaFoundation.Check(frame.WritePixels((uint)Height, (uint)(Width * 4), (uint)(Width * Height * 4), (IntPtr)handle.Pointer));
+ }
+ else if (format == PixelFormat24bppBgr)
+ {
+ // the codec asked for 24 bits per pixel: the alpha byte is dropped
+ _rgb ??= new byte[Width * Height * 3];
+ ReadOnlySpan<int> source = pixels.Span[..(Width * Height)];
+ for (int i = 0; i < source.Length; i++)
+ {
+ _rgb[i * 3] = (byte)source[i];
+ _rgb[i * 3 + 1] = (byte)(source[i] >> 8);
+ _rgb[i * 3 + 2] = (byte)(source[i] >> 16);
+ }
+ fixed (byte* rgb = _rgb)
+ {
+ MediaFoundation.Check(frame.WritePixels((uint)Height, (uint)(Width * 3), (uint)_rgb.Length, (IntPtr)rgb));
+ }
+ }
+ else
+ {
+ throw new NotSupportedException("The JPEG codec accepts neither 32- nor 24-bit BGR pixels.");
+ }
+ MediaFoundation.Check(frame.Commit());
+ MediaFoundation.Check(encoder.Commit());
+ }
+ finally
+ {
+ if (frame != null)
+ {
+ Marshal.ReleaseComObject(frame);
+ }
+ if (options != null)
+ {
+ Marshal.ReleaseComObject(options);
+ }
+ Marshal.ReleaseComObject(encoder);
+ }
+ }
+
+ /// <summary>Encodes one frame to a byte array.</summary>
+ public byte[] Encode(ReadOnlyMemory<int> pixels)
+ {
+ using var stream = new MemoryStream();
+ Write(stream, pixels);
+ return stream.ToArray();
+ }
+
+ [DllImport("ole32.dll", ExactSpelling = true)]
+ private static extern int CoCreateInstance(in Guid clsid, IntPtr outer, uint context, in Guid iid, out IntPtr obj);
+
+ /// <summary>
+ /// The sink's stream as the <see cref="IStream"/> the encoder writes to: positions are relative to where the
+ /// stream stood when the adapter was made; the stream need not be readable (the sinks open theirs for
+ /// writing only). Reading, cloning, copying and locking are not supported.
+ /// </summary>
+ private sealed class StreamAdapter(Stream stream) : IStream
+ {
+ private readonly long _start = stream.CanSeek ? stream.Position : 0;
+
+ public void Read(byte[] pv, int cb, IntPtr pcbRead) => throw new NotSupportedException();
+
+ public void Write(byte[] pv, int cb, IntPtr pcbWritten)
+ {
+ stream.Write(pv, 0, cb);
+ if (pcbWritten != IntPtr.Zero)
+ {
+ Marshal.WriteInt32(pcbWritten, cb);
+ }
+ }
+
+ public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition)
+ {
+ long position = dwOrigin switch
+ {
+ 0 => _start + dlibMove, // STREAM_SEEK_SET
+ 1 => stream.Position + dlibMove, // STREAM_SEEK_CUR
+ 2 => stream.Length + dlibMove, // STREAM_SEEK_END
+ _ => throw new ArgumentOutOfRangeException(nameof(dwOrigin)),
+ };
+ if (position != stream.Position)
+ {
+ stream.Position = position;
+ }
+ if (plibNewPosition != IntPtr.Zero)
+ {
+ Marshal.WriteInt64(plibNewPosition, position - _start);
+ }
+ }
+
+ public void SetSize(long libNewSize) => stream.SetLength(_start + libNewSize);
+
+ public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten) => throw new NotSupportedException();
+
+ public void Commit(int grfCommitFlags) => stream.Flush();
+
+ public void Revert() => throw new NotSupportedException();
+
+ public void LockRegion(long libOffset, long cb, int dwLockType) => throw new NotSupportedException();
+
+ public void UnlockRegion(long libOffset, long cb, int dwLockType) => throw new NotSupportedException();
+
+ public void Stat(out STATSTG pstatstg, int grfStatFlag) => pstatstg = new STATSTG { type = 2 /* STGTY_STREAM */, cbSize = stream.CanSeek ? stream.Length - _start : 0 };
+
+ public void Clone(out IStream ppstm) => throw new NotSupportedException();
+ }
+
+ /// <summary><c>PROPBAG2</c>: the name and type of one encoder option.</summary>
+ [StructLayout(LayoutKind.Sequential)]
+ private struct PROPBAG2
+ {
+ public uint dwType;
+ public ushort vt;
+ public ushort cfType;
+ public uint dwHint;
+ [MarshalAs(UnmanagedType.LPWStr)] public string pstrName;
+ public Guid clsid;
+ }
+
+ /// <summary>A <c>VARIANT</c> as 24 bytes: the type, three reserved words, the value in the first bytes of the union.</summary>
+ [StructLayout(LayoutKind.Sequential)]
+ private struct Variant
+ {
+ public ushort vt;
+ public ushort reserved1;
+ public ushort reserved2;
+ public ushort reserved3;
+ public ulong data;
+ public ulong data2;
+ }
+
+ [ComImport]
+ [Guid("ec5ec8a9-c395-4314-9c77-54d7a935ff70")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IWICImagingFactory
+ {
+ [PreserveSig] int CreateDecoderFromFilename();
+ [PreserveSig] int CreateDecoderFromStream();
+ [PreserveSig] int CreateDecoderFromFileHandle();
+ [PreserveSig] int CreateComponentInfo();
+ [PreserveSig] int CreateDecoder();
+ [PreserveSig] int CreateEncoder(in Guid containerFormat, IntPtr vendor, out IWICBitmapEncoder encoder);
+ }
+
+ [ComImport]
+ [Guid("00000103-a8f2-4877-ba0a-fd2b6645fb94")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IWICBitmapEncoder
+ {
+ [PreserveSig] int Initialize(IStream stream, uint cacheOption);
+ [PreserveSig] int GetContainerFormat();
+ [PreserveSig] int GetEncoderInfo();
+ [PreserveSig] int SetColorContexts();
+ [PreserveSig] int SetPalette();
+ [PreserveSig] int SetThumbnail();
+ [PreserveSig] int SetPreview();
+ [PreserveSig] int CreateNewFrame(out IWICBitmapFrameEncode frame, ref IPropertyBag2? options);
+ [PreserveSig] int Commit();
+ }
+
+ [ComImport]
+ [Guid("00000105-a8f2-4877-ba0a-fd2b6645fb94")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IWICBitmapFrameEncode
+ {
+ [PreserveSig] int Initialize(IPropertyBag2? options);
+ [PreserveSig] int SetSize(uint width, uint height);
+ [PreserveSig] int SetResolution();
+ [PreserveSig] int SetPixelFormat(ref Guid format);
+ [PreserveSig] int SetColorContexts();
+ [PreserveSig] int SetPalette();
+ [PreserveSig] int SetThumbnail();
+ [PreserveSig] int WritePixels(uint lineCount, uint stride, uint bufferSize, IntPtr pixels);
+ [PreserveSig] int WriteSource();
+ [PreserveSig] int Commit();
+ }
+
+ [ComImport]
+ [Guid("22f55882-280b-11d0-a8a9-00a0c90c2004")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IPropertyBag2
+ {
+ [PreserveSig] int Read();
+ [PreserveSig] int Write(uint count, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] PROPBAG2[] properties, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] Variant[] values);
+ }
+}
diff --git a/WaveDudeNext/Export/YuvPlanes.cs b/WaveDudeNext/Export/YuvPlanes.cs
index 0c38b99..acd48be 100644
--- a/WaveDudeNext/Export/YuvPlanes.cs
+++ b/WaveDudeNext/Export/YuvPlanes.cs
@@ -21,8 +21,9 @@ using System.Runtime.Intrinsics.X86;
namespace WaveDudeNext.Export;
/// <summary>
-/// A frame as 8-bit Y, Cb and Cr planes with the chroma sampled 2 × 2 (4:2:0), padded to whole 16 × 16
-/// macroblocks by repeating the last column and row, which is what both the JPEG and the MPEG-1 encoder
+/// A frame as 8-bit Y, Cb and Cr planes, the chroma either at full resolution (4:4:4, the JPEG encoder since
+/// 2026-10-18: a wave picture's information is in its colour) or sampled 2 × 2 (4:2:0, MPEG-1), padded to
+/// whole 16 × 16 macroblocks by repeating the last column and row, which is what both encoders
/// consume. Converted with the BT.601 matrix: full range (JFIF, Y 0..255) for JPEG, studio range
/// (Y 16..235, chroma 16..240) for MPEG-1, which is what its decoders assume. Four pixels at a time on
/// <see cref="Vector128{T}"/>, the width every x64 and ARM64 machine accelerates (2026-10-14, the user's rule:
@@ -33,17 +34,19 @@ public sealed class YuvPlanes
/// <param name="width">Picture width in pixels.</param>
/// <param name="height">Picture height in pixels.</param>
/// <param name="studioRange">Studio (MPEG) range instead of full (JFIF) range.</param>
- public YuvPlanes(int width, int height, bool studioRange)
+ /// <param name="subsampled">Chroma sampled 2 × 2 (4:2:0) instead of at full resolution (4:4:4).</param>
+ public YuvPlanes(int width, int height, bool studioRange, bool subsampled)
{
Width = width;
Height = height;
StudioRange = studioRange;
+ Subsampled = subsampled;
MacroblockColumns = (width + 15) / 16;
MacroblockRows = (height + 15) / 16;
PaddedWidth = MacroblockColumns * 16;
PaddedHeight = MacroblockRows * 16;
Y = new byte[PaddedWidth * PaddedHeight];
- Cb = new byte[PaddedWidth / 2 * (PaddedHeight / 2)];
+ Cb = new byte[subsampled ? PaddedWidth / 2 * (PaddedHeight / 2) : Y.Length];
Cr = new byte[Cb.Length];
if (studioRange)
{
@@ -67,6 +70,9 @@ public sealed class YuvPlanes
/// <summary>Whether the planes use the studio range.</summary>
public bool StudioRange { get; }
+ /// <summary>Whether the chroma is sampled 2 × 2 (4:2:0); otherwise it has the luma's resolution (4:4:4).</summary>
+ public bool Subsampled { get; }
+
/// <summary>Macroblocks per row.</summary>
public int MacroblockColumns { get; }
@@ -79,13 +85,13 @@ public sealed class YuvPlanes
/// <summary>Height of the Y plane, a multiple of 16.</summary>
public int PaddedHeight { get; }
- /// <summary>Width of the chroma planes.</summary>
- public int ChromaWidth => PaddedWidth / 2;
+ /// <summary>Width of the chroma planes: half the padded width when <see cref="Subsampled"/>, else all of it.</summary>
+ public int ChromaWidth => Subsampled ? PaddedWidth / 2 : PaddedWidth;
/// <summary>Luma plane, <see cref="PaddedWidth"/> × <see cref="PaddedHeight"/>, row-major.</summary>
public byte[] Y { get; }
- /// <summary>Blue-difference plane, <see cref="ChromaWidth"/> × <see cref="PaddedHeight"/> / 2.</summary>
+ /// <summary>Blue-difference plane, <see cref="ChromaWidth"/> wide, half the padded height when <see cref="Subsampled"/>, else all of it.</summary>
public byte[] Cb { get; }
/// <summary>Red-difference plane, like <see cref="Cb"/>.</summary>
@@ -126,7 +132,16 @@ public sealed class YuvPlanes
cb[x] = _matrix[4] + _matrix[5] * r + _matrix[6] * g + _matrix[7] * b;
cr[x] = _matrix[8] + _matrix[9] * r + _matrix[10] * g + _matrix[11] * b;
}
- if ((y & 1) == 0)
+ if (!Subsampled)
+ {
+ int chromaOffset = y * paddedWidth;
+ for (int cx = 0; cx < paddedWidth; cx++)
+ {
+ Cb[chromaOffset + cx] = ClampByte(cb[cx]);
+ Cr[chromaOffset + cx] = ClampByte(cr[cx]);
+ }
+ }
+ else if ((y & 1) == 0)
{
cb.CopyTo(cbAbove);
cr.CopyTo(crAbove);
diff --git a/_tools/library_check/ExportChecks.cs b/_tools/library_check/ExportChecks.cs
index 019d226..5a9db05 100644
--- a/_tools/library_check/ExportChecks.cs
+++ b/_tools/library_check/ExportChecks.cs
@@ -68,6 +68,27 @@ internal static class ExportChecks
File.WriteAllBytes(jpgPath, jpg);
byte[] jpgLow = new JpegEncoder(w, h, 20).Encode(frames[0]);
check(jpgLow.Length < jpg.Length, "jpeg: quality 20 is smaller than quality 90 (" + jpgLow.Length + " < " + jpg.Length + " bytes)");
+ check(SamplingFactors(jpg) is [0x11, 0x11, 0x11], "jpeg: the frame header says 4:4:4, every component sampled 1 × 1");
+ if (OperatingSystem.IsWindows())
+ {
+ // the app's path: WIC called natively with its subsampling option, which WPF's wrapper never set (4:2:0 at every quality, 2026-10-18)
+ byte[] wic = WicEncode(frames[0], w, h, 90);
+ check(wic.Length > 4 && wic[0] == 0xFF && wic[1] == 0xD8 && SamplingFactors(wic) is [0x11, 0x11, 0x11], "jpeg by WIC: a JPEG whose frame header says 4:4:4");
+ using (var file = new MemoryStream())
+ {
+ file.Write([1, 2, 3]); // the sink's stream may stand past a start: the adapter's positions are relative to it
+ new WicJpegEncoder(w, h, 90).Write(file, frames[0]);
+ check(file.Length == 3 + wic.Length && file.ToArray().AsSpan(3).SequenceEqual(wic), "jpeg by WIC: written to a stream from its current position, byte for byte the same");
+ }
+ if (Ffmpeg != null)
+ {
+ string wicPath = Path.Combine(folder, "wic.jpg");
+ File.WriteAllBytes(wicPath, wic);
+ byte[]? rgb = Decode(wicPath, w, h, out int count);
+ double psnr = rgb == null ? 0 : Psnr(rgb, frames[0], w, h);
+ check(rgb != null && count == 1 && psnr > 30, "jpeg by WIC: ffmpeg decodes it at " + psnr.ToString("0.0", CultureInfo.InvariantCulture) + " dB (> 30)");
+ }
+ }
if (Ffmpeg != null)
{
byte[]? rgb = Decode(jpgPath, w, h, out int count);
@@ -321,11 +342,12 @@ internal static class ExportChecks
var edgeProbe = new Probe { Kind = ProbeKind.Point, AX = 0, AY = 0 };
ProbeMarkers.DrawStrokes(marked, w, h, edgeProbe);
check(marked[0] == white && ProbeMarkers.Label(3, true, true) == "3B" && ProbeMarkers.Label(2, false, false) == "2", "markers: a cross at the corner is clipped, labels read 3B and 2");
- // an alternative JPEG encoder is used (on several workers), and one that throws on a frame hands that frame to the
+ // the preferred JPEG encoder is used (on several workers), and one that throws on a frame hands that frame to the
// in-house encoder; the frames after it come from whichever encoder their worker is left with, both valid
int alternativeCalls = 0;
int secondFrameMark = (frames[1][1] >> 16) & 0xFF;
- ExportFormats.AlternativeJpeg = (fw, fh, q) => (stream, frame) =>
+ Func<int, int, int, Action<Stream, ReadOnlyMemory<int>>>? preferred = ExportFormats.PreferredJpeg;
+ ExportFormats.PreferredJpeg = (fw, fh, q) => (stream, frame) =>
{
Interlocked.Increment(ref alternativeCalls);
if (((frame.Span[1] >> 16) & 0xFF) == secondFrameMark)
@@ -341,12 +363,12 @@ internal static class ExportChecks
alt.Add(frames[1]);
alt.Add(frames[2]);
}
- ExportFormats.AlternativeJpeg = null;
+ ExportFormats.PreferredJpeg = preferred;
byte[] alt0 = File.ReadAllBytes(Path.Combine(folder, "alt", "alt_0000.jpg"));
byte[] alt1 = File.ReadAllBytes(Path.Combine(folder, "alt", "alt_0001.jpg"));
byte[] alt2 = File.ReadAllBytes(Path.Combine(folder, "alt", "alt_0002.jpg"));
check(alternativeCalls >= 2 && alt0[1] == (byte)'P' && alt1[0] == 0xFF && alt1[1] == 0xD8 && (alt2[1] == (byte)'P' || (alt2[0] == 0xFF && alt2[1] == 0xD8)),
- "formats: the alternative JPEG encoder is used; the frame it throws on is rewound and written by the in-house encoder");
+ "formats: the preferred JPEG encoder is used; the frame it throws on is rewound and written by the in-house encoder");
CheckJob(check, folder);
}
@@ -490,7 +512,7 @@ internal static class ExportChecks
var jpeg = new JpegEncoder(w, h, 85);
Time("jpeg encode (q 85)", () => jpeg.Encode(frame), 5);
Console.WriteLine($" phases: convert {jpeg.LastPhases.Convert:0.0} ms, rows {jpeg.LastPhases.Rows:0.0} ms; Vector128 accelerated: {System.Runtime.Intrinsics.Vector128.IsHardwareAccelerated}, Vector256: {System.Runtime.Intrinsics.Vector256.IsHardwareAccelerated}, Vector<float>.Count {System.Numerics.Vector<float>.Count}");
- var planes = new YuvPlanes(w, h, false);
+ var planes = new YuvPlanes(w, h, studioRange: false, subsampled: false);
Time(" of which yuv conversion", () => planes.Convert(frame), 5);
jpeg.ParallelRows = false;
Time("jpeg encode, rows one after the other", () => jpeg.Encode(frame), 3);
@@ -502,7 +524,7 @@ internal static class ExportChecks
Time($"jpeg encode on {threads} thread(s)", () => jpeg.Encode(frame), 3);
}
jpeg.MaxThreads = -1;
- // the WIC codec of Windows through WPF's encoder (the same call the app's WicJpeg makes), timed and compared at the same quality
+ // the WIC codec of Windows called natively at 4:4:4 (the app's path), timed and compared at the same quality
if (OperatingSystem.IsWindows())
{
byte[] inHouse = jpeg.Encode(frame);
@@ -528,7 +550,7 @@ internal static class ExportChecks
}
}
// the per-block costs, single-threaded over as many blocks as a frame has
- int blocks = planes.MacroblockColumns * planes.MacroblockRows * 6;
+ int blocks = planes.MacroblockColumns * planes.MacroblockRows * (planes.Subsampled ? 6 : 12);
var block = new float[64];
var dct = new float[64];
Time($" {blocks} block copies", () => { for (int i = 0; i < blocks; i++) { YuvPlanes.CopyBlock(planes.Y, planes.PaddedWidth, (i % planes.MacroblockColumns) * 16, (i / planes.MacroblockColumns % planes.MacroblockRows) * 16, 128f, block); } }, 3);
@@ -657,11 +679,12 @@ internal static class ExportChecks
File.Delete(raw);
}
}
+ Func<int, int, int, Action<Stream, ReadOnlyMemory<int>>>? preferredJpeg = ExportFormats.PreferredJpeg;
foreach ((string name, Func<IFrameSink> open) in new (string, Func<IFrameSink>)[]
{
("png sequence", () => ExportFormats.Open(ExportFormat.Png, Path.Combine(folder, "j.png"), w, h, 30, 85, 60)),
- ("jpeg sequence (in-house)", () => ExportFormats.Open(ExportFormat.Jpeg, Path.Combine(folder, "j.jpg"), w, h, 30, 85, 60)),
- ("jpeg sequence (WIC)", () => { ExportFormats.AlternativeJpeg = (fw, fh, q) => (stream, frame) => stream.Write(WicEncode(frame.ToArray(), fw, fh, q)); return ExportFormats.Open(ExportFormat.Jpeg, Path.Combine(folder, "k.jpg"), w, h, 30, 85, 60); }),
+ ("jpeg sequence (in-house)", () => { ExportFormats.PreferredJpeg = null; return ExportFormats.Open(ExportFormat.Jpeg, Path.Combine(folder, "j.jpg"), w, h, 30, 85, 60); }),
+ ("jpeg sequence (WIC, the library's choice on Windows)", () => ExportFormats.Open(ExportFormat.Jpeg, Path.Combine(folder, "k.jpg"), w, h, 30, 85, 60)),
("mpeg-1", () => ExportFormats.Open(ExportFormat.Mpeg1, Path.Combine(folder, "j.mpg"), w, h, 30, 85, 60)),
("avi", () => ExportFormats.Open(ExportFormat.Avi, Path.Combine(folder, "j.avi"), w, h, 30, 85, 60)),
("mov (Animation)", () => ExportFormats.Open(ExportFormat.Mov, Path.Combine(folder, "j.mov"), w, h, 30, 85, 60)),
@@ -669,7 +692,7 @@ internal static class ExportChecks
("mp4, writer not throttling", () => { Mp4Writer.Throttle = false; return ExportFormats.Open(ExportFormat.Mp4, Path.Combine(folder, "k.mp4"), w, h, 30, 85, 60); }),
})
{
- if (name == "mp4" && !(OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4)))
+ if ((name == "mp4" && !(OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4))) || (name.StartsWith("jpeg sequence (WIC", StringComparison.Ordinal) && preferredJpeg == null))
{
continue;
}
@@ -680,7 +703,7 @@ internal static class ExportChecks
job.Completion.Wait();
string ratio = job.Targets[0].Sink is MovAnimationWriter movSink ? $", {(double)store.Count * w * h * 3 / Math.Max(1, movSink.FrameBytes):0.00} : 1 on the run's frames" : "";
Console.WriteLine($" job to {name}: {clock.Elapsed.TotalMilliseconds / store.Count:0.0} ms per frame ({job.State}){ratio}");
- ExportFormats.AlternativeJpeg = null;
+ ExportFormats.PreferredJpeg = preferredJpeg;
Mp4Writer.Throttle = true;
}
}
@@ -690,15 +713,29 @@ internal static class ExportChecks
}
}
- /// <summary>What the app's WicJpeg does: WPF's JpegBitmapEncoder over a Bgr32 bitmap of the frame.</summary>
- private static byte[] WicEncode(int[] frame, int w, int h, int quality)
+ /// <summary>The app's JPEG path: the WIC codec called natively at 4:4:4.</summary>
+ [System.Runtime.Versioning.SupportedOSPlatform("windows")]
+ private static byte[] WicEncode(int[] frame, int w, int h, int quality) => new WicJpegEncoder(w, h, quality).Encode(frame);
+
+ /// <summary>The three components' sampling factor bytes from the SOF0 segment, or null when there is none.</summary>
+ private static byte[]? SamplingFactors(byte[] jpg)
{
- var source = System.Windows.Media.Imaging.BitmapSource.Create(w, h, 96, 96, System.Windows.Media.PixelFormats.Bgr32, null, frame, w * 4);
- var encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder { QualityLevel = quality };
- encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(source));
- using var stream = new MemoryStream();
- encoder.Save(stream);
- return stream.ToArray();
+ int i = 2;
+ while (i + 4 <= jpg.Length && jpg[i] == 0xFF)
+ {
+ int marker = jpg[i + 1];
+ int length = (jpg[i + 2] << 8) | jpg[i + 3];
+ if (marker == 0xC0 && jpg[i + 9] == 3)
+ {
+ return [jpg[i + 11], jpg[i + 14], jpg[i + 17]];
+ }
+ if (marker == 0xDA)
+ {
+ break;
+ }
+ i += 2 + length;
+ }
+ return null;
}
private static void Time(string what, Action action, int repeats)