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#

Export: PNG and JPEG sequences, MPEG-1, AVI, H.264 MP4; busy indicator, taskbar progress, computing overlay

Alexander Graef05b86e2cb711
diff --git a/.gitignore b/.gitignore
index e0ea4a6..c433975 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,23 @@ _tools/*.txt
# Claude Code local permissions
.claude/settings.local.json
+
+# exports and saved projects beside the author's examples are never committed
+Wave_Dude_Examples/**/*.wdproj
+Wave_Dude_Examples/**/*.avi
+Wave_Dude_Examples/**/*.mp4
+Wave_Dude_Examples/**/*.mpg
+Wave_Dude_Examples/**/*_field/
+Wave_Dude_Examples/**/*_intensity/
+Wave_Dude_Examples/**/*_field_*.png
+Wave_Dude_Examples/**/*_intensity_*.png
+
+# exports and saved projects beside the author's examples are never committed
+Wave_Dude_Examples/**/*.wdproj
+Wave_Dude_Examples/**/*.avi
+Wave_Dude_Examples/**/*.mp4
+Wave_Dude_Examples/**/*.mpg
+Wave_Dude_Examples/**/*_field/
+Wave_Dude_Examples/**/*_intensity/
+Wave_Dude_Examples/**/*_field_*.png
+Wave_Dude_Examples/**/*_intensity_*.png
diff --git a/CLAUDE.md b/CLAUDE.md
index c916d8e..3fabd1d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -41,7 +41,22 @@ WPF shell as it stands:
(persisted in settings); the native title bar is darkened via DWM. Use `DynamicResource` for every
theme brush.
- Logging: NLog; `Info` and up reach the status bar (`Logging/StatusBarTarget`, Warn/Error coloured),
- everything reaches the Messages pane and the log file next to the exe (Debug builds).
+ everything reaches the Messages pane in every build (2026-10-14; the pane hides Trace and Debug by default
+ in Release, its level toggles show them) and the log file next to the exe (Debug builds; Info and up in
+ Release). Debug lines say what the application decides: scratch requests and their reason, stale marks,
+ automatic re-runs postponed or skipped and why, discarded runs, every export step (path, format, range,
+ the run decision, each target's colours, outline and boxes). Keep adding them where a decision is made.
+- **Computing overlay** (2026-10-14, the user's rule, after the author read a frame in the making as "the
+ preview does not update"): while a scratch frame for the position is being computed (`MainWindow.
+ IsComputingFrame`, from the request to its result or a newer request's) and that has lasted longer than
+ 150 ms, each picture dims (black at 45 %) under a turning three-quarter ring (`PreviewPane.
+ IsBusyOverlayVisible`, the `Spinner` style with a storyboard on `IsVisible`); the overlay goes the moment
+ the frame arrives, and shorter waits pass unmarked so a fast machine does not strobe. A frame that was
+ skipped (over the scratch budget) with no stored frame to stand in shows a note on the pictures instead
+ (`IsFrameSkipped`, `PreviewNotComputed`, id `PreviewNotComputed`), since no spinner would ever resolve it.
+- **Taskbar progress** (2026-10-14, the user's rule): the status bar's busy bar (an export's frames, or the
+ marquee while an export waits for its run or a scratch frame computes) is mirrored on the taskbar button
+ through WPF's `TaskbarItemInfo` (`MainWindow.Taskbar.cs`, fed from `UpdateBusy`).
- **Simulation** (2026-10-09): menu Simulation > Run (F5), Pause/Resume (F6), Stop (Shift+F5, also
Esc). `OnRun` decodes the scene image (`Rendering/SceneImageLoader`, WPF decoders → BGRA bytes),
snapshots the project into a `RunSpec`, checks the cache drive, creates the `FrameStore` and
@@ -235,7 +250,123 @@ WPF shell as it stands:
in canvas pixels. **An auto-scaled value axis is symmetric about zero** for an amplitude (±largest
magnitude + 8 %), from zero up for an intensity, and stays at the fixed range while the data is all zeros
(`ProbeGraph.AutoRange`, 2026-10-14, the user's rule: the author's independent fit of both ends made the
- zero line wander and the labels flicker while the first oscillations arrived). Still open: the signal lane under the timeline (roadmap) and the box in exports.
+ zero line wander and the labels flicker while the first oscillations arrived). Still open: the signal lane under the timeline (roadmap); the box in exports is drawn (see "Export").
+- **Export** (2026-10-14, the user's design): File > Export > Field… / Intensity… / Both…, the same three on each
+ picture's context menu (its own layer first; `Controls`-less: a `ContextMenu` on the picture cell with
+ `CommandTarget` = the cell, ids `ContextExportField|Intensity|Both`). The standard Save dialog picks the
+ format by extension and the name, pre-set to `<project>_field` / `_intensity` in the project file's folder
+ (last used folder for an unsaved project; `LastExportFolder`, `ExportFilterIndex` settings); "Both" writes
+ `<name>_field` and `<name>_intensity` from one name (a typed `_field`/`_intensity` is stripped). A sequence
+ chosen as `C:\Temp\name.png` goes to `C:\Temp\name\name_0000.png` and on; a non-empty folder is replaced only
+ after a Yes. **No automatic export, no project saving**: export is a command at any time. **There is always a
+ run to export**: the current one when it is fresh, finished (or in progress: the export waits) and has the
+ intensity plane when asked for; else a run is started first (`StartRun(automatic, trackIntensity)`,
+ `RunSpec.Create(…, trackIntensity)`) and awaited (`EnsureRunForExport`, status "Export: waiting for the run";
+ an edit meanwhile restarts it, three attempts). The range is `Display.ExportFrom/To` in frames like the in/out
+ points, rendered with the display settings as they are, the outline per `OverlayInExport`
+ (`GlowingEdges.BlendAdditive`), and the probe graph boxes when `Display.ProbeGraphsInExport` (new, default
+ on) through `Rendering/ProbeGraphPainter` (the probes cloned, each box drawn with `Controls/ProbeGraphDrawing`,
+ the drawing code shared with the overlay, into a `RenderTargetBitmap` on the export's STA thread and
+ blended in), and **the probe markers in the author's style** when `Display.ProbeMarkersInExport` (2026-10-15,
+ default on, as his program always drew them): `Export/ProbeMarkers` strokes the crosses and a line probe's
+ line on the pixels, black radius 2 under white radius 1, arms max(6, height/120), and the painter sets the
+ number ("1", or "1A"/"1B", in project order over the active probes) in bold Segoe UI at max(12, height/60) px
+ with a drop shadow above and to the right of each cross; source handles are not drawn (he never did).
+ `DisplayLayer.Export` is gone (it meant "export on the next run"). The `ExportJob` reports to
+ the status bar (`StatusExport` text + progress bar, `ExportStatusConverter`); Esc cancels it (Stop prefers
+ the export over the run); runs are not started, Play does nothing and the auto re-run waits while an export
+ reads the store (`IsExporting`); New/Open/Close cancel it; closing waits up to 10 s for the files. Formats
+ (`WaveDude.Export`, in-house but MP4): PNG sequence (lossless, Paeth, `PngEncoder`), JPEG sequence (baseline
+ 4:2:0, Annex K tables scaled IJG-style, `JpegEncoder`), MPEG-1 I-pictures in a program stream (`Mpeg1Writer`:
+ one slice per macroblock row, default matrix, quantiser 31..1 from the quality, one of the eight MPEG-1 frame
+ rates, logged when it differs; table B.14 up to 13 bits, escapes beyond), uncompressed AVI with OpenDML
+ (`AviWriter`: 1 GB RIFF segments `AVI `/`AVIX`, `ix00` per segment, `indx` super index, `idx1` for the first,
+ `dmlh` total, the header written at Close so a cancelled export is a valid file), and H.264 MP4 through the
+ Media Foundation of Windows (`Mp4Writer` + `MediaFoundation` interop: hardware transforms enabled, quality
+ rate control + GOP = fps + no B-frames as encoding parameters with the author's bits-per-pixel bitrate as the
+ declared average and the fallback, odd sizes padded by repeating the edge; absent on Windows N without the
+ Media Feature Pack, the command then says so). `Video.Fps`/`Quality` (default 85 since 2026-10-14, the user's JPEG default; was the author's 70) drive every video; quality means JPEG
+ table scaling, the MPEG-1 quantiser and the H.264 quality. **A still**: "Export this frame…" first on each
+ picture's context menu (id `ContextExportFrame`) and File > Export > Field frame… / Intensity frame…
+ write the frame the preview shows as one PNG or JPEG (`ImageFileSink`, `ExportFormats.OpenStill`), named
+ `<project>_field_<step>`; it goes through the same job over a one-frame range, so it shows exactly what a
+ video export shows there, never the scratch frame (the user's rule), run-first included. **The busy
+ indicator** (`MainWindow.Busy.cs`, `IsBusy`/`IsBusyIndeterminate`/`BusyText`, ids `StatusExport` and
+ `StatusBusyBar`): the export's frames done as a determinate bar; indeterminate while an export waits for its
+ run (the timeline shows that run) and while a scratch frame computes for the preview after a scrub or an
+ edit ("Computing frame n"; on from the request until the result of the newest request arrives). Still open:
+ probe data as CSV, an integer upscale for small canvases (recommended 2026-10-14, undecided). **The sinks are
+ opened by the job on its own thread** (`ExportTarget` carries a factory and the output name): the Media
+ Foundation writer refused calls from another apartment (E_NOINTERFACE on the sink writer, found by the
+ bench 2026-10-14; the app had opened it on the UI thread). **Speed** (2026-10-14, the user: SIMD is on every
+ machine now, so it is used either way): the colour conversion, the DCT (F = C·f·Cᵀ as two passes of
+ multiply-adds) and the quantisation run on `Vector128` (this Xeon E5-2690 v2 has AVX but no AVX2, so .NET
+ does not accelerate `Vector256`, and a first 256-bit version ran in software emulation, slower than scalar:
+ 128-bit is the width every x64 and ARM64 machine accelerates); every JPEG macroblock row is a restart
+ interval (DRI + RSTn) and every MPEG-1 slice is independent, so the rows are transformed, quantised and
+ entropy-coded in parallel into their own `BitWriter`s and concatenated; the `ExportJob` renders on one
+ thread and encodes/writes on a second (the sink thread, which also opens and closes the sinks), with two
+ frames in flight per target. Per 1080p frame on this machine (`library_check -- bench-export [w h]`;
+ the numbers move by half when another process is busy, measure on a quiet machine): JPEG encode 32 → 20 ms
+ (conversion 6.5 → 2), MPEG-1 52 → 23, the job to a JPEG sequence 32 → 10 ms per frame, MPEG-1 38 → 30,
+ AVI 13 → 11, MP4 about 40 (Media Foundation's encoder on the sink thread). **JPEG through WIC** (2026-10-15,
+ the user's choice): the app installs `Rendering/WicJpeg` (WPF's `JpegBitmapEncoder`, the Windows Imaging
+ Component codec: SIMD on the CPU, single-threaded per picture, no GPU) as `ExportFormats.AlternativeJpeg`;
+ the sink falls back to the in-house `JpegEncoder` when the alternative throws (the frame is rewound and
+ rewritten, logged once per writer; harness-checked). The quality number goes through unchanged: at 50, 70,
+ 85 and 95 WIC and the in-house encoder give the same file sizes and the same 47.2 dB, so WPF's
+ `QualityLevel` is the IJG scale and needs no mapping. **The in-house encoder, second version** (2026-10-15,
+ after the user asked why the fallback lost to one WIC thread): the AAN factorisation (`Dct8x8.ForwardAan`,
+ the IJG float DCT) on SSE registers with in-register 4 × 4 transposes, its output scaling folded into
+ quantiser divisors kept in zig-zag order so the coefficients land there directly; the entropy coder writes a
+ Huffman code and its value bits as one field into a 64-bit accumulator flushed by whole bytes (`BitSink`);
+ `Parallel.For` pinned to the core count (left to the scheduler it oversubscribed and doubled the time).
+ Steady state per 1080p picture: 20.7 ms on one thread (WIC 15.3), 5.4 ms on ten (2 → 11.7, 4 → 7.0); the job to a
+ JPEG sequence 7.7 ms per frame in-house, 4.8 through WIC on five workers. **Bench numbers need the JIT warm**:
+ the first timed calls ran tier-0 code at twice the cost, so `Time` now warms 40 calls and waits for the
+ background recompilation; the earlier numbers in this file (MPEG-1 23 ms, MP4 40) were partly that effect,
+ steady state is MPEG-1 9 ms a picture and the MP4 job 16 ms a frame. **GPU front end, built and measured**
+ (`Export/GpuJpeg`, 2026-10-15, the user asked for numbers, not estimates): one OpenCL work-item per block
+ does the colour conversion, the AAN transform and the quantisation into zig-zag 16-bit values, the CPU rows
+ Huffman-code them (`JpegEncoder.WriteCoded`); the picture decodes to the same dB and size as the CPU's.
+ Per picture, in-house on ten threads / GPU blocks (upload + kernel and download + Huffman) / WIC on one
+ thread: 1080p 5.4 / 5.4 (2.0 + 2.0 + 1.2) / 14.4 ms; 2160p 17 / 19 (9.1 + 7.8 + 3.3) / 54 ms. The job to a
+ JPEG sequence per frame, in-house (one worker) / WIC (five workers) / GPU (one worker): 1080p 8.8 / 4.8 / 9.6;
+ 2160p 25 / 18 / 28. So the device does the arithmetic in no time and the PCIe transfers cost what the CPU
+ rows cost, as predicted: **deleted again** the same day (the user: nothing would ever choose it; the numbers
+ stay here so nobody builds it twice). An RTX 2080 has no JPEG block (NVJPG is A100/Orin; Intel iGPUs have
+ one; neither is here) and no card encodes MPEG-1, so the only hardware encoder available is the card's
+ H.264/HEVC, through Media Foundation. WIC on the worker pool stays the app's encoder, the in-house
+ encoder the fallback. Other 2160p figures: MPEG-1 30 ms a
+ picture, MP4 10, AVI 40 (a 25 MB write), the PNG job 43 ms a frame. **H.264 and the card's encoder**
+ (2026-10-15): the sink writer does use the hardware, `Mp4Writer.Transforms` names them (through
+ `IMFSinkWriterEx.GetTransformForStream` and `MFT_FRIENDLY_NAME_Attribute`, whose GUID is
+ `314ffbae-…`, read from the SDK header after a wrong guess) and `Mp4Writer.AvailableEncoders` lists the
+ registered ones: here "NVIDIA H.264 Encoder MFT". The frames now go in as NV12, converted by `YuvPlanes`
+ on every core, so the writer's single-threaded colour converter is out of the chain; the writer also gets
+ a Direct3D 11 device manager (`MediaFoundation.CreateDeviceManager`, `MF_SINK_WRITER_D3D_MANAGER`), kept
+ because other vendors' transforms expect one. Neither moved the throughput: the job writes about 16 to 19
+ ms a 1080p frame (55 to 60 fps) with or without them, with the writer's throttling off, in quality or
+ bitrate mode, at any declared frame rate, and with the encoder's fastest settings (quality-versus-speed 0,
+ low latency, real time); the quality mode is the better one (47 dB at a tenth of the bitrate mode's size on
+ wave content). The writer alone on real frames measured 30 to 45 ms a frame on a machine 44 % busy with
+ the user's video playback, so the absolute figures are depressed; the relative picture is stable. Where the
+ cap sits: the sink writer drives the asynchronous hardware transform one sample at a time. The ways past
+ it are driving the transform directly (`IMFTransform` with the async event protocol, the sink writer then
+ muxing H.264 samples) or NVENC's own API (vendor-specific, `nvEncodeAPI64.dll` from the driver); both are
+ projects, neither started. The static knobs `Mp4Writer.Throttle`, `PreferNv12`, `QualityMode`, `UseDirect3D`,
+ `Fastest` exist for the bench, which also runs the same frames through the ffmpeg on the PATH as a
+ reference (its 2018 NVENC code no longer opens on the current driver; libx264 ultrafast did 16 ms a frame
+ including the raw read). **Sequences encode on a worker pool** (`ImageSequenceSink` workers: half the
+ cores for WIC and PNG, one for the in-house JPEG, which is parallel inside; the frame copies are pooled, and
+ the PNG's zlib output goes out as 64 KB IDAT chunks instead of a whole-file buffer): the job to a JPEG
+ sequence 27 → 10 ms per frame, the PNG sink 46 → 11 ms per frame on the bench picture, but a real wave frame
+ compresses slower, about 33 ms per frame in the job (`CompressionLevel.Fastest` would be the lever, at some
+ size). `JpegEncoder.ParallelRows` and `LastPhases` exist for the bench. The harness project is
+ `net10.0-windows` with `UseWPF` for that bench (the library stays `net10.0`).
+- **Unsaved edits** (2026-10-14): `MainWindow.IsDirty`, set by the watcher on any model change, cleared on
+ open/new/save; the title gets `*` after the file (or "Untitled*", `TitleConverter`, re-read on a language
+ switch) and New, Open, Close, Exit and a drop ask Yes/No/Cancel (`ConfirmDiscard`, `SaveChangesFormat`).
- Preview document: `Panes/PreviewPane`. Two pictures (field,
intensity) side by side or stacked (`Orientation`, persisted as the `PreviewOrientation` user
setting), each centred in its cell with its label laid out by `Controls/PictureFrame` (label above
@@ -375,7 +506,17 @@ passing harnesses for comfort, never all of them after an edit.
probe yielding one profile per frame, the box attached to the probe following it and a detached one staying put, and a
scratch frame's traces matching the run's bit for bit (series up to the step, the frame's profile, a second
request on the kept engine with an integrated line probe starting its sums afresh, and the same on the GPU
- after the cancelled GPU run), and a rotated 3 × 1 array. Prints
+ after the cancelled GPU run), and a rotated 3 × 1 array; the
+ **export** (`ExportChecks.cs`, 2026-10-14, `-- export` runs just these in a few seconds): PNG decoded in-house
+ (inflate + unfilter, CRCs) and by the ffmpeg found on the PATH (skipped without one; this machine has one in
+ `C:\Windows` and under ImageMagick), JPEG at quality 90 above 30 dB, MPEG-1 (frame rate codes, quantiser
+ mapping, start codes, 7 pictures decoded above 28 dB), AVI with a tiny segment limit (3 segments walked:
+ frames, `idx1`, `ix00` per segment, super index, `dmlh`, sizes, decoded pixel for pixel; a one-frame file),
+ MP4 when Media Foundation is there (7 frames decoded), the sequence folder rule, and the `ExportJob` over a
+ run's store (two sinks, the decoration seen per frame, a PNG equal to the renderer's frame, a cancelled job
+ leaving a valid AVI, a frame beyond the store failing it, a sink that cannot open, an MP4 written on the
+ job's thread; the one-frame still sink; the alternative JPEG encoder with its fallback). `-- bench-export [w h]`
+ times every encoder and the whole job per format, WIC against the in-house JPEG with sizes and PSNR. Prints
`skip GPU: …` when no OpenCL device works. `dotnet run --project _tools/library_check -c Release
-- bench [w h]` prints the per-step cost table above for this machine.
@@ -431,10 +572,22 @@ The two legacy harnesses are console programs compiled with `csc` against the `W
four sources and two probes in the tree with their enabled/active state, 7500 frames on the timeline, the
embedded image's 16:9 canvas, Source 1's marker at (150, 140), and the status bar's import message
(the message text block carries the id `StatusMessage`).
+ `_tools/ui_check/ExportCheck.ps1` (2026-10-14, 30 checks, about 50 s): on `tiny.wdproj` File > Export > Field…
+ by keyboard with no run yet (a run is made, 100 PNGs land in `%TEMP%\wd_export\tiny_field`, the status
+ message names it, the run stays in the preview), an edit putting the asterisk in the title and staling the
+ run, Export both… from the picture's context menu (the Apps key on a focused handle; `PopupItemVisible` /
+ `PopupFocusedId` look through the process's top-level windows, since a popup is not a descendant of the main
+ window, and the menu opens with no entry highlighted) redoing the run and writing both sequences; then
+ the still from the context menu's first entry (`tiny_field_0.png`); then
+ `tiny_probes.wdproj`'s field with the graph boxes drawn (a frame kept as `%TEMP%\export_probes.png`), the
+ same as an MP4 (the app's Media Foundation path) and as a JPEG sequence (WIC on the worker pool). Two
+ **harness hooks** in the app, read from the environment: `WAVEDUDE_EXPORT_PATH` replaces the Save dialog
+ (`{name}` = the suggested name) and `WAVEDUDE_DISCARD_EDITS=1` skips the save question on closing
+ (`Start-App` sets it), because posted keys cannot drive a common dialog or a message box.
`FocusedId` is **one** UI Automation query for the element with keyboard focus (a template part's
id such as `PART_EditableTextBox` is mapped to its owner); asking 17 ids one by one cost half a
second per Tab and made `FocusOn` crawl. Timings after the 2026-10-14 clean-up: RunCheck 67 s
- (was 455), PreviewCheck 12 s (was 36), LanguageCheck 17 s (was 76).
+ (was 455), PreviewCheck 12 s (was 36), LanguageCheck 17 s (was 76), ExportCheck 25 s.
Run `powershell -ExecutionPolicy Bypass -File _tools/ui_check/<script>.ps1` (`-Trace` adds
foreground/focus per line); exit code = failures. **How UI harnesses must work here**: the user may
be using the machine, so no mouse, no `SendKeys`, no `SetForegroundWindow`. Post `WM_KEYDOWN`/
@@ -473,6 +626,8 @@ ScratchRunner (one long-running task, one kept engine: Reset/SetEmitters/SetProb
scene or the options change; computes "frame k of the project as it is now" from step 0, sampling the probes on the
way, newest request wins, skips when the predicted cost exceeds Budget) -> ScratchResult (a FrameSnapshot + a
ProbeTrace per probe) -> FramePresenter via SnapshotFrameSource, ProbeGraphOverlay via PreviewPane.ShownScratch
+ExportJob (Export/, its own STA thread: per frame of the range, per target CopyLayer -> FrameRenderer -> GlowingEdges.BlendAdditive
+ -> Decorate (the WPF ProbeGraphPainter) -> IFrameSink: ImageSequenceSink (PngEncoder | JpegEncoder), Mpeg1Writer, AviWriter, Mp4Writer)
FrameStore (temporary file in %LOCALAPPDATA%\WaveDude\cache, DeleteOnClose, pre-sized; Half planes, padding stripped;
| positional RandomAccess reads/writes through the OS cache, no memory mapping)
'- read by FramePresenter (WPF): CopyLayer -> FrameRenderer (LUT, Parallel.For) -> WriteableBitmap
@@ -485,10 +640,12 @@ FrameStore (temporary file in %LOCALAPPDATA%\WaveDude\cache, DeleteOnClose, pre-
observable and XML-serialisable, `ColorLut`, `ColorSchemeStore` reading the author's JSON and
reading/writing XML, built-in schemes embedded, `FrameRenderer`),
`WaveDude.Runs` (`RunSpec`, `SimulationRun`, `RunState`, `FrameStore`, `FrameLayer(s)`,
- `FrameCache`, `ScenePixels`). All copied from `Wave_Dude_2D` and adapted; the legacy app keeps
- its own copies and does not reference the library. Not ported: video sinks (`MfVideoWriter`,
- `AviMjpegWriter`, `AviFrameSink`), GDI+ painters (`ProbeGraphPainter`, `ProbeOverlay`), the glow
- overlay (now ported as `GlowingEdges`); export will render from the store instead.
+ `FrameCache`, `ScenePixels`), `WaveDude.Export` (2026-10-14: `IFrameSink`, `ExportJob`, `ExportFormat(s)`,
+ the encoders and writers, `BitWriter`, `YuvPlanes` + `Dct8x8` shared by JPEG and MPEG-1, `Crc32`). All copied
+ from `Wave_Dude_2D` and adapted; the legacy app keeps its own copies and does not reference the library. Not
+ ported: the legacy video sinks (`MfVideoWriter` was rewritten as `Mp4Writer`, `AviMjpegWriter` replaced by
+ the OpenDML `AviWriter`), GDI+ painters (`ProbeGraphPainter` exists anew in WPF, `ProbeOverlay`), the glow
+ overlay (now ported as `GlowingEdges`).
- **The engine choice is not in the project** (2026-10-09, the user's call: the old app's flag was an
artefact): `Simulation > Use the GPU (OpenCL)` is the persisted user setting `UseGpu` (default on),
passed to `RunSpec.Create(project, image, preferGpu)`; the CPU is the fallback with a note when no
@@ -677,8 +834,8 @@ functional spec for the WPF UI.
replace with `Program.Main` (`EnableVisualStyles`, `SetCompatibleTextRenderingDefault`) when convenient.
- Private `ref` parameters that are really `out` remain outside the engines (`TryPictureToCanvas`,
`TryParseInt`, `DampingProblem`, `PromptForCValue`, `ComputeRanges`, `RgbToHsv`, …).
-- WPF: no progress bar for a run (status text only); the Simulation menu has no About/Help; the probe
- signal lane is not drawn yet (the graph boxes are); export not rendered from the store yet; the preview skips frames at
+- WPF: no progress bar for a run (status text only; the export has one); the Simulation menu has no About/Help; the probe
+ signal lane is not drawn yet (the graph boxes are); the preview skips frames at
1080p (see the numbers in the library architecture section).
- WPF preview, frames vs. steps: the transport bar, scrubber and playback count **frames**
(0..`LastFrame`, one per `VisualizeEvery` steps), while sources, probes, the export range and the
@@ -732,7 +889,8 @@ Thirteen points on a sneak peek of the WPF app; status as of 2026-10-12:
(see "Probe graphs" above); probe measurement edits now re-run automatically.
- Still open: "re-run automatically does not always work" (by design: display edits and a probe's graph
settings do not re-run, and the run waits 1.5 s of quiet).
-- Roadmap already: (7) probe graphs, (10) export, (12) project format (the user answered: images
+- Done 2026-10-14: (10) export, from the store at any time (see "Export" in the WPF shell list).
+- Roadmap already: (7) probe graphs (the lane), (12) project format (the user answered: images
embedded or relative, output next to the file, the JSON format imported).
- The author also suggests dropping the 9-point Laplacian (confusing; only useful to show dispersion).
diff --git a/WaveDude.WPF/App.xaml.cs b/WaveDude.WPF/App.xaml.cs
index a6ae200..1e6266d 100644
--- a/WaveDude.WPF/App.xaml.cs
+++ b/WaveDude.WPF/App.xaml.cs
@@ -85,14 +85,12 @@ public partial class App : Application
config.AddTarget(statusBar);
config.AddRule(LogLevel.Info, LogLevel.Fatal, statusBar);
- // in-memory buffer behind the Messages pane; everything in Debug, Info and up in Release
+ // in-memory buffer behind the Messages pane: everything, in every build; the pane's level toggles hide
+ // Trace and Debug by default in Release, so they can be switched on when something needs a look
+ // (2026-10-14, the user: a Release build had nothing to show there, the messages never got in)
var messages = new MessagesTarget { Name = "messages" };
config.AddTarget(messages);
-#if DEBUG
config.AddRule(LogLevel.Trace, LogLevel.Fatal, messages);
-#else
- config.AddRule(LogLevel.Info, LogLevel.Fatal, messages);
-#endif
#if DEBUG
config.AddRule(LogLevel.Trace, LogLevel.Fatal, fileTarget);
config.AddRule(LogLevel.Trace, LogLevel.Fatal, new DebuggerTarget("debugger") { Layout = DebugLayout });
@@ -203,6 +201,8 @@ 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/WaveDude.WPF/Commands/ExportCommands.cs b/WaveDude.WPF/Commands/ExportCommands.cs
new file mode 100644
index 0000000..9710165
--- /dev/null
+++ b/WaveDude.WPF/Commands/ExportCommands.cs
@@ -0,0 +1,28 @@
+using System.Windows.Input;
+
+namespace WaveDude.WPF.Commands;
+
+/// <summary>
+/// The export commands, bound on the main window (handlers in <c>MainWindow.Export.cs</c>) and offered in
+/// File > Export and on the pictures' context menus. Each opens the Save dialog for the format and name,
+/// then renders the export range of the current run (started first when there is none or it is stale)
+/// with the display settings as they are; the frame commands write the frame the preview shows, from the
+/// same run, as one PNG or JPEG.
+/// </summary>
+public static class ExportCommands
+{
+ /// <summary>Exports the field pictures.</summary>
+ public static readonly RoutedUICommand Field = new("Export field", nameof(Field), typeof(ExportCommands));
+
+ /// <summary>Exports the intensity pictures.</summary>
+ public static readonly RoutedUICommand Intensity = new("Export intensity", nameof(Intensity), typeof(ExportCommands));
+
+ /// <summary>Exports both, as two outputs named <c>_field</c> and <c>_intensity</c> after the chosen name.</summary>
+ public static readonly RoutedUICommand Both = new("Export both", nameof(Both), typeof(ExportCommands));
+
+ /// <summary>Exports the field frame the preview shows as one image.</summary>
+ public static readonly RoutedUICommand FieldFrame = new("Export field frame", nameof(FieldFrame), typeof(ExportCommands));
+
+ /// <summary>Exports the intensity frame the preview shows as one image.</summary>
+ public static readonly RoutedUICommand IntensityFrame = new("Export intensity frame", nameof(IntensityFrame), typeof(ExportCommands));
+}
diff --git a/WaveDude.WPF/Controls/ProbeGraphDrawing.cs b/WaveDude.WPF/Controls/ProbeGraphDrawing.cs
new file mode 100644
index 0000000..49e554c
--- /dev/null
+++ b/WaveDude.WPF/Controls/ProbeGraphDrawing.cs
@@ -0,0 +1,138 @@
+using System.Globalization;
+using System.Windows;
+using System.Windows.Media;
+using WaveDude.Probes;
+
+namespace WaveDude.WPF.Controls;
+
+/// <summary>
+/// Draws a probe graph box from its <see cref="ProbeGraphLayout"/> with WPF drawing primitives: the
+/// translucent dark box, the axes with their labels, the curve and the title strip. Shared by the preview's
+/// <see cref="ProbeGraphOverlay"/> (screen pixels, the box scaled with the picture) and the export's painter
+/// (canvas pixels, rendered into the frame). Colours are the author's, fixed, not themed: the box sits on
+/// the picture. All brushes are frozen, so any thread may draw with them into its own visuals.
+/// </summary>
+public static class ProbeGraphDrawing
+{
+ /// <summary>The fixed label size in pixels (text does not scale with the box).</summary>
+ public const double FontSize = 11.0;
+
+ /// <summary>The graph font.</summary>
+ public static readonly Typeface Typeface = new("Segoe UI");
+
+ private static readonly Brush BackgroundBrush = Freeze(new SolidColorBrush(Color.FromArgb(235, 14, 16, 22)));
+ private static readonly Pen BorderPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(170, 200, 200, 210))), 1.0));
+ private static readonly Pen GridPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(46, 255, 255, 255))), 1.0));
+ private static readonly Pen ZeroPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(120, 255, 255, 255))), 1.0));
+ private static readonly Pen FramePen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(130, 200, 200, 210))), 1.0));
+ private static readonly Brush LabelBrush = Freeze(new SolidColorBrush(Color.FromArgb(225, 225, 225, 230)));
+ private static readonly Brush TitleBrush = Freeze(new SolidColorBrush(Color.FromArgb(240, 240, 240, 245)));
+ private static readonly Brush CurveBrush = Freeze(new SolidColorBrush(Color.FromArgb(255, 255, 208, 64)));
+
+ /// <summary>The text metrics of the graph font at a DPI: the line height and a measure of label widths, for <see cref="ProbeGraph.Layout"/>.</summary>
+ public static ProbeGraphStyle MakeStyle(double pixelsPerDip)
+ {
+ float lineHeight = (float)Text("0", FontSize, LabelBrush, pixelsPerDip).Height;
+ return new ProbeGraphStyle((float)FontSize, lineHeight, text => (float)Text(text, FontSize, LabelBrush, pixelsPerDip).Width);
+ }
+
+ /// <summary>Draws one box from its layout, with the origin at the box's top-left corner.</summary>
+ /// <param name="dc">The drawing context.</param>
+ /// <param name="layout">The box's geometry and text.</param>
+ /// <param name="border">The border pen for a selected box, or null for the usual one.</param>
+ /// <param name="pixelsPerDip">The DPI scale for the text.</param>
+ public static void DrawBox(DrawingContext dc, ProbeGraphLayout layout, Pen? border, double pixelsPerDip)
+ {
+ double w = layout.Width;
+ double h = layout.Height;
+ dc.DrawRectangle(BackgroundBrush, null, new Rect(0, 0, w, h));
+ dc.DrawRectangle(null, border ?? BorderPen, new Rect(0.5, 0.5, w - 1, h - 1));
+ double fontPx = layout.FontSize;
+ if (layout.HasPlot)
+ {
+ double plotLeft = layout.PlotX;
+ double plotTop = layout.PlotY;
+ double plotRight = layout.PlotX + layout.PlotWidth;
+ double plotBottom = layout.PlotY + layout.PlotHeight;
+ // value axis: grid lines (the zero line brighter) with right-aligned labels in the left margin
+ foreach (GraphTick tick in layout.YTicks)
+ {
+ double y = Math.Round(tick.Position) + 0.5;
+ dc.DrawLine(tick.IsZero ? ZeroPen : GridPen, new Point(plotLeft, y), new Point(plotRight, y));
+ if (tick.Label.Length == 0)
+ {
+ continue;
+ }
+ // right-aligned by position: a MaxTextWidth equal to the measured width made WPF wrap the label onto a
+ // second line, which the one-line limit dropped (the labels vanished, 2026-10-14)
+ FormattedText label = Text(tick.Label, fontPx, LabelBrush, pixelsPerDip);
+ double lx = Math.Max(layout.LabelLeft, plotLeft - ProbeGraph.LabelGap - label.Width);
+ dc.DrawText(label, new Point(lx, Math.Clamp(tick.Position - label.Height / 2, plotTop - label.Height / 2, plotBottom - label.Height / 2)));
+ }
+ // step axis (point probe) or position on the line (line probe): labels centred below the plot, kept inside the box
+ foreach (GraphTick tick in layout.XTicks)
+ {
+ double x = Math.Round(tick.Position) + 0.5;
+ dc.DrawLine(GridPen, new Point(x, plotTop), new Point(x, plotBottom));
+ if (tick.Label.Length == 0)
+ {
+ continue;
+ }
+ FormattedText label = Text(tick.Label, fontPx, LabelBrush, pixelsPerDip);
+ double lx = Math.Clamp(tick.Position - label.Width / 2, ProbeGraph.EdgePad, Math.Max(ProbeGraph.EdgePad, w - label.Width - ProbeGraph.EdgePad));
+ dc.DrawText(label, new Point(lx, plotBottom + 2));
+ }
+ dc.DrawRectangle(null, FramePen, new Rect(plotLeft + 0.5, plotTop + 0.5, layout.PlotWidth, layout.PlotHeight));
+ DrawCurve(dc, layout);
+ }
+ // the title strip: the readout right-aligned in its own colour, the title in the remaining width
+ double readoutWidth = 0;
+ if (layout.Readout.Length > 0)
+ {
+ FormattedText readout = Text(layout.Readout, fontPx, CurveBrush, pixelsPerDip);
+ readoutWidth = readout.Width;
+ dc.DrawText(readout, new Point(w - readoutWidth - 8, layout.TitleTop));
+ }
+ FormattedText title = Text(layout.Title, fontPx, TitleBrush, pixelsPerDip);
+ title.MaxTextWidth = Math.Max(10, w - readoutWidth - 16);
+ title.Trimming = TextTrimming.CharacterEllipsis;
+ dc.DrawText(title, new Point(ProbeGraph.EdgePad + 3, layout.TitleTop));
+ }
+
+ /// <summary>Strokes the curve clipped to the plot area; a single point is a small dot.</summary>
+ private static void DrawCurve(DrawingContext dc, ProbeGraphLayout layout)
+ {
+ if (layout.Curve.Length == 0)
+ {
+ return;
+ }
+ if (layout.Curve.Length == 1)
+ {
+ dc.DrawEllipse(CurveBrush, null, new Point(layout.Curve[0].X, layout.Curve[0].Y), 2, 2);
+ return;
+ }
+ var geometry = new StreamGeometry();
+ using (StreamGeometryContext context = geometry.Open())
+ {
+ context.BeginFigure(new Point(layout.Curve[0].X, layout.Curve[0].Y), false, false);
+ for (int i = 1; i < layout.Curve.Length; i++)
+ {
+ context.LineTo(new Point(layout.Curve[i].X, layout.Curve[i].Y), true, false);
+ }
+ }
+ geometry.Freeze();
+ dc.PushClip(new RectangleGeometry(new Rect(layout.PlotX, layout.PlotY, layout.PlotWidth, layout.PlotHeight)));
+ dc.DrawGeometry(null, new Pen(CurveBrush, layout.LineWidth) { LineJoin = PenLineJoin.Round }, geometry);
+ dc.Pop();
+ }
+
+ /// <summary>One line of text in the graph font.</summary>
+ public static FormattedText Text(string text, double size, Brush brush, double pixelsPerDip) =>
+ new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, Typeface, size, brush, pixelsPerDip) { MaxLineCount = 1 };
+
+ private static T Freeze<T>(T freezable) where T : Freezable
+ {
+ freezable.Freeze();
+ return freezable;
+ }
+}
diff --git a/WaveDude.WPF/Controls/ProbeGraphOverlay.cs b/WaveDude.WPF/Controls/ProbeGraphOverlay.cs
index da25bc1..32422e3 100644
--- a/WaveDude.WPF/Controls/ProbeGraphOverlay.cs
+++ b/WaveDude.WPF/Controls/ProbeGraphOverlay.cs
@@ -87,20 +87,6 @@ public sealed class ProbeGraphOverlay : Panel
/// <summary>Screen distance an attached box must be dragged from the probe before it comes off: wider than <see cref="SnapRadius"/>, so a drag near the edge does not attach and detach in turn (hysteresis, 2026-10-14).</summary>
public const double SnapRelease = 28.0;
- // the author's colours: the box sits on the picture, not on the window, so they do not follow the theme
- private static readonly Brush BackgroundBrush = Freeze(new SolidColorBrush(Color.FromArgb(235, 14, 16, 22)));
- private static readonly Pen BorderPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(170, 200, 200, 210))), 1.0));
- private static readonly Pen GridPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(46, 255, 255, 255))), 1.0));
- private static readonly Pen ZeroPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(120, 255, 255, 255))), 1.0));
- private static readonly Pen FramePen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(130, 200, 200, 210))), 1.0));
- private static readonly Brush LabelBrush = Freeze(new SolidColorBrush(Color.FromArgb(225, 225, 225, 230)));
- private static readonly Brush TitleBrush = Freeze(new SolidColorBrush(Color.FromArgb(240, 240, 240, 245)));
- private static readonly Brush CurveBrush = Freeze(new SolidColorBrush(Color.FromArgb(255, 255, 208, 64)));
- private static readonly Typeface GraphTypeface = new("Segoe UI");
-
- /// <summary>Font height of the labels and the title in screen pixels: the handle labels' size, whatever the box size.</summary>
- private const double GraphFontSize = 11.0;
-
/// <summary>The text metrics handed to the layout, built per DPI.</summary>
private ProbeGraphStyle? _style;
private double _stylePixelsPerDip;
@@ -399,118 +385,22 @@ public sealed class ProbeGraphOverlay : Panel
continue;
}
dc.PushTransform(new TranslateTransform(box.X, box.Y));
- DrawBox(dc, layout, ReferenceEquals(probe, selected), pixelsPerDip);
+ ProbeGraphDrawing.DrawBox(dc, layout, ReferenceEquals(probe, selected) ? new Pen(AccentBrush, 1.0) : null, pixelsPerDip);
dc.Pop();
}
}
- /// <summary>The text metrics of the fixed graph font at this DPI: the line height and the measured label widths.</summary>
+ /// <summary>The text metrics of the fixed graph font at this DPI (<see cref="ProbeGraphDrawing.MakeStyle"/>), kept per DPI.</summary>
private ProbeGraphStyle StyleFor(double pixelsPerDip)
{
if (_style == null || _stylePixelsPerDip != pixelsPerDip)
{
_stylePixelsPerDip = pixelsPerDip;
- float lineHeight = (float)Text("0", GraphFontSize, LabelBrush, pixelsPerDip).Height;
- _style = new ProbeGraphStyle((float)GraphFontSize, lineHeight, text => (float)Text(text, GraphFontSize, LabelBrush, pixelsPerDip).Width);
+ _style = ProbeGraphDrawing.MakeStyle(pixelsPerDip);
}
return _style;
}
- /// <summary>Draws one box from its layout, with the origin at the box's top-left corner.</summary>
- private void DrawBox(DrawingContext dc, ProbeGraphLayout layout, bool isSelected, double pixelsPerDip)
- {
- double w = layout.Width;
- double h = layout.Height;
- dc.DrawRectangle(BackgroundBrush, null, new Rect(0, 0, w, h));
- dc.DrawRectangle(null, isSelected ? new Pen(AccentBrush, 1.0) : BorderPen, new Rect(0.5, 0.5, w - 1, h - 1));
- double fontPx = layout.FontSize;
- if (layout.HasPlot)
- {
- double plotLeft = layout.PlotX;
- double plotTop = layout.PlotY;
- double plotRight = layout.PlotX + layout.PlotWidth;
- double plotBottom = layout.PlotY + layout.PlotHeight;
- // value axis: grid lines (the zero line brighter) with right-aligned labels in the left margin
- foreach (GraphTick tick in layout.YTicks)
- {
- double y = Math.Round(tick.Position) + 0.5;
- dc.DrawLine(tick.IsZero ? ZeroPen : GridPen, new Point(plotLeft, y), new Point(plotRight, y));
- if (tick.Label.Length == 0)
- {
- continue;
- }
- // right-aligned by position: a MaxTextWidth equal to the measured width made WPF wrap the label onto a
- // second line, which the one-line limit dropped (the labels vanished, 2026-10-14)
- FormattedText label = Text(tick.Label, fontPx, LabelBrush, pixelsPerDip);
- double lx = Math.Max(layout.LabelLeft, plotLeft - ProbeGraph.LabelGap - label.Width);
- dc.DrawText(label, new Point(lx, Math.Clamp(tick.Position - label.Height / 2, plotTop - label.Height / 2, plotBottom - label.Height / 2)));
- }
- // step axis (point probe) or position on the line (line probe): labels centred below the plot, kept inside the box
- foreach (GraphTick tick in layout.XTicks)
- {
- double x = Math.Round(tick.Position) + 0.5;
- dc.DrawLine(GridPen, new Point(x, plotTop), new Point(x, plotBottom));
- if (tick.Label.Length == 0)
- {
- continue;
- }
- FormattedText label = Text(tick.Label, fontPx, LabelBrush, pixelsPerDip);
- double lx = Math.Clamp(tick.Position - label.Width / 2, ProbeGraph.EdgePad, Math.Max(ProbeGraph.EdgePad, w - label.Width - ProbeGraph.EdgePad));
- dc.DrawText(label, new Point(lx, plotBottom + 2));
- }
- dc.DrawRectangle(null, FramePen, new Rect(plotLeft + 0.5, plotTop + 0.5, layout.PlotWidth, layout.PlotHeight));
- DrawCurve(dc, layout);
- }
- // the title strip: the readout right-aligned in its own colour, the title in the remaining width
- double readoutWidth = 0;
- if (layout.Readout.Length > 0)
- {
- FormattedText readout = Text(layout.Readout, fontPx, CurveBrush, pixelsPerDip);
- readoutWidth = readout.Width;
- dc.DrawText(readout, new Point(w - readoutWidth - 8, layout.TitleTop));
- }
- FormattedText title = Text(layout.Title, fontPx, TitleBrush, pixelsPerDip);
- title.MaxTextWidth = Math.Max(10, w - readoutWidth - 16);
- title.Trimming = TextTrimming.CharacterEllipsis;
- dc.DrawText(title, new Point(ProbeGraph.EdgePad + 3, layout.TitleTop));
- }
-
- /// <summary>Strokes the curve clipped to the plot area; a single point is a small dot.</summary>
- private static void DrawCurve(DrawingContext dc, ProbeGraphLayout layout)
- {
- if (layout.Curve.Length == 0)
- {
- return;
- }
- if (layout.Curve.Length == 1)
- {
- dc.DrawEllipse(CurveBrush, null, new Point(layout.Curve[0].X, layout.Curve[0].Y), 2, 2);
- return;
- }
- var geometry = new StreamGeometry();
- using (StreamGeometryContext context = geometry.Open())
- {
- context.BeginFigure(new Point(layout.Curve[0].X, layout.Curve[0].Y), false, false);
- for (int i = 1; i < layout.Curve.Length; i++)
- {
- context.LineTo(new Point(layout.Curve[i].X, layout.Curve[i].Y), true, false);
- }
- }
- geometry.Freeze();
- dc.PushClip(new RectangleGeometry(new Rect(layout.PlotX, layout.PlotY, layout.PlotWidth, layout.PlotHeight)));
- dc.DrawGeometry(null, new Pen(CurveBrush, layout.LineWidth) { LineJoin = PenLineJoin.Round }, geometry);
- dc.Pop();
- }
-
- private static FormattedText Text(string text, double size, Brush brush, double pixelsPerDip) =>
- new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, GraphTypeface, size, brush, pixelsPerDip) { MaxLineCount = 1 };
-
- private static T Freeze<T>(T freezable) where T : Freezable
- {
- freezable.Freeze();
- return freezable;
- }
-
// ---------------------------------------------------------------- dragging and keys
private void OnDragStarted(object sender, DragStartedEventArgs e)
diff --git a/WaveDude.WPF/Converters/TitleConverter.cs b/WaveDude.WPF/Converters/TitleConverter.cs
index 0153a1e..483baea 100644
--- a/WaveDude.WPF/Converters/TitleConverter.cs
+++ b/WaveDude.WPF/Converters/TitleConverter.cs
@@ -1,17 +1,33 @@
using System.Globalization;
+using System.Windows;
using System.Windows.Data;
namespace WaveDude.WPF.Converters;
/// <summary>
-/// Joins the non-empty parts of a window title with " - ", for example the application name
-/// and the open file, so that a missing file leaves just the name.
+/// Builds the window title from the application name, the open file and the dirty flag: the non-empty
+/// parts joined with " - ", an asterisk after the file for unsaved edits, and "Untitled*" when an unsaved
+/// project has no file yet (the word is looked up in the current language's strings on every conversion;
+/// the window refreshes the binding on a language switch).
/// </summary>
public sealed class TitleConverter : IMultiValueConverter
{
/// <inheritdoc/>
- public object Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture) =>
- string.Join(" - ", values.Select(v => v?.ToString()).Where(s => !string.IsNullOrEmpty(s)));
+ public object Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture)
+ {
+ string title = values.Length > 0 ? values[0]?.ToString() ?? "" : "";
+ string file = values.Length > 1 ? values[1]?.ToString() ?? "" : "";
+ bool dirty = values.Length > 2 && values[2] is true;
+ if (dirty)
+ {
+ if (file.Length == 0)
+ {
+ file = Application.Current?.TryFindResource("Untitled") as string ?? "Untitled";
+ }
+ file += "*";
+ }
+ return file.Length == 0 ? title : title + " - " + file;
+ }
/// <inheritdoc/>
public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) =>
diff --git a/WaveDude.WPF/MainWindow.Busy.cs b/WaveDude.WPF/MainWindow.Busy.cs
new file mode 100644
index 0000000..ac5704a
--- /dev/null
+++ b/WaveDude.WPF/MainWindow.Busy.cs
@@ -0,0 +1,99 @@
+using System.Windows;
+using WaveDude.Export;
+
+namespace WaveDude.WPF;
+
+/// <summary>
+/// The status bar's busy indicator (2026-10-14, the user's rule: whenever the application computes something
+/// the user waits for, a bar shows it): an export writing frames (determinate, frames done of the range), an
+/// export waiting for its run (indeterminate, the timeline shows that run's progress), and a scratch frame
+/// being computed for the preview after a scrub or an edit (indeterminate, "Computing frame n"). One text
+/// and one bar, fed by <see cref="UpdateBusy"/> from wherever the state changes.
+/// </summary>
+public partial class MainWindow
+{
+ /// <summary>Identifies the <see cref="IsBusy"/> property.</summary>
+ public static readonly DependencyProperty IsBusyProperty = DependencyProperty.Register(
+ nameof(IsBusy), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
+
+ /// <summary>Identifies the <see cref="IsBusyIndeterminate"/> property.</summary>
+ public static readonly DependencyProperty IsBusyIndeterminateProperty = DependencyProperty.Register(
+ nameof(IsBusyIndeterminate), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
+
+ /// <summary>Identifies the <see cref="BusyText"/> property.</summary>
+ public static readonly DependencyProperty BusyTextProperty = DependencyProperty.Register(
+ nameof(BusyText), typeof(string), typeof(MainWindow), new PropertyMetadata(""));
+
+ /// <summary>The scratch frame being computed for the preview, or -1.</summary>
+ private int _scratchBusyFrame = -1;
+
+ /// <summary>Whether the bar is shown.</summary>
+ public bool IsBusy
+ {
+ get => (bool)GetValue(IsBusyProperty);
+ private set => SetValue(IsBusyProperty, value);
+ }
+
+ /// <summary>Whether the bar has no measure of progress (a run being waited for, a scratch frame).</summary>
+ public bool IsBusyIndeterminate
+ {
+ get => (bool)GetValue(IsBusyIndeterminateProperty);
+ private set => SetValue(IsBusyIndeterminateProperty, value);
+ }
+
+ /// <summary>What the application is busy with, in the current language; empty when idle.</summary>
+ public string BusyText
+ {
+ get => (string)GetValue(BusyTextProperty);
+ private set => SetValue(BusyTextProperty, value);
+ }
+
+ /// <summary>Recomputes the indicator from the export and the scratch state. UI thread.</summary>
+ private void UpdateBusy()
+ {
+ if (Export is { IsActive: true } job)
+ {
+ BusyText = string.Format((string)FindResource("ExportStatusFormat"), job.FramesDone, job.FrameCount);
+ IsBusyIndeterminate = false;
+ IsBusy = true;
+ }
+ else if (IsExportWaiting)
+ {
+ BusyText = (string)FindResource("ExportStatusWaiting");
+ IsBusyIndeterminate = true;
+ IsBusy = true;
+ }
+ else if (_scratchBusyFrame >= 0)
+ {
+ BusyText = string.Format((string)FindResource("StatusComputingFormat"), _scratchBusyFrame);
+ IsBusyIndeterminate = true;
+ IsBusy = true;
+ }
+ else
+ {
+ BusyText = "";
+ IsBusyIndeterminate = false;
+ IsBusy = false;
+ }
+ UpdateTaskbar();
+ }
+
+ /// <summary>A scratch frame was requested (or the request completed: -1).</summary>
+ private void SetScratchBusy(int frame)
+ {
+ _scratchBusyFrame = frame;
+ UpdateBusy();
+ }
+
+ /// <summary>Follows an export job's progress and state into the indicator.</summary>
+ private void WatchExport(ExportJob job)
+ {
+ job.PropertyChanged += (_, args) =>
+ {
+ if (args.PropertyName is nameof(ExportJob.FramesDone) or nameof(ExportJob.State) && ReferenceEquals(job, Export))
+ {
+ UpdateBusy();
+ }
+ };
+ }
+}
diff --git a/WaveDude.WPF/MainWindow.Export.cs b/WaveDude.WPF/MainWindow.Export.cs
new file mode 100644
index 0000000..2c028ae
--- /dev/null
+++ b/WaveDude.WPF/MainWindow.Export.cs
@@ -0,0 +1,368 @@
+using System.IO;
+using System.Windows;
+using System.Windows.Input;
+using Microsoft.Win32;
+using WaveDude.Export;
+using WaveDude.Model;
+using WaveDude.Rendering;
+using WaveDude.Runs;
+using WaveDude.WPF.Properties;
+using WaveDude.WPF.Rendering;
+
+namespace WaveDude.WPF;
+
+/// <summary>
+/// Handlers of <see cref="Commands.ExportCommands"/> (2026-10-14): the Save dialog picks the format by its
+/// extension (PNG or JPEG sequence, MPEG-1, AVI, MP4) and the name, pre-set to the project's name with
+/// <c>_field</c> / <c>_intensity</c> in the project file's folder; "both" writes two outputs from one name;
+/// a frame command writes the frame the preview shows as one PNG or JPEG (<c>_field_&lt;step&gt;</c>).
+/// Every export renders from the run's store with the display settings as they are, the outline when opted
+/// in and the probe graph boxes when <see cref="Display.ProbeGraphsInExport"/> is on; a still shows exactly
+/// what a video export would show at that frame (the user's rule), never the scratch frame. There is always a
+/// run to export: when there is none, it is stale, or it lacks the intensity plane, a run is started first
+/// (like Play does) and the export waits for it (<see cref="IsExportWaiting"/>). The <see cref="ExportJob"/>
+/// works on its own thread and reports to the status bar's busy indicator; Esc cancels it. Runs are not
+/// started or replaced while an export reads the store.
+/// </summary>
+public partial class MainWindow
+{
+ /// <summary>Identifies the <see cref="Export"/> property.</summary>
+ public static readonly DependencyProperty ExportProperty = DependencyProperty.Register(
+ nameof(Export), typeof(ExportJob), typeof(MainWindow),
+ new PropertyMetadata(null, (d, _) => ((MainWindow)d).OnExportChanged()));
+
+ /// <summary>Identifies the <see cref="IsExportWaiting"/> property.</summary>
+ public static readonly DependencyProperty IsExportWaitingProperty = DependencyProperty.Register(
+ nameof(IsExportWaiting), typeof(bool), typeof(MainWindow),
+ new PropertyMetadata(false, (d, _) => ((MainWindow)d).OnExportChanged()));
+
+ /// <summary>The current export (running or finished), or null.</summary>
+ public ExportJob? Export
+ {
+ get => (ExportJob?)GetValue(ExportProperty);
+ set => SetValue(ExportProperty, value);
+ }
+
+ /// <summary>Whether an export is waiting for its run to complete before it starts writing.</summary>
+ public bool IsExportWaiting
+ {
+ get => (bool)GetValue(IsExportWaitingProperty);
+ set => SetValue(IsExportWaitingProperty, value);
+ }
+
+ /// <summary>Whether an export is running or waiting for its run.</summary>
+ private bool IsExporting => Export?.IsActive == true || IsExportWaiting;
+
+ private void OnExportChanged()
+ {
+ CommandManager.InvalidateRequerySuggested();
+ UpdateBusy();
+ }
+
+ private void CanExport(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = !IsExporting && Project.Simulation.Steps > 0;
+
+ private void OnExportField(object sender, ExecutedRoutedEventArgs e) => BeginExport(field: true, intensity: false);
+
+ private void OnExportIntensity(object sender, ExecutedRoutedEventArgs e) => BeginExport(field: false, intensity: true);
+
+ private void OnExportBoth(object sender, ExecutedRoutedEventArgs e) => BeginExport(field: true, intensity: true);
+
+ private void OnExportFieldFrame(object sender, ExecutedRoutedEventArgs e) => BeginExport(field: true, intensity: false, still: true);
+
+ private void OnExportIntensityFrame(object sender, ExecutedRoutedEventArgs e) => BeginExport(field: false, intensity: true, still: true);
+
+ /// <summary>The Save dialog, the run, the targets, the job.</summary>
+ /// <param name="field">Export the field.</param>
+ /// <param name="intensity">Export the intensity.</param>
+ /// <param name="still">One frame, the one the preview shows, as a single image file.</param>
+ private async void BeginExport(bool field, bool intensity, bool still = false)
+ {
+ if (IsExporting)
+ {
+ return;
+ }
+ int stillFrame = Math.Max(0, PreviewPosition);
+ string suffix = field && intensity ? "" : field ? "_field" : "_intensity";
+ if (still)
+ {
+ suffix += "_" + (stillFrame * Math.Max(1, Project.Simulation.VisualizeEvery)).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ }
+ string chosen;
+ int filterIndex = still ? Math.Clamp(Settings.Default.ExportFilterIndex + 1, 1, 2) : Math.Clamp(Settings.Default.ExportFilterIndex + 1, 1, ExportFormats.All.Length);
+ string? scripted = Environment.GetEnvironmentVariable("WAVEDUDE_EXPORT_PATH");
+ if (!string.IsNullOrEmpty(scripted))
+ {
+ // a UI harness cannot drive the common dialog by posted keys: it hands the path in instead, "{name}" standing for the suggested name
+ chosen = scripted.Replace("{name}", ProjectName() + suffix, StringComparison.Ordinal);
+ Logger.Debug("Export path taken from WAVEDUDE_EXPORT_PATH: {Path}", chosen);
+ }
+ else
+ {
+ var dialog = new SaveFileDialog
+ {
+ Title = (string)FindResource(still ? "ExportDialogTitleFrame" : field && intensity ? "ExportDialogTitleBoth" : field ? "ExportDialogTitleField" : "ExportDialogTitleIntensity"),
+ Filter = (string)FindResource(still ? "ExportDialogFilterStill" : "ExportDialogFilter"),
+ FilterIndex = filterIndex,
+ AddExtension = true,
+ DefaultExt = ExportFormats.Extension(ExportFormat.Png),
+ FileName = ProjectName() + suffix,
+ InitialDirectory = ProjectFolder ?? (Directory.Exists(Settings.Default.LastExportFolder) ? Settings.Default.LastExportFolder : ""),
+ };
+ if (dialog.ShowDialog(this) != true)
+ {
+ Logger.Debug("Export cancelled in the Save dialog");
+ return;
+ }
+ chosen = dialog.FileName;
+ filterIndex = dialog.FilterIndex;
+ if (!still)
+ {
+ Settings.Default.ExportFilterIndex = filterIndex - 1;
+ }
+ Settings.Default.LastExportFolder = Path.GetDirectoryName(chosen) ?? "";
+ }
+ ExportFormat format = ExportFormats.FromPath(chosen) ?? ExportFormats.All[Math.Clamp(filterIndex - 1, 0, ExportFormats.All.Length - 1)];
+ if (still && !ExportFormats.IsSequence(format))
+ {
+ format = ExportFormat.Png;
+ }
+ if (ExportFormats.FromPath(chosen) != format)
+ {
+ chosen = Path.ChangeExtension(chosen, ExportFormats.Extension(format));
+ }
+ Logger.Debug("Export: {What} as {Format} to {Path}", still ? "the shown frame " + stillFrame : field && intensity ? "field and intensity" : field ? "field" : "intensity", format, chosen);
+ if (!ExportFormats.IsAvailable(format))
+ {
+ Logger.Error("MP4 export is not available: Media Foundation is missing on this computer (Windows N needs the Media Feature Pack)");
+ MessageBox.Show(this, (string)FindResource("ExportError"), (string)FindResource("Title"), MessageBoxButton.OK, MessageBoxImage.Error);
+ return;
+ }
+ // the output paths: one per layer; "both" takes the chosen name without a layer suffix and appends its own
+ var outputs = new List<(FrameLayer Layer, string Path)>();
+ if (field && intensity)
+ {
+ string folder = Path.GetDirectoryName(chosen) ?? "";
+ string name = Path.GetFileNameWithoutExtension(chosen);
+ foreach (string known in new[] { "_field", "_intensity" })
+ {
+ if (name.EndsWith(known, StringComparison.OrdinalIgnoreCase))
+ {
+ name = name[..^known.Length];
+ }
+ }
+ string extension = ExportFormats.Extension(format);
+ outputs.Add((FrameLayer.Field, Path.Combine(folder, name + "_field" + extension)));
+ outputs.Add((FrameLayer.Intensity, Path.Combine(folder, name + "_intensity" + extension)));
+ }
+ else
+ {
+ outputs.Add((field ? FrameLayer.Field : FrameLayer.Intensity, chosen));
+ }
+ // a sequence goes to a folder of its own; one that exists with files in it is replaced only on request
+ if (!still && ExportFormats.IsSequence(format))
+ {
+ foreach ((_, string path) in outputs)
+ {
+ string folder = ExportFormats.SequenceFolder(path);
+ if (Directory.Exists(folder) && Directory.EnumerateFileSystemEntries(folder).Any()
+ && MessageBox.Show(this, string.Format((string)FindResource("ExportFolderExistsFormat"), folder), (string)FindResource("Title"), MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
+ {
+ Logger.Debug("Export cancelled: {Folder} kept", folder);
+ return;
+ }
+ }
+ }
+ SimulationRun? run = await EnsureRunForExport(intensity);
+ if (run == null)
+ {
+ return;
+ }
+ // the range in frames, from the model's steps like the preview's in/out points; a still is the shown frame
+ Display display = Project.Display;
+ int every = run.Spec.VisualizeEvery;
+ int lastFrame = run.Spec.FrameCount - 1;
+ int first;
+ int last;
+ if (still)
+ {
+ first = last = Math.Clamp(stillFrame, 0, lastFrame);
+ }
+ else
+ {
+ first = Math.Clamp(display.ExportFrom / every, 0, lastFrame);
+ last = display.ExportTo <= 0 ? lastFrame : Math.Clamp(display.ExportTo / every, first, lastFrame);
+ }
+ int frameCount = last - first + 1;
+ Logger.Debug("Export range: frames {First} to {Last} ({Count}) of the run's {Total}, {Width}×{Height}, store {Store}", first, last, frameCount, run.Spec.FrameCount, run.Spec.Width, run.Spec.Height, run.Store.Path);
+ // the targets: the layer's colours and outline, the probe boxes, the sink
+ var targets = new List<ExportTarget>();
+ try
+ {
+ byte[]? edges = null;
+ if (display.Field.OverlayInExport || display.Intensity.OverlayInExport)
+ {
+ ScenePixels? scene = LoadSceneImage();
+ if (scene != null && scene.Width == run.Spec.Width && scene.Height == run.Spec.Height)
+ {
+ edges = GlowingEdges.Compute(scene.Bgra, scene.Width, scene.Height, scene.StrideBytes);
+ }
+ Logger.Debug("Export outline: {State}", edges != null ? "computed from the scene image" : "none (no image scene)");
+ }
+ ProbeGraphPainter? painter = display.ProbeGraphsInExport || display.ProbeMarkersInExport ? new ProbeGraphPainter(Project, run, display.ProbeGraphsInExport, display.ProbeMarkersInExport) : null;
+ foreach ((FrameLayer layer, string path) in outputs)
+ {
+ DisplayLayer settings = layer == FrameLayer.Field ? display.Field : display.Intensity;
+ int[]? lut = ColorSchemeCatalog.Instance.LutFor(Project, settings.ColorScheme, settings.BlackLevel);
+ Action<int, Memory<int>>? decorate = painter?.For(layer == FrameLayer.Field ? ProbeLayer.Field : ProbeLayer.Intensity);
+ var exportLayer = new ExportLayer(layer, lut, (float)settings.Brightness, settings.OverlayInExport ? edges : null, settings.OverlayGain, decorate);
+ // the sink is opened by the job on its thread (a Media Foundation writer must stay on one thread)
+ int width = run.Spec.Width;
+ int height = run.Spec.Height;
+ int fps = display.Video.Fps;
+ int quality = display.Video.Quality;
+ string output = !still && ExportFormats.IsSequence(format) ? ExportFormats.SequenceFolder(path) : path;
+ Func<IFrameSink> open = still
+ ? () => ExportFormats.OpenStill(format, path, width, height, quality)
+ : () => ExportFormats.Open(format, path, width, height, fps, quality, frameCount);
+ targets.Add(new ExportTarget(exportLayer, output, open));
+ Logger.Debug("Export target {Layer}: scheme '{Scheme}' (black level {Black}), brightness {Brightness}, outline {Outline}, probe boxes {Boxes}, markers {Markers}, to {Output}",
+ layer, settings.ColorScheme, settings.BlackLevel, settings.Brightness, settings.OverlayInExport && edges != null ? "gain " + settings.OverlayGain : "off", display.ProbeGraphsInExport ? "on" : "off", display.ProbeMarkersInExport ? "on" : "off", output);
+ }
+ if (!still && format == ExportFormat.Mpeg1)
+ {
+ double used = Mpeg1Writer.FrameRates[Mpeg1Writer.NearestFrameRateCode(display.Video.Fps) - 1];
+ if (Math.Abs(used - display.Video.Fps) > 0.01)
+ {
+ Logger.Warn("MPEG-1 has no {Wanted} fps: the video is written at {Used:0.###} fps", display.Video.Fps, used);
+ }
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or RunSpecException)
+ {
+ Logger.Error(ex, "The export could not start: {Message}", ex.Message);
+ ShowError((string)FindResource("ExportError"), ex);
+ return;
+ }
+ var job = new ExportJob(run.Store, first, last, targets, SynchronizationContext.Current);
+ job.Finished += (_, _) => OnExportFinished(job);
+ WatchExport(job);
+ Export = job;
+ Logger.Info("Export started: frames {First} to {Last} ({Count}) of {Width}×{Height} to {Outputs}",
+ first, last, frameCount, run.Spec.Width, run.Spec.Height, string.Join(", ", targets.Select(target => target.Output)));
+ job.Start();
+ }
+
+ /// <summary>The project's name for a file: the project file's name, else "project".</summary>
+ private string ProjectName() => Path.GetFileNameWithoutExtension(Filename ?? _suggestedFileName ?? "project");
+
+ /// <summary>
+ /// A completed run the export can read: the current one when it is fresh, finished or in progress, and
+ /// holds the intensity plane if asked for; otherwise a run is started and awaited. Null when no run could
+ /// be had (logged, and an error shown when the run could not start).
+ /// </summary>
+ private async Task<SimulationRun?> EnsureRunForExport(bool intensity)
+ {
+ IsExportWaiting = true;
+ try
+ {
+ for (int attempt = 0; attempt < 3; attempt++)
+ {
+ SimulationRun? run = Run;
+ string? reason = run == null ? "no run" : IsRunStale ? "the run is stale" : IsProbesStale ? "the probes were edited since the run"
+ : intensity && !run.Store.Has(FrameLayer.Intensity) ? "the run has no intensity plane" : !run.IsActive && run.State != RunState.Completed ? "the run did not complete" : null;
+ if (reason != null)
+ {
+ Logger.Debug("Export: a run is started first ({Reason})", reason);
+ StartRun(automatic: true, trackIntensity: intensity);
+ run = Run;
+ }
+ else if (run!.IsActive)
+ {
+ Logger.Debug("Export: waiting for the run in progress");
+ }
+ if (run == null)
+ {
+ return null;
+ }
+ await run.Completion;
+ await WaitForState(run);
+ if (run.State == RunState.Completed && ReferenceEquals(run, Run))
+ {
+ return run;
+ }
+ if (!ReferenceEquals(run, Run))
+ {
+ // replaced meanwhile (an edit started a fresh one): look at the new one
+ Logger.Debug("Export: the run was replaced while waited for, looking again");
+ continue;
+ }
+ Logger.Warn("Export abandoned: the run ended {State}", run.State);
+ return null;
+ }
+ Logger.Warn("Export abandoned: the project kept changing while its run was computed");
+ return null;
+ }
+ catch (Exception ex) when (ex is RunSpecException or IOException or UnauthorizedAccessException or NotSupportedException)
+ {
+ Logger.Error(ex, "The export's run could not start: {Message}", ex.Message);
+ ShowError((string)FindResource("RunError"), ex);
+ return null;
+ }
+ finally
+ {
+ IsExportWaiting = false;
+ }
+ }
+
+ /// <summary>The run's final state is posted to the UI thread after its completion task completes; wait for that post.</summary>
+ private static async Task WaitForState(SimulationRun run)
+ {
+ for (int i = 0; i < 50 && !run.IsFinished; i++)
+ {
+ await Task.Delay(20);
+ }
+ }
+
+ private void OnExportFinished(ExportJob job)
+ {
+ if (!ReferenceEquals(job, Export))
+ {
+ return;
+ }
+ UpdateBusy();
+ string outputs = string.Join(", ", job.Targets.Select(target => target.Output));
+ switch (job.State)
+ {
+ case ExportState.Completed:
+ Logger.Info("Exported {Frames} frames to {Outputs} in {Seconds:0.0} s", job.FramesDone, outputs, job.Elapsed.TotalSeconds);
+ break;
+ case ExportState.Cancelled:
+ Logger.Warn("Export cancelled after {Frames} of {Total} frames; {Outputs} hold what was written", job.FramesDone, job.FrameCount, outputs);
+ break;
+ default:
+ Logger.Error("Export failed after {Frames} frames: {Message}", job.FramesDone, job.Error?.Message);
+ if (job.Error != null)
+ {
+ ShowError((string)FindResource("ExportError"), job.Error);
+ }
+ break;
+ }
+ // the auto re-run held back during the export may be due now
+ OnRunFinished();
+ }
+
+ /// <summary>Cancels a running export and waits briefly for its files to close; for closing the window.</summary>
+ private void ShutdownExport()
+ {
+ ExportJob? job = Export;
+ if (job?.IsActive != true)
+ {
+ return;
+ }
+ job.Cancel();
+ if (!job.Completion.Wait(TimeSpan.FromSeconds(10)))
+ {
+ Logger.Warn("The export did not stop in time; its last file may be incomplete");
+ }
+ }
+}
diff --git a/WaveDude.WPF/MainWindow.Live.cs b/WaveDude.WPF/MainWindow.Live.cs
index 0da8111..016bbc1 100644
--- a/WaveDude.WPF/MainWindow.Live.cs
+++ b/WaveDude.WPF/MainWindow.Live.cs
@@ -32,6 +32,10 @@ public partial class MainWindow
public static readonly DependencyProperty IsRunStaleProperty = DependencyProperty.Register(
nameof(IsRunStale), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
+ /// <summary>Identifies the <see cref="IsComputingFrame"/> property.</summary>
+ public static readonly DependencyProperty IsComputingFrameProperty = DependencyProperty.Register(
+ nameof(IsComputingFrame), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
+
/// <summary>Identifies the <see cref="IsProbesStale"/> property.</summary>
public static readonly DependencyProperty IsProbesStaleProperty = DependencyProperty.Register(
nameof(IsProbesStale), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
@@ -50,6 +54,7 @@ public partial class MainWindow
private int _lastSkippedFrame = -1;
private DispatcherTimer? _scratchTimer;
private DispatcherTimer? _rerunTimer;
+ private (RunSpec Spec, int Frame)? _scratchRequested;
private (string Path, DateTime Written, ScenePixels Pixels)? _imageCache;
private (byte[] Data, ScenePixels Pixels)? _embeddedCache;
@@ -72,6 +77,18 @@ public partial class MainWindow
set => SetValue(IsProbesStaleProperty, value);
}
+ /// <summary>
+ /// Whether a scratch frame for the preview's position is being computed: from the request until its result
+ /// (or a newer request's). The preview dims its pictures and shows a spinner meanwhile, so the wait reads as
+ /// work in progress rather than as a preview that does not update (the author's impression; the user's
+ /// rule, 2026-10-14).
+ /// </summary>
+ public bool IsComputingFrame
+ {
+ get => (bool)GetValue(IsComputingFrameProperty);
+ private set => SetValue(IsComputingFrameProperty, value);
+ }
+
/// <summary>The newest scratch frame (or skip notice) for the preview's position; null when none applies.</summary>
public ScratchResult? ScratchFrame
{
@@ -101,6 +118,7 @@ public partial class MainWindow
}, DispatcherPriority.Background);
IsRunStale = false;
IsProbesStale = false;
+ IsDirty = false;
ScratchFrame = null;
if (project != null)
{
@@ -113,6 +131,7 @@ public partial class MainWindow
private void OnProjectChanged(object? sender, ProjectChange change)
{
+ IsDirty = true;
if (change.Item is ColorScheme or ObservableCollection<ColorScheme>)
{
// a project scheme edited, added or removed: recolour the frame shown
@@ -122,8 +141,9 @@ public partial class MainWindow
if (change.AffectsProbes)
{
// the frames stay, the recordings are stale: the scratch frame brings the new recording for the position
- if (Run != null)
+ if (Run != null && !IsProbesStale)
{
+ Logger.Debug("Probes edited ({Item}.{Property}): the run's recordings are stale", change.Item, change.Property);
IsProbesStale = true;
}
ScheduleScratch();
@@ -133,6 +153,10 @@ public partial class MainWindow
{
return;
}
+ if (Run != null && !IsRunStale)
+ {
+ Logger.Debug("Edited ({Item}.{Property}): the run is stale", change.Item, change.Property ?? "list");
+ }
if (change.Item is Scene)
{
UpdateScenePixels();
@@ -144,6 +168,7 @@ public partial class MainWindow
if (Run is { IsAutomatic: true, IsActive: true })
{
// its snapshot is already obsolete: stop it now, the quiet period starts a fresh one
+ Logger.Debug("The automatic run is stopped: its snapshot is obsolete");
Run.Stop();
}
ScheduleScratch();
@@ -194,11 +219,24 @@ public partial class MainWindow
run.Pause();
_pausedForScratch = run;
}
- _scratch.Request(spec, Math.Clamp(PreviewPosition, 0, Math.Max(0, spec.FrameCount - 1)));
+ int frame = Math.Clamp(PreviewPosition, 0, Math.Max(0, spec.FrameCount - 1));
+ Logger.Debug("Preview frame {Frame} requested from scratch ({Reason})", frame,
+ Run == null ? "no run" : IsRunStale ? "the run is stale" : IsProbesStale ? "the probes changed" : "the run has not got there yet");
+ _scratchRequested = (spec, frame);
+ _scratch.Request(spec, frame);
+ SetScratchBusy(frame);
+ IsComputingFrame = true;
}
private void OnScratchCompleted(object? sender, ScratchResult result)
{
+ // the request this result answers is the newest one: the indicator goes off (a newer request keeps it on)
+ if (_scratchRequested is { } requested && ReferenceEquals(requested.Spec, result.Spec) && requested.Frame == result.Frame)
+ {
+ _scratchRequested = null;
+ SetScratchBusy(-1);
+ IsComputingFrame = false;
+ }
if (_pausedForScratch is { } paused)
{
_pausedForScratch = null;
@@ -233,11 +271,14 @@ public partial class MainWindow
_rerunTimer!.Stop();
if (!Settings.Default.AutoRerun || !IsRunStale || Run?.IsActive == true)
{
+ Logger.Debug("No automatic re-run: {Reason}", !Settings.Default.AutoRerun ? "switched off" : !IsRunStale ? "the run is not stale" : "a run is active");
return;
}
- if (_scratch?.IsBusy == true || _scratchTimer?.IsEnabled == true)
+ if (_scratch?.IsBusy == true || _scratchTimer?.IsEnabled == true || IsExporting)
{
- // the frame the user is looking at comes first, requested or computing; the run would take the cores away from it
+ // the frame the user is looking at comes first, requested or computing; the run would take the cores away
+ // from it. An export reads the current run's store, so it keeps its run until it is done.
+ Logger.Debug("Automatic re-run postponed: {Reason}", IsExporting ? "an export is in progress" : "a preview frame is being computed");
ScheduleRerun();
return;
}
@@ -336,6 +377,7 @@ public partial class MainWindow
private void ShutdownScratch()
{
+ _scratchRequested = null;
_scratchTimer?.Stop();
_rerunTimer?.Stop();
_scratch?.Dispose();
diff --git a/WaveDude.WPF/MainWindow.Simulation.cs b/WaveDude.WPF/MainWindow.Simulation.cs
index 85a398b..d93866b 100644
--- a/WaveDude.WPF/MainWindow.Simulation.cs
+++ b/WaveDude.WPF/MainWindow.Simulation.cs
@@ -28,7 +28,7 @@ public partial class MainWindow
set => SetValue(RunProperty, value);
}
- private void CanRun(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = Run?.IsActive != true;
+ private void CanRun(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = Run?.IsActive != true && !IsExporting;
private void OnRun(object sender, ExecutedRoutedEventArgs e)
{
@@ -45,13 +45,14 @@ public partial class MainWindow
/// <summary>Decodes the scene image, snapshots the project, checks the disk, creates the store and starts the worker.</summary>
/// <param name="automatic">Started after an edit rather than by the user: the preview keeps its position.</param>
- private void StartRun(bool automatic = false)
+ /// <param name="trackIntensity">Store the intensity plane whatever the project needs (an export of the intensity asks for it).</param>
+ private void StartRun(bool automatic = false, bool trackIntensity = false)
{
if (!Settings.Default.UseGpu)
{
Logger.Info("Running on the CPU: 'Use the GPU' is off in the Simulation menu");
}
- RunSpec spec = RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu);
+ RunSpec spec = RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu, trackIntensity);
// the frames stay in memory up to the budget (the user's share of the RAM, capped by what is free now); only
// the rest needs room on the cache drive (2026-10-14)
long budget = FrameMemory.Budget(Settings.Default.FrameMemoryPercent);
@@ -102,10 +103,13 @@ public partial class MainWindow
private void CanControlRun(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = Run?.IsActive == true;
- /// <summary>Play pressed: a missing or stale run is started like an automatic one (position kept, not followed); errors go to the log and status bar.</summary>
+ /// <summary>Stop applies to a run in progress, or to an export in progress (Esc cancels it).</summary>
+ private void CanStop(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = Run?.IsActive == true || Export?.IsActive == true;
+
+ /// <summary>Play pressed: a missing or stale run is started like an automatic one (position kept, not followed); errors go to the log and status bar. Not while an export reads the store.</summary>
private void OnEnsureRun(object sender, ExecutedRoutedEventArgs e)
{
- if (Run?.IsActive == true || (Run != null && !IsRunStale && !IsProbesStale))
+ if (IsExporting || Run?.IsActive == true || (Run != null && !IsRunStale && !IsProbesStale))
{
return;
}
@@ -121,7 +125,18 @@ public partial class MainWindow
private void OnTogglePause(object sender, ExecutedRoutedEventArgs e) => Run?.TogglePause();
- private void OnStop(object sender, ExecutedRoutedEventArgs e) => Run?.Stop();
+ /// <summary>Cancels the export when one is running (it has the user's attention then), else stops the run.</summary>
+ private void OnStop(object sender, ExecutedRoutedEventArgs e)
+ {
+ if (Export?.IsActive == true)
+ {
+ Export.Cancel();
+ }
+ else
+ {
+ Run?.Stop();
+ }
+ }
/// <summary>
/// Drops the current run: stops it and disposes its store (deleting the cache file) once the worker has
@@ -129,7 +144,17 @@ public partial class MainWindow
/// </summary>
private void DiscardRun()
{
+ if (Export?.IsActive == true)
+ {
+ // the export reads this run's store; a project replaced under it ends it with what it has
+ Logger.Warn("Export cancelled: its run is being discarded");
+ Export.Cancel();
+ }
SimulationRun? old = Run;
+ if (old != null)
+ {
+ Logger.Debug("Run discarded: {State}, {Frames} frames, cache {Path}", old.State, old.FrameCount, old.Store.Path);
+ }
// the run goes first: with it gone the preview shows the scratch frame; clearing the stale flag before
// would make it pick the old store for a moment (and wait on its file being deleted)
Run = null;
diff --git a/WaveDude.WPF/MainWindow.Taskbar.cs b/WaveDude.WPF/MainWindow.Taskbar.cs
new file mode 100644
index 0000000..e527fb4
--- /dev/null
+++ b/WaveDude.WPF/MainWindow.Taskbar.cs
@@ -0,0 +1,36 @@
+using System.Windows.Shell;
+
+namespace WaveDude.WPF;
+
+/// <summary>
+/// Mirrors the status bar's busy indicator on the window's taskbar button (the Windows 7 taskbar progress,
+/// which WPF exposes as <see cref="TaskbarItemInfo"/>; the user's rule, 2026-10-14): an export writing frames
+/// fills the button as the frames go, an export waiting for its run or a scratch frame being computed shows
+/// the indeterminate marquee, and an idle application shows nothing. Fed by <see cref="UpdateBusy"/>. UI thread.
+/// </summary>
+public partial class MainWindow
+{
+ /// <summary>Puts the busy state on the taskbar button; the element is declared in the window's XAML.</summary>
+ private void UpdateTaskbar()
+ {
+ if (TaskbarItemInfo is not { } taskbar)
+ {
+ return;
+ }
+ if (!IsBusy)
+ {
+ taskbar.ProgressState = TaskbarItemProgressState.None;
+ taskbar.ProgressValue = 0;
+ }
+ else if (IsBusyIndeterminate)
+ {
+ taskbar.ProgressState = TaskbarItemProgressState.Indeterminate;
+ }
+ else
+ {
+ int total = Export?.FrameCount ?? 0;
+ taskbar.ProgressValue = total > 0 ? Math.Clamp((double)(Export?.FramesDone ?? 0) / total, 0.0, 1.0) : 0.0;
+ taskbar.ProgressState = TaskbarItemProgressState.Normal;
+ }
+ }
+}
diff --git a/WaveDude.WPF/MainWindow.xaml b/WaveDude.WPF/MainWindow.xaml
index a345be7..49be8c6 100644
--- a/WaveDude.WPF/MainWindow.xaml
+++ b/WaveDude.WPF/MainWindow.xaml
@@ -87,11 +87,17 @@
</Style>
</Window.Resources>
- <!-- "Wave Dude - <file>", just the name while no file is open -->
+ <!-- the taskbar button shows the status bar's busy state too (export progress, or the marquee while waiting or computing a frame); MainWindow.Taskbar.cs feeds it -->
+ <Window.TaskbarItemInfo>
+ <TaskbarItemInfo />
+ </Window.TaskbarItemInfo>
+
+ <!-- "Wave Dude - <file>", just the name while no file is open; an asterisk after the file (or "Untitled") marks unsaved edits -->
<Window.Title>
<MultiBinding Converter="{StaticResource TitleConverter}">
<Binding Source="{StaticResource Title}" />
<Binding Path="Filename" />
+ <Binding Path="IsDirty" />
</MultiBinding>
</Window.Title>
@@ -108,7 +114,14 @@
<!-- the run; handlers in MainWindow.Simulation.cs -->
<CommandBinding Command="{x:Static commands:SimulationCommands.Run}" CanExecute="CanRun" Executed="OnRun" />
<CommandBinding Command="{x:Static commands:SimulationCommands.TogglePause}" CanExecute="CanControlRun" Executed="OnTogglePause" />
- <CommandBinding Command="{x:Static commands:SimulationCommands.Stop}" CanExecute="CanControlRun" Executed="OnStop" />
+ <CommandBinding Command="{x:Static commands:SimulationCommands.Stop}" CanExecute="CanStop" Executed="OnStop" />
+
+ <!-- export; handlers in MainWindow.Export.cs -->
+ <CommandBinding Command="{x:Static commands:ExportCommands.Field}" CanExecute="CanExport" Executed="OnExportField" />
+ <CommandBinding Command="{x:Static commands:ExportCommands.Intensity}" CanExecute="CanExport" Executed="OnExportIntensity" />
+ <CommandBinding Command="{x:Static commands:ExportCommands.Both}" CanExecute="CanExport" Executed="OnExportBoth" />
+ <CommandBinding Command="{x:Static commands:ExportCommands.FieldFrame}" CanExecute="CanExport" Executed="OnExportFieldFrame" />
+ <CommandBinding Command="{x:Static commands:ExportCommands.IntensityFrame}" CanExecute="CanExport" Executed="OnExportIntensityFrame" />
<CommandBinding Command="{x:Static commands:SimulationCommands.EnsureRun}" Executed="OnEnsureRun" />
<CommandBinding Command="{x:Static commands:SimulationCommands.SetFrameMemory}" Executed="OnSetFrameMemory" />
@@ -143,6 +156,17 @@
<MenuItem Command="ApplicationCommands.Save" Header="{DynamicResource MenuFileSave}" />
<MenuItem Command="ApplicationCommands.SaveAs" Header="{DynamicResource MenuFileSaveAs}" InputGestureText="Ctrl+Shift+S" />
<Separator />
+ <!-- export of the current run's frames (the export range, the display settings as they are); the same entries sit on the pictures' context menus -->
+ <MenuItem Header="{DynamicResource MenuFileExport}" AutomationProperties.AutomationId="MenuExport">
+ <MenuItem Command="{x:Static commands:ExportCommands.Field}" Header="{DynamicResource MenuFileExportField}" AutomationProperties.AutomationId="MenuExportField" />
+ <MenuItem Command="{x:Static commands:ExportCommands.Intensity}" Header="{DynamicResource MenuFileExportIntensity}" AutomationProperties.AutomationId="MenuExportIntensity" />
+ <MenuItem Command="{x:Static commands:ExportCommands.Both}" Header="{DynamicResource MenuFileExportBoth}" AutomationProperties.AutomationId="MenuExportBoth" />
+ <Separator />
+ <!-- the frame the preview shows, from the same run, as one image -->
+ <MenuItem Command="{x:Static commands:ExportCommands.FieldFrame}" Header="{DynamicResource MenuFileExportFieldFrame}" AutomationProperties.AutomationId="MenuExportFieldFrame" />
+ <MenuItem Command="{x:Static commands:ExportCommands.IntensityFrame}" Header="{DynamicResource MenuFileExportIntensityFrame}" AutomationProperties.AutomationId="MenuExportIntensityFrame" />
+ </MenuItem>
+ <Separator />
<MenuItem Command="ApplicationCommands.Close" Header="{DynamicResource MenuFileClose}" />
<Separator />
<MenuItem Command="{StaticResource FileExit}" Header="{DynamicResource MenuFileExit}" />
@@ -205,6 +229,17 @@
<StatusBar.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{StaticResource ShowMessages}" />
</StatusBar.InputBindings>
+ <!-- the busy indicator: an export (frames done), an export waiting for its run or a scratch frame being
+ computed for the preview (indeterminate); Esc cancels an export -->
+ <StatusBarItem DockPanel.Dock="Right" HorizontalAlignment="Right">
+ <StackPanel Orientation="Horizontal">
+ <TextBlock Text="{Binding BusyText}" AutomationProperties.AutomationId="StatusExport" VerticalAlignment="Center" />
+ <ProgressBar Width="120" Height="12" Margin="6,0,8,0" VerticalAlignment="Center" ToolTip="{DynamicResource TipExportCancel}"
+ Minimum="0" Maximum="{Binding Export.FrameCount, FallbackValue=1}" Value="{Binding Export.FramesDone, Mode=OneWay, FallbackValue=0}"
+ IsIndeterminate="{Binding IsBusyIndeterminate}" AutomationProperties.AutomationId="StatusBusyBar"
+ Visibility="{Binding IsBusy, Converter={StaticResource BoolToVisibility}}" />
+ </StackPanel>
+ </StatusBarItem>
<!-- the run's progress on the right: state, steps, engine; empty while there is no run -->
<StatusBarItem DockPanel.Dock="Right" HorizontalAlignment="Right">
<TextBlock AutomationProperties.AutomationId="StatusRun">
@@ -240,6 +275,7 @@
<Border BorderThickness="1" BorderBrush="{DynamicResource ToolWindowBorder}">
<panes:PreviewPane x:Name="previewPane" Project="{Binding Project}" Run="{Binding Run}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
IsStale="{Binding IsRunStale}" IsProbesStale="{Binding IsProbesStale}" ScratchFrame="{Binding ScratchFrame}"
+ IsComputing="{Binding IsComputingFrame}"
Position="{Binding PreviewPosition, Mode=TwoWay}"
Orientation="{Binding Source={x:Static p:Settings.Default}, Path=PreviewOrientation, Mode=TwoWay}" />
</Border>
diff --git a/WaveDude.WPF/MainWindow.xaml.cs b/WaveDude.WPF/MainWindow.xaml.cs
index a526762..e64d0a5 100644
--- a/WaveDude.WPF/MainWindow.xaml.cs
+++ b/WaveDude.WPF/MainWindow.xaml.cs
@@ -3,6 +3,7 @@ using System.Configuration;
using System.IO;
using System.Windows;
using System.Windows.Controls;
+using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Shell;
using Microsoft.Win32;
@@ -41,6 +42,10 @@ public partial class MainWindow : Window
nameof(Filename), typeof(string), typeof(MainWindow),
new PropertyMetadata(null, (_, _) => CommandManager.InvalidateRequerySuggested()));
+ /// <summary>Identifies the <see cref="IsDirty"/> property.</summary>
+ public static readonly DependencyProperty IsDirtyProperty = DependencyProperty.Register(
+ nameof(IsDirty), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
+
/// <summary>Identifies the <see cref="SelectedItem"/> property.</summary>
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
nameof(SelectedItem), typeof(object), typeof(MainWindow),
@@ -81,9 +86,15 @@ public partial class MainWindow : Window
Logger.Info("Frames kept in memory: {Percent} % of the RAM, {Budget} right now (Simulation menu)", Settings.Default.FrameMemoryPercent, FrameMemory.Gigabytes(FrameMemory.Budget(Settings.Default.FrameMemoryPercent)));
}
};
- Closing += (_, _) =>
+ Closing += (_, e) =>
{
+ if (!ConfirmDiscard())
+ {
+ e.Cancel = true;
+ return;
+ }
Settings.Default.Layout = dockHost.SaveLayout();
+ ShutdownExport();
ShutdownRun();
ShutdownScratch();
};
@@ -103,6 +114,17 @@ public partial class MainWindow : Window
set => SetValue(FilenameProperty, value);
}
+ /// <summary>
+ /// Whether the project was edited since it was opened, created or last saved (2026-10-14): the title
+ /// carries an asterisk and New, Open, Close and Exit ask before discarding. Set by the watcher on any
+ /// change, model-wide; cleared when the project is replaced or saved.
+ /// </summary>
+ public bool IsDirty
+ {
+ get => (bool)GetValue(IsDirtyProperty);
+ set => SetValue(IsDirtyProperty, value);
+ }
+
/// <summary>The model object selected in the project tree (or on the preview's pictures), or null.</summary>
public object? SelectedItem
{
@@ -222,6 +244,7 @@ public partial class MainWindow : Window
fileName = Path.GetFullPath(fileName);
Project.Save(fileName);
Filename = fileName;
+ IsDirty = false;
Logger.Info("Saved '{Path}'", fileName);
RememberRecent(fileName);
return true;
@@ -255,6 +278,50 @@ public partial class MainWindow : Window
private void ShowError(string message, Exception ex) =>
MessageBox.Show(this, $"{message}\n{ex.Message}", (string)FindResource("Title"), MessageBoxButton.OK, MessageBoxImage.Error);
+ /// <summary>
+ /// Asks whether to save an edited project before it is discarded: Yes saves (through Save As when it has
+ /// no file yet), No discards, Cancel keeps it. True when the caller may go on.
+ /// </summary>
+ private bool ConfirmDiscard()
+ {
+ if (!IsDirty)
+ {
+ return true;
+ }
+ if (Environment.GetEnvironmentVariable("WAVEDUDE_DISCARD_EDITS") == "1")
+ {
+ // a UI harness cannot answer the question by posted keys: it discards
+ Logger.Debug("Edits discarded without asking (WAVEDUDE_DISCARD_EDITS)");
+ return true;
+ }
+ string name = Filename != null ? Path.GetFileName(Filename) : (string)FindResource("Untitled");
+ MessageBoxResult answer = MessageBox.Show(this, string.Format((string)FindResource("SaveChangesFormat"), name), (string)FindResource("Title"),
+ MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
+ return answer switch
+ {
+ MessageBoxResult.Yes => SaveInteractively(),
+ MessageBoxResult.No => true,
+ _ => false,
+ };
+ }
+
+ /// <summary>Save, or Save As for a project without a file; false when the user cancelled or the save failed.</summary>
+ private bool SaveInteractively()
+ {
+ if (Filename != null)
+ {
+ return SaveFile(Filename);
+ }
+ var dialog = new SaveFileDialog
+ {
+ Filter = (string)FindResource("SaveFileDialogFilter"),
+ DefaultExt = ProjectExtension,
+ AddExtension = true,
+ FileName = _suggestedFileName ?? "",
+ };
+ return dialog.ShowDialog(this) == true && SaveFile(dialog.FileName);
+ }
+
/// <summary>Simulation > Frames kept in memory: the chosen share of the RAM, applied to the next run.</summary>
private void OnSetFrameMemory(object sender, ExecutedRoutedEventArgs e)
{
@@ -267,6 +334,10 @@ public partial class MainWindow : Window
private void OnFileNew(object sender, ExecutedRoutedEventArgs e)
{
+ if (!ConfirmDiscard())
+ {
+ return;
+ }
DiscardRun();
Project = new Project();
Filename = null;
@@ -276,6 +347,10 @@ public partial class MainWindow : Window
private void OnFileOpen(object sender, ExecutedRoutedEventArgs e)
{
+ if (!ConfirmDiscard())
+ {
+ return;
+ }
if (e.Parameter is string recent)
{
OpenFile(recent);
@@ -319,10 +394,17 @@ public partial class MainWindow : Window
}
}
+ /// <summary>The folder of the project file, or null for an unsaved project.</summary>
+ private string? ProjectFolder => Filename != null ? Path.GetDirectoryName(Filename) : null;
+
private void CanFileClose(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = Filename != null;
private void OnFileClose(object sender, ExecutedRoutedEventArgs e)
{
+ if (!ConfirmDiscard())
+ {
+ return;
+ }
DiscardRun();
Project = new Project();
Filename = null;
@@ -341,7 +423,7 @@ public partial class MainWindow : Window
private void OnDrop(object sender, DragEventArgs e)
{
- if (e.Data.GetData(DataFormats.FileDrop) is string[] { Length: > 0 } files)
+ if (e.Data.GetData(DataFormats.FileDrop) is string[] { Length: > 0 } files && ConfirmDiscard())
{
OpenFile(files[0]);
}
@@ -356,6 +438,9 @@ public partial class MainWindow : Window
propertiesDock.Title = (string)FindResource("PaneProperties");
messagesDock.Title = (string)FindResource("PaneMessages");
themeMenu.Items.Refresh();
+ // the title's "Untitled" is looked up by the converter; the busy text is built in code
+ BindingOperations.GetMultiBindingExpression(this, TitleProperty)?.UpdateTarget();
+ UpdateBusy();
}
/// <summary>
diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml b/WaveDude.WPF/Panes/PreviewPane.xaml
index b522d86..3d233d0 100644
--- a/WaveDude.WPF/Panes/PreviewPane.xaml
+++ b/WaveDude.WPF/Panes/PreviewPane.xaml
@@ -35,6 +35,40 @@
<StreamGeometry x:Key="LiveGeometry">M0.5,5 A4.5,4.5 0 1 1 9.5,5 A4.5,4.5 0 1 1 0.5,5 Z M1.5,5 A3.5,3.5 0 1 0 8.5,5 A3.5,3.5 0 1 0 1.5,5 Z M3.5,5 A1.5,1.5 0 1 1 6.5,5 A1.5,1.5 0 1 1 3.5,5 Z</StreamGeometry>
<BooleanToVisibilityConverter x:Key="BoolToVisibility" />
+ <!-- the spinner over a dimmed picture while a frame computes: a three-quarter ring turning once a second while visible -->
+ <StreamGeometry x:Key="SpinnerGeometry">M18,3 A15,15 0 1 1 3,18</StreamGeometry>
+ <Style x:Key="Spinner" TargetType="{x:Type Path}">
+ <Setter Property="Data" Value="{StaticResource SpinnerGeometry}" />
+ <Setter Property="Width" Value="36" />
+ <Setter Property="Height" Value="36" />
+ <Setter Property="Stroke" Value="White" />
+ <Setter Property="StrokeThickness" Value="3" />
+ <Setter Property="StrokeStartLineCap" Value="Round" />
+ <Setter Property="StrokeEndLineCap" Value="Round" />
+ <Setter Property="HorizontalAlignment" Value="Center" />
+ <Setter Property="VerticalAlignment" Value="Center" />
+ <Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
+ <Setter Property="RenderTransform">
+ <Setter.Value>
+ <RotateTransform />
+ </Setter.Value>
+ </Setter>
+ <Style.Triggers>
+ <Trigger Property="IsVisible" Value="True">
+ <Trigger.EnterActions>
+ <BeginStoryboard Name="Spin">
+ <Storyboard>
+ <DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" From="0" To="360" Duration="0:0:1" RepeatBehavior="Forever" />
+ </Storyboard>
+ </BeginStoryboard>
+ </Trigger.EnterActions>
+ <Trigger.ExitActions>
+ <StopStoryboard BeginStoryboardName="Spin" />
+ </Trigger.ExitActions>
+ </Trigger>
+ </Style.Triggers>
+ </Style>
+
<!-- filled-glyph transport button; Content is the geometry. A tab stop: keyboard focus shows as an accent border -->
<Style x:Key="TransportButton" TargetType="{x:Type Button}">
<Setter Property="Width" Value="22" />
@@ -431,6 +465,18 @@
CanvasWidth="{Binding CanvasWidth, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"
CanvasHeight="{Binding CanvasHeight, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"
SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}, Mode=TwoWay}" />
+ <!-- a frame for this position is being computed (longer than a moment): the stale picture dims and a spinner
+ turns, so the wait reads as work in progress and not as a preview that does not update (2026-10-14) -->
+ <Grid IsHitTestVisible="False" Visibility="{Binding IsBusyOverlayVisible, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}, Converter={StaticResource BoolToVisibility}}">
+ <Rectangle Fill="Black" Opacity="0.45" />
+ <Path Style="{StaticResource Spinner}" />
+ </Grid>
+ <!-- the frame was not computed (its predicted cost is over the scratch budget) and nothing stands in: say so -->
+ <Border IsHitTestVisible="False" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#C0101216" CornerRadius="3" Padding="10,6"
+ Visibility="{Binding IsFrameSkipped, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}, Converter={StaticResource BoolToVisibility}}">
+ <TextBlock Text="{DynamicResource PreviewNotComputed}" Foreground="White" TextWrapping="Wrap" MaxWidth="280" TextAlignment="Center"
+ AutomationProperties.AutomationId="PreviewNotComputed" />
+ </Border>
</Grid>
</controls:PictureFrame>
</ControlTemplate>
@@ -499,14 +545,46 @@
<HeaderedContentControl x:Name="fieldCell" Style="{StaticResource PictureCell}" Header="{DynamicResource SectionField}"
Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage" local:PreviewPane.Layer="Field"
local:PreviewPane.OverlayImage="{Binding FieldOverlay, ElementName=pane}"
- Visibility="{Binding FieldSettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}" />
+ Visibility="{Binding FieldSettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}">
+ <HeaderedContentControl.ContextMenu>
+ <!-- export of this picture first, then the other and both; the commands route from the cell (CommandTarget) up to the window -->
+ <ContextMenu>
+ <ContextMenu.Resources>
+ <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
+ <Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
+ </Style>
+ </ContextMenu.Resources>
+ <MenuItem Header="{DynamicResource MenuExportThisFrame}" Command="{x:Static commands:ExportCommands.FieldFrame}" AutomationProperties.AutomationId="ContextExportFrame" />
+ <Separator />
+ <MenuItem Header="{DynamicResource MenuFileExportField}" Command="{x:Static commands:ExportCommands.Field}" AutomationProperties.AutomationId="ContextExportField" />
+ <MenuItem Header="{DynamicResource MenuFileExportIntensity}" Command="{x:Static commands:ExportCommands.Intensity}" AutomationProperties.AutomationId="ContextExportIntensity" />
+ <MenuItem Header="{DynamicResource MenuFileExportBoth}" Command="{x:Static commands:ExportCommands.Both}" AutomationProperties.AutomationId="ContextExportBoth" />
+ </ContextMenu>
+ </HeaderedContentControl.ContextMenu>
+ </HeaderedContentControl>
<GridSplitter x:Name="pictureSplitter" Style="{StaticResource PictureSplitter}" ToolTip="{DynamicResource TipPreviewSplitter}"
AutomationProperties.Name="{DynamicResource TipPreviewSplitter}" AutomationProperties.AutomationId="PreviewSplitter"
MouseDoubleClick="OnSplitterMouseDoubleClick" KeyDown="OnSplitterKeyDown" />
<HeaderedContentControl x:Name="intensityCell" Style="{StaticResource SecondPictureCell}" Header="{DynamicResource SectionIntensity}"
Content="{Binding IntensityImage, ElementName=pane}" Tag="PreviewIntensityImage" local:PreviewPane.Layer="Intensity"
local:PreviewPane.OverlayImage="{Binding IntensityOverlay, ElementName=pane}"
- Visibility="{Binding IntensitySettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}" />
+ Visibility="{Binding IntensitySettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}">
+ <HeaderedContentControl.ContextMenu>
+ <!-- export of this picture first, then the other and both; the commands route from the cell (CommandTarget) up to the window -->
+ <ContextMenu>
+ <ContextMenu.Resources>
+ <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
+ <Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
+ </Style>
+ </ContextMenu.Resources>
+ <MenuItem Header="{DynamicResource MenuExportThisFrame}" Command="{x:Static commands:ExportCommands.IntensityFrame}" AutomationProperties.AutomationId="ContextExportFrame" />
+ <Separator />
+ <MenuItem Header="{DynamicResource MenuFileExportIntensity}" Command="{x:Static commands:ExportCommands.Intensity}" AutomationProperties.AutomationId="ContextExportIntensity" />
+ <MenuItem Header="{DynamicResource MenuFileExportField}" Command="{x:Static commands:ExportCommands.Field}" AutomationProperties.AutomationId="ContextExportField" />
+ <MenuItem Header="{DynamicResource MenuFileExportBoth}" Command="{x:Static commands:ExportCommands.Both}" AutomationProperties.AutomationId="ContextExportBoth" />
+ </ContextMenu>
+ </HeaderedContentControl.ContextMenu>
+ </HeaderedContentControl>
</Grid>
</DockPanel>
diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml.cs b/WaveDude.WPF/Panes/PreviewPane.xaml.cs
index 20a0191..2f22e19 100644
--- a/WaveDude.WPF/Panes/PreviewPane.xaml.cs
+++ b/WaveDude.WPF/Panes/PreviewPane.xaml.cs
@@ -178,6 +178,25 @@ public partial class PreviewPane : UserControl
public static readonly DependencyProperty IsStaleProperty = DependencyProperty.Register(
nameof(IsStale), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false, (d, _) => ((PreviewPane)d).UpdateSource()));
+ /// <summary>Identifies the <see cref="IsComputing"/> property.</summary>
+ public static readonly DependencyProperty IsComputingProperty = DependencyProperty.Register(
+ nameof(IsComputing), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false, (d, _) => ((PreviewPane)d).OnComputingChanged()));
+
+ private static readonly DependencyPropertyKey IsBusyOverlayVisibleKey = DependencyProperty.RegisterReadOnly(
+ nameof(IsBusyOverlayVisible), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false));
+
+ /// <summary>Identifies the <see cref="IsBusyOverlayVisible"/> property.</summary>
+ public static readonly DependencyProperty IsBusyOverlayVisibleProperty = IsBusyOverlayVisibleKey.DependencyProperty;
+
+ private static readonly DependencyPropertyKey IsFrameSkippedKey = DependencyProperty.RegisterReadOnly(
+ nameof(IsFrameSkipped), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false));
+
+ /// <summary>Identifies the <see cref="IsFrameSkipped"/> property.</summary>
+ public static readonly DependencyProperty IsFrameSkippedProperty = IsFrameSkippedKey.DependencyProperty;
+
+ /// <summary>How long a frame may take before the pictures dim and the spinner shows; shorter waits pass unmarked, so a fast machine does not strobe.</summary>
+ private static readonly TimeSpan BusyOverlayDelay = TimeSpan.FromMilliseconds(150);
+
/// <summary>Identifies the <see cref="IsProbesStale"/> property.</summary>
public static readonly DependencyProperty IsProbesStaleProperty = DependencyProperty.Register(
nameof(IsProbesStale), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false, (d, _) => ((PreviewPane)d).UpdateSource()));
@@ -221,6 +240,7 @@ public partial class PreviewPane : UserControl
nameof(IntensitySettings), typeof(DisplayLayer), typeof(PreviewPane), new PropertyMetadata(null, (d, e) => ((PreviewPane)d).OnLayerSettingsChanged(FrameLayer.Intensity, e)));
private readonly DispatcherTimer _timer;
+ private readonly DispatcherTimer _busyDelay;
private readonly Stopwatch _clock = new();
private readonly FramePresenter _presenter;
@@ -263,6 +283,12 @@ public partial class PreviewPane : UserControl
_timer = new DispatcherTimer(DispatcherPriority.Render) { Interval = TimeSpan.FromSeconds(1.0 / 60.0) };
_timer.Tick += OnTick;
+ _busyDelay = new DispatcherTimer(DispatcherPriority.Normal) { Interval = BusyOverlayDelay };
+ _busyDelay.Tick += (_, _) =>
+ {
+ _busyDelay.Stop();
+ IsBusyOverlayVisible = IsComputing;
+ };
Unloaded += (_, _) => IsPlaying = false;
}
@@ -458,6 +484,27 @@ public partial class PreviewPane : UserControl
private set => SetValue(GraphScratchKey, value);
}
+ /// <summary>Whether a frame for <see cref="Position"/> is being computed (bound to the main window); after <see cref="BusyOverlayDelay"/> the pictures dim and a spinner turns until it arrives.</summary>
+ public bool IsComputing
+ {
+ get => (bool)GetValue(IsComputingProperty);
+ set => SetValue(IsComputingProperty, value);
+ }
+
+ /// <summary>Whether the dim and the spinner are shown over the pictures: <see cref="IsComputing"/> has lasted longer than <see cref="BusyOverlayDelay"/>.</summary>
+ public bool IsBusyOverlayVisible
+ {
+ get => (bool)GetValue(IsBusyOverlayVisibleProperty);
+ private set => SetValue(IsBusyOverlayVisibleKey, value);
+ }
+
+ /// <summary>Whether the frame at <see cref="Position"/> was not computed (its predicted cost exceeded the scratch budget) and nothing else can show it; a note says so on the pictures.</summary>
+ public bool IsFrameSkipped
+ {
+ get => (bool)GetValue(IsFrameSkippedProperty);
+ private set => SetValue(IsFrameSkippedKey, value);
+ }
+
/// <summary>Whether a probe was edited since the run started: its frames hold, its recordings do not. Bound to the main window.</summary>
public bool IsProbesStale
{
@@ -572,6 +619,9 @@ public partial class PreviewPane : UserControl
{
SimulationRun? run = Run;
ScratchResult? scratch = ScratchFrame;
+ bool storeHasFrame = run != null && !IsStale && run.FrameCount > Position;
+ // the position's frame was skipped (over the budget) and no stored frame stands in: the pictures say so
+ IsFrameSkipped = scratch is { Snapshot: null } && scratch.Frame == Position && !storeHasFrame;
bool useScratch = scratch is { Snapshot: not null } && scratch.Frame == Position
&& (run == null || IsStale || run.FrameCount <= Position);
if (useScratch)
@@ -665,6 +715,21 @@ public partial class PreviewPane : UserControl
Position = 0;
}
+ /// <summary>A frame started computing: the overlay follows after the delay; the frame arrived: it goes at once.</summary>
+ private void OnComputingChanged()
+ {
+ if (IsComputing)
+ {
+ _busyDelay.Stop();
+ _busyDelay.Start();
+ }
+ else
+ {
+ _busyDelay.Stop();
+ IsBusyOverlayVisible = false;
+ }
+ }
+
/// <summary>A black picture of the given size, frozen; what the pane shows before any run.</summary>
private static BitmapSource BlackFrame(int width, int height)
{
diff --git a/WaveDude.WPF/Properties/Settings.Designer.cs b/WaveDude.WPF/Properties/Settings.Designer.cs
index c55fd1d..4b6f0a0 100644
--- a/WaveDude.WPF/Properties/Settings.Designer.cs
+++ b/WaveDude.WPF/Properties/Settings.Designer.cs
@@ -176,6 +176,7 @@ namespace WaveDude.WPF.Properties {
this["UseGpu"] = value;
}
}
+
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("50")]
@@ -188,5 +189,28 @@ namespace WaveDude.WPF.Properties {
}
}
+ [global::System.Configuration.UserScopedSettingAttribute()]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Configuration.DefaultSettingValueAttribute("")]
+ public string LastExportFolder {
+ get {
+ return ((string)(this["LastExportFolder"]));
+ }
+ set {
+ this["LastExportFolder"] = value;
+ }
+ }
+
+ [global::System.Configuration.UserScopedSettingAttribute()]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Configuration.DefaultSettingValueAttribute("0")]
+ public int ExportFilterIndex {
+ get {
+ return ((int)(this["ExportFilterIndex"]));
+ }
+ set {
+ this["ExportFilterIndex"] = value;
+ }
+ }
}
}
diff --git a/WaveDude.WPF/Properties/Settings.settings b/WaveDude.WPF/Properties/Settings.settings
index 8817555..db89a87 100644
--- a/WaveDude.WPF/Properties/Settings.settings
+++ b/WaveDude.WPF/Properties/Settings.settings
@@ -44,5 +44,11 @@
<Setting Name="FrameMemoryPercent" Type="System.Int32" Scope="User">
<Value Profile="(Default)">50</Value>
</Setting>
+ <Setting Name="LastExportFolder" Type="System.String" Scope="User">
+ <Value Profile="(Default)" />
+ </Setting>
+ <Setting Name="ExportFilterIndex" Type="System.Int32" Scope="User">
+ <Value Profile="(Default)">0</Value>
+ </Setting>
</Settings>
</SettingsFile>
diff --git a/WaveDude.WPF/Rendering/ProbeGraphPainter.cs b/WaveDude.WPF/Rendering/ProbeGraphPainter.cs
new file mode 100644
index 0000000..8329923
--- /dev/null
+++ b/WaveDude.WPF/Rendering/ProbeGraphPainter.cs
@@ -0,0 +1,191 @@
+using System.Collections.Immutable;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using WaveDude.Export;
+using WaveDude.Model;
+using WaveDude.Probes;
+using WaveDude.Runs;
+using WaveDude.WPF.Controls;
+
+namespace WaveDude.WPF.Rendering;
+
+/// <summary>
+/// Draws the probes into exported frames at canvas scale: the markers in the author's style (the strokes by
+/// <see cref="ProbeMarkers"/> on the pixels, the numbers as bold Segoe UI with a drop shadow rendered here)
+/// and the graph boxes as the preview shows them (for every active probe of a layer, the box where the probe
+/// says, with the run's recording as it stood at the frame, <see cref="ProbeGraphData.At"/>). Built on the UI
+/// thread from the project (the probes are cloned, so edits during the export do not move anything) and the
+/// run; <see cref="For"/> gives the export job a decoration that runs on the export's own thread (a
+/// single-threaded apartment), where each box and label is rendered into a <see cref="RenderTargetBitmap"/>
+/// of its size and blended over the frame's pixels. Probes are numbered in project order, active ones only,
+/// as the author numbered his run list.
+/// </summary>
+public sealed class ProbeGraphPainter
+{
+ private readonly (Probe Probe, ProbeTrace? Trace, int Number)[] _items;
+ private readonly bool _graphs;
+ private readonly bool _markers;
+ private static readonly Typeface LabelTypeface = new(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal);
+ private static readonly Brush ShadowBrush = Frozen(new SolidColorBrush(Color.FromArgb(220, 0, 0, 0)));
+ private readonly int _every;
+ private readonly int _totalSteps;
+ private readonly int _width;
+ private readonly int _height;
+ private ProbeGraphStyle? _style;
+
+ /// <param name="project">The project whose active probes are drawn.</param>
+ /// <param name="run">The run whose recordings the graphs show; its size is the frame size.</param>
+ /// <param name="graphs">Draw the graph boxes.</param>
+ /// <param name="markers">Draw the markers.</param>
+ public ProbeGraphPainter(Project project, SimulationRun run, bool graphs, bool markers)
+ {
+ _graphs = graphs;
+ _markers = markers;
+ _items = [.. project.Probes.Where(probe => probe.Active).Select((probe, i) => (probe.Clone(), TraceOf(run.Spec.Probes, run.Traces, probe), i + 1))];
+ _every = run.Spec.VisualizeEvery;
+ _totalSteps = Math.Max(1, run.Spec.Steps);
+ _width = run.Spec.Width;
+ _height = run.Spec.Height;
+ }
+
+ /// <summary>The decoration for a layer: null when nothing is to be drawn or no active probe sits on it.</summary>
+ public Action<int, Memory<int>>? For(ProbeLayer layer) =>
+ (_graphs || _markers) && _items.Any(item => item.Probe.Layer == layer) ? (frame, pixels) => Paint(layer, frame, pixels) : null;
+
+ /// <summary>Draws the layer's markers, then its boxes, over one frame. Export thread.</summary>
+ private void Paint(ProbeLayer layer, int frame, Memory<int> pixels)
+ {
+ if (_markers)
+ {
+ foreach ((Probe probe, _, int number) in _items)
+ {
+ if (probe.Layer == layer)
+ {
+ ProbeMarkers.DrawStrokes(pixels.Span, _width, _height, probe);
+ }
+ }
+ foreach ((Probe probe, _, int number) in _items)
+ {
+ if (probe.Layer != layer)
+ {
+ continue;
+ }
+ bool line = probe.Kind == ProbeKind.Line;
+ DrawLabel(pixels.Span, ProbeMarkers.Label(number, line, endB: false), probe.AX, probe.AY);
+ if (line)
+ {
+ DrawLabel(pixels.Span, ProbeMarkers.Label(number, line, endB: true), probe.BX, probe.BY);
+ }
+ }
+ }
+ if (!_graphs)
+ {
+ return;
+ }
+ _style ??= ProbeGraphDrawing.MakeStyle(1.0);
+ foreach ((Probe probe, ProbeTrace? trace, _) in _items)
+ {
+ if (probe.Layer != layer)
+ {
+ continue;
+ }
+ BoxRect box = ProbeGraph.BoxInCanvas(probe, _width, _height);
+ if (box.Width < 1 || box.Height < 1)
+ {
+ continue;
+ }
+ ProbeGraphData data = trace != null ? ProbeGraphData.At(trace, frame * _every, frame) : default;
+ ProbeGraphLayout layout = ProbeGraph.Layout(probe, data, _totalSteps, box.Width, box.Height, _style, CultureInfo.CurrentCulture);
+ if (!layout.IsVisible)
+ {
+ continue;
+ }
+ var visual = new DrawingVisual();
+ using (DrawingContext dc = visual.RenderOpen())
+ {
+ ProbeGraphDrawing.DrawBox(dc, layout, null, 1.0);
+ }
+ var bitmap = new RenderTargetBitmap(box.Width, box.Height, 96, 96, PixelFormats.Pbgra32);
+ bitmap.Render(visual);
+ var buffer = new byte[box.Width * box.Height * 4];
+ bitmap.CopyPixels(buffer, box.Width * 4, 0);
+ Blend(buffer, box, pixels.Span);
+ }
+ }
+
+ /// <summary>A marker's label above and to the right of the cross at (<paramref name="x"/>, <paramref name="y"/>): bold, white over a shadow two pixels in, like the author's.</summary>
+ private void DrawLabel(Span<int> frame, string text, int x, int y)
+ {
+ double fontPx = ProbeMarkers.FontSize(_height);
+ var shadow = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, LabelTypeface, fontPx, ShadowBrush, 1.0);
+ var white = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, LabelTypeface, fontPx, Brushes.White, 1.0);
+ int boxWidth = (int)Math.Ceiling(white.Width) + 4;
+ int boxHeight = (int)Math.Ceiling(white.Height) + 4;
+ var visual = new DrawingVisual();
+ using (DrawingContext dc = visual.RenderOpen())
+ {
+ dc.DrawText(shadow, new Point(3, 3));
+ dc.DrawText(white, new Point(2, 2));
+ }
+ var bitmap = new RenderTargetBitmap(boxWidth, boxHeight, 96, 96, PixelFormats.Pbgra32);
+ bitmap.Render(visual);
+ var buffer = new byte[boxWidth * boxHeight * 4];
+ bitmap.CopyPixels(buffer, boxWidth * 4, 0);
+ (int left, int top) = ProbeMarkers.LabelOrigin(x, y, _height);
+ Blend(buffer, new BoxRect(left, top, boxWidth, boxHeight), frame);
+ }
+
+ private static Brush Frozen(Brush brush)
+ {
+ brush.Freeze();
+ return brush;
+ }
+
+ /// <summary>Composites a premultiplied BGRA box over the frame at the box's position, clipped to the frame.</summary>
+ private void Blend(byte[] box, BoxRect rect, Span<int> frame)
+ {
+ for (int y = 0; y < rect.Height; y++)
+ {
+ int fy = rect.Y + y;
+ if (fy < 0 || fy >= _height)
+ {
+ continue;
+ }
+ for (int x = 0; x < rect.Width; x++)
+ {
+ int fx = rect.X + x;
+ if (fx < 0 || fx >= _width)
+ {
+ continue;
+ }
+ int i = (y * rect.Width + x) * 4;
+ int a = box[i + 3];
+ if (a == 0)
+ {
+ continue;
+ }
+ int argb = frame[fy * _width + fx];
+ int inverse = 255 - a;
+ int b = box[i] + ((argb & 0xFF) * inverse + 127) / 255;
+ int g = box[i + 1] + (((argb >> 8) & 0xFF) * inverse + 127) / 255;
+ int r = box[i + 2] + (((argb >> 16) & 0xFF) * inverse + 127) / 255;
+ frame[fy * _width + fx] = unchecked((int)0xFF000000) | (Math.Min(255, r) << 16) | (Math.Min(255, g) << 8) | Math.Min(255, b);
+ }
+ }
+ }
+
+ /// <summary>The trace of the model probe among a spec's probes (matched by <see cref="ProbeSpec.Origin"/>), or null when it was not recorded.</summary>
+ private static ProbeTrace? TraceOf(ImmutableArray<ProbeSpec> specs, ProbeTrace[] traces, Probe probe)
+ {
+ for (int i = 0; i < specs.Length && i < traces.Length; i++)
+ {
+ if (ReferenceEquals(specs[i].Origin, probe))
+ {
+ return traces[i];
+ }
+ }
+ return null;
+ }
+}
diff --git a/WaveDude.WPF/Rendering/WicJpeg.cs b/WaveDude.WPF/Rendering/WicJpeg.cs
new file mode 100644
index 0000000..d5864bf
--- /dev/null
+++ b/WaveDude.WPF/Rendering/WicJpeg.cs
@@ -0,0 +1,44 @@
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using WaveDude.Export;
+
+namespace WaveDude.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/WaveDude.WPF/Strings/Strings.DE.xaml b/WaveDude.WPF/Strings/Strings.DE.xaml
index b4d43ff..4a38590 100644
--- a/WaveDude.WPF/Strings/Strings.DE.xaml
+++ b/WaveDude.WPF/Strings/Strings.DE.xaml
@@ -13,6 +13,13 @@
<s:String x:Key="MenuFileSave">_Speichern</s:String>
<s:String x:Key="MenuFileSaveAs">Speichern _unter...</s:String>
<s:String x:Key="MenuFileClose">Projekt s_chließen</s:String>
+ <s:String x:Key="MenuFileExport">_Exportieren</s:String>
+ <s:String x:Key="MenuFileExportField">_Feld exportieren...</s:String>
+ <s:String x:Key="MenuFileExportIntensity">_Intensität exportieren...</s:String>
+ <s:String x:Key="MenuFileExportBoth">_Beides exportieren...</s:String>
+ <s:String x:Key="MenuFileExportFieldFrame">Feld-Ein_zelbild exportieren...</s:String>
+ <s:String x:Key="MenuFileExportIntensityFrame">Intensitäts-Einzelbild e_xportieren...</s:String>
+ <s:String x:Key="MenuExportThisFrame">_Dieses Bild exportieren...</s:String>
<s:String x:Key="MenuFileExit">_Beenden</s:String>
<s:String x:Key="MenuView">_Ansicht</s:String>
<s:String x:Key="MenuViewPanes">_Fenster</s:String>
@@ -111,6 +118,23 @@
<s:String x:Key="RunErrorNoImage">Die Szene verwendet ein Bild, aber es ist keine Bilddatei angegeben.</s:String>
<s:String x:Key="RunErrorUnsavedImagePath">Zuerst das Projekt speichern, damit das Szenenbild relativ dazu gefunden wird.</s:String>
<s:String x:Key="Ready">Bereit</s:String>
+
+ <!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->
+ <s:String x:Key="ExportDialogFilter">PNG-Bildfolge (*.png)|*.png|JPEG-Bildfolge (*.jpg)|*.jpg|MPEG-1-Video (*.mpg)|*.mpg|AVI-Video, unkomprimiert (*.avi)|*.avi|MP4-Video, H.264 (*.mp4)|*.mp4</s:String>
+ <s:String x:Key="ExportDialogTitleField">Feld exportieren</s:String>
+ <s:String x:Key="ExportDialogTitleIntensity">Intensität exportieren</s:String>
+ <s:String x:Key="ExportDialogTitleBoth">Feld und Intensität exportieren</s:String>
+ <s:String x:Key="ExportDialogFilterStill">PNG-Bild (*.png)|*.png|JPEG-Bild (*.jpg)|*.jpg</s:String>
+ <s:String x:Key="ExportDialogTitleFrame">Bild exportieren</s:String>
+ <s:String x:Key="ExportFolderExistsFormat">Der Ordner {0} existiert und enthält Dateien. Ersetzen?</s:String>
+ <s:String x:Key="ExportError">Der Export ist fehlgeschlagen.</s:String>
+ <s:String x:Key="ExportStatusFormat">Exportiere {0} / {1} Bilder</s:String>
+ <s:String x:Key="ExportStatusWaiting">Export: wartet auf den Lauf</s:String>
+ <s:String x:Key="StatusComputingFormat">Berechne Bild {0}</s:String>
+ <s:String x:Key="PreviewNotComputed">Nicht berechnet: dieses Bild allein würde zu lange dauern. Starten Sie die Simulation (F5), um es zu erhalten.</s:String>
+ <s:String x:Key="TipExportCancel">Export abbrechen (Esc)</s:String>
+ <s:String x:Key="Untitled">Unbenannt</s:String>
+ <s:String x:Key="SaveChangesFormat">Änderungen an {0} speichern?</s:String>
<s:String x:Key="NoSelection">Keine Auswahl</s:String>
<s:String x:Key="TreeProject">Projekt</s:String>
@@ -129,7 +153,7 @@
<s:String x:Key="SectionField">Feld</s:String>
<s:String x:Key="SectionIntensity">Intensität</s:String>
<s:String x:Key="SectionVideo">Videoexport</s:String>
- <s:String x:Key="SectionExportRange">Exportbereich</s:String>
+ <s:String x:Key="SectionExportRange">Export</s:String>
<s:String x:Key="SectionPosition">Position</s:String>
<s:String x:Key="SectionWave">Welle</s:String>
<s:String x:Key="SectionTiming">Zeitverhalten</s:String>
@@ -179,6 +203,10 @@
<s:String x:Key="Hint.Display.ExportFrom">Erster Simulationsschritt des exportierten Bereichs; 0 ist der Anfang des Laufs.</s:String>
<s:String x:Key="Label.Display.ExportTo">Bis Schritt</s:String>
<s:String x:Key="Hint.Display.ExportTo">Letzter Simulationsschritt des exportierten Bereichs; 0 bedeutet das Ende des Laufs.</s:String>
+ <s:String x:Key="Label.Display.ProbeGraphsInExport">Sondengraphen im Export</s:String>
+ <s:String x:Key="Hint.Display.ProbeGraphsInExport">Die Graphkästen der Sonden in exportierte Bilder und Videos zeichnen.</s:String>
+ <s:String x:Key="Label.Display.ProbeMarkersInExport">Sondenmarkierungen im Export</s:String>
+ <s:String x:Key="Hint.Display.ProbeMarkersInExport">Die Positionen der Sonden (Kreuze, die Linie einer Liniensonde, die Nummer) in exportierte Bilder und Videos zeichnen.</s:String>
<s:String x:Key="Label.DisplayLayer.ColorScheme">Farbschema</s:String>
<s:String x:Key="Hint.DisplayLayer.ColorScheme">Name des Farbschemas, das auf die Werte abgebildet wird.</s:String>
<s:String x:Key="Label.DisplayLayer.Brightness">Helligkeit</s:String>
@@ -187,8 +215,6 @@
<s:String x:Key="Hint.DisplayLayer.BlackLevel">Versatz vor der Farbzuordnung; Werte darunter oder gleich erhalten die erste Farbe.</s:String>
<s:String x:Key="Label.DisplayLayer.Preview">Vorschau</s:String>
<s:String x:Key="Hint.DisplayLayer.Preview">Diese Ausgabe in der Live-Vorschau zeigen.</s:String>
- <s:String x:Key="Label.DisplayLayer.Export">Exportieren</s:String>
- <s:String x:Key="Hint.DisplayLayer.Export">Die Bilder dieser Ausgabe in eine Videodatei schreiben.</s:String>
<s:String x:Key="Label.DisplayLayer.Overlay">Umriss in der Vorschau</s:String>
<s:String x:Key="Hint.DisplayLayer.Overlay">Den Leuchtkanten-Umriss des Szenenbilds in der Vorschau über diese Ausgabe legen.</s:String>
<s:String x:Key="Label.DisplayLayer.OverlayGain">Umrisshelligkeit</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xaml
index baaf386..1b85fe4 100644
--- a/WaveDude.WPF/Strings/Strings.EN.xaml
+++ b/WaveDude.WPF/Strings/Strings.EN.xaml
@@ -13,6 +13,13 @@
<s:String x:Key="MenuFileSave">_Save</s:String>
<s:String x:Key="MenuFileSaveAs">Save _As...</s:String>
<s:String x:Key="MenuFileClose">_Close Project</s:String>
+ <s:String x:Key="MenuFileExport">_Export</s:String>
+ <s:String x:Key="MenuFileExportField">Export _field...</s:String>
+ <s:String x:Key="MenuFileExportIntensity">Export _intensity...</s:String>
+ <s:String x:Key="MenuFileExportBoth">Export _both...</s:String>
+ <s:String x:Key="MenuFileExportFieldFrame">Export field f_rame...</s:String>
+ <s:String x:Key="MenuFileExportIntensityFrame">Export intensity fra_me...</s:String>
+ <s:String x:Key="MenuExportThisFrame">Export _this frame...</s:String>
<s:String x:Key="MenuFileExit">E_xit</s:String>
<s:String x:Key="MenuView">_View</s:String>
<s:String x:Key="MenuViewPanes">_Panes</s:String>
@@ -111,6 +118,23 @@
<s:String x:Key="RunErrorNoImage">The scene uses an image, but no image file is set.</s:String>
<s:String x:Key="RunErrorUnsavedImagePath">Save the project first, so the scene image can be found relative to it.</s:String>
<s:String x:Key="Ready">Ready</s:String>
+
+ <!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->
+ <s:String x:Key="ExportDialogFilter">PNG image sequence (*.png)|*.png|JPEG image sequence (*.jpg)|*.jpg|MPEG-1 video (*.mpg)|*.mpg|AVI video, uncompressed (*.avi)|*.avi|MP4 video, H.264 (*.mp4)|*.mp4</s:String>
+ <s:String x:Key="ExportDialogTitleField">Export the field</s:String>
+ <s:String x:Key="ExportDialogTitleIntensity">Export the intensity</s:String>
+ <s:String x:Key="ExportDialogTitleBoth">Export the field and the intensity</s:String>
+ <s:String x:Key="ExportDialogFilterStill">PNG image (*.png)|*.png|JPEG image (*.jpg)|*.jpg</s:String>
+ <s:String x:Key="ExportDialogTitleFrame">Export the frame</s:String>
+ <s:String x:Key="ExportFolderExistsFormat">The folder {0} exists and holds files. Replace them?</s:String>
+ <s:String x:Key="ExportError">The export failed.</s:String>
+ <s:String x:Key="ExportStatusFormat">Exporting {0} / {1} frames</s:String>
+ <s:String x:Key="ExportStatusWaiting">Export: waiting for the run</s:String>
+ <s:String x:Key="StatusComputingFormat">Computing frame {0}</s:String>
+ <s:String x:Key="PreviewNotComputed">Not computed: this frame would take too long on its own. Run the simulation (F5) to get it.</s:String>
+ <s:String x:Key="TipExportCancel">Cancel the export (Esc)</s:String>
+ <s:String x:Key="Untitled">Untitled</s:String>
+ <s:String x:Key="SaveChangesFormat">Save the changes to {0}?</s:String>
<s:String x:Key="NoSelection">No selection</s:String>
<s:String x:Key="TreeProject">Project</s:String>
@@ -129,7 +153,7 @@
<s:String x:Key="SectionField">Field</s:String>
<s:String x:Key="SectionIntensity">Intensity</s:String>
<s:String x:Key="SectionVideo">Video export</s:String>
- <s:String x:Key="SectionExportRange">Export range</s:String>
+ <s:String x:Key="SectionExportRange">Export</s:String>
<s:String x:Key="SectionPosition">Position</s:String>
<s:String x:Key="SectionWave">Wave</s:String>
<s:String x:Key="SectionTiming">Timing</s:String>
@@ -179,6 +203,10 @@
<s:String x:Key="Hint.Display.ExportFrom">First simulation step of the exported range; 0 is the start of the run.</s:String>
<s:String x:Key="Label.Display.ExportTo">To step</s:String>
<s:String x:Key="Hint.Display.ExportTo">Last simulation step of the exported range; 0 means the end of the run.</s:String>
+ <s:String x:Key="Label.Display.ProbeGraphsInExport">Probe graphs in the export</s:String>
+ <s:String x:Key="Hint.Display.ProbeGraphsInExport">Draw the probes' graph boxes over exported frames and videos.</s:String>
+ <s:String x:Key="Label.Display.ProbeMarkersInExport">Probe markers in the export</s:String>
+ <s:String x:Key="Hint.Display.ProbeMarkersInExport">Draw the probes' positions (crosses, the line of a line probe, the number) over exported frames and videos.</s:String>
<s:String x:Key="Label.DisplayLayer.ColorScheme">Colour scheme</s:String>
<s:String x:Key="Hint.DisplayLayer.ColorScheme">Name of the colour scheme mapped onto the values.</s:String>
<s:String x:Key="Label.DisplayLayer.Brightness">Brightness</s:String>
@@ -187,8 +215,6 @@
<s:String x:Key="Hint.DisplayLayer.BlackLevel">Offset applied before the colour lookup; values at or below it map to the first colour.</s:String>
<s:String x:Key="Label.DisplayLayer.Preview">Preview</s:String>
<s:String x:Key="Hint.DisplayLayer.Preview">Show this output in the live preview.</s:String>
- <s:String x:Key="Label.DisplayLayer.Export">Export</s:String>
- <s:String x:Key="Hint.DisplayLayer.Export">Write this output's frames to a video file.</s:String>
<s:String x:Key="Label.DisplayLayer.Overlay">Outline in the preview</s:String>
<s:String x:Key="Hint.DisplayLayer.Overlay">Lay the scene image's glowing-edges outline over this output in the preview.</s:String>
<s:String x:Key="Label.DisplayLayer.OverlayGain">Outline brightness</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.FR.xaml b/WaveDude.WPF/Strings/Strings.FR.xaml
index 74cd80d..27f5ed1 100644
--- a/WaveDude.WPF/Strings/Strings.FR.xaml
+++ b/WaveDude.WPF/Strings/Strings.FR.xaml
@@ -13,6 +13,13 @@
<s:String x:Key="MenuFileSave">_Enregistrer</s:String>
<s:String x:Key="MenuFileSaveAs">Enregistrer _sous...</s:String>
<s:String x:Key="MenuFileClose">_Fermer le projet</s:String>
+ <s:String x:Key="MenuFileExport">E_xporter</s:String>
+ <s:String x:Key="MenuFileExportField">Exporter le _champ...</s:String>
+ <s:String x:Key="MenuFileExportIntensity">Exporter l'_intensité...</s:String>
+ <s:String x:Key="MenuFileExportBoth">Exporter les _deux...</s:String>
+ <s:String x:Key="MenuFileExportFieldFrame">Exporter l'i_mage du champ...</s:String>
+ <s:String x:Key="MenuFileExportIntensityFrame">Exporter l'image de l'intensi_té...</s:String>
+ <s:String x:Key="MenuExportThisFrame">Exporter _cette image...</s:String>
<s:String x:Key="MenuFileExit">_Quitter</s:String>
<s:String x:Key="MenuView">_Affichage</s:String>
<s:String x:Key="MenuViewPanes">_Panneaux</s:String>
@@ -111,6 +118,23 @@
<s:String x:Key="RunErrorNoImage">La scène utilise une image, mais aucun fichier image n'est défini.</s:String>
<s:String x:Key="RunErrorUnsavedImagePath">Enregistrez d'abord le projet, pour que l'image de la scène soit trouvée relativement à lui.</s:String>
<s:String x:Key="Ready">Prêt</s:String>
+
+ <!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->
+ <s:String x:Key="ExportDialogFilter">Séquence d'images PNG (*.png)|*.png|Séquence d'images JPEG (*.jpg)|*.jpg|Vidéo MPEG-1 (*.mpg)|*.mpg|Vidéo AVI non compressée (*.avi)|*.avi|Vidéo MP4, H.264 (*.mp4)|*.mp4</s:String>
+ <s:String x:Key="ExportDialogTitleField">Exporter le champ</s:String>
+ <s:String x:Key="ExportDialogTitleIntensity">Exporter l'intensité</s:String>
+ <s:String x:Key="ExportDialogTitleBoth">Exporter le champ et l'intensité</s:String>
+ <s:String x:Key="ExportDialogFilterStill">Image PNG (*.png)|*.png|Image JPEG (*.jpg)|*.jpg</s:String>
+ <s:String x:Key="ExportDialogTitleFrame">Exporter l'image</s:String>
+ <s:String x:Key="ExportFolderExistsFormat">Le dossier {0} existe et contient des fichiers. Les remplacer ?</s:String>
+ <s:String x:Key="ExportError">L'export a échoué.</s:String>
+ <s:String x:Key="ExportStatusFormat">Export : {0} / {1} images</s:String>
+ <s:String x:Key="ExportStatusWaiting">Export : en attente de l'exécution</s:String>
+ <s:String x:Key="StatusComputingFormat">Calcul de l'image {0}</s:String>
+ <s:String x:Key="PreviewNotComputed">Non calculée : cette image seule prendrait trop de temps. Lancez la simulation (F5) pour l'obtenir.</s:String>
+ <s:String x:Key="TipExportCancel">Annuler l'export (Échap)</s:String>
+ <s:String x:Key="Untitled">Sans titre</s:String>
+ <s:String x:Key="SaveChangesFormat">Enregistrer les modifications de {0} ?</s:String>
<s:String x:Key="NoSelection">Aucune sélection</s:String>
<s:String x:Key="TreeProject">Projet</s:String>
@@ -129,7 +153,7 @@
<s:String x:Key="SectionField">Champ</s:String>
<s:String x:Key="SectionIntensity">Intensité</s:String>
<s:String x:Key="SectionVideo">Export vidéo</s:String>
- <s:String x:Key="SectionExportRange">Plage d'export</s:String>
+ <s:String x:Key="SectionExportRange">Export</s:String>
<s:String x:Key="SectionPosition">Position</s:String>
<s:String x:Key="SectionWave">Onde</s:String>
<s:String x:Key="SectionTiming">Chronologie</s:String>
@@ -179,6 +203,10 @@
<s:String x:Key="Hint.Display.ExportFrom">Premier pas de simulation de la plage exportée ; 0 est le début de l'exécution.</s:String>
<s:String x:Key="Label.Display.ExportTo">Au pas</s:String>
<s:String x:Key="Hint.Display.ExportTo">Dernier pas de simulation de la plage exportée ; 0 signifie la fin de l'exécution.</s:String>
+ <s:String x:Key="Label.Display.ProbeGraphsInExport">Graphes des sondes dans l'export</s:String>
+ <s:String x:Key="Hint.Display.ProbeGraphsInExport">Dessiner les cadres de graphe des sondes sur les images et vidéos exportées.</s:String>
+ <s:String x:Key="Label.Display.ProbeMarkersInExport">Marqueurs des sondes dans l'export</s:String>
+ <s:String x:Key="Hint.Display.ProbeMarkersInExport">Dessiner les positions des sondes (croix, la ligne d'une sonde linéaire, le numéro) sur les images et vidéos exportées.</s:String>
<s:String x:Key="Label.DisplayLayer.ColorScheme">Palette de couleurs</s:String>
<s:String x:Key="Hint.DisplayLayer.ColorScheme">Nom de la palette appliquée aux valeurs.</s:String>
<s:String x:Key="Label.DisplayLayer.Brightness">Luminosité</s:String>
@@ -187,8 +215,6 @@
<s:String x:Key="Hint.DisplayLayer.BlackLevel">Décalage appliqué avant la correspondance des couleurs ; les valeurs inférieures ou égales prennent la première couleur.</s:String>
<s:String x:Key="Label.DisplayLayer.Preview">Aperçu</s:String>
<s:String x:Key="Hint.DisplayLayer.Preview">Afficher cette sortie dans l'aperçu en direct.</s:String>
- <s:String x:Key="Label.DisplayLayer.Export">Exporter</s:String>
- <s:String x:Key="Hint.DisplayLayer.Export">Écrire les images de cette sortie dans un fichier vidéo.</s:String>
<s:String x:Key="Label.DisplayLayer.Overlay">Contour dans l'aperçu</s:String>
<s:String x:Key="Hint.DisplayLayer.Overlay">Superposer le contour « bords lumineux » de l'image de scène à cette sortie dans l'aperçu.</s:String>
<s:String x:Key="Label.DisplayLayer.OverlayGain">Luminosité du contour</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.NL.xaml b/WaveDude.WPF/Strings/Strings.NL.xaml
index d29b153..2915fd1 100644
--- a/WaveDude.WPF/Strings/Strings.NL.xaml
+++ b/WaveDude.WPF/Strings/Strings.NL.xaml
@@ -13,6 +13,13 @@
<s:String x:Key="MenuFileSave">Op_slaan</s:String>
<s:String x:Key="MenuFileSaveAs">Opslaan _als...</s:String>
<s:String x:Key="MenuFileClose">Project s_luiten</s:String>
+ <s:String x:Key="MenuFileExport">_Exporteren</s:String>
+ <s:String x:Key="MenuFileExportField">_Veld exporteren...</s:String>
+ <s:String x:Key="MenuFileExportIntensity">_Intensiteit exporteren...</s:String>
+ <s:String x:Key="MenuFileExportBoth">_Beide exporteren...</s:String>
+ <s:String x:Key="MenuFileExportFieldFrame">Veld_beeld exporteren...</s:String>
+ <s:String x:Key="MenuFileExportIntensityFrame">Intensiteitsbeel_d exporteren...</s:String>
+ <s:String x:Key="MenuExportThisFrame">_Dit beeld exporteren...</s:String>
<s:String x:Key="MenuFileExit">A_fsluiten</s:String>
<s:String x:Key="MenuView">Beel_d</s:String>
<s:String x:Key="MenuViewPanes">_Panelen</s:String>
@@ -111,6 +118,23 @@
<s:String x:Key="RunErrorNoImage">De scène gebruikt een afbeelding, maar er is geen afbeeldingsbestand ingesteld.</s:String>
<s:String x:Key="RunErrorUnsavedImagePath">Sla het project eerst op, zodat de scèneafbeelding relatief daaraan gevonden wordt.</s:String>
<s:String x:Key="Ready">Gereed</s:String>
+
+ <!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->
+ <s:String x:Key="ExportDialogFilter">PNG-beeldreeks (*.png)|*.png|JPEG-beeldreeks (*.jpg)|*.jpg|MPEG-1-video (*.mpg)|*.mpg|AVI-video, ongecomprimeerd (*.avi)|*.avi|MP4-video, H.264 (*.mp4)|*.mp4</s:String>
+ <s:String x:Key="ExportDialogTitleField">Veld exporteren</s:String>
+ <s:String x:Key="ExportDialogTitleIntensity">Intensiteit exporteren</s:String>
+ <s:String x:Key="ExportDialogTitleBoth">Veld en intensiteit exporteren</s:String>
+ <s:String x:Key="ExportDialogFilterStill">PNG-beeld (*.png)|*.png|JPEG-beeld (*.jpg)|*.jpg</s:String>
+ <s:String x:Key="ExportDialogTitleFrame">Beeld exporteren</s:String>
+ <s:String x:Key="ExportFolderExistsFormat">De map {0} bestaat en bevat bestanden. Vervangen?</s:String>
+ <s:String x:Key="ExportError">De export is mislukt.</s:String>
+ <s:String x:Key="ExportStatusFormat">Exporteren: {0} / {1} beelden</s:String>
+ <s:String x:Key="ExportStatusWaiting">Export: wacht op de run</s:String>
+ <s:String x:Key="StatusComputingFormat">Beeld {0} wordt berekend</s:String>
+ <s:String x:Key="PreviewNotComputed">Niet berekend: dit beeld alleen zou te lang duren. Start de simulatie (F5) om het te krijgen.</s:String>
+ <s:String x:Key="TipExportCancel">Export annuleren (Esc)</s:String>
+ <s:String x:Key="Untitled">Naamloos</s:String>
+ <s:String x:Key="SaveChangesFormat">Wijzigingen in {0} opslaan?</s:String>
<s:String x:Key="NoSelection">Geen selectie</s:String>
<s:String x:Key="TreeProject">Project</s:String>
@@ -129,7 +153,7 @@
<s:String x:Key="SectionField">Veld</s:String>
<s:String x:Key="SectionIntensity">Intensiteit</s:String>
<s:String x:Key="SectionVideo">Video-export</s:String>
- <s:String x:Key="SectionExportRange">Exportbereik</s:String>
+ <s:String x:Key="SectionExportRange">Export</s:String>
<s:String x:Key="SectionPosition">Positie</s:String>
<s:String x:Key="SectionWave">Golf</s:String>
<s:String x:Key="SectionTiming">Timing</s:String>
@@ -179,6 +203,10 @@
<s:String x:Key="Hint.Display.ExportFrom">Eerste simulatiestap van het geëxporteerde bereik; 0 is het begin van de run.</s:String>
<s:String x:Key="Label.Display.ExportTo">Tot stap</s:String>
<s:String x:Key="Hint.Display.ExportTo">Laatste simulatiestap van het geëxporteerde bereik; 0 betekent het einde van de run.</s:String>
+ <s:String x:Key="Label.Display.ProbeGraphsInExport">Sondegrafieken in de export</s:String>
+ <s:String x:Key="Hint.Display.ProbeGraphsInExport">De grafiekvakken van de sondes over geëxporteerde beelden en video's tekenen.</s:String>
+ <s:String x:Key="Label.Display.ProbeMarkersInExport">Sondemarkeringen in de export</s:String>
+ <s:String x:Key="Hint.Display.ProbeMarkersInExport">De posities van de sondes (kruisen, de lijn van een lijnsonde, het nummer) over geëxporteerde beelden en video's tekenen.</s:String>
<s:String x:Key="Label.DisplayLayer.ColorScheme">Kleurenschema</s:String>
<s:String x:Key="Hint.DisplayLayer.ColorScheme">Naam van het kleurenschema dat op de waarden wordt toegepast.</s:String>
<s:String x:Key="Label.DisplayLayer.Brightness">Helderheid</s:String>
@@ -187,8 +215,6 @@
<s:String x:Key="Hint.DisplayLayer.BlackLevel">Verschuiving vóór de kleurtoewijzing; waarden op of onder dit niveau krijgen de eerste kleur.</s:String>
<s:String x:Key="Label.DisplayLayer.Preview">Voorbeeld</s:String>
<s:String x:Key="Hint.DisplayLayer.Preview">Deze uitvoer in het live-voorbeeld tonen.</s:String>
- <s:String x:Key="Label.DisplayLayer.Export">Exporteren</s:String>
- <s:String x:Key="Hint.DisplayLayer.Export">De beelden van deze uitvoer naar een videobestand schrijven.</s:String>
<s:String x:Key="Label.DisplayLayer.Overlay">Omtrek in het voorbeeld</s:String>
<s:String x:Key="Hint.DisplayLayer.Overlay">De gloeiende-randen-omtrek van de scèneafbeelding in het voorbeeld over deze uitvoer leggen.</s:String>
<s:String x:Key="Label.DisplayLayer.OverlayGain">Omtrekhelderheid</s:String>
diff --git a/WaveDude.WPF/Views/DisplayLayerView.xaml b/WaveDude.WPF/Views/DisplayLayerView.xaml
index e619159..47dd38c 100644
--- a/WaveDude.WPF/Views/DisplayLayerView.xaml
+++ b/WaveDude.WPF/Views/DisplayLayerView.xaml
@@ -29,7 +29,5 @@
<controls:NumberBox Text="{Binding OverlayGain}" Minimum="0" Maximum="5" Increment="0.05" ToolTip="{meta:Hint model:DisplayLayer.OverlayGain}" />
<CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:DisplayLayer.OverlayInExport}"
IsChecked="{Binding OverlayInExport}" ToolTip="{meta:Hint model:DisplayLayer.OverlayInExport}" />
- <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:DisplayLayer.Export}"
- IsChecked="{Binding Export}" ToolTip="{meta:Hint model:DisplayLayer.Export}" />
</controls:FormPanel>
</UserControl>
diff --git a/WaveDude.WPF/Views/DisplayView.xaml b/WaveDude.WPF/Views/DisplayView.xaml
index af61594..d0c338f 100644
--- a/WaveDude.WPF/Views/DisplayView.xaml
+++ b/WaveDude.WPF/Views/DisplayView.xaml
@@ -21,6 +21,11 @@
<TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Display.ExportTo}" />
<controls:NumberBox Text="{Binding ExportTo}" Minimum="0" ToolTip="{meta:Hint model:Display.ExportTo}" />
+
+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Display.ProbeGraphsInExport}"
+ IsChecked="{Binding ProbeGraphsInExport}" ToolTip="{meta:Hint model:Display.ProbeGraphsInExport}" />
+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Display.ProbeMarkersInExport}"
+ IsChecked="{Binding ProbeMarkersInExport}" ToolTip="{meta:Hint model:Display.ProbeMarkersInExport}" />
</controls:FormPanel>
<Label Style="{StaticResource FormSection}" Content="{DynamicResource SectionVideo}" />
diff --git a/WaveDude/Export/AviWriter.cs b/WaveDude/Export/AviWriter.cs
new file mode 100644
index 0000000..42594b1
--- /dev/null
+++ b/WaveDude/Export/AviWriter.cs
@@ -0,0 +1,399 @@
+using System.Buffers.Binary;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes an uncompressed AVI (24-bit BGR, bottom-up rows padded to four bytes, one <c>00db</c> chunk per
+/// frame) with the OpenDML extensions, so the file may be as large as the disk allows: the frames are split
+/// over RIFF segments of at most <see cref="SegmentLimit"/> bytes (the first <c>AVI </c>, the rest
+/// <c>AVIX</c>), each segment ends with a standard index (<c>ix00</c>) and the header carries the super
+/// index (<c>indx</c>) pointing at them, plus the legacy <c>idx1</c> for the first segment and the total
+/// frame count in <c>dmlh</c>. Every frame has the same size, so the layout is arithmetic; the header is
+/// written at <see cref="Close"/> with the counts that were reached, so a cancelled export is still a
+/// valid file. In-house, no dependencies. One thread at a time.
+/// </summary>
+/// <remarks>
+/// Layout: <c>RIFF 'AVI ' [LIST hdrl: avih, LIST strl: strh strf indx] [LIST odml: dmlh] [LIST movi: 00db… ix00] idx1</c>,
+/// then per further segment <c>RIFF 'AVIX' [LIST movi: 00db… ix00]</c>. The first segment's RIFF head and
+/// the hdrl/odml lists occupy the first <see cref="_headerBytes"/> bytes, reserved at open and filled at close.
+/// </remarks>
+public sealed class AviWriter : IFrameSink
+{
+ /// <summary>Largest RIFF segment: 1 GB, the size every player handles for the first segment.</summary>
+ public const long DefaultSegmentLimit = 1L << 30;
+
+ private const uint AvifHasIndex = 0x10;
+ private const uint AvifTrustChunkType = 0x800;
+ private const uint AviifKeyframe = 0x10;
+ private const int DmlhSize = 248;
+
+ private readonly FileStream _stream;
+ private readonly int _rowBytes;
+ private readonly int _frameBytes;
+ private readonly int _chunkBytes;
+ private readonly int _headerBytes;
+ private readonly int _firstSegmentFrames;
+ private readonly int _laterSegmentFrames;
+ private readonly int _superEntries;
+ private readonly byte[] _row;
+ private readonly List<Segment> _segments = [];
+ private bool _closed;
+
+ /// <summary>One RIFF segment: where its RIFF head and its movi LIST head are, how many frames it holds, and its index once closed.</summary>
+ private sealed class Segment(long riffStart, long moviStart)
+ {
+ public long RiffStart { get; } = riffStart;
+ public long MoviStart { get; } = moviStart;
+ public int Frames { get; set; }
+ public long End { get; set; }
+ public long IndexPosition { get; set; }
+ }
+
+ /// <param name="path">Output file; an existing file is replaced.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="framesPerSecond">Playback rate.</param>
+ /// <param name="plannedFrames">How many frames will come at most (sizes the super index); more are refused.</param>
+ /// <param name="segmentLimit">Largest RIFF segment in bytes; the default is 1 GB (a harness uses small values to force several segments).</param>
+ public AviWriter(string path, int width, int height, int framesPerSecond, int plannedFrames, long segmentLimit = DefaultSegmentLimit)
+ {
+ Width = width;
+ Height = height;
+ FramesPerSecond = Math.Max(1, framesPerSecond);
+ Output = path;
+ SegmentLimit = segmentLimit;
+ PlannedFrames = Math.Max(1, plannedFrames);
+ _rowBytes = (width * 3 + 3) & ~3;
+ _frameBytes = _rowBytes * height;
+ _chunkBytes = 8 + _frameBytes; // the row padding keeps the chunk even
+ _row = new byte[_rowBytes];
+ // a later segment: RIFF head, LIST movi head, the frames, ix00 (32 + 8 per frame)
+ _laterSegmentFrames = (int)Math.Max(1, (segmentLimit - 12 - 12 - 32) / (_chunkBytes + 8));
+ // the first segment also holds the header (which grows with the number of segments) and idx1 (16 per frame)
+ int entries = 1;
+ for (int pass = 0; pass < 3; pass++)
+ {
+ _headerBytes = HeaderBytes(entries);
+ _firstSegmentFrames = (int)Math.Max(1, (segmentLimit - _headerBytes - 12 - 32 - 8) / (_chunkBytes + 8 + 16));
+ int rest = Math.Max(0, PlannedFrames - _firstSegmentFrames);
+ int needed = 1 + (rest + _laterSegmentFrames - 1) / _laterSegmentFrames;
+ if (needed <= entries)
+ {
+ break;
+ }
+ entries = needed;
+ }
+ _superEntries = entries;
+ _stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 16);
+ _stream.SetLength(_headerBytes);
+ _stream.Position = _headerBytes;
+ BeginSegment();
+ }
+
+ /// <inheritdoc/>
+ public int Width { get; }
+
+ /// <inheritdoc/>
+ public int Height { get; }
+
+ /// <inheritdoc/>
+ public int FrameCount { get; private set; }
+
+ /// <inheritdoc/>
+ public string Output { get; }
+
+ /// <summary>Frames per second written to the headers.</summary>
+ public int FramesPerSecond { get; }
+
+ /// <summary>The frame count the writer was sized for.</summary>
+ public int PlannedFrames { get; }
+
+ /// <summary>Largest RIFF segment in bytes.</summary>
+ public long SegmentLimit { get; }
+
+ /// <summary>Bytes of one frame chunk's data (padded rows × height).</summary>
+ public int FrameBytes => _frameBytes;
+
+ /// <summary>Segments begun so far (at least one).</summary>
+ public int SegmentCount => _segments.Count;
+
+ /// <summary>The size of the file a given frame count produces, header, indexes and padding included.</summary>
+ public long SizeOf(int frames)
+ {
+ int inFirst = Math.Min(frames, _firstSegmentFrames);
+ long size = _headerBytes + 12 + (long)inFirst * _chunkBytes + 32 + 8L * inFirst + 8 + 16L * inFirst;
+ int remaining = frames - inFirst;
+ while (remaining > 0)
+ {
+ int inSegment = Math.Min(remaining, _laterSegmentFrames);
+ size += 12 + 12 + (long)inSegment * _chunkBytes + 32 + 8L * inSegment;
+ remaining -= inSegment;
+ }
+ return size;
+ }
+
+ /// <summary>The size of the file for a frame count, without opening a file.</summary>
+ public static long EstimateSize(int width, int height, int frames, long segmentLimit = DefaultSegmentLimit)
+ {
+ int rowBytes = (width * 3 + 3) & ~3;
+ long chunk = 8L + rowBytes * height;
+ return frames * (chunk + 8 + 16) + 2048 + (frames * chunk / segmentLimit + 1) * 64;
+ }
+
+ /// <inheritdoc/>
+ public void Add(ReadOnlySpan<int> pixels)
+ {
+ if (_closed)
+ {
+ throw new InvalidOperationException("The video file is already closed.");
+ }
+ if (FrameCount >= PlannedFrames)
+ {
+ throw new InvalidOperationException("More frames than the writer was sized for.");
+ }
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the video.", nameof(pixels));
+ }
+ Segment segment = _segments[^1];
+ int limit = _segments.Count == 1 ? _firstSegmentFrames : _laterSegmentFrames;
+ if (segment.Frames >= limit)
+ {
+ EndSegment();
+ segment = BeginSegment();
+ }
+ Span<byte> head = stackalloc byte[8];
+ "00db"u8.CopyTo(head);
+ BinaryPrimitives.WriteInt32LittleEndian(head[4..], _frameBytes);
+ _stream.Write(head);
+ // bottom-up BGR rows
+ for (int y = Height - 1; y >= 0; y--)
+ {
+ ReadOnlySpan<int> row = pixels.Slice(y * Width, Width);
+ for (int x = 0; x < Width; x++)
+ {
+ int argb = row[x];
+ _row[x * 3] = (byte)argb;
+ _row[x * 3 + 1] = (byte)(argb >> 8);
+ _row[x * 3 + 2] = (byte)(argb >> 16);
+ }
+ _stream.Write(_row);
+ }
+ segment.Frames++;
+ FrameCount++;
+ }
+
+ /// <inheritdoc/>
+ public void Close()
+ {
+ if (_closed)
+ {
+ return;
+ }
+ _closed = true;
+ try
+ {
+ EndSegment();
+ _stream.Position = 0;
+ _stream.Write(BuildHeader());
+ _stream.Flush();
+ }
+ finally
+ {
+ _stream.Dispose();
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Dispose() => Close();
+
+ // ---------------------------------------------------------------- segments
+
+ /// <summary>Opens a segment at the current position: for the first only its 'LIST movi' head (its RIFF head is part of the header), for later ones 'RIFF … AVIX' and 'LIST … movi'; the sizes are patched by <see cref="EndSegment"/>.</summary>
+ private Segment BeginSegment()
+ {
+ Span<byte> head = stackalloc byte[24];
+ Segment segment;
+ if (_segments.Count == 0)
+ {
+ segment = new Segment(0, _stream.Position);
+ "LIST"u8.CopyTo(head);
+ "movi"u8.CopyTo(head[8..]);
+ _stream.Write(head[..12]);
+ }
+ else
+ {
+ segment = new Segment(_stream.Position, _stream.Position + 12);
+ "RIFF"u8.CopyTo(head);
+ "AVIX"u8.CopyTo(head[8..]);
+ "LIST"u8.CopyTo(head[12..]);
+ "movi"u8.CopyTo(head[20..]);
+ _stream.Write(head);
+ }
+ _segments.Add(segment);
+ return segment;
+ }
+
+ /// <summary>Closes the current segment: its ix00 inside movi, the idx1 after the first segment's movi, and the patched sizes.</summary>
+ private void EndSegment()
+ {
+ Segment segment = _segments[^1];
+ int frames = segment.Frames;
+ long moviStart = segment.MoviStart;
+ long dataStart = moviStart + 12; // the first frame chunk's header
+ // ix00: the standard index of this segment's chunks, offsets from the movi LIST head to each chunk's data
+ var index = new byte[32 + 8 * frames];
+ "ix00"u8.CopyTo(index);
+ BinaryPrimitives.WriteInt32LittleEndian(index.AsSpan(4), 24 + 8 * frames);
+ BinaryPrimitives.WriteUInt16LittleEndian(index.AsSpan(8), 2); // wLongsPerEntry
+ index[10] = 0; // bIndexSubType
+ index[11] = 1; // bIndexType: AVI_INDEX_OF_CHUNKS
+ BinaryPrimitives.WriteInt32LittleEndian(index.AsSpan(12), frames); // nEntriesInUse
+ "00db"u8.CopyTo(index.AsSpan(16)); // dwChunkId
+ BinaryPrimitives.WriteInt64LittleEndian(index.AsSpan(20), moviStart); // qwBaseOffset
+ for (int i = 0; i < frames; i++)
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(index.AsSpan(32 + 8 * i), (int)(dataStart + (long)i * _chunkBytes + 8 - moviStart));
+ BinaryPrimitives.WriteInt32LittleEndian(index.AsSpan(36 + 8 * i), _frameBytes); // bit 31 clear: a key frame
+ }
+ segment.IndexPosition = _stream.Position;
+ _stream.Write(index);
+ long moviEnd = _stream.Position;
+ if (_segments.Count == 1)
+ {
+ // idx1: the legacy index, chunk offsets relative to the 'movi' fourcc
+ var legacy = new byte[8 + 16 * frames];
+ "idx1"u8.CopyTo(legacy);
+ BinaryPrimitives.WriteInt32LittleEndian(legacy.AsSpan(4), 16 * frames);
+ for (int i = 0; i < frames; i++)
+ {
+ "00db"u8.CopyTo(legacy.AsSpan(8 + 16 * i));
+ BinaryPrimitives.WriteUInt32LittleEndian(legacy.AsSpan(12 + 16 * i), AviifKeyframe);
+ BinaryPrimitives.WriteInt32LittleEndian(legacy.AsSpan(16 + 16 * i), (int)(dataStart + (long)i * _chunkBytes - (moviStart + 8)));
+ BinaryPrimitives.WriteInt32LittleEndian(legacy.AsSpan(20 + 16 * i), _frameBytes);
+ }
+ _stream.Write(legacy);
+ }
+ segment.End = _stream.Position;
+ if (_segments.Count > 1)
+ {
+ Patch(segment.RiffStart + 4, (uint)(segment.End - segment.RiffStart - 8));
+ }
+ Patch(moviStart + 4, (uint)(moviEnd - moviStart - 8));
+ _stream.Position = segment.End;
+ }
+
+ private void Patch(long position, uint value)
+ {
+ Span<byte> bytes = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(bytes, value);
+ _stream.Position = position;
+ _stream.Write(bytes);
+ }
+
+ // ---------------------------------------------------------------- header
+
+ /// <summary>Bytes before the first segment's movi LIST: the RIFF head, 'LIST hdrl' and 'LIST odml'.</summary>
+ private static int HeaderBytes(int superEntries) => 12 + HdrlChunkBytes(superEntries) + (12 + 8 + DmlhSize);
+
+ /// <summary>Bytes of the whole 'LIST hdrl' chunk with a super index of <paramref name="superEntries"/> entries.</summary>
+ private static int HdrlChunkBytes(int superEntries) => 12 + (8 + 56) + StrlChunkBytes(superEntries);
+
+ private static int StrlChunkBytes(int superEntries) => 12 + (8 + 56) + (8 + 40) + (8 + 24 + 16 * superEntries);
+
+ /// <summary>The first <see cref="_headerBytes"/> bytes of the file, with the counts reached.</summary>
+ private byte[] BuildHeader()
+ {
+ Segment first = _segments[0];
+ var header = new byte[_headerBytes];
+ Span<byte> h = header;
+ "RIFF"u8.CopyTo(h);
+ BinaryPrimitives.WriteUInt32LittleEndian(h[4..], (uint)(first.End - 8));
+ "AVI "u8.CopyTo(h[8..]);
+ int p = 12;
+ // LIST hdrl
+ "LIST"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], HdrlChunkBytes(_superEntries) - 8);
+ "hdrl"u8.CopyTo(h[(p + 8)..]);
+ p += 12;
+ // avih
+ "avih"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], 56);
+ Span<byte> avih = h.Slice(p + 8, 56);
+ BinaryPrimitives.WriteUInt32LittleEndian(avih, (uint)(1000000 / FramesPerSecond)); // dwMicroSecPerFrame
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[4..], (uint)Math.Min(uint.MaxValue, (long)_chunkBytes * FramesPerSecond)); // dwMaxBytesPerSec
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[8..], 0); // dwPaddingGranularity
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[12..], AvifHasIndex | AvifTrustChunkType);
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[16..], (uint)first.Frames); // dwTotalFrames: the first segment's, per OpenDML
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[20..], 0); // dwInitialFrames
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[24..], 1); // dwStreams
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[28..], (uint)_frameBytes); // dwSuggestedBufferSize
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[32..], (uint)Width);
+ BinaryPrimitives.WriteUInt32LittleEndian(avih[36..], (uint)Height);
+ p += 8 + 56;
+ // LIST strl
+ "LIST"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], StrlChunkBytes(_superEntries) - 8);
+ "strl"u8.CopyTo(h[(p + 8)..]);
+ p += 12;
+ // strh
+ "strh"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], 56);
+ Span<byte> strh = h.Slice(p + 8, 56);
+ "vids"u8.CopyTo(strh);
+ "DIB "u8.CopyTo(strh[4..]);
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[8..], 0); // dwFlags
+ BinaryPrimitives.WriteUInt16LittleEndian(strh[12..], 0); // wPriority
+ BinaryPrimitives.WriteUInt16LittleEndian(strh[14..], 0); // wLanguage
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[16..], 0); // dwInitialFrames
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[20..], 1); // dwScale
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[24..], (uint)FramesPerSecond); // dwRate
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[28..], 0); // dwStart
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[32..], (uint)FrameCount); // dwLength: all segments
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[36..], (uint)_frameBytes); // dwSuggestedBufferSize
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[40..], 0xFFFFFFFF); // dwQuality: default
+ BinaryPrimitives.WriteUInt32LittleEndian(strh[44..], 0); // dwSampleSize
+ BinaryPrimitives.WriteUInt16LittleEndian(strh[48..], 0); // rcFrame
+ BinaryPrimitives.WriteUInt16LittleEndian(strh[50..], 0);
+ BinaryPrimitives.WriteUInt16LittleEndian(strh[52..], (ushort)Width);
+ BinaryPrimitives.WriteUInt16LittleEndian(strh[54..], (ushort)Height);
+ p += 8 + 56;
+ // strf: BITMAPINFOHEADER
+ "strf"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], 40);
+ Span<byte> strf = h.Slice(p + 8, 40);
+ BinaryPrimitives.WriteInt32LittleEndian(strf, 40);
+ BinaryPrimitives.WriteInt32LittleEndian(strf[4..], Width);
+ BinaryPrimitives.WriteInt32LittleEndian(strf[8..], Height); // positive: bottom-up
+ BinaryPrimitives.WriteUInt16LittleEndian(strf[12..], 1); // biPlanes
+ BinaryPrimitives.WriteUInt16LittleEndian(strf[14..], 24); // biBitCount
+ BinaryPrimitives.WriteUInt32LittleEndian(strf[16..], 0); // BI_RGB
+ BinaryPrimitives.WriteUInt32LittleEndian(strf[20..], (uint)_frameBytes); // biSizeImage
+ p += 8 + 40;
+ // indx: the super index, one entry per segment's ix00
+ "indx"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], 24 + 16 * _superEntries);
+ Span<byte> indx = h.Slice(p + 8, 24 + 16 * _superEntries);
+ BinaryPrimitives.WriteUInt16LittleEndian(indx, 4); // wLongsPerEntry
+ indx[2] = 0; // bIndexSubType
+ indx[3] = 0; // bIndexType: AVI_INDEX_OF_INDEXES
+ BinaryPrimitives.WriteInt32LittleEndian(indx[4..], Math.Min(_segments.Count, _superEntries)); // nEntriesInUse
+ "00db"u8.CopyTo(indx[8..]);
+ for (int i = 0; i < _segments.Count && i < _superEntries; i++)
+ {
+ Segment segment = _segments[i];
+ BinaryPrimitives.WriteInt64LittleEndian(indx[(24 + 16 * i)..], segment.IndexPosition); // qwOffset: the ix00 chunk
+ BinaryPrimitives.WriteInt32LittleEndian(indx[(32 + 16 * i)..], 32 + 8 * segment.Frames); // dwSize: the chunk with its head
+ BinaryPrimitives.WriteInt32LittleEndian(indx[(36 + 16 * i)..], segment.Frames); // dwDuration
+ }
+ p += 8 + 24 + 16 * _superEntries;
+ // LIST odml with dmlh: the total frame count
+ "LIST"u8.CopyTo(h[p..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 4)..], 4 + 8 + DmlhSize);
+ "odml"u8.CopyTo(h[(p + 8)..]);
+ "dmlh"u8.CopyTo(h[(p + 12)..]);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 16)..], DmlhSize);
+ BinaryPrimitives.WriteInt32LittleEndian(h[(p + 20)..], FrameCount);
+ return header;
+ }
+}
diff --git a/WaveDude/Export/BitWriter.cs b/WaveDude/Export/BitWriter.cs
new file mode 100644
index 0000000..ef91975
--- /dev/null
+++ b/WaveDude/Export/BitWriter.cs
@@ -0,0 +1,125 @@
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes bit fields most-significant-bit first into a byte buffer, as the JPEG and MPEG-1 syntaxes want
+/// them. JPEG entropy-coded data needs a 0x00 after every 0xFF byte (<see cref="StuffJpeg"/>); MPEG-1
+/// does not. Single thread; the caller takes the bytes with <see cref="WrittenBytes"/> or <see cref="WriteTo"/>.
+/// </summary>
+public sealed class BitWriter
+{
+ private byte[] _buffer;
+ private int _count;
+ private ulong _bits;
+ private int _bitCount;
+
+ /// <param name="capacity">Initial size of the byte buffer; it grows as needed.</param>
+ /// <param name="stuffJpeg">Insert a 0x00 after every 0xFF written (JPEG byte stuffing).</param>
+ public BitWriter(int capacity = 1 << 16, bool stuffJpeg = false)
+ {
+ _buffer = new byte[Math.Max(16, capacity)];
+ StuffJpeg = stuffJpeg;
+ }
+
+ /// <summary>Whether a 0x00 follows every 0xFF (JPEG).</summary>
+ public bool StuffJpeg { get; }
+
+ /// <summary>Bytes completed so far (pending bits not included).</summary>
+ public int ByteCount => _count;
+
+ /// <summary>Bits waiting for a full byte, 0 to 7.</summary>
+ public int PendingBits => _bitCount;
+
+ /// <summary>Whole bits written so far, pending ones included.</summary>
+ public long BitPosition => (long)_count * 8 + _bitCount;
+
+ /// <summary>Appends the low <paramref name="bits"/> bits of <paramref name="value"/>, most significant first.</summary>
+ /// <param name="value">The field's value; bits above <paramref name="bits"/> are ignored.</param>
+ /// <param name="bits">Field width, 0 to 32.</param>
+ public void Write(uint value, int bits)
+ {
+ if (bits == 0)
+ {
+ return;
+ }
+ _bits = (_bits << bits) | (value & (bits == 32 ? 0xFFFFFFFFu : (1u << bits) - 1));
+ _bitCount += bits;
+ while (_bitCount >= 8)
+ {
+ _bitCount -= 8;
+ Put((byte)(_bits >> _bitCount));
+ }
+ }
+
+ /// <summary>Appends a code given as a string of '0' and '1' characters.</summary>
+ public void WriteCode(string code)
+ {
+ uint value = 0;
+ foreach (char c in code)
+ {
+ value = (value << 1) | (c == '1' ? 1u : 0u);
+ }
+ Write(value, code.Length);
+ }
+
+ /// <summary>Appends a signed value in <paramref name="bits"/> bits two's complement.</summary>
+ public void WriteSigned(int value, int bits) => Write(unchecked((uint)value), bits);
+
+ /// <summary>Pads with zero bits to the next byte boundary (MPEG start codes, slice ends).</summary>
+ public void AlignZero()
+ {
+ if (_bitCount > 0)
+ {
+ Write(0, 8 - _bitCount);
+ }
+ }
+
+ /// <summary>Pads with one bits to the next byte boundary (the JPEG rule before a marker).</summary>
+ public void AlignOne()
+ {
+ if (_bitCount > 0)
+ {
+ Write(0xFF, 8 - _bitCount);
+ }
+ }
+
+ /// <summary>Appends whole bytes; the writer must be byte-aligned.</summary>
+ /// <exception cref="InvalidOperationException">Bits are pending.</exception>
+ public void WriteBytes(ReadOnlySpan<byte> bytes)
+ {
+ if (_bitCount != 0)
+ {
+ throw new InvalidOperationException("The bit writer is not byte-aligned.");
+ }
+ foreach (byte b in bytes)
+ {
+ Put(b);
+ }
+ }
+
+ /// <summary>The completed bytes (pending bits are not included; align first).</summary>
+ public ReadOnlySpan<byte> WrittenBytes => _buffer.AsSpan(0, _count);
+
+ /// <summary>Writes the completed bytes to <paramref name="stream"/>.</summary>
+ public void WriteTo(Stream stream) => stream.Write(_buffer, 0, _count);
+
+ /// <summary>Forgets everything written; the buffer is kept.</summary>
+ public void Reset()
+ {
+ _count = 0;
+ _bits = 0;
+ _bitCount = 0;
+ }
+
+ private void Put(byte b)
+ {
+ if (_count + 2 > _buffer.Length)
+ {
+ Array.Resize(ref _buffer, _buffer.Length * 2);
+ }
+ _buffer[_count++] = b;
+ if (StuffJpeg && b == 0xFF)
+ {
+ _buffer[_count++] = 0;
+ }
+ }
+}
diff --git a/WaveDude/Export/ExportFormat.cs b/WaveDude/Export/ExportFormat.cs
new file mode 100644
index 0000000..9465da8
--- /dev/null
+++ b/WaveDude/Export/ExportFormat.cs
@@ -0,0 +1,175 @@
+namespace WaveDude.Export;
+
+/// <summary>The export formats, in the order of the Save dialog's filter.</summary>
+public enum ExportFormat
+{
+ /// <summary>A PNG per frame in a folder of its own; lossless.</summary>
+ Png,
+ /// <summary>A JPEG per frame in a folder of its own; the quality setting applies.</summary>
+ Jpeg,
+ /// <summary>An MPEG-1 program stream of I-pictures (<c>.mpg</c>); the quality setting and the nearest standard frame rate apply.</summary>
+ Mpeg1,
+ /// <summary>An uncompressed AVI with OpenDML indexes; lossless, large.</summary>
+ Avi,
+ /// <summary>An H.264 MP4 through the Media Foundation of Windows; the quality setting applies.</summary>
+ Mp4,
+}
+
+/// <summary>What is known about each <see cref="ExportFormat"/>: extensions, whether it is a sequence, how to open its sink.</summary>
+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.
+ /// </summary>
+ public static Func<int, int, int, Action<Stream, ReadOnlyMemory<int>>>? AlternativeJpeg { get; set; }
+
+ /// <summary>
+ /// Frames of a sequence encoded at once: half the cores for encoders that are single-threaded per picture
+ /// (PNG's zlib, the WIC codec), one for the in-house JPEG encoder, which already uses every core itself.
+ /// </summary>
+ 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.
+ /// </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)
+ {
+ return InHouse();
+ }
+ Action<Stream, ReadOnlyMemory<int>> preferred;
+ try
+ {
+ preferred = alternative(width, height, quality);
+ }
+ catch (Exception ex)
+ {
+ Logger.Warn(ex, "The alternative JPEG encoder is not available ({Message}); using the in-house encoder", ex.Message);
+ return InHouse();
+ }
+ bool fallen = false;
+ return (stream, frame) =>
+ {
+ if (!fallen)
+ {
+ long start = stream.CanSeek ? stream.Position : 0;
+ try
+ {
+ preferred(stream, frame);
+ return;
+ }
+ catch (Exception ex)
+ {
+ fallen = true;
+ Logger.Warn(ex, "The alternative JPEG encoder failed ({Message}); the in-house encoder takes over", ex.Message);
+ if (stream.CanSeek)
+ {
+ stream.SetLength(start);
+ stream.Position = start;
+ }
+ }
+ }
+ InHouse()(stream, frame);
+ };
+ }
+
+ /// <summary>The formats in filter order.</summary>
+ public static readonly ExportFormat[] All = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mp4];
+
+ /// <summary>The file extension with its dot.</summary>
+ public static string Extension(ExportFormat format) => format switch
+ {
+ ExportFormat.Png => ".png",
+ ExportFormat.Jpeg => ".jpg",
+ ExportFormat.Mpeg1 => ".mpg",
+ ExportFormat.Avi => ".avi",
+ ExportFormat.Mp4 => ".mp4",
+ _ => throw new ArgumentOutOfRangeException(nameof(format)),
+ };
+
+ /// <summary>The format of a path by its extension (<c>.jpeg</c> and <c>.mpeg</c> count too), or null.</summary>
+ public static ExportFormat? FromPath(string path) => Path.GetExtension(path).ToLowerInvariant() switch
+ {
+ ".png" => ExportFormat.Png,
+ ".jpg" or ".jpeg" => ExportFormat.Jpeg,
+ ".mpg" or ".mpeg" or ".m1v" => ExportFormat.Mpeg1,
+ ".avi" => ExportFormat.Avi,
+ ".mp4" or ".m4v" => ExportFormat.Mp4,
+ _ => null,
+ };
+
+ /// <summary>Whether the format writes one file per frame.</summary>
+ public static bool IsSequence(ExportFormat format) => format is ExportFormat.Png or ExportFormat.Jpeg;
+
+ /// <summary>Whether the quality setting means anything to the format.</summary>
+ public static bool UsesQuality(ExportFormat format) => format is ExportFormat.Jpeg or ExportFormat.Mpeg1 or ExportFormat.Mp4;
+
+ /// <summary>Whether the format can be written here (MP4 needs Media Foundation).</summary>
+ public static bool IsAvailable(ExportFormat format) => format != ExportFormat.Mp4 || (OperatingSystem.IsWindows() && Mp4Writer.IsAvailable());
+
+ /// <summary>
+ /// Where a sequence chosen as <c>C:\Temp\name.png</c> goes: the folder <c>C:\Temp\name</c>, holding
+ /// <c>name_0000.png</c> and on (the user's rule, 2026-10-14).
+ /// </summary>
+ public static string SequenceFolder(string path) =>
+ Path.Combine(Path.GetDirectoryName(path) ?? "", Path.GetFileNameWithoutExtension(path));
+
+ /// <summary>Opens a one-file sink for a still (PNG or JPEG only) at <paramref name="path"/>.</summary>
+ /// <param name="format">PNG or JPEG.</param>
+ /// <param name="path">The file.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="quality">1..100 for JPEG.</param>
+ /// <exception cref="NotSupportedException">A video format was asked for.</exception>
+ public static IFrameSink OpenStill(ExportFormat format, string path, int width, int height, int quality) => format switch
+ {
+ ExportFormat.Png => new ImageFileSink(path, width, height, (stream, frame) => PngEncoder.Write(stream, frame.Span, width, height)),
+ ExportFormat.Jpeg => new ImageFileSink(path, width, height, JpegWriter(width, height, quality)),
+ _ => throw new NotSupportedException("A still is a PNG or a JPEG."),
+ };
+
+ /// <summary>
+ /// Opens the sink for a format at <paramref name="path"/> (for a sequence, the folder of <see cref="SequenceFolder"/>).
+ /// </summary>
+ /// <param name="format">The format.</param>
+ /// <param name="path">The file the user chose; a sequence takes its folder and base name from it.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="fps">Frame rate of a video.</param>
+ /// <param name="quality">1..100 for the lossy formats.</param>
+ /// <param name="plannedFrames">How many frames will come at most (the AVI sizes its indexes by it, a sequence the width of its frame numbers).</param>
+ /// <exception cref="NotSupportedException">The format cannot carry the size, or MP4 is not available here.</exception>
+ public static IFrameSink Open(ExportFormat format, string path, int width, int height, int fps, int quality, int plannedFrames)
+ {
+ switch (format)
+ {
+ case ExportFormat.Png:
+ return new ImageSequenceSink(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), ".png", width, height,
+ () => (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);
+ case ExportFormat.Mpeg1:
+ return new Mpeg1Writer(path, width, height, fps, quality);
+ case ExportFormat.Avi:
+ return new AviWriter(path, width, height, fps, plannedFrames);
+ case ExportFormat.Mp4:
+ if (!OperatingSystem.IsWindows())
+ {
+ throw new NotSupportedException("MP4 export needs the Media Foundation of Windows.");
+ }
+ return new Mp4Writer(path, width, height, fps, quality);
+ default:
+ throw new ArgumentOutOfRangeException(nameof(format));
+ }
+ }
+}
diff --git a/WaveDude/Export/ExportJob.cs b/WaveDude/Export/ExportJob.cs
new file mode 100644
index 0000000..89a11b1
--- /dev/null
+++ b/WaveDude/Export/ExportJob.cs
@@ -0,0 +1,355 @@
+using System.Collections.Concurrent;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using NLog;
+using WaveDude.Rendering;
+using WaveDude.Runs;
+
+namespace WaveDude.Export;
+
+/// <summary>Where an export stands.</summary>
+public enum ExportState
+{
+ /// <summary>Not started.</summary>
+ Created,
+ /// <summary>Frames are being written.</summary>
+ Running,
+ /// <summary>Every frame of the range was written.</summary>
+ Completed,
+ /// <summary>Stopped by <see cref="ExportJob.Cancel"/>; the files hold the frames written so far.</summary>
+ Cancelled,
+ /// <summary>Stopped by an error (<see cref="ExportJob.Error"/>).</summary>
+ Failed,
+}
+
+/// <summary>
+/// How one layer is rendered for an export: the colour table, gain, the scene outline to bake in, and an
+/// optional decoration step (the probe graph boxes, drawn by the application). The decoration runs on the
+/// render thread, once per frame, after the outline, on the frame's packed BGRA32 pixels.
+/// </summary>
+/// <param name="Layer">Which plane of the store.</param>
+/// <param name="Lut">The colour table (<c>ColorLut.Argb</c>), or null for grey levels.</param>
+/// <param name="Brightness">The layer's gain.</param>
+/// <param name="Edges">The glowing-edges picture (<see cref="GlowingEdges.Compute"/>) to add, or null.</param>
+/// <param name="EdgeGain">The outline's gain; 0 adds nothing.</param>
+/// <param name="Decorate">Draws over the rendered frame: the frame index and the pixels; null for none.</param>
+public sealed record ExportLayer(FrameLayer Layer, int[]? Lut, float Brightness, byte[]? Edges, double EdgeGain, Action<int, Memory<int>>? Decorate);
+
+/// <summary>
+/// One output of an export: a layer rendered into a sink. The sink is opened by the job on its sink thread
+/// (<see cref="Open"/>), not by the caller: a Media Foundation writer must be created and used on one
+/// thread, and the COM object refused a thread from another apartment (2026-10-14).
+/// </summary>
+/// <param name="Layer">How the frames are rendered.</param>
+/// <param name="Output">What the output will be called in messages before the sink exists: the file or the sequence folder.</param>
+/// <param name="Open">Creates the sink; called once on the sink thread, closed by the job.</param>
+public sealed record ExportTarget(ExportLayer Layer, string Output, Func<IFrameSink> Open)
+{
+ /// <summary>The sink once the job has opened it; null before, and when opening failed.</summary>
+ public IFrameSink? Sink { get; internal set; }
+}
+
+/// <summary>
+/// Renders a range of a run's stored frames into one or more sinks: a render thread reads each target's
+/// plane from the <see cref="FrameStore"/>, colours it with <see cref="FrameRenderer"/>, adds the outline
+/// (<see cref="GlowingEdges.BlendAdditive"/>) and the decoration, and hands the pixels to a sink thread,
+/// which opens the sinks, encodes and writes; the two overlap, so a frame's encoding costs no rendering time
+/// (2026-10-14). Progress and the final state are published through the <see cref="SynchronizationContext"/>
+/// given to the constructor (the WPF dispatcher; null runs them on the worker), so the properties bind
+/// directly. Both threads are single-threaded apartments on Windows: the decoration may use WPF drawing
+/// objects of its own, and Media Foundation stays on the thread that created its writer.
+/// </summary>
+public sealed class ExportJob : INotifyPropertyChanged
+{
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+
+ /// <summary>Least interval between progress posts.</summary>
+ private const long ProgressIntervalMs = 100;
+
+ /// <summary>Rendered frames waiting for the sinks, per target; the render thread blocks beyond that.</summary>
+ private const int QueueDepth = 2;
+
+ private readonly SynchronizationContext? _context;
+ private readonly CancellationTokenSource _cancel = new();
+ private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ private ExportState _state = ExportState.Created;
+ private int _framesDone;
+ private TimeSpan _elapsed;
+ private Exception? _error;
+
+ /// <param name="store">The frames; read from <paramref name="firstFrame"/> to <paramref name="lastFrame"/>, which must exist by the time they are reached.</param>
+ /// <param name="firstFrame">First frame index.</param>
+ /// <param name="lastFrame">Last frame index, inclusive.</param>
+ /// <param name="targets">The outputs; their sinks are opened when the job starts and closed when it ends, however it ends.</param>
+ /// <param name="context">Where properties are published; null for the worker.</param>
+ public ExportJob(FrameStore store, int firstFrame, int lastFrame, IReadOnlyList<ExportTarget> targets, SynchronizationContext? context)
+ {
+ if (firstFrame < 0 || lastFrame < firstFrame)
+ {
+ throw new ArgumentOutOfRangeException(nameof(lastFrame), "The range is empty.");
+ }
+ Store = store;
+ FirstFrame = firstFrame;
+ LastFrame = lastFrame;
+ Targets = targets;
+ _context = context;
+ }
+
+ /// <inheritdoc/>
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ /// <summary>The job reached a final state; raised once, after <see cref="State"/> changed.</summary>
+ public event EventHandler? Finished;
+
+ /// <summary>The frames being exported.</summary>
+ public FrameStore Store { get; }
+
+ /// <summary>First frame of the range.</summary>
+ public int FirstFrame { get; }
+
+ /// <summary>Last frame of the range, inclusive.</summary>
+ public int LastFrame { get; }
+
+ /// <summary>Frames in the range.</summary>
+ public int FrameCount => LastFrame - FirstFrame + 1;
+
+ /// <summary>The outputs.</summary>
+ public IReadOnlyList<ExportTarget> Targets { get; }
+
+ /// <summary>Current state.</summary>
+ public ExportState State
+ {
+ get => _state;
+ private set => Set(ref _state, value);
+ }
+
+ /// <summary>Whether the job is running.</summary>
+ public bool IsActive => State == ExportState.Running;
+
+ /// <summary>Frames written to every target so far; refreshed about ten times a second and at the end.</summary>
+ public int FramesDone
+ {
+ get => _framesDone;
+ private set => Set(ref _framesDone, value);
+ }
+
+ /// <summary>Time spent so far, set at the end.</summary>
+ public TimeSpan Elapsed
+ {
+ get => _elapsed;
+ private set => Set(ref _elapsed, value);
+ }
+
+ /// <summary>The error that ended the job, when <see cref="State"/> is Failed.</summary>
+ public Exception? Error
+ {
+ get => _error;
+ private set => Set(ref _error, value);
+ }
+
+ /// <summary>Completes when the job has reached a final state and every sink is closed.</summary>
+ public Task Completion => _completion.Task;
+
+ /// <summary>Starts the threads. Once.</summary>
+ public void Start()
+ {
+ if (State != ExportState.Created)
+ {
+ throw new InvalidOperationException("The export has already been started.");
+ }
+ State = ExportState.Running;
+ StartThread("Export render", Render);
+ }
+
+ /// <summary>Asks the threads to stop after the frame in progress; the sinks are closed with what they have.</summary>
+ public void Cancel() => _cancel.Cancel();
+
+ private static Thread StartThread(string name, ThreadStart work)
+ {
+ var thread = new Thread(work, 16 << 20) { Name = name, IsBackground = true };
+ if (OperatingSystem.IsWindows())
+ {
+ thread.SetApartmentState(ApartmentState.STA);
+ }
+ thread.Start();
+ return thread;
+ }
+
+ /// <summary>A rendered frame on its way to a sink.</summary>
+ private sealed record Item(int Frame, int Target, int[] Pixels);
+
+ /// <summary>The render thread: starts the sink thread, renders every frame of the range into pooled buffers and queues them; waits for the sink thread at the end.</summary>
+ private void Render()
+ {
+ var stopwatch = Stopwatch.StartNew();
+ ExportState final = ExportState.Completed;
+ Exception? error = null;
+ int width = Store.Width;
+ int height = Store.Height;
+ int buffers = Targets.Count * QueueDepth + 1;
+ var free = new BlockingCollection<int[]>(buffers);
+ for (int i = 0; i < buffers; i++)
+ {
+ free.Add(new int[width * height]);
+ }
+ var queue = new BlockingCollection<Item>(Targets.Count * QueueDepth);
+ using var sinksReady = new ManualResetEventSlim();
+ Exception? sinkError = null;
+ Exception? closeError = null;
+ Thread sink = StartThread("Export sinks", () =>
+ {
+ int written = 0;
+ long lastPost = 0;
+ try
+ {
+ foreach (ExportTarget target in Targets)
+ {
+ target.Sink = target.Open();
+ Logger.Debug("Export output opened: {Output}", target.Sink.Output);
+ }
+ sinksReady.Set();
+ foreach (Item item in queue.GetConsumingEnumerable())
+ {
+ Targets[item.Target].Sink!.Add(item.Pixels);
+ free.Add(item.Pixels);
+ if (item.Target == Targets.Count - 1)
+ {
+ written++;
+ int done = written;
+ if (stopwatch.ElapsedMilliseconds - lastPost >= ProgressIntervalMs)
+ {
+ lastPost = stopwatch.ElapsedMilliseconds;
+ Post(() => FramesDone = done);
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ sinkError = ex;
+ _cancel.Cancel();
+ sinksReady.Set();
+ // drain, so the render thread never blocks on a full queue
+ foreach (Item item in queue.GetConsumingEnumerable())
+ {
+ free.Add(item.Pixels);
+ }
+ }
+ finally
+ {
+ // closed where they were opened: a Media Foundation writer is bound to its thread
+ foreach (ExportTarget target in Targets)
+ {
+ if (target.Sink == null)
+ {
+ continue;
+ }
+ try
+ {
+ target.Sink.Close();
+ }
+ catch (Exception ex)
+ {
+ Logger.Error(ex, "Closing {Output} failed: {Message}", target.Sink.Output, ex.Message);
+ closeError ??= ex;
+ }
+ }
+ }
+ });
+ try
+ {
+ sinksReady.Wait();
+ var values = new Half[width * height];
+ for (int frame = FirstFrame; frame <= LastFrame && sinkError == null; frame++)
+ {
+ if (_cancel.IsCancellationRequested)
+ {
+ final = ExportState.Cancelled;
+ break;
+ }
+ for (int t = 0; t < Targets.Count; t++)
+ {
+ ExportLayer layer = Targets[t].Layer;
+ if (frame >= Store.Count || !Store.CopyLayer(frame, layer.Layer, values))
+ {
+ throw new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");
+ }
+ int[] pixels = free.Take();
+ if (layer.Layer == FrameLayer.Intensity)
+ {
+ FrameRenderer.RenderIntensity(values, width, height, layer.Lut, layer.Brightness, pixels);
+ }
+ else
+ {
+ FrameRenderer.RenderField(values, width, height, layer.Lut, layer.Brightness, pixels);
+ }
+ if (layer.Edges != null && layer.EdgeGain > 0.0)
+ {
+ GlowingEdges.BlendAdditive(pixels, width, height, layer.Edges, layer.EdgeGain);
+ }
+ layer.Decorate?.Invoke(frame, pixels);
+ queue.Add(new Item(frame, t, pixels));
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ final = ExportState.Failed;
+ error = ex;
+ Logger.Error(ex, "Export failed: {Message}", ex.Message);
+ }
+ finally
+ {
+ queue.CompleteAdding();
+ sink.Join();
+ if (sinkError != null)
+ {
+ final = ExportState.Failed;
+ error = sinkError;
+ Logger.Error(sinkError, "Export failed: {Message}", sinkError.Message);
+ }
+ else if (closeError != null && final == ExportState.Completed)
+ {
+ final = ExportState.Failed;
+ error = closeError;
+ }
+ }
+ stopwatch.Stop();
+ int framesDone = Targets.Count > 0 ? Targets[0].Sink?.FrameCount ?? 0 : FrameCount;
+ Post(() =>
+ {
+ FramesDone = framesDone;
+ Elapsed = stopwatch.Elapsed;
+ Error = error;
+ State = final;
+ Finished?.Invoke(this, EventArgs.Empty);
+ _completion.TrySetResult();
+ });
+ }
+
+ private void Post(Action action)
+ {
+ if (_context == null)
+ {
+ action();
+ }
+ else
+ {
+ _context.Post(_ => action(), null);
+ }
+ }
+
+ private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
+ {
+ if (!EqualityComparer<T>.Default.Equals(field, value))
+ {
+ field = value;
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
+ if (name == nameof(State))
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsActive)));
+ }
+ }
+ }
+}
diff --git a/WaveDude/Export/IFrameSink.cs b/WaveDude/Export/IFrameSink.cs
new file mode 100644
index 0000000..89b26ae
--- /dev/null
+++ b/WaveDude/Export/IFrameSink.cs
@@ -0,0 +1,33 @@
+namespace WaveDude.Export;
+
+/// <summary>
+/// One export output: a video file or an image sequence that takes rendered frames one after the other.
+/// Frames are <see cref="Width"/> × <see cref="Height"/> packed BGRA32 pixels (<c>0xAARRGGBB</c> as an
+/// <c>int</c>, blue in the lowest byte in memory), row-major, top row first; the alpha byte is ignored.
+/// One thread at a time (the export worker); <see cref="Close"/> finishes the file and <see cref="IDisposable.Dispose"/>
+/// does the same, so a failed export still leaves a readable file of the frames written so far where the
+/// format allows it.
+/// </summary>
+public interface IFrameSink : IDisposable
+{
+ /// <summary>Width of every frame in pixels.</summary>
+ int Width { get; }
+
+ /// <summary>Height of every frame in pixels.</summary>
+ int Height { get; }
+
+ /// <summary>Frames taken so far.</summary>
+ int FrameCount { get; }
+
+ /// <summary>A description of the output for the log: the file, or the folder of a sequence.</summary>
+ string Output { get; }
+
+ /// <summary>Appends one frame of <see cref="Width"/> × <see cref="Height"/> pixels.</summary>
+ /// <param name="pixels">The frame, packed BGRA32, row-major, at least width × height values.</param>
+ /// <exception cref="InvalidOperationException">The sink is closed.</exception>
+ /// <exception cref="IOException">The file could not be written.</exception>
+ void Add(ReadOnlySpan<int> pixels);
+
+ /// <summary>Finishes the output (indexes, trailers, open handles). Idempotent.</summary>
+ void Close();
+}
diff --git a/WaveDude/Export/ImageFileSink.cs b/WaveDude/Export/ImageFileSink.cs
new file mode 100644
index 0000000..f74f29e
--- /dev/null
+++ b/WaveDude/Export/ImageFileSink.cs
@@ -0,0 +1,60 @@
+namespace WaveDude.Export;
+
+/// <summary>
+/// A still: exactly one frame written to one file (PNG or JPEG through the encoder delegate, like
+/// <see cref="ImageSequenceSink"/>). A second frame is refused. One thread at a time.
+/// </summary>
+public sealed class ImageFileSink : IFrameSink
+{
+ private readonly Action<Stream, ReadOnlyMemory<int>> _encode;
+ private bool _closed;
+
+ /// <param name="path">The file; replaced when it exists.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="encode">Writes the frame (packed BGRA32, width × height) to a stream.</param>
+ public ImageFileSink(string path, int width, int height, Action<Stream, ReadOnlyMemory<int>> encode)
+ {
+ Output = path;
+ Width = width;
+ Height = height;
+ _encode = encode;
+ }
+
+ /// <inheritdoc/>
+ public int Width { get; }
+
+ /// <inheritdoc/>
+ public int Height { get; }
+
+ /// <inheritdoc/>
+ public int FrameCount { get; private set; }
+
+ /// <inheritdoc/>
+ public string Output { get; }
+
+ /// <inheritdoc/>
+ public void Add(ReadOnlySpan<int> pixels)
+ {
+ if (_closed || FrameCount > 0)
+ {
+ throw new InvalidOperationException("A still takes one frame.");
+ }
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the picture.", nameof(pixels));
+ }
+ int[] frame = pixels[..(Width * Height)].ToArray();
+ using (var stream = new FileStream(Output, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 16))
+ {
+ _encode(stream, frame);
+ }
+ FrameCount = 1;
+ }
+
+ /// <inheritdoc/>
+ public void Close() => _closed = true;
+
+ /// <inheritdoc/>
+ public void Dispose() => Close();
+}
diff --git a/WaveDude/Export/ImageSequenceSink.cs b/WaveDude/Export/ImageSequenceSink.cs
new file mode 100644
index 0000000..0cc8ad2
--- /dev/null
+++ b/WaveDude/Export/ImageSequenceSink.cs
@@ -0,0 +1,178 @@
+using System.Collections.Concurrent;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// An image sequence: one file per frame, <c>&lt;name&gt;_0000.&lt;ext&gt;</c> and on, in a folder of its own. The
+/// frame number has a fixed width for the whole sequence, at least four digits and as many as the planned frame
+/// count needs, so the names sort in frame order past 9999 frames and a <c>%05d</c> pattern takes them all
+/// (2026-10-15).
+/// The encoder is given as a factory, so the same sink serves PNG (<see cref="PngEncoder"/>) and JPEG
+/// (<see cref="JpegEncoder"/> or the application's alternative). Frames are independent files, so with
+/// <see cref="Workers"/> above one they are encoded on that many threads at once, each with its own encoder
+/// from the factory (2026-10-15: WIC and zlib are single-threaded per picture); <see cref="Add"/> then only
+/// queues the frame and <see cref="Close"/> waits for the last file. A worker's error surfaces from the next
+/// <see cref="Add"/> or from <see cref="Close"/>. The folder is created; files of the same names are
+/// replaced. One caller thread at a time.
+/// </summary>
+public sealed class ImageSequenceSink : IFrameSink
+{
+ /// <summary>Fewest digits of the frame number in the file names.</summary>
+ public const int MinDigits = 4;
+
+ private readonly Func<Action<Stream, ReadOnlyMemory<int>>> _makeEncoder;
+ private readonly Action<Stream, ReadOnlyMemory<int>>? _encoder;
+ private readonly BlockingCollection<(int Index, int[] Frame)>? _queue;
+ private readonly ConcurrentBag<int[]> _pool = [];
+ private readonly Thread[] _threads = [];
+ private Exception? _error;
+ private bool _closed;
+
+ /// <param name="folder">Where the files go; created when missing.</param>
+ /// <param name="baseName">The name before the underscore and number.</param>
+ /// <param name="extension">The file extension with its dot.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="makeEncoder">Makes an encoder that writes one frame (packed BGRA32, width × height) to a stream; called once per worker.</param>
+ /// <param name="workers">Frames encoded at once; 1 encodes on the caller's thread.</param>
+ /// <param name="plannedFrames">How many frames will come at most; decides the width of the frame numbers (<see cref="Digits"/>).</param>
+ public ImageSequenceSink(string folder, string baseName, string extension, int width, int height, Func<Action<Stream, ReadOnlyMemory<int>>> makeEncoder, int workers = 1, int plannedFrames = 0)
+ {
+ Folder = folder;
+ BaseName = baseName;
+ Extension = extension;
+ Width = width;
+ Height = height;
+ Workers = Math.Max(1, workers);
+ Digits = Math.Max(MinDigits, Math.Max(0, plannedFrames - 1).ToString(System.Globalization.CultureInfo.InvariantCulture).Length);
+ _makeEncoder = makeEncoder;
+ Directory.CreateDirectory(folder);
+ if (Workers == 1)
+ {
+ _encoder = makeEncoder();
+ return;
+ }
+ _queue = new BlockingCollection<(int, int[])>(Workers * 2);
+ _threads = new Thread[Workers];
+ for (int i = 0; i < Workers; i++)
+ {
+ _threads[i] = new Thread(Work) { Name = "Image sequence " + i, IsBackground = true };
+ _threads[i].Start();
+ }
+ }
+
+ /// <summary>The sequence's folder.</summary>
+ public string Folder { get; }
+
+ /// <summary>The name before the frame number.</summary>
+ public string BaseName { get; }
+
+ /// <summary>The extension with its dot.</summary>
+ public string Extension { get; }
+
+ /// <inheritdoc/>
+ public int Width { get; }
+
+ /// <inheritdoc/>
+ public int Height { get; }
+
+ /// <summary>Frames encoded at once.</summary>
+ public int Workers { get; }
+
+ /// <summary>Digits of the frame number in every file name of this sequence: <see cref="MinDigits"/>, or more when the planned frame count needs them.</summary>
+ public int Digits { get; }
+
+ /// <inheritdoc/>
+ public int FrameCount { get; private set; }
+
+ /// <inheritdoc/>
+ public string Output => Folder;
+
+ /// <summary>The path of frame <paramref name="index"/>.</summary>
+ public string PathOf(int index) => Path.Combine(Folder, BaseName + "_" + index.ToString("D" + Digits, System.Globalization.CultureInfo.InvariantCulture) + Extension);
+
+ /// <inheritdoc/>
+ public void Add(ReadOnlySpan<int> pixels)
+ {
+ if (_closed)
+ {
+ throw new InvalidOperationException("The sequence is already closed.");
+ }
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the sequence.", nameof(pixels));
+ }
+ Rethrow();
+ // the encoders read the frame from other threads, so it is copied into a buffer of the sink's own (pooled:
+ // a fresh eight-megabyte array per frame kept the garbage collector busier than the encoders, 2026-10-15)
+ if (!_pool.TryTake(out int[]? frame))
+ {
+ frame = new int[Width * Height];
+ }
+ pixels[..(Width * Height)].CopyTo(frame);
+ int index = FrameCount++;
+ if (_queue == null)
+ {
+ Encode(_encoder!, index, frame);
+ _pool.Add(frame);
+ }
+ else
+ {
+ _queue.Add((index, frame));
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Close()
+ {
+ if (_closed)
+ {
+ return;
+ }
+ _closed = true;
+ if (_queue != null)
+ {
+ _queue.CompleteAdding();
+ foreach (Thread thread in _threads)
+ {
+ thread.Join();
+ }
+ }
+ Rethrow();
+ }
+
+ /// <inheritdoc/>
+ public void Dispose() => Close();
+
+ private void Work()
+ {
+ try
+ {
+ Action<Stream, ReadOnlyMemory<int>> encoder = _makeEncoder();
+ foreach ((int index, int[] frame) in _queue!.GetConsumingEnumerable())
+ {
+ Encode(encoder, index, frame);
+ _pool.Add(frame);
+ }
+ }
+ catch (Exception ex)
+ {
+ Interlocked.CompareExchange(ref _error, ex, null);
+ // let the others finish; nothing more is taken by this worker
+ }
+ }
+
+ private void Encode(Action<Stream, ReadOnlyMemory<int>> encoder, int index, int[] frame)
+ {
+ using var stream = new FileStream(PathOf(index), FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 16);
+ encoder(stream, frame);
+ }
+
+ private void Rethrow()
+ {
+ if (Volatile.Read(ref _error) is { } error)
+ {
+ throw new IOException("Writing the image sequence failed: " + error.Message, error);
+ }
+ }
+}
diff --git a/WaveDude/Export/JpegEncoder.cs b/WaveDude/Export/JpegEncoder.cs
new file mode 100644
index 0000000..40baa05
--- /dev/null
+++ b/WaveDude/Export/JpegEncoder.cs
@@ -0,0 +1,448 @@
+using System.Buffers.Binary;
+using System.Numerics;
+using System.Runtime.Intrinsics;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes baseline JPEG files (JFIF, 4:2:0, 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
+/// 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
+/// directly); the entropy coder emits a Huffman code and its value bits as one field into a 64-bit
+/// accumulator flushed four bytes at a time (2026-10-15; the first version took three times WIC's time per
+/// thread). Reusable for frames of one size; one thread at a time.
+/// </summary>
+public sealed class JpegEncoder
+{
+ private readonly YuvPlanes _planes;
+ private readonly byte[] _lumaQuant = new byte[64];
+ private readonly byte[] _chromaQuant = new byte[64];
+ private readonly float[] _lumaDivisorsZ = new float[64];
+ private readonly float[] _chromaDivisorsZ = new float[64];
+ private readonly RowBuffer[] _rows;
+ private readonly byte[] _header;
+
+ /// <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>
+ public JpegEncoder(int width, int height, int quality)
+ {
+ Width = width;
+ Height = height;
+ Quality = Math.Clamp(quality, 1, 100);
+ _planes = new YuvPlanes(width, height, studioRange: false);
+ 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));
+ }
+ _header = BuildHeader();
+ }
+
+ /// <summary>Frame width in pixels.</summary>
+ public int Width { get; }
+
+ /// <summary>Frame height in pixels.</summary>
+ public int Height { get; }
+
+ /// <summary>The quality the tables were scaled for.</summary>
+ public int Quality { get; }
+
+ /// <summary>Whether the rows are coded in parallel (the default); off, they go one after the other, for the bench's comparison.</summary>
+ public bool ParallelRows { get; set; } = true;
+
+ /// <summary>
+ /// Threads the rows may use when <see cref="ParallelRows"/> is on: the core count. Left to the scheduler (-1)
+ /// the pool oversubscribed and the frame took twice as long (13.8 against 5.8 ms at 1080p, 2026-10-15); the
+ /// bench sets other values for its scaling curve.
+ /// </summary>
+ public int MaxThreads { get; set; } = Environment.ProcessorCount;
+
+ /// <summary>Milliseconds the last frame spent in the colour conversion and in the rows' transform-and-code pass (for the bench).</summary>
+ public (double Convert, double Rows) LastPhases { get; private set; }
+
+ /// <summary>Writes one frame as a JPEG to <paramref name="stream"/> (left open).</summary>
+ /// <param name="stream">Destination.</param>
+ /// <param name="pixels">Packed BGRA32 pixels, row-major, at least width × height.</param>
+ public void Write(Stream stream, ReadOnlyMemory<int> pixels)
+ {
+ long t0 = System.Diagnostics.Stopwatch.GetTimestamp();
+ _planes.Convert(pixels);
+ long t1 = System.Diagnostics.Stopwatch.GetTimestamp();
+ if (ParallelRows)
+ {
+ Parallel.For(0, _rows.Length, new ParallelOptions { MaxDegreeOfParallelism = MaxThreads }, EncodeRow);
+ }
+ else
+ {
+ for (int row = 0; row < _rows.Length; row++)
+ {
+ EncodeRow(row);
+ }
+ }
+ long t2 = System.Diagnostics.Stopwatch.GetTimestamp();
+ LastPhases = (System.Diagnostics.Stopwatch.GetElapsedTime(t0, t1).TotalMilliseconds, System.Diagnostics.Stopwatch.GetElapsedTime(t1, t2).TotalMilliseconds);
+ stream.Write(_header);
+ for (int row = 0; row < _rows.Length; row++)
+ {
+ stream.Write(_rows[row].Bytes, 0, _rows[row].Count);
+ if (row < _rows.Length - 1)
+ {
+ stream.Write([0xFF, (byte)(0xD0 + (row & 7))]); // RSTn
+ }
+ }
+ stream.Write([0xFF, 0xD9]); // EOI
+ }
+
+ /// <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();
+ }
+
+ /// <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>
+ private void EncodeRow(int mbRow)
+ {
+ YuvPlanes planes = _planes;
+ RowBuffer row = _rows[mbRow];
+ row.Count = 0;
+ var bits = new BitSink(row);
+ Span<float> block = stackalloc float[64];
+ Span<float> dct = stackalloc float[64];
+ Span<int> quantised = stackalloc int[64];
+ int predictorY = 0;
+ int predictorCb = 0;
+ int predictorCr = 0;
+ for (int mbColumn = 0; mbColumn < planes.MacroblockColumns; mbColumn++)
+ {
+ for (int blockIndex = 0; blockIndex < 6; blockIndex++)
+ {
+ 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
+ {
+ EncodeBlock(ref bits, quantised, ChromaDcCodes, ChromaDcLengths, ChromaAcCodes, ChromaAcLengths, ref predictorCr);
+ }
+ }
+ }
+ bits.Finish();
+ }
+
+ /// <summary>Rounds the AAN coefficients times their folded divisors, straight into zig-zag order.</summary>
+ private static void QuantiseZigZag(ReadOnlySpan<float> dct, ReadOnlySpan<float> divisorsZ, Span<int> quantised)
+ {
+ ReadOnlySpan<int> order = Dct8x8.ZigZagAan;
+ if (Vector128.IsHardwareAccelerated)
+ {
+ Span<float> gathered = stackalloc float[64];
+ for (int i = 0; i < 64; i++)
+ {
+ gathered[i] = dct[order[i]];
+ }
+ for (int i = 0; i < 64; i += 4)
+ {
+ Vector128<float> scaled = Vector128.Create(gathered.Slice(i, 4)) * Vector128.Create(divisorsZ.Slice(i, 4));
+ Vector128.ConvertToInt32(Vector128.Round(scaled)).CopyTo(quantised.Slice(i, 4));
+ }
+ }
+ else
+ {
+ for (int i = 0; i < 64; i++)
+ {
+ quantised[i] = (int)MathF.Round(dct[order[i]] * divisorsZ[i]);
+ }
+ }
+ }
+
+ /// <summary>Huffman-codes one block already in zig-zag order: the DC difference, the AC run/size pairs with their value bits as one field each, ZRL and EOB.</summary>
+ private static void EncodeBlock(ref BitSink bits, scoped ReadOnlySpan<int> quantised, ushort[] dcCodes, byte[] dcLengths, ushort[] acCodes, byte[] acLengths, ref int predictor)
+ {
+ int diff = quantised[0] - predictor;
+ predictor = quantised[0];
+ int size = Category(diff);
+ bits.Write(((ulong)dcCodes[size] << size) | ValueBits(diff, size), dcLengths[size] + size);
+ int run = 0;
+ for (int i = 1; i < 64; i++)
+ {
+ int value = quantised[i];
+ if (value == 0)
+ {
+ run++;
+ continue;
+ }
+ while (run >= 16)
+ {
+ bits.Write(acCodes[0xF0], acLengths[0xF0]); // ZRL: sixteen zeros
+ run -= 16;
+ }
+ int category = Category(value);
+ int symbol = (run << 4) | category;
+ bits.Write(((ulong)acCodes[symbol] << category) | ValueBits(value, category), acLengths[symbol] + category);
+ run = 0;
+ }
+ if (run > 0)
+ {
+ bits.Write(acCodes[0x00], acLengths[0x00]); // EOB
+ }
+ }
+
+ /// <summary>The magnitude category of a coefficient: the number of bits of its absolute value.</summary>
+ private static int Category(int value) => value == 0 ? 0 : 32 - BitOperations.LeadingZeroCount((uint)Math.Abs(value));
+
+ /// <summary>The additional bits of a value in a category: the value itself, or for a negative one its one's complement in that many bits.</summary>
+ private static ulong ValueBits(int value, int category) => (ulong)(uint)(value < 0 ? value - 1 : value) & ((1UL << category) - 1);
+
+ /// <summary>Everything before the entropy-coded data: SOI, APP0, two DQT, SOF0, four DHT, DRI, SOS.</summary>
+ private byte[] BuildHeader()
+ {
+ using var stream = new MemoryStream();
+ stream.Write([0xFF, 0xD8]); // SOI
+ // APP0 JFIF 1.01, no density, no thumbnail
+ Segment(stream, 0xE0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
+ // DQT: 8-bit tables in zig-zag order, luma 0, chroma 1
+ var quant = new byte[2 * 65];
+ quant[0] = 0;
+ quant[65] = 1;
+ for (int i = 0; i < 64; i++)
+ {
+ quant[1 + i] = _lumaQuant[Dct8x8.ZigZag[i]];
+ 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
+ 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[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
+ var interval = new byte[2];
+ BinaryPrimitives.WriteUInt16BigEndian(interval, (ushort)_planes.MacroblockColumns);
+ 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]);
+ return stream.ToArray();
+ }
+
+ private static byte[] DhtSegment(byte classAndId, byte[] counts, byte[] symbols) => [classAndId, .. counts, .. symbols];
+
+ private static void Segment(Stream stream, byte marker, ReadOnlySpan<byte> payload)
+ {
+ Span<byte> head = stackalloc byte[4];
+ head[0] = 0xFF;
+ head[1] = marker;
+ BinaryPrimitives.WriteUInt16BigEndian(head[2..], (ushort)(payload.Length + 2));
+ stream.Write(head);
+ stream.Write(payload);
+ }
+
+ /// <summary>
+ /// Scales a base table to a quality (the IJG rule) into byte entries, and into the reciprocals in zig-zag order
+ /// with the AAN output scaling folded in (<see cref="Dct8x8.AanScale"/>): quantised = round(aanOut × divisor).
+ /// </summary>
+ private static void ScaleTables(int quality, ReadOnlySpan<byte> baseTable, byte[] table, float[] divisorsZ)
+ {
+ int scale = quality < 50 ? 5000 / quality : 200 - 2 * quality;
+ for (int i = 0; i < 64; i++)
+ {
+ table[i] = (byte)Math.Clamp((baseTable[i] * scale + 50) / 100, 1, 255);
+ }
+ for (int i = 0; i < 64; i++)
+ {
+ int natural = Dct8x8.ZigZag[i];
+ int v = natural / 8;
+ int u = natural % 8;
+ divisorsZ[i] = (float)(1.0 / (table[natural] * Dct8x8.AanScale[u] * Dct8x8.AanScale[v] * 8.0));
+ }
+ }
+
+ /// <summary>A row's output bytes.</summary>
+ private sealed class RowBuffer(int capacity)
+ {
+ public byte[] Bytes = new byte[capacity];
+ public int Count;
+ }
+
+ /// <summary>
+ /// The entropy coder's bit sink: fields of up to 32 bits go into a 64-bit accumulator, which is emptied four
+ /// bytes at a time with the 0x00 after every 0xFF the JPEG syntax wants; the buffer grows as needed.
+ /// </summary>
+ private ref struct BitSink(RowBuffer row)
+ {
+ private readonly RowBuffer _row = row;
+ private ulong _acc;
+ private int _bits;
+
+ public void Write(ulong field, int length)
+ {
+ _acc = (_acc << length) | field;
+ _bits += length;
+ if (_bits >= 32)
+ {
+ Flush();
+ }
+ }
+
+ /// <summary>Moves whole bytes out of the accumulator.</summary>
+ private void Flush()
+ {
+ byte[] bytes = _row.Bytes;
+ int count = _row.Count;
+ if (count + 16 > bytes.Length)
+ {
+ Array.Resize(ref _row.Bytes, bytes.Length * 2);
+ bytes = _row.Bytes;
+ }
+ while (_bits >= 8)
+ {
+ _bits -= 8;
+ byte b = (byte)(_acc >> _bits);
+ bytes[count++] = b;
+ if (b == 0xFF)
+ {
+ bytes[count++] = 0;
+ }
+ }
+ _row.Count = count;
+ }
+
+ /// <summary>Pads to a byte with one bits (the rule before a marker) and empties the accumulator.</summary>
+ public void Finish()
+ {
+ int pad = (8 - _bits % 8) % 8;
+ if (pad > 0)
+ {
+ Write((1UL << pad) - 1, pad);
+ }
+ Flush();
+ }
+ }
+
+ // Annex K.1: the luminance quantisation table, row-major
+ private static ReadOnlySpan<byte> LumaBase =>
+ [
+ 16, 11, 10, 16, 24, 40, 51, 61,
+ 12, 12, 14, 19, 26, 58, 60, 55,
+ 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62,
+ 18, 22, 37, 56, 68, 109, 103, 77,
+ 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101,
+ 72, 92, 95, 98, 112, 100, 103, 99,
+ ];
+
+ // Annex K.2: the chrominance quantisation table, row-major
+ private static ReadOnlySpan<byte> ChromaBase =>
+ [
+ 17, 18, 24, 47, 99, 99, 99, 99,
+ 18, 21, 26, 66, 99, 99, 99, 99,
+ 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ ];
+
+ // Annex K.3 to K.6: the standard Huffman tables as (codes per length 1..16, symbols), expanded to code/length per symbol
+ private static readonly byte[] LumaDcCounts = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
+ private static readonly byte[] LumaDcSymbols = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
+ private static readonly byte[] ChromaDcCounts = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
+ private static readonly byte[] ChromaDcSymbols = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
+ private static readonly byte[] LumaAcCounts = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D];
+ private static readonly byte[] LumaAcSymbols =
+ [
+ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
+ 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
+ 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
+ 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
+ 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
+ 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
+ 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
+ 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
+ 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
+ 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
+ 0xF9, 0xFA,
+ ];
+ private static readonly byte[] ChromaAcCounts = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
+ private static readonly byte[] ChromaAcSymbols =
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
+ 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0,
+ 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26,
+ 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
+ 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
+ 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+ 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5,
+ 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3,
+ 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA,
+ 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
+ 0xF9, 0xFA,
+ ];
+
+ private static readonly ushort[] LumaDcCodes = new ushort[256];
+ private static readonly byte[] LumaDcLengths = new byte[256];
+ private static readonly ushort[] ChromaDcCodes = new ushort[256];
+ private static readonly byte[] ChromaDcLengths = new byte[256];
+ private static readonly ushort[] LumaAcCodes = new ushort[256];
+ private static readonly byte[] LumaAcLengths = new byte[256];
+ private static readonly ushort[] ChromaAcCodes = new ushort[256];
+ private static readonly byte[] ChromaAcLengths = new byte[256];
+
+ static JpegEncoder()
+ {
+ Expand(LumaDcCounts, LumaDcSymbols, LumaDcCodes, LumaDcLengths);
+ Expand(ChromaDcCounts, ChromaDcSymbols, ChromaDcCodes, ChromaDcLengths);
+ Expand(LumaAcCounts, LumaAcSymbols, LumaAcCodes, LumaAcLengths);
+ Expand(ChromaAcCounts, ChromaAcSymbols, ChromaAcCodes, ChromaAcLengths);
+ }
+
+ /// <summary>A JPEG Huffman table from its DHT form (counts per code length, then the symbols) to code and length per symbol, per Annex C.</summary>
+ private static void Expand(byte[] counts, byte[] symbols, ushort[] codes, byte[] lengths)
+ {
+ int code = 0;
+ int k = 0;
+ for (int length = 1; length <= 16; length++)
+ {
+ for (int i = 0; i < counts[length - 1]; i++)
+ {
+ codes[symbols[k]] = (ushort)code;
+ lengths[symbols[k]] = (byte)length;
+ k++;
+ code++;
+ }
+ code <<= 1;
+ }
+ }
+}
diff --git a/WaveDude/Export/MediaFoundation.cs b/WaveDude/Export/MediaFoundation.cs
new file mode 100644
index 0000000..0a1b793
--- /dev/null
+++ b/WaveDude/Export/MediaFoundation.cs
@@ -0,0 +1,479 @@
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// The slice of Media Foundation <see cref="Mp4Writer"/> uses: the flat functions of <c>mfplat.dll</c> and
+/// <c>mfreadwrite.dll</c>, hand-written COM interfaces with the vtable order of the SDK headers (a derived
+/// COM interface in .NET does not inherit its base's slots, so each one lists every method from
+/// <c>IUnknown</c> on, unused ones as placeholders), and the attribute GUIDs. All methods return HRESULTs;
+/// <see cref="Check"/> turns a failure into the matching exception. Windows only.
+/// </summary>
+[SupportedOSPlatform("windows")]
+internal static class MediaFoundation
+{
+ /// <summary><c>MF_VERSION</c> of the Windows 7 and later SDK (SDK version 2, API version 0x70).</summary>
+ public const int Version = 0x00020070;
+
+ /// <summary><c>eAVEncCommonRateControlMode_Quality</c>.</summary>
+ public const int RateControlQuality = 3;
+
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFStartup(int version, int flags);
+
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFShutdown();
+
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFCreateMediaType(ref IntPtr mediaType);
+
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFCreateAttributes(ref IntPtr attributes, int initialSize);
+
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFCreateSample(ref IntPtr sample);
+
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFCreateMemoryBuffer(int maxLength, ref IntPtr buffer);
+
+ [DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
+ public static extern int MFCreateSinkWriterFromURL(string url, IntPtr byteStream, IntPtr attributes, ref IntPtr writer);
+
+ /// <summary><c>MFTEnumEx</c>: the registered transforms of a category matching the type filters; the caller releases each activate and frees the array.</summary>
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFTEnumEx([MarshalAs(UnmanagedType.LPStruct)] Guid category, uint flags, IntPtr inputType, IntPtr outputType, out IntPtr activates, out uint count);
+
+ [DllImport("ole32.dll", ExactSpelling = true)]
+ public static extern void CoTaskMemFree(IntPtr ptr);
+
+ /// <summary><c>MFCreateDXGIDeviceManager</c>: the object through which Media Foundation shares a Direct3D 11 device with hardware transforms.</summary>
+ [DllImport("mfplat.dll", ExactSpelling = true)]
+ public static extern int MFCreateDXGIDeviceManager(out uint resetToken, out IntPtr manager);
+
+ /// <summary><c>D3D11CreateDevice</c> on the default hardware adapter.</summary>
+ [DllImport("d3d11.dll", ExactSpelling = true)]
+ public static extern int D3D11CreateDevice(IntPtr adapter, int driverType, IntPtr software, uint flags, IntPtr featureLevels, uint featureLevelCount, uint sdkVersion, out IntPtr device, out int featureLevel, out IntPtr immediateContext);
+
+ /// <summary><c>MF_SINK_WRITER_D3D_MANAGER</c>: the device manager the writer hands its transforms.</summary>
+ public static readonly Guid SinkWriterD3DManager = new("ec822da2-e1e9-4b29-a0d8-563c719f5269");
+
+ /// <summary>
+ /// A Direct3D 11 device (video support, BGRA, multithread-protected) wrapped in a DXGI device manager for the
+ /// sink writer; both released by <see cref="ReleaseDeviceManager"/>. Null when Direct3D refuses.
+ /// </summary>
+ public static (IntPtr Manager, IntPtr Device)? CreateDeviceManager()
+ {
+ const int DriverTypeHardware = 1;
+ const uint CreateDeviceBgraSupport = 0x20;
+ const uint CreateDeviceVideoSupport = 0x800;
+ const uint SdkVersion = 7;
+ if (D3D11CreateDevice(IntPtr.Zero, DriverTypeHardware, IntPtr.Zero, CreateDeviceBgraSupport | CreateDeviceVideoSupport, IntPtr.Zero, 0, SdkVersion, out IntPtr device, out _, out IntPtr context) < 0)
+ {
+ return null;
+ }
+ Marshal.Release(context);
+ try
+ {
+ // Media Foundation's transforms use the device from their own threads
+ var multithread = (ID3D10Multithread)Marshal.GetObjectForIUnknown(device);
+ try
+ {
+ multithread.SetMultithreadProtected(1);
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(multithread);
+ }
+ Check(MFCreateDXGIDeviceManager(out uint token, out IntPtr manager));
+ var dxgi = (IMFDXGIDeviceManager)Marshal.GetObjectForIUnknown(manager);
+ try
+ {
+ Check(dxgi.ResetDevice(device, token));
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(dxgi);
+ }
+ return (manager, device);
+ }
+ catch
+ {
+ Marshal.Release(device);
+ throw;
+ }
+ }
+
+ /// <summary>Releases what <see cref="CreateDeviceManager"/> made.</summary>
+ public static void ReleaseDeviceManager((IntPtr Manager, IntPtr Device) pair)
+ {
+ Marshal.Release(pair.Manager);
+ Marshal.Release(pair.Device);
+ }
+
+ /// <summary>Sets an IUnknown attribute.</summary>
+ public static void SetUnknown(IntPtr attributes, Guid key, IntPtr value)
+ {
+ var store = (IMFAttributes)Marshal.GetObjectForIUnknown(attributes);
+ try
+ {
+ Check(store.SetUnknown(key, value));
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ /// <summary><c>ID3D10Multithread</c>: the device's lock for use from several threads.</summary>
+ [Guid("9B7E4E00-342C-4106-A19F-4F2704F689F0")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface ID3D10Multithread
+ {
+ [PreserveSig] void Enter();
+ [PreserveSig] void Leave();
+ [PreserveSig] int SetMultithreadProtected(int protect);
+ [PreserveSig] int GetMultithreadProtected();
+ }
+
+ /// <summary><c>IMFDXGIDeviceManager</c>; only <c>ResetDevice</c> (slot 5) is called.</summary>
+ [Guid("eb533d5d-2db6-40f8-97a9-494692014f07")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFDXGIDeviceManager
+ {
+ [PreserveSig] int CloseDeviceHandle();
+ [PreserveSig] int GetVideoService();
+ [PreserveSig] int LockDevice();
+ [PreserveSig] int OpenDeviceHandle();
+ [PreserveSig] int ResetDevice(IntPtr device, uint resetToken);
+ [PreserveSig] int TestDevice();
+ [PreserveSig] int UnlockDevice();
+ }
+
+ /// <summary><c>MFT_CATEGORY_VIDEO_ENCODER</c>.</summary>
+ public static readonly Guid VideoEncoderCategory = new("f79eac7d-e545-4387-bdee-d647d7bde42a");
+
+ /// <summary><c>MFT_FRIENDLY_NAME_Attribute</c>: the transform's display name.</summary>
+ public static readonly Guid FriendlyName = new("314ffbae-5b41-4c95-9c19-4e7d586face3");
+
+ /// <summary><c>MFT_ENUM_FLAG_HARDWARE</c>.</summary>
+ public const uint EnumHardware = 0x4;
+
+ /// <summary><c>MFT_ENUM_FLAG_SYNCMFT | ASYNCMFT | HARDWARE | SORTANDFILTER</c>: everything, best first.</summary>
+ public const uint EnumAll = 0x1 | 0x2 | 0x4 | 0x40;
+
+ /// <summary>The friendly name of a transform or activate (both carry attributes), or null.</summary>
+ public static string? FriendlyNameOf(IntPtr unknown)
+ {
+ object rcw = Marshal.GetObjectForIUnknown(unknown);
+ try
+ {
+ if (rcw is IMFAttributes attributes && attributes.GetAllocatedString(FriendlyName, out IntPtr text, out _) >= 0 && text != IntPtr.Zero)
+ {
+ string? name = Marshal.PtrToStringUni(text);
+ CoTaskMemFree(text);
+ return name;
+ }
+ if (rcw is IMFTransform transform && transform.GetAttributes(out IntPtr attributesPtr) >= 0 && attributesPtr != IntPtr.Zero)
+ {
+ try
+ {
+ return FriendlyNameOf(attributesPtr);
+ }
+ finally
+ {
+ Marshal.Release(attributesPtr);
+ }
+ }
+ return null;
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(rcw);
+ }
+ }
+
+ /// <summary>The names of the registered H.264 encoder transforms, hardware ones first (<c>MFTEnumEx</c>), for the log.</summary>
+ public static List<string> H264Encoders(bool hardwareOnly)
+ {
+ var names = new List<string>();
+ IntPtr outputType = Marshal.AllocHGlobal(32);
+ try
+ {
+ Marshal.Copy(VideoType.ToByteArray(), 0, outputType, 16);
+ Marshal.Copy(H264Format.ToByteArray(), 0, outputType + 16, 16);
+ if (MFTEnumEx(VideoEncoderCategory, hardwareOnly ? EnumHardware : EnumAll, IntPtr.Zero, outputType, out IntPtr activates, out uint count) < 0 || activates == IntPtr.Zero)
+ {
+ return names;
+ }
+ for (int i = 0; i < count; i++)
+ {
+ IntPtr activate = Marshal.ReadIntPtr(activates, i * IntPtr.Size);
+ names.Add(FriendlyNameOf(activate) ?? "(unnamed transform)");
+ Marshal.Release(activate);
+ }
+ CoTaskMemFree(activates);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(outputType);
+ }
+ return names;
+ }
+
+ /// <summary>Throws for a failed HRESULT.</summary>
+ public static void Check(int hr)
+ {
+ if (hr < 0)
+ {
+ Marshal.ThrowExceptionForHR(hr);
+ }
+ }
+
+ /// <summary>A new, empty attribute store; the caller releases the pointer.</summary>
+ public static IntPtr CreateAttributes()
+ {
+ IntPtr attributes = IntPtr.Zero;
+ Check(MFCreateAttributes(ref attributes, 8));
+ return attributes;
+ }
+
+ /// <summary>Sets a UINT32 attribute on an attribute store or media type (both implement <c>IMFAttributes</c>).</summary>
+ public static void SetUInt32(IntPtr attributes, Guid key, int value)
+ {
+ var store = (IMFAttributes)Marshal.GetObjectForIUnknown(attributes);
+ try
+ {
+ Check(store.SetUINT32(key, value));
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ /// <summary>Sets a UINT64 attribute.</summary>
+ public static void SetUInt64(IntPtr attributes, Guid key, ulong value)
+ {
+ var store = (IMFAttributes)Marshal.GetObjectForIUnknown(attributes);
+ try
+ {
+ Check(store.SetUINT64(key, value));
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ /// <summary>Sets a GUID attribute.</summary>
+ public static void SetGuid(IntPtr attributes, Guid key, Guid value)
+ {
+ var store = (IMFAttributes)Marshal.GetObjectForIUnknown(attributes);
+ try
+ {
+ Check(store.SetGUID(key, value));
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ // media type attributes
+ public static readonly Guid MajorType = new("48eba18e-f8c9-4687-bf11-0a74c9f96a8f");
+ public static readonly Guid SubType = new("f7e34c9a-42e8-4714-b74b-cb29d72c35e5");
+ public static readonly Guid AvgBitrate = new("20332624-fb0d-4d9e-bd0d-cbf6786c102e");
+ public static readonly Guid InterlaceMode = new("e2724bb8-e676-4806-b4b2-a8d6efb44ccd");
+ public static readonly Guid FrameSize = new("1652c33d-d6b2-4012-b834-72030849a37d");
+ public static readonly Guid FrameRate = new("c459a2e8-3d2c-4e44-b132-fee5156c7bb0");
+ public static readonly Guid PixelAspectRatio = new("c6376a1e-8d0a-4027-be45-6d9a0ad39bb6");
+ public static readonly Guid DefaultStride = new("644b4e48-1e02-4516-b0eb-c01ca9d49ac6");
+ public static readonly Guid VideoType = new("73646976-0000-0010-8000-00AA00389B71");
+ public static readonly Guid H264Format = new("34363248-0000-0010-8000-00AA00389B71");
+ public static readonly Guid Rgb32Format = new("00000016-0000-0010-8000-00AA00389B71");
+ /// <summary><c>MFVideoFormat_NV12</c> ('NV12'): a Y plane, then interleaved Cb/Cr at half resolution, what the hardware encoders take natively.</summary>
+ public static readonly Guid Nv12Format = new("3231564E-0000-0010-8000-00AA00389B71");
+ /// <summary><c>MF_MT_VIDEO_NOMINAL_RANGE</c>: 2 = studio range 16..235.</summary>
+ public static readonly Guid NominalRange = new("c21b8ee5-b956-4071-8daf-325edf5cab11");
+
+ /// <summary><c>MF_SINK_WRITER_DISABLE_THROTTLING</c>: the writer takes samples as fast as they come instead of pacing the caller.</summary>
+ public static readonly Guid DisableThrottling = new("08b845d8-2b74-4afe-9d53-be16d2d5ae4f");
+
+ /// <summary><c>MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS</c>: let the sink writer pick a hardware encoder.</summary>
+ public static readonly Guid EnableHardwareTransforms = new("a634a91c-822b-41b9-a494-4de4643612b0");
+
+ // encoder properties (ICodecAPI), passed as the sink writer's encoding parameters
+ /// <summary><c>CODECAPI_AVEncCommonRateControlMode</c>.</summary>
+ public static readonly Guid CodecRateControlMode = new("1c0608e9-370c-4710-8a58-cb6181c42423");
+ /// <summary><c>CODECAPI_AVEncCommonQuality</c>, 0..100.</summary>
+ public static readonly Guid CodecQuality = new("fcbf57a3-7ea5-4b0c-9644-69b40c39c391");
+ /// <summary><c>CODECAPI_AVEncMPVGOPSize</c>.</summary>
+ public static readonly Guid CodecGopSize = new("95f31b26-95a4-41aa-9303-246a7fc6eef1");
+ /// <summary><c>CODECAPI_AVEncMPVDefaultBPictureCount</c>.</summary>
+ public static readonly Guid CodecBPictureCount = new("8d390aeb-b9cd-47e5-8f82-ac7e3ff6a7a0");
+ /// <summary><c>CODECAPI_AVEncCommonQualityVsSpeed</c>, 0 (fastest) to 100 (best).</summary>
+ public static readonly Guid CodecQualityVsSpeed = new("98332df8-03cd-476b-89fa-3f9e442dec9f");
+ /// <summary><c>CODECAPI_AVLowLatencyMode</c> (the same GUID as <c>MF_LOW_LATENCY</c>).</summary>
+ public static readonly Guid CodecLowLatency = new("9c27891a-ed7a-40e1-88e8-b22727a024ee");
+ /// <summary><c>CODECAPI_AVEncCommonRealTime</c>: the encoder must keep up with real time rather than take its time.</summary>
+ public static readonly Guid CodecRealTime = new("143a0ff6-a131-43da-b81e-98fbb8ec378e");
+
+ /// <summary><c>IMFAttributes</c>; only the three setters are called.</summary>
+ [Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFAttributes
+ {
+ [PreserveSig] int GetItem();
+ [PreserveSig] int GetItemType();
+ [PreserveSig] int CompareItem();
+ [PreserveSig] int Compare();
+ [PreserveSig] int GetUINT32();
+ [PreserveSig] int GetUINT64();
+ [PreserveSig] int GetDouble();
+ [PreserveSig] int GetGUID();
+ [PreserveSig] int GetStringLength();
+ [PreserveSig] int GetString();
+ [PreserveSig] int GetAllocatedString([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr value, out int length);
+ [PreserveSig] int GetBlobSize();
+ [PreserveSig] int GetBlob();
+ [PreserveSig] int GetAllocatedBlob();
+ [PreserveSig] int GetUnknown();
+ [PreserveSig] int SetItem();
+ [PreserveSig] int DeleteItem();
+ [PreserveSig] int DeleteAllItems();
+ [PreserveSig] int SetUINT32([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int value);
+ [PreserveSig] int SetUINT64([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, ulong value);
+ [PreserveSig] int SetDouble();
+ [PreserveSig] int SetGUID([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPStruct)] Guid value);
+ [PreserveSig] int SetString();
+ [PreserveSig] int SetBlob();
+ [PreserveSig] int SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value);
+ [PreserveSig] int LockStore();
+ [PreserveSig] int UnlockStore();
+ [PreserveSig] int GetCount();
+ [PreserveSig] int GetItemByIndex();
+ [PreserveSig] int CopyAllItems();
+ }
+
+ /// <summary><c>IMFSinkWriter</c>; <c>Finalize</c> is named <see cref="FinalizeWriting"/> to keep clear of <see cref="object.Finalize"/>.</summary>
+ [Guid("3137F1CD-FE5E-4805-A5D8-FB477448CB3D")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFSinkWriter
+ {
+ [PreserveSig] int AddStream(IntPtr mediaType, ref int streamIndex);
+ [PreserveSig] int SetInputMediaType(int streamIndex, IntPtr mediaType, IntPtr encodingParameters);
+ [PreserveSig] int BeginWriting();
+ [PreserveSig] int WriteSample(int streamIndex, IntPtr sample);
+ [PreserveSig] int SendStreamTick();
+ [PreserveSig] int PlaceMarker();
+ [PreserveSig] int NotifyEndOfSegment();
+ [PreserveSig] int Flush();
+ [PreserveSig] int FinalizeWriting();
+ [PreserveSig] int GetServiceForStream();
+ [PreserveSig] int GetStatistics();
+ }
+
+ /// <summary><c>IMFSinkWriterEx</c>: <c>IMFSinkWriter</c>'s slots, then <c>GetTransformForStream</c>, which tells which transforms (converter, encoder) serve a stream.</summary>
+ [Guid("588d72ab-5bc1-496a-8714-b70617141b25")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFSinkWriterEx
+ {
+ [PreserveSig] int AddStream(IntPtr mediaType, ref int streamIndex);
+ [PreserveSig] int SetInputMediaType(int streamIndex, IntPtr mediaType, IntPtr encodingParameters);
+ [PreserveSig] int BeginWriting();
+ [PreserveSig] int WriteSample(int streamIndex, IntPtr sample);
+ [PreserveSig] int SendStreamTick();
+ [PreserveSig] int PlaceMarker();
+ [PreserveSig] int NotifyEndOfSegment();
+ [PreserveSig] int Flush();
+ [PreserveSig] int FinalizeWriting();
+ [PreserveSig] int GetServiceForStream();
+ [PreserveSig] int GetStatistics();
+ [PreserveSig] int GetTransformForStream(int streamIndex, int transformIndex, out Guid category, out IntPtr transform);
+ }
+
+ /// <summary><c>IMFTransform</c>; only <c>GetAttributes</c> (slot 6) is called.</summary>
+ [Guid("bf94c121-5b05-4e6f-8000-ba598961414d")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFTransform
+ {
+ [PreserveSig] int GetStreamLimits();
+ [PreserveSig] int GetStreamCount();
+ [PreserveSig] int GetStreamIDs();
+ [PreserveSig] int GetInputStreamInfo();
+ [PreserveSig] int GetOutputStreamInfo();
+ [PreserveSig] int GetAttributes(out IntPtr attributes);
+ }
+
+ /// <summary><c>IMFMediaBuffer</c>.</summary>
+ [Guid("045FA593-8799-42B8-BC8D-8968C6453507")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFMediaBuffer
+ {
+ [PreserveSig] int Lock(ref IntPtr data, ref int maxLength, ref int currentLength);
+ [PreserveSig] int Unlock();
+ [PreserveSig] int GetCurrentLength();
+ [PreserveSig] int SetCurrentLength(int length);
+ [PreserveSig] int GetMaxLength();
+ }
+
+ /// <summary><c>IMFSample</c>: the 30 <c>IMFAttributes</c> slots first (placeholders), then its own methods.</summary>
+ [Guid("C40A00F2-B93A-4D80-AE8C-5A1C634F58E4")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ public interface IMFSample
+ {
+ [PreserveSig] int A01();
+ [PreserveSig] int A02();
+ [PreserveSig] int A03();
+ [PreserveSig] int A04();
+ [PreserveSig] int A05();
+ [PreserveSig] int A06();
+ [PreserveSig] int A07();
+ [PreserveSig] int A08();
+ [PreserveSig] int A09();
+ [PreserveSig] int A10();
+ [PreserveSig] int A11();
+ [PreserveSig] int A12();
+ [PreserveSig] int A13();
+ [PreserveSig] int A14();
+ [PreserveSig] int A15();
+ [PreserveSig] int A16();
+ [PreserveSig] int A17();
+ [PreserveSig] int A18();
+ [PreserveSig] int A19();
+ [PreserveSig] int A20();
+ [PreserveSig] int A21();
+ [PreserveSig] int A22();
+ [PreserveSig] int A23();
+ [PreserveSig] int A24();
+ [PreserveSig] int A25();
+ [PreserveSig] int A26();
+ [PreserveSig] int A27();
+ [PreserveSig] int A28();
+ [PreserveSig] int A29();
+ [PreserveSig] int A30();
+ [PreserveSig] int GetSampleFlags();
+ [PreserveSig] int SetSampleFlags();
+ [PreserveSig] int GetSampleTime();
+ [PreserveSig] int SetSampleTime(long time);
+ [PreserveSig] int GetSampleDuration();
+ [PreserveSig] int SetSampleDuration(long duration);
+ [PreserveSig] int GetBufferCount();
+ [PreserveSig] int GetBufferByIndex();
+ [PreserveSig] int ConvertToContiguousBuffer();
+ [PreserveSig] int AddBuffer(IntPtr buffer);
+ [PreserveSig] int RemoveBufferByIndex();
+ [PreserveSig] int RemoveAllBuffers();
+ [PreserveSig] int GetTotalLength();
+ [PreserveSig] int CopyToBuffer();
+ }
+}
diff --git a/WaveDude/Export/Mp4Writer.cs b/WaveDude/Export/Mp4Writer.cs
new file mode 100644
index 0000000..957eef8
--- /dev/null
+++ b/WaveDude/Export/Mp4Writer.cs
@@ -0,0 +1,488 @@
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using NLog;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes H.264 MP4 through the Media Foundation sink writer that ships with Windows (<c>mfplat.dll</c>,
+/// <c>mfreadwrite.dll</c>, talked to through the hand-written COM interfaces in <see cref="MediaFoundation"/>),
+/// so no package or codec is installed: the only export format with a dependency outside the library, and
+/// that one is the operating system's. Hardware encoders are allowed (this machine's NVENC), the encoder
+/// is asked for quality-based rate control with the project's 1..100 (the software encoder honours it, the
+/// bitrate from the author's bits-per-pixel rule stays the fallback), no B-frames and a one-second GOP so
+/// the file scrubs cleanly. Odd sizes are padded by repeating the last row or column (H.264 needs even
+/// sizes; the author cropped). A failing constructor means "no H.264 on this machine" (Windows N without
+/// the Media Feature Pack, or a size the encoder refuses). Windows only; one thread at a time.
+/// </summary>
+[SupportedOSPlatform("windows")]
+public sealed class Mp4Writer : IFrameSink
+{
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+
+ /// <summary>Largest picture the software encoder of Windows takes (4096 × 2304); hardware encoders may do more, but this is the safe limit.</summary>
+ public const long MaxPixels = 4096L * 2304L;
+
+ private readonly int _encodedWidth;
+ private readonly int _encodedHeight;
+ private readonly int[]? _padded;
+ private readonly int _fps;
+ private readonly YuvPlanes _planes;
+ private bool _nv12;
+ private IntPtr _writerPtr;
+ private (IntPtr Manager, IntPtr Device)? _d3d;
+ private MediaFoundation.IMFSinkWriter? _writer;
+ private bool _started;
+ private bool _closed;
+
+ /// <param name="path">Output .mp4 path; an existing file is replaced.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="framesPerSecond">Playback frame rate.</param>
+ /// <param name="quality">1..100: the encoder's quality setting, and the bitrate fallback.</param>
+ /// <exception cref="NotSupportedException">The size is below 16 × 16 or above <see cref="MaxPixels"/>.</exception>
+ /// <exception cref="COMException">Media Foundation refused (not installed, no H.264 encoder, bad path).</exception>
+ public Mp4Writer(string path, int width, int height, int framesPerSecond, int quality)
+ {
+ Width = width;
+ Height = height;
+ Output = path;
+ _fps = Math.Max(1, framesPerSecond);
+ _encodedWidth = (width + 1) & ~1;
+ _encodedHeight = (height + 1) & ~1;
+ if (_encodedWidth < 16 || _encodedHeight < 16)
+ {
+ throw new NotSupportedException("The picture is too small for H.264 video (16 × 16 at least).");
+ }
+ if ((long)_encodedWidth * _encodedHeight > MaxPixels)
+ {
+ throw new NotSupportedException("The picture is too large for the H.264 encoder of Windows (4096 × 2304 at most).");
+ }
+ if (_encodedWidth != width || _encodedHeight != height)
+ {
+ _padded = new int[_encodedWidth * _encodedHeight];
+ }
+ _planes = new YuvPlanes(_encodedWidth, _encodedHeight, studioRange: true);
+ if (File.Exists(path))
+ {
+ File.Delete(path); // the sink writer appends to nothing, but a stale file must not survive a failure
+ }
+ Quality = Math.Clamp(quality, 1, 100);
+ MediaFoundation.Check(MediaFoundation.MFStartup(MediaFoundation.Version, 0));
+ _started = true;
+ try
+ {
+ IntPtr writerAttributes = MediaFoundation.CreateAttributes();
+ try
+ {
+ MediaFoundation.SetUInt32(writerAttributes, MediaFoundation.EnableHardwareTransforms, 1);
+ if (!Throttle)
+ {
+ MediaFoundation.SetUInt32(writerAttributes, MediaFoundation.DisableThrottling, 1);
+ }
+ if (UseDirect3D)
+ {
+ // a Direct3D device for the hardware encoder: with one, the writer moves the samples into textures and the
+ // transform runs asynchronously instead of being driven one sample at a time through system memory
+ try
+ {
+ _d3d = MediaFoundation.CreateDeviceManager();
+ if (_d3d is { } d3d)
+ {
+ MediaFoundation.SetUnknown(writerAttributes, MediaFoundation.SinkWriterD3DManager, d3d.Manager);
+ }
+ }
+ catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException)
+ {
+ Logger.Debug("No Direct3D device for the encoder: {Message}", ex.Message);
+ _d3d = null;
+ }
+ }
+ MediaFoundation.Check(MediaFoundation.MFCreateSinkWriterFromURL(path, IntPtr.Zero, writerAttributes, ref _writerPtr));
+ }
+ finally
+ {
+ Marshal.Release(writerAttributes);
+ }
+ _writer = (MediaFoundation.IMFSinkWriter)Marshal.GetObjectForIUnknown(_writerPtr);
+ // the author's bitrate rule: 0.01 × 50^(quality/100) bits per pixel (0.15 at 70), 300 kbit/s to 200 Mbit/s
+ double bitsPerPixel = 0.01 * Math.Pow(50.0, Quality / 100.0);
+ long bitrate = (long)Math.Round((double)_encodedWidth * _encodedHeight * _fps * bitsPerPixel);
+ Bitrate = (int)Math.Clamp(bitrate, 300_000L, 200_000_000L);
+ IntPtr outputType = MakeType(MediaFoundation.H264Format, Bitrate, topDown: false);
+ int streamIndex = 0;
+ try
+ {
+ MediaFoundation.Check(_writer.AddStream(outputType, ref streamIndex));
+ }
+ finally
+ {
+ Marshal.Release(outputType);
+ }
+ // quality mode, no B-frames, a GOP per second; an encoder that rejects them gets the bitrate alone
+ IntPtr parameters = MediaFoundation.CreateAttributes();
+ try
+ {
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecRateControlMode, MediaFoundation.RateControlQuality);
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecQuality, Quality);
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecGopSize, _fps);
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecBPictureCount, 0);
+ if (Fastest)
+ {
+ // the encoder's fastest path: speed over quality, low latency, real time
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecQualityVsSpeed, 0);
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecLowLatency, 1);
+ MediaFoundation.SetUInt32(parameters, MediaFoundation.CodecRealTime, 1);
+ }
+ // NV12 first, converted here on every core: with RGB32 the writer puts its own colour converter before the
+ // encoder, one thread for a whole frame, which held the hardware encoder to 60 frames a second (2026-10-15)
+ IntPtr wanted = QualityMode ? parameters : IntPtr.Zero;
+ UsedBitrateOnly = !QualityMode;
+ _nv12 = PreferNv12 && TrySetInput(streamIndex, MediaFoundation.Nv12Format, wanted);
+ if (!_nv12 && !TrySetInput(streamIndex, MediaFoundation.Rgb32Format, wanted))
+ {
+ _nv12 = TrySetInput(streamIndex, MediaFoundation.Nv12Format, IntPtr.Zero);
+ if (!_nv12)
+ {
+ IntPtr rgb = MakeType(MediaFoundation.Rgb32Format, 0, topDown: true);
+ try
+ {
+ MediaFoundation.Check(_writer.SetInputMediaType(streamIndex, rgb, IntPtr.Zero));
+ }
+ finally
+ {
+ Marshal.Release(rgb);
+ }
+ }
+ UsedBitrateOnly = true;
+ }
+ }
+ finally
+ {
+ Marshal.Release(parameters);
+ }
+ MediaFoundation.Check(_writer.BeginWriting());
+ Transforms = DescribeTransforms(streamIndex);
+ Logger.Debug("MP4: {Input} in, {Transforms}, {D3D}; quality {Quality}, average bitrate {Bitrate} bit/s{Note}", _nv12 ? "NV12" : "RGB32", Transforms, _d3d != null ? "Direct3D device shared" : "system memory", Quality, Bitrate, UsedBitrateOnly ? ", the encoder took no quality parameters" : "");
+ }
+ catch
+ {
+ Cleanup();
+ throw;
+ }
+ }
+
+ /// <summary>The transforms the sink writer put behind the stream (a colour converter, the encoder), by their friendly names.</summary>
+ public string Transforms { get; private set; } = "";
+
+ /// <summary>Whether the sink writer paces <c>WriteSample</c> (its default); off, samples queue up to the encoder's speed. For the bench.</summary>
+ public static bool Throttle { get; set; } = true;
+
+ /// <summary>Whether the encoder is asked for its fastest path (quality-versus-speed 0, low latency, real time); for the bench's comparison.</summary>
+ public static bool Fastest { get; set; }
+
+ /// <summary>Whether a Direct3D 11 device is handed to the writer for the hardware encoder (the default); off for the bench's comparison.</summary>
+ public static bool UseDirect3D { get; set; } = true;
+
+ /// <summary>Whether the writer got a Direct3D device.</summary>
+ public bool HasDirect3D => _d3d != null;
+
+ /// <summary>Whether NV12 input is tried first (the default); off, the frames go in as RGB32 and the writer converts. For the bench.</summary>
+ public static bool PreferNv12 { get; set; } = true;
+
+ /// <summary>Whether the quality rate control is asked for (the default); off, the encoder gets the average bitrate alone. For the bench.</summary>
+ public static bool QualityMode { get; set; } = true;
+
+ /// <summary>Whether the frames go in as NV12 (converted here) rather than RGB32 (converted by the writer).</summary>
+ public bool Nv12Input => _nv12;
+
+ /// <summary>Sets the input type of the stream; false when the writer refused it (with or without the encoding parameters).</summary>
+ private bool TrySetInput(int streamIndex, Guid format, IntPtr parameters)
+ {
+ IntPtr inputType = MakeType(format, 0, topDown: format == MediaFoundation.Rgb32Format);
+ try
+ {
+ if (format == MediaFoundation.Nv12Format)
+ {
+ MediaFoundation.SetUInt32(inputType, MediaFoundation.NominalRange, 2); // studio range, what the planes produce
+ }
+ return _writer!.SetInputMediaType(streamIndex, inputType, parameters) >= 0;
+ }
+ finally
+ {
+ Marshal.Release(inputType);
+ }
+ }
+
+ /// <summary>The registered H.264 encoders, hardware ones only or all, for the log (empty when Media Foundation is absent).</summary>
+ public static IReadOnlyList<string> AvailableEncoders(bool hardwareOnly)
+ {
+ try
+ {
+ MediaFoundation.Check(MediaFoundation.MFStartup(MediaFoundation.Version, 0));
+ try
+ {
+ return MediaFoundation.H264Encoders(hardwareOnly);
+ }
+ finally
+ {
+ MediaFoundation.MFShutdown();
+ }
+ }
+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or COMException)
+ {
+ return [];
+ }
+ }
+
+ private string DescribeTransforms(int streamIndex)
+ {
+ if (_writer is not MediaFoundation.IMFSinkWriterEx extended)
+ {
+ return "(not reported)";
+ }
+ var names = new List<string>();
+ for (int i = 0; i < 8; i++)
+ {
+ if (extended.GetTransformForStream(streamIndex, i, out _, out IntPtr transform) < 0 || transform == IntPtr.Zero)
+ {
+ break;
+ }
+ names.Add(MediaFoundation.FriendlyNameOf(transform) ?? "(unnamed transform)");
+ Marshal.Release(transform);
+ }
+ return names.Count == 0 ? "(none reported)" : string.Join(" → ", names);
+ }
+
+ /// <inheritdoc/>
+ public int Width { get; }
+
+ /// <inheritdoc/>
+ public int Height { get; }
+
+ /// <inheritdoc/>
+ public int FrameCount { get; private set; }
+
+ /// <inheritdoc/>
+ public string Output { get; }
+
+ /// <summary>The quality 1..100 the encoder was given.</summary>
+ public int Quality { get; }
+
+ /// <summary>The average bitrate in bits per second from the author's rule (the fallback, and what the output type declares).</summary>
+ public int Bitrate { get; }
+
+ /// <summary>Whether the encoder refused the quality parameters and runs on the bitrate alone.</summary>
+ public bool UsedBitrateOnly { get; private set; }
+
+ /// <summary>Whether Media Foundation is there at all: the libraries load and start (false on Windows N without the Media Feature Pack).</summary>
+ public static bool IsAvailable()
+ {
+ try
+ {
+ if (MediaFoundation.MFStartup(MediaFoundation.Version, 0) < 0)
+ {
+ return false;
+ }
+ MediaFoundation.MFShutdown();
+ return true;
+ }
+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException)
+ {
+ return false;
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Add(ReadOnlySpan<int> pixels)
+ {
+ if (_closed || _writer == null)
+ {
+ throw new InvalidOperationException("The video file is already closed.");
+ }
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the video.", nameof(pixels));
+ }
+ ReadOnlySpan<int> source = pixels[..(Width * Height)];
+ if (_padded != null)
+ {
+ for (int y = 0; y < _encodedHeight; y++)
+ {
+ ReadOnlySpan<int> row = pixels.Slice(Math.Min(y, Height - 1) * Width, Width);
+ Span<int> target = _padded.AsSpan(y * _encodedWidth, _encodedWidth);
+ row.CopyTo(target);
+ if (_encodedWidth > Width)
+ {
+ target[Width] = row[Width - 1];
+ }
+ }
+ source = _padded;
+ }
+ int byteLength = _nv12 ? _encodedWidth * _encodedHeight * 3 / 2 : _encodedWidth * _encodedHeight * 4;
+ if (_nv12)
+ {
+ _planes.Convert(source.ToArray());
+ }
+ IntPtr bufferPtr = IntPtr.Zero;
+ IntPtr samplePtr = IntPtr.Zero;
+ MediaFoundation.IMFMediaBuffer? buffer = null;
+ MediaFoundation.IMFSample? sample = null;
+ try
+ {
+ MediaFoundation.Check(MediaFoundation.MFCreateMemoryBuffer(byteLength, ref bufferPtr));
+ buffer = (MediaFoundation.IMFMediaBuffer)Marshal.GetObjectForIUnknown(bufferPtr);
+ IntPtr data = IntPtr.Zero;
+ int maxLength = 0;
+ int currentLength = 0;
+ MediaFoundation.Check(buffer.Lock(ref data, ref maxLength, ref currentLength));
+ try
+ {
+ unsafe
+ {
+ if (_nv12)
+ {
+ CopyNv12(new Span<byte>((void*)data, byteLength));
+ }
+ else
+ {
+ source.CopyTo(new Span<int>((void*)data, source.Length));
+ }
+ }
+ }
+ finally
+ {
+ buffer.Unlock();
+ }
+ MediaFoundation.Check(buffer.SetCurrentLength(byteLength));
+ MediaFoundation.Check(MediaFoundation.MFCreateSample(ref samplePtr));
+ sample = (MediaFoundation.IMFSample)Marshal.GetObjectForIUnknown(samplePtr);
+ MediaFoundation.Check(sample.AddBuffer(bufferPtr));
+ MediaFoundation.Check(sample.SetSampleTime(FrameCount * 10_000_000L / _fps));
+ MediaFoundation.Check(sample.SetSampleDuration(10_000_000L / _fps));
+ MediaFoundation.Check(_writer.WriteSample(0, samplePtr));
+ FrameCount++;
+ }
+ finally
+ {
+ if (sample != null)
+ {
+ Marshal.ReleaseComObject(sample);
+ }
+ if (samplePtr != IntPtr.Zero)
+ {
+ Marshal.Release(samplePtr);
+ }
+ if (buffer != null)
+ {
+ Marshal.ReleaseComObject(buffer);
+ }
+ if (bufferPtr != IntPtr.Zero)
+ {
+ Marshal.Release(bufferPtr);
+ }
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Close()
+ {
+ if (_closed)
+ {
+ return;
+ }
+ _closed = true;
+ try
+ {
+ if (_writer != null && FrameCount > 0)
+ {
+ MediaFoundation.Check(_writer.FinalizeWriting());
+ }
+ }
+ finally
+ {
+ Cleanup();
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Dispose() => Close();
+
+ /// <summary>The planes as NV12: the Y rows (the planes are padded to 16, the picture is not), then Cb and Cr interleaved at half resolution.</summary>
+ private void CopyNv12(Span<byte> target)
+ {
+ int w = _encodedWidth;
+ int h = _encodedHeight;
+ for (int y = 0; y < h; y++)
+ {
+ _planes.Y.AsSpan(y * _planes.PaddedWidth, w).CopyTo(target.Slice(y * w, w));
+ }
+ Span<byte> uv = target[(w * h)..];
+ int chromaWidth = _planes.ChromaWidth;
+ for (int y = 0; y < h / 2; y++)
+ {
+ ReadOnlySpan<byte> cb = _planes.Cb.AsSpan(y * chromaWidth, w / 2);
+ ReadOnlySpan<byte> cr = _planes.Cr.AsSpan(y * chromaWidth, w / 2);
+ Span<byte> row = uv.Slice(y * w, w);
+ for (int x = 0; x < w / 2; x++)
+ {
+ row[2 * x] = cb[x];
+ row[2 * x + 1] = cr[x];
+ }
+ }
+ }
+
+ /// <summary>A progressive video media type of the encoded size, the frame rate and square pixels; the caller releases it.</summary>
+ private IntPtr MakeType(Guid subtype, int bitrate, bool topDown)
+ {
+ IntPtr mediaType = IntPtr.Zero;
+ MediaFoundation.Check(MediaFoundation.MFCreateMediaType(ref mediaType));
+ try
+ {
+ MediaFoundation.SetGuid(mediaType, MediaFoundation.MajorType, MediaFoundation.VideoType);
+ MediaFoundation.SetGuid(mediaType, MediaFoundation.SubType, subtype);
+ if (bitrate > 0)
+ {
+ MediaFoundation.SetUInt32(mediaType, MediaFoundation.AvgBitrate, bitrate);
+ }
+ MediaFoundation.SetUInt32(mediaType, MediaFoundation.InterlaceMode, 2); // progressive
+ MediaFoundation.SetUInt64(mediaType, MediaFoundation.FrameSize, ((ulong)(uint)_encodedWidth << 32) | (uint)_encodedHeight);
+ MediaFoundation.SetUInt64(mediaType, MediaFoundation.FrameRate, ((ulong)(uint)_fps << 32) | 1UL);
+ MediaFoundation.SetUInt64(mediaType, MediaFoundation.PixelAspectRatio, (1UL << 32) | 1UL);
+ if (topDown)
+ {
+ MediaFoundation.SetUInt32(mediaType, MediaFoundation.DefaultStride, _encodedWidth * 4);
+ }
+ }
+ catch
+ {
+ Marshal.Release(mediaType);
+ throw;
+ }
+ return mediaType;
+ }
+
+ private void Cleanup()
+ {
+ if (_writer != null)
+ {
+ Marshal.ReleaseComObject(_writer);
+ _writer = null;
+ }
+ if (_writerPtr != IntPtr.Zero)
+ {
+ Marshal.Release(_writerPtr);
+ _writerPtr = IntPtr.Zero;
+ }
+ if (_d3d is { } d3d)
+ {
+ _d3d = null;
+ MediaFoundation.ReleaseDeviceManager(d3d);
+ }
+ if (_started)
+ {
+ _started = false;
+ MediaFoundation.MFShutdown();
+ }
+ }
+}
diff --git a/WaveDude/Export/Mpeg1Writer.cs b/WaveDude/Export/Mpeg1Writer.cs
new file mode 100644
index 0000000..0979217
--- /dev/null
+++ b/WaveDude/Export/Mpeg1Writer.cs
@@ -0,0 +1,479 @@
+using System.Runtime.Intrinsics;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes an MPEG-1 video of intra-coded pictures only (ISO/IEC 11172-2, every picture an I-picture of one
+/// slice per macroblock row, the default quantisation matrix, no custom tables) inside an MPEG-1 program
+/// stream (11172-1: one pack per picture, PES packets of at most 64 KB, a PTS on each picture), the
+/// <c>.mpg</c> file every player and editor reads without a codec. In-house, no dependencies. The quality
+/// 1..100 becomes the quantiser scale 31..1; only the standard frame rates exist in MPEG-1, so the nearest
+/// is taken (<see cref="FrameRate"/>). 4:2:0, studio range. Slices are independent bit streams (their DC
+/// predictors reset), so the rows are transformed, quantised and coded in parallel and concatenated
+/// (2026-10-14); the DCT and quantisation run on <see cref="Vector128{T}"/> where the hardware has it.
+/// One thread at a time.
+/// </summary>
+public sealed class Mpeg1Writer : IFrameSink
+{
+ /// <summary>The frame rates MPEG-1 can express, by frame_rate_code 1..8.</summary>
+ public static readonly double[] FrameRates = [24000.0 / 1001, 24, 25, 30000.0 / 1001, 30, 50, 60000.0 / 1001, 60];
+
+ /// <summary>Pictures per group of pictures (each starts with a GOP header carrying the time code).</summary>
+ private const int GopLength = 12;
+
+ /// <summary>Largest PES payload: the packet length field is 16 bits and the header needs a few bytes.</summary>
+ private const int PesPayloadLimit = 65000;
+
+ private readonly FileStream _stream;
+ private readonly YuvPlanes _planes;
+ private readonly BitWriter _bits = new(1 << 20);
+ private readonly BitWriter[] _slices;
+ private readonly float[] _reciprocals = new float[64];
+ private readonly int _frameRateCode;
+ private readonly int _quantiserScale;
+ private readonly byte[] _sequenceHeader;
+ private bool _closed;
+
+ /// <param name="path">Output file; an existing file is replaced.</param>
+ /// <param name="width">Frame width in pixels, at most 4095.</param>
+ /// <param name="height">Frame height in pixels, at most 2800 (175 slices of 16 rows).</param>
+ /// <param name="framesPerSecond">Wanted frame rate; the nearest of <see cref="FrameRates"/> is used.</param>
+ /// <param name="quality">1 (coarsest quantiser) to 100 (finest).</param>
+ /// <exception cref="NotSupportedException">The size is outside what MPEG-1 can carry.</exception>
+ public Mpeg1Writer(string path, int width, int height, double framesPerSecond, int quality)
+ {
+ if (width < 16 || height < 16 || width > 4095 || height > 175 * 16)
+ {
+ throw new NotSupportedException($"MPEG-1 cannot carry a {width} × {height} picture (16 × 16 up to 4095 × 2800).");
+ }
+ Width = width;
+ Height = height;
+ Output = path;
+ _frameRateCode = NearestFrameRateCode(framesPerSecond);
+ FrameRate = FrameRates[_frameRateCode - 1];
+ _quantiserScale = QuantiserScaleFor(quality);
+ _planes = new YuvPlanes(width, height, studioRange: 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++)
+ {
+ _reciprocals[i] = 8f / (_quantiserScale * IntraMatrix[i]);
+ }
+ _slices = new BitWriter[_planes.MacroblockRows];
+ for (int i = 0; i < _slices.Length; i++)
+ {
+ _slices[i] = new BitWriter(Math.Max(4096, _planes.MacroblockColumns * 128));
+ }
+ _sequenceHeader = BuildSequenceHeader();
+ _stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 16);
+ }
+
+ /// <inheritdoc/>
+ public int Width { get; }
+
+ /// <inheritdoc/>
+ public int Height { get; }
+
+ /// <inheritdoc/>
+ public int FrameCount { get; private set; }
+
+ /// <inheritdoc/>
+ public string Output { get; }
+
+ /// <summary>The frame rate actually written, one of <see cref="FrameRates"/>.</summary>
+ public double FrameRate { get; }
+
+ /// <summary>The quantiser scale 1..31 used for every macroblock.</summary>
+ public int QuantiserScale => _quantiserScale;
+
+ /// <summary>The frame_rate_code 1..8 whose rate is nearest to <paramref name="framesPerSecond"/>.</summary>
+ public static int NearestFrameRateCode(double framesPerSecond)
+ {
+ int best = 1;
+ for (int i = 1; i < FrameRates.Length; i++)
+ {
+ if (Math.Abs(FrameRates[i] - framesPerSecond) < Math.Abs(FrameRates[best - 1] - framesPerSecond))
+ {
+ best = i + 1;
+ }
+ }
+ return best;
+ }
+
+ /// <summary>The quantiser scale for a quality: 1 at 100, growing faster towards the coarse end, 31 at 1 (quality 70 gives 6, 50 gives 12).</summary>
+ public static int QuantiserScaleFor(int quality)
+ {
+ double t = (100 - Math.Clamp(quality, 1, 100)) / 99.0;
+ return Math.Clamp(1 + (int)Math.Round(30.0 * Math.Pow(t, 1.5)), 1, 31);
+ }
+
+ /// <inheritdoc/>
+ public void Add(ReadOnlySpan<int> pixels)
+ {
+ if (_closed)
+ {
+ throw new InvalidOperationException("The video file is already closed.");
+ }
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the video.", nameof(pixels));
+ }
+ // the planes read the frame while the rows convert in parallel, so it is copied into a heap buffer first
+ int[] frame = pixels[..(Width * Height)].ToArray();
+ _planes.Convert(frame);
+ _bits.Reset();
+ int inGop = FrameCount % GopLength;
+ if (inGop == 0)
+ {
+ _bits.WriteBytes(_sequenceHeader);
+ WriteGopHeader(FrameCount);
+ }
+ WritePicture(inGop);
+ WritePack(FrameCount, withSystemHeader: FrameCount == 0);
+ FrameCount++;
+ }
+
+ /// <inheritdoc/>
+ public void Close()
+ {
+ if (_closed)
+ {
+ return;
+ }
+ _closed = true;
+ try
+ {
+ if (FrameCount > 0)
+ {
+ // sequence_end_code in its own PES, then the program end code
+ _bits.Reset();
+ _bits.WriteBytes([0, 0, 1, 0xB7]);
+ WritePack(FrameCount, withSystemHeader: false, withPts: false);
+ }
+ _stream.Write([0, 0, 1, 0xB9]);
+ _stream.Flush();
+ }
+ finally
+ {
+ _stream.Dispose();
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Dispose() => Close();
+
+ // ---------------------------------------------------------------- video elementary stream
+
+ private byte[] BuildSequenceHeader()
+ {
+ var bits = new BitWriter(32);
+ bits.WriteBytes([0, 0, 1, 0xB3]);
+ bits.Write((uint)Width, 12);
+ bits.Write((uint)Height, 12);
+ bits.Write(1, 4); // aspect_ratio_information: square pixels
+ bits.Write((uint)_frameRateCode, 4);
+ bits.Write(0x3FFFF, 18); // bit_rate: variable
+ bits.Write(1, 1); // marker
+ bits.Write(0x3FF, 10); // vbv_buffer_size, the largest
+ bits.Write(0, 1); // constrained_parameters_flag
+ bits.Write(0, 1); // load_intra_quantiser_matrix: the default
+ bits.Write(0, 1); // load_non_intra_quantiser_matrix
+ bits.AlignZero();
+ return bits.WrittenBytes.ToArray();
+ }
+
+ /// <summary>group_of_pictures header: the time code of the first picture, closed GOP.</summary>
+ private void WriteGopHeader(int frame)
+ {
+ double seconds = frame / FrameRate;
+ int hours = (int)(seconds / 3600) % 24;
+ int minutes = (int)(seconds / 60) % 60;
+ int wholeSeconds = (int)seconds % 60;
+ int pictures = (int)Math.Round((seconds - Math.Floor(seconds)) * FrameRate) % 60;
+ _bits.WriteBytes([0, 0, 1, 0xB8]);
+ _bits.Write(0, 1); // drop_frame_flag
+ _bits.Write((uint)hours, 5);
+ _bits.Write((uint)minutes, 6);
+ _bits.Write(1, 1); // marker
+ _bits.Write((uint)wholeSeconds, 6);
+ _bits.Write((uint)pictures, 6);
+ _bits.Write(1, 1); // closed_gop
+ _bits.Write(0, 1); // broken_link
+ _bits.AlignZero();
+ }
+
+ /// <summary>One I-picture: the picture header, then the slices (one per macroblock row, coded in parallel) in order.</summary>
+ private void WritePicture(int temporalReference)
+ {
+ _bits.WriteBytes([0, 0, 1, 0x00]);
+ _bits.Write((uint)temporalReference, 10);
+ _bits.Write(1, 3); // picture_coding_type: I
+ _bits.Write(0xFFFF, 16); // vbv_delay: variable
+ _bits.Write(0, 1); // extra_bit_picture
+ _bits.AlignZero();
+ Parallel.For(0, _slices.Length, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, EncodeSlice);
+ foreach (BitWriter slice in _slices)
+ {
+ _bits.WriteBytes(slice.WrittenBytes);
+ }
+ }
+
+ /// <summary>One slice: its start code with the row, the quantiser, every macroblock of the row as intra with its six blocks; byte-aligned at the end.</summary>
+ private void EncodeSlice(int row)
+ {
+ YuvPlanes planes = _planes;
+ BitWriter bits = _slices[row];
+ bits.Reset();
+ bits.WriteBytes([0, 0, 1, (byte)(row + 1)]); // slice_start_code with the vertical position
+ bits.Write((uint)_quantiserScale, 5);
+ bits.Write(0, 1); // extra_bit_slice
+ Span<float> block = stackalloc float[64];
+ Span<float> dct = stackalloc float[64];
+ Span<int> quantised = stackalloc int[64];
+ Span<int> predictors = stackalloc int[3];
+ predictors[0] = predictors[1] = predictors[2] = 128; // the DC predictors reset at every slice
+ for (int column = 0; column < planes.MacroblockColumns; column++)
+ {
+ bits.Write(1, 1); // macroblock_address_increment: 1
+ bits.Write(1, 1); // macroblock_type: intra
+ for (int blockIndex = 0; blockIndex < 6; blockIndex++)
+ {
+ if (blockIndex < 4)
+ {
+ YuvPlanes.CopyBlock(planes.Y, planes.PaddedWidth, column * 16 + (blockIndex & 1) * 8, row * 16 + (blockIndex >> 1) * 8, 0f, block);
+ }
+ else
+ {
+ YuvPlanes.CopyBlock(blockIndex == 4 ? planes.Cb : planes.Cr, planes.ChromaWidth, column * 8, row * 8, 0f, block);
+ }
+ Dct8x8.Forward(block, dct);
+ Quantise(dct, quantised);
+ int component = blockIndex < 4 ? 0 : blockIndex - 3;
+ WriteBlock(bits, quantised, component, ref predictors[component]);
+ }
+ }
+ bits.AlignZero();
+ }
+
+ /// <summary>The intra DC as F(0,0) / 8 (0..255) and the AC levels truncated and clamped to ±255, row-major.</summary>
+ private void Quantise(ReadOnlySpan<float> dct, Span<int> quantised)
+ {
+ if (Vector128.IsHardwareAccelerated)
+ {
+ Vector128<int> low = Vector128.Create(-255);
+ Vector128<int> high = Vector128.Create(255);
+ for (int i = 0; i < 64; i += 4)
+ {
+ Vector128<float> scaled = Vector128.Create(dct.Slice(i, 4)) * Vector128.Create(_reciprocals.AsSpan(i, 4));
+ Vector128.Clamp(Vector128.ConvertToInt32(scaled), low, high).CopyTo(quantised.Slice(i, 4)); // ConvertToInt32 truncates
+ }
+ }
+ else
+ {
+ for (int i = 0; i < 64; i++)
+ {
+ quantised[i] = Math.Clamp((int)(dct[i] * _reciprocals[i]), -255, 255);
+ }
+ }
+ quantised[0] = Math.Clamp((int)MathF.Round(dct[0] / 8f), 0, 255);
+ }
+
+ /// <summary>One intra block: the DC differential with its size code, the AC run/level codes in zig-zag order, the end of block.</summary>
+ private static void WriteBlock(BitWriter bits, ReadOnlySpan<int> quantised, int component, ref int predictor)
+ {
+ int dc = quantised[0];
+ int diff = dc - predictor;
+ predictor = dc;
+ int size = 0;
+ for (int magnitude = Math.Abs(diff); magnitude > 0; magnitude >>= 1)
+ {
+ size++;
+ }
+ (ushort dcCode, byte dcLength) = component == 0 ? DcSizeLuma[size] : DcSizeChroma[size];
+ bits.Write(dcCode, dcLength);
+ if (size > 0)
+ {
+ bits.Write((uint)(diff < 0 ? diff + (1 << size) - 1 : diff), size);
+ }
+ int run = 0;
+ for (int i = 1; i < 64; i++)
+ {
+ int level = quantised[Dct8x8.ZigZag[i]];
+ if (level == 0)
+ {
+ run++;
+ continue;
+ }
+ WriteRunLevel(bits, run, level);
+ run = 0;
+ }
+ bits.Write(0b10, 2); // end_of_block
+ }
+
+ /// <summary>A run/level pair from table B.14 with its sign bit, or the escape form (6 + 6 + 8 or 16 bits) for pairs outside it.</summary>
+ private static void WriteRunLevel(BitWriter bits, int run, int level)
+ {
+ int magnitude = Math.Abs(level);
+ if (magnitude <= 40 && run <= 31)
+ {
+ (ushort code, byte length) = AcCodes[run, magnitude];
+ if (length > 0)
+ {
+ bits.Write(code, length);
+ bits.Write(level < 0 ? 1u : 0u, 1);
+ return;
+ }
+ }
+ bits.Write(0b000001, 6); // escape
+ bits.Write((uint)run, 6);
+ if (level >= -127 && level <= 127)
+ {
+ bits.WriteSigned(level, 8);
+ }
+ else
+ {
+ // 16-bit form: 1000 0000 for -255..-128, 0000 0000 for 128..255, then the low byte
+ bits.Write(level < 0 ? 0x80u : 0x00u, 8);
+ bits.Write((uint)(level & 0xFF), 8);
+ }
+ }
+
+ // ---------------------------------------------------------------- program stream
+
+ /// <summary>Wraps the bits written so far (a picture with its headers, or the end code) into one pack of PES packets.</summary>
+ private void WritePack(int frame, bool withSystemHeader, bool withPts = true)
+ {
+ long clock = (long)Math.Round(frame * 90000.0 / FrameRate); // 90 kHz
+ Span<byte> pack = stackalloc byte[12];
+ pack[0] = 0; pack[1] = 0; pack[2] = 1; pack[3] = 0xBA;
+ // '0010' SCR[32..30] '1' SCR[29..15] '1' SCR[14..0] '1' '1' mux_rate '1'
+ var bits = new BitWriter(16);
+ bits.Write(0b0010, 4);
+ bits.Write((uint)((clock >> 30) & 7), 3);
+ bits.Write(1, 1);
+ bits.Write((uint)((clock >> 15) & 0x7FFF), 15);
+ bits.Write(1, 1);
+ bits.Write((uint)(clock & 0x7FFF), 15);
+ bits.Write(1, 1);
+ bits.Write(1, 1);
+ bits.Write(0x3FFFFF, 22); // mux_rate: the largest, in 50 bytes/s
+ bits.Write(1, 1);
+ bits.WrittenBytes.CopyTo(pack[4..]);
+ _stream.Write(pack);
+ if (withSystemHeader)
+ {
+ // system_header: one video stream, bounds at their maxima
+ var system = new BitWriter(32);
+ system.WriteBytes([0, 0, 1, 0xBB, 0, 9]);
+ system.Write(1, 1);
+ system.Write(0x3FFFFF, 22); // rate_bound
+ system.Write(1, 1);
+ system.Write(0, 6); // audio_bound
+ system.Write(0, 1); // fixed_flag
+ system.Write(0, 1); // CSPS_flag
+ system.Write(0, 1); // system_audio_lock_flag
+ system.Write(0, 1); // system_video_lock_flag
+ system.Write(1, 1); // marker
+ system.Write(1, 5); // video_bound
+ system.Write(0xFF, 8); // reserved
+ system.Write(0xE0, 8); // stream_id: video stream 0
+ system.Write(0b11, 2);
+ system.Write(1, 1); // P-STD_buffer_bound_scale: 1024-byte units
+ system.Write(0x1FFF, 13); // P-STD_buffer_size_bound
+ _stream.Write(system.WrittenBytes);
+ }
+ ReadOnlySpan<byte> payload = _bits.WrittenBytes;
+ bool first = true;
+ Span<byte> header = stackalloc byte[6 + 5];
+ while (payload.Length > 0 || first)
+ {
+ int take = Math.Min(payload.Length, PesPayloadLimit);
+ ReadOnlySpan<byte> part = payload[..take];
+ payload = payload[take..];
+ int headerLength = first && withPts ? 5 : 1;
+ header[0] = 0; header[1] = 0; header[2] = 1; header[3] = 0xE0;
+ int length = headerLength + take;
+ header[4] = (byte)(length >> 8);
+ header[5] = (byte)length;
+ if (first && withPts)
+ {
+ // '0010' PTS[32..30] '1' PTS[29..15] '1' PTS[14..0] '1'
+ header[6] = (byte)(0x21 | (((clock >> 30) & 7) << 1));
+ header[7] = (byte)((clock >> 22) & 0xFF);
+ header[8] = (byte)(0x01 | (((clock >> 15) & 0x7F) << 1));
+ header[9] = (byte)((clock >> 7) & 0xFF);
+ header[10] = (byte)(0x01 | ((clock & 0x7F) << 1));
+ _stream.Write(header);
+ }
+ else
+ {
+ header[6] = 0x0F; // no PTS, no DTS
+ _stream.Write(header[..7]);
+ }
+ _stream.Write(part);
+ first = false;
+ }
+ }
+
+ // ---------------------------------------------------------------- tables
+
+ /// <summary>The default intra quantiser matrix of 11172-2, row-major.</summary>
+ private static readonly int[] IntraMatrix =
+ [
+ 8, 16, 19, 22, 26, 27, 29, 34,
+ 16, 16, 22, 24, 27, 29, 34, 37,
+ 19, 22, 26, 27, 29, 34, 34, 38,
+ 22, 22, 26, 27, 29, 34, 37, 40,
+ 22, 26, 27, 29, 32, 35, 40, 48,
+ 26, 27, 29, 32, 35, 40, 48, 58,
+ 26, 27, 29, 34, 38, 46, 56, 69,
+ 27, 29, 35, 38, 46, 56, 69, 83,
+ ];
+
+ /// <summary>dct_dc_size_luminance codes (table B.12), indexed by size 0..8.</summary>
+ private static readonly (ushort Code, byte Length)[] DcSizeLuma = Codes(["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"]);
+
+ /// <summary>dct_dc_size_chrominance codes (table B.13), indexed by size 0..8.</summary>
+ private static readonly (ushort Code, byte Length)[] DcSizeChroma = Codes(["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"]);
+
+ /// <summary>
+ /// Table B.14, the run/level codes of up to 13 bits without the sign bit, indexed [run, level]; a zero length
+ /// means "use the escape". The 0/1 entry is the "next coefficient" form (11), the only one an intra block uses.
+ /// </summary>
+ private static readonly (ushort Code, byte Length)[,] AcCodes = MakeAcCodes();
+
+ private static (ushort, byte) Code(string code)
+ {
+ ushort value = 0;
+ foreach (char c in code)
+ {
+ value = (ushort)((value << 1) | (c == '1' ? 1 : 0));
+ }
+ return (value, (byte)code.Length);
+ }
+
+ private static (ushort, byte)[] Codes(string[] codes) => [.. codes.Select(Code)];
+
+ private static (ushort, byte)[,] MakeAcCodes()
+ {
+ var table = new (ushort, byte)[32, 41];
+ (int Run, int Level, string Code)[] entries =
+ [
+ (0, 1, "11"), (1, 1, "011"), (0, 2, "0100"), (2, 1, "0101"), (0, 3, "00101"), (3, 1, "00111"), (4, 1, "00110"),
+ (1, 2, "000110"), (5, 1, "000111"), (6, 1, "000101"), (7, 1, "000100"),
+ (0, 4, "0000110"), (2, 2, "0000100"), (8, 1, "0000111"), (9, 1, "0000101"),
+ (0, 5, "00100110"), (0, 6, "00100001"), (1, 3, "00100101"), (3, 2, "00100100"), (10, 1, "00100111"), (11, 1, "00100011"), (12, 1, "00100010"), (13, 1, "00100000"),
+ (0, 7, "0000001010"), (1, 4, "0000001100"), (2, 3, "0000001011"), (4, 2, "0000001111"), (5, 2, "0000001001"), (14, 1, "0000001110"), (15, 1, "0000001101"), (16, 1, "0000001000"),
+ (0, 8, "000000011101"), (0, 9, "000000011000"), (0, 10, "000000010011"), (0, 11, "000000010000"), (1, 5, "000000011011"), (2, 4, "000000010100"), (3, 3, "000000011100"),
+ (4, 3, "000000010010"), (6, 2, "000000011110"), (7, 2, "000000010101"), (8, 2, "000000010001"), (17, 1, "000000011111"), (18, 1, "000000011010"), (19, 1, "000000011001"),
+ (20, 1, "000000010111"), (21, 1, "000000010110"),
+ (0, 12, "0000000011010"), (0, 13, "0000000011001"), (0, 14, "0000000011000"), (0, 15, "0000000010111"), (1, 6, "0000000010110"), (1, 7, "0000000010101"),
+ (2, 5, "0000000010100"), (3, 4, "0000000010011"), (5, 3, "0000000010010"), (9, 2, "0000000010001"), (10, 2, "0000000010000"), (22, 1, "0000000011111"),
+ (23, 1, "0000000011110"), (24, 1, "0000000011101"), (25, 1, "0000000011100"), (26, 1, "0000000011011"),
+ ];
+ foreach ((int run, int level, string code) in entries)
+ {
+ table[run, level] = Code(code);
+ }
+ return table;
+ }
+}
diff --git a/WaveDude/Export/PngEncoder.cs b/WaveDude/Export/PngEncoder.cs
new file mode 100644
index 0000000..90ad4e9
--- /dev/null
+++ b/WaveDude/Export/PngEncoder.cs
@@ -0,0 +1,200 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Text;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes 24-bit RGB PNG files from packed BGRA32 frames, in-house: the signature, IHDR, the zlib stream
+/// (<see cref="ZLibStream"/>, which writes the zlib header and Adler-32 itself) as IDAT chunks of up to 64 KB
+/// written as the compressor produces them (no whole-file buffer: that cost more in garbage than the
+/// compression, 2026-10-15) and IEND, with a <see cref="Crc32"/> per chunk. Every row is Paeth-filtered
+/// (filter type 4), which suits the smooth gradients of a wave picture. Lossless; the alpha byte is
+/// dropped. Any thread.
+/// </summary>
+public static class PngEncoder
+{
+ private static readonly byte[] Signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
+
+ /// <summary>Writes one frame as a PNG to <paramref name="stream"/>.</summary>
+ /// <param name="stream">Destination; left open.</param>
+ /// <param name="pixels">Packed BGRA32 pixels, row-major, at least <paramref name="width"/> × <paramref name="height"/>.</param>
+ /// <param name="width">Width in pixels.</param>
+ /// <param name="height">Height in pixels.</param>
+ public static void Write(Stream stream, ReadOnlySpan<int> pixels, int width, int height)
+ {
+ stream.Write(Signature);
+ Span<byte> header = stackalloc byte[13];
+ BinaryPrimitives.WriteInt32BigEndian(header, width);
+ BinaryPrimitives.WriteInt32BigEndian(header[4..], height);
+ header[8] = 8; // bit depth
+ header[9] = 2; // colour type: truecolour
+ header[10] = 0; // deflate
+ header[11] = 0; // adaptive filtering
+ header[12] = 0; // no interlace
+ WriteChunk(stream, "IHDR", header);
+ using (var idat = new IdatStream(stream))
+ {
+ Deflate(idat, pixels, width, height);
+ }
+ WriteChunk(stream, "IEND", default);
+ }
+
+ /// <summary>Encodes a frame to a byte array (for a harness or a clipboard).</summary>
+ public static byte[] Encode(ReadOnlySpan<int> pixels, int width, int height)
+ {
+ using var stream = new MemoryStream();
+ Write(stream, pixels, width, height);
+ return stream.ToArray();
+ }
+
+ /// <summary>The filtered rows, zlib-compressed into <paramref name="output"/>.</summary>
+ private static void Deflate(Stream output, ReadOnlySpan<int> pixels, int width, int height)
+ {
+ int rowBytes = width * 3;
+ var previous = new byte[rowBytes];
+ var current = new byte[rowBytes];
+ var filtered = new byte[rowBytes + 1];
+ using (var zlib = new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true))
+ {
+ for (int y = 0; y < height; y++)
+ {
+ ReadOnlySpan<int> row = pixels.Slice(y * width, width);
+ for (int x = 0; x < width; x++)
+ {
+ int argb = row[x];
+ current[x * 3] = (byte)(argb >> 16);
+ current[x * 3 + 1] = (byte)(argb >> 8);
+ current[x * 3 + 2] = (byte)argb;
+ }
+ filtered[0] = 4; // Paeth
+ for (int i = 0; i < rowBytes; i++)
+ {
+ int a = i >= 3 ? current[i - 3] : 0;
+ int b = previous[i];
+ int c = i >= 3 ? previous[i - 3] : 0;
+ filtered[i + 1] = (byte)(current[i] - Paeth(a, b, c));
+ }
+ zlib.Write(filtered, 0, filtered.Length);
+ (previous, current) = (current, previous);
+ }
+ }
+ }
+
+ /// <summary>Collects what the compressor writes and emits it as IDAT chunks of up to <see cref="ChunkSize"/> bytes.</summary>
+ private sealed class IdatStream(Stream target) : Stream
+ {
+ private const int ChunkSize = 1 << 16;
+ private readonly byte[] _buffer = new byte[ChunkSize];
+ private int _filled;
+
+ public override bool CanRead => false;
+ public override bool CanSeek => false;
+ public override bool CanWrite => true;
+ public override long Length => throw new NotSupportedException();
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
+
+ public override void Write(ReadOnlySpan<byte> buffer)
+ {
+ while (buffer.Length > 0)
+ {
+ int take = Math.Min(buffer.Length, ChunkSize - _filled);
+ buffer[..take].CopyTo(_buffer.AsSpan(_filled));
+ _filled += take;
+ buffer = buffer[take..];
+ if (_filled == ChunkSize)
+ {
+ Flush();
+ }
+ }
+ }
+
+ public override void Flush()
+ {
+ if (_filled > 0)
+ {
+ WriteChunk(target, "IDAT", _buffer.AsSpan(0, _filled));
+ _filled = 0;
+ }
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ Flush();
+ }
+ base.Dispose(disposing);
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ }
+
+ /// <summary>The PNG Paeth predictor: whichever of left, above and above-left is closest to left + above − above-left.</summary>
+ private static int Paeth(int a, int b, int c)
+ {
+ int p = a + b - c;
+ int pa = Math.Abs(p - a);
+ int pb = Math.Abs(p - b);
+ int pc = Math.Abs(p - c);
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
+ }
+
+ private static void WriteChunk(Stream stream, string type, ReadOnlySpan<byte> data)
+ {
+ Span<byte> length = stackalloc byte[4];
+ BinaryPrimitives.WriteInt32BigEndian(length, data.Length);
+ stream.Write(length);
+ byte[] typeBytes = Encoding.ASCII.GetBytes(type);
+ stream.Write(typeBytes);
+ stream.Write(data);
+ uint crc = Crc32.Update(Crc32.Update(Crc32.Initial, typeBytes), data);
+ Span<byte> crcBytes = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt32BigEndian(crcBytes, Crc32.Finish(crc));
+ stream.Write(crcBytes);
+ }
+}
+
+/// <summary>The CRC-32 of PNG and zip (polynomial 0xEDB88320, reflected), table-driven.</summary>
+public static class Crc32
+{
+ private static readonly uint[] Table = MakeTable();
+
+ /// <summary>The running value before any byte.</summary>
+ public const uint Initial = 0xFFFFFFFFu;
+
+ /// <summary>Feeds bytes into a running value.</summary>
+ public static uint Update(uint crc, ReadOnlySpan<byte> data)
+ {
+ foreach (byte b in data)
+ {
+ crc = Table[(crc ^ b) & 0xFF] ^ (crc >> 8);
+ }
+ return crc;
+ }
+
+ /// <summary>The final CRC of a running value.</summary>
+ public static uint Finish(uint crc) => crc ^ 0xFFFFFFFFu;
+
+ /// <summary>The CRC-32 of a whole buffer.</summary>
+ public static uint Of(ReadOnlySpan<byte> data) => Finish(Update(Initial, data));
+
+ private static uint[] MakeTable()
+ {
+ var table = new uint[256];
+ for (uint n = 0; n < 256; n++)
+ {
+ uint c = n;
+ for (int k = 0; k < 8; k++)
+ {
+ c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
+ }
+ table[n] = c;
+ }
+ return table;
+ }
+}
diff --git a/WaveDude/Export/ProbeMarkers.cs b/WaveDude/Export/ProbeMarkers.cs
new file mode 100644
index 0000000..0cbe477
--- /dev/null
+++ b/WaveDude/Export/ProbeMarkers.cs
@@ -0,0 +1,84 @@
+using WaveDude.Model;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// The probe markers of an exported frame, in the author's style (his <c>ProbeOverlay.DrawMarkerPixels</c>):
+/// a cross at a probe point, two crosses and the connecting line for a line probe, each stroke drawn twice,
+/// black with a radius of 2 under white with a radius of 1, arms of max(6, height / 120) pixels. The
+/// labels ("1", or "1A" and "1B") need a font and are drawn by the application (<c>ProbeGraphPainter</c>)
+/// at the position <see cref="LabelOrigin"/> gives, bold Segoe UI at <see cref="FontSize"/> pixels with a
+/// drop shadow. Any thread.
+/// </summary>
+public static class ProbeMarkers
+{
+ private const int Black = unchecked((int)0xFF000000);
+ private const int White = unchecked((int)0xFFFFFFFF);
+
+ /// <summary>Arm length of a cross for a frame height, in pixels.</summary>
+ public static int ArmLength(int height) => Math.Max(6, height / 120);
+
+ /// <summary>Label height for a frame height, in pixels.</summary>
+ public static float FontSize(int height) => Math.Max(12f, height / 60f);
+
+ /// <summary>Top-left corner of the label of the cross at (<paramref name="x"/>, <paramref name="y"/>): above and to the right, as the author placed it.</summary>
+ public static (int X, int Y) LabelOrigin(int x, int y, int height)
+ {
+ int arm = ArmLength(height);
+ return (x + arm + 2, y - arm - (int)Math.Round(FontSize(height) * 1.4f));
+ }
+
+ /// <summary>Draws the strokes of one probe's marker into a packed BGRA32 frame.</summary>
+ /// <param name="pixels">The frame, width × height, modified in place.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="probe">The probe; its positions are canvas pixels, the frame's.</param>
+ public static void DrawStrokes(Span<int> pixels, int width, int height, Probe probe)
+ {
+ int arm = ArmLength(height);
+ bool line = probe.Kind == ProbeKind.Line;
+ for (int pass = 0; pass <= 1; pass++)
+ {
+ int color = pass == 0 ? Black : White;
+ int radius = pass == 0 ? 2 : 1;
+ if (line)
+ {
+ ThickLine(pixels, width, height, probe.AX, probe.AY, probe.BX, probe.BY, color, radius);
+ }
+ Cross(pixels, width, height, probe.AX, probe.AY, arm, color, radius);
+ if (line)
+ {
+ Cross(pixels, width, height, probe.BX, probe.BY, arm, color, radius);
+ }
+ }
+ }
+
+ /// <summary>The label text of a probe end: the 1-based number, with "A"/"B" for a line probe's ends.</summary>
+ public static string Label(int number, bool line, bool endB) => line ? number + (endB ? "B" : "A") : number.ToString(System.Globalization.CultureInfo.InvariantCulture);
+
+ private static void Cross(Span<int> pixels, int width, int height, int x, int y, int arm, int color, int radius)
+ {
+ ThickLine(pixels, width, height, x - arm, y, x + arm, y, color, radius);
+ ThickLine(pixels, width, height, x, y - arm, x, y + arm, color, radius);
+ }
+
+ /// <summary>A line of (2 × <paramref name="radius"/> + 1) pixels' thickness, stamped point by point, clipped to the frame.</summary>
+ public static void ThickLine(Span<int> pixels, int width, int height, int x0, int y0, int x1, int y1, int color, int radius)
+ {
+ int dx = Math.Abs(x1 - x0);
+ int dy = Math.Abs(y1 - y0);
+ int steps = Math.Max(dx, dy);
+ for (int i = 0; i <= steps; i++)
+ {
+ int x = steps == 0 ? x0 : x0 + (int)Math.Round((x1 - x0) * (double)i / steps);
+ int y = steps == 0 ? y0 : y0 + (int)Math.Round((y1 - y0) * (double)i / steps);
+ for (int yy = Math.Max(0, y - radius); yy <= Math.Min(height - 1, y + radius); yy++)
+ {
+ for (int xx = Math.Max(0, x - radius); xx <= Math.Min(width - 1, x + radius); xx++)
+ {
+ pixels[yy * width + xx] = color;
+ }
+ }
+ }
+ }
+}
diff --git a/WaveDude/Export/YuvPlanes.cs b/WaveDude/Export/YuvPlanes.cs
new file mode 100644
index 0000000..9d9bce5
--- /dev/null
+++ b/WaveDude/Export/YuvPlanes.cs
@@ -0,0 +1,439 @@
+using System.Runtime.Intrinsics;
+using System.Runtime.Intrinsics.X86;
+
+namespace WaveDude.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
+/// 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:
+/// SIMD is everywhere now; this machine's .NET does not accelerate 256-bit vectors), rows in parallel. Reusable: <see cref="Convert"/> overwrites the planes. Any thread, one at a time.
+/// </summary>
+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)
+ {
+ Width = width;
+ Height = height;
+ StudioRange = studioRange;
+ 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)];
+ Cr = new byte[Cb.Length];
+ if (studioRange)
+ {
+ _matrix = [16f, 0.257f, 0.504f, 0.098f, 128f, -0.148f, -0.291f, 0.439f, 128f, 0.439f, -0.368f, -0.071f];
+ }
+ else
+ {
+ _matrix = [0f, 0.299f, 0.587f, 0.114f, 128f, -0.168736f, -0.331264f, 0.5f, 128f, 0.5f, -0.418688f, -0.081312f];
+ }
+ }
+
+ /// <summary>The conversion as (offset, r, g, b) for Y, Cb and Cr.</summary>
+ private readonly float[] _matrix;
+
+ /// <summary>Picture width in pixels.</summary>
+ public int Width { get; }
+
+ /// <summary>Picture height in pixels.</summary>
+ public int Height { get; }
+
+ /// <summary>Whether the planes use the studio range.</summary>
+ public bool StudioRange { get; }
+
+ /// <summary>Macroblocks per row.</summary>
+ public int MacroblockColumns { get; }
+
+ /// <summary>Macroblock rows.</summary>
+ public int MacroblockRows { get; }
+
+ /// <summary>Width of the Y plane, a multiple of 16.</summary>
+ public int PaddedWidth { get; }
+
+ /// <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>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>
+ public byte[] Cb { get; }
+
+ /// <summary>Red-difference plane, like <see cref="Cb"/>.</summary>
+ public byte[] Cr { get; }
+
+ /// <summary>Converts a packed BGRA32 frame of <see cref="Width"/> × <see cref="Height"/> into the planes; macroblock rows run in parallel.</summary>
+ public void Convert(ReadOnlyMemory<int> pixels)
+ {
+ Parallel.For(0, MacroblockRows, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, mbRow => ConvertRows(pixels.Span, mbRow * 16, mbRow * 16 + 16));
+ }
+
+ /// <summary>Converts picture rows <paramref name="fromY"/> (inclusive) to <paramref name="toY"/> (exclusive), an even count starting on an even row.</summary>
+ private void ConvertRows(ReadOnlySpan<int> frame, int fromY, int toY)
+ {
+ int width = Width;
+ int paddedWidth = PaddedWidth;
+ int chromaWidth = ChromaWidth;
+ Span<float> cb = stackalloc float[paddedWidth];
+ Span<float> cr = stackalloc float[paddedWidth];
+ Span<float> cbAbove = stackalloc float[paddedWidth];
+ Span<float> crAbove = stackalloc float[paddedWidth];
+ for (int y = fromY; y < toY; y++)
+ {
+ ReadOnlySpan<int> row = frame.Slice(Math.Min(y, Height - 1) * width, width);
+ Span<byte> luma = Y.AsSpan(y * paddedWidth, paddedWidth);
+ int x = 0;
+ if (Vector128.IsHardwareAccelerated)
+ {
+ x = ConvertVector(row, luma, cb, cr);
+ }
+ for (; x < paddedWidth; x++)
+ {
+ int argb = row[Math.Min(x, width - 1)];
+ float r = (argb >> 16) & 0xFF;
+ float g = (argb >> 8) & 0xFF;
+ float b = argb & 0xFF;
+ luma[x] = ClampByte(_matrix[0] + _matrix[1] * r + _matrix[2] * g + _matrix[3] * b);
+ 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)
+ {
+ cb.CopyTo(cbAbove);
+ cr.CopyTo(crAbove);
+ }
+ else
+ {
+ // the 2 × 2 mean of this row and the one above
+ int chromaOffset = (y >> 1) * chromaWidth;
+ for (int cx = 0; cx < chromaWidth; cx++)
+ {
+ int px = cx * 2;
+ Cb[chromaOffset + cx] = ClampByte((cb[px] + cb[px + 1] + cbAbove[px] + cbAbove[px + 1]) * 0.25f);
+ Cr[chromaOffset + cx] = ClampByte((cr[px] + cr[px + 1] + crAbove[px] + crAbove[px + 1]) * 0.25f);
+ }
+ }
+ }
+ }
+
+ /// <summary>Converts the pixels of one row four at a time; returns how many were done (the rest, fewer than four plus the padding, is scalar).</summary>
+ private int ConvertVector(ReadOnlySpan<int> row, Span<byte> luma, Span<float> cb, Span<float> cr)
+ {
+ Vector128<int> mask = Vector128.Create(0xFF);
+ Vector128<float> yOffset = Vector128.Create(_matrix[0]);
+ Vector128<float> yR = Vector128.Create(_matrix[1]);
+ Vector128<float> yG = Vector128.Create(_matrix[2]);
+ Vector128<float> yB = Vector128.Create(_matrix[3]);
+ Vector128<float> cbOffset = Vector128.Create(_matrix[4]);
+ Vector128<float> cbR = Vector128.Create(_matrix[5]);
+ Vector128<float> cbG = Vector128.Create(_matrix[6]);
+ Vector128<float> cbB = Vector128.Create(_matrix[7]);
+ Vector128<float> crOffset = Vector128.Create(_matrix[8]);
+ Vector128<float> crR = Vector128.Create(_matrix[9]);
+ Vector128<float> crG = Vector128.Create(_matrix[10]);
+ Vector128<float> crB = Vector128.Create(_matrix[11]);
+ Vector128<float> zero = Vector128<float>.Zero;
+ Vector128<float> top = Vector128.Create(255f);
+ Span<int> lumaInts = stackalloc int[4];
+ int x = 0;
+ for (; x + 4 <= row.Length; x += 4)
+ {
+ Vector128<int> argb = Vector128.Create(row.Slice(x, 4));
+ Vector128<float> r = Vector128.ConvertToSingle(Vector128.ShiftRightLogical(argb, 16) & mask);
+ Vector128<float> g = Vector128.ConvertToSingle(Vector128.ShiftRightLogical(argb, 8) & mask);
+ Vector128<float> b = Vector128.ConvertToSingle(argb & mask);
+ Vector128<float> yv = yB * b + yG * g + yR * r + yOffset;
+ Vector128<float> cbv = cbB * b + cbG * g + cbR * r + cbOffset;
+ Vector128<float> crv = crB * b + crG * g + crR * r + crOffset;
+ Vector128.ConvertToInt32(Vector128.Round(Vector128.Clamp(yv, zero, top))).CopyTo(lumaInts);
+ luma[x] = (byte)lumaInts[0];
+ luma[x + 1] = (byte)lumaInts[1];
+ luma[x + 2] = (byte)lumaInts[2];
+ luma[x + 3] = (byte)lumaInts[3];
+ cbv.CopyTo(cb.Slice(x, 4));
+ crv.CopyTo(cr.Slice(x, 4));
+ }
+ return x;
+ }
+
+ private static byte ClampByte(float value) => (byte)Math.Clamp((int)MathF.Round(value), 0, 255);
+
+ /// <summary>Copies the 8 × 8 block at (<paramref name="x"/>, <paramref name="y"/>) of a plane into <paramref name="block"/> as floats, minus <paramref name="offset"/>.</summary>
+ /// <param name="plane">One of the planes.</param>
+ /// <param name="planeWidth">The plane's row length.</param>
+ /// <param name="x">Left column of the block.</param>
+ /// <param name="y">Top row of the block.</param>
+ /// <param name="offset">Subtracted from every sample (128 for JPEG's level shift, 0 for MPEG-1).</param>
+ /// <param name="block">64 values, row-major.</param>
+ public static void CopyBlock(byte[] plane, int planeWidth, int x, int y, float offset, Span<float> block)
+ {
+ for (int row = 0; row < 8; row++)
+ {
+ int source = (y + row) * planeWidth + x;
+ for (int column = 0; column < 8; column++)
+ {
+ block[row * 8 + column] = plane[source + column] - offset;
+ }
+ }
+ }
+}
+
+/// <summary>
+/// The forward 8 × 8 DCT-II with the orthonormal scaling of JPEG and MPEG (<c>F(u,v) = ¼ C(u) C(v) ΣΣ f(x,y)
+/// cos((2x+1)uπ/16) cos((2y+1)vπ/16)</c>, C(0) = 1/√2), computed separably: F = C · f · Cᵀ as two passes of
+/// 64 multiply-adds on rows held as two <see cref="Vector128{T}"/> halves where the hardware has them, else in
+/// scalar floats. Any thread.
+/// </summary>
+public static class Dct8x8
+{
+ private static readonly float[] Cosines = MakeCosines();
+ private static readonly Vector128<float>[] CosineColumnsLow = MakeCosineColumns(0);
+ private static readonly Vector128<float>[] CosineColumnsHigh = MakeCosineColumns(4);
+
+ /// <summary>The zig-zag scan order shared by JPEG and MPEG-1: entry i is the row-major index of the i-th coefficient.</summary>
+ public static readonly int[] ZigZag =
+ [
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
+ ];
+
+ /// <summary>
+ /// The AAN output scaling per frequency index: <see cref="ForwardAan"/> gives F(u,v) × 8 × AanScale[u] × AanScale[v],
+ /// which a quantiser folds into its divisors (the way the IJG float DCT is used).
+ /// </summary>
+ public static readonly double[] AanScale = [1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379];
+
+ /// <summary>The zig-zag order over the transposed layout of <see cref="ForwardAan"/> (index u × 8 + v): entry i is where the i-th coefficient sits.</summary>
+ public static readonly int[] ZigZagAan = [.. ZigZag.Select(n => (n % 8) * 8 + n / 8)];
+
+ /// <summary>
+ /// The AAN factorisation (Arai, Agui, Nakajima; the IJG float DCT: 5 multiplications and 29 additions per
+ /// 8-point transform) on SSE registers: a pass down the columns with the lanes along x, two in-register
+ /// 4 × 4 transposes, the same pass again. The output is scaled (see <see cref="AanScale"/>) and lands
+ /// transposed, <paramref name="coefficients"/>[u × 8 + v], so the caller indexes it with <see cref="ZigZagAan"/>.
+ /// Without SSE the exact transform stands in, rearranged and scaled to match.
+ /// </summary>
+ public static void ForwardAan(ReadOnlySpan<float> block, Span<float> coefficients)
+ {
+ if (!Sse.IsSupported)
+ {
+ Span<float> exact = stackalloc float[64];
+ Forward(block, exact);
+ for (int v = 0; v < 8; v++)
+ {
+ for (int u = 0; u < 8; u++)
+ {
+ coefficients[u * 8 + v] = exact[v * 8 + u] * (float)(8.0 * AanScale[u] * AanScale[v]);
+ }
+ }
+ return;
+ }
+ Span<Vector128<float>> lo = stackalloc Vector128<float>[8];
+ Span<Vector128<float>> hi = stackalloc Vector128<float>[8];
+ for (int y = 0; y < 8; y++)
+ {
+ lo[y] = Vector128.Create(block.Slice(y * 8, 4));
+ hi[y] = Vector128.Create(block.Slice(y * 8 + 4, 4));
+ }
+ // pass 1: down the columns (the 8 rows are the 8 inputs), both halves of the columns
+ Aan1D(lo);
+ Aan1D(hi);
+ // transpose: rows become columns; the quadrants swap across the diagonal
+ Transpose4(lo, 0);
+ Transpose4(hi, 4);
+ Transpose4(lo, 4);
+ Transpose4(hi, 0);
+ for (int i = 0; i < 4; i++)
+ {
+ (lo[4 + i], hi[i]) = (hi[i], lo[4 + i]);
+ }
+ // pass 2: the former rows, now down the columns again
+ Aan1D(lo);
+ Aan1D(hi);
+ for (int u = 0; u < 8; u++)
+ {
+ lo[u].CopyTo(coefficients.Slice(u * 8, 4));
+ hi[u].CopyTo(coefficients.Slice(u * 8 + 4, 4));
+ }
+ }
+
+ /// <summary>One 8-point AAN transform over the eight vectors (lane-wise), in place.</summary>
+ private static void Aan1D(Span<Vector128<float>> d)
+ {
+ Vector128<float> tmp0 = d[0] + d[7];
+ Vector128<float> tmp7 = d[0] - d[7];
+ Vector128<float> tmp1 = d[1] + d[6];
+ Vector128<float> tmp6 = d[1] - d[6];
+ Vector128<float> tmp2 = d[2] + d[5];
+ Vector128<float> tmp5 = d[2] - d[5];
+ Vector128<float> tmp3 = d[3] + d[4];
+ Vector128<float> tmp4 = d[3] - d[4];
+ // even part
+ Vector128<float> tmp10 = tmp0 + tmp3;
+ Vector128<float> tmp13 = tmp0 - tmp3;
+ Vector128<float> tmp11 = tmp1 + tmp2;
+ Vector128<float> tmp12 = tmp1 - tmp2;
+ d[0] = tmp10 + tmp11;
+ d[4] = tmp10 - tmp11;
+ Vector128<float> z1 = (tmp12 + tmp13) * Vector128.Create(0.707106781f);
+ d[2] = tmp13 + z1;
+ d[6] = tmp13 - z1;
+ // odd part
+ tmp10 = tmp4 + tmp5;
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+ Vector128<float> z5 = (tmp10 - tmp12) * Vector128.Create(0.382683433f);
+ Vector128<float> z2 = Vector128.Create(0.541196100f) * tmp10 + z5;
+ Vector128<float> z4 = Vector128.Create(1.306562965f) * tmp12 + z5;
+ Vector128<float> z3 = tmp11 * Vector128.Create(0.707106781f);
+ Vector128<float> z11 = tmp7 + z3;
+ Vector128<float> z13 = tmp7 - z3;
+ d[5] = z13 + z2;
+ d[3] = z13 - z2;
+ d[1] = z11 + z4;
+ d[7] = z11 - z4;
+ }
+
+ /// <summary>Transposes the 4 × 4 block of rows <paramref name="first"/> .. +3 in place (the classic unpack/move sequence).</summary>
+ private static void Transpose4(Span<Vector128<float>> rows, int first)
+ {
+ Vector128<float> r0 = rows[first];
+ Vector128<float> r1 = rows[first + 1];
+ Vector128<float> r2 = rows[first + 2];
+ Vector128<float> r3 = rows[first + 3];
+ Vector128<float> t0 = Sse.UnpackLow(r0, r1);
+ Vector128<float> t1 = Sse.UnpackLow(r2, r3);
+ Vector128<float> t2 = Sse.UnpackHigh(r0, r1);
+ Vector128<float> t3 = Sse.UnpackHigh(r2, r3);
+ rows[first] = Sse.MoveLowToHigh(t0, t1);
+ rows[first + 1] = Sse.MoveHighToLow(t1, t0);
+ rows[first + 2] = Sse.MoveLowToHigh(t2, t3);
+ rows[first + 3] = Sse.MoveHighToLow(t3, t2);
+ }
+
+ /// <summary>Transforms <paramref name="block"/> (64 samples, row-major) into <paramref name="coefficients"/> (64, row-major, u along the row).</summary>
+ public static void Forward(ReadOnlySpan<float> block, Span<float> coefficients)
+ {
+ if (Vector128.IsHardwareAccelerated)
+ {
+ ForwardVector(block, coefficients);
+ }
+ else
+ {
+ ForwardScalar(block, coefficients);
+ }
+ }
+
+ /// <summary>
+ /// Pass 1 down the columns with the lanes along x: T[v] = Σy C[v][y] · f[y]; pass 2 along the rows with the
+ /// lanes along u: F[v] = Σx T[v][x] · C[·][x], the column x of C as a vector.
+ /// </summary>
+ private static void ForwardVector(ReadOnlySpan<float> block, Span<float> coefficients)
+ {
+ Span<Vector128<float>> low = stackalloc Vector128<float>[8];
+ Span<Vector128<float>> high = stackalloc Vector128<float>[8];
+ for (int y = 0; y < 8; y++)
+ {
+ low[y] = Vector128.Create(block.Slice(y * 8, 4));
+ high[y] = Vector128.Create(block.Slice(y * 8 + 4, 4));
+ }
+ Span<float> t = stackalloc float[8];
+ for (int v = 0; v < 8; v++)
+ {
+ Vector128<float> c0 = Vector128.Create(Cosines[v * 8]);
+ Vector128<float> sumLow = c0 * low[0];
+ Vector128<float> sumHigh = c0 * high[0];
+ for (int y = 1; y < 8; y++)
+ {
+ Vector128<float> c = Vector128.Create(Cosines[v * 8 + y]);
+ sumLow += c * low[y];
+ sumHigh += c * high[y];
+ }
+ sumLow.CopyTo(t);
+ sumHigh.CopyTo(t[4..]);
+ Vector128<float> t0 = Vector128.Create(t[0]);
+ Vector128<float> resultLow = t0 * CosineColumnsLow[0];
+ Vector128<float> resultHigh = t0 * CosineColumnsHigh[0];
+ for (int x = 1; x < 8; x++)
+ {
+ Vector128<float> tx = Vector128.Create(t[x]);
+ resultLow += tx * CosineColumnsLow[x];
+ resultHigh += tx * CosineColumnsHigh[x];
+ }
+ resultLow.CopyTo(coefficients.Slice(v * 8, 4));
+ resultHigh.CopyTo(coefficients.Slice(v * 8 + 4, 4));
+ }
+ }
+
+ private static void ForwardScalar(ReadOnlySpan<float> block, Span<float> coefficients)
+ {
+ Span<float> rows = stackalloc float[64];
+ for (int y = 0; y < 8; y++)
+ {
+ for (int u = 0; u < 8; u++)
+ {
+ float sum = 0f;
+ for (int x = 0; x < 8; x++)
+ {
+ sum += block[y * 8 + x] * Cosines[u * 8 + x];
+ }
+ rows[y * 8 + u] = sum;
+ }
+ }
+ for (int u = 0; u < 8; u++)
+ {
+ for (int v = 0; v < 8; v++)
+ {
+ float sum = 0f;
+ for (int y = 0; y < 8; y++)
+ {
+ sum += rows[y * 8 + u] * Cosines[v * 8 + y];
+ }
+ coefficients[v * 8 + u] = sum;
+ }
+ }
+ }
+
+ /// <summary><c>½ C(u) cos((2x+1)uπ/16)</c>, indexed u × 8 + x, so a row pass and a column pass together give the ¼ C(u) C(v) scaling.</summary>
+ private static float[] MakeCosines()
+ {
+ var table = new float[64];
+ for (int u = 0; u < 8; u++)
+ {
+ double scale = (u == 0 ? Math.Sqrt(0.5) : 1.0) * 0.5;
+ for (int x = 0; x < 8; x++)
+ {
+ table[u * 8 + x] = (float)(scale * Math.Cos((2 * x + 1) * u * Math.PI / 16.0));
+ }
+ }
+ return table;
+ }
+
+ /// <summary>Column x of the cosine table as a vector over u = <paramref name="firstU"/> .. +3.</summary>
+ private static Vector128<float>[] MakeCosineColumns(int firstU)
+ {
+ var columns = new Vector128<float>[8];
+ var column = new float[4];
+ for (int x = 0; x < 8; x++)
+ {
+ for (int u = 0; u < 4; u++)
+ {
+ column[u] = Cosines[(firstU + u) * 8 + x];
+ }
+ columns[x] = Vector128.Create(column);
+ }
+ return columns;
+ }
+}
diff --git a/WaveDude/Model/Display.cs b/WaveDude/Model/Display.cs
index 8405eca..d45f008 100644
--- a/WaveDude/Model/Display.cs
+++ b/WaveDude/Model/Display.cs
@@ -19,6 +19,8 @@ public sealed class Display : ObservableObject
private Video _video = new();
private int _exportFrom;
private int _exportTo;
+ private bool _probeGraphsInExport = true;
+ private bool _probeMarkersInExport = true;
/// <summary>Rendering of the wave field.</summary>
[XmlElement]
@@ -74,6 +76,38 @@ public sealed class Display : ObservableObject
set => SetProperty(ref _exportTo, value);
}
+ /// <summary>
+ /// Whether an export draws the probes' graph boxes over the frames, as the author's program always did
+ /// (2026-10-14, his videos carried them; here a choice, on by default). The boxes are drawn at canvas
+ /// scale with the recording as it stood at each frame, like the preview shows them.
+ /// </summary>
+ [XmlAttribute]
+ [DefaultValue(true)]
+ [Category("Export")]
+ [DisplayName("Probe graphs in the export")]
+ [Description("Draw the probes' graph boxes over exported frames and videos.")]
+ public bool ProbeGraphsInExport
+ {
+ get => _probeGraphsInExport;
+ set => SetProperty(ref _probeGraphsInExport, value);
+ }
+
+ /// <summary>
+ /// Whether an export draws the probe markers over the frames in the author's style (2026-10-15): a cross at a
+ /// probe point, two crosses and the line for a line probe, black under white, and the probe's number
+ /// ("1", "1A"/"1B") beside it. His program always did; here a choice, on by default.
+ /// </summary>
+ [XmlAttribute]
+ [DefaultValue(true)]
+ [Category("Export")]
+ [DisplayName("Probe markers in the export")]
+ [Description("Draw the probes' positions (crosses, the line of a line probe, the number) over exported frames and videos.")]
+ public bool ProbeMarkersInExport
+ {
+ get => _probeMarkersInExport;
+ set => SetProperty(ref _probeMarkersInExport, value);
+ }
+
/// <summary>Tells <see cref="XmlSerializer"/> to leave all-default video settings out of the file.</summary>
public bool ShouldSerializeVideo() => Video.Fps != Video.DefaultFps || Video.Quality != Video.DefaultQuality;
@@ -112,7 +146,6 @@ public sealed class DisplayLayer : ObservableObject
private double _brightness = DefaultBrightness;
private double _blackLevel;
private bool _preview = true;
- private bool _export;
private bool _overlay = true;
private double _overlayGain = DefaultOverlayGain;
private bool _overlayInExport;
@@ -162,17 +195,6 @@ public sealed class DisplayLayer : ObservableObject
set => SetProperty(ref _preview, value);
}
- /// <summary>Whether the output's frames are written to a video file.</summary>
- [XmlAttribute]
- [DefaultValue(false)]
- [Category("Output")]
- [Description("Write this output's frames to a video file.")]
- public bool Export
- {
- get => _export;
- set => SetProperty(ref _export, value);
- }
-
/// <summary>
/// Whether the preview lays the scene image's "glowing edges" outline over this output (the author's
/// "Display overlay"; on by default here, 2026-10-13), so the scene layout shows under the field or
@@ -238,7 +260,7 @@ public sealed class Video : ObservableObject
/// <summary>Largest accepted <see cref="Fps"/>.</summary>
public const int MaxFps = 240;
/// <summary>Default <see cref="Quality"/>.</summary>
- public const int DefaultQuality = 70;
+ public const int DefaultQuality = 85;
private int _fps = DefaultFps;
private int _quality = DefaultQuality;
diff --git a/WaveDude/Model/LegacyProject.cs b/WaveDude/Model/LegacyProject.cs
index 39efc88..e4db563 100644
--- a/WaveDude/Model/LegacyProject.cs
+++ b/WaveDude/Model/LegacyProject.cs
@@ -135,8 +135,7 @@ public static class LegacyProject
Display display = project.Display;
display.Field.Preview = Bool(section, "preview_field", true);
display.Intensity.Preview = Bool(section, "preview_intensity", true);
- display.Field.Export = Bool(section, "export_field", false);
- display.Intensity.Export = Bool(section, "export_intensity", false);
+ // the author's "export on the next run" flags have no counterpart: export is a command here
display.Field.ColorScheme = Text(section, "field_color_scheme", Display.DefaultFieldColorScheme);
display.Intensity.ColorScheme = Text(section, "intensity_color_scheme", Display.DefaultIntensityColorScheme);
display.Field.Brightness = Double(section, "field_brightness", DisplayLayer.DefaultBrightness);
diff --git a/WaveDude/Runs/RunSpec.cs b/WaveDude/Runs/RunSpec.cs
index b3ef240..ec20fff 100644
--- a/WaveDude/Runs/RunSpec.cs
+++ b/WaveDude/Runs/RunSpec.cs
@@ -95,8 +95,9 @@ public sealed class RunSpec
/// <param name="project">The project to run; not modified beyond the emitter regeneration.</param>
/// <param name="image">The decoded scene image when <see cref="Scene.Mode"/> is <see cref="SceneMode.Image"/>; ignored otherwise.</param>
/// <param name="preferGpu">Try the OpenCL engine first (the application's choice; the CPU is the fallback either way).</param>
+ /// <param name="trackIntensity">Store the intensity plane even when nothing in the project needs it (an export of the intensity asks for it).</param>
/// <exception cref="RunSpecException">The project cannot run: no image for an image scene, or no steps.</exception>
- public static RunSpec Create(Project project, ScenePixels? image, bool preferGpu = true)
+ public static RunSpec Create(Project project, ScenePixels? image, bool preferGpu = true, bool trackIntensity = false)
{
project.Normalize();
if (project.Simulation.Steps < 1)
@@ -124,7 +125,7 @@ public sealed class RunSpec
width = project.Scene.Width;
height = project.Scene.Height;
}
- bool trackIntensity = project.Display.Intensity.Preview || project.Display.Intensity.Export
+ trackIntensity |= project.Display.Intensity.Preview
|| project.Probes.Any(probe => probe.Active && probe.Measurement != ProbeMeasurement.Amplitude);
return new RunSpec(project, image, width, height, trackIntensity, preferGpu);
}
diff --git a/Wave_Dude_Examples/Example2_Coherent_source/Example2_Coherent_source.wdproj b/Wave_Dude_Examples/Example2_Coherent_source/Example2_Coherent_source.wdproj
deleted file mode 100644
index 118acb8..0000000
--- a/Wave_Dude_Examples/Example2_Coherent_source/Example2_Coherent_source.wdproj
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project Version="1" Seed="1524560584">
- <Description>Featuring a 21 x 7 composite source that emits a continuous gaussian wave beam</Description>
- <Scene DampingEdge="64" />
- <Simulation Steps="4000" />
- <Display>
- <Field ColorScheme="Default_Field" Brightness="6" BlackLevel="-0.05" />
- <Intensity ColorScheme="inferno" Brightness="7" />
- </Display>
- <Source Name="Source 2" X="442" Y="580" Frequency="50" Amplitude="30">
- <Array SizeX="21" SizeY="7" SpacingX="32" SpacingY="16" />
- </Source>
- <Probe Name="Probe 1" Active="false" AX="1171" AY="226" BoxSize="Large" BoxX="13" BoxY="11" />
- <Probe Name="Probe 2" Layer="Intensity" Measurement="IntegratedIntensity" Kind="Line" AX="1051" AY="534" BX="1294" BY="957" BoxSize="ExtraLarge" BoxX="16" BoxY="13" YMin="0" YMax="0.005" />
-</Project>
\ No newline at end of file
diff --git a/_tools/library_check/ExportChecks.cs b/_tools/library_check/ExportChecks.cs
new file mode 100644
index 0000000..79b6868
--- /dev/null
+++ b/_tools/library_check/ExportChecks.cs
@@ -0,0 +1,896 @@
+using System.Buffers.Binary;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using WaveDude.Export;
+using WaveDude.Model;
+using WaveDude.Rendering;
+using WaveDude.Runs;
+
+namespace LibraryCheck;
+
+// The export formats and the export job: every writer produces a file that an independent decoder (the
+// ffmpeg found on the PATH, skipped when there is none) reads back with the right frame count and, for
+// the lossless ones, the same pixels; the PNG is also decoded in-house. The job renders a run's frames
+// into two sinks, calls the decoration per frame and ends in the right state.
+internal static class ExportChecks
+{
+ private static readonly string? Ffmpeg = FindFfmpeg();
+
+ public static void Run(Action<bool, string> check)
+ {
+ Console.WriteLine("--- export: encoders" + (Ffmpeg == null ? " (no ffmpeg on the PATH: decoding checks skipped)" : " (decoded with " + Ffmpeg + ")"));
+ string folder = Path.Combine(Path.GetTempPath(), "library_check-export-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(folder);
+ try
+ {
+ const int w = 70; // not a multiple of 16, not even: exercises the padding of every format
+ const int h = 45;
+ int[][] frames = [.. Enumerable.Range(0, 7).Select(i => TestFrame(w, h, i))];
+
+ // PNG: decoded in-house (inflate + unfilter) and by ffmpeg
+ byte[] png = PngEncoder.Encode(frames[0], w, h);
+ check(png.Length > 8 && png[1] == (byte)'P' && png[2] == (byte)'N' && png[3] == (byte)'G', "png: signature");
+ int[]? decoded = DecodePng(png, w, h);
+ check(decoded != null && decoded.SequenceEqual(frames[0]), "png: in-house decode gives the frame back pixel for pixel");
+ string pngPath = Path.Combine(folder, "one.png");
+ File.WriteAllBytes(pngPath, png);
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(pngPath, w, h, out int count);
+ check(rgb != null && count == 1 && Psnr(rgb, frames[0], w, h) >= 99, "png: ffmpeg decodes it, identical" + Mismatch(rgb, frames[0], w, h));
+ }
+
+ // JPEG: a baseline file ffmpeg decodes close to the original
+ var jpeg = new JpegEncoder(w, h, 90);
+ byte[] jpg = jpeg.Encode(frames[0]);
+ check(jpg.Length > 4 && jpg[0] == 0xFF && jpg[1] == 0xD8 && jpg[^2] == 0xFF && jpg[^1] == 0xD9, "jpeg: SOI and EOI markers");
+ string jpgPath = Path.Combine(folder, "one.jpg");
+ 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)");
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(jpgPath, w, h, out int count);
+ double psnr = rgb == null ? 0 : Psnr(rgb, frames[0], w, h);
+ check(rgb != null && count == 1 && psnr > 30, "jpeg: ffmpeg decodes it at " + psnr.ToString("0.0", CultureInfo.InvariantCulture) + " dB (> 30)");
+ }
+
+ // MPEG-1: the frame rate table, the quantiser mapping, a 7-picture program stream
+ check(Mpeg1Writer.NearestFrameRateCode(60) == 8 && Mpeg1Writer.NearestFrameRateCode(29.97) == 4 && Mpeg1Writer.NearestFrameRateCode(240) == 8 && Mpeg1Writer.NearestFrameRateCode(1) == 1, "mpeg-1: nearest frame rate codes (60 → 8, 29.97 → 4, 240 → 8, 1 → 1)");
+ check(Mpeg1Writer.QuantiserScaleFor(100) == 1 && Mpeg1Writer.QuantiserScaleFor(1) == 31 && Mpeg1Writer.QuantiserScaleFor(70) == 6 && Mpeg1Writer.QuantiserScaleFor(50) == 12, "mpeg-1: quantiser scale 1 at 100, 31 at 1, 6 at 70, 12 at 50");
+ string mpgPath = Path.Combine(folder, "seven.mpg");
+ using (var mpeg = new Mpeg1Writer(mpgPath, w, h, 30, 85))
+ {
+ check(mpeg.FrameRate == 30 && mpeg.QuantiserScale == 3, "mpeg-1: 30 fps, quantiser 3 at quality 85");
+ foreach (int[] frame in frames)
+ {
+ mpeg.Add(frame);
+ }
+ check(mpeg.FrameCount == 7, "mpeg-1: 7 pictures taken");
+ }
+ byte[] mpg = File.ReadAllBytes(mpgPath);
+ check(mpg.Length > 100 && mpg[0] == 0 && mpg[1] == 0 && mpg[2] == 1 && mpg[3] == 0xBA && mpg[^4] == 0 && mpg[^3] == 0 && mpg[^2] == 1 && mpg[^1] == 0xB9, "mpeg-1: starts with a pack header, ends with the program end code");
+ check(CountStartCodes(mpg, 0xB3) == 1 && CountStartCodes(mpg, 0x00) == 7 && CountStartCodes(mpg, 0xB7) == 1, "mpeg-1: one sequence header, seven picture headers, one sequence end");
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(mpgPath, w, h, out int count);
+ double worst = 99;
+ if (rgb != null && count == 7)
+ {
+ for (int i = 0; i < 7; i++)
+ {
+ worst = Math.Min(worst, Psnr(rgb.AsSpan(i * w * h * 3, w * h * 3), frames[i], w, h));
+ }
+ }
+ check(rgb != null && count == 7 && worst > 28, "mpeg-1: ffmpeg decodes 7 pictures, worst " + worst.ToString("0.0", CultureInfo.InvariantCulture) + " dB (> 28)" + (count != 7 ? ", got " + count : ""));
+ }
+
+ // AVI: three segments forced by a small limit, the structure walked, decoded pixel for pixel
+ string aviPath = Path.Combine(folder, "seven.avi");
+ int rowBytes = (w * 3 + 3) & ~3;
+ long chunk = 8 + (long)rowBytes * h;
+ using (var avi = new AviWriter(aviPath, w, h, 25, 7, segmentLimit: 3 * chunk + 1200))
+ {
+ foreach (int[] frame in frames)
+ {
+ avi.Add(frame);
+ }
+ check(avi.SegmentCount >= 2, "avi: the small limit split the frames over " + avi.SegmentCount + " segments");
+ check(avi.SizeOf(7) > 7 * chunk, "avi: predicted size covers the frames");
+ }
+ long aviSize = new FileInfo(aviPath).Length;
+ byte[] avi1 = File.ReadAllBytes(aviPath);
+ check(Fourcc(avi1, 0) == "RIFF" && Fourcc(avi1, 8) == "AVI " && Fourcc(avi1, 12) == "LIST" && Fourcc(avi1, 20) == "hdrl" && Fourcc(avi1, 24) == "avih", "avi: RIFF AVI, LIST hdrl, avih");
+ AviWalk walk = WalkAvi(avi1);
+ check(walk.Segments >= 2 && walk.Frames == 7 && walk.TotalInDmlh == 7 && walk.Idx1Entries == walk.FramesInFirst && walk.StandardIndexes == walk.Segments && walk.SuperEntries == walk.Segments,
+ "avi: " + walk.Segments + " segments hold 7 frames, dmlh says 7, idx1 covers the first segment's " + walk.FramesInFirst + ", one ix00 per segment, the super index lists them");
+ check(walk.EndsAtFileEnd && walk.FirstRiffSize == walk.FirstSegmentBytes - 8, "avi: segment sizes add up to the file (" + aviSize + " bytes)");
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(aviPath, w, h, out int count);
+ bool exact = rgb != null && count == 7;
+ for (int i = 0; exact && i < 7; i++)
+ {
+ exact = Psnr(rgb!.AsSpan(i * w * h * 3, w * h * 3), frames[i], w, h) >= 99;
+ }
+ check(exact, "avi: ffmpeg decodes 7 frames from all segments, identical" + (rgb == null ? "" : ", got " + count));
+ }
+ // a writer closed after one frame is a valid one-frame file
+ string shortPath = Path.Combine(folder, "short.avi");
+ using (var avi = new AviWriter(shortPath, w, h, 25, 7))
+ {
+ avi.Add(frames[3]);
+ }
+ AviWalk shortWalk = WalkAvi(File.ReadAllBytes(shortPath));
+ check(shortWalk.Segments == 1 && shortWalk.Frames == 1 && shortWalk.TotalInDmlh == 1 && shortWalk.EndsAtFileEnd, "avi: cancelled after one frame is a valid one-frame file");
+
+ // MP4: Media Foundation, when it is there
+ if (OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4))
+ {
+ string mp4Path = Path.Combine(folder, "seven.mp4");
+ try
+ {
+ using (var mp4 = new Mp4Writer(mp4Path, w, h, 30, 80))
+ {
+ foreach (int[] frame in frames)
+ {
+ mp4.Add(frame);
+ }
+ Console.WriteLine(" mp4: bitrate " + mp4.Bitrate + " bit/s" + (mp4.UsedBitrateOnly ? ", quality parameters refused" : ", quality parameters accepted"));
+ }
+ byte[] mp4Bytes = File.ReadAllBytes(mp4Path);
+ check(mp4Bytes.Length > 100 && Encoding.ASCII.GetString(mp4Bytes, 4, 4) == "ftyp", "mp4: ftyp box, " + mp4Bytes.Length + " bytes");
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(mp4Path, w, h, out int count);
+ double psnr = rgb == null || count < 1 ? 0 : Psnr(rgb.AsSpan(0, w * h * 3), frames[0], w, h);
+ check(rgb != null && count == 7 && psnr > 25, "mp4: ffmpeg decodes 7 frames, the first at " + psnr.ToString("0.0", CultureInfo.InvariantCulture) + " dB (> 25)" + (rgb == null ? "" : ", got " + count));
+ }
+ }
+ catch (Exception ex)
+ {
+ check(false, "mp4: " + ex.Message);
+ }
+ }
+ else
+ {
+ Console.WriteLine(" skip mp4: Media Foundation not available");
+ }
+
+ // formats
+ check(ExportFormats.FromPath(@"C:\x\a.JPEG") == ExportFormat.Jpeg && ExportFormats.FromPath("a.mpeg") == ExportFormat.Mpeg1 && ExportFormats.FromPath("a.txt") == null, "formats: extensions map, unknown is null");
+ check(ExportFormats.SequenceFolder(@"C:\Temp\chosenname.png") == @"C:\Temp\chosenname", "formats: a sequence chosen as C:\\Temp\\chosenname.png goes to C:\\Temp\\chosenname");
+ using (IFrameSink sink = ExportFormats.Open(ExportFormat.Png, Path.Combine(folder, "seq.png"), w, h, 30, 70, 3))
+ {
+ sink.Add(frames[1]);
+ sink.Add(frames[2]);
+ }
+ check(File.Exists(Path.Combine(folder, "seq", "seq_0000.png")) && File.Exists(Path.Combine(folder, "seq", "seq_0001.png")) && !File.Exists(Path.Combine(folder, "seq", "seq_0002.png")), "formats: the PNG sequence sink writes seq\\seq_0000.png and seq_0001.png");
+ check(DecodePng(File.ReadAllBytes(Path.Combine(folder, "seq", "seq_0001.png")), w, h)!.SequenceEqual(frames[2]), "formats: the second file holds the second frame");
+ string stillPath = Path.Combine(folder, "still.png");
+ using (IFrameSink still = ExportFormats.OpenStill(ExportFormat.Png, stillPath, w, h, 70))
+ {
+ still.Add(frames[4]);
+ bool refused = false;
+ try
+ {
+ still.Add(frames[5]);
+ }
+ catch (InvalidOperationException)
+ {
+ refused = true;
+ }
+ check(still.FrameCount == 1 && refused, "formats: a still takes one frame and refuses a second");
+ }
+ check(DecodePng(File.ReadAllBytes(stillPath), w, h)!.SequenceEqual(frames[4]), "formats: the still is the frame");
+ bool videoRefused = false;
+ try
+ {
+ ExportFormats.OpenStill(ExportFormat.Avi, Path.Combine(folder, "still.avi"), w, h, 70);
+ }
+ catch (NotSupportedException)
+ {
+ videoRefused = true;
+ }
+ check(videoRefused, "formats: a still is never a video");
+ // the author's marker strokes: a line probe's line and crosses, black radius 2 under white radius 1, clipped
+ var marked = new int[w * h];
+ var lineProbe = new Probe { Kind = ProbeKind.Line, AX = 10, AY = 10, BX = 60, BY = 30 };
+ ProbeMarkers.DrawStrokes(marked, w, h, lineProbe);
+ int white = unchecked((int)0xFFFFFFFF);
+ int black = unchecked((int)0xFF000000);
+ check(marked[10 * w + 10] == white && marked[30 * w + 60] == white && marked[20 * w + 35] == white, "markers: the crosses' centres and the line's middle are white");
+ var pointProbe = new Probe { Kind = ProbeKind.Point, AX = 40, AY = 40 };
+ ProbeMarkers.DrawStrokes(marked, w, h, pointProbe);
+ check(marked[42 * w + 42] == black && marked[42 * w + 38] == black && marked[40 * w + 44] == white && marked[(40 - ProbeMarkers.ArmLength(h) - 3) * w + 40] != black, "markers: the black stroke lies around the white one and ends with the arm");
+ check(ProbeMarkers.ArmLength(1080) == 9 && ProbeMarkers.ArmLength(100) == 6 && Math.Abs(ProbeMarkers.FontSize(1080) - 18f) < 0.01f && ProbeMarkers.LabelOrigin(100, 100, 1080) == (111, 66), "markers: the author's arm length, font size and label position at 1080p");
+ 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
+ // 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) =>
+ {
+ Interlocked.Increment(ref alternativeCalls);
+ if (((frame.Span[1] >> 16) & 0xFF) == secondFrameMark)
+ {
+ stream.WriteByte(0x42); // half-written: the fallback must rewind
+ throw new InvalidOperationException("the codec gave up");
+ }
+ PngEncoder.Write(stream, frame.Span, fw, fh); // recognisable: not a JPEG at all
+ };
+ using (IFrameSink alt = ExportFormats.Open(ExportFormat.Jpeg, Path.Combine(folder, "alt.jpg"), w, h, 30, 85, 3))
+ {
+ alt.Add(frames[0]);
+ alt.Add(frames[1]);
+ alt.Add(frames[2]);
+ }
+ ExportFormats.AlternativeJpeg = null;
+ 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");
+
+ CheckJob(check, folder);
+ }
+ finally
+ {
+ try
+ {
+ Directory.Delete(folder, recursive: true);
+ }
+ catch (IOException)
+ {
+ // a file still open by a decoder; the temp folder is cleaned up another day
+ }
+ }
+ }
+
+ /// <summary>A run of 10 frames exported to a PNG sequence (field, decorated) and an AVI (intensity); then a cancelled job.</summary>
+ private static void CheckJob(Action<bool, string> check, string folder)
+ {
+ // the frame numbers' width follows the planned count: four digits up to 10000 frames, five beyond (2026-10-15)
+ using (var narrow = new ImageSequenceSink(Path.Combine(folder, "narrow"), "f", ".png", 4, 4, () => (stream, px) => PngEncoder.Write(stream, px.Span, 4, 4), 1, 500))
+ using (var wide = new ImageSequenceSink(Path.Combine(folder, "wide"), "f", ".png", 4, 4, () => (stream, px) => PngEncoder.Write(stream, px.Span, 4, 4), 1, 12000))
+ {
+ check(narrow.Digits == 4 && narrow.PathOf(7).EndsWith("f_0007.png", StringComparison.Ordinal) && wide.Digits == 5 && wide.PathOf(7).EndsWith("f_00007.png", StringComparison.Ordinal) && wide.PathOf(10000).EndsWith("f_10000.png", StringComparison.Ordinal),
+ "sequence names: 4 digits for 500 frames, 5 for 12000, so they sort past frame 9999");
+ }
+ Console.WriteLine("--- export: job");
+ var project = new Project();
+ project.Scene.Width = 64;
+ project.Scene.Height = 48;
+ project.Simulation.Steps = 20;
+ project.Simulation.VisualizeEvery = 2;
+ Source source = project.AddSource();
+ source.X = 20;
+ source.Y = 24;
+ source.Frequency = 120;
+ RunSpec spec = RunSpec.Create(project, null, preferGpu: false);
+ string storePath = Path.Combine(folder, "job" + FrameCache.Extension);
+ using var store = FrameStore.Create(storePath, spec.Width, spec.Height, spec.Layers, spec.FrameCount, spec.VisualizeEvery);
+ using var run = new SimulationRun(spec, store, null);
+ run.Start();
+ check(run.Completion.Wait(30000) && store.Count == 10, "job: a 10-frame run to export");
+
+ int[] lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(scheme => scheme.Name == Display.DefaultFieldColorScheme)).Argb;
+ var decorated = new List<int>();
+ var fieldLayer = new ExportLayer(FrameLayer.Field, lut, 30f, null, 0, (frame, pixels) =>
+ {
+ decorated.Add(frame);
+ pixels.Span[0] = unchecked((int)0xFFFF0000); // a red pixel at the top left, to be found in the file
+ });
+ var intensityLayer = new ExportLayer(FrameLayer.Intensity, null, 30f, null, 0, null);
+ string seqPath = Path.Combine(folder, "field.png");
+ string aviPath = Path.Combine(folder, "intensity.avi");
+ var targets = new List<ExportTarget>
+ {
+ new(fieldLayer, ExportFormats.SequenceFolder(seqPath), () => ExportFormats.Open(ExportFormat.Png, seqPath, 64, 48, 30, 70, 6)),
+ new(intensityLayer, aviPath, () => ExportFormats.Open(ExportFormat.Avi, aviPath, 64, 48, 30, 70, 6)),
+ };
+ var job = new ExportJob(store, 2, 7, targets, null);
+ var states = new List<ExportState>();
+ job.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName == nameof(ExportJob.State))
+ {
+ states.Add(job.State);
+ }
+ };
+ int finished = 0;
+ job.Finished += (_, _) => finished++;
+ job.Start();
+ check(job.Completion.Wait(30000) && job.State == ExportState.Completed && finished == 1 && job.Error == null, "job: completes, Finished once");
+ check(targets.All(target => target.Sink != null && target.Sink.Output == target.Output), "job: the sinks were opened by the job, where the targets said");
+ check(states.SequenceEqual([ExportState.Running, ExportState.Completed]) && job.FramesDone == 6 && job.FrameCount == 6, "job: Running then Completed, 6 of 6 frames");
+ check(decorated.SequenceEqual([2, 3, 4, 5, 6, 7]), "job: the decoration saw frames 2 to 7 in order");
+ string[] files = Directory.GetFiles(Path.Combine(folder, "field"));
+ check(files.Length == 6 && File.Exists(Path.Combine(folder, "field", "field_0005.png")), "job: six PNGs, field_0000 to field_0005");
+ // the first file is frame 2 rendered with the same LUT and gain, plus the decoration
+ var values = new Half[64 * 48];
+ var expected = new int[64 * 48];
+ store.CopyLayer(2, FrameLayer.Field, values);
+ FrameRenderer.RenderField(values, 64, 48, lut, 30f, expected);
+ expected[0] = unchecked((int)0xFFFF0000);
+ int[]? first = DecodePng(File.ReadAllBytes(Path.Combine(folder, "field", "field_0000.png")), 64, 48);
+ check(first != null && first.SequenceEqual(expected), "job: field_0000.png is frame 2 as the renderer colours it, with the decoration");
+ AviWalk walk = WalkAvi(File.ReadAllBytes(aviPath));
+ check(walk.Frames == 6 && walk.TotalInDmlh == 6 && walk.EndsAtFileEnd, "job: the intensity AVI holds 6 frames");
+
+ // cancelled: a slow decoration lets the cancel land after the first frame
+ using var started = new ManualResetEventSlim();
+ var slowLayer = new ExportLayer(FrameLayer.Field, lut, 30f, null, 0, (_, _) =>
+ {
+ started.Set();
+ Thread.Sleep(150);
+ });
+ string cancelPath = Path.Combine(folder, "cancel.avi");
+ var cancelled = new ExportJob(store, 0, 9, [new ExportTarget(slowLayer, cancelPath, () => ExportFormats.Open(ExportFormat.Avi, cancelPath, 64, 48, 30, 70, 10))], null);
+ cancelled.Start();
+ started.Wait(10000);
+ cancelled.Cancel();
+ check(cancelled.Completion.Wait(10000) && cancelled.State == ExportState.Cancelled && cancelled.FramesDone >= 1 && cancelled.FramesDone < 10, "job: cancel ends it Cancelled after " + cancelled.FramesDone + " frames");
+ AviWalk cancelWalk = WalkAvi(File.ReadAllBytes(cancelPath));
+ check(cancelWalk.Frames == cancelled.FramesDone && cancelWalk.EndsAtFileEnd, "job: the cancelled AVI is a valid file of the frames written");
+
+ // a frame beyond the store fails the job, the sinks still close
+ string failPath = Path.Combine(folder, "fail.avi");
+ var failing = new ExportJob(store, 8, 12, [new ExportTarget(intensityLayer, failPath, () => ExportFormats.Open(ExportFormat.Avi, failPath, 64, 48, 30, 70, 5))], null);
+ failing.Start();
+ check(failing.Completion.Wait(10000) && failing.State == ExportState.Failed && failing.Error is InvalidOperationException && failing.FramesDone == 2, "job: a frame beyond the store fails it after the 2 that exist");
+ // a sink that cannot open fails the job before any frame, with the error kept
+ var unopenable = new ExportJob(store, 0, 1, [new ExportTarget(intensityLayer, "nowhere", () => throw new IOException("no such drive"))], null);
+ unopenable.Start();
+ check(unopenable.Completion.Wait(10000) && unopenable.State == ExportState.Failed && unopenable.Error is IOException && unopenable.FramesDone == 0, "job: a sink that cannot open fails the job with its error");
+ // an MP4 written by the job: the Media Foundation writer lives on the job's thread (it refused a caller's thread, 2026-10-14)
+ if (OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4))
+ {
+ string mp4Path = Path.Combine(folder, "job.mp4");
+ var mp4Job = new ExportJob(store, 0, 9, [new ExportTarget(fieldLayer, mp4Path, () => ExportFormats.Open(ExportFormat.Mp4, mp4Path, 64, 48, 30, 70, 10))], null);
+ mp4Job.Start();
+ check(mp4Job.Completion.Wait(30000) && mp4Job.State == ExportState.Completed && mp4Job.FramesDone == 10 && new FileInfo(mp4Path).Length > 100, "job: an MP4 of 10 frames written on the job's thread" + (mp4Job.Error != null ? " (" + mp4Job.Error.Message + ")" : ""));
+ }
+ }
+
+ /// <summary>Per-frame cost of every encoder at a given size, for `-- bench-export [w h]`.</summary>
+ public static void Bench(int w, int h)
+ {
+ Console.WriteLine($"--- export bench {w} x {h}, {Environment.ProcessorCount} cores");
+ int[] frame = TestFrame(w, h, 3);
+ string folder = Path.Combine(Path.GetTempPath(), "library_check-bench-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(folder);
+ try
+ {
+ Time("png encode", () => PngEncoder.Encode(frame, w, h), 3);
+ 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);
+ Time(" of which yuv conversion", () => planes.Convert(frame), 5);
+ jpeg.ParallelRows = false;
+ Time("jpeg encode, rows one after the other", () => jpeg.Encode(frame), 3);
+ Console.WriteLine($" phases: convert {jpeg.LastPhases.Convert:0.0} ms, rows {jpeg.LastPhases.Rows:0.0} ms");
+ jpeg.ParallelRows = true;
+ foreach (int threads in new[] { 1, 2, 4, Environment.ProcessorCount })
+ {
+ jpeg.MaxThreads = threads;
+ 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
+ if (OperatingSystem.IsWindows())
+ {
+ byte[] inHouse = jpeg.Encode(frame);
+ byte[] wic = [];
+ Time("jpeg encode by WIC (q 85)", () => wic = WicEncode(frame, w, h, 85), 5);
+ File.WriteAllBytes(Path.Combine(folder, "wic.jpg"), wic);
+ File.WriteAllBytes(Path.Combine(folder, "inhouse.jpg"), inHouse);
+ double wicDb = 0;
+ double inHouseDb = 0;
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(Path.Combine(folder, "wic.jpg"), w, h, out int n);
+ wicDb = rgb == null || n != 1 ? 0 : Psnr(rgb, frame, w, h);
+ rgb = Decode(Path.Combine(folder, "inhouse.jpg"), w, h, out n);
+ inHouseDb = rgb == null || n != 1 ? 0 : Psnr(rgb, frame, w, h);
+ }
+ Console.WriteLine($" at quality 85: WIC {wic.Length / 1024} KB at {wicDb:0.0} dB, in-house {inHouse.Length / 1024} KB at {inHouseDb:0.0} dB");
+ foreach (int q in new[] { 50, 70, 95 })
+ {
+ byte[] a = WicEncode(frame, w, h, q);
+ byte[] b = new JpegEncoder(w, h, q).Encode(frame);
+ Console.WriteLine($" at quality {q}: WIC {a.Length / 1024} KB, in-house {b.Length / 1024} KB");
+ }
+ }
+ // the per-block costs, single-threaded over as many blocks as a frame has
+ int blocks = planes.MacroblockColumns * planes.MacroblockRows * 6;
+ 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);
+ Time($" {blocks} DCTs", () => { for (int i = 0; i < blocks; i++) { Dct8x8.Forward(block, dct); } }, 3);
+ var bits = new BitWriter(1 << 20, stuffJpeg: true);
+ Time($" {blocks * 40} bit fields", () => { bits.Reset(); for (int i = 0; i < blocks * 40; i++) { bits.Write((uint)i, 7); } }, 3);
+ using (var mpeg = new Mpeg1Writer(Path.Combine(folder, "b.mpg"), w, h, 30, 85))
+ {
+ Time("mpeg-1 picture", () => mpeg.Add(frame), 5);
+ }
+ using (var avi = new AviWriter(Path.Combine(folder, "b.avi"), w, h, 30, 100))
+ {
+ Time("avi frame (uncompressed)", () => avi.Add(frame), 5);
+ }
+ if (OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4))
+ {
+ using var mp4 = new Mp4Writer(Path.Combine(folder, "b.mp4"), w, h, 30, 85);
+ Console.WriteLine(" mp4: " + (mp4.Nv12Input ? "NV12" : "RGB32") + " in, " + mp4.Transforms + (mp4.HasDirect3D ? ", Direct3D device shared" : ", system memory") + "; hardware H.264 encoders registered: " + string.Join(", ", Mp4Writer.AvailableEncoders(hardwareOnly: true).DefaultIfEmpty("none")));
+ Time("mp4 frame (Media Foundation)", () => mp4.Add(frame), 10);
+ }
+ // the sequence sink's workers: PNG with one worker and with the default, ten frames each
+ foreach (int workers in new[] { 1, ExportFormats.SequenceWorkers(encoderIsParallel: false) })
+ {
+ string seqFolder = Path.Combine(folder, "scale" + workers);
+ var clock = Stopwatch.StartNew();
+ using (var seq = new ImageSequenceSink(seqFolder, "f", ".png", w, h, () => (stream, px) => PngEncoder.Write(stream, px.Span, w, h), workers))
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ seq.Add(frame);
+ }
+ }
+ Console.WriteLine($" png sequence sink, {workers} worker(s): {clock.Elapsed.TotalMilliseconds / 10:0.0} ms per frame");
+ }
+ // the whole job over a real store: a short run at this size (GPU when it works), then each format
+ var project = new Project();
+ project.Scene.Width = w;
+ project.Scene.Height = h;
+ project.Simulation.Steps = 120;
+ project.Simulation.VisualizeEvery = 2;
+ Source source = project.AddSource();
+ source.X = w / 2;
+ source.Y = h / 2;
+ source.Frequency = 120;
+ RunSpec spec = RunSpec.Create(project, null, preferGpu: true);
+ using var store = FrameStore.Create(Path.Combine(folder, "bench" + FrameCache.Extension), spec.Width, spec.Height, spec.Layers, spec.FrameCount, spec.VisualizeEvery);
+ using (var run = new SimulationRun(spec, store, null))
+ {
+ run.Start();
+ run.Completion.Wait();
+ Console.WriteLine(" run: " + run.EngineDescription + ", " + store.Count + " frames");
+ }
+ int[] lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(scheme => scheme.Name == Display.DefaultFieldColorScheme)).Argb;
+ // the MP4 writer alone on the run's real frames, rendered up front: input format and rate control compared
+ if (OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4))
+ {
+ var rendered = new List<int[]>();
+ var values = new Half[w * h];
+ for (int i = 0; i < store.Count; i++)
+ {
+ var px = new int[w * h];
+ store.CopyLayer(i, FrameLayer.Field, values);
+ FrameRenderer.RenderField(values, w, h, lut, 30f, px);
+ rendered.Add(px);
+ }
+ // the declared frame rate is varied too: if the time per frame tracks it, the encoder paces itself to real time
+ foreach ((string label, bool nv12, bool quality, int fps, bool d3d, bool fastest) in new[] { ("NV12, quality mode, Direct3D", true, true, 30, true, false), ("NV12, quality mode, Direct3D, fastest", true, true, 30, true, true), ("NV12, bitrate mode, Direct3D, fastest", true, false, 30, true, true), ("NV12, quality mode, system memory, fastest", true, true, 30, false, true) })
+ {
+ Mp4Writer.PreferNv12 = nv12;
+ Mp4Writer.QualityMode = quality;
+ Mp4Writer.UseDirect3D = d3d;
+ Mp4Writer.Fastest = fastest;
+ var clock = Stopwatch.StartNew();
+ using (var writer = new Mp4Writer(Path.Combine(folder, "real.mp4"), w, h, fps, 85))
+ {
+ foreach (int[] px in rendered)
+ {
+ writer.Add(px);
+ }
+ }
+ double psnr = 0;
+ int probe = Math.Min(30, rendered.Count - 1);
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(Path.Combine(folder, "real.mp4"), w, h, out int n);
+ psnr = rgb == null || n <= probe ? 0 : Psnr(rgb.AsSpan(probe * w * h * 3, w * h * 3), rendered[probe], w, h);
+ }
+ Console.WriteLine($" mp4 writer alone on {rendered.Count} real frames, {label}: {clock.Elapsed.TotalMilliseconds / rendered.Count:0.0} ms per frame, {new FileInfo(Path.Combine(folder, "real.mp4")).Length / 1024} KB, frame {probe} at {psnr:0.0} dB");
+ }
+ Mp4Writer.PreferNv12 = true;
+ Mp4Writer.QualityMode = true;
+ Mp4Writer.UseDirect3D = true;
+ Mp4Writer.Fastest = false;
+ // the same frames through ffmpeg's encoders, as a reference for what the hardware and a CPU encoder do outside Media Foundation
+ if (Ffmpeg != null)
+ {
+ string raw = Path.Combine(folder, "real.bgra");
+ using (var rawStream = new FileStream(raw, FileMode.Create))
+ {
+ foreach (int[] px in rendered)
+ {
+ rawStream.Write(System.Runtime.InteropServices.MemoryMarshal.AsBytes(px.AsSpan()));
+ }
+ }
+ foreach ((string label, string[] codec) in new[] { ("h264_nvenc", new[] { "-c:v", "h264_nvenc", "-preset", "fast", "-b:v", "17M" }), ("libx264 ultrafast", new[] { "-c:v", "libx264", "-preset", "ultrafast", "-b:v", "17M" }) })
+ {
+ var info = new ProcessStartInfo(Ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true };
+ foreach (string a in new[] { "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgra", "-s", $"{w}x{h}", "-r", "30", "-i", raw })
+ {
+ info.ArgumentList.Add(a);
+ }
+ foreach (string a in codec)
+ {
+ info.ArgumentList.Add(a);
+ }
+ info.ArgumentList.Add(Path.Combine(folder, "ref.mp4"));
+ var clock = Stopwatch.StartNew();
+ using Process p = Process.Start(info)!;
+ string err = p.StandardError.ReadToEnd();
+ p.WaitForExit();
+ Console.WriteLine(p.ExitCode == 0
+ ? $" ffmpeg {label} on the same frames: {clock.Elapsed.TotalMilliseconds / rendered.Count:0.0} ms per frame including the raw read ({new FileInfo(Path.Combine(folder, "ref.mp4")).Length / 1024} KB)"
+ : $" ffmpeg {label}: not available ({err.Trim().Split('\n').LastOrDefault()})");
+ }
+ File.Delete(raw);
+ }
+ }
+ 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); }),
+ ("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)),
+ ("mp4", () => ExportFormats.Open(ExportFormat.Mp4, Path.Combine(folder, "j.mp4"), w, h, 30, 85, 60)),
+ ("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)))
+ {
+ continue;
+ }
+ var layer = new ExportLayer(FrameLayer.Field, lut, 30f, null, 0, null);
+ var job = new ExportJob(store, 0, store.Count - 1, [new ExportTarget(layer, name, open)], null);
+ var clock = Stopwatch.StartNew();
+ job.Start();
+ job.Completion.Wait();
+ Console.WriteLine($" job to {name}: {clock.Elapsed.TotalMilliseconds / store.Count:0.0} ms per frame ({job.State})");
+ ExportFormats.AlternativeJpeg = null;
+ Mp4Writer.Throttle = true;
+ }
+ }
+ finally
+ {
+ Directory.Delete(folder, recursive: true);
+ }
+ }
+
+ /// <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)
+ {
+ 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();
+ }
+
+ private static void Time(string what, Action action, int repeats)
+ {
+ // warm up past the JIT's tiering (a method is recompiled after 30 calls; timing the first ones gave twice the cost, 2026-10-15)
+ for (int i = 0; i < 40; i++)
+ {
+ action();
+ }
+ Thread.Sleep(150); // the recompilation happens in the background
+ var clock = Stopwatch.StartNew();
+ for (int i = 0; i < repeats; i++)
+ {
+ action();
+ }
+ Console.WriteLine($" {what}: {clock.Elapsed.TotalMilliseconds / repeats:0.0} ms");
+ }
+
+ // ---------------------------------------------------------------- helpers
+
+ /// <summary>A test picture: a diagonal gradient with a bright moving square and a few saturated pixels, different per frame.</summary>
+ private static int[] TestFrame(int w, int h, int index)
+ {
+ var pixels = new int[w * h];
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ // smooth ramps (no wrap-around: a 4:2:0 format blurs a hard colour edge and that would dominate the PSNR)
+ int r = Math.Min(255, x * 255 / Math.Max(1, w - 1) + index * 8);
+ int g = y * 255 / Math.Max(1, h - 1);
+ int b = Math.Min(255, (x + y) * 255 / (w + h) + index * 12);
+ pixels[y * w + x] = unchecked((int)0xFF000000) | (r << 16) | (g << 8) | b;
+ }
+ }
+ int left = 5 + index * 6;
+ for (int y = 8; y < 24; y++)
+ {
+ for (int x = left; x < left + 16 && x < w; x++)
+ {
+ pixels[y * w + x] = unchecked((int)0xFFFFFFFF);
+ }
+ }
+ pixels[0] = unchecked((int)0xFFFF0000);
+ pixels[w - 1] = unchecked((int)0xFF00FF00);
+ pixels[(h - 1) * w] = unchecked((int)0xFF0000FF);
+ return pixels;
+ }
+
+ private static string? FindFfmpeg()
+ {
+ foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator))
+ {
+ string candidate = Path.Combine(dir.Trim(), OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg");
+ if (dir.Length > 0 && File.Exists(candidate))
+ {
+ return candidate;
+ }
+ }
+ return null;
+ }
+
+ /// <summary>Decodes a file with ffmpeg to packed RGB24 frames of w × h and counts them; null when ffmpeg failed.</summary>
+ private static byte[]? Decode(string path, int w, int h, out int frames)
+ {
+ frames = 0;
+ var info = new ProcessStartInfo(Ffmpeg!)
+ {
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ };
+ foreach (string arg in new[] { "-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-" })
+ {
+ info.ArgumentList.Add(arg);
+ }
+ using Process process = Process.Start(info)!;
+ using var output = new MemoryStream();
+ Task<string> errors = process.StandardError.ReadToEndAsync();
+ process.StandardOutput.BaseStream.CopyTo(output);
+ process.WaitForExit();
+ string error = errors.Result;
+ if (process.ExitCode != 0 || output.Length == 0)
+ {
+ Console.WriteLine(" ffmpeg: exit " + process.ExitCode + " " + error.Trim());
+ return null;
+ }
+ if (error.Trim().Length > 0)
+ {
+ Console.WriteLine(" ffmpeg: " + error.Trim());
+ }
+ byte[] bytes = output.ToArray();
+ frames = bytes.Length / (w * h * 3);
+ return bytes;
+ }
+
+ /// <summary>For a failure message: the first pixel where RGB24 bytes differ from the frame, with both values.</summary>
+ private static string Mismatch(byte[]? rgb, int[] frame, int w, int h)
+ {
+ if (rgb == null)
+ {
+ return " (no output)";
+ }
+ if (rgb.Length != w * h * 3)
+ {
+ return " (" + rgb.Length + " bytes, expected " + w * h * 3 + ")";
+ }
+ for (int i = 0; i < w * h; i++)
+ {
+ int argb = frame[i];
+ if (rgb[i * 3] != ((argb >> 16) & 0xFF) || rgb[i * 3 + 1] != ((argb >> 8) & 0xFF) || rgb[i * 3 + 2] != (argb & 0xFF))
+ {
+ return " (pixel " + i + " at " + i % w + "," + i / w + ": got " + rgb[i * 3] + "," + rgb[i * 3 + 1] + "," + rgb[i * 3 + 2] + ", expected " + ((argb >> 16) & 0xFF) + "," + ((argb >> 8) & 0xFF) + "," + (argb & 0xFF) + ")";
+ }
+ }
+ return "";
+ }
+
+ /// <summary>PSNR in dB of RGB24 bytes against a BGRA32 frame; 99 for identical.</summary>
+ private static double Psnr(ReadOnlySpan<byte> rgb, int[] frame, int w, int h)
+ {
+ double sum = 0;
+ int n = w * h;
+ for (int i = 0; i < n; i++)
+ {
+ int argb = frame[i];
+ int dr = rgb[i * 3] - ((argb >> 16) & 0xFF);
+ int dg = rgb[i * 3 + 1] - ((argb >> 8) & 0xFF);
+ int db = rgb[i * 3 + 2] - (argb & 0xFF);
+ sum += dr * dr + dg * dg + db * db;
+ }
+ double mse = sum / (3.0 * n);
+ return mse == 0 ? 99 : 10 * Math.Log10(255.0 * 255.0 / mse);
+ }
+
+ /// <summary>Decodes an 8-bit RGB PNG with any of the five filters; null when it is not one.</summary>
+ private static int[]? DecodePng(byte[] png, int w, int h)
+ {
+ int p = 8;
+ using var idat = new MemoryStream();
+ while (p + 8 <= png.Length)
+ {
+ int length = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(p));
+ string type = Encoding.ASCII.GetString(png, p + 4, 4);
+ if (type == "IHDR" && (BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(p + 8)) != w || BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(p + 12)) != h || png[p + 16] != 8 || png[p + 17] != 2))
+ {
+ return null;
+ }
+ if (type == "IDAT")
+ {
+ idat.Write(png, p + 8, length);
+ }
+ if (Crc32.Of(png.AsSpan(p + 4, 4 + length)) != BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(p + 8 + length)))
+ {
+ return null;
+ }
+ p += 12 + length;
+ }
+ idat.Position = 0;
+ using var zlib = new ZLibStream(idat, CompressionMode.Decompress);
+ int rowBytes = w * 3;
+ var raw = new byte[(rowBytes + 1) * h];
+ zlib.ReadExactly(raw);
+ var previous = new byte[rowBytes];
+ var current = new byte[rowBytes];
+ var pixels = new int[w * h];
+ for (int y = 0; y < h; y++)
+ {
+ int filter = raw[y * (rowBytes + 1)];
+ for (int i = 0; i < rowBytes; i++)
+ {
+ int x = raw[y * (rowBytes + 1) + 1 + i];
+ int a = i >= 3 ? current[i - 3] : 0;
+ int b = previous[i];
+ int c = i >= 3 ? previous[i - 3] : 0;
+ int predictor = filter switch
+ {
+ 1 => a,
+ 2 => b,
+ 3 => (a + b) / 2,
+ 4 => Paeth(a, b, c),
+ _ => 0,
+ };
+ current[i] = (byte)(x + predictor);
+ }
+ for (int x = 0; x < w; x++)
+ {
+ pixels[y * w + x] = unchecked((int)0xFF000000) | (current[x * 3] << 16) | (current[x * 3 + 1] << 8) | current[x * 3 + 2];
+ }
+ (previous, current) = (current, previous);
+ }
+ return pixels;
+ }
+
+ private static int Paeth(int a, int b, int c)
+ {
+ int p = a + b - c;
+ int pa = Math.Abs(p - a);
+ int pb = Math.Abs(p - b);
+ int pc = Math.Abs(p - c);
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
+ }
+
+ private static int CountStartCodes(byte[] data, byte code)
+ {
+ int count = 0;
+ for (int i = 0; i + 3 < data.Length; i++)
+ {
+ if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 && data[i + 3] == code)
+ {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ private static string Fourcc(byte[] data, long offset) => Encoding.ASCII.GetString(data, (int)offset, 4);
+
+ private sealed class AviWalk
+ {
+ public int Segments;
+ public int Frames;
+ public int FramesInFirst;
+ public int Idx1Entries;
+ public int StandardIndexes;
+ public int SuperEntries;
+ public int TotalInDmlh;
+ public long FirstRiffSize;
+ public long FirstSegmentBytes;
+ public bool EndsAtFileEnd;
+ }
+
+ /// <summary>Walks the RIFF segments of an AVI, counting frames, indexes and the OpenDML entries.</summary>
+ private static AviWalk WalkAvi(byte[] data)
+ {
+ var walk = new AviWalk();
+ long p = 0;
+ while (p + 12 <= data.Length && Fourcc(data, p) == "RIFF")
+ {
+ long riffSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan((int)p + 4));
+ long end = p + 8 + riffSize;
+ bool first = walk.Segments == 0;
+ if (first)
+ {
+ walk.FirstRiffSize = riffSize;
+ walk.FirstSegmentBytes = end;
+ }
+ walk.Segments++;
+ long q = p + 12;
+ while (q + 8 <= end)
+ {
+ string id = Fourcc(data, q);
+ int size = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan((int)q + 4));
+ if (id == "LIST")
+ {
+ string type = Fourcc(data, q + 8);
+ if (type == "movi")
+ {
+ long r = q + 12;
+ long moviEnd = q + 8 + size;
+ while (r + 8 <= moviEnd)
+ {
+ string chunk = Fourcc(data, r);
+ int chunkSize = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan((int)r + 4));
+ if (chunk == "00db")
+ {
+ walk.Frames++;
+ if (first)
+ {
+ walk.FramesInFirst++;
+ }
+ }
+ else if (chunk == "ix00")
+ {
+ walk.StandardIndexes++;
+ }
+ r += 8 + chunkSize + (chunkSize & 1);
+ }
+ }
+ else if (type == "hdrl")
+ {
+ // find indx inside strl, and dmlh is in the odml list that follows hdrl
+ int at = IndexOf(data, "indx"u8, (int)q, (int)(q + 8 + size));
+ if (at >= 0)
+ {
+ walk.SuperEntries = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(at + 12));
+ }
+ }
+ else if (type == "odml")
+ {
+ walk.TotalInDmlh = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan((int)q + 20));
+ }
+ }
+ else if (id == "idx1")
+ {
+ walk.Idx1Entries = size / 16;
+ }
+ q += 8 + size + (size & 1);
+ }
+ p = end;
+ }
+ walk.EndsAtFileEnd = p == data.Length;
+ return walk;
+ }
+
+ private static int IndexOf(byte[] data, ReadOnlySpan<byte> needle, int from, int to)
+ {
+ for (int i = from; i + needle.Length <= Math.Min(to, data.Length); i++)
+ {
+ if (data.AsSpan(i, needle.Length).SequenceEqual(needle))
+ {
+ return i;
+ }
+ }
+ return -1;
+ }
+}
diff --git a/_tools/library_check/LibraryCheck.csproj b/_tools/library_check/LibraryCheck.csproj
index 52a6c17..865f7d0 100644
--- a/_tools/library_check/LibraryCheck.csproj
+++ b/_tools/library_check/LibraryCheck.csproj
@@ -4,12 +4,19 @@
Not part of the solution; run with "dotnet run" on this project (Release) -->
<PropertyGroup>
<OutputType>Exe</OutputType>
- <TargetFramework>net10.0</TargetFramework>
+ <!-- Windows with WPF, for the bench of the WIC JPEG encoder (the library itself stays net10.0) -->
+ <TargetFramework>net10.0-windows</TargetFramework>
+ <UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>LibraryCheck</RootNamespace>
</PropertyGroup>
+ <!-- UseWPF drops System.IO from the implicit usings -->
+ <ItemGroup>
+ <Using Include="System.IO" />
+ </ItemGroup>
+
<ItemGroup>
<ProjectReference Include="..\..\WaveDude\WaveDude.csproj" />
</ItemGroup>
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index a1677c9..b4b06b6 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -155,6 +155,18 @@ internal static class Program
}
return 0;
}
+ if (args.Length > 0 && args[0] == "bench-export")
+ {
+ ExportChecks.Bench(args.Length > 1 ? int.Parse(args[1]) : 1920, args.Length > 2 ? int.Parse(args[2]) : 1080);
+ return 0;
+ }
+ if (args.Length > 0 && args[0] == "export")
+ {
+ // just the export checks (they take a few seconds and need no engine)
+ ExportChecks.Run(Check);
+ Console.WriteLine(_failures == 0 ? "EXPORT OK" : _failures + " check(s) failed");
+ return _failures == 0 ? 0 : 1;
+ }
const int W = 64, H = 48, Steps = 200;
(byte[] bgra, int stride) = ScenePixels(W, H);
SceneData scene = SceneData.FromBgra(bgra, W, H, stride, true, 6);
@@ -172,6 +184,7 @@ internal static class Program
CheckProbeGraph();
CheckImport();
CheckRun();
+ ExportChecks.Run(Check);
Console.WriteLine(_failures == 0 ? "LIBRARY OK" : _failures + " check(s) failed");
return _failures == 0 ? 0 : 1;
@@ -895,7 +908,7 @@ internal static class Program
Check(p.Scene.DampingEdge == 64 && !p.Scene.ImageSources && p.Scene.ObjectSources && p.Scene.RefractiveIndex == 1.0 && p.Scene.ImageSourceScale == 1.0, "scene: damping 64, object sources on, image sources off");
Check(p.Simulation.Steps == 15000 && p.Simulation.VisualizeEvery == 2 && !p.Simulation.FourthOrderLaplacian && p.Simulation.WaveSpeed == 1.0 && p.Simulation.TimeDecay == 10.0 && p.Simulation.SourceFrequencyScale == 2.0 && p.Simulation.IntensityScale == 1.0, "simulation: 15000 steps every 2, 9-point stencil, c 1, decay 10");
Check(p.Display.Field.Brightness == 80 && p.Display.Intensity.Brightness == 30 && p.Display.Field.BlackLevel == -0.05 && p.Display.Intensity.BlackLevel == 0 && p.Display.Field.ColorScheme == "Default_Field" && p.Display.Intensity.ColorScheme == "Default_intensity", "display: brightness 80 / 30, black levels, schemes");
- Check(p.Display.Field.Preview && p.Display.Intensity.Preview && !p.Display.Field.Export && !p.Display.Intensity.Export && p.Display.Video.Fps == 60 && p.Display.Video.Quality == 70, "display: previews on, exports off, 60 fps at quality 70");
+ Check(p.Display.Field.Preview && p.Display.Intensity.Preview && p.Display.ProbeGraphsInExport && p.Display.Video.Fps == 60 && p.Display.Video.Quality == 70, "display: previews on, probe graphs in the export, 60 fps at the file's quality 70");
Check(p.Sources.Count == 4 && p.Sources.Select(s => s.Name).SequenceEqual(["Source 1", "Source 2", "Source 3", "Source 4"]) && p.Sources.Select(s => s.Frequency).SequenceEqual([40, 100, 150, 240]) && p.Sources.Select(s => s.Amplitude).SequenceEqual([70, 80, 90, 100]), "4 single sources with their names, levels and amplitudes");
Check(p.Sources.All(s => s.Enabled && s.Array == null && s.DetachAfter == Source.NeverDetach && s.Mode == SourceMode.Continuous && s.Elements.Count == 1) && p.Sources[0].X == 150 && p.Sources[0].Y == 140 && p.Sources[3].Y == 924, "sources enabled, single, never detaching, placed, with one emitter each");
Check(p.Probes.Count == 2 && p.Probes.All(pr => !pr.Active && pr.Layer == ProbeLayer.Field && pr.Measurement == ProbeMeasurement.Amplitude && pr.BoxSize == ProbeBoxSize.Medium && pr.Window == 500 && pr.StartAfter == 0), "2 inactive field probes, medium boxes, window 500, no start step");
diff --git a/_tools/ui_check/Common.ps1 b/_tools/ui_check/Common.ps1
index e420672..baeab16 100644
--- a/_tools/ui_check/Common.ps1
+++ b/_tools/ui_check/Common.ps1
@@ -204,6 +204,8 @@ function WaitFor([scriptblock]$condition, [int]$timeoutMs = 10000, [int]$pollMs
# is busy elsewhere this silently fails and the foreground stays theirs, which is just as good): every
# check must then leave the app inactive.
function Start-App([string]$Exe, [string]$ProjectFile = "") {
+ # an edited project asks "save?" on closing (2026-10-14); a harness cannot answer a message box by posted keys, so the app is told to discard
+ $env:WAVEDUDE_DISCARD_EDITS = "1"
if ($ProjectFile -ne "") { $script:p = Start-Process -FilePath $Exe -ArgumentList ('"' + $ProjectFile + '"') -PassThru }
else { $script:p = Start-Process -FilePath $Exe -PassThru }
$script:win = $null
diff --git a/_tools/ui_check/ExportCheck.ps1 b/_tools/ui_check/ExportCheck.ps1
new file mode 100644
index 0000000..a263aea
--- /dev/null
+++ b/_tools/ui_check/ExportCheck.ps1
@@ -0,0 +1,165 @@
+# Drives the export (2026-10-14) on tiny.wdproj (64 x 48, 200 steps, a frame every 2 = 100 frames): File > Export >
+# Export field... with no run yet (a run is started first, then 100 PNGs land in <temp>\wd_export\tiny_field), the
+# title's asterisk after an edit, and Export both... from the picture's context menu (the Apps key on a focused
+# handle) on the now stale run, which re-runs and writes both sequences; then tiny_probes.wdproj's field with the
+# probe graph boxes drawn in (a frame is kept as %TEMP%\export_probes.png). The Save dialog cannot be driven by
+# posted keys, so the app takes the path from WAVEDUDE_EXPORT_PATH ("{name}" = the name it would suggest).
+# See Common.ps1 for the rules (no mouse, no activation, no UIA patterns). Exits with the failure count.
+#
+# powershell -ExecutionPolicy Bypass -File _tools\ui_check\ExportCheck.ps1 [-Exe <path>] [-Trace]
+
+param(
+ [string]$Exe = (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows\WaveDude.WPF.exe"),
+ [switch]$Trace
+)
+
+. (Join-Path $PSScriptRoot "Common.ps1")
+
+$VK_APPS = 0x5D
+$out = Join-Path $env:TEMP "wd_export"
+if (Test-Path $out) { Remove-Item -Recurse -Force $out }
+New-Item -ItemType Directory -Force $out | Out-Null
+$env:WAVEDUDE_EXPORT_PATH = Join-Path $out "{name}.png"
+
+function MenuItemVisible([string]$name) {
+ $c = New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, $name)
+ return ($script:win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c) -ne $null)
+}
+# a context menu's popup is a top-level window of the process, not a descendant of the main window
+function PopupItemVisible([string]$name) {
+ $byProcess = New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $script:p.Id)
+ foreach ($top in $A::RootElement.FindAll([System.Windows.Automation.TreeScope]::Children, $byProcess)) {
+ $c = New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, $name)
+ if ($top.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c) -ne $null) { return $true }
+ }
+ return $false
+}
+# the automation id of the focused element in any of the process's top-level windows (a popup's entries included)
+function PopupFocusedId() {
+ $byProcess = New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $script:p.Id)
+ $focused = New-Object System.Windows.Automation.PropertyCondition($A::HasKeyboardFocusProperty, $true)
+ foreach ($top in $A::RootElement.FindAll([System.Windows.Automation.TreeScope]::Children, $byProcess)) {
+ $e = $top.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $focused)
+ if ($e -ne $null) { return $e.Current.AutomationId }
+ }
+ return "(none)"
+}
+function Step([string]$what, [int]$vk, [int]$settle) {
+ Key $vk $settle
+ if ($Trace) { " {0,-12} focus {1} foreground {2} export '{3}'" -f $what, (FocusedId), (Foreground), (ExportStatus) }
+}
+function ExportStatus() { return (Find "StatusExport").Current.Name }
+function Pngs([string]$folder) { if (Test-Path $folder) { return @(Get-ChildItem $folder -Filter *.png).Count } else { return 0 } }
+function IsPng([string]$path) { $b = [System.IO.File]::ReadAllBytes($path); return ($b.Length -gt 8 -and $b[1] -eq 0x50 -and $b[2] -eq 0x4E -and $b[3] -eq 0x47) }
+
+Start-App $Exe (Join-Path $PSScriptRoot "tiny.wdproj")
+try {
+ Check "the title names the file, no asterisk" ($win.Current.Name -like "*tiny.wdproj") $win.Current.Name
+
+ # File > Export > Export field...: F10 focuses the menu bar, Down opens File on New; New, Open, Recent, Save, Save As, Export
+ Step "F10" 0x79 150; Step "Down" $VK_DOWN 150
+ for ($i = 0; $i -lt 5; $i++) { Step "Down" $VK_DOWN 80 }
+ Step "Right" $VK_RIGHT 150
+ Check "File > Export opens on 'Export field...'" (MenuItemVisible "Export intensity...")
+ Step "Enter" $VK_RETURN 200
+ $field = Join-Path $out "tiny_field"
+ Check "with no run yet a run is made and 100 PNGs land in tiny_field" (WaitFor { (Pngs $field) -eq 100 } 60000) ("{0} files, status '{1}'" -f (Pngs $field), (ExportStatus))
+ Check "the export ends and its status item clears" (WaitFor { (ExportStatus) -eq "" } 10000) (ExportStatus)
+ $msg = (Find "StatusMessage").Current.Name
+ Check "the status bar reports it" ($msg -like "Exported 100 frames to *tiny_field*") $msg
+ Check "the files are tiny_field_0000.png to _0099.png and PNGs" ((Test-Path (Join-Path $field "tiny_field_0000.png")) -and (Test-Path (Join-Path $field "tiny_field_0099.png")) -and (IsPng (Join-Path $field "tiny_field_0050.png")))
+ Check "the run made for the export stays in the preview (100 frames)" ((Frame) -like "* / 99") (Frame)
+ Check "and is reported completed" ((RunStatus) -like "Completed*") (RunStatus)
+
+ # an edit: the title gets its asterisk and the run goes stale
+ FocusOn "Source:Source 1"
+ Step "Right" $VK_RIGHT 300
+ Check "an edit puts an asterisk after the file name" ($win.Current.Name -like "*tiny.wdproj*") $win.Current.Name
+ Check "and marks the run stale" ((RunStatus) -like "*edited since*") (RunStatus)
+
+ # Export both... from the picture's context menu, the Apps key on the focused handle: the stale run is redone first
+ Remove-Item -Recurse -Force $field
+ $null = WaitFor { (RunStatus) -notlike "Running*" } 10000 # the automatic re-run after the edit, if it started, must not be mid-way
+ FocusOn "Source:Source 1"
+ Step "Apps" $VK_APPS 300
+ Check "the Apps key opens the picture's context menu with the export entries" (WaitFor { PopupItemVisible "Export both..." } 3000)
+ # opened by keyboard, no entry is highlighted yet: Down walks Field, Intensity, Both
+ for ($i = 0; $i -lt 4 -and (PopupFocusedId) -ne "ContextExportBoth"; $i++) { Step "Down" $VK_DOWN 120 }
+ Check "Down reaches 'Export both...'" ((PopupFocusedId) -eq "ContextExportBoth") (PopupFocusedId)
+ Step "Enter" $VK_RETURN 200
+ $intensity = Join-Path $out "tiny_intensity"
+ Check "both sequences arrive, 100 files each" (WaitFor { (Pngs $field) -eq 100 -and (Pngs $intensity) -eq 100 } 60000) ("{0} + {1} files, status '{2}'" -f (Pngs $field), (Pngs $intensity), (ExportStatus))
+ Check "the export ends" (WaitFor { (ExportStatus) -eq "" } 10000) (ExportStatus)
+ Check "the run is fresh again" ((WaitFor { (RunStatus) -like "Completed*" -and (RunStatus) -notlike "*edited since*" } 10000)) (RunStatus)
+ Check "the intensity files are PNGs" (IsPng (Join-Path $intensity "tiny_intensity_0099.png"))
+
+ # the still: the context menu's first entry writes the shown frame (frame 0, step 0) as one file, from the run
+ FocusOn "Source:Source 1"
+ Step "Apps" $VK_APPS 300
+ for ($i = 0; $i -lt 2 -and (PopupFocusedId) -ne "ContextExportFrame"; $i++) { Step "Down" $VK_DOWN 120 }
+ Check "'Export this frame...' is the context menu's first entry" ((PopupFocusedId) -eq "ContextExportFrame") (PopupFocusedId)
+ Step "Enter" $VK_RETURN 200
+ $still = Join-Path $out "tiny_field_0.png"
+ Check "the shown frame lands as tiny_field_0.png" (WaitFor { Test-Path $still } 20000) ((Find "StatusMessage").Current.Name)
+ Check "and is a PNG, with the status bar reporting one frame" ((IsPng $still) -and (WaitFor { (Find "StatusMessage").Current.Name -like "Exported 1 frames to *tiny_field_0.png*" } 5000)) ((Find "StatusMessage").Current.Name)
+ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+}
+
+# tiny_probes.wdproj: the probe graph boxes are drawn into the frames (the painter renders on the export thread),
+# first as PNGs (one frame is kept as %TEMP%\export_probes.png for a look), then the same as an MP4 through
+# Media Foundation, whose writer must live on the export thread (it refused the UI thread's, 2026-10-14)
+Start-App $Exe (Join-Path $PSScriptRoot "tiny_probes.wdproj")
+try {
+ Step "F10" 0x79 150; Step "Down" $VK_DOWN 150
+ for ($i = 0; $i -lt 5; $i++) { Step "Down" $VK_DOWN 80 }
+ Step "Right" $VK_RIGHT 150; Step "Enter" $VK_RETURN 200
+ $probes = Join-Path $out "tiny_probes_field"
+ Check "the probes project exports its field with the graph boxes drawn" (WaitFor { (Find "StatusMessage").Current.Name -like "Exported * frames to *tiny_probes_field*" } 60000) ((Find "StatusMessage").Current.Name)
+ $last = Get-ChildItem $probes -Filter *.png | Sort-Object Name | Select-Object -Last 1
+ Check "the last frame is a PNG" ($last -ne $null -and (IsPng $last.FullName)) $last.Name
+ if ($last -ne $null) { Copy-Item $last.FullName (Join-Path $env:TEMP "export_probes.png") -Force }
+ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+}
+$env:WAVEDUDE_EXPORT_PATH = Join-Path $out "{name}.mp4"
+Start-App $Exe (Join-Path $PSScriptRoot "tiny_probes.wdproj")
+try {
+ Step "F10" 0x79 150; Step "Down" $VK_DOWN 150
+ for ($i = 0; $i -lt 5; $i++) { Step "Down" $VK_DOWN 80 }
+ Step "Right" $VK_RIGHT 150; Step "Enter" $VK_RETURN 200
+ $mp4 = Join-Path $out "tiny_probes_field.mp4"
+ Check "the same export as an MP4 completes" (WaitFor { (Find "StatusMessage").Current.Name -like "Exported 50 frames to *tiny_probes_field.mp4*" } 60000) ((Find "StatusMessage").Current.Name)
+ Check "the MP4 file is there and not empty" ((Test-Path $mp4) -and (Get-Item $mp4).Length -gt 1000) (if (Test-Path $mp4) { (Get-Item $mp4).Length } else { "missing" })
+ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+}
+# a JPEG sequence through the app: the WIC codec with workers in parallel (2026-10-15). The PNG section filled the
+# same sequence folder, and a folder with files in it makes the app ask "replace?" (a message box the harness cannot
+# answer; it stalled there once), so it goes first
+Remove-Item -Recurse -Force (Join-Path $out "tiny_probes_field") -ErrorAction SilentlyContinue
+$env:WAVEDUDE_EXPORT_PATH = Join-Path $out "{name}.jpg"
+Start-App $Exe (Join-Path $PSScriptRoot "tiny_probes.wdproj")
+try {
+ Step "F10" 0x79 150; Step "Down" $VK_DOWN 150
+ for ($i = 0; $i -lt 5; $i++) { Step "Down" $VK_DOWN 80 }
+ Step "Right" $VK_RIGHT 150; Step "Enter" $VK_RETURN 200
+ $jpgs = Join-Path $out "tiny_probes_field"
+ Check "the same export as a JPEG sequence completes" (WaitFor { (Find "StatusMessage").Current.Name -like "Exported 50 frames to *tiny_probes_field*" } 60000) ((Find "StatusMessage").Current.Name)
+ $files = @(Get-ChildItem $jpgs -Filter *.jpg)
+ $b = if ($files.Count -gt 0) { [System.IO.File]::ReadAllBytes((Join-Path $jpgs "tiny_probes_field_0049.jpg")) } else { @() }
+ Check "50 JPEG files, the last one starting with the JPEG marker" ($files.Count -eq 50 -and $b.Length -gt 4 -and $b[0] -eq 0xFF -and $b[1] -eq 0xD8) ("{0} files" -f $files.Count)
+ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+ Remove-Item Env:\WAVEDUDE_EXPORT_PATH -ErrorAction SilentlyContinue
+}
+Write-Output ("{0} failure(s)" -f $script:failures)
+exit $script:failures