Plan: camera raw #
A roadmap for reading camera raw files — Canon CR2 and CR3, Nikon NEF, and Adobe's DNG — and possibly writing DNG. None of it is implemented. It is written down so that the work can be picked up a phase at a time, and so that the question "does z2d need deeper pixels first?" has an answer on file.
The file and line references below were true at commit 0e5aa9e of this
repository and at c016785 of the z2d fork. They will drift; the function
names will not, so search for those.
The formats #
- CR2 — Canon, 2004–2018. TIFF-based. The raw data is lossless JPEG
(SOF3) cut into vertical slices, which the
cr2_slicetag describes. - CR3 — Canon, 2018 onward. ISO base media file format (the MP4 container), with raw data in Canon's CRX codec, which is wavelet-based and has no public specification.
- NEF — Nikon. TIFF-based, close to CR2 in shape, with Nikon's own lossless or lossy Huffman compression and a tone curve in the maker notes. Nikon cameras do not write DNG.
- DNG — Adobe's published raw format, TIFF/EP-based. Written natively by Leica, Pentax, Ricoh and many phones, and by converters from everything else. The only one of the four with a full specification, which is why it comes first.
Where things stand #
In z2dimg #
-
TIFF. There is no general IFD walker.
src/exif.zig(scan, around lines 180–233) reads the orientation tag and nothing else: forward offsets only, no next-IFD chain, no SubIFDs, no strip or tile offsets. Itstake/skip/readInthelpers are small enough to be reused or replaced. -
JPEG. 8-bit baseline and progressive only. SOF3 (lossless) and 12-bit samples are refused (
src/jpeg.zignear lines 30–38, 146 and 401).src/jpeg/huffman.zig—Table.initandBitReaderwith its unstuffing, marker detection andreceiveExtend— is reusable for lossless JPEG. The catch is thatreceiveExtendtakes au6, and CR2 and DNG both need the SSSS=16 case. The marker, DHT and restart handling injpeg.zigcarry over too; the DCT-shapedState/Framedo not. -
Bit depth. Every codec scales 16-bit samples down to 8 bits itself (
scaleinsrc/png.zigandsrc/netpbm.zig). The only type between the codecs and z2d is straight-alphaRgba8insrc/pixels.zig. -
Color. ICC profiles are carried through, never applied (
src/icc.zig). The only color math in the library is JPEG's YCbCr to RGB. -
Containers. There is no ISO-BMFF box parser. WebP's RIFF chunk walking is the nearest thing, and its layout differs.
-
Adding a format follows a well-worn path, with WebP as the most recent example:
- the
Formatenum, name, MIME type and magic detection insrc/format.zig; - decode and probe dispatch in
src/codecs.zig; src/sandbox.zig, which is almost entirely driven by the enum;tests/<format>.zigand fixtures, a test module inbuild.zig, a fuzz corpus intests/fuzz.zig, a row in the README's format table, and a page indoc/.
A format that is recognized but has no codec fails with
error.Unsupported, so detection can land before decoding does. - the
In z2d #
- Pixel formats are 8 bits per channel or fewer:
argb,xrgb,rgba,rgbandalpha8down toalpha1(pixel.zignear lines 47–56). Pixels are premultiplied, and the painter enforces it. - Color. Surfaces are documented as holding linear RGB (
color.zignear lines 14–16). sRGB is a plain 2.2 power, not the piecewise curve (color.zignear lines 201–209). There is no ICC and no notion of primaries or gamut. Gradients interpolate in linear RGB by default. - Precision. Compositing happens in linear light but is stored in 8
bits, which bands in the shadows. z2d ships a ditherer to hide this. The
compositor already has an f32 path (
Precision.float), used for blend modes, but it loads and stores through u8 at both ends. - Export. The PNG exporter writes 8 bits per channel at most, and marks
sRGB with a
gAMAchunk only. - Extensibility.
ImageSurface(T)is generic over the pixel type, and mostSurfacemethods dispatch withinline else. What is fixed:- three parallel unions in
pixel.zig(Format,Stride,Pixel); - the
Surfaceunion; - the compositor's u8 transposes (
transposeToVecandtransposeFromVec) and its 255 constants; - the PNG exporter's depth and stride switches.
- three parallel unions in
Does z2d need deeper pixels first? #
No, not to start. A raw decoder can develop the image in its own f32 buffers and hand z2d 8-bit sRGB. That is what every codec here already does with 16-bit PNG. Deeper surfaces matter only when the precision has to survive the decode: editing, writing 16-bit PNG or DNG, HDR. That is Phase 3.
When it comes to that, a float surface (rgbaf32, or f16) is moderate
work, and the float compositor is its natural home:
- give it a direct float load and store;
- force float precision whenever the destination is float;
- add a 16-bit PNG path.
An rgba16 integer surface is harder than it looks. The compositor's u16
working vectors have no headroom for 16-bit multiplies, and the u8 shuffles
and 255 constants are spread throughout.
What's missing isn't a nonlinear curve; it's color management. z2d already stores linear light. What raw needs, and what lives in z2dimg rather than z2d:
- black and white levels;
- white balance;
- demosaicing;
- a camera → XYZ → sRGB matrix, from DNG's
ColorMatrixtags or a per-model table for the others; - the correct piecewise sRGB curve.
The z2d changes worth making are small and optional: the piecewise curve, and
sRGB/iCCP chunks on export.
Phases #
Each phase is worth shipping on its own.
Phase 0: recognize the formats, and decode the embedded preview #
Every one of these formats embeds a full-size or near-full-size JPEG preview. Decoding it covers most of what a viewer wants, at a fraction of the cost.
-
Detection:
- CR2 is
II*\0followed byCR; - CR3 is an ISO-BMFF
ftypbox with thecrxbrand; - DNG is TIFF carrying the
DNGVersiontag; - NEF is plain TIFF, so it needs the
Maketag.
- CR2 is
-
src/tiff.zig, a general IFD walker:- both byte orders and every tag type;
- IFD chains, SubIFDs and the EXIF IFD;
- random access over a bounded in-memory buffer, which is what the sandbox already reads its input into.
EXIF orientation can move onto it later.
-
src/bmff.zig, a minimal ISO-BMFF box walker:moov,trak, and Canon'suuidboxes, enough to find CR3's preview (PRVW, or the full-size JPEG track). -
Decoding the preview: its bytes go to the existing
jpeg.decode, and the raw file's orientation is applied. -
API: opt-in, not implicit. Something like
DecodeOptions.raw = .preview, so that a caller never mistakes the camera's preview for a development of the raw data.
Phase 1: real development, DNG first, 8-bit output #
- DNG:
- uncompressed and deflate data;
- lossless JPEG (SOF3): extend the JPEG decoder with predictors 1–7, the
point transform, 2–16 bit precision and SSSS=16, reusing
huffman.zig; - tiles and strips;
- the tags
CFAPattern,BlackLevel/WhiteLevel,LinearizationTable,AsShotNeutral,ColorMatrix1/ColorMatrix2andForwardMatrix; - a bilinear demosaic first, then Malvar–He–Cutler (cheap and good) or AHD;
- development in f32, then the sRGB curve, then scaling to
Rgba8.
- CR2:
- the same TIFF walker;
- Canon's sliced lossless JPEG;
- a per-model color matrix table. The usual sources are dcraw's
adobe_coeffand LibRaw's table, and their licensing has to be checked before either is used; LibRaw is LGPL/CDDL.
- NEF: Nikon's Huffman compression and its maker-note curve. It is known mostly from reverse engineering, and can wait.
- Memory: a 45 MP raw is about 90 MB of u16 samples, and full f32 RGB
working buffers are about 540 MB more. Develop in strips, and give
Limitsa raw-specific pixel budget so that the sandbox's arena stays bounded.
Phase 2: CR3 #
- The Phase 0 box walker, plus the CRX codec. It is known only from
reverse engineering: LibRaw's
crx.cpp, rawspeed, and rawloader. It is the largest single piece of this plan and the one most likely to hide bugs, so fuzzing and the sandbox matter more here than anywhere else.
Phase 3: high-precision surfaces, and writing DNG (optional) #
- In the z2d fork:
- an
rgbaf32or f16 format inpixel.zigandsurface.zig; - a direct float load and store in the compositor;
- float precision forced for float destinations;
- 16-bit PNG export;
- the piecewise sRGB curve;
sRGBandiCCPchunks.
- an
- In z2dimg: raw development into a float surface, and a high-depth type
beside
Rgba8insrc/pixels.zig. - Writing: CR2, CR3 and NEF are not worth writing, because nothing consumes a synthesized one. DNG is: either linear DNG (already demosaiced) or CFA DNG, uncompressed or lossless JPEG. It is only worth doing once float surfaces exist, because a DNG of 8-bit data is pointless.
Testing #
- Corpus. Raw files are large and belong to their photographers, so none
are checked in. A pinned sample set, such as files from raw.pixls.us (mostly
CC0), is fetched as a lazy Zig dependency, the way
corpus/fetches wuffs' test images. - Oracle.
- For previews, compare exact bytes with what
exiftool -b -PreviewImageextracts. - For development, compare with LibRaw's
dcraw_emuorrawpy. Undeveloped CFA values (rawpy'sraw_image) must match exactly. Developed output gets a tolerance, since demosaicing and matrices legitimately differ. - A checker script lives beside
tools/check_samples.py.
- For previews, compare exact bytes with what
- Fuzzing. A target for each container walker and each decompressor:
lossless JPEG, Nikon's Huffman coding, CRX. Each is seeded from the corpus
and run with
--alloc-failas well. - Sandbox and FreeBSD. New codecs run under the existing sandbox tests and the FreeBSD check with no extra wiring.
Rough size #
| Phase | New code | Risk |
|---|---|---|
| 0: detection, TIFF and BMFF walkers, previews | ~1.5k lines | low |
| 1: DNG and CR2 development, lossless JPEG | ~3–4k lines, plus a matrix table | medium |
| 1b: NEF | ~1k lines | medium: reverse-engineered |
| 2: CR3 and CRX | ~2–3k lines | high: no specification |
| 3: float surfaces, 16-bit PNG, DNG writer | ~2k lines in z2d, ~1k here | medium |