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: QuickTime movie with the Animation codec, lossless RGB, the moov in front

Alexander Graef09f845a4e4bc
diff --git a/.gitignore b/.gitignore
index c433975..fdf2edd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,7 @@ Wave_Dude_Examples/**/*.wdproj
Wave_Dude_Examples/**/*.avi
Wave_Dude_Examples/**/*.mp4
Wave_Dude_Examples/**/*.mpg
+Wave_Dude_Examples/**/*.mov
Wave_Dude_Examples/**/*_field/
Wave_Dude_Examples/**/*_intensity/
Wave_Dude_Examples/**/*_field_*.png
diff --git a/CLAUDE.md b/CLAUDE.md
index cabd53a..73b3edd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -294,7 +294,15 @@ WPF shell as it stands:
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
+ Media Feature Pack, the command then says so), and a QuickTime movie with the Animation codec
+ (`MovAnimationWriter`, 2026-10-15, the user's choice of the one lossless single-file format for the editing
+ suites, Final Cut above all since it opens no AVI: 24-bit RGB run-length coded, every frame a key frame,
+ `ftyp qt `, the `moov` first in a reservation sized from the planned frame count (1024 fixed + 12 a frame,
+ overwritten at close, a `free` atom over the rest; a writer without a plan puts it at the end), one 64-bit
+ `mdat`, `rle ` sample description and `co64`; ffmpeg's `qtrle` gives
+ the frames back pixel for pixel; a real-world ratio of only 1.3 : 1 on a 1080p canvas full of waves, 54 : 1
+ while most of it is black, since runs of identical pixels are all the codec compresses; 10 ms a frame in
+ the job). `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
diff --git a/WaveDude.WPF/Strings/Strings.DE.xaml b/WaveDude.WPF/Strings/Strings.DE.xaml
index 8fe8097..c294875 100644
--- a/WaveDude.WPF/Strings/Strings.DE.xaml
+++ b/WaveDude.WPF/Strings/Strings.DE.xaml
@@ -120,7 +120,7 @@
<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="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|QuickTime-Film, Animation-Codec, verlustfrei (*.mov)|*.mov</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>
diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xaml
index f250cc4..90738ea 100644
--- a/WaveDude.WPF/Strings/Strings.EN.xaml
+++ b/WaveDude.WPF/Strings/Strings.EN.xaml
@@ -120,7 +120,7 @@
<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="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|QuickTime movie, Animation codec, lossless (*.mov)|*.mov</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>
diff --git a/WaveDude.WPF/Strings/Strings.FR.xaml b/WaveDude.WPF/Strings/Strings.FR.xaml
index 06e926a..1b719c5 100644
--- a/WaveDude.WPF/Strings/Strings.FR.xaml
+++ b/WaveDude.WPF/Strings/Strings.FR.xaml
@@ -120,7 +120,7 @@
<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="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|Film QuickTime, codec Animation, sans perte (*.mov)|*.mov</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>
diff --git a/WaveDude.WPF/Strings/Strings.NL.xaml b/WaveDude.WPF/Strings/Strings.NL.xaml
index 9b1e999..22bcec3 100644
--- a/WaveDude.WPF/Strings/Strings.NL.xaml
+++ b/WaveDude.WPF/Strings/Strings.NL.xaml
@@ -120,7 +120,7 @@
<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="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|QuickTime-film, Animation-codec, verliesvrij (*.mov)|*.mov</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>
diff --git a/WaveDude/Export/ExportFormat.cs b/WaveDude/Export/ExportFormat.cs
index 9465da8..da5b3e5 100644
--- a/WaveDude/Export/ExportFormat.cs
+++ b/WaveDude/Export/ExportFormat.cs
@@ -13,6 +13,8 @@ public enum ExportFormat
Avi,
/// <summary>An H.264 MP4 through the Media Foundation of Windows; the quality setting applies.</summary>
Mp4,
+ /// <summary>A QuickTime movie with the Animation codec: lossless RGB, run-length coded, what the editing suites open natively.</summary>
+ Mov,
}
/// <summary>What is known about each <see cref="ExportFormat"/>: extensions, whether it is a sequence, how to open its sink.</summary>
@@ -83,7 +85,7 @@ public static class ExportFormats
}
/// <summary>The formats in filter order.</summary>
- public static readonly ExportFormat[] All = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mp4];
+ public static readonly ExportFormat[] All = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mp4, ExportFormat.Mov];
/// <summary>The file extension with its dot.</summary>
public static string Extension(ExportFormat format) => format switch
@@ -93,6 +95,7 @@ public static class ExportFormats
ExportFormat.Mpeg1 => ".mpg",
ExportFormat.Avi => ".avi",
ExportFormat.Mp4 => ".mp4",
+ ExportFormat.Mov => ".mov",
_ => throw new ArgumentOutOfRangeException(nameof(format)),
};
@@ -104,6 +107,7 @@ public static class ExportFormats
".mpg" or ".mpeg" or ".m1v" => ExportFormat.Mpeg1,
".avi" => ExportFormat.Avi,
".mp4" or ".m4v" => ExportFormat.Mp4,
+ ".mov" or ".qt" => ExportFormat.Mov,
_ => null,
};
@@ -168,6 +172,8 @@ public static class ExportFormats
throw new NotSupportedException("MP4 export needs the Media Foundation of Windows.");
}
return new Mp4Writer(path, width, height, fps, quality);
+ case ExportFormat.Mov:
+ return new MovAnimationWriter(path, width, height, fps, plannedFrames);
default:
throw new ArgumentOutOfRangeException(nameof(format));
}
diff --git a/WaveDude/Export/MovAnimationWriter.cs b/WaveDude/Export/MovAnimationWriter.cs
new file mode 100644
index 0000000..2f7c09b
--- /dev/null
+++ b/WaveDude/Export/MovAnimationWriter.cs
@@ -0,0 +1,348 @@
+using System.Buffers.Binary;
+using System.Text;
+
+namespace WaveDude.Export;
+
+/// <summary>
+/// Writes a QuickTime movie (<c>.mov</c>) with the Animation codec (<c>rle </c>, 24-bit RGB, run-length
+/// coded, mathematically lossless, every frame a key frame), the lossless RGB format Final Cut, Premiere,
+/// After Effects and Resolve all decode without anything installed (2026-10-15, the user's choice: one
+/// lossless single-file format per container, this one for the editors, the uncompressed AVI for the
+/// Windows tools). In-house, no dependencies. The <c>moov</c> with the sample tables comes first: its size
+/// follows from the planned frame count (a fixed part plus 12 bytes a frame), so that much is reserved
+/// after <c>ftyp</c> as a <c>free</c> atom, the samples go into one <c>mdat</c> behind it as they come, and at
+/// close the reservation is overwritten with the real <c>moov</c> and a <c>free</c> atom for the rest (the
+/// user's rule, 2026-10-15: a player streaming the file should not read it all before the first frame). More
+/// frames than planned, or none planned, put the <c>moov</c> at the end. The <c>mdat</c> size and the chunk
+/// offsets are 64-bit from the start (<c>co64</c>), so the file may grow past 4 GB. One thread at a time.
+/// </summary>
+/// <remarks>
+/// A frame: a 4-byte big-endian length of the whole frame data, a 2-byte header of 0 (a full frame), then
+/// per row a skip code (1 = no skip), run codes (a positive count n: n literal RGB pixels follow; a negative
+/// count −n: one RGB pixel follows, repeated n times; 0: another skip code follows) and −1 at the row's end.
+/// That is what every <c>rle </c> decoder expects (ffmpeg's <c>qtrle</c>, QuickTime's own).
+/// </remarks>
+public sealed class MovAnimationWriter : IFrameSink
+{
+ /// <summary>The moov's bytes besides the two per-frame tables (measured on the atoms as written, with slack).</summary>
+ private const int MoovFixedBytes = 1024;
+
+ private readonly FileStream _stream;
+ private readonly long _reservedStart;
+ private readonly long _reservedBytes;
+ private readonly long _mdatStart;
+ private readonly List<long> _offsets = [];
+ private readonly List<int> _sizes = [];
+ private readonly byte[] _row;
+ private byte[] _frame;
+ private bool _closed;
+
+ /// <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; the movie's time scale.</param>
+ /// <param name="plannedFrames">How many frames will come at most, which sizes the reservation for the leading <c>moov</c>; 0 puts it at the end.</param>
+ public MovAnimationWriter(string path, int width, int height, int framesPerSecond, int plannedFrames = 0)
+ {
+ Width = width;
+ Height = height;
+ FramesPerSecond = Math.Max(1, framesPerSecond);
+ Output = path;
+ PlannedFrames = Math.Max(0, plannedFrames);
+ _row = new byte[width * 3];
+ // the worst case of a row: every pixel a literal in runs of 127, plus the codes, plus the skip and the end
+ _frame = new byte[6 + height * (width * 3 + width / 127 + 4)];
+ _stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 16);
+ // ftyp, then the mdat with a 64-bit size patched at Close
+ _stream.Write(Atom("ftyp", [.. "qt "u8, 0, 0, 2, 0, .. "qt "u8]));
+ _reservedStart = _stream.Position;
+ if (PlannedFrames > 0)
+ {
+ // room for the moov of the planned frames, plus a free atom's head behind it, as one free atom for now
+ _reservedBytes = MoovFixedBytes + 12L * PlannedFrames + 8;
+ _stream.Write(FreeAtomHead(_reservedBytes));
+ _stream.Position = _reservedStart + _reservedBytes;
+ }
+ _mdatStart = _stream.Position;
+ Span<byte> mdat = stackalloc byte[16];
+ BinaryPrimitives.WriteUInt32BigEndian(mdat, 1); // size 1: a 64-bit size follows the type
+ "mdat"u8.CopyTo(mdat[4..]);
+ BinaryPrimitives.WriteUInt64BigEndian(mdat[8..], 0);
+ _stream.Write(mdat);
+ }
+
+ /// <inheritdoc/>
+ public int Width { get; }
+
+ /// <inheritdoc/>
+ public int Height { get; }
+
+ /// <inheritdoc/>
+ public int FrameCount => _sizes.Count;
+
+ /// <inheritdoc/>
+ public string Output { get; }
+
+ /// <summary>Frames per second, the movie's time scale.</summary>
+ public int FramesPerSecond { get; }
+
+ /// <summary>The frame count the leading moov was reserved for; 0 for a trailing moov.</summary>
+ public int PlannedFrames { get; }
+
+ /// <summary>Whether the moov was written at the front (the reservation held it).</summary>
+ public bool MoovFirst { get; private set; }
+
+ /// <summary>Bytes of frame data written so far (for the bench's ratio against width × height × 3 per frame).</summary>
+ public long FrameBytes { get; private set; }
+
+ /// <inheritdoc/>
+ public void Add(ReadOnlySpan<int> pixels)
+ {
+ if (_closed)
+ {
+ throw new InvalidOperationException("The movie file is already closed.");
+ }
+ if (pixels.Length < Width * Height)
+ {
+ throw new ArgumentException("The frame is smaller than the movie.", nameof(pixels));
+ }
+ int length = Encode(pixels, _frame);
+ _offsets.Add(_stream.Position);
+ _sizes.Add(length);
+ _stream.Write(_frame, 0, length);
+ FrameBytes += length;
+ }
+
+ /// <summary>Run-length codes one frame into <paramref name="target"/>; returns the byte count.</summary>
+ public int Encode(ReadOnlySpan<int> pixels, byte[] target)
+ {
+ int p = 6; // the length and the header are filled in at the end
+ int width = Width;
+ for (int y = 0; y < Height; y++)
+ {
+ ReadOnlySpan<int> row = pixels.Slice(y * width, width);
+ target[p++] = 1; // skip nothing
+ int x = 0;
+ while (x < width)
+ {
+ int pixel = row[x];
+ // a run of identical pixels: a repeat code, up to 128
+ int run = 1;
+ while (x + run < width && run < 128 && row[x + run] == pixel)
+ {
+ run++;
+ }
+ if (run >= 2)
+ {
+ target[p++] = (byte)(-run);
+ target[p++] = (byte)(pixel >> 16);
+ target[p++] = (byte)(pixel >> 8);
+ target[p++] = (byte)pixel;
+ x += run;
+ continue;
+ }
+ // literals until the next run of at least two, up to 127
+ int start = x;
+ int count = 0;
+ while (x < width && count < 127)
+ {
+ if (x + 1 < width && row[x + 1] == row[x])
+ {
+ break;
+ }
+ x++;
+ count++;
+ }
+ if (count == 0)
+ {
+ // x stands on the first of a run; taken by the next round
+ continue;
+ }
+ target[p++] = (byte)count;
+ for (int i = 0; i < count; i++)
+ {
+ int v = row[start + i];
+ target[p++] = (byte)(v >> 16);
+ target[p++] = (byte)(v >> 8);
+ target[p++] = (byte)v;
+ }
+ }
+ target[p++] = 0xFF; // −1: the row's end
+ }
+ BinaryPrimitives.WriteInt32BigEndian(target, p);
+ BinaryPrimitives.WriteUInt16BigEndian(target.AsSpan(4), 0); // a full frame
+ return p;
+ }
+
+ /// <inheritdoc/>
+ public void Close()
+ {
+ if (_closed)
+ {
+ return;
+ }
+ _closed = true;
+ try
+ {
+ long mdatEnd = _stream.Position;
+ byte[] moov = BuildMoov();
+ if (_reservedBytes > 0 && moov.Length + 8 <= _reservedBytes)
+ {
+ // the real moov over the reservation, a free atom over what is left of it
+ _stream.Position = _reservedStart;
+ _stream.Write(moov);
+ _stream.Write(FreeAtomHead(_reservedBytes - moov.Length));
+ MoovFirst = true;
+ }
+ else
+ {
+ _stream.Position = mdatEnd;
+ _stream.Write(moov);
+ }
+ _stream.Position = _mdatStart + 8;
+ Span<byte> size = stackalloc byte[8];
+ BinaryPrimitives.WriteUInt64BigEndian(size, (ulong)(mdatEnd - _mdatStart));
+ _stream.Write(size);
+ _stream.Flush();
+ }
+ finally
+ {
+ _stream.Dispose();
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Dispose() => Close();
+
+ // ---------------------------------------------------------------- the movie atoms
+
+ private byte[] BuildMoov()
+ {
+ int frames = _sizes.Count;
+ uint timescale = (uint)FramesPerSecond;
+ uint duration = (uint)frames;
+ return Atom("moov", [.. Mvhd(timescale, duration), .. Atom("trak", [.. Tkhd(duration), .. Atom("mdia", [.. Mdhd(timescale, duration), .. Hdlr("mhlr", "vide", "VideoHandler"), .. Atom("minf",
+ [.. Atom("vmhd", [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]), .. Hdlr("dhlr", "alis", "DataHandler"), .. Atom("dinf", Atom("dref", [0, 0, 0, 0, 0, 0, 0, 1, .. Atom("alis", [0, 0, 0, 1])])),
+ .. Atom("stbl", [.. Stsd(), .. Stts(frames), .. Atom("stsc", [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]), .. Stsz(), .. Co64()])])])])]);
+ }
+
+ private static byte[] Mvhd(uint timescale, uint duration)
+ {
+ var b = new byte[100];
+ // version 0, flags 0, creation and modification time 0 (Mac epoch), timescale, duration
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(12), timescale);
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(16), duration);
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(20), 0x00010000); // preferred rate 1.0
+ BinaryPrimitives.WriteUInt16BigEndian(b.AsSpan(24), 0x0100); // preferred volume 1.0
+ Matrix(b.AsSpan(36));
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(96), 2); // next track id
+ return Atom("mvhd", b);
+ }
+
+ private byte[] Tkhd(uint duration)
+ {
+ var b = new byte[84];
+ b[3] = 0x0F; // enabled, in movie, in preview, in poster
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(12), 1); // track id
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(20), duration);
+ Matrix(b.AsSpan(40));
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(76), (uint)Width << 16);
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(80), (uint)Height << 16);
+ return Atom("tkhd", b);
+ }
+
+ private static byte[] Mdhd(uint timescale, uint duration)
+ {
+ var b = new byte[24];
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(12), timescale);
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(16), duration);
+ BinaryPrimitives.WriteUInt16BigEndian(b.AsSpan(20), 0x55C4); // language: undetermined
+ return Atom("mdhd", b);
+ }
+
+ /// <summary>A handler reference the QuickTime way: component type and subtype, manufacturer 'appl', the name as a counted string.</summary>
+ private static byte[] Hdlr(string type, string subtype, string name)
+ {
+ byte[] nameBytes = Encoding.ASCII.GetBytes(name);
+ return Atom("hdlr", [0, 0, 0, 0, .. Encoding.ASCII.GetBytes(type), .. Encoding.ASCII.GetBytes(subtype), .. "appl"u8, 0, 0, 0, 0, 0, 0, 0, 0, (byte)nameBytes.Length, .. nameBytes]);
+ }
+
+ /// <summary>The sample description: one 'rle ' entry, 24-bit, spatial quality lossless, named "Animation".</summary>
+ private byte[] Stsd()
+ {
+ var e = new byte[86];
+ BinaryPrimitives.WriteUInt32BigEndian(e, 86);
+ "rle "u8.CopyTo(e.AsSpan(4));
+ BinaryPrimitives.WriteUInt16BigEndian(e.AsSpan(14), 1); // data reference index
+ "appl"u8.CopyTo(e.AsSpan(20)); // vendor
+ BinaryPrimitives.WriteUInt32BigEndian(e.AsSpan(28), 0x3FF); // spatial quality: lossless
+ BinaryPrimitives.WriteUInt16BigEndian(e.AsSpan(32), (ushort)Width);
+ BinaryPrimitives.WriteUInt16BigEndian(e.AsSpan(34), (ushort)Height);
+ BinaryPrimitives.WriteUInt32BigEndian(e.AsSpan(36), 0x00480000); // 72 dpi
+ BinaryPrimitives.WriteUInt32BigEndian(e.AsSpan(40), 0x00480000);
+ BinaryPrimitives.WriteUInt16BigEndian(e.AsSpan(48), 1); // frames per sample
+ byte[] name = Encoding.ASCII.GetBytes("Animation");
+ e[50] = (byte)name.Length;
+ name.CopyTo(e, 51);
+ BinaryPrimitives.WriteUInt16BigEndian(e.AsSpan(82), 24); // depth
+ BinaryPrimitives.WriteUInt16BigEndian(e.AsSpan(84), 0xFFFF); // no colour table
+ return Atom("stsd", [0, 0, 0, 0, 0, 0, 0, 1, .. e]);
+ }
+
+ private static byte[] Stts(int frames)
+ {
+ var b = new byte[16];
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(4), 1);
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(8), (uint)frames);
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(12), 1); // every sample lasts one tick
+ return Atom("stts", b);
+ }
+
+ private byte[] Stsz()
+ {
+ var b = new byte[12 + 4 * _sizes.Count];
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(8), (uint)_sizes.Count);
+ for (int i = 0; i < _sizes.Count; i++)
+ {
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(12 + 4 * i), (uint)_sizes[i]);
+ }
+ return Atom("stsz", b);
+ }
+
+ private byte[] Co64()
+ {
+ var b = new byte[8 + 8 * _offsets.Count];
+ BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(4), (uint)_offsets.Count);
+ for (int i = 0; i < _offsets.Count; i++)
+ {
+ BinaryPrimitives.WriteUInt64BigEndian(b.AsSpan(8 + 8 * i), (ulong)_offsets[i]);
+ }
+ return Atom("co64", b);
+ }
+
+ /// <summary>The head of a <c>free</c> atom of <paramref name="bytes"/> bytes in all (the body is whatever lies there).</summary>
+ private static byte[] FreeAtomHead(long bytes)
+ {
+ var head = new byte[8];
+ BinaryPrimitives.WriteUInt32BigEndian(head, (uint)bytes);
+ "free"u8.CopyTo(head.AsSpan(4));
+ return head;
+ }
+
+ /// <summary>The identity transformation matrix (16.16 and 2.30 fixed point).</summary>
+ private static void Matrix(Span<byte> b)
+ {
+ BinaryPrimitives.WriteUInt32BigEndian(b, 0x00010000);
+ BinaryPrimitives.WriteUInt32BigEndian(b[16..], 0x00010000);
+ BinaryPrimitives.WriteUInt32BigEndian(b[32..], 0x40000000);
+ }
+
+ private static byte[] Atom(string type, ReadOnlySpan<byte> payload)
+ {
+ var atom = new byte[8 + payload.Length];
+ BinaryPrimitives.WriteUInt32BigEndian(atom, (uint)atom.Length);
+ Encoding.ASCII.GetBytes(type).CopyTo(atom, 4);
+ payload.CopyTo(atom.AsSpan(8));
+ return atom;
+ }
+}
diff --git a/_tools/library_check/ExportChecks.cs b/_tools/library_check/ExportChecks.cs
index 79b6868..1e67c5d 100644
--- a/_tools/library_check/ExportChecks.cs
+++ b/_tools/library_check/ExportChecks.cs
@@ -126,6 +126,54 @@ internal static class ExportChecks
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");
+ // MOV with the Animation codec: the atoms, ffmpeg's qtrle decoder giving the frames back exactly, a run of one colour compressing
+ string movPath = Path.Combine(folder, "seven.mov");
+ bool moovFirst;
+ using (var mov = new MovAnimationWriter(movPath, w, h, 25, 7))
+ {
+ foreach (int[] frame in frames)
+ {
+ mov.Add(frame);
+ }
+ check(mov.FrameCount == 7 && mov.FrameBytes < 7L * w * h * 3, "mov: 7 frames taken, smaller than raw (" + mov.FrameBytes + " of " + 7L * w * h * 3 + " bytes)");
+ mov.Close();
+ moovFirst = mov.MoovFirst;
+ }
+ byte[] movBytes = File.ReadAllBytes(movPath);
+ int moovAt = IndexOf(movBytes, "moov"u8, 0, movBytes.Length);
+ int mdatAt = IndexOf(movBytes, "mdat"u8, 0, movBytes.Length);
+ check(Encoding.ASCII.GetString(movBytes, 4, 4) == "ftyp" && Encoding.ASCII.GetString(movBytes, 8, 4) == "qt " && moovFirst && moovAt > 0 && moovAt < mdatAt
+ && IndexOf(movBytes, "free"u8, moovAt, mdatAt) > moovAt && IndexOf(movBytes, "rle "u8, 0, movBytes.Length) > 0 && IndexOf(movBytes, "co64"u8, 0, movBytes.Length) > 0,
+ "mov: ftyp qt, the moov before the mdat with a free atom filling the reservation, an rle sample description, 64-bit offsets");
+ // a writer told nothing about the count has no reservation and puts the moov at the end, still a valid file
+ using (var trailing = new MovAnimationWriter(Path.Combine(folder, "trailing.mov"), w, h, 25))
+ {
+ foreach (int[] frame in frames)
+ {
+ trailing.Add(frame);
+ }
+ trailing.Close();
+ byte[] t = File.ReadAllBytes(Path.Combine(folder, "trailing.mov"));
+ check(!trailing.MoovFirst && IndexOf(t, "moov"u8, 0, t.Length) > IndexOf(t, "mdat"u8, 0, t.Length), "mov: with no planned count the moov goes at the end");
+ }
+ if (Ffmpeg != null)
+ {
+ byte[]? rgb = Decode(movPath, 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, "mov: ffmpeg decodes 7 frames, identical" + (rgb == null ? "" : ", got " + count));
+ }
+ var flat = new int[w * h];
+ Array.Fill(flat, unchecked((int)0xFF123456));
+ var scratch = new byte[6 + h * (w * 3 + w / 127 + 4)];
+ using (var mov = new MovAnimationWriter(Path.Combine(folder, "flat.mov"), w, h, 25))
+ {
+ int flatBytes = mov.Encode(flat, scratch);
+ check(flatBytes < h * 8 + 6, "mov: a flat frame codes to " + flatBytes + " bytes (under " + (h * 8 + 6) + ")");
+ }
// MP4: Media Foundation, when it is there
if (OperatingSystem.IsWindows() && ExportFormats.IsAvailable(ExportFormat.Mp4))
{
@@ -447,8 +495,9 @@ internal static class ExportChecks
var project = new Project();
project.Scene.Width = w;
project.Scene.Height = h;
- project.Simulation.Steps = 120;
- project.Simulation.VisualizeEvery = 2;
+ // a long enough run for the waves to fill the canvas (the frames' content decides every lossless ratio), 60 frames spread over it
+ project.Simulation.Steps = 3000;
+ project.Simulation.VisualizeEvery = 50;
Source source = project.AddSource();
source.X = w / 2;
source.Y = h / 2;
@@ -543,6 +592,7 @@ internal static class ExportChecks
("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)),
+ ("mov (Animation)", () => ExportFormats.Open(ExportFormat.Mov, Path.Combine(folder, "j.mov"), 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); }),
})
@@ -556,7 +606,8 @@ internal static class ExportChecks
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})");
+ string ratio = job.Targets[0].Sink is MovAnimationWriter movSink ? $", {(double)store.Count * w * h * 3 / Math.Max(1, movSink.FrameBytes):0.00} : 1 on the run's frames" : "";
+ Console.WriteLine($" job to {name}: {clock.Elapsed.TotalMilliseconds / store.Count:0.0} ms per frame ({job.State}){ratio}");
ExportFormats.AlternativeJpeg = null;
Mp4Writer.Throttle = true;
}