- C 49.9%
- F* 48.8%
- Makefile 1.1%
- Nix 0.2%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
T.81 gives F.1.2.1 and Figure F.12 as two separate procedures: how a coefficient becomes a category and some bits, and how those become a coefficient again. Nothing said they were inverse. `size_of` ensured only that its bits fit in its category, which a category one too large satisfies just as well -- and which would write a coefficient the decoder reads back as a different number, producing a plausible wrong image rather than a failure. `size_of_go` now characterises the category instead of bounding it: the magnitude fits in `r - n` bits and does not fit in one fewer. That second half is what turns the bound into an inverse, and `size_of` carries `extend (snd r) (fst r) == v` in its own postcondition, so every caller has it without asking. PLAN.md had drifted: a Phase 10 that appeared twice, once "not started" and once done, and a Phase 11 marked not started that had shipped. It now says what is actually done, and Phase 13 names the codec laws still missing in the order their value falls off -- the Huffman pair, the bit writer across the byte stuffing, the zig-zag as a permutation, quantisation as an inequality. The inverse transform stays out on purpose: T.83 specifies an accuracy bound for it rather than a value, so there is no equality to prove. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01S852yy4t7AsCkxUYisD1f4 |
||
| api | ||
| bench | ||
| spec | ||
| src | ||
| test | ||
| .gitignore | ||
| COMPAT.md | ||
| ISSUES.md | ||
| Makefile | ||
| PLAN.md | ||
| README.md | ||
| shell.nix | ||
libheif in Low*
libheif's box layer, reimplemented in Low* and extracted to C by KaRaMeL, behind libheif's own API. All 454 public functions are implemented: reading, writing, sequences, regions, properties, components and the rest. Coded images still need an external codec, as they do in libheif. See What is not.
nix-shell --run 'make check' # proofs, both corpora, and every test below
What is proved
Three theorems, machine-checked, for the box layer:
(1) spec_parse (spec_serialize v) == Some (v, |spec_serialize v|) -- complete
(2) spec_parse b == Some (v, n) ==> spec_serialize v == b[0..n) -- non-malleable
(3) impl_parse b == spec_parse b -- refinement
(1) and (2) say the F* specification is the ISO/IEC 14496-12 byte format rather than some arbitrary function of bytes: every value has exactly one encoding, and every well-formed encoding parses back to the value that produced it. (3) says the extracted C computes exactly that — memory-safely and terminating, since it is Low*. Without (1) and (2), (3) would be vacuous.
On top of that:
- Nesting is bounded by construction. The box tree is validated to a depth
index rather than a runtime counter, so a maliciously nested file cannot
recurse — libheif checks the same bound (
MAX_BOX_NESTING_LEVEL = 20) at run time to avoid stack exhaustion. - Item extents cannot escape the file.
resolve_extentis the only way to turn anilocoffset — an arbitrary 64-bit number from the input — into a readable range, and it returns one only if the range is inside the file. - A track's sample table is walked under its own checked bounds. Where an item states an offset, a track states four run-length-coded tables that have to agree with each other. Every one is read with its entry count checked against the room the box has, every walk is bounded by that checked count rather than the declared one, and the products that could overflow — a chunk count times a per-chunk count, a sum over a chunk's sample sizes — are compared by division instead of being formed.
- Colour conversion is bit-identical to libheif, checked over all 2²⁴
(y, cb, cr)triples, with no overflow and every plane access in bounds. - Derived images terminate by construction.
iden,gridandiovlare composited by a recursion whose bound is itsdecreasesmeasure, so a file nesting them deeper than the limit is refused and a circular one terminates -- neither depending on a runtime counter being checked in the right place. - A plane's sample width is part of its type. An 8-bit and a 16-bit plane
are different types carrying different buffers, and a channel is a field
rather than a list entry, so the shape of CVE-2026-84383 -- two Alpha planes
of different depths, one allocation written at the other's width -- has no
expression here.
ISSUES.mdworks through which of its four steps that rules out and which it does not. - The JPEG magnitude categories are inverse. T.81 gives F.1.2.1 and
Figure F.12 as two separate procedures -- how a coefficient becomes a
category and some bits, and how those become a coefficient again. Here
size_ofcarriesextend (snd r) (fst r) == vin its own postcondition, so every caller has it: a coefficient that goes through the entropy coder comes back as the number that went in. The category is characterised rather than bounded -- the magnitude fits innbits and not inn-1-- which is the half a bounds-only contract was missing and the half that makes it an inverse. - The JPEG codec cannot overflow or diverge on any input. Every coefficient
is clamped at the point it is read rather than assumed to be in range, so the
I64 accumulators in the transform are bounded by construction: a coefficient
capped at 2^25 times a constant below 2^13, summed eight times, is below
2^41. The Huffman decode, the marker walk and the bit filler each carry a
decreasesmeasure, so a truncated or adversarial codestream terminates rather than spinning. What is not claimed is bit-exactness of the inverse transform: ITU-T T.83 specifies an accuracy bound for it, not a value, somake jpegholds the decoder to within one level of libjpeg over fifteen cases rather than to equality.PLAN.mdphase 13 has the rest of the codec laws, in the order their value falls off. - Writing cannot run off the end. The emitter is a cursor that stops at the end of the buffer and never moves again, so a whole file is written with one check at the end rather than one per field, and a size computed wrongly overruns nothing. The only write that is not at the cursor is a box's size, and it checks that the position it was given lies behind the cursor.
Trust base: the specification matching the ISO documents, plus F*, Z3, KaRaMeL
and the C compiler. No assume val — the byte readers are built from
LowStar.Buffer.index rather than the axiomatised LowStar.Endianness
primitives, to keep it that way.
What is not
HEVC, AV1, VVC and AVC are not decoded here. libheif delegates them to
external codecs through a plugin interface, and so does this:
heifv_register_decoder takes one, and heif_decode_image returns
heif_error_Unsupported_feature without it. What is decoded natively is
everything whose bitstream is small enough to be worth proving: unci
(uncompressed) items, baseline JPEG (Heif.Impl.Jpeg, ITU-T T.81), and the
derived types grid, iovl and iden, which are composited from whatever
the leaves decoded to.
Encoding is native for the same two formats and absent for the rest.
heif_context_encode_image produces unci items and baseline JPEG ones, both
through the verified layer, and heif_context_add_grid_image and
heif_context_add_overlay_image arrange them. Asking the encoder for HEVC,
AV1 or VVC returns heif_error_Unsupported_feature with a message rather than
going missing, so a caller written against libheif links, runs, and is told.
There is no plugin loader. A codec is registered in-process with
heifv_register_decoder, which takes a function table rather than a shared
object; heif_load_plugin and its neighbours refuse. A verified library that
dlopens arbitrary code to parse untrusted input would be giving away what it
is for.
COMPAT.md lists all 51 places the API deliberately differs from libheif or
declines something, and nine more where libheif parses differently from the
standard. PLAN.md has the phase breakdown and how much of each is trusted
glue rather than verification.
What is implemented
454 of libheif's 454 public functions. The differential harness asks an identical set of questions of this library and of libheif 1.23.3 and diffs the answers: items, properties, brands, metadata, thumbnails, auxiliary images, entity groups, colour, regions, text, tiling, per-item component tables, and for sequences each track's id, handler, resolution, timescale, repetition count, sample count, byte total and a checksum over every sample's bytes. All 48 files of MPEG's conformance suite agree on all of it.
| area | verified layer | notes |
|---|---|---|
| box tree, all 44 types | Heif.Spec.*, Heif.Impl.Box/Tree/Dispatch |
the three theorems |
| items, properties, references | Heif.Impl.Meta, .Item, .Props |
|
| derived images | Heif.Impl.Render, .Compose, .Image |
grid, iovl, iden |
| uncompressed frames | Heif.Impl.Unci |
ISO/IEC 23001-17 |
| colour conversion | Heif.Impl.Color |
bit-identical to libheif |
| region annotations | Heif.Impl.Region |
all seven geometries |
| the MinimizedImageBox | Heif.Impl.Mini, .Bits |
ISO/IEC 23008-12 Annex O |
| codestream headers | Heif.Impl.Stream |
JPEG SOF, JPEG 2000 SIZ, depth SEI |
| baseline JPEG | Heif.Impl.Jpeg |
ITU-T T.81, decode and encode |
| tracks and sample tables | Heif.Impl.Track |
moov/trak/stbl, edit lists |
| writing | Heif.Impl.Emit, .Write |
boxes out, and the round-trip theorem |
Results
| MPEG HEIF conformance suite | 48/48 parsed completely |
| libheif well-formed corpus | 105/105 parsed completely |
| independent C walk vs. extracted proof | 0 disagreements over 203 files |
| item extents resolved | 239, 0 unreadable |
| colour conversion vs. libheif | 2²⁴ triples, 0 mismatches |
| compat API vs. libheif 1.23.3 | identical on 48/48 files (strict mode) |
| the same, over both corpora | 298 files, 0 where libheif finds an image and this does not |
| derived-image placement | 5/5 grids and nested iden chains correct |
| sequence samples located | 4,234 across 15 tracks, every one inside the file |
| written files read back | items, properties, references, metadata, regions, text, timestamps, grids, overlays, tracks |
| JPEG decode vs. libjpeg | 15 cases, every sample within 1 (T.83 accuracy, not exactness) |
| JPEG encode round trip | 6 cases, and libjpeg reads the result within 7 levels of the original |
The four extents reported as outside the file all come from
pclr_zero_columns.heic, which is 3,173 bytes and declares extents ending at
718,098. Refusing them is the point.
Two files in libheif's corpus are rejected by its sequence parser and opened here; neither contains a still image. There is no file in either corpus where libheif finds an image and this does not.
What goes out comes back. The writer is checked the only way a writer can
be: a context is built through the public API, written, and read with a fresh
context through the same accessors every other file goes through. The reader
knows nothing about the writer, so a box emitted at the wrong offset, with the
wrong size, or with its fields in the wrong order fails there — which is how
three real defects were found. fmt_infe rejected a mime entry written
without its content encoding; a two-by-one grid read back as one-by-two,
because ISO/IEC 23008-12 puts rows before columns; and an inline region mask
packed with row padding came back one region short, because the format pads
only the last byte of the whole mask.
Performance
make bench, against libheif 1.23.3 from nixpkgs, same machine, same flags,
alternating order, best of N trials. Minimum rather than mean: both sides do
the same work on the same bytes, so every difference between trials is
interference, and interference only ever adds time.
| verified | reference | ratio | |
|---|---|---|---|
| opening a file (48-file corpus) | 0.77 µs/file | 0.77 µs/file (libheif) | 1.00x |
| YCbCr 4:2:0 → RGBA, 1920×1080 | 4.76 ns/px | 4.66 ns/px (libheif's integer path) | 1.02x |
| compositing a 2×2 grid of 1280×720 tiles | 55 Gpx/s | 55 Gpx/s (row-wise memcpy) |
0.99x |
Three things are worth saying about those numbers rather than leaving them to be read off.
Opening a file costs the same, but this does more. 68% of the open here is
validating the entire box tree to the nesting limit against the format
specification -- that is what heif_context_read_from_memory means in this
library. libheif parses the boxes it needs. Neither reads the payload: a box
header carries its own size, so mdat is stepped over, and the cost tracks the
number of boxes rather than the size of the file. C025 is 19 KiB and C007 is
535 KiB, and both open in about a microsecond.
The colour converter is bit-identical, not merely close -- all 2²⁴ input
triples agree with libheif's integer path -- and getting it to parity took two
codegen fixes rather than any change to the algorithm. The rounding divide is
done unsigned so gcc emits a shift instead of the sign-correction sequence a
signed divide by a power of two needs, and the loops are C.Loops.for so
KaRaMeL emits a real for that gcc can hoist the row bases out of. Both are
commented in Heif.Impl.Color with the measurement that motivated them.
The blit was 13x slower before it was measured. It was a per-sample loop:
correct, proved, and pointless, because the bound it establishes is the same
one a row-wise copy needs. B.blit is verified and extracts to memcpy, so
the fix cost nothing in assurance. That is the general shape of the three
results -- where this is slower than libheif it has been a code-generation or
loop-shape problem, not the proofs.
Layout
| path | contents |
|---|---|
spec/Heif.Spec.Format |
valid laws; uintbe, lbytes, map, filter, bind |
spec/Heif.Spec.Exact |
evalid; exact, exactly, all, list, nlist, region |
spec/Heif.Spec.BE, .Cstring |
big-endian bridge; NUL-terminated strings |
spec/Heif.Spec.Box |
box header (§4.2), fmt_box, fmt_boxes |
spec/Heif.Spec.Body, .Codec |
all 44 box payloads; hvcC, av1C |
spec/Heif.Spec.Dispatch, .Tree |
fourcc → format; depth-bounded tree |
src/Heif.Impl.Slice, .Validate |
input view; validator/reader combinators |
src/Heif.Impl.Body, .Box, .Dispatch, .Tree |
validators for every format above |
src/Heif.Impl.Item |
iloc extent resolution |
src/Heif.Impl.Meta |
readers for pitm, iinf, ipma/ipco, iref, ispe |
src/Heif.Impl.Props |
irot, clap, grid, iovl; depth from hvcC/av1C |
src/Heif.Impl.Image |
planes, allocation, scaling, the clipping blit |
src/Heif.Impl.Compose |
tile placement; sub-plane views |
src/Heif.Impl.Render |
iden/grid/iovl; multi-extent and idat items |
src/Heif.Impl.Unci |
uncompressed frames (ISO/IEC 23001-17) |
src/Heif.Impl.Color |
YCbCr → RGBA |
src/Heif.Impl.Region |
region annotations (rgan), all seven geometries |
src/Heif.Impl.Bits |
a bit cursor, and Exp-Golomb |
src/Heif.Impl.Mini |
the MinimizedImageBox (23008-12 Annex O) |
src/Heif.Impl.Stream |
what a codestream says about itself: JPEG SOF, J2K SIZ, depth SEI |
src/Heif.Impl.Track |
tracks and sample tables; stts/stsc/stsz/stco, edit lists |
src/Heif.Impl.Write |
serialisation primitives and the round-trip theorem |
src/Heif.Impl.Emit |
the box writer: a cursor that stops at the end |
api/heifv.h, api/heifv.c |
the native API: ranges, extents, planes |
api/heif.h, api/heif_compat.c |
the libheif-compatible API, all 454 functions |
test/ |
box walk, item dump, exhaustive colour check, libheif diff, placement, components, sensor properties, writing, sequences |
bench/ |
open, colour conversion, compositing — each against a reference |
Building
krml is built once from the karamel/ checkout; nixpkgs has no karamel
derivation. karamel/flake.nix is more hermetic but rebuilds F* from source,
whereas the nixpkgs F* is binary-cached and was checked compatible with this
krml. make conformance fetches MPEG's suite over git-lfs.
Conformance
COMPAT.md lists every place libheif parses differently from the standard —
nine cases, all of them libheif accepting two byte strings as the same value,
which property (2) forbids — and 47 more where api/heif.h deliberately
differs from libheif or declines something, four of which
heifv_set_libheif_strict switches off.
ISSUES.md records memory-safety findings. In libheif: none so far, which
is a real result given the 132 fuzzer crash inputs in its corpus. It also
records what CVE-2026-84383 would and would not have been caught by, two
defects found in this code by tests rather than by proof — a base offset
added twice, and a cmpd box read as a FullBox when it is a plain one — both
silently wrong and neither unsafe, because in each case the bound was
established independently of the value that was wrong. That split is the
recurring shape: the proofs rule out reading the wrong memory, and the
differential and round-trip tests are what rule out reading the wrong
numbers.
Grounding is MPEG's machine-readable box syntax (300 definitions across
14496-12 and 23008-12) and its HEIF conformance suite, both freely available;
the normative prose is paywalled and is not used. Cross-checking against it
found two places where libheif's non-normative behaviour had been copied into
this parser, and one design bug: box semantics are container-dependent, and
inside iref a child's fourcc is a reference type rather than a box type.