Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M9.6: DNxHD/DNxHR (SMPTE ST 2019-1 VC-3) decoder and DNxHR encoder

Brandon Thomas226c13974113
diff --git a/Cargo.lock b/Cargo.lock
index a26c5e7d6..fa2abe37d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1391,6 +1391,7 @@ dependencies = [
"filmcraft-aac",
"filmcraft-bitstream",
"filmcraft-color",
+ "filmcraft-dnx",
"filmcraft-frame",
"filmcraft-h264",
"filmcraft-hevc",
@@ -1415,6 +1416,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "filmcraft-dnx"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-bitstream",
+ "filmcraft-testkit",
+ "rayon",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "filmcraft-edit"
version = "0.1.0"
@@ -1460,6 +1471,7 @@ dependencies = [
"filmcraft-aac",
"filmcraft-codecs",
"filmcraft-color",
+ "filmcraft-dnx",
"filmcraft-frame",
"filmcraft-h264enc",
"filmcraft-isobmff",
diff --git a/Cargo.toml b/Cargo.toml
index 00ddb8419..cad78fb55 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,6 +22,7 @@ filmcraft-h264 = { path = "crates/h264" }
filmcraft-hevc = { path = "crates/hevc" }
filmcraft-vp9 = { path = "crates/vp9" }
filmcraft-prores = { path = "crates/prores" }
+filmcraft-dnx = { path = "crates/dnx" }
filmcraft-aac = { path = "crates/aac" }
filmcraft-opus = { path = "crates/opus" }
filmcraft-h264enc = { path = "crates/h264enc" }
@@ -87,6 +88,9 @@ opt-level = 3
[profile.dev.package.filmcraft-prores]
opt-level = 3
+[profile.dev.package.filmcraft-dnx]
+opt-level = 3
+
[profile.dev.package.filmcraft-aac]
opt-level = 3
diff --git a/ROADMAP.md b/ROADMAP.md
index c979d9064..5b8b23a8a 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -37,7 +37,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining
| M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 + own AAC; ProRes, MJPEG, PNG, GIF, WAV; background jobs | Preset library, queue UI, smart render | 6–8 |
| M7 | Audio | 🟡 | Mixer graph (tracks → submixes → Mix, pre/post-fader inserts and sends, latency-compensated, sample-accurate, ~6× realtime for 24 tracks × 3 effects on one core), Audio Track Mixer + Audio Clip Mixer panels, track automation (Off/Read/Latch/Touch/Write, recorded live while playing, thinned to keyframes, timeline lanes with pen editing), solo/solo-safe, channel mapping basics, peak + BS.1770 loudness meters (match ffmpeg), DSP crate with 16 clip/track effects, Audio Gain (set/adjust/normalize), Constant Power / Constant Gain / Exponential Fade, Essential Sound (types, Loudness auto-match, Repair incl. DeEss/DeReverb, Clarity, Creative, Ducking keyframes, presets; full Dialogue chain 22× realtime) | Music duration remix, ML speech enhancement, 5.1 panner and multichannel buses, voice-over record, effect editor windows (EQ curve), remaining effects (multiband, convolution reverb), clip-mixer automation recording | 6–9 |
| M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette, section bypass; Input LUT / Look LUT (.cube 1D/3D/shaper, .3dl; tetrahedral CPU + WGSL; project LUT library; built-in camera conversions); Colour Match (Oklab tonal-range statistics, skin protection, solved in Lumetri wheels); colour management: Rec. 709 / Rec. 2100 PQ / HLG working spaces + wide gamut, Interpret Footage colour space (S-Log3, V-Log, Canon Log 2/3, LogC3/4, Apple Log, D-Log from published specs), metadata auto-detect, BT.2390 tone mapping, gamut mapping, HDR export signalling (VUI/colr/mdcv/clli/SEI, ffprobe-verified); scopes incl. HDR nits waveform | Parade/histogram/HLS scopes, HDR-aware Lumetri maths, macOS EDR monitors, mastering metadata → tone-map peak, D-Log M (no published formula), HSL Secondary refine | 3–5 |
-| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), VP9 decoder (profiles 0–3, 8/10/12-bit, bit-exact on 50+ fixtures; WebM/MKV `V_VP9` and MP4 `vp09` import with key-frame-checked seeking), Matroska/WebM import (H.264/HEVC/VP9/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4) | VP9 frame threading, Ogg Opus files, AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |
+| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), VP9 decoder (profiles 0–3, 8/10/12-bit, bit-exact on 50+ fixtures; WebM/MKV `V_VP9` and MP4 `vp09` import with key-frame-checked seeking), Matroska/WebM import (H.264/HEVC/VP9/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4), DNxHD/DNxHR decoder (all SMPTE ST 2019-1 CIDs, 8/10/12-bit, 4:2:2/4:4:4, interlaced, alpha; within IDCT precision of ffmpeg on 22 fixtures) + DNxHR LB/SQ/HQ/HQX/444 encoder and MOV `AVdh` export | VP9 frame threading, Ogg Opus files, AV1, MXF, hardware decode | 12–20 |
| M10 | Graphics & captions | 🟡 | Caption tracks (Subtitle/CEA-608/708/Teletext formats, track style), SRT/WebVTT/SCC import+export (frame-exact, property-tested), caption editing (add/split/merge/trim/move, sync-locked insert/extract), Text panel Captions tab, burn-in in Program monitor and export; text engine (`crates/text`: bundled + system fonts, harfrust shaping, bidi, line breaking, paragraph layout, glyph cache; 3-line 1080p title ≈ 0.15 ms warm); graphic clips with text + shape layers (fill, 2 strokes, background, shadow, keyframable transform), Type tool with on-monitor editing, shape/pen tools, Properties/Essential Graphics editor, align/distribute | Responsive design pins, rolls/crawls, per-character styles, motion graphics templates, MCC/STL/TTML, 608/708 embedding, speech-to-text | 12–18 |
| M11 | Interchange & project management | ✅ | `.fcproj` schema versions + migrations, atomic saves, Save a Copy/Revert, auto-save ring + crash-recovery journal (Preferences ▸ Auto Save, recovery prompt), FCP7 XML, FCPXML, EDL, OTIO; offline media (own slate) + Link Media (fingerprint-checked relink, folder remap, search, Align Timecode, Make Offline); proxies (ProRes Proxy/LT, H.264 ¼/½ background jobs, attach/detach/reconnect, monitor toggle, export full-res) + ingest (copy/transcode/proxies); Project Manager (collect, consolidate + transcode with handles, size estimate) | Rename media to clip names, image-sequence conversion, Media Browser-driven relink, smart (cross-drive) path tracking | 1–2 |
| M12–M16 | Web (WASM), platform, long tail | 🟡 | L0–L4 crates compile to wasm32 | Web app shell (file access, WebCodecs, audio), ~850 remaining commands and dialogs, performance hardening | 40–65 |
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index 843bd4f1a..a672f68d2 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -21,6 +21,7 @@ filmcraft-h264 = { workspace = true }
filmcraft-hevc = { workspace = true }
filmcraft-vp9 = { workspace = true }
filmcraft-prores = { workspace = true }
+filmcraft-dnx = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-opus = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 7a1baad0d..4eee8d9eb 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -51,7 +51,9 @@ impl From<CodecError> for filmcraft_media::MediaError {
fn factories() -> &'static RwLock<Vec<VideoDecoderFactory>> {
static F: std::sync::OnceLock<RwLock<Vec<VideoDecoderFactory>>> = std::sync::OnceLock::new();
- F.get_or_init(|| RwLock::new(vec![video::h264_factory, video::hevc_factory, video::vp9_factory, video::prores_factory, video::mjpeg_factory]))
+ F.get_or_init(|| {
+ RwLock::new(vec![video::h264_factory, video::hevc_factory, video::vp9_factory, video::prores_factory, video::dnx_factory, video::mjpeg_factory])
+ })
}
/// Register a video decoder factory (tried before previously registered ones).
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 8d8f46097..071939d64 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -113,7 +113,7 @@ impl Mp4Source {
explicit_color = Some(color);
}
let bitrate = (t.samples.iter().map(|s| s.size as u64).sum::<u64>() * 8 * t.timescale as u64).checked_div(t.duration);
- VideoStreamInfo {
+ let mut info = VideoStreamInfo {
width: w,
height: h,
frame_rate: rate,
@@ -123,7 +123,23 @@ impl Mp4Source {
color,
has_alpha: matches!(&entry.codec, CodecConfig::ProRes { fourcc } if fourcc.0 == *b"ap4h" || fourcc.0 == *b"ap4x"),
bitrate,
+ };
+ if matches!(entry.codec, CodecConfig::Dnx { .. }) {
+ // the sample entry doesn't say which VC-3 compression ID it is: read the first frame header
+ let s0 = &t.samples[0];
+ if let Some(h) = bytes.get(s0.offset as usize..(s0.offset as usize).saturating_add(s0.size as usize)).and_then(|d| filmcraft_dnx::probe(d).ok())
+ {
+ info.codec = filmcraft_dnx::cid_name(h.cid);
+ let sub = match h.chroma {
+ filmcraft_dnx::ChromaFormat::Yuv420 => "YUV 4:2:0",
+ filmcraft_dnx::ChromaFormat::Yuv422 => "YUV 4:2:2",
+ filmcraft_dnx::ChromaFormat::Yuv444 => "4:4:4",
+ };
+ info.pixel_format = format!("{sub} {}-bit", h.bit_depth);
+ info.has_alpha = h.alpha;
+ }
}
+ info
});
let audio = atrack.map(|i| {
let t = &file.tracks[i];
@@ -396,6 +412,8 @@ fn codec_label(c: &CodecConfig) -> String {
}
CodecConfig::Pcm(p) => format!("PCM {}-bit{}", p.bits, if p.float { " float" } else { "" }),
CodecConfig::Opus(_) => "Opus".into(),
+ CodecConfig::Dnx { fourcc } if fourcc.0 == *b"AVdh" => "Avid DNxHR".into(),
+ CodecConfig::Dnx { .. } => "Avid DNxHD".into(),
other => other.name().to_string(),
}
}
diff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rs
index fc35862aa..d07dbbe99 100644
--- a/crates/codecs/src/tests.rs
+++ b/crates/codecs/src/tests.rs
@@ -136,6 +136,29 @@ fn prores_mov_decodes() {
assert!((c[0] as i32 - 104).abs() < 6, "{c:?}");
}
+#[test]
+fn dnxhd_and_dnxhr_movs_decode() {
+ for (name, args, codec, fmt) in [
+ ("bars_dnxhr_hq.mov", &["-c:v", "dnxhd", "-profile:v", "dnxhr_hq", "-pix_fmt", "yuv422p"][..], "DNxHR HQ", "4:2:2"),
+ ("bars_dnxhr_hqx.mov", &["-c:v", "dnxhd", "-profile:v", "dnxhr_hqx", "-pix_fmt", "yuv422p10le"][..], "DNxHR HQX", "4:2:2"),
+ ("bars_dnxhd_1251.mov", &["-c:v", "dnxhd", "-b:v", "90M", "-pix_fmt", "yuv422p"][..], "CID 1251", "4:2:2"),
+ ] {
+ let mut a = vec!["-f", "lavfi", "-i", if name.contains("1251") { "smptehdbars=s=1280x720:r=50:d=0.2" } else { "smptehdbars=s=640x360:r=24:d=0.5" }];
+ a.extend_from_slice(args);
+ let Some(b) = fixture(name, &a) else { return };
+ let src = crate::open_bytes(name, b).unwrap();
+ let info = src.info().video.clone().unwrap();
+ assert!(info.codec.contains(codec), "{}", info.codec);
+ let f = src.video_frame(FrameRequest::full(Tick(TICKS_PER_SECOND / 10))).unwrap();
+ assert!(f.format_label().contains(fmt), "{}", f.format_label());
+ let w = f.width as usize;
+ let px = f.to_rgba8();
+ // leftmost bars area is 40% grey
+ let c = &px[(100 * w + 20) * 4..][..3];
+ assert!((c[0] as i32 - 104).abs() < 6, "{name}: {c:?}");
+ }
+}
+
/// Solid-colour Matroska fixtures: decoded frames must match the colour, audio must be a 1 kHz tone.
fn check_mkv(name: &str, vcodec: &[&str], acodec: &[&str]) {
let mut args: Vec<&str> =
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index 9542951d1..b473ce253 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -409,3 +409,75 @@ impl VideoDecoder for ProResDecoder {
pub fn prores_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
matches!(e.codec, CodecConfig::ProRes { .. }).then(|| Ok(Box::new(ProResDecoder) as Box<dyn VideoDecoder>))
}
+
+/// Our DNxHD / DNxHR (VC-3) decoder (every frame is intra; macroblock rows decode in parallel).
+pub struct DnxDecoder;
+
+/// Convert a decoded VC-3 frame to a [`VideoFrame`]. RGB (4:4:4) frames are converted to
+/// BT.709 video-range Y'CbCr 4:4:4 at the coded depth.
+pub fn dnx_to_video_frame(f: filmcraft_dnx::Frame) -> VideoFrame {
+ use std::sync::Arc;
+ let chroma = match f.chroma {
+ filmcraft_dnx::ChromaFormat::Yuv420 => filmcraft_frame::Chroma::C420,
+ filmcraft_dnx::ChromaFormat::Yuv422 => filmcraft_frame::Chroma::C422,
+ filmcraft_dnx::ChromaFormat::Yuv444 => filmcraft_frame::Chroma::C444,
+ };
+ let mut color = filmcraft_color::ColorInfo::REC709;
+ if matches!(f.color_volume, filmcraft_dnx::ColorVolume::Bt2020Ncl | filmcraft_dnx::ColorVolume::Bt2020Cl) {
+ color.matrix = filmcraft_color::Matrix::Bt2020Ncl;
+ color.primaries = filmcraft_color::Primaries::Bt2020;
+ }
+ let (mut y, mut cb, mut cr) = (f.y, f.cb, f.cr);
+ if f.rgb {
+ // planes hold G, B, R (video range); derive Y'CbCr with the stream's matrix
+ let (kr, kb) = color.matrix.kr_kb();
+ let kg = 1.0 - kr - kb;
+ let s = (1u32 << (f.bit_depth - 8)) as f32;
+ let max = ((1u32 << f.bit_depth) - 1) as f32;
+ let c = 224.0 / 219.0;
+ for i in 0..y.len() {
+ let (g, b, r) = (y[i] as f32, cb[i] as f32, cr[i] as f32);
+ let yy = kr * r + kg * g + kb * b;
+ let u = (b - yy) / (2.0 * (1.0 - kb)) * c + 128.0 * s;
+ let v = (r - yy) / (2.0 * (1.0 - kr)) * c + 128.0 * s;
+ y[i] = (yy + 0.5).clamp(0.0, max) as u16;
+ cb[i] = (u + 0.5).clamp(0.0, max) as u16;
+ cr[i] = (v + 0.5).clamp(0.0, max) as u16;
+ }
+ }
+ let par = match f.par {
+ (n, d) if n > 0 && d > 0 => (n as u32, d as u32),
+ // thin rasters (1440 / 960 wide) are anamorphic 16:9
+ _ if matches!(f.cid, 1244 | 1259 | 1260) => (4, 3),
+ _ if f.cid == 1258 => (4, 3),
+ _ => (1, 1),
+ };
+ let data = if f.bit_depth == 8 {
+ let to8 = |p: Vec<u16>| Arc::new(p.into_iter().map(|v| v as u8).collect::<Vec<u8>>());
+ filmcraft_frame::PixelData::Yuv8 { planes: [to8(y), to8(cb), to8(cr)], chroma, alpha: f.alpha.map(to8) }
+ } else {
+ filmcraft_frame::PixelData::Yuv16 { planes: [Arc::new(y), Arc::new(cb), Arc::new(cr)], chroma, bits: f.bit_depth as u32, alpha: f.alpha.map(Arc::new) }
+ };
+ VideoFrame { width: f.width, height: f.height, data, color, par, pts: filmcraft_time::Tick::ZERO }
+}
+
+impl VideoDecoder for DnxDecoder {
+ fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
+ let f = filmcraft_dnx::decode_frame(sample).map_err(|e| CodecError::Decode(e.to_string()))?;
+ Ok(vec![DecodedFrame { pts, frame: dnx_to_video_frame(f) }])
+ }
+ fn flush(&mut self) -> Vec<DecodedFrame> {
+ Vec::new()
+ }
+ fn reset(&mut self) {}
+ fn name(&self) -> &str {
+ "FilmCraft DNxHD/DNxHR"
+ }
+ fn intra_only(&self) -> bool {
+ true
+ }
+}
+
+pub fn dnx_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
+ matches!(e.codec, CodecConfig::Dnx { .. }).then(|| Ok(Box::new(DnxDecoder) as Box<dyn VideoDecoder>))
+}
diff --git a/crates/dnx/Cargo.toml b/crates/dnx/Cargo.toml
new file mode 100644
index 000000000..9b5d34db5
--- /dev/null
+++ b/crates/dnx/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "filmcraft-dnx"
+description = "Clean-room Avid DNxHD / DNxHR (SMPTE ST 2019-1 VC-3) decoder and encoder"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[features]
+default = ["threads"]
+threads = ["dep:rayon"]
+
+[dependencies]
+filmcraft-bitstream = { workspace = true }
+thiserror = { workspace = true }
+rayon = { workspace = true, optional = true }
+
+[dev-dependencies]
+filmcraft-testkit = { workspace = true }
diff --git a/crates/dnx/README.md b/crates/dnx/README.md
new file mode 100644
index 000000000..cf51f71f9
--- /dev/null
+++ b/crates/dnx/README.md
@@ -0,0 +1,141 @@
+# filmcraft-dnx
+
+Clean-room Avid DNxHD / DNxHR (VC-3) decoder and encoder in pure Rust, written from the public
+**SMPTE ST 2019-1:2016** *VC-3 Picture Compression and Data Stream Format* and its
+**Amendment 1:2023** (both free from `pub.smpte.org`). Layer L0: depends only on
+`filmcraft-bitstream`, `thiserror` and (optional, feature `threads`, default on) `rayon`. Builds
+for `wasm32-unknown-unknown`; no `unsafe`.
+
+The constant tables (Annex D quantisation weights, Annex E VLC tables) were extracted from the
+standard's text by [`tools/extract_tables.py`](tools/extract_tables.py) into
+`src/spec_tables.rs`; the script checks every table's size and that every VLC table is a
+complete prefix code. No code was taken from FFmpeg or any other implementation; ffmpeg is used
+only as an external fixture generator and test oracle.
+
+## Status
+
+| Area | Status |
+|---|---|
+| Header (§7.2): all fields, HVN 1–4, RI header growth above 1088 lines, time code | done |
+| DNxHD (HD profile) CIDs 1235, 1237, 1238, 1241–1244, 1250–1253, 1258, 1259 | done, oracle-tested |
+| CID 1256 (HD RGB 4:4:4) and 1260 (macroblock-adaptive field/frame, 1440×1080i) | done, not oracle-tested (ffmpeg can't encode them) |
+| DNxHR (RI profile) 1270–1274: LB, SQ, HQ, HQX, 444; any raster 1…16384 | done, oracle-tested |
+| 8-, 10-, 12-bit; 4:2:2, 4:4:4; Y′CbCr and RGB (per-macroblock ACF) | done (12-bit: our encoder's streams, compared with ffmpeg's decode) |
+| 4:2:0 (RI only) | done, not oracle-tested (ffmpeg can't encode it) |
+| Interlaced: field-coded (two coding units) and frame-coded MACF | done |
+| Alpha: DCT-coded and lossless differential RLE (Amendment 1 for HD CIDs) | done, not oracle-tested (no encoder produces it) |
+| CBR padding, VBR, scan-line indices, EOF signature / CRC flag | done |
+| Encoder: DNxHR LB, SQ, HQ (8-bit), HQX (10/12-bit), 444 (10/12-bit); CBR | done |
+| Encoder: DNxHD (HD CIDs), interlaced, alpha, VBR | not yet |
+
+## API
+
+```rust
+use filmcraft_dnx::*;
+
+let frame: Frame = decode_frame(&sample)?; // one or two coding units
+let f = decode_frame_with(&sample, &DecodeOptions { threads: false, ..Default::default() })?;
+let hdr: FrameHeader = probe(&sample)?; // cid, raster, depth, chroma…
+let name = cid_name(hdr.cid); // "DNxHR HQX", "DNxHD 1080i 8-bit (CID 1242)"
+
+let mut enc = Encoder::new(Profile::Hq, 1920, 1080); // or Encoder::with_config(EncoderConfig { .. })
+let sample: Vec<u8> = enc.encode(&frame)?; // exactly enc.frame_size() bytes (CBR)
+```
+
+`Frame { width, height, chroma, rgb, bit_depth, y, cb, cr: Vec<u16>, alpha, interlace,
+color_volume, cid, par }` holds planar samples without row padding. Interlaced frames are woven
+(field 1 = top field on even lines). RGB frames hold G, B, R in `y`, `cb`, `cr`. In MOV the
+sample entry is `AVdn` (DNxHD) or `AVdh` (DNxHR); `filmcraft-codecs` reads the CID from the
+first frame header to label the stream.
+
+## Decoder
+
+- Every coding unit's scan-line indices give each macroblock row's byte offset, so rows decode
+ independently and in parallel, writing straight into their 16-line bands.
+- VLCs are decoded with two-level lookup tables (11-bit primary) built from the Annex E lists.
+- Inverse quantisation with the CID's Annex D weights; IDCT: the exact orthonormal 8×8 inverse DCT
+ of equation 8.3, evaluated separably in `f32` (shared design with `filmcraft-prores`).
+ Output: `floor(x·s + 2^(b−1) + ½)` clipped to `[0, 2^b − 1]`, where `s = 4` at 12 bits (the
+ 12-bit coefficient domain is ¼ of the orthonormal DCT, as Table 14's 13-bit IDCT input range
+ for 12-bit samples implies) and 1 otherwise.
+- Robustness: every offset and size is validated, run lengths past coefficient 63 are rejected,
+ and corrupted or truncated streams return `Err` without panicking (`tests/roundtrip.rs`).
+
+### Where we follow ffmpeg rather than the letter of the standard
+
+ffmpeg's decoder is the reference everyone interoperates with (and the oracle of our tests). In
+three places it differs from the text of ST 2019-1:2016; black-box probes (`src/ffmpeg_probe.rs`:
+streams with a single coefficient, decoded by ffmpeg, measured with a forward DCT) pinned down
+its behaviour, and we match it by default:
+
+1. **Reconstruction offset.** Equation 8.1 reconstructs a quantised amplitude `A` at
+ ≈ `(A + ½)·W·qsf/p`. ffmpeg reconstructs at `(A + ¾)·W·qsf/p` (fitted intercept 0.750 ± 0.01
+ steps for every CID family and step size). The decoder does the same;
+ `DecodeOptions::spec_dequant` selects equation 8.1 instead. The encoder picks the amplitude
+ nearest to the `(A + ¾)` reconstruction.
+2. **CID 1271 (DNxHR HQX) weights.** Table C.2 assigns Table D.1 to CID 1271. ffmpeg's decoder and
+ encoder use Table D.4 (the CID 1241 weights) — fitted RMS error 0.65 against D.4, > 2.6
+ against every other table. We use D.4.
+3. **4:4:4 signalling.** ffmpeg writes RGB DNxHR 444 with `CLF = 0`, and Y′CbCr 444 with `CLF = 1`
+ plus `ACF = 1` on every macroblock; its channel order is G, B, R (Ch1 = G). The decoder treats
+ every 4:4:4 stream as RGB except macroblocks flagged `ACF = 1` (a stream that is entirely
+ ACF = 1 is returned as Y′CbCr; mixed streams are converted to RGB macroblock by macroblock as
+ §8.1.1 describes), and the encoder writes the same signalling.
+
+Also noted: the RLE alpha pseudo code (Figure 50) tests the header bit the opposite way from
+the prose of §7.3.1.2; we follow the prose (normative text takes precedence).
+
+## Encoder
+
+- DNxHR LB/SQ/HQ (8-bit 4:2:2), HQX (10- or 12-bit 4:2:2) and 444 (10- or 12-bit 4:4:4,
+ Y′CbCr or RGB), progressive, CBR at exactly the equation 7.1 frame size (e.g. 917 504 bytes
+ for 1080p HQ, 606 208 for SQ). Input at any depth 8–16 is rescaled to the coded depth.
+- Every macroblock is transformed once (orthonormal FDCT) and stored pre-divided by its weights.
+ Rate control binary-searches the smallest uniform `qsf` whose frame fits the payload
+ (including the 4-byte scan-line alignment), starting from the previous frame's value, then
+ gives macroblocks one finer step, spread evenly over the frame, while the budget allows.
+- `export::Format::DnxHr` (`file.exportMedia {"format":"dnxhr","dnxProfile":"lb|sq|hq|hqx"}`)
+ writes QuickTime `AVdh` + PCM. The Avid-specific `ACLR`/`ADHR` sample-entry atoms are not
+ written (ffmpeg and our reader don't need them).
+
+## Accuracy (vs ffmpeg as an external oracle)
+
+`tests/oracle_decode.rs` decodes 22 fixtures made by ffmpeg's VC-3 encoder: CIDs 1235, 1237,
+1238, 1241, 1242, 1243, 1244, 1250, 1251, 1252, 1253, 1258, 1259 and DNxHR LB/SQ/HQ/HQX/444
+(Y′CbCr and RGB), with testsrc2, mandelbrot and heavy noise, at 1920×1080, 1280×720, 960×720,
+1440×1080 (thin raster, interlaced), 1000×562, 640×360, 256×120 and 3840×2160. Compared with
+ffmpeg's decode at the native depth, **every fixture is within ±2 LSB, with at most ~50 samples
+per million at ±2** (typically 1–30 per fixture); 87–99% of samples are bit-identical and the
+mean absolute error is 0.01–0.13 LSB. The remaining differences are ffmpeg's integer IDCT; this
+decoder evaluates the exact IDCT of equation 8.3, so decode is **not bit-exact, but within IDCT
+precision** of ffmpeg. (ffmpeg wraps rather than clips 10-bit reconstructions that overflow
+1023, so the noise fixtures keep their samples inside 24…231 before encoding.)
+
+`tests/oracle_encode.rs` encodes 1920×1080 frames with every profile and writes them into a
+minimal test-only MOV. ffmpeg decodes them with `-xerror`, without errors, and agrees with our
+decoder within ±2 (90–99% identical). Luma PSNR against the source: HQ 58.8 dB (mandelbrot) and
+66.3 dB (testsrc2), SQ 57.5 dB, LB 56.1 dB, HQX 10-bit 67.5 dB, HQX 12-bit 80.2 dB, 444 10-bit
+79.7 dB — all above the 45 dB HQ target.
+
+## Performance
+
+`cargo test --release -p filmcraft-dnx --test perf -- --ignored --nocapture` on an M4 Pro
+(14 cores) while the machine was **heavily overloaded** by other jobs (load average ≈ 190).
+Under the same load `filmcraft-prores`' perf test measured 30 fps threaded / 11.8 fps single
+for a 1080p HQ frame, against 318 / 53 fps in its README on a less loaded machine, so these are
+lower bounds by a factor of roughly 4–10:
+
+| Frame (busy synthetic content) | Decode, threaded | Decode, 1 thread | Encode |
+|---|---|---|---|
+| DNxHR HQ 1080p (896 KB) | 41 fps | 13.2 fps | 4.1 fps |
+| DNxHR HQX 10-bit 1080p (896 KB) | 39 fps | 8.9 fps | 3.6 fps |
+| DNxHR SQ 2160p (2352 KB) | 21 fps | 15.6 fps | 1.1 fps |
+| DNxHR HQX 10-bit 2160p (3556 KB) | 16 fps | 12.2 fps | 1.1 fps |
+
+## Gaps
+
+- Decode is within IDCT precision of ffmpeg, not bit-exact (see above).
+- Encoder: no DNxHD (HD CIDs), interlaced, alpha or VBR output; no RDO/trellis.
+- CIDs 1256/1260 and alpha decoding are implemented from the standard but have no oracle
+ fixtures, because no available encoder produces them.
+- No MXF; DNx in MOV only (via `filmcraft-isobmff` / `filmcraft-codecs`).
diff --git a/crates/dnx/src/bits.rs b/crates/dnx/src/bits.rs
new file mode 100644
index 000000000..9c3ae8fdf
--- /dev/null
+++ b/crates/dnx/src/bits.rs
@@ -0,0 +1,127 @@
+//! Fast MSB-first bit reader (64-bit cache) and writer for the macroblock data.
+
+use crate::tables::{LINK, Lut};
+
+/// Bit reader over one macroblock scan line. Reads past the end yield zero bits; callers check
+/// [`Reader::overrun`].
+pub(crate) struct Reader<'a> {
+ data: &'a [u8],
+ next: usize,
+ cache: u64,
+ avail: u32,
+}
+
+impl<'a> Reader<'a> {
+ #[inline]
+ pub fn new(data: &'a [u8]) -> Self {
+ let mut r = Self { data, next: 0, cache: 0, avail: 0 };
+ r.refill();
+ r
+ }
+
+ /// Ensure at least 56 valid bits are cached.
+ #[inline(always)]
+ fn refill(&mut self) {
+ if self.avail >= 56 {
+ return;
+ }
+ if let Some(s) = self.data.get(self.next..self.next + 8) {
+ let w = u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]);
+ self.cache |= w >> self.avail;
+ self.next += ((63 - self.avail) >> 3) as usize;
+ self.avail |= 56;
+ } else {
+ while self.avail <= 56 {
+ let b = self.data.get(self.next).copied().unwrap_or(0) as u64;
+ self.cache |= b << (56 - self.avail);
+ self.avail += 8;
+ self.next += 1;
+ }
+ }
+ }
+
+ #[inline(always)]
+ fn consume(&mut self, n: u32) {
+ self.cache <<= n;
+ self.avail -= n;
+ }
+
+ #[inline]
+ pub fn consumed(&self) -> usize {
+ self.next * 8 - self.avail as usize
+ }
+
+ #[inline]
+ pub fn overrun(&self) -> bool {
+ self.consumed() > self.data.len() * 8
+ }
+
+ /// Read `n` ≤ 32 bits.
+ #[inline(always)]
+ pub fn read(&mut self, n: u32) -> u32 {
+ if n == 0 {
+ return 0;
+ }
+ self.refill();
+ let v = (self.cache >> (64 - n)) as u32;
+ self.consume(n);
+ v
+ }
+
+ /// Decode one VLC symbol (value bits of the LUT entry).
+ #[inline(always)]
+ pub fn vlc(&mut self, t: &Lut) -> u32 {
+ self.refill();
+ let w = self.cache;
+ let mut e = t.primary[(w >> (64 - t.bits)) as usize];
+ if e & LINK != 0 {
+ let sb = (e >> 24) & 0x7f;
+ let off = (e & 0xff_ffff) as usize;
+ e = t.secondary[off + ((w << t.bits) >> (64 - sb)) as usize];
+ }
+ // entries are always filled for complete prefix codes
+ self.consume(e >> 16);
+ e & 0xffff
+ }
+}
+
+/// MSB-first bit writer.
+#[derive(Default)]
+pub(crate) struct Writer {
+ pub buf: Vec<u8>,
+ acc: u64,
+ n: u32,
+}
+
+impl Writer {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ #[inline(always)]
+ pub fn put(&mut self, val: u32, bits: u32) {
+ if bits == 0 {
+ return;
+ }
+ let v = (val as u64) & ((1u64 << bits) - 1);
+ self.acc = (self.acc << bits) | v;
+ self.n += bits;
+ while self.n >= 8 {
+ self.n -= 8;
+ self.buf.push((self.acc >> self.n) as u8);
+ }
+ self.acc &= (1u64 << self.n) - 1;
+ }
+
+ /// Pad with zero bits to a multiple of `align` bytes and return the bytes.
+ pub fn finish_aligned(mut self, align: usize) -> Vec<u8> {
+ if self.n > 0 {
+ let pad = 8 - self.n;
+ self.put(0, pad);
+ }
+ while !self.buf.len().is_multiple_of(align) {
+ self.buf.push(0);
+ }
+ self.buf
+ }
+}
diff --git a/crates/dnx/src/dct.rs b/crates/dnx/src/dct.rs
new file mode 100644
index 000000000..1d1603bce
--- /dev/null
+++ b/crates/dnx/src/dct.rs
@@ -0,0 +1,161 @@
+//! 8×8 orthonormal DCT-II / DCT-III (IDCT) in single precision.
+//!
+//! The reconstruction IDCT is defined as the exact real-valued 2-D inverse DCT
+//! `f(x,y) = Σ_u Σ_v C(u)C(v)/4 · F(v,u) · cos((2x+1)uπ/16) · cos((2y+1)vπ/16)`
+//! evaluated separably (rows then columns) in `f32`. For VC-3 coefficient ranges the `f32`
+//! evaluation error is below 2⁻⁸ in the 12-bit sample domain, so the rounded output equals the
+//! rounded exact IDCT except when the exact value lies within that distance of a rounding tie.
+
+use crate::tables::BASIS;
+
+/// In-place inverse DCT. `block` holds dequantised coefficients in raster order
+/// (`block[v*8 + u]`, `v` = vertical frequency) and receives samples (`block[y*8 + x]`).
+///
+/// Each 1-D pass uses the even/odd symmetry of the basis (`B[u][7-x] = ±B[u][x]` for even/odd
+/// `u`) and skips all-zero rows; DC-only blocks are filled directly.
+#[inline]
+pub(crate) fn idct8x8(block: &mut [f32; 64]) {
+ let mut t = [[0f32; 8]; 8];
+ let mut nz = [false; 8];
+ let mut dc_only = true;
+ // Horizontal pass: t[r][x] = Σ_u F[r][u] · B[u][x]
+ for r in 0..8 {
+ let c: &[f32; 8] = block[r * 8..r * 8 + 8].try_into().unwrap();
+ if c[1..].iter().all(|&v| v == 0.0) {
+ if c[0] != 0.0 {
+ t[r] = [c[0] * BASIS[0][0]; 8];
+ nz[r] = true;
+ dc_only &= r == 0;
+ }
+ continue;
+ }
+ dc_only = false;
+ nz[r] = true;
+ let mut out = [0f32; 8];
+ for x in 0..4 {
+ let e = c[0] * BASIS[0][x] + c[2] * BASIS[2][x] + c[4] * BASIS[4][x] + c[6] * BASIS[6][x];
+ let o = c[1] * BASIS[1][x] + c[3] * BASIS[3][x] + c[5] * BASIS[5][x] + c[7] * BASIS[7][x];
+ out[x] = e + o;
+ out[7 - x] = e - o;
+ }
+ t[r] = out;
+ }
+ if dc_only {
+ *block = [t[0][0] * BASIS[0][0]; 64];
+ return;
+ }
+ // Vertical pass: f[y][x] = Σ_v t[v][x] · B[v][y]
+ for y in 0..4 {
+ let mut e = [0f32; 8];
+ let mut o = [0f32; 8];
+ for v in [0, 2, 4, 6] {
+ if nz[v] {
+ let b = BASIS[v][y];
+ for x in 0..8 {
+ e[x] += t[v][x] * b;
+ }
+ }
+ }
+ for v in [1, 3, 5, 7] {
+ if nz[v] {
+ let b = BASIS[v][y];
+ for x in 0..8 {
+ o[x] += t[v][x] * b;
+ }
+ }
+ }
+ for x in 0..8 {
+ block[y * 8 + x] = e[x] + o[x];
+ block[(7 - y) * 8 + x] = e[x] - o[x];
+ }
+ }
+}
+
+/// In-place forward DCT (samples in, coefficients out; same layout as [`idct8x8`]).
+pub(crate) fn fdct8x8(block: &mut [f32; 64]) {
+ let mut t = [[0f32; 8]; 8];
+ // Horizontal: t[y][u] = Σ_x f[y][x] · B[u][x]
+ for y in 0..8 {
+ for u in 0..8 {
+ let mut s = 0f32;
+ for x in 0..8 {
+ s += block[y * 8 + x] * BASIS[u][x];
+ }
+ t[y][u] = s;
+ }
+ }
+ // Vertical: F[v][u] = Σ_y t[y][u] · B[v][y]
+ for v in 0..8 {
+ let mut acc = [0f32; 8];
+ for y in 0..8 {
+ let b = BASIS[v][y];
+ for u in 0..8 {
+ acc[u] += t[y][u] * b;
+ }
+ }
+ block[v * 8..v * 8 + 8].copy_from_slice(&acc);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn reference_idct(c: &[f32; 64]) -> [f64; 64] {
+ let mut out = [0f64; 64];
+ for y in 0..8 {
+ for x in 0..8 {
+ let mut s = 0f64;
+ for v in 0..8 {
+ for u in 0..8 {
+ let cu = if u == 0 { std::f64::consts::FRAC_1_SQRT_2 } else { 1.0 };
+ let cv = if v == 0 { std::f64::consts::FRAC_1_SQRT_2 } else { 1.0 };
+ s += cu * cv / 4.0
+ * c[v * 8 + u] as f64
+ * (((2 * x + 1) * u) as f64 * std::f64::consts::PI / 16.0).cos()
+ * (((2 * y + 1) * v) as f64 * std::f64::consts::PI / 16.0).cos();
+ }
+ }
+ out[y * 8 + x] = s;
+ }
+ }
+ out
+ }
+
+ #[test]
+ fn idct_matches_double_reference() {
+ let mut seed = 12345u32;
+ let mut rnd = || {
+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ seed >> 8
+ };
+ for _ in 0..200 {
+ let mut c = [0f32; 64];
+ for v in c.iter_mut() {
+ if rnd() % 3 == 0 {
+ *v = ((rnd() % 8192) as i32 - 4096) as f32;
+ }
+ }
+ let r = reference_idct(&c);
+ let mut b = c;
+ idct8x8(&mut b);
+ for i in 0..64 {
+ assert!((b[i] as f64 - r[i]).abs() < 4e-3, "{} vs {}", b[i], r[i]);
+ }
+ }
+ }
+
+ #[test]
+ fn fdct_inverts_idct() {
+ let mut b = [0f32; 64];
+ for (i, v) in b.iter_mut().enumerate() {
+ *v = ((i * 37) % 200) as f32 - 100.0;
+ }
+ let orig = b;
+ fdct8x8(&mut b);
+ idct8x8(&mut b);
+ for i in 0..64 {
+ assert!((b[i] - orig[i]).abs() < 1e-3);
+ }
+ }
+}
diff --git a/crates/dnx/src/decode.rs b/crates/dnx/src/decode.rs
new file mode 100644
index 000000000..22f9f542b
--- /dev/null
+++ b/crates/dnx/src/decode.rs
@@ -0,0 +1,496 @@
+//! VC-3 decoding (SMPTE ST 2019-1 §8).
+
+use crate::bits::Reader;
+use crate::dct::idct8x8;
+use crate::header::{self, FieldCode, FrameHeader, SCAN_INDEX_OFFSET};
+use crate::tables::{AMP_EOB, AMP_FINDEX, AMP_FRUN, CidInfo, VlcSet, ZIGZAG, cid_info, vlc};
+use crate::{ChromaFormat, Error, Frame, Interlace, Result};
+
+/// Decoder options.
+#[derive(Debug, Clone, Copy)]
+pub struct DecodeOptions {
+ /// Decode macroblock scan lines in parallel (needs the `threads` feature).
+ pub threads: bool,
+ /// Use the standard's integer inverse quantisation (equation 8.1) instead of the
+ /// ffmpeg-compatible reconstruction (default false; see the README).
+ pub spec_dequant: bool,
+}
+
+impl Default for DecodeOptions {
+ fn default() -> Self {
+ DecodeOptions { threads: true, spec_dequant: false }
+ }
+}
+
+/// Parse the header of the first coding unit of a frame.
+pub fn probe(data: &[u8]) -> Result<FrameHeader> {
+ header::parse(data)
+}
+
+/// Decode one compressed frame (one or two coding units).
+pub fn decode_frame(data: &[u8]) -> Result<Frame> {
+ decode_frame_with(data, &DecodeOptions::default())
+}
+
+/// Decode one compressed frame with options.
+pub fn decode_frame_with(data: &[u8], opts: &DecodeOptions) -> Result<Frame> {
+ let h1 = header::parse(data)?;
+ let field_coded = h1.interlaced && !h1.frame_encoding;
+ if !field_coded {
+ let planes = decode_unit(&h1, data, opts)?;
+ let mut f = Frame::new_like(&h1, h1.width, h1.lines);
+ f.interlace = if h1.interlaced { Interlace::TopFieldFirst } else { Interlace::Progressive };
+ planes.copy_into(&mut f, 0, 1);
+ return Ok(f);
+ }
+ // field encoding: two coding units, field 1 (top) then field 2
+ let off = second_unit_offset(&h1, data)?;
+ let h2 = header::parse(&data[off..])?;
+ if h2.cid != h1.cid || h2.width != h1.width || h2.lines != h1.lines || h2.chroma != h1.chroma || h2.alpha != h1.alpha {
+ return Err(Error::Invalid("field coding units differ"));
+ }
+ let (p1, p2) = if opts.threads {
+ join(|| decode_unit(&h1, &data[..off], opts), || decode_unit(&h2, &data[off..], opts))
+ } else {
+ (decode_unit(&h1, &data[..off], opts), decode_unit(&h2, &data[off..], opts))
+ };
+ let mut f = Frame::new_like(&h1, h1.width, h1.lines * 2);
+ f.interlace = Interlace::TopFieldFirst;
+ let (top, bottom) = if h1.field == FieldCode::Field2 { (p2?, p1?) } else { (p1?, p2?) };
+ top.copy_into(&mut f, 0, 2);
+ bottom.copy_into(&mut f, 1, 2);
+ Ok(f)
+}
+
+#[cfg(feature = "threads")]
+fn join<A: Send, B: Send>(a: impl FnOnce() -> A + Send, b: impl FnOnce() -> B + Send) -> (A, B) {
+ rayon::join(a, b)
+}
+
+#[cfg(not(feature = "threads"))]
+fn join<A, B>(a: impl FnOnce() -> A, b: impl FnOnce() -> B) -> (A, B) {
+ (a(), b())
+}
+
+/// Byte offset of the second coding unit of a field-coded frame.
+fn second_unit_offset(h: &FrameHeader, data: &[u8]) -> Result<usize> {
+ if let Some(sz) = h.coding_unit_size() {
+ let sz = sz as usize;
+ if data.len() >= sz + 0x280 && data[sz..sz + 4] == data[0..4] && data[sz + 4] == data[4] {
+ return Ok(sz);
+ }
+ }
+ // VBR (or unexpected size): find the next header prefix after the first unit's scan lines
+ let prefix = &data[0..5];
+ let start = h.header_size as usize;
+ data[start..]
+ .windows(5)
+ .position(|w| w == prefix)
+ .map(|p| p + start)
+ .filter(|&p| header::parse(&data[p..]).is_ok())
+ .ok_or(Error::Invalid("second field coding unit not found"))
+}
+
+/// Decoded planes of one coding unit at the coded (macroblock-aligned) size.
+struct CodedPlanes {
+ /// Y / Cb / Cr / A (or R / G / B / A).
+ planes: [Vec<u16>; 4],
+ strides: [usize; 4],
+ /// An RGB-signalled stream whose macroblocks are all coded as Y'CbCr.
+ ycbcr: bool,
+}
+
+impl CodedPlanes {
+ /// Crop into `f`, writing coded line `i` to frame line `first + i·step`.
+ fn copy_into(&self, f: &mut Frame, first: usize, step: usize) {
+ if self.ycbcr {
+ f.rgb = false;
+ }
+ let cw = f.chroma_width() as usize;
+ let w = f.width as usize;
+ let ch = f.chroma_height() as usize;
+ let h = f.height as usize;
+ let cfirst = first;
+ let mut targets: Vec<(&mut Vec<u16>, usize, usize, usize, usize)> =
+ vec![(&mut f.y, w, h, first, 0), (&mut f.cb, cw, ch, cfirst, 1), (&mut f.cr, cw, ch, cfirst, 2)];
+ if let Some(a) = f.alpha.as_mut() {
+ targets.push((a, w, h, first, 3));
+ }
+ for (dst, pw, ph, first, pi) in targets {
+ let src = &self.planes[pi];
+ let ss = self.strides[pi];
+ let mut line = 0;
+ let mut y = first;
+ while y < ph {
+ let s = &src[line * ss..line * ss + pw];
+ dst[y * pw..y * pw + pw].copy_from_slice(s);
+ line += 1;
+ y += step;
+ }
+ }
+ }
+}
+
+/// Block layout entry: plane, x offset and y offset (0 or 8) inside the macroblock.
+type BlockPos = (u8, u8, u8);
+
+const LAYOUT_422: [BlockPos; 8] = [(0, 0, 0), (0, 8, 0), (1, 0, 0), (2, 0, 0), (0, 0, 8), (0, 8, 8), (1, 0, 8), (2, 0, 8)];
+const LAYOUT_420: [BlockPos; 6] = [(0, 0, 0), (0, 8, 0), (1, 0, 0), (2, 0, 0), (0, 0, 8), (0, 8, 8)];
+const LAYOUT_444: [BlockPos; 12] =
+ [(0, 0, 0), (0, 8, 0), (1, 0, 0), (1, 8, 0), (2, 0, 0), (2, 8, 0), (0, 0, 8), (0, 8, 8), (1, 0, 8), (1, 8, 8), (2, 0, 8), (2, 8, 8)];
+const LAYOUT_ALPHA: [BlockPos; 4] = [(3, 0, 0), (3, 8, 0), (3, 0, 8), (3, 8, 8)];
+
+/// Per-coding-unit decoding context.
+struct Ctx<'a> {
+ h: &'a FrameHeader,
+ info: &'static CidInfo,
+ vlc: &'static VlcSet,
+ nw: usize,
+ layout: &'static [BlockPos],
+ /// Plane macroblock sizes (width, height) for Y/Cb/Cr/A.
+ mb_size: [(usize, usize); 4],
+ strides: [usize; 4],
+ p_bits: u32,
+ p_shift: u32,
+ p_half: u32,
+ spec_dequant: bool,
+ /// `1 / (4p)`
+ inv_4p: f32,
+ /// IDCT output scale (4 at 12 bits, see README) and level offset.
+ scale: f32,
+ mid: f32,
+ max: f32,
+}
+
+fn decode_unit(h: &FrameHeader, data: &[u8], opts: &DecodeOptions) -> Result<CodedPlanes> {
+ let info = cid_info(h.cid).ok_or(Error::UnknownCid(h.cid))?;
+ let nw = h.mb_width() as usize;
+ let ns = h.mb_rows as usize;
+ let (layout, cmb): (&'static [BlockPos], (usize, usize)) = match h.chroma {
+ ChromaFormat::Yuv422 => (&LAYOUT_422, (8, 16)),
+ ChromaFormat::Yuv420 => (&LAYOUT_420, (8, 8)),
+ ChromaFormat::Yuv444 => (&LAYOUT_444, (16, 16)),
+ };
+ let mb_size = [(16, 16), cmb, cmb, (16, 16)];
+ let strides = [nw * 16, nw * cmb.0, nw * cmb.0, nw * 16];
+ let ctx = Ctx {
+ h,
+ info,
+ vlc: vlc(info.vlc),
+ nw,
+ layout,
+ mb_size,
+ strides,
+ p_bits: if h.bit_depth == 8 { 4 } else { 6 },
+ p_shift: info.p.trailing_zeros(),
+ p_half: info.p / 2,
+ spec_dequant: opts.spec_dequant,
+ inv_4p: 1.0 / (4 * info.p) as f32,
+ scale: if h.bit_depth == 12 { 4.0 } else { 1.0 },
+ mid: (1u32 << (h.bit_depth - 1)) as f32,
+ max: ((1u32 << h.bit_depth) - 1) as f32,
+ };
+ // scan line byte ranges
+ let hs = h.header_size as usize;
+ let mut starts = Vec::with_capacity(ns);
+ for s in 0..ns {
+ let o = SCAN_INDEX_OFFSET + 4 * s;
+ let idx = u32::from_be_bytes([data[o], data[o + 1], data[o + 2], data[o + 3]]) as usize;
+ let st = hs.checked_add(idx).filter(|&v| v < data.len()).ok_or(Error::Truncated)?;
+ starts.push(st);
+ }
+ let ranges: Vec<(usize, usize)> = (0..ns)
+ .map(|s| {
+ let st = starts[s];
+ let end = starts.get(s + 1).copied().filter(|&e| e > st).unwrap_or(data.len());
+ (st, end)
+ })
+ .collect();
+
+ let alpha = h.alpha;
+ let mut planes: [Vec<u16>; 4] = [
+ vec![0; strides[0] * 16 * ns],
+ vec![0; strides[1] * cmb.1 * ns],
+ vec![0; strides[2] * cmb.1 * ns],
+ if alpha { vec![0; strides[3] * 16 * ns] } else { Vec::new() },
+ ];
+ let [py, pcb, pcr, pa] = &mut planes;
+ let band = [strides[0] * 16, strides[1] * cmb.1, strides[2] * cmb.1, strides[3] * 16];
+ let mut alpha_bands: Vec<&mut [u16]> = if alpha { pa.chunks_mut(band[3]).collect() } else { (0..ns).map(|_| &mut [][..]).collect() };
+ let rows: Vec<(usize, &mut [u16], &mut [u16], &mut [u16], &mut [u16])> = py
+ .chunks_mut(band[0])
+ .zip(pcb.chunks_mut(band[1]))
+ .zip(pcr.chunks_mut(band[2]))
+ .zip(alpha_bands.drain(..))
+ .enumerate()
+ .map(|(i, (((y, cb), cr), a))| (i, y, cb, cr, a))
+ .collect();
+ let run = |(i, y, cb, cr, a): (usize, &mut [u16], &mut [u16], &mut [u16], &mut [u16])| -> Result<Vec<bool>> {
+ let (st, end) = ranges[i];
+ decode_row(&ctx, &data[st..end], [y, cb, cr, a]).map_err(|e| match e {
+ Error::Row(_) => Error::Row(i),
+ e => e,
+ })
+ };
+ #[cfg(feature = "threads")]
+ let acf: Vec<Vec<bool>> = if opts.threads {
+ use rayon::prelude::*;
+ rows.into_par_iter().map(run).collect::<Result<_>>()?
+ } else {
+ rows.into_iter().map(run).collect::<Result<_>>()?
+ };
+ #[cfg(not(feature = "threads"))]
+ let acf: Vec<Vec<bool>> = {
+ let _ = opts;
+ rows.into_iter().map(run).collect::<Result<_>>()?
+ };
+ // RGB streams (CLF = 1) choose RGB or Y'CbCr per macroblock (ACF). A stream whose
+ // macroblocks are all Y'CbCr is returned as Y'CbCr 4:4:4; mixed streams are converted to RGB
+ // macroblock by macroblock (ConvertMacroblockColor, 8.1.1).
+ let n_acf: usize = acf.iter().map(|r| r.iter().filter(|&&a| a).count()).sum();
+ let ycbcr = h.rgb_planes() && n_acf == nw * ns;
+ if h.rgb_planes() && n_acf > 0 && !ycbcr && h.color_volume != crate::ColorVolume::OutOfBand {
+ let [py, pcb, pcr, _] = &mut planes;
+ for (s, row) in acf.iter().enumerate() {
+ for (mb, &a) in row.iter().enumerate() {
+ if a {
+ let o = s * band[0];
+ convert_mb_to_rgb(&ctx, [&mut py[o..o + band[0]], &mut pcb[o..o + band[0]], &mut pcr[o..o + band[0]]], mb);
+ }
+ }
+ }
+ }
+ Ok(CodedPlanes { planes, strides, ycbcr })
+}
+
+/// Decode one macroblock scan line into the 16-line bands of each plane.
+fn decode_row(ctx: &Ctx, data: &[u8], bands: [&mut [u16]; 4]) -> Result<Vec<bool>> {
+ let h = ctx.h;
+ let mut r = Reader::new(data);
+ // DC predictors: Y/Ch1, Cb, Cr, R, G, B, A
+ let mut pred = [0i32; 7];
+ let rgb = h.rgb_planes();
+ let mff_cid = ctx.info.cid == 1260;
+ let mut block = [0f32; 64];
+ let mut acfs = Vec::new();
+ for mb in 0..ctx.nw {
+ let (qsf, flag, mff) = if mff_cid {
+ let mff = r.read(1) == 1;
+ (r.read(10), r.read(1) == 1, mff)
+ } else {
+ (r.read(11), r.read(1) == 1, false)
+ };
+ let acf = rgb && flag;
+ let wq = scaled_weights(ctx.info.weights, qsf);
+ for &(plane, xo, yo) in ctx.layout {
+ let comp = plane as usize;
+ let slot = if rgb && !acf { 3 + comp } else { comp };
+ let w = &wq[(comp != 0) as usize];
+ decode_block(ctx, &mut r, &mut pred[slot], w, &mut block)?;
+ store(ctx, bands[comp], comp, mb, xo as usize, yo as usize, mff, &mut block);
+ }
+ if rgb {
+ acfs.push(acf);
+ }
+ if r.overrun() {
+ return Err(Error::Row(0));
+ }
+ }
+ if h.alpha {
+ if h.lossless_alpha {
+ for mb in 0..ctx.nw {
+ decode_rle_alpha(ctx, &mut r, bands[3], mb)?;
+ }
+ } else {
+ for mb in 0..ctx.nw {
+ let qsf = if mff_cid {
+ r.read(1);
+ let q = r.read(10);
+ r.read(1);
+ q
+ } else {
+ let q = r.read(11);
+ r.read(1);
+ q
+ };
+ let wq = scaled_weights(ctx.info.weights, qsf);
+ for &(plane, xo, yo) in &LAYOUT_ALPHA {
+ decode_block(ctx, &mut r, &mut pred[6], &wq[0], &mut block)?;
+ store(ctx, bands[3], plane as usize, mb, xo as usize, yo as usize, false, &mut block);
+ }
+ }
+ }
+ if r.overrun() {
+ return Err(Error::Row(0));
+ }
+ }
+ Ok(acfs)
+}
+
+/// `W(u,v)·qsf` for every AC raster position (index 0 unused), luma and chroma.
+#[inline]
+fn scaled_weights(w: &[[u8; 63]; 2], qsf: u32) -> [[(u32, u32); 64]; 2] {
+ let mut out = [[(0u32, 0u32); 64]; 2];
+ for c in 0..2 {
+ for i in 0..63 {
+ let wi = w[c][i] as u32;
+ out[c][i + 1] = (wi * qsf, wi);
+ }
+ }
+ out
+}
+
+/// Decode one DCT block into dequantised coefficients (raster order).
+#[inline]
+fn decode_block(ctx: &Ctx, r: &mut Reader, pred: &mut i32, wq: &[(u32, u32); 64], block: &mut [f32; 64]) -> Result<()> {
+ let v = ctx.vlc;
+ *block = [0.0; 64];
+ // DC (8.2.4)
+ let eta = r.vlc(&v.dc);
+ let eps = if eta == 0 {
+ 0
+ } else {
+ let rho = r.read(eta) as i32;
+ if rho >= 1 << (eta - 1) { rho } else { rho + 1 - (1 << eta) }
+ };
+ let dc = pred.wrapping_add(eps);
+ *pred = dc;
+ block[0] = dc as f32;
+ // AC (8.2.5)
+ let mut pos = 0usize;
+ loop {
+ let s = r.vlc(&v.amp);
+ if s & AMP_EOB != 0 {
+ break;
+ }
+ let neg = r.read(1) == 1;
+ let mut a = s & 0xff;
+ if s & AMP_FINDEX != 0 {
+ a += r.read(ctx.p_bits) * 64;
+ }
+ pos += 1;
+ if s & AMP_FRUN != 0 {
+ pos += r.vlc(&v.run) as usize;
+ }
+ if pos > 63 {
+ return Err(Error::Row(0));
+ }
+ let z = ZIGZAG[pos] as usize;
+ let (wqs, w) = wq[z];
+ // inverse quantisation (8.2.7)
+ // Reconstruction at (|X̂| + 3/4)·W·qsf/p, as ffmpeg's decoder does (see README); the
+ // standard's equation 8.1 rounds to an integer near (|X̂| + 1/2)·W·qsf/p.
+ let mag = if ctx.spec_dequant {
+ let add = if w != ctx.info.p { ctx.p_half } else { 0 };
+ ((a as u64 * wqs as u64 + (wqs >> 1) as u64 + add as u64) >> ctx.p_shift) as f32
+ } else {
+ ((4 * a as u64 + 3) * wqs as u64) as f32 * ctx.inv_4p
+ };
+ block[z] = if neg { -mag } else { mag };
+ }
+ Ok(())
+}
+
+/// IDCT a block and store it (with level adjustment and clipping) into a plane band.
+#[inline]
+fn store(ctx: &Ctx, band: &mut [u16], plane: usize, mb: usize, xo: usize, yo: usize, field: bool, block: &mut [f32; 64]) {
+ idct8x8(block);
+ let stride = ctx.strides[plane];
+ let x0 = mb * ctx.mb_size[plane].0 + xo;
+ let (first, step) = if field { (yo / 8, 2) } else { (yo, 1) };
+ let (scale, mid, max) = (ctx.scale, ctx.mid + 0.5, ctx.max);
+ for j in 0..8 {
+ let row = &mut band[(first + j * step) * stride + x0..][..8];
+ let src = &block[j * 8..j * 8 + 8];
+ for i in 0..8 {
+ row[i] = (src[i] * scale + mid).floor().clamp(0.0, max) as u16;
+ }
+ }
+}
+
+/// `ConvertMacroblockColor` (8.1.1): BT.709 Y′CbCr → R′G′B′ on the quantised (video-range)
+/// signals, in place over the macroblock's three planes.
+fn convert_mb_to_rgb(ctx: &Ctx, bands: [&mut [u16]; 3], mb: usize) {
+ let stride = ctx.strides[0];
+ let s = (1u32 << (ctx.h.bit_depth - 8)) as f32;
+ let (kr, kb) = match ctx.h.color_volume {
+ crate::ColorVolume::Bt709 => (0.2126f32, 0.0722f32),
+ _ => (0.2627, 0.0593),
+ };
+ let kg = 1.0 - kr - kb;
+ let c = 219.0 / 224.0;
+ for y in 0..16 {
+ for x in 0..16 {
+ let i = y * stride + mb * 16 + x;
+ let yy = bands[0][i] as f32;
+ let cb = bands[1][i] as f32 - 128.0 * s;
+ let cr = bands[2][i] as f32 - 128.0 * s;
+ let r = yy + 2.0 * (1.0 - kr) * c * cr;
+ let b = yy + 2.0 * (1.0 - kb) * c * cb;
+ let g = (yy - kr * r - kb * b) / kg;
+ // RGB planes are stored in coded channel order G, B, R
+ bands[0][i] = (g + 0.5).floor().clamp(0.0, ctx.max) as u16;
+ bands[1][i] = (b + 0.5).floor().clamp(0.0, ctx.max) as u16;
+ bands[2][i] = (r + 0.5).floor().clamp(0.0, ctx.max) as u16;
+ }
+ }
+}
+
+/// Lossless (differential RLE) alpha macroblock (§7.3.1.2, §8.3).
+fn decode_rle_alpha(ctx: &Ctx, r: &mut Reader, band: &mut [u16], mb: usize) -> Result<()> {
+ let d = ctx.h.bit_depth as u32;
+ let mask = (1u32 << d) - 1;
+ let stride = ctx.strides[3];
+ let pos = |count: usize| {
+ let y = count / 16;
+ let x = if y.is_multiple_of(2) { count % 16 } else { 15 - count % 16 };
+ y * stride + mb * 16 + x
+ };
+ // RL = 1: RLE coded; RL = 0: 256 raw samples (§7.3.1.2 prose; see README)
+ let rl = r.read(4) & 1;
+ if rl == 0 {
+ for count in 0..256 {
+ band[pos(count)] = r.read(d) as u16;
+ }
+ return Ok(());
+ }
+ let rice = d / 2 - 2;
+ let (mut d1, mut d2) = (mask >> 1, mask >> 1);
+ let mut count = 0usize;
+ while count < 256 {
+ let p = r.read(1);
+ // Elias gamma
+ let mut n = 0;
+ while r.read(1) == 0 {
+ n += 1;
+ if n > 8 || r.overrun() {
+ return Err(Error::Row(0));
+ }
+ }
+ let nrl = (1usize << n) + r.read(n) as usize;
+ let dcw = if r.read(1) == 1 {
+ let mut q = 0u32;
+ while r.read(1) == 1 {
+ q += 1;
+ if q > 1 << d || r.overrun() {
+ return Err(Error::Row(0));
+ }
+ }
+ (q << rice) + r.read(rice)
+ } else {
+ r.read(d)
+ };
+ let diff = if dcw & 1 == 1 { mask.wrapping_sub(dcw >> 1) } else { dcw >> 1 };
+ if count + nrl > 256 {
+ return Err(Error::Row(0));
+ }
+ for _ in 0..nrl {
+ let v = if p == 1 { (2 * d1).wrapping_sub(d2).wrapping_add(diff) & mask } else { d1.wrapping_add(diff) & mask };
+ band[pos(count)] = v as u16;
+ d2 = d1;
+ d1 = v;
+ count += 1;
+ }
+ }
+ Ok(())
+}
diff --git a/crates/dnx/src/encode.rs b/crates/dnx/src/encode.rs
new file mode 100644
index 000000000..4c5dbf58a
--- /dev/null
+++ b/crates/dnx/src/encode.rs
@@ -0,0 +1,437 @@
+//! DNxHR encoder (RI profile, CBR, progressive).
+//!
+//! Every macroblock is transformed once (orthonormal 8×8 FDCT). Quantisation follows equation
+//! 8.2 exactly (`X̂ = ⌊p·|X| / (qsf·W)⌋`, which the decoder reconstructs at the interval
+//! midpoint). Rate control: a binary search finds the smallest uniform quantisation scale factor
+//! whose frame fits the CBR payload, then macroblocks get one finer step in scan order while the
+//! budget allows.
+
+use crate::bits::Writer;
+use crate::dct::fdct8x8;
+use crate::header::{self, EOF_SIGNATURE, FieldCode, FrameHeader, SCAN_INDEX_OFFSET};
+use crate::tables::{CidInfo, VlcSet, ZIGZAG, cid_info, vlc};
+use crate::{ChromaFormat, ColorVolume, Error, Frame, Profile, Result};
+
+/// Encoder configuration.
+#[derive(Debug, Clone)]
+pub struct EncoderConfig {
+ pub profile: Profile,
+ pub width: u32,
+ pub height: u32,
+ /// Coded sample depth: 8 for LB/SQ/HQ; 10 or 12 for HQX and 444.
+ pub bit_depth: u8,
+ pub color_volume: ColorVolume,
+ /// Pixel aspect ratio to signal (0/0 = not signalled).
+ pub par: (u16, u16),
+}
+
+impl EncoderConfig {
+ pub fn new(profile: Profile, width: u32, height: u32) -> EncoderConfig {
+ let bit_depth = match profile {
+ Profile::Hqx | Profile::R444 => 10,
+ _ => 8,
+ };
+ EncoderConfig { profile, width, height, bit_depth, color_volume: ColorVolume::Bt709, par: (0, 0) }
+ }
+
+ pub fn chroma(&self) -> ChromaFormat {
+ if self.profile == Profile::R444 { ChromaFormat::Yuv444 } else { ChromaFormat::Yuv422 }
+ }
+}
+
+/// DNxHR encoder.
+pub struct Encoder {
+ cfg: EncoderConfig,
+ info: &'static CidInfo,
+ frame_size: u32,
+ header_size: u32,
+ last_q: u32,
+}
+
+/// Transformed macroblock data: per block, the DC value and the AC magnitudes pre-divided by
+/// the weights (`p·|X|/W`, sign in the float's sign) in bitstream (zig-zag) order.
+struct Prepared {
+ nw: usize,
+ ns: usize,
+ nblk: usize,
+ /// `[mb * nblk + k][r]`; `[..][0]` is the DC value.
+ t: Vec<[f32; 64]>,
+ /// DC bits of each macroblock (independent of the quantiser).
+ dc_bits: Vec<u32>,
+}
+
+impl Encoder {
+ pub fn new(profile: Profile, width: u32, height: u32) -> Encoder {
+ Encoder::with_config(EncoderConfig::new(profile, width, height)).expect("valid default configuration")
+ }
+
+ pub fn with_config(cfg: EncoderConfig) -> Result<Encoder> {
+ if cfg.width == 0 || cfg.height == 0 || cfg.width > 16384 || cfg.height > 16384 {
+ return Err(Error::Input(format!("unsupported raster {}x{}", cfg.width, cfg.height)));
+ }
+ if cfg.chroma() == ChromaFormat::Yuv422 && !cfg.width.is_multiple_of(2) {
+ return Err(Error::Input("4:2:2 needs an even width".into()));
+ }
+ let ok_depth = match cfg.profile {
+ Profile::Hqx | Profile::R444 => matches!(cfg.bit_depth, 10 | 12),
+ _ => cfg.bit_depth == 8,
+ };
+ if !ok_depth {
+ return Err(Error::Input(format!("{} does not support {}-bit", cfg.profile.name(), cfg.bit_depth)));
+ }
+ let info = cid_info(cfg.profile.cid()).expect("RI CID");
+ let frame_size = cfg.profile.frame_size(cfg.width, cfg.height);
+ let header_size = header::header_size_for(cfg.height);
+ Ok(Encoder { cfg, info, frame_size, header_size, last_q: 8 })
+ }
+
+ pub fn config(&self) -> &EncoderConfig {
+ &self.cfg
+ }
+
+ /// Size of every encoded frame in bytes (CBR).
+ pub fn frame_size(&self) -> u32 {
+ self.frame_size
+ }
+
+ /// Encode one frame. Its geometry and chroma format must match the configuration; samples
+ /// at another depth are rescaled to the coded depth.
+ pub fn encode(&mut self, f: &Frame) -> Result<Vec<u8>> {
+ let cfg = &self.cfg;
+ if f.width != cfg.width || f.height != cfg.height {
+ return Err(Error::Input(format!("frame is {}x{}, encoder is {}x{}", f.width, f.height, cfg.width, cfg.height)));
+ }
+ if f.chroma != cfg.chroma() {
+ return Err(Error::Input(format!("{:?} input for {}", f.chroma, cfg.profile.name())));
+ }
+ if !(8..=16).contains(&f.bit_depth) {
+ return Err(Error::Input(format!("unsupported input depth {}", f.bit_depth)));
+ }
+ let n = f.width as usize * f.height as usize;
+ let cn = f.chroma_width() as usize * f.chroma_height() as usize;
+ if f.y.len() != n || f.cb.len() != cn || f.cr.len() != cn {
+ return Err(Error::Input("plane sizes do not match the frame geometry".into()));
+ }
+ let prep = self.prepare(f);
+ let vlc = vlc(self.info.vlc);
+ let budget_bits = (self.frame_size as u64 - self.header_size as u64 - 4) * 8;
+ let q = self.rate_control(&prep, vlc, budget_bits);
+ self.write(&prep, vlc, &q, f.rgb)
+ }
+
+ fn mb_layout(&self) -> &'static [(u8, u8, u8)] {
+ match self.cfg.chroma() {
+ ChromaFormat::Yuv444 => {
+ &[(0, 0, 0), (0, 8, 0), (1, 0, 0), (1, 8, 0), (2, 0, 0), (2, 8, 0), (0, 0, 8), (0, 8, 8), (1, 0, 8), (1, 8, 8), (2, 0, 8), (2, 8, 8)]
+ }
+ _ => &[(0, 0, 0), (0, 8, 0), (1, 0, 0), (2, 0, 0), (0, 0, 8), (0, 8, 8), (1, 0, 8), (2, 0, 8)],
+ }
+ }
+
+ fn prepare(&self, f: &Frame) -> Prepared {
+ let cfg = &self.cfg;
+ let nw = cfg.width.div_ceil(16) as usize;
+ let ns = cfg.height.div_ceil(16) as usize;
+ let layout = self.mb_layout();
+ let nblk = layout.len();
+ let depth = cfg.bit_depth as i32;
+ let shift = depth - f.bit_depth as i32;
+ let mid = (1i32 << (depth - 1)) as f32;
+ let inv_scale = if depth == 12 { 0.25f32 } else { 1.0 };
+ let p = self.info.p as f32;
+ let w = self.info.weights;
+ let cmbw = if cfg.chroma() == ChromaFormat::Yuv444 { 16 } else { 8 };
+ let planes: [(&[u16], usize, usize, usize); 3] = [
+ (&f.y, f.width as usize, f.height as usize, 16),
+ (&f.cb, f.chroma_width() as usize, f.chroma_height() as usize, cmbw),
+ (&f.cr, f.chroma_width() as usize, f.chroma_height() as usize, cmbw),
+ ];
+ let sample = |pl: usize, x: usize, y: usize| -> f32 {
+ let (d, pw, ph, _) = planes[pl];
+ let v = d[y.min(ph - 1) * pw + x.min(pw - 1)] as i32;
+ let v = if shift >= 0 { v << shift } else { (v + (1 << (-shift - 1))) >> -shift };
+ v.min((1 << depth) - 1) as f32 - mid
+ };
+ let do_row = |s: usize| -> Vec<[f32; 64]> {
+ let mut out = Vec::with_capacity(nw * nblk);
+ for mb in 0..nw {
+ for &(pl, xo, yo) in layout {
+ let pl = pl as usize;
+ let x0 = mb * planes[pl].3 + xo as usize;
+ let y0 = s * 16 + yo as usize;
+ let mut b = [0f32; 64];
+ for j in 0..8 {
+ for i in 0..8 {
+ b[j * 8 + i] = sample(pl, x0 + i, y0 + j);
+ }
+ }
+ fdct8x8(&mut b);
+ let wt = &w[(pl != 0) as usize];
+ let mut t = [0f32; 64];
+ let dc_max = if depth == 8 { 1023.0 } else { 4095.0 };
+ t[0] = (b[0] * inv_scale).round().clamp(-dc_max - 1.0, dc_max);
+ for r in 1..64 {
+ let z = ZIGZAG[r] as usize;
+ t[r] = b[z] * inv_scale * p / wt[z - 1] as f32;
+ }
+ out.push(t);
+ }
+ }
+ out
+ };
+ #[cfg(feature = "threads")]
+ let rows: Vec<Vec<[f32; 64]>> = {
+ use rayon::prelude::*;
+ (0..ns).into_par_iter().map(do_row).collect()
+ };
+ #[cfg(not(feature = "threads"))]
+ let rows: Vec<Vec<[f32; 64]>> = (0..ns).map(do_row).collect();
+ let t: Vec<[f32; 64]> = rows.into_iter().flatten().collect();
+ // DC bits with per-row, per-component prediction
+ let v = vlc(self.info.vlc);
+ let mut dc_bits = vec![0u32; nw * ns];
+ for s in 0..ns {
+ let mut pred = [0i32; 3];
+ for mb in 0..nw {
+ let mut bits = 0;
+ for (k, &(pl, _, _)) in layout.iter().enumerate() {
+ let dc = t[(s * nw + mb) * nblk + k][0] as i32;
+ let e = dc - pred[pl as usize];
+ pred[pl as usize] = dc;
+ let eta = dc_eta(e);
+ bits += v.dc_code[eta as usize].1 as u32 + eta;
+ }
+ dc_bits[s * nw + mb] = bits;
+ }
+ }
+ Prepared { nw, ns, nblk, t, dc_bits }
+ }
+
+ /// Per-macroblock qsf values whose coded frame fits `budget_bits`.
+ fn rate_control(&mut self, prep: &Prepared, vlc: &VlcSet, budget_bits: u64) -> Vec<u32> {
+ let p_bits = if self.cfg.bit_depth == 8 { 4 } else { 6 };
+ let max_amp = if p_bits == 4 { 1024 } else { 4096 };
+ let nmb = prep.nw * prep.ns;
+ let mb_bits = |mb: usize, q: u32| -> u32 {
+ let mut bits = 12 + prep.dc_bits[mb];
+ for k in 0..prep.nblk {
+ bits += ac_bits(&prep.t[mb * prep.nblk + k], q as f32, vlc, p_bits, max_amp);
+ }
+ bits
+ };
+ let frame_bits = |q: u32| -> u64 {
+ let row = |s: usize| -> u64 { row_bytes((0..prep.nw).map(|m| mb_bits(s * prep.nw + m, q) as u64).sum()) * 8 };
+ #[cfg(feature = "threads")]
+ {
+ use rayon::prelude::*;
+ (0..prep.ns).into_par_iter().map(row).sum()
+ }
+ #[cfg(not(feature = "threads"))]
+ {
+ (0..prep.ns).map(row).sum()
+ }
+ };
+ // smallest feasible uniform q (bits are non-increasing in q)
+ let (mut lo, mut hi) = (1u32, 2047u32);
+ if frame_bits(1) <= budget_bits {
+ hi = 1;
+ } else {
+ // bracket around the previous frame's choice first
+ let g = self.last_q.clamp(2, 2047);
+ if frame_bits(g) <= budget_bits {
+ hi = g;
+ let g2 = (g / 2).max(1);
+ if g2 > 1 && frame_bits(g2) > budget_bits {
+ lo = g2;
+ }
+ } else {
+ lo = g;
+ }
+ while hi - lo > 1 {
+ let m = (lo + hi) / 2;
+ if frame_bits(m) <= budget_bits { hi = m } else { lo = m }
+ }
+ }
+ let q = hi;
+ self.last_q = q;
+ let mut qs = vec![q; nmb];
+ if q > 1 {
+ // refine: one finer step per macroblock while the budget allows
+ let mut row_bits: Vec<u64> = (0..prep.ns).map(|s| (0..prep.nw).map(|m| mb_bits(s * prep.nw + m, q) as u64).sum()).collect();
+ let mut total: u64 = row_bits.iter().map(|&b| row_bytes(b) * 8).sum();
+ let cur: Vec<u32> = (0..nmb).map(|mb| mb_bits(mb, q)).collect();
+ let finer: Vec<u32> = (0..nmb).map(|mb| mb_bits(mb, q - 1)).collect();
+ // spread the refinement evenly over the frame: visit macroblocks in a strided order
+ let stride = 7919usize;
+ let mut idx = 0usize;
+ for _ in 0..nmb {
+ idx = (idx + stride) % nmb;
+ let s = idx / prep.nw;
+ let extra = finer[idx] as u64 - cur[idx].min(finer[idx]) as u64;
+ let nb = row_bits[s] + extra;
+ let nt = total - row_bytes(row_bits[s]) * 8 + row_bytes(nb) * 8;
+ if nt <= budget_bits {
+ row_bits[s] = nb;
+ total = nt;
+ qs[idx] = q - 1;
+ }
+ }
+ }
+ qs
+ }
+
+ fn write(&self, prep: &Prepared, vlc: &VlcSet, qs: &[u32], rgb: bool) -> Result<Vec<u8>> {
+ let cfg = &self.cfg;
+ let p_bits = if cfg.bit_depth == 8 { 4 } else { 6 };
+ let max_amp = if p_bits == 4 { 1024 } else { 4096 };
+ let layout = self.mb_layout();
+ // 4:4:4 signalling as ffmpeg writes and reads it (see `FrameHeader::rgb_planes`): RGB is
+ // CLF = 0 with ACF = 0; Y'CbCr is CLF = 1 with ACF = 1 on every macroblock.
+ let ycbcr444 = cfg.chroma() == ChromaFormat::Yuv444 && !rgb;
+ let write_row = |s: usize| -> Vec<u8> {
+ let mut w = Writer::new();
+ let mut pred = [0i32; 3];
+ for mb in 0..prep.nw {
+ let m = s * prep.nw + mb;
+ let q = qs[m];
+ w.put(q, 11);
+ w.put(ycbcr444 as u32, 1);
+ for (k, &(pl, _, _)) in layout.iter().enumerate() {
+ let t = &prep.t[m * prep.nblk + k];
+ let dc = t[0] as i32;
+ let e = dc - pred[pl as usize];
+ pred[pl as usize] = dc;
+ let eta = dc_eta(e);
+ let (c, l) = vlc.dc_code[eta as usize];
+ w.put(c as u32, l as u32);
+ if eta > 0 {
+ let rho = if e > 0 { e } else { e + (1 << eta) - 1 };
+ w.put(rho as u32, eta);
+ }
+ write_ac(&mut w, t, q as f32, vlc, p_bits, max_amp);
+ }
+ }
+ w.finish_aligned(4)
+ };
+ #[cfg(feature = "threads")]
+ let rows: Vec<Vec<u8>> = {
+ use rayon::prelude::*;
+ (0..prep.ns).into_par_iter().map(write_row).collect()
+ };
+ #[cfg(not(feature = "threads"))]
+ let rows: Vec<Vec<u8>> = (0..prep.ns).map(write_row).collect();
+
+ let h = FrameHeader {
+ header_size: self.header_size,
+ version: 3,
+ cid: self.info.cid,
+ vbr: false,
+ field: FieldCode::Frame,
+ macf: false,
+ crc: false,
+ alpha: false,
+ lossless_alpha: false,
+ premultiplied_alpha: false,
+ width: cfg.width,
+ lines: cfg.height,
+ par: cfg.par,
+ bit_depth: cfg.bit_depth,
+ interlaced: false,
+ frame_encoding: true,
+ chroma: cfg.chroma(),
+ rgb: ycbcr444,
+ color_volume: cfg.color_volume,
+ timecode: None,
+ mb_rows: prep.ns as u32,
+ };
+ let mut out = header::write(&h);
+ out.reserve(self.frame_size as usize - out.len());
+ let mut off = 0u32;
+ for (s, r) in rows.iter().enumerate() {
+ let o = SCAN_INDEX_OFFSET + 4 * s;
+ out[o..o + 4].copy_from_slice(&off.to_be_bytes());
+ off += r.len() as u32;
+ }
+ for r in rows {
+ out.extend_from_slice(&r);
+ }
+ let end = self.frame_size as usize - 4;
+ if out.len() > end {
+ return Err(Error::Input("rate control overflow".into()));
+ }
+ out.resize(end, 0);
+ out.extend_from_slice(&EOF_SIGNATURE);
+ Ok(out)
+ }
+}
+
+#[inline]
+fn row_bytes(bits: u64) -> u64 {
+ bits.div_ceil(32) * 4
+}
+
+#[inline]
+fn dc_eta(e: i32) -> u32 {
+ if e == 0 { 0 } else { 32 - e.unsigned_abs().leading_zeros() }
+}
+
+/// Quantised amplitude (≥ 1) of a pre-divided magnitude `|t| ≥ q`: the nearest reconstruction
+/// level for decoders that reconstruct at `(A + 3/4)·step` (ffmpeg and ours by default).
+#[inline(always)]
+fn quant(t: f32, q: f32, max_amp: u32) -> u32 {
+ ((t.abs() / q - 0.25) as u32).clamp(1, max_amp)
+}
+
+/// Bits of a block's AC coefficients plus EOB at quantiser `q`.
+#[inline]
+fn ac_bits(t: &[f32; 64], q: f32, v: &VlcSet, p_bits: u32, max_amp: u32) -> u32 {
+ let mut bits = v.eob.1 as u32;
+ let mut run = 0usize;
+ for &x in &t[1..] {
+ if x.abs() < q {
+ run += 1;
+ continue;
+ }
+ let a = quant(x, q, max_amp);
+ let p = (a - 1) >> 6;
+ let base = ((a - 1) & 63) as usize;
+ let frun = (run > 0) as usize;
+ let findex = (p > 0) as usize;
+ bits += v.amp_code[frun][findex][base].1 as u32 + 1;
+ if findex == 1 {
+ bits += p_bits;
+ }
+ if frun == 1 {
+ bits += v.run_code[run].1 as u32;
+ }
+ run = 0;
+ }
+ bits
+}
+
+fn write_ac(w: &mut Writer, t: &[f32; 64], q: f32, v: &VlcSet, p_bits: u32, max_amp: u32) {
+ let mut run = 0usize;
+ for &x in &t[1..] {
+ if x.abs() < q {
+ run += 1;
+ continue;
+ }
+ let a = quant(x, q, max_amp);
+ let p = (a - 1) >> 6;
+ let base = ((a - 1) & 63) as usize;
+ let frun = (run > 0) as usize;
+ let findex = (p > 0) as usize;
+ let (c, l) = v.amp_code[frun][findex][base];
+ w.put(c as u32, l as u32);
+ w.put((x < 0.0) as u32, 1);
+ if findex == 1 {
+ w.put(p, p_bits);
+ }
+ if frun == 1 {
+ let (c, l) = v.run_code[run];
+ w.put(c as u32, l as u32);
+ }
+ run = 0;
+ }
+ w.put(v.eob.0 as u32, v.eob.1 as u32);
+}
diff --git a/crates/dnx/src/ffmpeg_probe.rs b/crates/dnx/src/ffmpeg_probe.rs
new file mode 100644
index 000000000..49622fa22
--- /dev/null
+++ b/crates/dnx/src/ffmpeg_probe.rs
@@ -0,0 +1,248 @@
+//! Black-box probes of ffmpeg's VC-3 decoder (ignored tests, run by hand).
+//!
+//! Each probe writes a stream whose first DCT block holds one AC coefficient (all other blocks
+//! empty), decodes it with ffmpeg as an external process, and measures the reconstructed
+//! coefficient with a forward DCT of the output pixels. They established the two places where
+//! ffmpeg's decoder differs from the text of SMPTE ST 2019-1 (see the README): the quantisation
+//! weights it uses for CID 1271, and its reconstruction offset.
+//!
+//! `DNX_CID=1271 cargo test -p filmcraft-dnx --lib ffmpeg_probe -- --ignored --nocapture`
+use crate::bits::Writer;
+use crate::header::{self, EOF_SIGNATURE, FieldCode, FrameHeader, SCAN_INDEX_OFFSET};
+use crate::tables::{ZIGZAG, cid_info, vlc};
+use crate::{ChromaFormat, ColorVolume};
+
+fn stream_cid(cid: u32, w: u32, h: u32, depth: u8, q: u32, pos: usize, amp: u32, neg: bool, blk: usize) -> Vec<u8> {
+ let info = cid_info(cid).unwrap();
+ let v = vlc(info.vlc);
+ let p_bits = if depth == 8 { 4 } else { 6 };
+ let nw = w.div_ceil(16) as usize;
+ let ns = h.div_ceil(16) as usize;
+ let mut rows = Vec::new();
+ for s in 0..ns {
+ let mut wr = Writer::new();
+ for mb in 0..nw {
+ wr.put(q, 11);
+ wr.put(0, 1);
+ for k in 0..8 {
+ let (c, l) = v.dc_code[0];
+ wr.put(c as u32, l as u32);
+ if s == 0 && mb == 0 && k == blk {
+ let p = (amp - 1) >> 6;
+ let base = ((amp - 1) & 63) as usize;
+ let frun = (pos > 1) as usize;
+ let (c, l) = v.amp_code[frun][(p > 0) as usize][base];
+ wr.put(c as u32, l as u32);
+ wr.put(neg as u32, 1);
+ if p > 0 {
+ wr.put(p, p_bits);
+ }
+ if frun == 1 {
+ let (c, l) = v.run_code[pos - 1];
+ wr.put(c as u32, l as u32);
+ }
+ }
+ wr.put(v.eob.0 as u32, v.eob.1 as u32);
+ }
+ }
+ rows.push(wr.finish_aligned(4));
+ }
+ let hdr = FrameHeader {
+ header_size: 0x280,
+ version: if cid >= 1270 { 3 } else { 1 },
+ cid,
+ vbr: false,
+ field: FieldCode::Frame,
+ macf: false,
+ crc: false,
+ alpha: false,
+ lossless_alpha: false,
+ premultiplied_alpha: false,
+ width: w,
+ lines: h,
+ par: (0, 0),
+ bit_depth: depth,
+ interlaced: false,
+ frame_encoding: true,
+ chroma: ChromaFormat::Yuv422,
+ rgb: false,
+ color_volume: ColorVolume::Bt709,
+ timecode: None,
+ mb_rows: ns as u32,
+ };
+ let mut out = header::write(&hdr);
+ let mut off = 0u32;
+ for (s, r) in rows.iter().enumerate() {
+ out[SCAN_INDEX_OFFSET + 4 * s..SCAN_INDEX_OFFSET + 4 * s + 4].copy_from_slice(&off.to_be_bytes());
+ off += r.len() as u32;
+ }
+ for r in rows {
+ out.extend_from_slice(&r);
+ }
+ let size = match info.kind {
+ crate::tables::Kind::Hd { frame_size, .. } => frame_size as usize,
+ crate::tables::Kind::Ri { c0 } => crate::ri_frame_size(w, h, c0, false) as usize,
+ };
+ out.resize(size - 4, 0);
+ out.extend_from_slice(&EOF_SIGNATURE);
+ out
+}
+
+#[test]
+#[ignore]
+fn probe_weights() {
+ let ff = filmcraft_testkit::ffmpeg().unwrap();
+ let dir = filmcraft_testkit::fixtures_dir("dnx");
+ let cid: u32 = std::env::var("DNX_CID").unwrap().parse().unwrap();
+ let (w, h, depth): (u32, u32, u8) = match cid {
+ 1250 => (1280, 720, 10),
+ 1251 | 1252 => (1280, 720, 8),
+ 1235 => (1920, 1080, 10),
+ 1271 => (256, 128, 10),
+ 1272..=1274 => (256, 128, 8),
+ c => {
+ let i = cid_info(c).unwrap();
+ match i.kind {
+ crate::tables::Kind::Hd { width, height, depth, .. } => (width as u32, height as u32, depth),
+ _ => panic!(),
+ }
+ }
+ };
+ let pix = if depth == 10 { "yuv422p10le" } else { "yuv422p" };
+ let prof = cid;
+ let amp = 20u32;
+ let q = 4u32;
+ for blk in [0usize, 2] {
+ let mut grid = [[0f64; 8]; 8];
+ for pos in 1..64 {
+ let s = stream_cid(cid, w, h, depth, q, pos, amp, false, blk);
+ let path = dir.join("explore.dnxhd");
+ std::fs::write(&path, &s).unwrap();
+ let out = std::process::Command::new(&ff)
+ .args(["-hide_banner", "-loglevel", "error", "-f", "dnxhd", "-i"])
+ .arg(&path)
+ .args(["-f", "rawvideo", "-pix_fmt", pix, "-"])
+ .output()
+ .unwrap();
+ let px: Vec<f64> = if depth == 8 {
+ out.stdout.iter().map(|&b| b as f64).collect()
+ } else {
+ out.stdout.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]]) as f64).collect()
+ };
+ let (off, stride) = if blk == 0 { (0, w as usize) } else { ((w * h) as usize, w as usize / 2) };
+ let mid = (1 << (depth - 1)) as f64;
+ let z = ZIGZAG[pos] as usize;
+ let (u, vv) = (z % 8, z / 8);
+ let mut sum = 0f64;
+ for j in 0..8 {
+ for i in 0..8 {
+ let cu = if u == 0 { 0.5f64.sqrt() } else { 1.0 };
+ let cv = if vv == 0 { 0.5f64.sqrt() } else { 1.0 };
+ sum += cu * cv / 4.0
+ * (px[off + j * stride + i] - mid)
+ * (((2 * i + 1) * u) as f64 * std::f64::consts::PI / 16.0).cos()
+ * (((2 * j + 1) * vv) as f64 * std::f64::consts::PI / 16.0).cos();
+ }
+ }
+ grid[vv][u] = sum * cid_info(cid).unwrap().p as f64 / ((amp as f64 + 0.5) * q as f64);
+ }
+ {
+ use crate::spec_tables::*;
+ let all: [(&str, &[[u8; 63]; 2]); 11] = [
+ ("D1", &W_D_1),
+ ("D2", &W_D_2),
+ ("D3", &W_D_3),
+ ("D4", &W_D_4),
+ ("D5", &W_D_5),
+ ("D6", &W_D_6),
+ ("D7", &W_D_7),
+ ("D8", &W_D_8),
+ ("D9", &W_D_9),
+ ("D10", &W_D_10),
+ ("D11", &W_D_11),
+ ];
+ let mut res = vec![];
+ for (n, t) in all {
+ for c in 0..2 {
+ let mut e = 0f64;
+ for i in 1..64 {
+ e += (grid[i / 8][i % 8] - t[c][i - 1] as f64).powi(2);
+ }
+ res.push(((e / 63.0).sqrt(), format!("{n}{}", if c == 0 { "L" } else { "C" })));
+ }
+ }
+ res.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
+ println!("best matches: {:?}", &res[..4]);
+ }
+ println!("{prof:?} block {blk} estimated W (spec table below):");
+ let w = &cid_info(cid).unwrap().weights[(blk != 0) as usize];
+ for v in 0..8 {
+ let mut l = String::new();
+ for u in 0..8 {
+ l += &format!("{:6.1}", grid[v][u]);
+ }
+ l += " |";
+ for u in 0..8 {
+ if v + u > 0 {
+ l += &format!("{:4}", w[v * 8 + u - 1]);
+ } else {
+ l += " -";
+ }
+ }
+ println!("{l}");
+ }
+ }
+}
+
+#[test]
+#[ignore]
+fn probe_reconstruction() {
+ let ff = filmcraft_testkit::ffmpeg().unwrap();
+ let dir = filmcraft_testkit::fixtures_dir("dnx");
+ let cid: u32 = std::env::var("DNX_CID").unwrap().parse().unwrap();
+ let (w, h, depth): (u32, u32, u8) = match cid {
+ 1250 => (1280, 720, 10),
+ 1251 | 1252 => (1280, 720, 8),
+ 1235 => (1920, 1080, 10),
+ 1271 => (256, 128, 10),
+ _ => (256, 128, 8),
+ };
+ let pix = if depth == 10 { "yuv422p10le" } else { "yuv422p" };
+ let p = cid_info(cid).unwrap().p as f64;
+ for q in [1u32, 2, 3, 4, 8, 16] {
+ let mut xs = vec![];
+ for amp in 1..=40u32 {
+ let s = stream_cid(cid, w, h, depth, q, 1, amp, false, 0);
+ let path = dir.join("explore.dnxhd");
+ std::fs::write(&path, &s).unwrap();
+ let out = std::process::Command::new(&ff)
+ .args(["-hide_banner", "-loglevel", "error", "-f", "dnxhd", "-i"])
+ .arg(&path)
+ .args(["-f", "rawvideo", "-pix_fmt", pix, "-"])
+ .output()
+ .unwrap();
+ let px: Vec<f64> = if depth == 8 {
+ out.stdout.iter().map(|&b| b as f64).collect()
+ } else {
+ out.stdout.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]]) as f64).collect()
+ };
+ let mid = (1 << (depth - 1)) as f64;
+ let mut sum = 0f64;
+ for j in 0..8 {
+ for i in 0..8 {
+ sum += 0.25 * (px[j * w as usize + i] - mid) * ((2 * i + 1) as f64 * std::f64::consts::PI / 16.0).cos() * std::f64::consts::FRAC_1_SQRT_2;
+ }
+ }
+ xs.push((amp as f64, sum));
+ }
+ let n = xs.len() as f64;
+ let sx: f64 = xs.iter().map(|x| x.0).sum();
+ let sy: f64 = xs.iter().map(|x| x.1).sum();
+ let sxx: f64 = xs.iter().map(|x| x.0 * x.0).sum();
+ let sxy: f64 = xs.iter().map(|x| x.0 * x.1).sum();
+ let a = (n * sxy - sx * sy) / (n * sxx - sx * sx);
+ let b = (sy - a * sx) / n;
+ let step = 32.0 * q as f64 / p;
+ println!("cid {cid} q {q}: step {step} slope {a:.4} ({:.4} steps) intercept {b:.3} ({:.4} steps)", a / step, b / step);
+ }
+}
diff --git a/crates/dnx/src/header.rs b/crates/dnx/src/header.rs
new file mode 100644
index 000000000..345fd1730
--- /dev/null
+++ b/crates/dnx/src/header.rs
@@ -0,0 +1,259 @@
+//! Coding-unit header (SMPTE ST 2019-1 §7.2): parse and write.
+
+use crate::tables::{Kind, cid_info, ri_frame_size};
+use crate::{ChromaFormat, ColorVolume, Error, Result};
+
+/// Offset of the macroblock scan indices payload.
+pub const SCAN_INDEX_OFFSET: usize = 0x170;
+/// EOF signature when the CRC flag is clear (§7.4, Figure 39).
+pub const EOF_SIGNATURE: [u8; 4] = [0x60, 0x0D, 0xC0, 0xDE];
+
+/// Field/frame code of a coding unit (`FFC`, §7.2.2).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum FieldCode {
+ /// A progressive frame, or an interlaced frame coded as one unit.
+ Frame,
+ /// Field 1 (the top field) of a field-coded interlaced frame.
+ Field1,
+ /// Field 2 (the bottom field).
+ Field2,
+}
+
+/// A parsed coding-unit header.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FrameHeader {
+ /// Header size `HS` in bytes (the compressed payload starts here).
+ pub header_size: u32,
+ /// Header version number `HVN` (1, 2 = HD profile; 3 = RI profile; 4 = HD with alpha).
+ pub version: u8,
+ pub cid: u32,
+ /// Variable bitrate (no payload padding).
+ pub vbr: bool,
+ pub field: FieldCode,
+ /// Macroblock-adaptive field/frame coding (CID 1260).
+ pub macf: bool,
+ /// The EOF signature holds a CRC-32 instead of `0x600DC0DE`.
+ pub crc: bool,
+ pub alpha: bool,
+ /// Alpha is coded losslessly (differential RLE) instead of with the DCT.
+ pub lossless_alpha: bool,
+ pub premultiplied_alpha: bool,
+ /// Samples per line (`SPL`).
+ pub width: u32,
+ /// Active lines (`ALPF`) of this coding unit: lines per frame, or per field for a field
+ /// coding unit.
+ pub lines: u32,
+ /// Pixel aspect ratio `PARC / PARN` (0/0 = not signalled).
+ pub par: (u16, u16),
+ pub bit_depth: u8,
+ /// Source scan type is interlaced (`SST`).
+ pub interlaced: bool,
+ /// Frame encoding (`FFE`); false = each field is its own coding unit.
+ pub frame_encoding: bool,
+ pub chroma: ChromaFormat,
+ /// The bitstream codes RGB (`CLF`).
+ pub rgb: bool,
+ pub color_volume: ColorVolume,
+ /// SMPTE ST 12-1 time code bytes, if present.
+ pub timecode: Option<[u8; 8]>,
+ /// Number of macroblock scan lines `NS`.
+ pub mb_rows: u32,
+}
+
+impl FrameHeader {
+ /// Whether the 4:4:4 planes carry R′G′B′ (macroblocks with ACF = 1 carry Y′CbCr).
+ ///
+ /// The standard ties RGB to `CLF = 1`. ffmpeg's encoder, the most common source of DNxHR 444
+ /// files, writes RGB with `CLF = 0` (and Y′CbCr with `CLF = 1`, `ACF = 1` everywhere), and
+ /// its decoder reads them that way; we follow that interpretation: every 4:4:4 stream is RGB
+ /// except macroblocks flagged ACF = 1.
+ pub fn rgb_planes(&self) -> bool {
+ self.rgb || self.chroma == ChromaFormat::Yuv444
+ }
+
+ /// Macroblocks per scan line `NW`.
+ pub fn mb_width(&self) -> u32 {
+ self.width.div_ceil(16)
+ }
+
+ /// Size of this coding unit for CBR streams (`None` for VBR streams), from Table C.1 or
+ /// equation 7.1.
+ pub fn coding_unit_size(&self) -> Option<u32> {
+ if self.vbr {
+ return None;
+ }
+ let info = cid_info(self.cid)?;
+ Some(match info.kind {
+ Kind::Hd { frame_size, interlaced, .. } => {
+ let f = if self.alpha { frame_size + frame_size / 2 } else { frame_size };
+ if interlaced && !self.frame_encoding { f / 2 } else { f }
+ }
+ Kind::Ri { c0 } => ri_frame_size(self.width, self.lines, c0, self.alpha),
+ })
+ }
+}
+
+fn be16(d: &[u8], o: usize) -> u32 {
+ u32::from(d[o]) << 8 | u32::from(d[o + 1])
+}
+
+fn be32(d: &[u8], o: usize) -> u32 {
+ u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]])
+}
+
+/// Parse a coding-unit header at the start of `d`.
+pub fn parse(d: &[u8]) -> Result<FrameHeader> {
+ if d.len() < 0x280 {
+ return Err(Error::Truncated);
+ }
+ let header_size = be32(d, 0);
+ let version = d[4];
+ if !(1..=4).contains(&version) {
+ return Err(Error::Invalid("unknown header version"));
+ }
+ if header_size < 0x280 || header_size as usize > d.len() {
+ return Err(if header_size as usize > d.len() { Error::Truncated } else { Error::Invalid("header size") });
+ }
+ let cid = be32(d, 0x28);
+ let info = cid_info(cid).ok_or(Error::UnknownCid(cid))?;
+ let vbr = d[5] & 0x10 != 0;
+ let field = match d[5] & 3 {
+ 2 => FieldCode::Field1,
+ 3 => FieldCode::Field2,
+ _ => FieldCode::Frame,
+ };
+ let macf = d[6] & 0x20 != 0;
+ let crc = d[6] & 0x10 != 0;
+ let alpha = d[7] & 1 != 0;
+ let lossless_alpha = d[7] & 2 != 0;
+ let premultiplied_alpha = d[7] & 4 != 0;
+ let lines = be16(d, 0x18);
+ let width = be16(d, 0x1A);
+ let parc = (u32::from(d[0x1C] >> 2 & 3) << 8 | u32::from(d[0x1F])) as u16;
+ let parn = (u32::from(d[0x1C] & 3) << 8 | u32::from(d[0x20])) as u16;
+ let bit_depth = match d[0x21] >> 5 {
+ 1 => 8,
+ 2 => 10,
+ 3 => 12,
+ _ => return Err(Error::Invalid("sample bit depth")),
+ };
+ let interlaced = d[0x22] & 4 != 0;
+ let frame_encoding = d[0x2C] & 0x80 != 0;
+ let chroma = match d[0x2C] >> 5 & 3 {
+ 0 => ChromaFormat::Yuv422,
+ 1 => ChromaFormat::Yuv420,
+ 2 => ChromaFormat::Yuv444,
+ _ => return Err(Error::Invalid("sub sampling")),
+ };
+ let rgb = d[0x2C] & 1 != 0;
+ let color_volume = match d[0x2C] >> 1 & 3 {
+ 0 => ColorVolume::Bt709,
+ 1 => ColorVolume::Bt2020Ncl,
+ 2 => ColorVolume::Bt2020Cl,
+ _ => ColorVolume::OutOfBand,
+ };
+ let timecode = (d[0x30] & 0x80 != 0).then(|| d[0x31..0x39].try_into().unwrap());
+ let mb_rows = be16(d, 0x16C);
+ if width == 0 || lines == 0 || width > 16384 || lines > 16384 {
+ return Err(Error::Invalid("raster size"));
+ }
+ if let Kind::Hd { width: w, depth, .. } = info.kind
+ && (w as u32 != width || depth != bit_depth)
+ {
+ return Err(Error::Invalid("raster does not match the compression ID"));
+ }
+ if rgb && chroma != ChromaFormat::Yuv444 {
+ return Err(Error::Invalid("RGB requires 4:4:4"));
+ }
+ if chroma == ChromaFormat::Yuv444 && !matches!(cid, 1256 | 1270) {
+ return Err(Error::Invalid("4:4:4 requires CID 1256 or 1270"));
+ }
+ // macroblock scan lines must cover the coded raster, and their indices must fit the header
+ if mb_rows == 0 || SCAN_INDEX_OFFSET + 4 * mb_rows as usize > header_size as usize {
+ return Err(Error::Invalid("macroblock scan line count"));
+ }
+ if mb_rows != lines.div_ceil(16) {
+ return Err(Error::Invalid("macroblock scan lines do not match the raster"));
+ }
+ Ok(FrameHeader {
+ header_size,
+ version,
+ cid,
+ vbr,
+ field,
+ macf,
+ crc,
+ alpha,
+ lossless_alpha,
+ premultiplied_alpha,
+ width,
+ lines,
+ par: (parc, parn),
+ bit_depth,
+ interlaced,
+ frame_encoding,
+ chroma,
+ rgb,
+ color_volume,
+ timecode,
+ mb_rows,
+ })
+}
+
+/// Header size for a raster of `lines` lines (§7.2: 640 bytes up to 1088 lines, plus 4 bytes
+/// per further 16 lines).
+pub fn header_size_for(lines: u32) -> u32 {
+ if lines <= 1088 { 0x280 } else { 0x280 + 4 * (lines - 1088).div_ceil(16) }
+}
+
+/// Write a header (without scan indices) for `h` into a zeroed buffer of `h.header_size` bytes.
+pub fn write(h: &FrameHeader) -> Vec<u8> {
+ let mut d = vec![0u8; h.header_size as usize];
+ d[0..4].copy_from_slice(&h.header_size.to_be_bytes());
+ d[4] = h.version;
+ d[5] = (h.vbr as u8) << 4
+ | match h.field {
+ FieldCode::Frame => 1,
+ FieldCode::Field1 => 2,
+ FieldCode::Field2 => 3,
+ };
+ d[6] = 0x80 | (h.macf as u8) << 5 | (h.crc as u8) << 4;
+ d[7] = 0xA0 | (h.premultiplied_alpha as u8) << 2 | (h.lossless_alpha as u8) << 1 | h.alpha as u8;
+ d[0x18..0x1A].copy_from_slice(&(h.lines as u16).to_be_bytes());
+ d[0x1A..0x1C].copy_from_slice(&(h.width as u16).to_be_bytes());
+ d[0x1C] = ((h.par.0 >> 8) as u8 & 3) << 2 | ((h.par.1 >> 8) as u8 & 3);
+ d[0x1D..0x1F].copy_from_slice(&(h.lines as u16).to_be_bytes());
+ d[0x1F] = h.par.0 as u8;
+ d[0x20] = h.par.1 as u8;
+ let sbd = match h.bit_depth {
+ 8 => 1,
+ 10 => 2,
+ _ => 3,
+ };
+ d[0x21] = sbd << 5 | 0x18;
+ d[0x22] = 0x88 | (h.interlaced as u8) << 2;
+ d[0x28..0x2C].copy_from_slice(&h.cid.to_be_bytes());
+ let ssc = match h.chroma {
+ ChromaFormat::Yuv422 => 0,
+ ChromaFormat::Yuv420 => 1,
+ ChromaFormat::Yuv444 => 2,
+ };
+ let clv = match h.color_volume {
+ ColorVolume::Bt709 => 0,
+ ColorVolume::Bt2020Ncl => 1,
+ ColorVolume::Bt2020Cl => 2,
+ ColorVolume::OutOfBand => 3,
+ };
+ d[0x2C] = (h.frame_encoding as u8) << 7 | ssc << 5 | clv << 1 | h.rgb as u8;
+ if let Some(tc) = h.timecode {
+ d[0x30] = 0x80;
+ d[0x31..0x39].copy_from_slice(&tc);
+ }
+ d[0x5F] = 0x01;
+ d[0x167] = 0x02;
+ let msips = (4 * h.mb_rows + 4) as u16;
+ d[0x16A..0x16C].copy_from_slice(&msips.to_be_bytes());
+ d[0x16C..0x16E].copy_from_slice(&(h.mb_rows as u16).to_be_bytes());
+ d[0x16F] = 0x10;
+ d
+}
diff --git a/crates/dnx/src/lib.rs b/crates/dnx/src/lib.rs
new file mode 100644
index 000000000..87a3e0c47
--- /dev/null
+++ b/crates/dnx/src/lib.rs
@@ -0,0 +1,233 @@
+//! Clean-room Avid DNxHD / DNxHR codec (VC-3, implemented from SMPTE ST 2019-1:2016 and its
+//! Amendment 1:2023).
+//!
+//! - **Decoder** ([`decode_frame`]): every compression ID of the standard — the DNxHD (HD
+//! profile) IDs 1235–1260 including interlaced field and macroblock-adaptive coding, thin
+//! rasters and 4:4:4 RGB, and the resolution-independent DNxHR IDs 1270–1274 (LB, SQ, HQ, HQX,
+//! 444) at 8, 10 and 12 bits in 4:2:0, 4:2:2 and 4:4:4, with DCT or lossless alpha. Macroblock
+//! scan lines decode in parallel with the `threads` feature (rayon).
+//! - **Encoder** ([`Encoder`]): DNxHR SQ / HQ (8-bit 4:2:2) and HQX (10- or 12-bit 4:2:2), CBR
+//! at the standard's frame sizes, progressive.
+//!
+//! See the crate README for accuracy, performance and limitations.
+
+mod bits;
+mod dct;
+mod decode;
+mod encode;
+pub mod header;
+mod spec_tables;
+mod tables;
+
+pub use decode::{DecodeOptions, decode_frame, decode_frame_with, probe};
+pub use encode::{Encoder, EncoderConfig};
+pub use header::{FieldCode, FrameHeader};
+pub use tables::ri_frame_size;
+
+/// Codec errors.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum Error {
+ #[error("truncated VC-3 data")]
+ Truncated,
+ #[error("invalid VC-3 data: {0}")]
+ Invalid(&'static str),
+ #[error("unknown VC-3 compression ID {0}")]
+ UnknownCid(u32),
+ #[error("corrupt macroblock scan line {0}")]
+ Row(usize),
+ #[error("invalid encoder input: {0}")]
+ Input(String),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Chroma subsampling (`SSC`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ChromaFormat {
+ /// Half width, half height.
+ Yuv420,
+ /// Half width, full height.
+ Yuv422,
+ /// Full size (also RGB).
+ Yuv444,
+}
+
+impl ChromaFormat {
+ pub fn chroma_width(self, width: u32) -> u32 {
+ match self {
+ ChromaFormat::Yuv444 => width,
+ _ => width.div_ceil(2),
+ }
+ }
+ pub fn chroma_height(self, height: u32) -> u32 {
+ match self {
+ ChromaFormat::Yuv420 => height.div_ceil(2),
+ _ => height,
+ }
+ }
+}
+
+/// Colour volume (`CLV`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
+pub enum ColorVolume {
+ #[default]
+ Bt709,
+ /// BT.2020 non-constant luminance.
+ Bt2020Ncl,
+ /// BT.2020 constant luminance.
+ Bt2020Cl,
+ /// Described out of band.
+ OutOfBand,
+}
+
+/// Frame scan structure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
+pub enum Interlace {
+ #[default]
+ Progressive,
+ /// Interlaced; field 1 (the top field, even lines) comes first.
+ TopFieldFirst,
+}
+
+/// DNxHR profiles (resolution-independent compression IDs).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Profile {
+ /// DNxHR LB (CID 1274), 8-bit.
+ Lb,
+ /// DNxHR SQ (CID 1273), 8-bit.
+ Sq,
+ /// DNxHR HQ (CID 1272), 8-bit.
+ Hq,
+ /// DNxHR HQX (CID 1271), 10- or 12-bit.
+ Hqx,
+ /// DNxHR 444 (CID 1270), 10- or 12-bit 4:4:4.
+ R444,
+}
+
+impl Profile {
+ pub fn cid(self) -> u32 {
+ match self {
+ Profile::Lb => 1274,
+ Profile::Sq => 1273,
+ Profile::Hq => 1272,
+ Profile::Hqx => 1271,
+ Profile::R444 => 1270,
+ }
+ }
+ pub fn from_cid(cid: u32) -> Option<Profile> {
+ [Profile::Lb, Profile::Sq, Profile::Hq, Profile::Hqx, Profile::R444].into_iter().find(|p| p.cid() == cid)
+ }
+ pub fn name(self) -> &'static str {
+ match self {
+ Profile::Lb => "DNxHR LB",
+ Profile::Sq => "DNxHR SQ",
+ Profile::Hq => "DNxHR HQ",
+ Profile::Hqx => "DNxHR HQX",
+ Profile::R444 => "DNxHR 444",
+ }
+ }
+ /// CBR frame size for a raster (equation 7.1).
+ pub fn frame_size(self, width: u32, height: u32) -> u32 {
+ let c0 = match self {
+ Profile::Lb => 188416,
+ Profile::Sq => 606208,
+ Profile::Hq | Profile::Hqx => 917504,
+ Profile::R444 => 1835008,
+ };
+ ri_frame_size(width, height, c0, false)
+ }
+}
+
+/// A human-readable name for a compression ID ("DNxHD 1080p 145/120 8-bit", "DNxHR HQ"…).
+pub fn cid_name(cid: u32) -> String {
+ if let Some(p) = Profile::from_cid(cid) {
+ return p.name().into();
+ }
+ match cid {
+ 1235 => "DNxHD 1080p 10-bit (CID 1235)".into(),
+ 1237 => "DNxHD 1080p 8-bit (CID 1237)".into(),
+ 1238 => "DNxHD 1080p 8-bit (CID 1238)".into(),
+ 1241 => "DNxHD 1080i 10-bit (CID 1241)".into(),
+ 1242 => "DNxHD 1080i 8-bit (CID 1242)".into(),
+ 1243 => "DNxHD 1080i 8-bit (CID 1243)".into(),
+ 1244 => "DNxHD 1080i thin raster (CID 1244)".into(),
+ 1250 => "DNxHD 720p 10-bit (CID 1250)".into(),
+ 1251 => "DNxHD 720p 8-bit (CID 1251)".into(),
+ 1252 => "DNxHD 720p 8-bit (CID 1252)".into(),
+ 1253 => "DNxHD 1080p 36 (CID 1253)".into(),
+ 1256 => "DNxHD 444 10-bit (CID 1256)".into(),
+ 1258 => "DNxHD 720p thin raster (CID 1258)".into(),
+ 1259 => "DNxHD 1080p thin raster (CID 1259)".into(),
+ 1260 => "DNxHD 1080i thin raster (CID 1260)".into(),
+ _ => format!("VC-3 (CID {cid})"),
+ }
+}
+
+/// A decoded (or to-be-encoded) picture: planar `u16` samples, rows packed without padding.
+///
+/// For RGB streams (`rgb == true`) the planes `y`, `cb`, `cr` hold G, B and R: the coded channel
+/// order Ch1/Ch2/Ch3 as written by ffmpeg and read by its decoder (the standard's text names Ch1
+/// red; see the README).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Frame {
+ pub width: u32,
+ pub height: u32,
+ pub chroma: ChromaFormat,
+ pub rgb: bool,
+ /// Significant bits per sample of every plane (8, 10 or 12).
+ pub bit_depth: u8,
+ pub y: Vec<u16>,
+ pub cb: Vec<u16>,
+ pub cr: Vec<u16>,
+ /// Full-range alpha (0 = transparent).
+ pub alpha: Option<Vec<u16>>,
+ pub interlace: Interlace,
+ pub color_volume: ColorVolume,
+ /// Compression ID of the stream.
+ pub cid: u32,
+ /// Pixel aspect ratio (0/0 = not signalled).
+ pub par: (u16, u16),
+}
+
+impl Frame {
+ /// A black (video-range) frame.
+ pub fn new(width: u32, height: u32, chroma: ChromaFormat, bit_depth: u8, with_alpha: bool) -> Frame {
+ let n = width as usize * height as usize;
+ let cn = chroma.chroma_width(width) as usize * chroma.chroma_height(height) as usize;
+ let s = bit_depth.saturating_sub(8) as u32;
+ Frame {
+ width,
+ height,
+ chroma,
+ rgb: false,
+ bit_depth,
+ y: vec![(16u32 << s) as u16; n],
+ cb: vec![(128u32 << s) as u16; cn],
+ cr: vec![(128u32 << s) as u16; cn],
+ alpha: with_alpha.then(|| vec![((1u32 << bit_depth) - 1) as u16; n]),
+ interlace: Interlace::Progressive,
+ color_volume: ColorVolume::Bt709,
+ cid: 0,
+ par: (0, 0),
+ }
+ }
+
+ pub(crate) fn new_like(h: &FrameHeader, width: u32, height: u32) -> Frame {
+ let mut f = Frame::new(width, height, h.chroma, h.bit_depth, h.alpha);
+ f.rgb = h.rgb_planes();
+ f.color_volume = h.color_volume;
+ f.cid = h.cid;
+ f.par = h.par;
+ f
+ }
+
+ pub fn chroma_width(&self) -> u32 {
+ self.chroma.chroma_width(self.width)
+ }
+
+ pub fn chroma_height(&self) -> u32 {
+ self.chroma.chroma_height(self.height)
+ }
+}
+#[cfg(test)]
+mod ffmpeg_probe;
diff --git a/crates/dnx/src/spec_tables.rs b/crates/dnx/src/spec_tables.rs
new file mode 100644
index 000000000..a22bf3b9e
--- /dev/null
+++ b/crates/dnx/src/spec_tables.rs
@@ -0,0 +1,2115 @@
+// Generated by tools/extract_tables.py from SMPTE ST 2019-1:2016 (VC-3), Annexes D and E.
+// Do not edit by hand.
+
+pub const W_D_1: [[u8; 63]; 2] = [
+ [
+ 32, 32, 32, 33, 35, 38, 39, 32, 33, 32, 33, 36, 36, 39, 42, 32, 32, 33, 36, 35, 37, 41, 43, 31, 33, 34, 36, 36, 40, 42, 48, 32, 34, 36, 37, 39, 42, 46,
+ 51, 36, 37, 37, 39, 41, 46, 51, 55, 37, 39, 41, 41, 47, 50, 55, 56, 41, 42, 41, 44, 50, 53, 60, 60,
+ ],
+ [
+ 32, 33, 34, 39, 41, 54, 59, 33, 34, 35, 38, 43, 49, 58, 84, 34, 37, 39, 44, 46, 55, 74, 87, 40, 42, 47, 48, 58, 70, 87, 86, 43, 50, 56, 63, 72, 94, 91,
+ 82, 55, 63, 65, 75, 93, 89, 85, 73, 61, 67, 82, 81, 83, 90, 79, 73, 74, 84, 75, 78, 90, 85, 73, 73,
+ ],
+];
+pub const W_D_2: [[u8; 63]; 2] = [
+ [
+ 32, 36, 37, 41, 44, 54, 60, 33, 34, 36, 39, 43, 51, 62, 78, 34, 36, 38, 41, 49, 59, 73, 79, 37, 38, 40, 47, 55, 66, 80, 95, 38, 41, 46, 54, 63, 79, 93,
+ 96, 46, 47, 56, 64, 78, 90, 97, 98, 49, 58, 66, 78, 89, 97, 102, 98, 61, 65, 82, 87, 100, 104, 99, 99,
+ ],
+ [
+ 32, 38, 39, 47, 51, 77, 83, 36, 39, 41, 48, 55, 74, 85, 95, 39, 45, 53, 58, 72, 83, 105, 89, 51, 58, 66, 73, 82, 109, 92, 95, 57, 75, 78, 89, 105, 95,
+ 93, 96, 81, 82, 99, 99, 94, 90, 97, 98, 83, 96, 97, 93, 89, 97, 102, 98, 90, 94, 92, 88, 100, 104, 99, 99,
+ ],
+];
+pub const W_D_3: [[u8; 63]; 2] = [
+ [
+ 32, 33, 33, 37, 37, 41, 42, 32, 34, 33, 35, 36, 38, 41, 43, 33, 33, 33, 36, 37, 39, 41, 44, 33, 33, 35, 36, 38, 40, 44, 50, 33, 36, 35, 38, 39, 44, 49,
+ 51, 38, 36, 38, 39, 44, 47, 51, 58, 38, 39, 41, 44, 47, 51, 57, 59, 41, 42, 45, 47, 53, 55, 57, 57,
+ ],
+ [
+ 32, 34, 34, 40, 41, 55, 61, 35, 35, 35, 39, 42, 52, 62, 75, 35, 39, 41, 44, 52, 58, 68, 77, 43, 45, 48, 53, 58, 65, 74, 80, 45, 55, 59, 63, 66, 74, 76,
+ 89, 59, 65, 66, 70, 77, 73, 90, 84, 63, 66, 74, 76, 73, 82, 86, 82, 65, 70, 73, 73, 77, 80, 82, 82,
+ ],
+];
+pub const W_D_4: [[u8; 63]; 2] = [
+ [
+ 32, 35, 36, 39, 40, 45, 45, 33, 34, 37, 39, 40, 43, 46, 46, 34, 36, 38, 38, 42, 47, 46, 46, 37, 38, 38, 41, 46, 45, 47, 49, 38, 39, 41, 45, 45, 47, 48,
+ 50, 38, 39, 43, 44, 46, 47, 49, 48, 37, 39, 40, 44, 45, 48, 48, 49, 37, 37, 42, 43, 46, 47, 49, 49,
+ ],
+ [
+ 32, 37, 40, 41, 41, 45, 45, 36, 37, 41, 41, 42, 45, 46, 48, 38, 40, 41, 43, 45, 47, 48, 46, 40, 42, 44, 44, 46, 48, 47, 49, 42, 44, 45, 45, 47, 47, 48,
+ 50, 45, 46, 44, 45, 46, 47, 49, 48, 46, 42, 45, 47, 45, 48, 49, 49, 41, 43, 46, 45, 46, 48, 49, 49,
+ ],
+];
+pub const W_D_5: [[u8; 63]; 2] = [
+ [
+ 32, 35, 36, 38, 37, 40, 42, 33, 34, 35, 37, 37, 37, 45, 49, 33, 33, 37, 37, 36, 46, 48, 50, 33, 36, 36, 37, 44, 46, 52, 51, 35, 37, 39, 41, 48, 52, 51,
+ 50, 37, 38, 42, 50, 50, 50, 49, 49, 37, 44, 49, 49, 50, 49, 51, 47, 45, 47, 47, 48, 51, 52, 47, 47,
+ ],
+ [
+ 32, 45, 45, 51, 47, 45, 47, 37, 45, 44, 49, 41, 47, 50, 51, 42, 38, 44, 40, 47, 51, 49, 51, 37, 42, 43, 51, 49, 48, 52, 54, 40, 44, 54, 46, 51, 52, 54,
+ 53, 46, 51, 47, 55, 54, 53, 53, 60, 48, 49, 55, 54, 52, 55, 62, 60, 47, 50, 49, 49, 59, 63, 60, 60,
+ ],
+];
+pub const W_D_6: [[u8; 63]; 2] = [
+ [
+ 32, 35, 35, 38, 40, 44, 45, 32, 33, 35, 35, 39, 42, 44, 45, 33, 35, 34, 37, 41, 42, 45, 45, 35, 35, 37, 40, 41, 44, 45, 48, 35, 37, 38, 40, 43, 45, 47,
+ 48, 36, 36, 38, 40, 45, 47, 48, 47, 35, 36, 38, 41, 45, 46, 47, 48, 36, 37, 39, 41, 44, 45, 47, 47,
+ ],
+ [
+ 32, 37, 39, 41, 42, 45, 45, 36, 36, 39, 41, 43, 45, 46, 45, 37, 41, 41, 43, 45, 44, 45, 46, 43, 42, 43, 46, 44, 45, 46, 48, 43, 44, 47, 45, 44, 46, 47,
+ 49, 44, 46, 44, 45, 45, 47, 48, 47, 44, 42, 46, 44, 45, 46, 47, 48, 41, 43, 45, 44, 45, 46, 47, 47,
+ ],
+];
+pub const W_D_7: [[u8; 63]; 2] = [
+ [
+ 32, 37, 37, 40, 41, 52, 53, 33, 36, 36, 38, 40, 48, 49, 52, 34, 34, 37, 39, 44, 47, 49, 54, 33, 35, 38, 40, 45, 46, 54, 51, 34, 37, 37, 42, 44, 49, 52,
+ 48, 34, 34, 38, 43, 44, 51, 50, 50, 33, 36, 41, 44, 51, 52, 50, 54, 36, 38, 44, 47, 53, 53, 54, 54,
+ ],
+ [
+ 32, 40, 38, 42, 40, 45, 45, 34, 42, 36, 43, 38, 46, 46, 49, 38, 35, 43, 39, 44, 47, 47, 49, 35, 42, 43, 42, 46, 47, 49, 52, 38, 43, 43, 44, 50, 49, 56,
+ 50, 42, 43, 44, 50, 51, 57, 52, 53, 41, 45, 46, 53, 53, 56, 53, 54, 46, 46, 51, 49, 56, 53, 58, 58,
+ ],
+];
+pub const W_D_8: [[u8; 63]; 2] = [
+ [
+ 32, 35, 35, 36, 36, 41, 43, 32, 34, 35, 36, 37, 39, 43, 47, 33, 34, 36, 38, 38, 42, 42, 50, 34, 36, 38, 38, 41, 40, 47, 54, 35, 38, 39, 40, 39, 45, 49,
+ 58, 38, 39, 40, 39, 46, 47, 54, 60, 38, 39, 41, 46, 46, 48, 57, 62, 40, 41, 44, 45, 49, 54, 63, 63,
+ ],
+ [
+ 32, 35, 36, 40, 42, 51, 51, 35, 36, 39, 39, 43, 51, 52, 55, 36, 41, 41, 43, 51, 53, 54, 56, 43, 44, 45, 50, 54, 54, 55, 57, 45, 48, 50, 51, 55, 58, 59,
+ 58, 49, 52, 49, 57, 58, 62, 58, 60, 51, 51, 56, 58, 62, 61, 59, 62, 52, 52, 60, 61, 59, 59, 63, 63,
+ ],
+];
+pub const W_D_9: [[u8; 63]; 2] = [
+ [
+ 32, 34, 34, 35, 36, 41, 44, 32, 34, 35, 36, 38, 39, 43, 46, 34, 35, 36, 38, 38, 41, 43, 46, 35, 37, 38, 38, 40, 40, 44, 55, 36, 38, 38, 40, 39, 44, 50,
+ 58, 38, 38, 40, 40, 44, 48, 53, 61, 38, 40, 41, 42, 46, 48, 58, 62, 39, 40, 41, 43, 50, 55, 62, 62,
+ ],
+ [
+ 32, 35, 36, 40, 42, 51, 51, 35, 36, 39, 39, 43, 51, 52, 55, 36, 41, 41, 43, 51, 53, 54, 56, 43, 44, 45, 50, 54, 54, 55, 57, 45, 48, 50, 51, 55, 58, 59,
+ 58, 48, 50, 49, 57, 58, 62, 58, 61, 48, 51, 56, 58, 62, 61, 59, 62, 52, 52, 60, 61, 59, 59, 62, 62,
+ ],
+];
+pub const W_D_10: [[u8; 63]; 2] = [
+ [
+ 32, 36, 36, 40, 40, 55, 60, 34, 36, 37, 40, 41, 48, 57, 82, 35, 36, 41, 41, 46, 52, 73, 82, 37, 40, 42, 45, 50, 65, 80, 87, 39, 41, 44, 49, 62, 78, 88,
+ 90, 41, 44, 49, 58, 73, 90, 95, 95, 43, 52, 55, 68, 90, 100, 97, 93, 52, 53, 71, 82, 107, 103, 99, 99,
+ ],
+ [
+ 32, 37, 38, 49, 53, 65, 66, 35, 37, 40, 49, 56, 64, 65, 82, 36, 42, 50, 56, 64, 67, 73, 85, 46, 50, 57, 63, 71, 72, 89, 87, 49, 58, 65, 72, 78, 88, 88,
+ 90, 60, 64, 74, 81, 84, 90, 95, 134, 62, 74, 77, 80, 90, 114, 129, 125, 74, 74, 90, 100, 128, 125, 116, 116,
+ ],
+];
+pub const W_D_11: [[u8; 63]; 2] = [
+ [
+ 32, 32, 32, 33, 35, 38, 39, 32, 33, 32, 33, 36, 36, 39, 42, 32, 32, 33, 36, 35, 37, 41, 43, 31, 33, 34, 36, 36, 40, 42, 48, 32, 34, 36, 37, 39, 42, 46,
+ 51, 36, 37, 37, 39, 41, 46, 51, 55, 37, 39, 41, 41, 47, 50, 55, 56, 41, 42, 41, 44, 50, 53, 60, 60,
+ ],
+ [
+ 32, 32, 32, 33, 35, 38, 39, 32, 33, 32, 33, 36, 36, 39, 42, 32, 32, 33, 36, 35, 37, 41, 43, 31, 33, 34, 36, 36, 40, 42, 48, 32, 34, 36, 37, 39, 42, 46,
+ 51, 36, 37, 37, 39, 41, 46, 51, 55, 37, 39, 41, 41, 47, 50, 55, 56, 41, 42, 41, 44, 50, 53, 60, 60,
+ ],
+];
+
+/// Table E.1: (codeword, length, amplitude (0 = EOB), Frun, Findex).
+pub const AMP_E_1: [(u16, u8, u8, u8, u8); 257] = [
+ (0b00, 2, 1, 0, 0),
+ (0b11111100111, 11, 37, 0, 0),
+ (0b01, 2, 1, 1, 0),
+ (0b11111101000, 11, 38, 0, 0),
+ (0b100, 3, 2, 0, 0),
+ (0b11111101001, 11, 10, 1, 0),
+ (0b1010, 4, 3, 0, 0),
+ (0b11111101010, 11, 11, 1, 0),
+ (0b1011, 4, 0, 0, 0),
+ (0b111111010110, 12, 39, 0, 0),
+ (0b11000, 5, 4, 0, 0),
+ (0b111111010111, 12, 40, 0, 0),
+ (0b11001, 5, 5, 0, 0),
+ (0b111111011000, 12, 41, 0, 0),
+ (0b11010, 5, 2, 1, 0),
+ (0b111111011001, 12, 42, 0, 0),
+ (0b110110, 6, 6, 0, 0),
+ (0b111111011010, 12, 43, 0, 0),
+ (0b110111, 6, 7, 0, 0),
+ (0b111111011011, 12, 44, 0, 0),
+ (0b111000, 6, 8, 0, 0),
+ (0b111111011100, 12, 45, 0, 0),
+ (0b111001, 6, 3, 1, 0),
+ (0b111111011101, 12, 46, 0, 0),
+ (0b1110100, 7, 9, 0, 0),
+ (0b111111011110, 12, 47, 0, 0),
+ (0b1110101, 7, 10, 0, 0),
+ (0b111111011111, 12, 48, 0, 0),
+ (0b1110110, 7, 11, 0, 0),
+ (0b111111100000, 12, 49, 0, 0),
+ (0b1110111, 7, 4, 1, 0),
+ (0b111111100001, 12, 50, 0, 0),
+ (0b11110000, 8, 12, 0, 0),
+ (0b111111100010, 12, 12, 1, 0),
+ (0b11110001, 8, 13, 0, 0),
+ (0b111111100011, 12, 13, 1, 0),
+ (0b11110010, 8, 14, 0, 0),
+ (0b111111100100, 12, 14, 1, 0),
+ (0b11110011, 8, 15, 0, 0),
+ (0b111111100101, 12, 15, 1, 0),
+ (0b11110100, 8, 16, 0, 0),
+ (0b1111111001100, 13, 51, 0, 0),
+ (0b11110101, 8, 5, 1, 0),
+ (0b1111111001101, 13, 52, 0, 0),
+ (0b111101100, 9, 17, 0, 0),
+ (0b1111111001110, 13, 53, 0, 0),
+ (0b111101101, 9, 18, 0, 0),
+ (0b1111111001111, 13, 54, 0, 0),
+ (0b111101110, 9, 19, 0, 0),
+ (0b1111111010000, 13, 55, 0, 0),
+ (0b111101111, 9, 20, 0, 0),
+ (0b1111111010001, 13, 56, 0, 0),
+ (0b111110000, 9, 21, 0, 0),
+ (0b1111111010010, 13, 57, 0, 0),
+ (0b111110001, 9, 6, 1, 0),
+ (0b1111111010011, 13, 58, 0, 0),
+ (0b111110010, 9, 7, 1, 0),
+ (0b1111111010100, 13, 59, 0, 0),
+ (0b1111100110, 10, 22, 0, 0),
+ (0b1111111010101, 13, 60, 0, 0),
+ (0b1111100111, 10, 23, 0, 0),
+ (0b1111111010110, 13, 61, 0, 0),
+ (0b1111101000, 10, 24, 0, 0),
+ (0b1111111010111, 13, 62, 0, 0),
+ (0b1111101001, 10, 25, 0, 0),
+ (0b1111111011000, 13, 63, 0, 0),
+ (0b1111101010, 10, 26, 0, 0),
+ (0b1111111011001, 13, 1, 0, 1),
+ (0b1111101011, 10, 27, 0, 0),
+ (0b1111111011010, 13, 16, 1, 0),
+ (0b1111101100, 10, 28, 0, 0),
+ (0b1111111011011, 13, 17, 1, 0),
+ (0b1111101101, 10, 29, 0, 0),
+ (0b1111111011100, 13, 18, 1, 0),
+ (0b1111101110, 10, 8, 1, 0),
+ (0b1111111011101, 13, 19, 1, 0),
+ (0b1111101111, 10, 9, 1, 0),
+ (0b11111110111100, 14, 64, 0, 0),
+ (0b11111100000, 11, 30, 0, 0),
+ (0b11111110111101, 14, 2, 0, 1),
+ (0b11111100001, 11, 31, 0, 0),
+ (0b11111110111110, 14, 3, 0, 1),
+ (0b11111100010, 11, 32, 0, 0),
+ (0b11111110111111, 14, 4, 0, 1),
+ (0b11111100011, 11, 33, 0, 0),
+ (0b11111111000000, 14, 5, 0, 1),
+ (0b11111100100, 11, 34, 0, 0),
+ (0b11111111000001, 14, 6, 0, 1),
+ (0b11111100101, 11, 35, 0, 0),
+ (0b11111111000010, 14, 7, 0, 1),
+ (0b11111100110, 11, 36, 0, 0),
+ (0b11111111000011, 14, 8, 0, 1),
+ (0b11111111000100, 14, 9, 0, 1),
+ (0b1111111110010101, 16, 54, 0, 1),
+ (0b11111111000101, 14, 10, 0, 1),
+ (0b1111111110010110, 16, 55, 0, 1),
+ (0b11111111000110, 14, 11, 0, 1),
+ (0b1111111110010111, 16, 56, 0, 1),
+ (0b11111111000111, 14, 12, 0, 1),
+ (0b1111111110011000, 16, 57, 0, 1),
+ (0b11111111001000, 14, 13, 0, 1),
+ (0b1111111110011001, 16, 58, 0, 1),
+ (0b11111111001001, 14, 14, 0, 1),
+ (0b1111111110011010, 16, 59, 0, 1),
+ (0b11111111001010, 14, 15, 0, 1),
+ (0b1111111110011011, 16, 60, 0, 1),
+ (0b11111111001011, 14, 16, 0, 1),
+ (0b1111111110011100, 16, 61, 0, 1),
+ (0b11111111001100, 14, 17, 0, 1),
+ (0b1111111110011101, 16, 62, 0, 1),
+ (0b11111111001101, 14, 20, 1, 0),
+ (0b1111111110011110, 16, 63, 0, 1),
+ (0b11111111001110, 14, 21, 1, 0),
+ (0b1111111110011111, 16, 64, 0, 1),
+ (0b11111111001111, 14, 22, 1, 0),
+ (0b1111111110100000, 16, 33, 1, 0),
+ (0b11111111010000, 14, 23, 1, 0),
+ (0b1111111110100001, 16, 34, 1, 0),
+ (0b11111111010001, 14, 24, 1, 0),
+ (0b1111111110100010, 16, 35, 1, 0),
+ (0b111111110100100, 15, 18, 0, 1),
+ (0b1111111110100011, 16, 36, 1, 0),
+ (0b111111110100101, 15, 19, 0, 1),
+ (0b1111111110100100, 16, 37, 1, 0),
+ (0b111111110100110, 15, 20, 0, 1),
+ (0b1111111110100101, 16, 38, 1, 0),
+ (0b111111110100111, 15, 21, 0, 1),
+ (0b1111111110100110, 16, 39, 1, 0),
+ (0b111111110101000, 15, 22, 0, 1),
+ (0b1111111110100111, 16, 40, 1, 0),
+ (0b111111110101001, 15, 23, 0, 1),
+ (0b1111111110101000, 16, 41, 1, 0),
+ (0b111111110101010, 15, 24, 0, 1),
+ (0b1111111110101001, 16, 42, 1, 0),
+ (0b111111110101011, 15, 25, 0, 1),
+ (0b1111111110101010, 16, 43, 1, 0),
+ (0b111111110101100, 15, 26, 0, 1),
+ (0b1111111110101011, 16, 44, 1, 0),
+ (0b111111110101101, 15, 27, 0, 1),
+ (0b1111111110101100, 16, 45, 1, 0),
+ (0b111111110101110, 15, 28, 0, 1),
+ (0b1111111110101101, 16, 46, 1, 0),
+ (0b111111110101111, 15, 29, 0, 1),
+ (0b1111111110101110, 16, 47, 1, 0),
+ (0b111111110110000, 15, 30, 0, 1),
+ (0b1111111110101111, 16, 48, 1, 0),
+ (0b111111110110001, 15, 31, 0, 1),
+ (0b1111111110110000, 16, 49, 1, 0),
+ (0b111111110110010, 15, 32, 0, 1),
+ (0b1111111110110001, 16, 50, 1, 0),
+ (0b111111110110011, 15, 33, 0, 1),
+ (0b1111111110110010, 16, 51, 1, 0),
+ (0b111111110110100, 15, 34, 0, 1),
+ (0b1111111110110011, 16, 52, 1, 0),
+ (0b111111110110101, 15, 35, 0, 1),
+ (0b1111111110110100, 16, 53, 1, 0),
+ (0b111111110110110, 15, 36, 0, 1),
+ (0b1111111110110101, 16, 54, 1, 0),
+ (0b111111110110111, 15, 37, 0, 1),
+ (0b1111111110110110, 16, 55, 1, 0),
+ (0b111111110111000, 15, 38, 0, 1),
+ (0b1111111110110111, 16, 56, 1, 0),
+ (0b111111110111001, 15, 39, 0, 1),
+ (0b1111111110111000, 16, 57, 1, 0),
+ (0b111111110111010, 15, 40, 0, 1),
+ (0b1111111110111001, 16, 58, 1, 0),
+ (0b111111110111011, 15, 41, 0, 1),
+ (0b1111111110111010, 16, 59, 1, 0),
+ (0b111111110111100, 15, 42, 0, 1),
+ (0b1111111110111011, 16, 60, 1, 0),
+ (0b111111110111101, 15, 25, 1, 0),
+ (0b1111111110111100, 16, 61, 1, 0),
+ (0b111111110111110, 15, 26, 1, 0),
+ (0b1111111110111101, 16, 62, 1, 0),
+ (0b111111110111111, 15, 27, 1, 0),
+ (0b1111111110111110, 16, 63, 1, 0),
+ (0b111111111000000, 15, 28, 1, 0),
+ (0b1111111110111111, 16, 64, 1, 0),
+ (0b111111111000001, 15, 29, 1, 0),
+ (0b1111111111000000, 16, 1, 1, 1),
+ (0b111111111000010, 15, 30, 1, 0),
+ (0b1111111111000001, 16, 2, 1, 1),
+ (0b111111111000011, 15, 31, 1, 0),
+ (0b1111111111000010, 16, 3, 1, 1),
+ (0b111111111000100, 15, 32, 1, 0),
+ (0b1111111111000011, 16, 4, 1, 1),
+ (0b1111111110001010, 16, 43, 0, 1),
+ (0b1111111111000100, 16, 5, 1, 1),
+ (0b1111111110001011, 16, 44, 0, 1),
+ (0b1111111111000101, 16, 6, 1, 1),
+ (0b1111111110001100, 16, 45, 0, 1),
+ (0b1111111111000110, 16, 7, 1, 1),
+ (0b1111111110001101, 16, 46, 0, 1),
+ (0b1111111111000111, 16, 8, 1, 1),
+ (0b1111111110001110, 16, 47, 0, 1),
+ (0b1111111111001000, 16, 9, 1, 1),
+ (0b1111111110001111, 16, 48, 0, 1),
+ (0b1111111111001001, 16, 10, 1, 1),
+ (0b1111111110010000, 16, 49, 0, 1),
+ (0b1111111111001010, 16, 11, 1, 1),
+ (0b1111111110010001, 16, 50, 0, 1),
+ (0b1111111111001011, 16, 12, 1, 1),
+ (0b1111111110010010, 16, 51, 0, 1),
+ (0b1111111111001100, 16, 13, 1, 1),
+ (0b1111111110010011, 16, 52, 0, 1),
+ (0b1111111111001101, 16, 14, 1, 1),
+ (0b1111111110010100, 16, 53, 0, 1),
+ (0b1111111111001110, 16, 15, 1, 1),
+ (0b1111111111001111, 16, 16, 1, 1),
+ (0b1111111111101001, 16, 42, 1, 1),
+ (0b1111111111010000, 16, 17, 1, 1),
+ (0b1111111111101010, 16, 43, 1, 1),
+ (0b1111111111010001, 16, 18, 1, 1),
+ (0b1111111111101011, 16, 44, 1, 1),
+ (0b1111111111010010, 16, 19, 1, 1),
+ (0b1111111111101100, 16, 45, 1, 1),
+ (0b1111111111010011, 16, 20, 1, 1),
+ (0b1111111111101101, 16, 46, 1, 1),
+ (0b1111111111010100, 16, 21, 1, 1),
+ (0b1111111111101110, 16, 47, 1, 1),
+ (0b1111111111010101, 16, 22, 1, 1),
+ (0b1111111111101111, 16, 48, 1, 1),
+ (0b1111111111010110, 16, 23, 1, 1),
+ (0b1111111111110000, 16, 49, 1, 1),
+ (0b1111111111010111, 16, 24, 1, 1),
+ (0b1111111111110001, 16, 50, 1, 1),
+ (0b1111111111011000, 16, 25, 1, 1),
+ (0b1111111111110010, 16, 51, 1, 1),
+ (0b1111111111011001, 16, 26, 1, 1),
+ (0b1111111111110011, 16, 52, 1, 1),
+ (0b1111111111011010, 16, 27, 1, 1),
+ (0b1111111111110100, 16, 53, 1, 1),
+ (0b1111111111011011, 16, 28, 1, 1),
+ (0b1111111111110101, 16, 54, 1, 1),
+ (0b1111111111011100, 16, 29, 1, 1),
+ (0b1111111111110110, 16, 55, 1, 1),
+ (0b1111111111011101, 16, 30, 1, 1),
+ (0b1111111111110111, 16, 56, 1, 1),
+ (0b1111111111011110, 16, 31, 1, 1),
+ (0b1111111111111000, 16, 57, 1, 1),
+ (0b1111111111011111, 16, 32, 1, 1),
+ (0b1111111111111001, 16, 58, 1, 1),
+ (0b1111111111100000, 16, 33, 1, 1),
+ (0b1111111111111010, 16, 59, 1, 1),
+ (0b1111111111100001, 16, 34, 1, 1),
+ (0b1111111111111011, 16, 60, 1, 1),
+ (0b1111111111100010, 16, 35, 1, 1),
+ (0b1111111111111100, 16, 61, 1, 1),
+ (0b1111111111100011, 16, 36, 1, 1),
+ (0b1111111111111101, 16, 62, 1, 1),
+ (0b1111111111100100, 16, 37, 1, 1),
+ (0b1111111111111110, 16, 63, 1, 1),
+ (0b1111111111100101, 16, 38, 1, 1),
+ (0b1111111111111111, 16, 64, 1, 1),
+ (0b1111111111100110, 16, 39, 1, 1),
+ (0b1111111111100111, 16, 40, 1, 1),
+ (0b1111111111101000, 16, 41, 1, 1),
+];
+/// Table E.2: (codeword, length, run).
+pub const RUN_E_1: [(u16, u8, u8); 62] = [
+ (0b0, 1, 1),
+ (0b1111100001, 10, 32),
+ (0b100, 3, 2),
+ (0b1111100010, 10, 33),
+ (0b1010, 4, 3),
+ (0b1111100011, 10, 34),
+ (0b1011, 4, 4),
+ (0b1111100100, 10, 35),
+ (0b11000, 5, 5),
+ (0b1111100101, 10, 36),
+ (0b11001, 5, 6),
+ (0b1111100110, 10, 37),
+ (0b11010, 5, 7),
+ (0b1111100111, 10, 38),
+ (0b11011, 5, 8),
+ (0b1111101000, 10, 39),
+ (0b111000, 6, 9),
+ (0b1111101001, 10, 40),
+ (0b111001, 6, 10),
+ (0b1111101010, 10, 41),
+ (0b111010, 6, 11),
+ (0b1111101011, 10, 42),
+ (0b111011, 6, 12),
+ (0b1111101100, 10, 43),
+ (0b1111000, 7, 13),
+ (0b1111101101, 10, 44),
+ (0b11110010, 8, 14),
+ (0b1111101110, 10, 45),
+ (0b111100110, 9, 15),
+ (0b1111101111, 10, 46),
+ (0b111100111, 9, 16),
+ (0b1111110000, 10, 47),
+ (0b111101000, 9, 18),
+ (0b1111110001, 10, 48),
+ (0b111101001, 9, 20),
+ (0b1111110010, 10, 49),
+ (0b1111010100, 10, 17),
+ (0b1111110011, 10, 50),
+ (0b1111010101, 10, 19),
+ (0b1111110100, 10, 51),
+ (0b1111010110, 10, 21),
+ (0b1111110101, 10, 52),
+ (0b1111010111, 10, 22),
+ (0b1111110110, 10, 53),
+ (0b1111011000, 10, 23),
+ (0b1111110111, 10, 54),
+ (0b1111011001, 10, 24),
+ (0b1111111000, 10, 55),
+ (0b1111011010, 10, 25),
+ (0b1111111001, 10, 56),
+ (0b1111011011, 10, 26),
+ (0b1111111010, 10, 57),
+ (0b1111011100, 10, 27),
+ (0b1111111011, 10, 58),
+ (0b1111011101, 10, 28),
+ (0b1111111100, 10, 59),
+ (0b1111011110, 10, 29),
+ (0b1111111101, 10, 60),
+ (0b1111011111, 10, 30),
+ (0b1111111110, 10, 61),
+ (0b1111100000, 10, 31),
+ (0b1111111111, 10, 62),
+];
+/// Table E.3: (codeword, length) indexed by the DC size (eta).
+pub const DC_E_1: [(u16, u8); 14] = [
+ (0b1010, 4),
+ (0b111110, 6),
+ (0b1011, 4),
+ (0b1100, 4),
+ (0b1101, 4),
+ (0b000, 3),
+ (0b001, 3),
+ (0b010, 3),
+ (0b011, 3),
+ (0b100, 3),
+ (0b1110, 4),
+ (0b11110, 5),
+ (0b1111110, 7),
+ (0b1111111, 7),
+];
+
+/// Table E.4: (codeword, length, amplitude (0 = EOB), Frun, Findex).
+pub const AMP_E_4: [(u16, u8, u8, u8, u8); 257] = [
+ (0b00, 2, 1, 0, 0),
+ (0b1111111011101, 13, 15, 1, 0),
+ (0b01, 2, 1, 1, 0),
+ (0b1111111011110, 13, 16, 1, 0),
+ (0b100, 3, 2, 0, 0),
+ (0b11111110111110, 14, 42, 0, 0),
+ (0b101, 3, 0, 0, 0),
+ (0b11111110111111, 14, 43, 0, 0),
+ (0b1100, 4, 3, 0, 0),
+ (0b11111111000000, 14, 44, 0, 0),
+ (0b11010, 5, 4, 0, 0),
+ (0b11111111000001, 14, 45, 0, 0),
+ (0b11011, 5, 2, 1, 0),
+ (0b11111111000010, 14, 46, 0, 0),
+ (0b111000, 6, 5, 0, 0),
+ (0b11111111000011, 14, 47, 0, 0),
+ (0b111001, 6, 6, 0, 0),
+ (0b11111111000100, 14, 48, 0, 0),
+ (0b111010, 6, 7, 0, 0),
+ (0b11111111000101, 14, 49, 0, 0),
+ (0b111011, 6, 3, 1, 0),
+ (0b11111111000110, 14, 50, 0, 0),
+ (0b1111000, 7, 8, 0, 0),
+ (0b11111111000111, 14, 51, 0, 0),
+ (0b1111001, 7, 9, 0, 0),
+ (0b11111111001000, 14, 52, 0, 0),
+ (0b11110100, 8, 10, 0, 0),
+ (0b11111111001001, 14, 17, 1, 0),
+ (0b11110101, 8, 11, 0, 0),
+ (0b11111111001010, 14, 18, 1, 0),
+ (0b11110110, 8, 12, 0, 0),
+ (0b11111111001011, 14, 19, 1, 0),
+ (0b11110111, 8, 4, 1, 0),
+ (0b11111111001100, 14, 20, 1, 0),
+ (0b11111000, 8, 5, 1, 0),
+ (0b11111111001101, 14, 21, 1, 0),
+ (0b111110010, 9, 13, 0, 0),
+ (0b111111110011100, 15, 53, 0, 0),
+ (0b111110011, 9, 14, 0, 0),
+ (0b111111110011101, 15, 54, 0, 0),
+ (0b111110100, 9, 15, 0, 0),
+ (0b111111110011110, 15, 55, 0, 0),
+ (0b111110101, 9, 16, 0, 0),
+ (0b111111110011111, 15, 56, 0, 0),
+ (0b111110110, 9, 6, 1, 0),
+ (0b111111110100000, 15, 57, 0, 0),
+ (0b1111101110, 10, 17, 0, 0),
+ (0b111111110100001, 15, 58, 0, 0),
+ (0b1111101111, 10, 18, 0, 0),
+ (0b111111110100010, 15, 59, 0, 0),
+ (0b1111110000, 10, 19, 0, 0),
+ (0b111111110100011, 15, 60, 0, 0),
+ (0b1111110001, 10, 20, 0, 0),
+ (0b111111110100100, 15, 61, 0, 0),
+ (0b1111110010, 10, 21, 0, 0),
+ (0b111111110100101, 15, 64, 0, 0),
+ (0b1111110011, 10, 7, 1, 0),
+ (0b111111110100110, 15, 1, 0, 1),
+ (0b11111101000, 11, 22, 0, 0),
+ (0b111111110100111, 15, 22, 1, 0),
+ (0b11111101001, 11, 23, 0, 0),
+ (0b111111110101000, 15, 23, 1, 0),
+ (0b11111101010, 11, 24, 0, 0),
+ (0b111111110101001, 15, 24, 1, 0),
+ (0b11111101011, 11, 25, 0, 0),
+ (0b111111110101010, 15, 25, 1, 0),
+ (0b11111101100, 11, 26, 0, 0),
+ (0b111111110101011, 15, 26, 1, 0),
+ (0b11111101101, 11, 27, 0, 0),
+ (0b111111110101100, 15, 27, 1, 0),
+ (0b11111101110, 11, 8, 1, 0),
+ (0b1111111101011010, 16, 62, 0, 0),
+ (0b11111101111, 11, 9, 1, 0),
+ (0b1111111101011011, 16, 63, 0, 0),
+ (0b111111100000, 12, 28, 0, 0),
+ (0b1111111101011100, 16, 2, 0, 1),
+ (0b111111100001, 12, 29, 0, 0),
+ (0b1111111101011101, 16, 3, 0, 1),
+ (0b111111100010, 12, 30, 0, 0),
+ (0b1111111101011110, 16, 4, 0, 1),
+ (0b111111100011, 12, 31, 0, 0),
+ (0b1111111101011111, 16, 5, 0, 1),
+ (0b111111100100, 12, 32, 0, 0),
+ (0b1111111101100000, 16, 6, 0, 1),
+ (0b111111100101, 12, 33, 0, 0),
+ (0b1111111101100001, 16, 7, 0, 1),
+ (0b111111100110, 12, 34, 0, 0),
+ (0b1111111101100010, 16, 8, 0, 1),
+ (0b111111100111, 12, 10, 1, 0),
+ (0b1111111101100011, 16, 9, 0, 1),
+ (0b111111101000, 12, 11, 1, 0),
+ (0b1111111101100100, 16, 10, 0, 1),
+ (0b111111101001, 12, 12, 1, 0),
+ (0b1111111101100101, 16, 11, 0, 1),
+ (0b1111111010100, 13, 35, 0, 0),
+ (0b1111111101100110, 16, 12, 0, 1),
+ (0b1111111010101, 13, 36, 0, 0),
+ (0b1111111101100111, 16, 13, 0, 1),
+ (0b1111111010110, 13, 37, 0, 0),
+ (0b1111111101101000, 16, 14, 0, 1),
+ (0b1111111010111, 13, 38, 0, 0),
+ (0b1111111101101001, 16, 15, 0, 1),
+ (0b1111111011000, 13, 39, 0, 0),
+ (0b1111111101101010, 16, 16, 0, 1),
+ (0b1111111011001, 13, 40, 0, 0),
+ (0b1111111101101011, 16, 17, 0, 1),
+ (0b1111111011010, 13, 41, 0, 0),
+ (0b1111111101101100, 16, 18, 0, 1),
+ (0b1111111011011, 13, 13, 1, 0),
+ (0b1111111101101101, 16, 19, 0, 1),
+ (0b1111111011100, 13, 14, 1, 0),
+ (0b1111111101101110, 16, 20, 0, 1),
+ (0b1111111101101111, 16, 21, 0, 1),
+ (0b1111111110101101, 16, 46, 1, 0),
+ (0b1111111101110000, 16, 22, 0, 1),
+ (0b1111111110101110, 16, 47, 1, 0),
+ (0b1111111101110001, 16, 23, 0, 1),
+ (0b1111111110101111, 16, 48, 1, 0),
+ (0b1111111101110010, 16, 24, 0, 1),
+ (0b1111111110110000, 16, 49, 1, 0),
+ (0b1111111101110011, 16, 25, 0, 1),
+ (0b1111111110110001, 16, 50, 1, 0),
+ (0b1111111101110100, 16, 26, 0, 1),
+ (0b1111111110110010, 16, 51, 1, 0),
+ (0b1111111101110101, 16, 27, 0, 1),
+ (0b1111111110110011, 16, 52, 1, 0),
+ (0b1111111101110110, 16, 28, 0, 1),
+ (0b1111111110110100, 16, 53, 1, 0),
+ (0b1111111101110111, 16, 29, 0, 1),
+ (0b1111111110110101, 16, 54, 1, 0),
+ (0b1111111101111000, 16, 30, 0, 1),
+ (0b1111111110110110, 16, 55, 1, 0),
+ (0b1111111101111001, 16, 31, 0, 1),
+ (0b1111111110110111, 16, 56, 1, 0),
+ (0b1111111101111010, 16, 32, 0, 1),
+ (0b1111111110111000, 16, 57, 1, 0),
+ (0b1111111101111011, 16, 33, 0, 1),
+ (0b1111111110111001, 16, 58, 1, 0),
+ (0b1111111101111100, 16, 34, 0, 1),
+ (0b1111111110111010, 16, 59, 1, 0),
+ (0b1111111101111101, 16, 35, 0, 1),
+ (0b1111111110111011, 16, 60, 1, 0),
+ (0b1111111101111110, 16, 36, 0, 1),
+ (0b1111111110111100, 16, 61, 1, 0),
+ (0b1111111101111111, 16, 37, 0, 1),
+ (0b1111111110111101, 16, 62, 1, 0),
+ (0b1111111110000000, 16, 38, 0, 1),
+ (0b1111111110111110, 16, 63, 1, 0),
+ (0b1111111110000001, 16, 39, 0, 1),
+ (0b1111111110111111, 16, 64, 1, 0),
+ (0b1111111110000010, 16, 40, 0, 1),
+ (0b1111111111000000, 16, 1, 1, 1),
+ (0b1111111110000011, 16, 41, 0, 1),
+ (0b1111111111000001, 16, 2, 1, 1),
+ (0b1111111110000100, 16, 42, 0, 1),
+ (0b1111111111000010, 16, 3, 1, 1),
+ (0b1111111110000101, 16, 43, 0, 1),
+ (0b1111111111000011, 16, 4, 1, 1),
+ (0b1111111110000110, 16, 44, 0, 1),
+ (0b1111111111000100, 16, 5, 1, 1),
+ (0b1111111110000111, 16, 45, 0, 1),
+ (0b1111111111000101, 16, 6, 1, 1),
+ (0b1111111110001000, 16, 46, 0, 1),
+ (0b1111111111000110, 16, 7, 1, 1),
+ (0b1111111110001001, 16, 47, 0, 1),
+ (0b1111111111000111, 16, 8, 1, 1),
+ (0b1111111110001010, 16, 48, 0, 1),
+ (0b1111111111001000, 16, 9, 1, 1),
+ (0b1111111110001011, 16, 49, 0, 1),
+ (0b1111111111001001, 16, 10, 1, 1),
+ (0b1111111110001100, 16, 50, 0, 1),
+ (0b1111111111001010, 16, 11, 1, 1),
+ (0b1111111110001101, 16, 51, 0, 1),
+ (0b1111111111001011, 16, 12, 1, 1),
+ (0b1111111110001110, 16, 52, 0, 1),
+ (0b1111111111001100, 16, 13, 1, 1),
+ (0b1111111110001111, 16, 53, 0, 1),
+ (0b1111111111001101, 16, 14, 1, 1),
+ (0b1111111110010000, 16, 54, 0, 1),
+ (0b1111111111001110, 16, 15, 1, 1),
+ (0b1111111110010001, 16, 55, 0, 1),
+ (0b1111111111001111, 16, 16, 1, 1),
+ (0b1111111110010010, 16, 56, 0, 1),
+ (0b1111111111010000, 16, 17, 1, 1),
+ (0b1111111110010011, 16, 57, 0, 1),
+ (0b1111111111010001, 16, 18, 1, 1),
+ (0b1111111110010100, 16, 58, 0, 1),
+ (0b1111111111010010, 16, 19, 1, 1),
+ (0b1111111110010101, 16, 59, 0, 1),
+ (0b1111111111010011, 16, 20, 1, 1),
+ (0b1111111110010110, 16, 60, 0, 1),
+ (0b1111111111010100, 16, 21, 1, 1),
+ (0b1111111110010111, 16, 61, 0, 1),
+ (0b1111111111010101, 16, 22, 1, 1),
+ (0b1111111110011000, 16, 62, 0, 1),
+ (0b1111111111010110, 16, 23, 1, 1),
+ (0b1111111110011001, 16, 63, 0, 1),
+ (0b1111111111010111, 16, 24, 1, 1),
+ (0b1111111110011010, 16, 64, 0, 1),
+ (0b1111111111011000, 16, 25, 1, 1),
+ (0b1111111110011011, 16, 28, 1, 0),
+ (0b1111111111011001, 16, 26, 1, 1),
+ (0b1111111110011100, 16, 29, 1, 0),
+ (0b1111111111011010, 16, 27, 1, 1),
+ (0b1111111110011101, 16, 30, 1, 0),
+ (0b1111111111011011, 16, 28, 1, 1),
+ (0b1111111110011110, 16, 31, 1, 0),
+ (0b1111111111011100, 16, 29, 1, 1),
+ (0b1111111110011111, 16, 32, 1, 0),
+ (0b1111111111011101, 16, 30, 1, 1),
+ (0b1111111110100000, 16, 33, 1, 0),
+ (0b1111111111011110, 16, 31, 1, 1),
+ (0b1111111110100001, 16, 34, 1, 0),
+ (0b1111111111011111, 16, 32, 1, 1),
+ (0b1111111110100010, 16, 35, 1, 0),
+ (0b1111111111100000, 16, 33, 1, 1),
+ (0b1111111110100011, 16, 36, 1, 0),
+ (0b1111111111100001, 16, 34, 1, 1),
+ (0b1111111110100100, 16, 37, 1, 0),
+ (0b1111111111100010, 16, 35, 1, 1),
+ (0b1111111110100101, 16, 38, 1, 0),
+ (0b1111111111100011, 16, 36, 1, 1),
+ (0b1111111110100110, 16, 39, 1, 0),
+ (0b1111111111100100, 16, 37, 1, 1),
+ (0b1111111110100111, 16, 40, 1, 0),
+ (0b1111111111100101, 16, 38, 1, 1),
+ (0b1111111110101000, 16, 41, 1, 0),
+ (0b1111111111100110, 16, 39, 1, 1),
+ (0b1111111110101001, 16, 42, 1, 0),
+ (0b1111111111100111, 16, 40, 1, 1),
+ (0b1111111110101010, 16, 43, 1, 0),
+ (0b1111111111101000, 16, 41, 1, 1),
+ (0b1111111110101011, 16, 44, 1, 0),
+ (0b1111111111101001, 16, 42, 1, 1),
+ (0b1111111110101100, 16, 45, 1, 0),
+ (0b1111111111101010, 16, 43, 1, 1),
+ (0b1111111111101011, 16, 44, 1, 1),
+ (0b1111111111110110, 16, 55, 1, 1),
+ (0b1111111111101100, 16, 45, 1, 1),
+ (0b1111111111110111, 16, 56, 1, 1),
+ (0b1111111111101101, 16, 46, 1, 1),
+ (0b1111111111111000, 16, 57, 1, 1),
+ (0b1111111111101110, 16, 47, 1, 1),
+ (0b1111111111111001, 16, 58, 1, 1),
+ (0b1111111111101111, 16, 48, 1, 1),
+ (0b1111111111111010, 16, 59, 1, 1),
+ (0b1111111111110000, 16, 49, 1, 1),
+ (0b1111111111111011, 16, 60, 1, 1),
+ (0b1111111111110001, 16, 50, 1, 1),
+ (0b1111111111111100, 16, 61, 1, 1),
+ (0b1111111111110010, 16, 51, 1, 1),
+ (0b1111111111111101, 16, 62, 1, 1),
+ (0b1111111111110011, 16, 52, 1, 1),
+ (0b1111111111111110, 16, 63, 1, 1),
+ (0b1111111111110100, 16, 53, 1, 1),
+ (0b1111111111111111, 16, 64, 1, 1),
+ (0b1111111111110101, 16, 54, 1, 1),
+];
+/// Table E.5: (codeword, length, run).
+pub const RUN_E_4: [(u16, u8, u8); 62] = [
+ (0b0, 1, 1),
+ (0b1111100001, 10, 25),
+ (0b100, 3, 2),
+ (0b1111100010, 10, 26),
+ (0b1010, 4, 3),
+ (0b1111100011, 10, 27),
+ (0b1011, 4, 4),
+ (0b1111100100, 10, 28),
+ (0b11000, 5, 5),
+ (0b1111100101, 10, 29),
+ (0b11001, 5, 6),
+ (0b1111100110, 10, 30),
+ (0b11010, 5, 7),
+ (0b1111100111, 10, 31),
+ (0b110110, 6, 8),
+ (0b1111101000, 10, 32),
+ (0b110111, 6, 9),
+ (0b1111101001, 10, 33),
+ (0b111000, 6, 10),
+ (0b1111101010, 10, 34),
+ (0b111001, 6, 11),
+ (0b1111101011, 10, 35),
+ (0b111010, 6, 12),
+ (0b1111101100, 10, 36),
+ (0b1110110, 7, 13),
+ (0b1111101101, 10, 37),
+ (0b1110111, 7, 14),
+ (0b1111101110, 10, 38),
+ (0b11110000, 8, 15),
+ (0b1111101111, 10, 39),
+ (0b111100010, 9, 16),
+ (0b1111110000, 10, 40),
+ (0b111100011, 9, 17),
+ (0b1111110001, 10, 41),
+ (0b111100100, 9, 18),
+ (0b1111110010, 10, 42),
+ (0b111100101, 9, 19),
+ (0b1111110011, 10, 43),
+ (0b111100110, 9, 20),
+ (0b1111110100, 10, 44),
+ (0b111100111, 9, 21),
+ (0b1111110101, 10, 45),
+ (0b111101000, 9, 53),
+ (0b1111110110, 10, 46),
+ (0b111101001, 9, 57),
+ (0b1111110111, 10, 47),
+ (0b111101010, 9, 58),
+ (0b1111111000, 10, 48),
+ (0b111101011, 9, 59),
+ (0b1111111001, 10, 49),
+ (0b111101100, 9, 60),
+ (0b1111111010, 10, 50),
+ (0b111101101, 9, 61),
+ (0b1111111011, 10, 51),
+ (0b111101110, 9, 62),
+ (0b1111111100, 10, 52),
+ (0b1111011110, 10, 22),
+ (0b1111111101, 10, 54),
+ (0b1111011111, 10, 23),
+ (0b1111111110, 10, 55),
+ (0b1111100000, 10, 24),
+ (0b1111111111, 10, 56),
+];
+/// Table E.6: (codeword, length) indexed by the DC size (eta).
+pub const DC_E_4: [(u16, u8); 12] =
+ [(0b000, 3), (0b1100, 4), (0b1101, 4), (0b001, 3), (0b010, 3), (0b011, 3), (0b100, 3), (0b101, 3), (0b1110, 4), (0b11110, 5), (0b111110, 6), (0b111111, 6)];
+
+/// Table E.7: (codeword, length, amplitude (0 = EOB), Frun, Findex).
+pub const AMP_E_7: [(u16, u8, u8, u8, u8); 257] = [
+ (0b00, 2, 1, 0, 0),
+ (0b111111011111, 12, 45, 0, 0),
+ (0b01, 2, 1, 1, 0),
+ (0b111111100000, 12, 46, 0, 0),
+ (0b100, 3, 2, 0, 0),
+ (0b111111100001, 12, 47, 0, 0),
+ (0b1010, 4, 3, 0, 0),
+ (0b111111100010, 12, 48, 0, 0),
+ (0b1011, 4, 0, 0, 0),
+ (0b111111100011, 12, 12, 1, 0),
+ (0b11000, 5, 4, 0, 0),
+ (0b111111100100, 12, 13, 1, 0),
+ (0b11001, 5, 5, 0, 0),
+ (0b111111100101, 12, 14, 1, 0),
+ (0b11010, 5, 2, 1, 0),
+ (0b1111111001100, 13, 49, 0, 0),
+ (0b110110, 6, 6, 0, 0),
+ (0b1111111001101, 13, 50, 0, 0),
+ (0b110111, 6, 7, 0, 0),
+ (0b1111111001110, 13, 51, 0, 0),
+ (0b111000, 6, 8, 0, 0),
+ (0b1111111001111, 13, 52, 0, 0),
+ (0b111001, 6, 3, 1, 0),
+ (0b1111111010000, 13, 53, 0, 0),
+ (0b1110100, 7, 9, 0, 0),
+ (0b1111111010001, 13, 54, 0, 0),
+ (0b1110101, 7, 10, 0, 0),
+ (0b1111111010010, 13, 55, 0, 0),
+ (0b1110110, 7, 11, 0, 0),
+ (0b1111111010011, 13, 56, 0, 0),
+ (0b1110111, 7, 4, 1, 0),
+ (0b1111111010100, 13, 57, 0, 0),
+ (0b11110000, 8, 12, 0, 0),
+ (0b1111111010101, 13, 58, 0, 0),
+ (0b11110001, 8, 13, 0, 0),
+ (0b1111111010110, 13, 59, 0, 0),
+ (0b11110010, 8, 14, 0, 0),
+ (0b1111111010111, 13, 60, 0, 0),
+ (0b11110011, 8, 15, 0, 0),
+ (0b1111111011000, 13, 61, 0, 0),
+ (0b11110100, 8, 16, 0, 0),
+ (0b1111111011001, 13, 15, 1, 0),
+ (0b11110101, 8, 5, 1, 0),
+ (0b1111111011010, 13, 16, 1, 0),
+ (0b111101100, 9, 17, 0, 0),
+ (0b1111111011011, 13, 17, 1, 0),
+ (0b111101101, 9, 18, 0, 0),
+ (0b1111111011100, 13, 18, 1, 0),
+ (0b111101110, 9, 19, 0, 0),
+ (0b11111110111010, 14, 62, 0, 0),
+ (0b111101111, 9, 20, 0, 0),
+ (0b11111110111011, 14, 63, 0, 0),
+ (0b111110000, 9, 21, 0, 0),
+ (0b11111110111100, 14, 64, 0, 0),
+ (0b111110001, 9, 22, 0, 0),
+ (0b11111110111101, 14, 1, 0, 1),
+ (0b111110010, 9, 6, 1, 0),
+ (0b11111110111110, 14, 2, 0, 1),
+ (0b111110011, 9, 7, 1, 0),
+ (0b11111110111111, 14, 3, 0, 1),
+ (0b1111101000, 10, 23, 0, 0),
+ (0b11111111000000, 14, 4, 0, 1),
+ (0b1111101001, 10, 24, 0, 0),
+ (0b11111111000001, 14, 5, 0, 1),
+ (0b1111101010, 10, 25, 0, 0),
+ (0b11111111000010, 14, 6, 0, 1),
+ (0b1111101011, 10, 26, 0, 0),
+ (0b11111111000011, 14, 7, 0, 1),
+ (0b1111101100, 10, 27, 0, 0),
+ (0b11111111000100, 14, 8, 0, 1),
+ (0b1111101101, 10, 28, 0, 0),
+ (0b11111111000101, 14, 9, 0, 1),
+ (0b1111101110, 10, 29, 0, 0),
+ (0b11111111000110, 14, 10, 0, 1),
+ (0b1111101111, 10, 8, 1, 0),
+ (0b11111111000111, 14, 11, 0, 1),
+ (0b1111110000, 10, 9, 1, 0),
+ (0b11111111001000, 14, 12, 0, 1),
+ (0b11111100010, 11, 30, 0, 0),
+ (0b11111111001001, 14, 13, 0, 1),
+ (0b11111100011, 11, 31, 0, 0),
+ (0b11111111001010, 14, 14, 0, 1),
+ (0b11111100100, 11, 32, 0, 0),
+ (0b11111111001011, 14, 15, 0, 1),
+ (0b11111100101, 11, 33, 0, 0),
+ (0b11111111001100, 14, 16, 0, 1),
+ (0b11111100110, 11, 34, 0, 0),
+ (0b11111111001101, 14, 19, 1, 0),
+ (0b11111100111, 11, 35, 0, 0),
+ (0b11111111001110, 14, 20, 1, 0),
+ (0b11111101000, 11, 36, 0, 0),
+ (0b11111111001111, 14, 21, 1, 0),
+ (0b11111101001, 11, 37, 0, 0),
+ (0b11111111010000, 14, 22, 1, 0),
+ (0b11111101010, 11, 10, 1, 0),
+ (0b11111111010001, 14, 23, 1, 0),
+ (0b11111101011, 11, 11, 1, 0),
+ (0b11111111010010, 14, 24, 1, 0),
+ (0b111111011000, 12, 38, 0, 0),
+ (0b111111110100110, 15, 17, 0, 1),
+ (0b111111011001, 12, 39, 0, 0),
+ (0b111111110100111, 15, 18, 0, 1),
+ (0b111111011010, 12, 40, 0, 0),
+ (0b111111110101000, 15, 19, 0, 1),
+ (0b111111011011, 12, 41, 0, 0),
+ (0b111111110101001, 15, 20, 0, 1),
+ (0b111111011100, 12, 42, 0, 0),
+ (0b111111110101010, 15, 21, 0, 1),
+ (0b111111011101, 12, 43, 0, 0),
+ (0b111111110101011, 15, 22, 0, 1),
+ (0b111111011110, 12, 44, 0, 0),
+ (0b111111110101100, 15, 23, 0, 1),
+ (0b111111110101101, 15, 24, 0, 1),
+ (0b1111111110101101, 16, 46, 1, 0),
+ (0b111111110101110, 15, 25, 0, 1),
+ (0b1111111110101110, 16, 47, 1, 0),
+ (0b111111110101111, 15, 26, 0, 1),
+ (0b1111111110101111, 16, 48, 1, 0),
+ (0b111111110110000, 15, 27, 0, 1),
+ (0b1111111110110000, 16, 49, 1, 0),
+ (0b111111110110001, 15, 28, 0, 1),
+ (0b1111111110110001, 16, 50, 1, 0),
+ (0b111111110110010, 15, 29, 0, 1),
+ (0b1111111110110010, 16, 51, 1, 0),
+ (0b111111110110011, 15, 30, 0, 1),
+ (0b1111111110110011, 16, 52, 1, 0),
+ (0b111111110110100, 15, 31, 0, 1),
+ (0b1111111110110100, 16, 53, 1, 0),
+ (0b111111110110101, 15, 32, 0, 1),
+ (0b1111111110110101, 16, 54, 1, 0),
+ (0b111111110110110, 15, 33, 0, 1),
+ (0b1111111110110110, 16, 55, 1, 0),
+ (0b111111110110111, 15, 34, 0, 1),
+ (0b1111111110110111, 16, 56, 1, 0),
+ (0b111111110111000, 15, 35, 0, 1),
+ (0b1111111110111000, 16, 57, 1, 0),
+ (0b111111110111001, 15, 36, 0, 1),
+ (0b1111111110111001, 16, 58, 1, 0),
+ (0b111111110111010, 15, 37, 0, 1),
+ (0b1111111110111010, 16, 59, 1, 0),
+ (0b111111110111011, 15, 40, 0, 1),
+ (0b1111111110111011, 16, 60, 1, 0),
+ (0b111111110111100, 15, 25, 1, 0),
+ (0b1111111110111100, 16, 61, 1, 0),
+ (0b111111110111101, 15, 26, 1, 0),
+ (0b1111111110111101, 16, 62, 1, 0),
+ (0b111111110111110, 15, 27, 1, 0),
+ (0b1111111110111110, 16, 63, 1, 0),
+ (0b111111110111111, 15, 28, 1, 0),
+ (0b1111111110111111, 16, 64, 1, 0),
+ (0b111111111000000, 15, 29, 1, 0),
+ (0b1111111111000000, 16, 1, 1, 1),
+ (0b111111111000001, 15, 30, 1, 0),
+ (0b1111111111000001, 16, 2, 1, 1),
+ (0b1111111110000100, 16, 38, 0, 1),
+ (0b1111111111000010, 16, 3, 1, 1),
+ (0b1111111110000101, 16, 39, 0, 1),
+ (0b1111111111000011, 16, 4, 1, 1),
+ (0b1111111110000110, 16, 41, 0, 1),
+ (0b1111111111000100, 16, 5, 1, 1),
+ (0b1111111110000111, 16, 42, 0, 1),
+ (0b1111111111000101, 16, 6, 1, 1),
+ (0b1111111110001000, 16, 43, 0, 1),
+ (0b1111111111000110, 16, 7, 1, 1),
+ (0b1111111110001001, 16, 44, 0, 1),
+ (0b1111111111000111, 16, 8, 1, 1),
+ (0b1111111110001010, 16, 45, 0, 1),
+ (0b1111111111001000, 16, 9, 1, 1),
+ (0b1111111110001011, 16, 46, 0, 1),
+ (0b1111111111001001, 16, 10, 1, 1),
+ (0b1111111110001100, 16, 47, 0, 1),
+ (0b1111111111001010, 16, 11, 1, 1),
+ (0b1111111110001101, 16, 48, 0, 1),
+ (0b1111111111001011, 16, 12, 1, 1),
+ (0b1111111110001110, 16, 49, 0, 1),
+ (0b1111111111001100, 16, 13, 1, 1),
+ (0b1111111110001111, 16, 50, 0, 1),
+ (0b1111111111001101, 16, 14, 1, 1),
+ (0b1111111110010000, 16, 51, 0, 1),
+ (0b1111111111001110, 16, 15, 1, 1),
+ (0b1111111110010001, 16, 52, 0, 1),
+ (0b1111111111001111, 16, 16, 1, 1),
+ (0b1111111110010010, 16, 53, 0, 1),
+ (0b1111111111010000, 16, 17, 1, 1),
+ (0b1111111110010011, 16, 54, 0, 1),
+ (0b1111111111010001, 16, 18, 1, 1),
+ (0b1111111110010100, 16, 55, 0, 1),
+ (0b1111111111010010, 16, 19, 1, 1),
+ (0b1111111110010101, 16, 56, 0, 1),
+ (0b1111111111010011, 16, 20, 1, 1),
+ (0b1111111110010110, 16, 57, 0, 1),
+ (0b1111111111010100, 16, 21, 1, 1),
+ (0b1111111110010111, 16, 58, 0, 1),
+ (0b1111111111010101, 16, 22, 1, 1),
+ (0b1111111110011000, 16, 59, 0, 1),
+ (0b1111111111010110, 16, 23, 1, 1),
+ (0b1111111110011001, 16, 60, 0, 1),
+ (0b1111111111010111, 16, 24, 1, 1),
+ (0b1111111110011010, 16, 61, 0, 1),
+ (0b1111111111011000, 16, 25, 1, 1),
+ (0b1111111110011011, 16, 62, 0, 1),
+ (0b1111111111011001, 16, 26, 1, 1),
+ (0b1111111110011100, 16, 63, 0, 1),
+ (0b1111111111011010, 16, 27, 1, 1),
+ (0b1111111110011101, 16, 64, 0, 1),
+ (0b1111111111011011, 16, 28, 1, 1),
+ (0b1111111110011110, 16, 31, 1, 0),
+ (0b1111111111011100, 16, 29, 1, 1),
+ (0b1111111110011111, 16, 32, 1, 0),
+ (0b1111111111011101, 16, 30, 1, 1),
+ (0b1111111110100000, 16, 33, 1, 0),
+ (0b1111111111011110, 16, 31, 1, 1),
+ (0b1111111110100001, 16, 34, 1, 0),
+ (0b1111111111011111, 16, 32, 1, 1),
+ (0b1111111110100010, 16, 35, 1, 0),
+ (0b1111111111100000, 16, 33, 1, 1),
+ (0b1111111110100011, 16, 36, 1, 0),
+ (0b1111111111100001, 16, 34, 1, 1),
+ (0b1111111110100100, 16, 37, 1, 0),
+ (0b1111111111100010, 16, 35, 1, 1),
+ (0b1111111110100101, 16, 38, 1, 0),
+ (0b1111111111100011, 16, 36, 1, 1),
+ (0b1111111110100110, 16, 39, 1, 0),
+ (0b1111111111100100, 16, 37, 1, 1),
+ (0b1111111110100111, 16, 40, 1, 0),
+ (0b1111111111100101, 16, 38, 1, 1),
+ (0b1111111110101000, 16, 41, 1, 0),
+ (0b1111111111100110, 16, 39, 1, 1),
+ (0b1111111110101001, 16, 42, 1, 0),
+ (0b1111111111100111, 16, 40, 1, 1),
+ (0b1111111110101010, 16, 43, 1, 0),
+ (0b1111111111101000, 16, 41, 1, 1),
+ (0b1111111110101011, 16, 44, 1, 0),
+ (0b1111111111101001, 16, 42, 1, 1),
+ (0b1111111110101100, 16, 45, 1, 0),
+ (0b1111111111101010, 16, 43, 1, 1),
+ (0b1111111111101011, 16, 44, 1, 1),
+ (0b1111111111110110, 16, 55, 1, 1),
+ (0b1111111111101100, 16, 45, 1, 1),
+ (0b1111111111110111, 16, 56, 1, 1),
+ (0b1111111111101101, 16, 46, 1, 1),
+ (0b1111111111111000, 16, 57, 1, 1),
+ (0b1111111111101110, 16, 47, 1, 1),
+ (0b1111111111111001, 16, 58, 1, 1),
+ (0b1111111111101111, 16, 48, 1, 1),
+ (0b1111111111111010, 16, 59, 1, 1),
+ (0b1111111111110000, 16, 49, 1, 1),
+ (0b1111111111111011, 16, 60, 1, 1),
+ (0b1111111111110001, 16, 50, 1, 1),
+ (0b1111111111111100, 16, 61, 1, 1),
+ (0b1111111111110010, 16, 51, 1, 1),
+ (0b1111111111111101, 16, 62, 1, 1),
+ (0b1111111111110011, 16, 52, 1, 1),
+ (0b1111111111111110, 16, 63, 1, 1),
+ (0b1111111111110100, 16, 53, 1, 1),
+ (0b1111111111111111, 16, 64, 1, 1),
+ (0b1111111111110101, 16, 54, 1, 1),
+];
+/// Table E.8: (codeword, length, run).
+pub const RUN_E_7: [(u16, u8, u8); 62] = [
+ (0b0, 1, 1),
+ (0b1111100001, 10, 32),
+ (0b100, 3, 2),
+ (0b1111100010, 10, 33),
+ (0b1010, 4, 3),
+ (0b1111100011, 10, 34),
+ (0b1011, 4, 4),
+ (0b1111100100, 10, 35),
+ (0b11000, 5, 5),
+ (0b1111100101, 10, 36),
+ (0b11001, 5, 6),
+ (0b1111100110, 10, 37),
+ (0b11010, 5, 7),
+ (0b1111100111, 10, 38),
+ (0b11011, 5, 8),
+ (0b1111101000, 10, 39),
+ (0b111000, 6, 9),
+ (0b1111101001, 10, 40),
+ (0b111001, 6, 10),
+ (0b1111101010, 10, 41),
+ (0b111010, 6, 11),
+ (0b1111101011, 10, 42),
+ (0b111011, 6, 12),
+ (0b1111101100, 10, 43),
+ (0b1111000, 7, 13),
+ (0b1111101101, 10, 44),
+ (0b11110010, 8, 14),
+ (0b1111101110, 10, 45),
+ (0b111100110, 9, 15),
+ (0b1111101111, 10, 46),
+ (0b111100111, 9, 16),
+ (0b1111110000, 10, 47),
+ (0b111101000, 9, 20),
+ (0b1111110001, 10, 48),
+ (0b111101001, 9, 21),
+ (0b1111110010, 10, 49),
+ (0b1111010100, 10, 17),
+ (0b1111110011, 10, 50),
+ (0b1111010101, 10, 18),
+ (0b1111110100, 10, 51),
+ (0b1111010110, 10, 19),
+ (0b1111110101, 10, 52),
+ (0b1111010111, 10, 22),
+ (0b1111110110, 10, 53),
+ (0b1111011000, 10, 23),
+ (0b1111110111, 10, 54),
+ (0b1111011001, 10, 24),
+ (0b1111111000, 10, 55),
+ (0b1111011010, 10, 25),
+ (0b1111111001, 10, 56),
+ (0b1111011011, 10, 26),
+ (0b1111111010, 10, 57),
+ (0b1111011100, 10, 27),
+ (0b1111111011, 10, 58),
+ (0b1111011101, 10, 28),
+ (0b1111111100, 10, 59),
+ (0b1111011110, 10, 29),
+ (0b1111111101, 10, 60),
+ (0b1111011111, 10, 30),
+ (0b1111111110, 10, 61),
+ (0b1111100000, 10, 31),
+ (0b1111111111, 10, 62),
+];
+/// Table E.9: (codeword, length) indexed by the DC size (eta).
+pub const DC_E_7: [(u16, u8); 12] =
+ [(0b000, 3), (0b1100, 4), (0b1101, 4), (0b001, 3), (0b010, 3), (0b011, 3), (0b100, 3), (0b101, 3), (0b1110, 4), (0b11110, 5), (0b111110, 6), (0b111111, 6)];
+
+/// Table E.10: (codeword, length, amplitude (0 = EOB), Frun, Findex).
+pub const AMP_E_10: [(u16, u8, u8, u8, u8); 257] = [
+ (0b00, 2, 1, 0, 0),
+ (0b111111011011, 12, 47, 0, 0),
+ (0b01, 2, 1, 1, 0),
+ (0b111111011100, 12, 48, 0, 0),
+ (0b100, 3, 2, 0, 0),
+ (0b111111011101, 12, 49, 0, 0),
+ (0b1010, 4, 3, 0, 0),
+ (0b111111011110, 12, 50, 0, 0),
+ (0b1011, 4, 0, 0, 0),
+ (0b111111011111, 12, 51, 0, 0),
+ (0b11000, 5, 4, 0, 0),
+ (0b111111100000, 12, 52, 0, 0),
+ (0b11001, 5, 5, 0, 0),
+ (0b111111100001, 12, 11, 1, 0),
+ (0b11010, 5, 2, 1, 0),
+ (0b111111100010, 12, 12, 1, 0),
+ (0b110110, 6, 6, 0, 0),
+ (0b111111100011, 12, 13, 1, 0),
+ (0b110111, 6, 7, 0, 0),
+ (0b1111111001000, 13, 53, 0, 0),
+ (0b111000, 6, 8, 0, 0),
+ (0b1111111001001, 13, 54, 0, 0),
+ (0b111001, 6, 3, 1, 0),
+ (0b1111111001010, 13, 55, 0, 0),
+ (0b1110100, 7, 9, 0, 0),
+ (0b1111111001011, 13, 56, 0, 0),
+ (0b1110101, 7, 10, 0, 0),
+ (0b1111111001100, 13, 57, 0, 0),
+ (0b1110110, 7, 11, 0, 0),
+ (0b1111111001101, 13, 58, 0, 0),
+ (0b1110111, 7, 4, 1, 0),
+ (0b1111111001110, 13, 59, 0, 0),
+ (0b11110000, 8, 12, 0, 0),
+ (0b1111111001111, 13, 60, 0, 0),
+ (0b11110001, 8, 13, 0, 0),
+ (0b1111111010000, 13, 61, 0, 0),
+ (0b11110010, 8, 14, 0, 0),
+ (0b1111111010001, 13, 62, 0, 0),
+ (0b11110011, 8, 15, 0, 0),
+ (0b1111111010010, 13, 63, 0, 0),
+ (0b11110100, 8, 16, 0, 0),
+ (0b1111111010011, 13, 64, 0, 0),
+ (0b11110101, 8, 5, 1, 0),
+ (0b1111111010100, 13, 1, 0, 1),
+ (0b111101100, 9, 17, 0, 0),
+ (0b1111111010101, 13, 2, 0, 1),
+ (0b111101101, 9, 18, 0, 0),
+ (0b1111111010110, 13, 3, 0, 1),
+ (0b111101110, 9, 19, 0, 0),
+ (0b1111111010111, 13, 4, 0, 1),
+ (0b111101111, 9, 20, 0, 0),
+ (0b1111111011000, 13, 5, 0, 1),
+ (0b111110000, 9, 21, 0, 0),
+ (0b1111111011001, 13, 14, 1, 0),
+ (0b111110001, 9, 22, 0, 0),
+ (0b1111111011010, 13, 15, 1, 0),
+ (0b111110010, 9, 6, 1, 0),
+ (0b1111111011011, 13, 16, 1, 0),
+ (0b1111100110, 10, 23, 0, 0),
+ (0b1111111011100, 13, 17, 1, 0),
+ (0b1111100111, 10, 24, 0, 0),
+ (0b11111110111010, 14, 6, 0, 1),
+ (0b1111101000, 10, 25, 0, 0),
+ (0b11111110111011, 14, 7, 0, 1),
+ (0b1111101001, 10, 26, 0, 0),
+ (0b11111110111100, 14, 8, 0, 1),
+ (0b1111101010, 10, 27, 0, 0),
+ (0b11111110111101, 14, 9, 0, 1),
+ (0b1111101011, 10, 28, 0, 0),
+ (0b11111110111110, 14, 10, 0, 1),
+ (0b1111101100, 10, 29, 0, 0),
+ (0b11111110111111, 14, 11, 0, 1),
+ (0b1111101101, 10, 7, 1, 0),
+ (0b11111111000000, 14, 12, 0, 1),
+ (0b1111101110, 10, 8, 1, 0),
+ (0b11111111000001, 14, 13, 0, 1),
+ (0b11111011110, 11, 30, 0, 0),
+ (0b11111111000010, 14, 14, 0, 1),
+ (0b11111011111, 11, 31, 0, 0),
+ (0b11111111000011, 14, 15, 0, 1),
+ (0b11111100000, 11, 32, 0, 0),
+ (0b11111111000100, 14, 16, 0, 1),
+ (0b11111100001, 11, 33, 0, 0),
+ (0b11111111000101, 14, 17, 0, 1),
+ (0b11111100010, 11, 34, 0, 0),
+ (0b11111111000110, 14, 18, 0, 1),
+ (0b11111100011, 11, 35, 0, 0),
+ (0b11111111000111, 14, 19, 0, 1),
+ (0b11111100100, 11, 36, 0, 0),
+ (0b11111111001000, 14, 20, 0, 1),
+ (0b11111100101, 11, 37, 0, 0),
+ (0b11111111001001, 14, 21, 0, 1),
+ (0b11111100110, 11, 38, 0, 0),
+ (0b11111111001010, 14, 22, 0, 1),
+ (0b11111100111, 11, 39, 0, 0),
+ (0b11111111001011, 14, 23, 0, 1),
+ (0b11111101000, 11, 9, 1, 0),
+ (0b11111111001100, 14, 24, 0, 1),
+ (0b11111101001, 11, 10, 1, 0),
+ (0b11111111001101, 14, 25, 0, 1),
+ (0b111111010100, 12, 40, 0, 0),
+ (0b11111111001110, 14, 26, 0, 1),
+ (0b111111010101, 12, 41, 0, 0),
+ (0b11111111001111, 14, 18, 1, 0),
+ (0b111111010110, 12, 42, 0, 0),
+ (0b11111111010000, 14, 19, 1, 0),
+ (0b111111010111, 12, 43, 0, 0),
+ (0b11111111010001, 14, 20, 1, 0),
+ (0b111111011000, 12, 44, 0, 0),
+ (0b11111111010010, 14, 21, 1, 0),
+ (0b111111011001, 12, 45, 0, 0),
+ (0b111111110100110, 15, 27, 0, 1),
+ (0b111111011010, 12, 46, 0, 0),
+ (0b111111110100111, 15, 28, 0, 1),
+ (0b111111110101000, 15, 29, 0, 1),
+ (0b1111111110101111, 16, 48, 1, 0),
+ (0b111111110101001, 15, 30, 0, 1),
+ (0b1111111110110000, 16, 49, 1, 0),
+ (0b111111110101010, 15, 31, 0, 1),
+ (0b1111111110110001, 16, 50, 1, 0),
+ (0b111111110101011, 15, 32, 0, 1),
+ (0b1111111110110010, 16, 51, 1, 0),
+ (0b111111110101100, 15, 33, 0, 1),
+ (0b1111111110110011, 16, 52, 1, 0),
+ (0b111111110101101, 15, 34, 0, 1),
+ (0b1111111110110100, 16, 53, 1, 0),
+ (0b111111110101110, 15, 35, 0, 1),
+ (0b1111111110110101, 16, 54, 1, 0),
+ (0b111111110101111, 15, 36, 0, 1),
+ (0b1111111110110110, 16, 55, 1, 0),
+ (0b111111110110000, 15, 37, 0, 1),
+ (0b1111111110110111, 16, 56, 1, 0),
+ (0b111111110110001, 15, 38, 0, 1),
+ (0b1111111110111000, 16, 57, 1, 0),
+ (0b111111110110010, 15, 39, 0, 1),
+ (0b1111111110111001, 16, 58, 1, 0),
+ (0b111111110110011, 15, 40, 0, 1),
+ (0b1111111110111010, 16, 59, 1, 0),
+ (0b111111110110100, 15, 41, 0, 1),
+ (0b1111111110111011, 16, 60, 1, 0),
+ (0b111111110110101, 15, 42, 0, 1),
+ (0b1111111110111100, 16, 61, 1, 0),
+ (0b111111110110110, 15, 43, 0, 1),
+ (0b1111111110111101, 16, 62, 1, 0),
+ (0b111111110110111, 15, 44, 0, 1),
+ (0b1111111110111110, 16, 63, 1, 0),
+ (0b111111110111000, 15, 45, 0, 1),
+ (0b1111111110111111, 16, 64, 1, 0),
+ (0b111111110111001, 15, 46, 0, 1),
+ (0b1111111111000000, 16, 1, 1, 1),
+ (0b111111110111010, 15, 47, 0, 1),
+ (0b1111111111000001, 16, 2, 1, 1),
+ (0b111111110111011, 15, 48, 0, 1),
+ (0b1111111111000010, 16, 3, 1, 1),
+ (0b111111110111100, 15, 49, 0, 1),
+ (0b1111111111000011, 16, 4, 1, 1),
+ (0b111111110111101, 15, 50, 0, 1),
+ (0b1111111111000100, 16, 5, 1, 1),
+ (0b111111110111110, 15, 51, 0, 1),
+ (0b1111111111000101, 16, 6, 1, 1),
+ (0b111111110111111, 15, 52, 0, 1),
+ (0b1111111111000110, 16, 7, 1, 1),
+ (0b111111111000000, 15, 53, 0, 1),
+ (0b1111111111000111, 16, 8, 1, 1),
+ (0b111111111000001, 15, 55, 0, 1),
+ (0b1111111111001000, 16, 9, 1, 1),
+ (0b111111111000010, 15, 56, 0, 1),
+ (0b1111111111001001, 16, 10, 1, 1),
+ (0b111111111000011, 15, 22, 1, 0),
+ (0b1111111111001010, 16, 11, 1, 1),
+ (0b111111111000100, 15, 23, 1, 0),
+ (0b1111111111001011, 16, 12, 1, 1),
+ (0b111111111000101, 15, 24, 1, 0),
+ (0b1111111111001100, 16, 13, 1, 1),
+ (0b111111111000110, 15, 25, 1, 0),
+ (0b1111111111001101, 16, 14, 1, 1),
+ (0b111111111000111, 15, 26, 1, 0),
+ (0b1111111111001110, 16, 15, 1, 1),
+ (0b111111111001000, 15, 27, 1, 0),
+ (0b1111111111001111, 16, 16, 1, 1),
+ (0b1111111110010010, 16, 54, 0, 1),
+ (0b1111111111010000, 16, 17, 1, 1),
+ (0b1111111110010011, 16, 57, 0, 1),
+ (0b1111111111010001, 16, 18, 1, 1),
+ (0b1111111110010100, 16, 58, 0, 1),
+ (0b1111111111010010, 16, 19, 1, 1),
+ (0b1111111110010101, 16, 59, 0, 1),
+ (0b1111111111010011, 16, 20, 1, 1),
+ (0b1111111110010110, 16, 60, 0, 1),
+ (0b1111111111010100, 16, 21, 1, 1),
+ (0b1111111110010111, 16, 61, 0, 1),
+ (0b1111111111010101, 16, 22, 1, 1),
+ (0b1111111110011000, 16, 62, 0, 1),
+ (0b1111111111010110, 16, 23, 1, 1),
+ (0b1111111110011001, 16, 63, 0, 1),
+ (0b1111111111010111, 16, 24, 1, 1),
+ (0b1111111110011010, 16, 64, 0, 1),
+ (0b1111111111011000, 16, 25, 1, 1),
+ (0b1111111110011011, 16, 28, 1, 0),
+ (0b1111111111011001, 16, 26, 1, 1),
+ (0b1111111110011100, 16, 29, 1, 0),
+ (0b1111111111011010, 16, 27, 1, 1),
+ (0b1111111110011101, 16, 30, 1, 0),
+ (0b1111111111011011, 16, 28, 1, 1),
+ (0b1111111110011110, 16, 31, 1, 0),
+ (0b1111111111011100, 16, 29, 1, 1),
+ (0b1111111110011111, 16, 32, 1, 0),
+ (0b1111111111011101, 16, 30, 1, 1),
+ (0b1111111110100000, 16, 33, 1, 0),
+ (0b1111111111011110, 16, 31, 1, 1),
+ (0b1111111110100001, 16, 34, 1, 0),
+ (0b1111111111011111, 16, 32, 1, 1),
+ (0b1111111110100010, 16, 35, 1, 0),
+ (0b1111111111100000, 16, 33, 1, 1),
+ (0b1111111110100011, 16, 36, 1, 0),
+ (0b1111111111100001, 16, 34, 1, 1),
+ (0b1111111110100100, 16, 37, 1, 0),
+ (0b1111111111100010, 16, 35, 1, 1),
+ (0b1111111110100101, 16, 38, 1, 0),
+ (0b1111111111100011, 16, 36, 1, 1),
+ (0b1111111110100110, 16, 39, 1, 0),
+ (0b1111111111100100, 16, 37, 1, 1),
+ (0b1111111110100111, 16, 40, 1, 0),
+ (0b1111111111100101, 16, 38, 1, 1),
+ (0b1111111110101000, 16, 41, 1, 0),
+ (0b1111111111100110, 16, 39, 1, 1),
+ (0b1111111110101001, 16, 42, 1, 0),
+ (0b1111111111100111, 16, 40, 1, 1),
+ (0b1111111110101010, 16, 43, 1, 0),
+ (0b1111111111101000, 16, 41, 1, 1),
+ (0b1111111110101011, 16, 44, 1, 0),
+ (0b1111111111101001, 16, 42, 1, 1),
+ (0b1111111110101100, 16, 45, 1, 0),
+ (0b1111111111101010, 16, 43, 1, 1),
+ (0b1111111110101101, 16, 46, 1, 0),
+ (0b1111111111101011, 16, 44, 1, 1),
+ (0b1111111110101110, 16, 47, 1, 0),
+ (0b1111111111101100, 16, 45, 1, 1),
+ (0b1111111111101101, 16, 46, 1, 1),
+ (0b1111111111110111, 16, 56, 1, 1),
+ (0b1111111111101110, 16, 47, 1, 1),
+ (0b1111111111111000, 16, 57, 1, 1),
+ (0b1111111111101111, 16, 48, 1, 1),
+ (0b1111111111111001, 16, 58, 1, 1),
+ (0b1111111111110000, 16, 49, 1, 1),
+ (0b1111111111111010, 16, 59, 1, 1),
+ (0b1111111111110001, 16, 50, 1, 1),
+ (0b1111111111111011, 16, 60, 1, 1),
+ (0b1111111111110010, 16, 51, 1, 1),
+ (0b1111111111111100, 16, 61, 1, 1),
+ (0b1111111111110011, 16, 52, 1, 1),
+ (0b1111111111111101, 16, 62, 1, 1),
+ (0b1111111111110100, 16, 53, 1, 1),
+ (0b1111111111111110, 16, 63, 1, 1),
+ (0b1111111111110101, 16, 54, 1, 1),
+ (0b1111111111111111, 16, 64, 1, 1),
+ (0b1111111111110110, 16, 55, 1, 1),
+];
+/// Table E.11: (codeword, length, run).
+pub const RUN_E_10: [(u16, u8, u8); 62] = [
+ (0b0, 1, 1),
+ (0b1111100001, 10, 32),
+ (0b100, 3, 2),
+ (0b1111100010, 10, 33),
+ (0b101, 3, 3),
+ (0b1111100011, 10, 34),
+ (0b1100, 4, 4),
+ (0b1111100100, 10, 35),
+ (0b11010, 5, 5),
+ (0b1111100101, 10, 36),
+ (0b11011, 5, 6),
+ (0b1111100110, 10, 37),
+ (0b11100, 5, 7),
+ (0b1111100111, 10, 38),
+ (0b111010, 6, 8),
+ (0b1111101000, 10, 39),
+ (0b1110110, 7, 9),
+ (0b1111101001, 10, 40),
+ (0b1110111, 7, 10),
+ (0b1111101010, 10, 41),
+ (0b1111000, 7, 11),
+ (0b1111101011, 10, 42),
+ (0b11110010, 8, 12),
+ (0b1111101100, 10, 43),
+ (0b111100110, 9, 13),
+ (0b1111101101, 10, 44),
+ (0b111100111, 9, 14),
+ (0b1111101110, 10, 45),
+ (0b1111010000, 10, 15),
+ (0b1111101111, 10, 46),
+ (0b1111010001, 10, 16),
+ (0b1111110000, 10, 47),
+ (0b1111010010, 10, 17),
+ (0b1111110001, 10, 48),
+ (0b1111010011, 10, 18),
+ (0b1111110010, 10, 49),
+ (0b1111010100, 10, 19),
+ (0b1111110011, 10, 50),
+ (0b1111010101, 10, 20),
+ (0b1111110100, 10, 51),
+ (0b1111010110, 10, 21),
+ (0b1111110101, 10, 52),
+ (0b1111010111, 10, 22),
+ (0b1111110110, 10, 53),
+ (0b1111011000, 10, 23),
+ (0b1111110111, 10, 54),
+ (0b1111011001, 10, 24),
+ (0b1111111000, 10, 55),
+ (0b1111011010, 10, 25),
+ (0b1111111001, 10, 56),
+ (0b1111011011, 10, 26),
+ (0b1111111010, 10, 57),
+ (0b1111011100, 10, 27),
+ (0b1111111011, 10, 58),
+ (0b1111011101, 10, 28),
+ (0b1111111100, 10, 59),
+ (0b1111011110, 10, 29),
+ (0b1111111101, 10, 60),
+ (0b1111011111, 10, 30),
+ (0b1111111110, 10, 61),
+ (0b1111100000, 10, 31),
+ (0b1111111111, 10, 62),
+];
+/// Table E.12: (codeword, length) indexed by the DC size (eta).
+pub const DC_E_10: [(u16, u8); 14] = [
+ (0b1010, 4),
+ (0b111110, 6),
+ (0b1011, 4),
+ (0b1100, 4),
+ (0b1101, 4),
+ (0b000, 3),
+ (0b001, 3),
+ (0b010, 3),
+ (0b011, 3),
+ (0b100, 3),
+ (0b1110, 4),
+ (0b11110, 5),
+ (0b1111110, 7),
+ (0b1111111, 7),
+];
+
+/// Table E.13: (codeword, length, amplitude (0 = EOB), Frun, Findex).
+pub const AMP_E_13: [(u16, u8, u8, u8, u8); 257] = [
+ (0b00, 2, 1, 0, 0),
+ (0b111111011000, 12, 45, 0, 0),
+ (0b01, 2, 1, 1, 0),
+ (0b111111011001, 12, 46, 0, 0),
+ (0b100, 3, 2, 0, 0),
+ (0b111111011010, 12, 47, 0, 0),
+ (0b1010, 4, 3, 0, 0),
+ (0b111111011011, 12, 48, 0, 0),
+ (0b1011, 4, 0, 0, 0),
+ (0b111111011100, 12, 49, 0, 0),
+ (0b11000, 5, 4, 0, 0),
+ (0b111111011101, 12, 50, 0, 0),
+ (0b11001, 5, 5, 0, 0),
+ (0b111111011110, 12, 51, 0, 0),
+ (0b11010, 5, 2, 1, 0),
+ (0b111111011111, 12, 52, 0, 0),
+ (0b110110, 6, 6, 0, 0),
+ (0b111111100000, 12, 12, 1, 0),
+ (0b110111, 6, 7, 0, 0),
+ (0b111111100001, 12, 13, 1, 0),
+ (0b111000, 6, 8, 0, 0),
+ (0b111111100010, 12, 14, 1, 0),
+ (0b111001, 6, 3, 1, 0),
+ (0b1111111000110, 13, 53, 0, 0),
+ (0b1110100, 7, 9, 0, 0),
+ (0b1111111000111, 13, 54, 0, 0),
+ (0b1110101, 7, 10, 0, 0),
+ (0b1111111001000, 13, 55, 0, 0),
+ (0b1110110, 7, 11, 0, 0),
+ (0b1111111001001, 13, 56, 0, 0),
+ (0b1110111, 7, 4, 1, 0),
+ (0b1111111001010, 13, 57, 0, 0),
+ (0b11110000, 8, 12, 0, 0),
+ (0b1111111001011, 13, 58, 0, 0),
+ (0b11110001, 8, 13, 0, 0),
+ (0b1111111001100, 13, 59, 0, 0),
+ (0b11110010, 8, 14, 0, 0),
+ (0b1111111001101, 13, 60, 0, 0),
+ (0b11110011, 8, 15, 0, 0),
+ (0b1111111001110, 13, 61, 0, 0),
+ (0b11110100, 8, 16, 0, 0),
+ (0b1111111001111, 13, 62, 0, 0),
+ (0b11110101, 8, 5, 1, 0),
+ (0b1111111010000, 13, 63, 0, 0),
+ (0b111101100, 9, 17, 0, 0),
+ (0b1111111010001, 13, 64, 0, 0),
+ (0b111101101, 9, 18, 0, 0),
+ (0b1111111010010, 13, 1, 0, 1),
+ (0b111101110, 9, 19, 0, 0),
+ (0b1111111010011, 13, 2, 0, 1),
+ (0b111101111, 9, 20, 0, 0),
+ (0b1111111010100, 13, 3, 0, 1),
+ (0b111110000, 9, 21, 0, 0),
+ (0b1111111010101, 13, 4, 0, 1),
+ (0b111110001, 9, 6, 1, 0),
+ (0b1111111010110, 13, 5, 0, 1),
+ (0b1111100100, 10, 22, 0, 0),
+ (0b1111111010111, 13, 6, 0, 1),
+ (0b1111100101, 10, 23, 0, 0),
+ (0b1111111011000, 13, 7, 0, 1),
+ (0b1111100110, 10, 24, 0, 0),
+ (0b1111111011001, 13, 8, 0, 1),
+ (0b1111100111, 10, 25, 0, 0),
+ (0b1111111011010, 13, 15, 1, 0),
+ (0b1111101000, 10, 26, 0, 0),
+ (0b1111111011011, 13, 16, 1, 0),
+ (0b1111101001, 10, 27, 0, 0),
+ (0b1111111011100, 13, 17, 1, 0),
+ (0b1111101010, 10, 28, 0, 0),
+ (0b11111110111010, 14, 9, 0, 1),
+ (0b1111101011, 10, 29, 0, 0),
+ (0b11111110111011, 14, 10, 0, 1),
+ (0b1111101100, 10, 7, 1, 0),
+ (0b11111110111100, 14, 11, 0, 1),
+ (0b1111101101, 10, 8, 1, 0),
+ (0b11111110111101, 14, 12, 0, 1),
+ (0b11111011100, 11, 30, 0, 0),
+ (0b11111110111110, 14, 13, 0, 1),
+ (0b11111011101, 11, 31, 0, 0),
+ (0b11111110111111, 14, 14, 0, 1),
+ (0b11111011110, 11, 32, 0, 0),
+ (0b11111111000000, 14, 15, 0, 1),
+ (0b11111011111, 11, 33, 0, 0),
+ (0b11111111000001, 14, 16, 0, 1),
+ (0b11111100000, 11, 34, 0, 0),
+ (0b11111111000010, 14, 17, 0, 1),
+ (0b11111100001, 11, 35, 0, 0),
+ (0b11111111000011, 14, 18, 0, 1),
+ (0b11111100010, 11, 36, 0, 0),
+ (0b11111111000100, 14, 19, 0, 1),
+ (0b11111100011, 11, 37, 0, 0),
+ (0b11111111000101, 14, 20, 0, 1),
+ (0b11111100100, 11, 38, 0, 0),
+ (0b11111111000110, 14, 21, 0, 1),
+ (0b11111100101, 11, 39, 0, 0),
+ (0b11111111000111, 14, 22, 0, 1),
+ (0b11111100110, 11, 40, 0, 0),
+ (0b11111111001000, 14, 23, 0, 1),
+ (0b11111100111, 11, 9, 1, 0),
+ (0b11111111001001, 14, 24, 0, 1),
+ (0b11111101000, 11, 10, 1, 0),
+ (0b11111111001010, 14, 25, 0, 1),
+ (0b11111101001, 11, 11, 1, 0),
+ (0b11111111001011, 14, 26, 0, 1),
+ (0b111111010100, 12, 41, 0, 0),
+ (0b11111111001100, 14, 27, 0, 1),
+ (0b111111010101, 12, 42, 0, 0),
+ (0b11111111001101, 14, 28, 0, 1),
+ (0b111111010110, 12, 43, 0, 0),
+ (0b11111111001110, 14, 29, 0, 1),
+ (0b111111010111, 12, 44, 0, 0),
+ (0b11111111001111, 14, 18, 1, 0),
+ (0b11111111010000, 14, 19, 1, 0),
+ (0b1111111110101101, 16, 46, 1, 0),
+ (0b11111111010001, 14, 20, 1, 0),
+ (0b1111111110101110, 16, 47, 1, 0),
+ (0b11111111010010, 14, 21, 1, 0),
+ (0b1111111110101111, 16, 48, 1, 0),
+ (0b11111111010011, 14, 22, 1, 0),
+ (0b1111111110110000, 16, 49, 1, 0),
+ (0b111111110101000, 15, 30, 0, 1),
+ (0b1111111110110001, 16, 50, 1, 0),
+ (0b111111110101001, 15, 31, 0, 1),
+ (0b1111111110110010, 16, 51, 1, 0),
+ (0b111111110101010, 15, 32, 0, 1),
+ (0b1111111110110011, 16, 52, 1, 0),
+ (0b111111110101011, 15, 33, 0, 1),
+ (0b1111111110110100, 16, 53, 1, 0),
+ (0b111111110101100, 15, 34, 0, 1),
+ (0b1111111110110101, 16, 54, 1, 0),
+ (0b111111110101101, 15, 35, 0, 1),
+ (0b1111111110110110, 16, 55, 1, 0),
+ (0b111111110101110, 15, 36, 0, 1),
+ (0b1111111110110111, 16, 56, 1, 0),
+ (0b111111110101111, 15, 37, 0, 1),
+ (0b1111111110111000, 16, 57, 1, 0),
+ (0b111111110110000, 15, 38, 0, 1),
+ (0b1111111110111001, 16, 58, 1, 0),
+ (0b111111110110001, 15, 39, 0, 1),
+ (0b1111111110111010, 16, 59, 1, 0),
+ (0b111111110110010, 15, 40, 0, 1),
+ (0b1111111110111011, 16, 60, 1, 0),
+ (0b111111110110011, 15, 41, 0, 1),
+ (0b1111111110111100, 16, 61, 1, 0),
+ (0b111111110110100, 15, 42, 0, 1),
+ (0b1111111110111101, 16, 62, 1, 0),
+ (0b111111110110101, 15, 43, 0, 1),
+ (0b1111111110111110, 16, 63, 1, 0),
+ (0b111111110110110, 15, 44, 0, 1),
+ (0b1111111110111111, 16, 64, 1, 0),
+ (0b111111110110111, 15, 45, 0, 1),
+ (0b1111111111000000, 16, 1, 1, 1),
+ (0b111111110111000, 15, 46, 0, 1),
+ (0b1111111111000001, 16, 2, 1, 1),
+ (0b111111110111001, 15, 47, 0, 1),
+ (0b1111111111000010, 16, 3, 1, 1),
+ (0b111111110111010, 15, 48, 0, 1),
+ (0b1111111111000011, 16, 4, 1, 1),
+ (0b111111110111011, 15, 49, 0, 1),
+ (0b1111111111000100, 16, 5, 1, 1),
+ (0b111111110111100, 15, 50, 0, 1),
+ (0b1111111111000101, 16, 6, 1, 1),
+ (0b111111110111101, 15, 51, 0, 1),
+ (0b1111111111000110, 16, 7, 1, 1),
+ (0b111111110111110, 15, 52, 0, 1),
+ (0b1111111111000111, 16, 8, 1, 1),
+ (0b111111110111111, 15, 53, 0, 1),
+ (0b1111111111001000, 16, 9, 1, 1),
+ (0b111111111000000, 15, 54, 0, 1),
+ (0b1111111111001001, 16, 10, 1, 1),
+ (0b111111111000001, 15, 55, 0, 1),
+ (0b1111111111001010, 16, 11, 1, 1),
+ (0b111111111000010, 15, 56, 0, 1),
+ (0b1111111111001011, 16, 12, 1, 1),
+ (0b111111111000011, 15, 57, 0, 1),
+ (0b1111111111001100, 16, 13, 1, 1),
+ (0b111111111000100, 15, 58, 0, 1),
+ (0b1111111111001101, 16, 14, 1, 1),
+ (0b111111111000101, 15, 23, 1, 0),
+ (0b1111111111001110, 16, 15, 1, 1),
+ (0b111111111000110, 15, 24, 1, 0),
+ (0b1111111111001111, 16, 16, 1, 1),
+ (0b111111111000111, 15, 25, 1, 0),
+ (0b1111111111010000, 16, 17, 1, 1),
+ (0b111111111001000, 15, 26, 1, 0),
+ (0b1111111111010001, 16, 18, 1, 1),
+ (0b111111111001001, 15, 27, 1, 0),
+ (0b1111111111010010, 16, 19, 1, 1),
+ (0b111111111001010, 15, 28, 1, 0),
+ (0b1111111111010011, 16, 20, 1, 1),
+ (0b1111111110010110, 16, 59, 0, 1),
+ (0b1111111111010100, 16, 21, 1, 1),
+ (0b1111111110010111, 16, 60, 0, 1),
+ (0b1111111111010101, 16, 22, 1, 1),
+ (0b1111111110011000, 16, 61, 0, 1),
+ (0b1111111111010110, 16, 23, 1, 1),
+ (0b1111111110011001, 16, 62, 0, 1),
+ (0b1111111111010111, 16, 24, 1, 1),
+ (0b1111111110011010, 16, 63, 0, 1),
+ (0b1111111111011000, 16, 25, 1, 1),
+ (0b1111111110011011, 16, 64, 0, 1),
+ (0b1111111111011001, 16, 26, 1, 1),
+ (0b1111111110011100, 16, 29, 1, 0),
+ (0b1111111111011010, 16, 27, 1, 1),
+ (0b1111111110011101, 16, 30, 1, 0),
+ (0b1111111111011011, 16, 28, 1, 1),
+ (0b1111111110011110, 16, 31, 1, 0),
+ (0b1111111111011100, 16, 29, 1, 1),
+ (0b1111111110011111, 16, 32, 1, 0),
+ (0b1111111111011101, 16, 30, 1, 1),
+ (0b1111111110100000, 16, 33, 1, 0),
+ (0b1111111111011110, 16, 31, 1, 1),
+ (0b1111111110100001, 16, 34, 1, 0),
+ (0b1111111111011111, 16, 32, 1, 1),
+ (0b1111111110100010, 16, 35, 1, 0),
+ (0b1111111111100000, 16, 33, 1, 1),
+ (0b1111111110100011, 16, 36, 1, 0),
+ (0b1111111111100001, 16, 34, 1, 1),
+ (0b1111111110100100, 16, 37, 1, 0),
+ (0b1111111111100010, 16, 35, 1, 1),
+ (0b1111111110100101, 16, 38, 1, 0),
+ (0b1111111111100011, 16, 36, 1, 1),
+ (0b1111111110100110, 16, 39, 1, 0),
+ (0b1111111111100100, 16, 37, 1, 1),
+ (0b1111111110100111, 16, 40, 1, 0),
+ (0b1111111111100101, 16, 38, 1, 1),
+ (0b1111111110101000, 16, 41, 1, 0),
+ (0b1111111111100110, 16, 39, 1, 1),
+ (0b1111111110101001, 16, 42, 1, 0),
+ (0b1111111111100111, 16, 40, 1, 1),
+ (0b1111111110101010, 16, 43, 1, 0),
+ (0b1111111111101000, 16, 41, 1, 1),
+ (0b1111111110101011, 16, 44, 1, 0),
+ (0b1111111111101001, 16, 42, 1, 1),
+ (0b1111111110101100, 16, 45, 1, 0),
+ (0b1111111111101010, 16, 43, 1, 1),
+ (0b1111111111101011, 16, 44, 1, 1),
+ (0b1111111111110110, 16, 55, 1, 1),
+ (0b1111111111101100, 16, 45, 1, 1),
+ (0b1111111111110111, 16, 56, 1, 1),
+ (0b1111111111101101, 16, 46, 1, 1),
+ (0b1111111111111000, 16, 57, 1, 1),
+ (0b1111111111101110, 16, 47, 1, 1),
+ (0b1111111111111001, 16, 58, 1, 1),
+ (0b1111111111101111, 16, 48, 1, 1),
+ (0b1111111111111010, 16, 59, 1, 1),
+ (0b1111111111110000, 16, 49, 1, 1),
+ (0b1111111111111011, 16, 60, 1, 1),
+ (0b1111111111110001, 16, 50, 1, 1),
+ (0b1111111111111100, 16, 61, 1, 1),
+ (0b1111111111110010, 16, 51, 1, 1),
+ (0b1111111111111101, 16, 62, 1, 1),
+ (0b1111111111110011, 16, 52, 1, 1),
+ (0b1111111111111110, 16, 63, 1, 1),
+ (0b1111111111110100, 16, 53, 1, 1),
+ (0b1111111111111111, 16, 64, 1, 1),
+ (0b1111111111110101, 16, 54, 1, 1),
+];
+/// Table E.14: (codeword, length, run).
+pub const RUN_E_13: [(u16, u8, u8); 62] = [
+ (0b0, 1, 1),
+ (0b1111100001, 10, 32),
+ (0b100, 3, 2),
+ (0b1111100010, 10, 33),
+ (0b101, 3, 3),
+ (0b1111100011, 10, 34),
+ (0b1100, 4, 4),
+ (0b1111100100, 10, 35),
+ (0b11010, 5, 5),
+ (0b1111100101, 10, 36),
+ (0b11011, 5, 6),
+ (0b1111100110, 10, 37),
+ (0b11100, 5, 7),
+ (0b1111100111, 10, 38),
+ (0b111010, 6, 8),
+ (0b1111101000, 10, 39),
+ (0b1110110, 7, 9),
+ (0b1111101001, 10, 40),
+ (0b1110111, 7, 10),
+ (0b1111101010, 10, 41),
+ (0b1111000, 7, 11),
+ (0b1111101011, 10, 42),
+ (0b11110010, 8, 12),
+ (0b1111101100, 10, 43),
+ (0b111100110, 9, 13),
+ (0b1111101101, 10, 44),
+ (0b111100111, 9, 14),
+ (0b1111101110, 10, 45),
+ (0b1111010000, 10, 15),
+ (0b1111101111, 10, 46),
+ (0b1111010001, 10, 16),
+ (0b1111110000, 10, 47),
+ (0b1111010010, 10, 17),
+ (0b1111110001, 10, 48),
+ (0b1111010011, 10, 18),
+ (0b1111110010, 10, 49),
+ (0b1111010100, 10, 19),
+ (0b1111110011, 10, 50),
+ (0b1111010101, 10, 20),
+ (0b1111110100, 10, 51),
+ (0b1111010110, 10, 21),
+ (0b1111110101, 10, 52),
+ (0b1111010111, 10, 22),
+ (0b1111110110, 10, 53),
+ (0b1111011000, 10, 23),
+ (0b1111110111, 10, 54),
+ (0b1111011001, 10, 24),
+ (0b1111111000, 10, 55),
+ (0b1111011010, 10, 25),
+ (0b1111111001, 10, 56),
+ (0b1111011011, 10, 26),
+ (0b1111111010, 10, 57),
+ (0b1111011100, 10, 27),
+ (0b1111111011, 10, 58),
+ (0b1111011101, 10, 28),
+ (0b1111111100, 10, 59),
+ (0b1111011110, 10, 29),
+ (0b1111111101, 10, 60),
+ (0b1111011111, 10, 30),
+ (0b1111111110, 10, 61),
+ (0b1111100000, 10, 31),
+ (0b1111111111, 10, 62),
+];
+/// Table E.15: (codeword, length) indexed by the DC size (eta).
+pub const DC_E_13: [(u16, u8); 12] =
+ [(0b000, 3), (0b1100, 4), (0b1101, 4), (0b001, 3), (0b010, 3), (0b011, 3), (0b100, 3), (0b101, 3), (0b1110, 4), (0b11110, 5), (0b111110, 6), (0b111111, 6)];
+
+/// Table E.16: (codeword, length, amplitude (0 = EOB), Frun, Findex).
+pub const AMP_E_16: [(u16, u8, u8, u8, u8); 257] = [
+ (0b00, 2, 1, 0, 0),
+ (0b1111111010001, 13, 43, 0, 0),
+ (0b01, 2, 1, 1, 0),
+ (0b1111111010010, 13, 44, 0, 0),
+ (0b100, 3, 2, 0, 0),
+ (0b1111111010011, 13, 45, 0, 0),
+ (0b1010, 4, 3, 0, 0),
+ (0b1111111010100, 13, 46, 0, 0),
+ (0b1011, 4, 2, 1, 0),
+ (0b1111111010101, 13, 47, 0, 0),
+ (0b1100, 4, 0, 0, 0),
+ (0b1111111010110, 13, 48, 0, 0),
+ (0b11010, 5, 4, 0, 0),
+ (0b1111111010111, 13, 49, 0, 0),
+ (0b11011, 5, 5, 0, 0),
+ (0b1111111011000, 13, 50, 0, 0),
+ (0b111000, 6, 6, 0, 0),
+ (0b1111111011001, 13, 51, 0, 0),
+ (0b111001, 6, 7, 0, 0),
+ (0b1111111011010, 13, 52, 0, 0),
+ (0b111010, 6, 3, 1, 0),
+ (0b1111111011011, 13, 53, 0, 0),
+ (0b1110110, 7, 8, 0, 0),
+ (0b1111111011100, 13, 14, 1, 0),
+ (0b1110111, 7, 9, 0, 0),
+ (0b1111111011101, 13, 15, 1, 0),
+ (0b1111000, 7, 10, 0, 0),
+ (0b1111111011110, 13, 16, 1, 0),
+ (0b11110010, 8, 11, 0, 0),
+ (0b11111110111110, 14, 54, 0, 0),
+ (0b11110011, 8, 12, 0, 0),
+ (0b11111110111111, 14, 55, 0, 0),
+ (0b11110100, 8, 13, 0, 0),
+ (0b11111111000000, 14, 56, 0, 0),
+ (0b11110101, 8, 14, 0, 0),
+ (0b11111111000001, 14, 57, 0, 0),
+ (0b11110110, 8, 4, 1, 0),
+ (0b11111111000010, 14, 58, 0, 0),
+ (0b11110111, 8, 5, 1, 0),
+ (0b11111111000011, 14, 59, 0, 0),
+ (0b111110000, 9, 15, 0, 0),
+ (0b11111111000100, 14, 60, 0, 0),
+ (0b111110001, 9, 16, 0, 0),
+ (0b11111111000101, 14, 61, 0, 0),
+ (0b111110010, 9, 17, 0, 0),
+ (0b11111111000110, 14, 62, 0, 0),
+ (0b111110011, 9, 18, 0, 0),
+ (0b11111111000111, 14, 63, 0, 0),
+ (0b111110100, 9, 6, 1, 0),
+ (0b11111111001000, 14, 64, 0, 0),
+ (0b1111101010, 10, 19, 0, 0),
+ (0b11111111001001, 14, 1, 0, 1),
+ (0b1111101011, 10, 20, 0, 0),
+ (0b11111111001010, 14, 2, 0, 1),
+ (0b1111101100, 10, 21, 0, 0),
+ (0b11111111001011, 14, 3, 0, 1),
+ (0b1111101101, 10, 22, 0, 0),
+ (0b11111111001100, 14, 17, 1, 0),
+ (0b1111101110, 10, 23, 0, 0),
+ (0b11111111001101, 14, 18, 1, 0),
+ (0b1111101111, 10, 24, 0, 0),
+ (0b11111111001110, 14, 19, 1, 0),
+ (0b1111110000, 10, 7, 1, 0),
+ (0b11111111001111, 14, 20, 1, 0),
+ (0b1111110001, 10, 8, 1, 0),
+ (0b111111110100000, 15, 4, 0, 1),
+ (0b11111100100, 11, 25, 0, 0),
+ (0b111111110100001, 15, 5, 0, 1),
+ (0b11111100101, 11, 26, 0, 0),
+ (0b111111110100010, 15, 6, 0, 1),
+ (0b11111100110, 11, 27, 0, 0),
+ (0b111111110100011, 15, 7, 0, 1),
+ (0b11111100111, 11, 28, 0, 0),
+ (0b111111110100100, 15, 8, 0, 1),
+ (0b11111101000, 11, 29, 0, 0),
+ (0b111111110100101, 15, 9, 0, 1),
+ (0b11111101001, 11, 30, 0, 0),
+ (0b111111110100110, 15, 10, 0, 1),
+ (0b11111101010, 11, 31, 0, 0),
+ (0b111111110100111, 15, 11, 0, 1),
+ (0b11111101011, 11, 32, 0, 0),
+ (0b111111110101000, 15, 12, 0, 1),
+ (0b11111101100, 11, 9, 1, 0),
+ (0b111111110101001, 15, 13, 0, 1),
+ (0b11111101101, 11, 10, 1, 0),
+ (0b111111110101010, 15, 14, 0, 1),
+ (0b111111011100, 12, 33, 0, 0),
+ (0b111111110101011, 15, 15, 0, 1),
+ (0b111111011101, 12, 34, 0, 0),
+ (0b111111110101100, 15, 16, 0, 1),
+ (0b111111011110, 12, 35, 0, 0),
+ (0b111111110101101, 15, 17, 0, 1),
+ (0b111111011111, 12, 36, 0, 0),
+ (0b111111110101110, 15, 18, 0, 1),
+ (0b111111100000, 12, 37, 0, 0),
+ (0b111111110101111, 15, 19, 0, 1),
+ (0b111111100001, 12, 38, 0, 0),
+ (0b111111110110000, 15, 20, 0, 1),
+ (0b111111100010, 12, 39, 0, 0),
+ (0b111111110110001, 15, 21, 0, 1),
+ (0b111111100011, 12, 40, 0, 0),
+ (0b111111110110010, 15, 21, 1, 0),
+ (0b111111100100, 12, 41, 0, 0),
+ (0b111111110110011, 15, 22, 1, 0),
+ (0b111111100101, 12, 11, 1, 0),
+ (0b111111110110100, 15, 23, 1, 0),
+ (0b111111100110, 12, 12, 1, 0),
+ (0b111111110110101, 15, 24, 1, 0),
+ (0b111111100111, 12, 13, 1, 0),
+ (0b111111110110110, 15, 25, 1, 0),
+ (0b1111111010000, 13, 42, 0, 0),
+ (0b1111111101101110, 16, 22, 0, 1),
+ (0b1111111101101111, 16, 23, 0, 1),
+ (0b1111111110101101, 16, 46, 1, 0),
+ (0b1111111101110000, 16, 24, 0, 1),
+ (0b1111111110101110, 16, 47, 1, 0),
+ (0b1111111101110001, 16, 25, 0, 1),
+ (0b1111111110101111, 16, 48, 1, 0),
+ (0b1111111101110010, 16, 26, 0, 1),
+ (0b1111111110110000, 16, 49, 1, 0),
+ (0b1111111101110011, 16, 27, 0, 1),
+ (0b1111111110110001, 16, 50, 1, 0),
+ (0b1111111101110100, 16, 28, 0, 1),
+ (0b1111111110110010, 16, 51, 1, 0),
+ (0b1111111101110101, 16, 29, 0, 1),
+ (0b1111111110110011, 16, 52, 1, 0),
+ (0b1111111101110110, 16, 30, 0, 1),
+ (0b1111111110110100, 16, 53, 1, 0),
+ (0b1111111101110111, 16, 31, 0, 1),
+ (0b1111111110110101, 16, 54, 1, 0),
+ (0b1111111101111000, 16, 32, 0, 1),
+ (0b1111111110110110, 16, 55, 1, 0),
+ (0b1111111101111001, 16, 33, 0, 1),
+ (0b1111111110110111, 16, 56, 1, 0),
+ (0b1111111101111010, 16, 34, 0, 1),
+ (0b1111111110111000, 16, 57, 1, 0),
+ (0b1111111101111011, 16, 35, 0, 1),
+ (0b1111111110111001, 16, 58, 1, 0),
+ (0b1111111101111100, 16, 36, 0, 1),
+ (0b1111111110111010, 16, 59, 1, 0),
+ (0b1111111101111101, 16, 37, 0, 1),
+ (0b1111111110111011, 16, 60, 1, 0),
+ (0b1111111101111110, 16, 38, 0, 1),
+ (0b1111111110111100, 16, 61, 1, 0),
+ (0b1111111101111111, 16, 39, 0, 1),
+ (0b1111111110111101, 16, 62, 1, 0),
+ (0b1111111110000000, 16, 40, 0, 1),
+ (0b1111111110111110, 16, 63, 1, 0),
+ (0b1111111110000001, 16, 41, 0, 1),
+ (0b1111111110111111, 16, 64, 1, 0),
+ (0b1111111110000010, 16, 42, 0, 1),
+ (0b1111111111000000, 16, 1, 1, 1),
+ (0b1111111110000011, 16, 43, 0, 1),
+ (0b1111111111000001, 16, 2, 1, 1),
+ (0b1111111110000100, 16, 44, 0, 1),
+ (0b1111111111000010, 16, 3, 1, 1),
+ (0b1111111110000101, 16, 45, 0, 1),
+ (0b1111111111000011, 16, 4, 1, 1),
+ (0b1111111110000110, 16, 46, 0, 1),
+ (0b1111111111000100, 16, 5, 1, 1),
+ (0b1111111110000111, 16, 47, 0, 1),
+ (0b1111111111000101, 16, 6, 1, 1),
+ (0b1111111110001000, 16, 48, 0, 1),
+ (0b1111111111000110, 16, 7, 1, 1),
+ (0b1111111110001001, 16, 49, 0, 1),
+ (0b1111111111000111, 16, 8, 1, 1),
+ (0b1111111110001010, 16, 50, 0, 1),
+ (0b1111111111001000, 16, 9, 1, 1),
+ (0b1111111110001011, 16, 51, 0, 1),
+ (0b1111111111001001, 16, 10, 1, 1),
+ (0b1111111110001100, 16, 52, 0, 1),
+ (0b1111111111001010, 16, 11, 1, 1),
+ (0b1111111110001101, 16, 53, 0, 1),
+ (0b1111111111001011, 16, 12, 1, 1),
+ (0b1111111110001110, 16, 54, 0, 1),
+ (0b1111111111001100, 16, 13, 1, 1),
+ (0b1111111110001111, 16, 55, 0, 1),
+ (0b1111111111001101, 16, 14, 1, 1),
+ (0b1111111110010000, 16, 56, 0, 1),
+ (0b1111111111001110, 16, 15, 1, 1),
+ (0b1111111110010001, 16, 57, 0, 1),
+ (0b1111111111001111, 16, 16, 1, 1),
+ (0b1111111110010010, 16, 58, 0, 1),
+ (0b1111111111010000, 16, 17, 1, 1),
+ (0b1111111110010011, 16, 59, 0, 1),
+ (0b1111111111010001, 16, 18, 1, 1),
+ (0b1111111110010100, 16, 60, 0, 1),
+ (0b1111111111010010, 16, 19, 1, 1),
+ (0b1111111110010101, 16, 61, 0, 1),
+ (0b1111111111010011, 16, 20, 1, 1),
+ (0b1111111110010110, 16, 62, 0, 1),
+ (0b1111111111010100, 16, 21, 1, 1),
+ (0b1111111110010111, 16, 63, 0, 1),
+ (0b1111111111010101, 16, 22, 1, 1),
+ (0b1111111110011000, 16, 64, 0, 1),
+ (0b1111111111010110, 16, 23, 1, 1),
+ (0b1111111110011001, 16, 26, 1, 0),
+ (0b1111111111010111, 16, 24, 1, 1),
+ (0b1111111110011010, 16, 27, 1, 0),
+ (0b1111111111011000, 16, 25, 1, 1),
+ (0b1111111110011011, 16, 28, 1, 0),
+ (0b1111111111011001, 16, 26, 1, 1),
+ (0b1111111110011100, 16, 29, 1, 0),
+ (0b1111111111011010, 16, 27, 1, 1),
+ (0b1111111110011101, 16, 30, 1, 0),
+ (0b1111111111011011, 16, 28, 1, 1),
+ (0b1111111110011110, 16, 31, 1, 0),
+ (0b1111111111011100, 16, 29, 1, 1),
+ (0b1111111110011111, 16, 32, 1, 0),
+ (0b1111111111011101, 16, 30, 1, 1),
+ (0b1111111110100000, 16, 33, 1, 0),
+ (0b1111111111011110, 16, 31, 1, 1),
+ (0b1111111110100001, 16, 34, 1, 0),
+ (0b1111111111011111, 16, 32, 1, 1),
+ (0b1111111110100010, 16, 35, 1, 0),
+ (0b1111111111100000, 16, 33, 1, 1),
+ (0b1111111110100011, 16, 36, 1, 0),
+ (0b1111111111100001, 16, 34, 1, 1),
+ (0b1111111110100100, 16, 37, 1, 0),
+ (0b1111111111100010, 16, 35, 1, 1),
+ (0b1111111110100101, 16, 38, 1, 0),
+ (0b1111111111100011, 16, 36, 1, 1),
+ (0b1111111110100110, 16, 39, 1, 0),
+ (0b1111111111100100, 16, 37, 1, 1),
+ (0b1111111110100111, 16, 40, 1, 0),
+ (0b1111111111100101, 16, 38, 1, 1),
+ (0b1111111110101000, 16, 41, 1, 0),
+ (0b1111111111100110, 16, 39, 1, 1),
+ (0b1111111110101001, 16, 42, 1, 0),
+ (0b1111111111100111, 16, 40, 1, 1),
+ (0b1111111110101010, 16, 43, 1, 0),
+ (0b1111111111101000, 16, 41, 1, 1),
+ (0b1111111110101011, 16, 44, 1, 0),
+ (0b1111111111101001, 16, 42, 1, 1),
+ (0b1111111110101100, 16, 45, 1, 0),
+ (0b1111111111101010, 16, 43, 1, 1),
+ (0b1111111111101011, 16, 44, 1, 1),
+ (0b1111111111110110, 16, 55, 1, 1),
+ (0b1111111111101100, 16, 45, 1, 1),
+ (0b1111111111110111, 16, 56, 1, 1),
+ (0b1111111111101101, 16, 46, 1, 1),
+ (0b1111111111111000, 16, 57, 1, 1),
+ (0b1111111111101110, 16, 47, 1, 1),
+ (0b1111111111111001, 16, 58, 1, 1),
+ (0b1111111111101111, 16, 48, 1, 1),
+ (0b1111111111111010, 16, 59, 1, 1),
+ (0b1111111111110000, 16, 49, 1, 1),
+ (0b1111111111111011, 16, 60, 1, 1),
+ (0b1111111111110001, 16, 50, 1, 1),
+ (0b1111111111111100, 16, 61, 1, 1),
+ (0b1111111111110010, 16, 51, 1, 1),
+ (0b1111111111111101, 16, 62, 1, 1),
+ (0b1111111111110011, 16, 52, 1, 1),
+ (0b1111111111111110, 16, 63, 1, 1),
+ (0b1111111111110100, 16, 53, 1, 1),
+ (0b1111111111111111, 16, 64, 1, 1),
+ (0b1111111111110101, 16, 54, 1, 1),
+];
+/// Table E.17: (codeword, length, run).
+pub const RUN_E_16: [(u16, u8, u8); 62] = [
+ (0b0, 1, 1),
+ (0b1111100001, 10, 32),
+ (0b100, 3, 2),
+ (0b1111100010, 10, 33),
+ (0b101, 3, 3),
+ (0b1111100011, 10, 34),
+ (0b1100, 4, 4),
+ (0b1111100100, 10, 35),
+ (0b11010, 5, 5),
+ (0b1111100101, 10, 36),
+ (0b11011, 5, 6),
+ (0b1111100110, 10, 37),
+ (0b11100, 5, 7),
+ (0b1111100111, 10, 38),
+ (0b111010, 6, 8),
+ (0b1111101000, 10, 39),
+ (0b1110110, 7, 9),
+ (0b1111101001, 10, 40),
+ (0b1110111, 7, 10),
+ (0b1111101010, 10, 41),
+ (0b1111000, 7, 11),
+ (0b1111101011, 10, 42),
+ (0b11110010, 8, 12),
+ (0b1111101100, 10, 43),
+ (0b111100110, 9, 13),
+ (0b1111101101, 10, 44),
+ (0b111100111, 9, 14),
+ (0b1111101110, 10, 45),
+ (0b1111010000, 10, 15),
+ (0b1111101111, 10, 46),
+ (0b1111010001, 10, 16),
+ (0b1111110000, 10, 47),
+ (0b1111010010, 10, 17),
+ (0b1111110001, 10, 48),
+ (0b1111010011, 10, 18),
+ (0b1111110010, 10, 49),
+ (0b1111010100, 10, 19),
+ (0b1111110011, 10, 50),
+ (0b1111010101, 10, 20),
+ (0b1111110100, 10, 51),
+ (0b1111010110, 10, 21),
+ (0b1111110101, 10, 52),
+ (0b1111010111, 10, 22),
+ (0b1111110110, 10, 53),
+ (0b1111011000, 10, 23),
+ (0b1111110111, 10, 54),
+ (0b1111011001, 10, 24),
+ (0b1111111000, 10, 55),
+ (0b1111011010, 10, 25),
+ (0b1111111001, 10, 56),
+ (0b1111011011, 10, 26),
+ (0b1111111010, 10, 57),
+ (0b1111011100, 10, 27),
+ (0b1111111011, 10, 58),
+ (0b1111011101, 10, 28),
+ (0b1111111100, 10, 59),
+ (0b1111011110, 10, 29),
+ (0b1111111101, 10, 60),
+ (0b1111011111, 10, 30),
+ (0b1111111110, 10, 61),
+ (0b1111100000, 10, 31),
+ (0b1111111111, 10, 62),
+];
+/// Table E.18: (codeword, length) indexed by the DC size (eta).
+pub const DC_E_16: [(u16, u8); 12] =
+ [(0b000, 3), (0b1100, 4), (0b1101, 4), (0b001, 3), (0b010, 3), (0b011, 3), (0b100, 3), (0b101, 3), (0b1110, 4), (0b11110, 5), (0b111110, 6), (0b111111, 6)];
diff --git a/crates/dnx/src/tables.rs b/crates/dnx/src/tables.rs
new file mode 100644
index 000000000..c1fe24909
--- /dev/null
+++ b/crates/dnx/src/tables.rs
@@ -0,0 +1,298 @@
+//! Compression-ID parameters (Annex C), zig-zag order (Figure 48) and VLC lookup tables built from
+//! the Annex E codeword lists in [`crate::spec_tables`].
+
+use crate::spec_tables::*;
+use std::sync::OnceLock;
+
+/// Bitstream coefficient index `r` → raster position `v*8 + u` (Figure 48).
+pub(crate) const ZIGZAG: [u8; 64] = {
+ // Figure 48 printed as a grid: GRID[v][u] = r
+ const GRID: [[u8; 8]; 8] = [
+ [0, 1, 5, 6, 14, 15, 27, 28],
+ [2, 4, 7, 13, 16, 26, 29, 42],
+ [3, 8, 12, 17, 25, 30, 41, 43],
+ [9, 11, 18, 24, 31, 40, 44, 53],
+ [10, 19, 23, 32, 39, 45, 52, 54],
+ [20, 22, 33, 38, 46, 51, 55, 60],
+ [21, 34, 37, 47, 50, 56, 59, 61],
+ [35, 36, 48, 49, 57, 58, 62, 63],
+ ];
+ let mut z = [0u8; 64];
+ let mut v = 0;
+ while v < 8 {
+ let mut u = 0;
+ while u < 8 {
+ z[GRID[v][u] as usize] = (v * 8 + u) as u8;
+ u += 1;
+ }
+ v += 1;
+ }
+ z
+};
+
+/// Raster profile of a compression ID.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Kind {
+ /// HD profile: fixed raster and frame size (Table C.1).
+ Hd { width: u16, height: u16, interlaced: bool, depth: u8, frame_size: u32 },
+ /// Resolution-independent profile (Table C.2): reference frame size C0 for 8160 macroblocks.
+ Ri { c0: u32 },
+}
+
+/// Parameters of one compression ID.
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct CidInfo {
+ pub cid: u32,
+ pub kind: Kind,
+ /// Quantisation weights (Annex D), `[luma, chroma]`, raster order without the DC entry.
+ pub weights: &'static [[u8; 63]; 2],
+ /// VLC table set (index into [`vlc`]): 0 = E.1–E.3, 1 = E.4–E.6, 2 = E.7–E.9, 3 = E.10–E.12,
+ /// 4 = E.13–E.15, 5 = E.16–E.18.
+ pub vlc: usize,
+ /// Inverse quantisation parameter `p` (8.2.7): 8 or 32.
+ pub p: u32,
+}
+
+const fn hd(cid: u32, width: u16, height: u16, interlaced: bool, depth: u8, frame_size: u32, weights: &'static [[u8; 63]; 2], vlc: usize) -> CidInfo {
+ let p = if cid == 1235 || cid == 1241 || cid == 1250 { 8 } else { 32 };
+ CidInfo { cid, kind: Kind::Hd { width, height, interlaced, depth, frame_size }, weights, vlc, p }
+}
+
+const fn ri(cid: u32, c0: u32, weights: &'static [[u8; 63]; 2], vlc: usize) -> CidInfo {
+ CidInfo { cid, kind: Kind::Ri { c0 }, weights, vlc, p: 32 }
+}
+
+/// Every compression ID of SMPTE ST 2019-1:2016 (Tables C.1 and C.2).
+pub(crate) const CIDS: [CidInfo; 20] = [
+ hd(1235, 1920, 1080, false, 10, 917504, &W_D_1, 0),
+ hd(1237, 1920, 1080, false, 8, 606208, &W_D_2, 1),
+ hd(1238, 1920, 1080, false, 8, 917504, &W_D_3, 2),
+ hd(1241, 1920, 1080, true, 10, 917504, &W_D_4, 0),
+ hd(1242, 1920, 1080, true, 8, 606208, &W_D_5, 1),
+ hd(1243, 1920, 1080, true, 8, 917504, &W_D_6, 2),
+ hd(1244, 1440, 1080, true, 8, 606208, &W_D_7, 1),
+ hd(1250, 1280, 720, false, 10, 458752, &W_D_8, 3),
+ hd(1251, 1280, 720, false, 8, 458752, &W_D_9, 4),
+ hd(1252, 1280, 720, false, 8, 303104, &W_D_10, 5),
+ hd(1253, 1920, 1080, false, 8, 188416, &W_D_2, 1),
+ hd(1256, 1920, 1080, false, 10, 1835008, &W_D_11, 0),
+ hd(1258, 960, 720, false, 8, 212992, &W_D_10, 5),
+ hd(1259, 1440, 1080, false, 8, 417792, &W_D_2, 1),
+ hd(1260, 1440, 1080, true, 8, 417792, &W_D_7, 1),
+ ri(1270, 1835008, &W_D_11, 0),
+ ri(1271, 917504, &W_D_4, 0),
+ ri(1272, 917504, &W_D_3, 2),
+ ri(1273, 606208, &W_D_2, 1),
+ ri(1274, 188416, &W_D_2, 1),
+];
+
+pub(crate) fn cid_info(cid: u32) -> Option<&'static CidInfo> {
+ CIDS.iter().find(|c| c.cid == cid)
+}
+
+/// Compressed frame size of an RI raster (equation 7.1 / the `RIsize` pseudo code), without the
+/// alpha factor when `alpha` is false.
+pub fn ri_frame_size(width: u32, height: u32, c0: u32, alpha: bool) -> u32 {
+ let nw = width.div_ceil(16) as u64;
+ let ns = height.div_ceil(16) as u64;
+ let mut size = c0 as u64 * nw * ns / 8160;
+ if alpha {
+ size += size / 2;
+ }
+ let rem = size % 4096;
+ if rem >= 2048 {
+ size += 4096 - rem;
+ } else {
+ size -= rem;
+ }
+ size.max(8192) as u32
+}
+
+/// Two-level VLC lookup table. `primary` is indexed by the next `PRIMARY_BITS` bits; an entry is
+/// either a decoded symbol (`len << 16 | value`, len ≤ PRIMARY_BITS) or a link to a secondary
+/// table (`LINK | sub_bits << 24 | offset`), indexed by the following `sub_bits` bits.
+pub(crate) struct Lut {
+ pub primary: Vec<u32>,
+ pub secondary: Vec<u32>,
+ pub bits: u32,
+}
+
+pub(crate) const LINK: u32 = 1 << 31;
+
+impl Lut {
+ /// `codes`: (codeword, length, value ≤ 0xFFFF).
+ fn build(codes: &[(u32, u32, u32)], bits: u32) -> Lut {
+ let max_len = codes.iter().map(|c| c.1).max().unwrap_or(1);
+ let bits = bits.min(max_len);
+ let mut primary = vec![0u32; 1 << bits];
+ // longest code under each long prefix
+ let mut sub_len = vec![0u32; 1 << bits];
+ for &(code, len, _) in codes {
+ if len > bits {
+ let pre = (code >> (len - bits)) as usize;
+ sub_len[pre] = sub_len[pre].max(len - bits);
+ }
+ }
+ let mut secondary = Vec::new();
+ for pre in 0..1usize << bits {
+ if sub_len[pre] > 0 {
+ let off = secondary.len() as u32;
+ secondary.resize(secondary.len() + (1 << sub_len[pre]), 0);
+ primary[pre] = LINK | sub_len[pre] << 24 | off;
+ }
+ }
+ for &(code, len, value) in codes {
+ if len <= bits {
+ let shift = bits - len;
+ let base = (code << shift) as usize;
+ for e in &mut primary[base..base + (1 << shift)] {
+ *e = len << 16 | value;
+ }
+ } else {
+ let pre = (code >> (len - bits)) as usize;
+ let link = primary[pre];
+ let sb = (link >> 24) & 0x7f;
+ let off = (link & 0xff_ffff) as usize;
+ let rest_len = len - bits;
+ let rest = code & ((1 << rest_len) - 1);
+ let shift = sb - rest_len;
+ let base = off + ((rest << shift) as usize);
+ for e in &mut secondary[base..base + (1 << shift)] {
+ *e = len << 16 | value;
+ }
+ }
+ }
+ Lut { primary, secondary, bits }
+ }
+}
+
+/// Decoded amplitude-table symbol value: `amp | frun << 8 | findex << 9 | eob << 10`.
+pub(crate) const AMP_FRUN: u32 = 1 << 8;
+pub(crate) const AMP_FINDEX: u32 = 1 << 9;
+pub(crate) const AMP_EOB: u32 = 1 << 10;
+
+/// One VLC table set (amplitude, run and DC tables) with decode LUTs and encode maps.
+pub(crate) struct VlcSet {
+ pub amp: Lut,
+ pub run: Lut,
+ pub dc: Lut,
+ /// Encoder: `amp_code[frun][findex][amp-1]` = (codeword, length).
+ pub amp_code: [[[(u16, u8); 64]; 2]; 2],
+ pub eob: (u16, u8),
+ /// Encoder: `run_code[run]` (run 1..=62; index 0 unused).
+ pub run_code: [(u16, u8); 63],
+ pub dc_code: Vec<(u16, u8)>,
+}
+
+fn build_set(amp: &[(u16, u8, u8, u8, u8)], run: &[(u16, u8, u8); 62], dc: &[(u16, u8)]) -> VlcSet {
+ let ac: Vec<(u32, u32, u32)> = amp
+ .iter()
+ .map(|&(c, l, a, fr, fi)| {
+ let v = if a == 0 { AMP_EOB } else { a as u32 | (fr as u32) << 8 | (fi as u32) << 9 };
+ (c as u32, l as u32, v)
+ })
+ .collect();
+ let rc: Vec<(u32, u32, u32)> = run.iter().map(|&(c, l, r)| (c as u32, l as u32, r as u32)).collect();
+ let dcc: Vec<(u32, u32, u32)> = dc.iter().enumerate().map(|(i, &(c, l))| (c as u32, l as u32, i as u32)).collect();
+ let mut amp_code = [[[(0u16, 0u8); 64]; 2]; 2];
+ let mut eob = (0, 0);
+ for &(c, l, a, fr, fi) in amp {
+ if a == 0 {
+ eob = (c, l);
+ } else {
+ amp_code[fr as usize][fi as usize][a as usize - 1] = (c, l);
+ }
+ }
+ let mut run_code = [(0u16, 0u8); 63];
+ for &(c, l, r) in run {
+ run_code[r as usize] = (c, l);
+ }
+ VlcSet { amp: Lut::build(&ac, 11), run: Lut::build(&rc, 10), dc: Lut::build(&dcc, 8), amp_code, eob, run_code, dc_code: dc.to_vec() }
+}
+
+/// The VLC table set `i` (see [`CidInfo::vlc`]), built on first use.
+pub(crate) fn vlc(i: usize) -> &'static VlcSet {
+ static SETS: [OnceLock<VlcSet>; 6] = [const { OnceLock::new() }; 6];
+ SETS[i].get_or_init(|| match i {
+ 0 => build_set(&AMP_E_1, &RUN_E_1, &DC_E_1),
+ 1 => build_set(&AMP_E_4, &RUN_E_4, &DC_E_4),
+ 2 => build_set(&AMP_E_7, &RUN_E_7, &DC_E_7),
+ 3 => build_set(&AMP_E_10, &RUN_E_10, &DC_E_10),
+ 4 => build_set(&AMP_E_13, &RUN_E_13, &DC_E_13),
+ _ => build_set(&AMP_E_16, &RUN_E_16, &DC_E_16),
+ })
+}
+
+/// Orthonormal 1-D DCT-II basis: `BASIS[u][x] = C(u)/2 · cos((2x+1)uπ/16)`, `C(0) = 1/√2`.
+pub(crate) const BASIS: [[f32; 8]; 8] = [
+ [0.353_553_39, 0.353_553_39, 0.353_553_39, 0.353_553_39, 0.353_553_39, 0.353_553_39, 0.353_553_39, 0.353_553_39],
+ [0.490_392_64, 0.415_734_8, 0.277_785_12, 0.097_545_16, -0.097_545_16, -0.277_785_12, -0.415_734_8, -0.490_392_64],
+ [0.461_939_77, 0.191_341_72, -0.191_341_72, -0.461_939_77, -0.461_939_77, -0.191_341_72, 0.191_341_72, 0.461_939_77],
+ [0.415_734_8, -0.097_545_16, -0.490_392_64, -0.277_785_12, 0.277_785_12, 0.490_392_64, 0.097_545_16, -0.415_734_8],
+ [0.353_553_39, -0.353_553_39, -0.353_553_39, 0.353_553_39, 0.353_553_39, -0.353_553_39, -0.353_553_39, 0.353_553_39],
+ [0.277_785_12, -0.490_392_64, 0.097_545_16, 0.415_734_8, -0.415_734_8, -0.097_545_16, 0.490_392_64, -0.277_785_12],
+ [0.191_341_72, -0.461_939_77, 0.461_939_77, -0.191_341_72, -0.191_341_72, 0.461_939_77, -0.461_939_77, 0.191_341_72],
+ [0.097_545_16, -0.277_785_12, 0.415_734_8, -0.490_392_64, 0.490_392_64, -0.415_734_8, 0.277_785_12, -0.097_545_16],
+];
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn zigzag_is_permutation() {
+ let mut seen = [false; 64];
+ for &z in &ZIGZAG {
+ assert!(!seen[z as usize]);
+ seen[z as usize] = true;
+ }
+ assert_eq!(ZIGZAG[1], 1);
+ assert_eq!(ZIGZAG[2], 8);
+ assert_eq!(ZIGZAG[63], 63);
+ }
+
+ #[test]
+ fn ri_size_matches_examples() {
+ // 1080p HQ (1272) has 8160 macroblocks: exactly C0
+ assert_eq!(ri_frame_size(1920, 1080, 917504, false), 917504);
+ // tiny rasters clamp to 8192
+ assert_eq!(ri_frame_size(16, 16, 188416, false), 8192);
+ }
+
+ #[test]
+ fn luts_decode_every_code() {
+ for i in 0..6 {
+ let s = vlc(i);
+ for f in 0..2 {
+ for x in 0..2 {
+ for a in 0..64 {
+ let (c, l) = s.amp_code[f][x][a];
+ assert!(l > 0);
+ let v = lookup(&s.amp, c as u32, l as u32);
+ assert_eq!(v, (a as u32 + 1) | (f as u32) << 8 | (x as u32) << 9);
+ }
+ }
+ }
+ assert_eq!(lookup(&s.amp, s.eob.0 as u32, s.eob.1 as u32), AMP_EOB);
+ for r in 1..63 {
+ let (c, l) = s.run_code[r];
+ assert_eq!(lookup(&s.run, c as u32, l as u32), r as u32);
+ }
+ }
+ }
+
+ fn lookup(t: &Lut, code: u32, len: u32) -> u32 {
+ // left-align the code in a 32-bit window
+ let w = code << (32 - len);
+ let e = t.primary[(w >> (32 - t.bits)) as usize];
+ let e = if e & LINK != 0 {
+ let sb = (e >> 24) & 0x7f;
+ let off = (e & 0xff_ffff) as usize;
+ t.secondary[off + ((w << t.bits) >> (32 - sb)) as usize]
+ } else {
+ e
+ };
+ assert_eq!(e >> 16, len);
+ e & 0xffff
+ }
+}
diff --git a/crates/dnx/tests/common/mod.rs b/crates/dnx/tests/common/mod.rs
new file mode 100644
index 000000000..8af783482
--- /dev/null
+++ b/crates/dnx/tests/common/mod.rs
@@ -0,0 +1,289 @@
+//! Shared helpers for oracle tests. ffmpeg is used only as an external fixture generator and
+//! reference decoder (never linked).
+#![allow(dead_code)]
+
+use filmcraft_dnx::{Frame, probe};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+/// ffmpeg, or `None` after printing `SKIPPED` (see `filmcraft_testkit::oracle`).
+pub fn ffmpeg() -> Option<PathBuf> {
+ filmcraft_testkit::ffmpeg_or_skip("dnx oracle")
+}
+
+pub fn fixture_dir() -> PathBuf {
+ filmcraft_testkit::fixtures_dir("dnx")
+}
+
+pub fn run(ff: &Path, args: &[&str]) {
+ let out = Command::new(ff).args(["-hide_banner", "-loglevel", "error", "-y"]).args(args).output().expect("run ffmpeg");
+ assert!(out.status.success(), "ffmpeg {:?} failed: {}", args, String::from_utf8_lossy(&out.stderr));
+}
+
+/// A DNxHD/DNxHR fixture: a lavfi source encoded by ffmpeg's VC-3 encoder into a MOV.
+pub struct Spec {
+ pub name: &'static str,
+ pub lavfi: String,
+ pub frames: u32,
+ /// Encoder arguments (bitrate / profile, pixel format, flags).
+ pub enc: Vec<&'static str>,
+ /// Raw pixel format of the reference decode.
+ pub pix_fmt: &'static str,
+}
+
+impl Spec {
+ pub fn new(name: &'static str, lavfi: impl Into<String>, frames: u32, enc: &[&'static str], pix_fmt: &'static str) -> Spec {
+ Spec { name, lavfi: lavfi.into(), frames, enc: enc.to_vec(), pix_fmt }
+ }
+}
+
+/// Generate (or reuse) the fixture MOV.
+pub fn make(ff: &Path, spec: &Spec) -> PathBuf {
+ let path = fixture_dir().join(format!("{}.mov", spec.name));
+ if !path.exists() {
+ let tmp = filmcraft_testkit::temp_path(&path);
+ let frames = spec.frames.to_string();
+ let mut args = vec!["-f", "lavfi", "-i", spec.lavfi.as_str(), "-frames:v", frames.as_str(), "-c:v", "dnxhd"];
+ args.extend(spec.enc.iter().copied());
+ args.extend(["-f", "mov"]);
+ let t = tmp.to_str().unwrap().to_string();
+ args.push(&t);
+ run(ff, &args);
+ std::fs::rename(&tmp, &path).unwrap();
+ }
+ path
+}
+
+/// The coded frames of a MOV (ffmpeg's `data` muxer concatenates packets; split them with the
+/// coding-unit sizes from the headers).
+pub fn packets(ff: &Path, mov: &Path) -> Vec<Vec<u8>> {
+ let out = Command::new(ff)
+ .args(["-hide_banner", "-loglevel", "error", "-i"])
+ .arg(mov)
+ .args(["-map", "0:v", "-c", "copy", "-f", "data", "-"])
+ .output()
+ .expect("run ffmpeg");
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ split_frames(&out.stdout)
+}
+
+pub fn split_frames(mut d: &[u8]) -> Vec<Vec<u8>> {
+ let mut v = Vec::new();
+ while d.len() >= 0x280 {
+ let h = probe(d).expect("header");
+ let mut n = h.coding_unit_size().expect("CBR") as usize;
+ if h.interlaced && !h.frame_encoding {
+ n += probe(&d[n..]).expect("second field").coding_unit_size().unwrap() as usize;
+ }
+ v.push(d[..n].to_vec());
+ d = &d[n..];
+ }
+ v
+}
+
+/// Reference-decode a MOV with ffmpeg; samples as u16 (8-bit formats widened).
+pub fn reference(ff: &Path, mov: &Path, pix_fmt: &str) -> Vec<u16> {
+ let out = Command::new(ff)
+ .args(["-hide_banner", "-loglevel", "error", "-i"])
+ .arg(mov)
+ .args(["-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
+ .output()
+ .expect("run ffmpeg");
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ if pix_fmt.ends_with("le") {
+ out.stdout.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect()
+ } else {
+ out.stdout.iter().map(|&b| b as u16).collect()
+ }
+}
+
+#[derive(Default, Clone, Copy, Debug)]
+pub struct Stats {
+ pub max: u32,
+ pub sum: u64,
+ pub n: u64,
+ pub exact: u64,
+ /// Samples off by more than 1.
+ pub over1: u64,
+}
+
+impl Stats {
+ pub fn add(&mut self, a: &[u16], b: &[u16]) {
+ assert_eq!(a.len(), b.len());
+ for (&x, &y) in a.iter().zip(b) {
+ let d = (x as i32 - y as i32).unsigned_abs();
+ self.max = self.max.max(d);
+ self.sum += d as u64;
+ self.n += 1;
+ self.exact += (d == 0) as u64;
+ self.over1 += (d > 1) as u64;
+ }
+ }
+ pub fn merge(&mut self, o: &Stats) {
+ self.max = self.max.max(o.max);
+ self.sum += o.sum;
+ self.n += o.n;
+ self.exact += o.exact;
+ self.over1 += o.over1;
+ }
+ pub fn mean(&self) -> f64 {
+ self.sum as f64 / self.n.max(1) as f64
+ }
+ pub fn exact_pct(&self) -> f64 {
+ 100.0 * self.exact as f64 / self.n.max(1) as f64
+ }
+}
+
+/// Planes in the order of ffmpeg's planar raw output.
+pub fn planes(f: &Frame, pix_fmt: &str) -> Vec<u16> {
+ // RGB frames hold G, B, R in y, cb, cr: the same order as `gbrp`
+ let _ = pix_fmt;
+ let order: Vec<&Vec<u16>> = vec![&f.y, &f.cb, &f.cr];
+ order.into_iter().chain(f.alpha.as_ref()).flat_map(|p| p.iter().copied()).collect()
+}
+
+/// Samples per frame of a raw reference image.
+pub fn frame_samples(f: &Frame) -> usize {
+ let n = f.width as usize * f.height as usize;
+ let c = f.chroma_width() as usize * f.chroma_height() as usize;
+ n + 2 * c + if f.alpha.is_some() { n } else { 0 }
+}
+
+pub fn psnr(a: &[u16], b: &[u16], peak: f64) -> f64 {
+ let mse: f64 = a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).powi(2)).sum::<f64>() / a.len() as f64;
+ if mse == 0.0 { 99.0 } else { 10.0 * (peak * peak / mse).log10() }
+}
+
+fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
+ let mut v = Vec::with_capacity(payload.len() + 8);
+ v.extend_from_slice(&((payload.len() + 8) as u32).to_be_bytes());
+ v.extend_from_slice(kind);
+ v.extend_from_slice(payload);
+ v
+}
+const MATRIX: [u32; 9] = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000];
+/// Minimal QuickTime writer (test-only): one video track, all samples in one chunk.
+pub fn write_mov(path: &Path, fourcc: &[u8; 4], width: u16, height: u16, depth: u16, frames: &[Vec<u8>]) {
+ let n = frames.len() as u32;
+ let be32 = |v: u32| v.to_be_bytes();
+ let ftyp = bx(b"ftyp", &[b"qt ".as_slice(), &be32(0x200), b"qt "].concat());
+ let mdat_payload: Vec<u8> = frames.concat();
+ let data_off = ftyp.len() as u32 + 8;
+ let mdat = bx(b"mdat", &mdat_payload);
+ let matrix: Vec<u8> = MATRIX.iter().flat_map(|v| v.to_be_bytes()).collect();
+
+ let mut mvhd = vec![0u8; 4 + 8];
+ mvhd.extend_from_slice(&be32(25));
+ mvhd.extend_from_slice(&be32(n));
+ mvhd.extend_from_slice(&be32(0x10000));
+ mvhd.extend_from_slice(&[1, 0]);
+ mvhd.extend_from_slice(&[0; 10]);
+ mvhd.extend_from_slice(&matrix);
+ mvhd.extend_from_slice(&[0; 24]);
+ mvhd.extend_from_slice(&be32(2));
+
+ let mut tkhd = vec![0, 0, 0, 0xf];
+ tkhd.extend_from_slice(&[0; 8]);
+ tkhd.extend_from_slice(&be32(1));
+ tkhd.extend_from_slice(&[0; 4]);
+ tkhd.extend_from_slice(&be32(n));
+ tkhd.extend_from_slice(&[0; 8]);
+ tkhd.extend_from_slice(&[0; 8]); // layer, alternate group, volume, reserved
+ tkhd.extend_from_slice(&matrix);
+ tkhd.extend_from_slice(&be32((width as u32) << 16));
+ tkhd.extend_from_slice(&be32((height as u32) << 16));
+
+ let mut mdhd = vec![0u8; 4 + 8];
+ mdhd.extend_from_slice(&be32(25));
+ mdhd.extend_from_slice(&be32(n));
+ mdhd.extend_from_slice(&[0; 4]);
+ let hdlr = [&[0u8; 4][..], b"mhlr", b"vide", &[0; 12], &[0]].concat();
+ let vmhd = [0u8, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
+ let dref = bx(b"dref", &[&[0u8; 4][..], &be32(1), &bx(b"alis", &[0, 0, 0, 1])].concat());
+ let dinf = bx(b"dinf", &dref);
+
+ let mut entry = vec![0u8; 6];
+ entry.extend_from_slice(&[0, 1]);
+ entry.extend_from_slice(&[0; 4]); // version, revision
+ entry.extend_from_slice(b"fmcr");
+ entry.extend_from_slice(&be32(0));
+ entry.extend_from_slice(&be32(0x400));
+ entry.extend_from_slice(&width.to_be_bytes());
+ entry.extend_from_slice(&height.to_be_bytes());
+ entry.extend_from_slice(&be32(72 << 16));
+ entry.extend_from_slice(&be32(72 << 16));
+ entry.extend_from_slice(&be32(0));
+ entry.extend_from_slice(&[0, 1]);
+ entry.extend_from_slice(&[0; 32]);
+ entry.extend_from_slice(&depth.to_be_bytes());
+ entry.extend_from_slice(&[0xff, 0xff]);
+ let stsd = bx(b"stsd", &[&[0u8; 4][..], &be32(1), &bx(fourcc, &entry)].concat());
+ let stts = bx(b"stts", &[&[0u8; 4][..], &be32(1), &be32(n), &be32(1)].concat());
+ let stsc = bx(b"stsc", &[&[0u8; 4][..], &be32(1), &be32(1), &be32(n), &be32(1)].concat());
+ let mut stsz = vec![0u8; 4];
+ stsz.extend_from_slice(&be32(0));
+ stsz.extend_from_slice(&be32(n));
+ for f in frames {
+ stsz.extend_from_slice(&be32(f.len() as u32));
+ }
+ let stsz = bx(b"stsz", &stsz);
+ let stco = bx(b"stco", &[&[0u8; 4][..], &be32(1), &be32(data_off)].concat());
+ let stbl = bx(b"stbl", &[stsd, stts, stsc, stsz, stco].concat());
+ let minf = bx(b"minf", &[bx(b"vmhd", &vmhd), dinf, stbl].concat());
+ let mdia = bx(b"mdia", &[bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), minf].concat());
+ let trak = bx(b"trak", &[bx(b"tkhd", &tkhd), mdia].concat());
+ let moov = bx(b"moov", &[bx(b"mvhd", &mvhd), trak].concat());
+ std::fs::write(path, [ftyp, mdat, moov].concat()).unwrap();
+}
+
+/// Decode a MOV with ffmpeg (failing on any decode error); raw samples as u16.
+pub fn ffmpeg_decode(ff: &Path, mov: &Path, pix_fmt: &str) -> Vec<u16> {
+ let out = Command::new(ff)
+ .args(["-hide_banner", "-loglevel", "error", "-xerror", "-i"])
+ .arg(mov)
+ .args(["-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
+ .output()
+ .expect("run ffmpeg");
+ let err = String::from_utf8_lossy(&out.stderr).to_string();
+ assert!(out.status.success() && err.trim().is_empty(), "ffmpeg failed: {err}");
+ if pix_fmt.ends_with("le") {
+ out.stdout.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect()
+ } else {
+ out.stdout.iter().map(|&b| b as u16).collect()
+ }
+}
+
+/// Render a lavfi source to raw planar frames with ffmpeg and load them as [`Frame`]s.
+pub fn source_frames(ff: &Path, name: &str, lavfi: &str, frames: u32, w: u32, h: u32, chroma: filmcraft_dnx::ChromaFormat, depth: u8) -> Vec<Frame> {
+ let pix = match (chroma, depth) {
+ (filmcraft_dnx::ChromaFormat::Yuv422, 8) => "yuv422p",
+ (filmcraft_dnx::ChromaFormat::Yuv422, 10) => "yuv422p10le",
+ (filmcraft_dnx::ChromaFormat::Yuv422, _) => "yuv422p12le",
+ (_, 10) => "yuv444p10le",
+ _ => "yuv444p12le",
+ };
+ let path = fixture_dir().join(format!("{name}.{pix}.raw"));
+ if !path.exists() {
+ let tmp = filmcraft_testkit::temp_path(&path);
+ let f = frames.to_string();
+ run(ff, &["-f", "lavfi", "-i", lavfi, "-frames:v", &f, "-f", "rawvideo", "-pix_fmt", pix, tmp.to_str().unwrap()]);
+ std::fs::rename(&tmp, &path).unwrap();
+ }
+ let bytes = std::fs::read(&path).unwrap();
+ let s: Vec<u16> =
+ if depth == 8 { bytes.iter().map(|&b| b as u16).collect() } else { bytes.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect() };
+ let proto = Frame::new(w, h, chroma, depth, false);
+ let per = frame_samples(&proto);
+ assert_eq!(s.len(), per * frames as usize);
+ s.chunks_exact(per)
+ .map(|p| {
+ let mut f = proto.clone();
+ let n = f.y.len();
+ let c = f.cb.len();
+ f.y.copy_from_slice(&p[..n]);
+ f.cb.copy_from_slice(&p[n..n + c]);
+ f.cr.copy_from_slice(&p[n + c..n + 2 * c]);
+ f
+ })
+ .collect()
+}
diff --git a/crates/dnx/tests/oracle_decode.rs b/crates/dnx/tests/oracle_decode.rs
new file mode 100644
index 000000000..476ee68d1
--- /dev/null
+++ b/crates/dnx/tests/oracle_decode.rs
@@ -0,0 +1,83 @@
+//! Decode ffmpeg-made DNxHD / DNxHR fixtures and compare with ffmpeg's own decode.
+
+mod common;
+use common::*;
+use filmcraft_dnx::{DecodeOptions, decode_frame_with};
+
+fn specs() -> Vec<Spec> {
+ let t = |s: &str, r: u32| format!("testsrc2=s={s}:r={r}");
+ let m = |s: &str, r: u32| format!("mandelbrot=s={s}:r={r}");
+ let n = |s: &str, r: u32| format!("testsrc2=s={s}:r={r},noise=alls=60:allf=t,lutyuv=y=clip(val\\,24\\,231):u=clip(val\\,24\\,231):v=clip(val\\,24\\,231)");
+ vec![
+ // DNxHD (HD profile)
+ Spec::new("hd1237_testsrc", t("1920x1080", 25), 2, &["-b:v", "120M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1235_mandel", m("1920x1080", 25), 2, &["-b:v", "185M", "-pix_fmt", "yuv422p10le"], "yuv422p10le"),
+ Spec::new("hd1238_noise", n("1920x1080", 25), 2, &["-b:v", "185M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1253_testsrc", t("1920x1080", 25), 2, &["-b:v", "36M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1250_noise", n("1280x720", 50), 2, &["-b:v", "90M", "-pix_fmt", "yuv422p10le"], "yuv422p10le"),
+ Spec::new("hd1251_testsrc", t("1280x720", 50), 2, &["-b:v", "90M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1252_mandel", m("1280x720", 50), 2, &["-b:v", "60M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1258_testsrc", t("960x720", 50), 2, &["-b:v", "60M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1259_testsrc", t("1440x1080", 25), 2, &["-b:v", "84M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1242_interlaced", t("1920x1080", 25), 2, &["-flags", "+ildct", "-b:v", "120M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1241_interlaced", n("1920x1080", 25), 2, &["-flags", "+ildct", "-b:v", "185M", "-pix_fmt", "yuv422p10le"], "yuv422p10le"),
+ Spec::new("hd1243_interlaced", m("1920x1080", 25), 2, &["-flags", "+ildct", "-b:v", "220M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hd1244_interlaced", t("1440x1080", 25), 2, &["-flags", "+ildct", "-b:v", "120M", "-pix_fmt", "yuv422p"], "yuv422p"),
+ // DNxHR (RI profile)
+ Spec::new("hr_lb_testsrc", t("1920x1080", 25), 2, &["-profile:v", "dnxhr_lb", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hr_sq_mandel", m("1920x1080", 25), 2, &["-profile:v", "dnxhr_sq", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hr_hq_noise", n("1920x1080", 25), 2, &["-profile:v", "dnxhr_hq", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hr_hqx_mandel", m("1920x1080", 25), 2, &["-profile:v", "dnxhr_hqx", "-pix_fmt", "yuv422p10le"], "yuv422p10le"),
+ Spec::new("hr_hqx_noise_odd", n("1000x562", 25), 2, &["-profile:v", "dnxhr_hqx", "-pix_fmt", "yuv422p10le"], "yuv422p10le"),
+ Spec::new("hr_444_testsrc", t("1280x720", 25), 2, &["-profile:v", "dnxhr_444", "-pix_fmt", "yuv444p10le"], "yuv444p10le"),
+ Spec::new("hr_444_rgb_mandel", m("640x360", 25), 2, &["-profile:v", "dnxhr_444", "-pix_fmt", "gbrp10le"], "gbrp10le"),
+ Spec::new("hr_hq_small", t("256x120", 25), 2, &["-profile:v", "dnxhr_hq", "-pix_fmt", "yuv422p"], "yuv422p"),
+ Spec::new("hr_sq_uhd", t("3840x2160", 25), 1, &["-profile:v", "dnxhr_sq", "-pix_fmt", "yuv422p"], "yuv422p"),
+ ]
+}
+
+/// Generate every fixture (used by `cargo xtask fixtures dnx`).
+#[test]
+#[ignore]
+fn generate_fixtures() {
+ let Some(ff) = ffmpeg() else { return };
+ for s in specs() {
+ make(&ff, &s);
+ }
+}
+
+#[test]
+fn decode_matches_ffmpeg() {
+ let Some(ff) = ffmpeg() else { return };
+ let mut worst = 0;
+ for spec in specs() {
+ let mov = make(&ff, &spec);
+ let pk = packets(&ff, &mov);
+ assert_eq!(pk.len(), spec.frames as usize, "{}", spec.name);
+ let raw = reference(&ff, &mov, spec.pix_fmt);
+ let mut st = Stats::default();
+ let mut off = 0;
+ for (i, p) in pk.iter().enumerate() {
+ let f =
+ decode_frame_with(p, &DecodeOptions { threads: i % 2 == 0, ..Default::default() }).unwrap_or_else(|e| panic!("{} frame {i}: {e}", spec.name));
+ let ours = planes(&f, spec.pix_fmt);
+ let n = frame_samples(&f);
+ st.add(&ours, &raw[off..off + n]);
+ off += n;
+ }
+ assert_eq!(off, raw.len(), "{}: frame size mismatch", spec.name);
+ println!(
+ "{:<22} cid {} max {} mean {:.5} exact {:.3}% beyond ±1: {}",
+ spec.name,
+ filmcraft_dnx::probe(&pk[0]).unwrap().cid,
+ st.max,
+ st.mean(),
+ st.exact_pct(),
+ st.over1
+ );
+ worst = worst.max(st.max);
+ // the remaining differences are ffmpeg's integer IDCT: ±1, at most ~50 samples per million at ±2
+ assert!(st.over1 * 10_000 <= st.n, "{}: {} samples beyond ±1", spec.name, st.over1);
+ }
+ assert!(worst <= 2, "max error {worst}");
+}
diff --git a/crates/dnx/tests/oracle_encode.rs b/crates/dnx/tests/oracle_encode.rs
new file mode 100644
index 000000000..ca64941df
--- /dev/null
+++ b/crates/dnx/tests/oracle_encode.rs
@@ -0,0 +1,76 @@
+//! Encode DNxHR with our encoder, decode with ffmpeg (`-xerror`) and with our decoder.
+
+mod common;
+use common::*;
+use filmcraft_dnx::{ChromaFormat, Encoder, EncoderConfig, Profile, decode_frame};
+
+struct Case {
+ name: &'static str,
+ profile: Profile,
+ depth: u8,
+ lavfi: &'static str,
+ min_psnr: f64,
+}
+
+#[test]
+fn encode_decodes_in_ffmpeg() {
+ let Some(ff) = ffmpeg() else { return };
+ let (w, h) = (1920u32, 1080u32);
+ let cases = [
+ Case { name: "enc_sq_mandel", profile: Profile::Sq, depth: 8, lavfi: "mandelbrot=s=1920x1080:r=25", min_psnr: 40.0 },
+ Case { name: "enc_hq_mandel", profile: Profile::Hq, depth: 8, lavfi: "mandelbrot=s=1920x1080:r=25", min_psnr: 45.0 },
+ Case { name: "enc_hq_testsrc", profile: Profile::Hq, depth: 8, lavfi: "testsrc2=s=1920x1080:r=25", min_psnr: 45.0 },
+ Case { name: "enc_hqx10_mandel", profile: Profile::Hqx, depth: 10, lavfi: "mandelbrot=s=1920x1080:r=25", min_psnr: 45.0 },
+ Case { name: "enc_hqx12_testsrc", profile: Profile::Hqx, depth: 12, lavfi: "testsrc2=s=1920x1080:r=25", min_psnr: 45.0 },
+ Case { name: "enc_lb_testsrc", profile: Profile::Lb, depth: 8, lavfi: "testsrc2=s=1920x1080:r=25", min_psnr: 30.0 },
+ Case { name: "enc_444_testsrc", profile: Profile::R444, depth: 10, lavfi: "testsrc2=s=1920x1080:r=25", min_psnr: 45.0 },
+ ];
+ for c in cases {
+ let mut cfg = EncoderConfig::new(c.profile, w, h);
+ cfg.bit_depth = c.depth;
+ let chroma = cfg.chroma();
+ let src = source_frames(&ff, c.name, c.lavfi, 2, w, h, chroma, c.depth);
+ let mut enc = Encoder::with_config(cfg).unwrap();
+ let t = std::time::Instant::now();
+ let coded: Vec<Vec<u8>> = src.iter().map(|f| enc.encode(f).unwrap()).collect();
+ let ms = t.elapsed().as_secs_f64() * 1000.0 / src.len() as f64;
+ for p in &coded {
+ assert_eq!(p.len() as u32, enc.frame_size(), "{}: CBR frame size", c.name);
+ }
+ let mov = fixture_dir().join(format!("{}.out.mov", c.name));
+ write_mov(&mov, b"AVdh", w as u16, h as u16, 24, &coded);
+ let pix = match (chroma, c.depth) {
+ (ChromaFormat::Yuv444, 10) => "yuv444p10le",
+ (_, 8) => "yuv422p",
+ (_, 10) => "yuv422p10le",
+ _ => "yuv422p12le",
+ };
+ // ffmpeg reads 4:4:4 Y'CbCr DNxHR as gbrp unless every macroblock is flagged
+ let ff_raw = ffmpeg_decode(&ff, &mov, pix);
+ let mut agree = Stats::default();
+ let mut psnr_min = f64::MAX;
+ let per = frame_samples(&src[0]);
+ assert_eq!(ff_raw.len(), per * coded.len(), "{}: ffmpeg frame count", c.name);
+ for (i, p) in coded.iter().enumerate() {
+ let f = decode_frame(p).unwrap();
+ let ours = planes(&f, pix);
+ agree.add(&ours, &ff_raw[i * per..(i + 1) * per]);
+ let peak = ((1u32 << c.depth) - 1) as f64;
+ let srcp = planes(&src[i], pix);
+ psnr_min = psnr_min.min(psnr(&srcp[..f.y.len()], &ours[..f.y.len()], peak));
+ }
+ println!(
+ "{:<18} {} {}-bit: {} bytes/frame, {:.1} ms/frame, Y PSNR {:.2} dB, vs ffmpeg max {} exact {:.2}%",
+ c.name,
+ c.profile.name(),
+ c.depth,
+ enc.frame_size(),
+ ms,
+ psnr_min,
+ agree.max,
+ agree.exact_pct()
+ );
+ assert!(agree.max <= 2, "{}: ffmpeg disagrees by {}", c.name, agree.max);
+ assert!(psnr_min >= c.min_psnr, "{}: PSNR {psnr_min:.2}", c.name);
+ }
+}
diff --git a/crates/dnx/tests/perf.rs b/crates/dnx/tests/perf.rs
new file mode 100644
index 000000000..255f1961c
--- /dev/null
+++ b/crates/dnx/tests/perf.rs
@@ -0,0 +1,59 @@
+//! Throughput: `cargo test --release -p filmcraft-dnx --test perf -- --ignored --nocapture`.
+
+use filmcraft_dnx::{ChromaFormat, DecodeOptions, Encoder, EncoderConfig, Frame, Profile, decode_frame_with};
+use std::time::Instant;
+
+fn busy(w: u32, h: u32, chroma: ChromaFormat, depth: u8) -> Frame {
+ let mut f = Frame::new(w, h, chroma, depth, false);
+ let max = (1u32 << depth) - 1;
+ let mut s = 1u32;
+ for v in f.y.iter_mut().chain(f.cb.iter_mut()).chain(f.cr.iter_mut()) {
+ s ^= s << 13;
+ s ^= s >> 17;
+ s ^= s << 5;
+ *v = (((*v as u32) + (s % (24 << (depth - 8)))).min(max)) as u16;
+ }
+ for y in 0..h {
+ for x in 0..w {
+ let i = (y * w + x) as usize;
+ f.y[i] = (f.y[i] as u32 + (((x ^ y) % 160) << (depth - 8))).min(max) as u16;
+ }
+ }
+ f
+}
+
+#[test]
+#[ignore]
+fn throughput() {
+ for (profile, depth, w, h) in [(Profile::Hq, 8, 1920, 1080), (Profile::Hqx, 10, 1920, 1080), (Profile::Sq, 8, 3840, 2160), (Profile::Hqx, 10, 3840, 2160)] {
+ let mut cfg = EncoderConfig::new(profile, w, h);
+ cfg.bit_depth = depth;
+ let src = busy(w, h, cfg.chroma(), depth);
+ let mut enc = Encoder::with_config(cfg).unwrap();
+ let data = enc.encode(&src).unwrap();
+ let n = if w > 1920 { 5 } else { 20 };
+ let t = Instant::now();
+ for _ in 0..n {
+ enc.encode(&src).unwrap();
+ }
+ let enc_fps = n as f64 / t.elapsed().as_secs_f64();
+ let mut fps = [0f64; 2];
+ for (k, threads) in [true, false].into_iter().enumerate() {
+ let opts = DecodeOptions { threads, ..Default::default() };
+ let m = if threads { n * 3 } else { n / 2 };
+ let t = Instant::now();
+ for _ in 0..m {
+ decode_frame_with(&data, &opts).unwrap();
+ }
+ fps[k] = m as f64 / t.elapsed().as_secs_f64();
+ }
+ println!(
+ "{} {depth}-bit {w}x{h} ({} KB/frame): decode {:.0} fps threaded, {:.1} fps single-thread; encode {:.1} fps",
+ profile.name(),
+ data.len() / 1024,
+ fps[0],
+ fps[1],
+ enc_fps
+ );
+ }
+}
diff --git a/crates/dnx/tests/roundtrip.rs b/crates/dnx/tests/roundtrip.rs
new file mode 100644
index 000000000..f677cd6eb
--- /dev/null
+++ b/crates/dnx/tests/roundtrip.rs
@@ -0,0 +1,103 @@
+//! Encoder → decoder round trips and robustness against corrupt data (no ffmpeg needed).
+
+use filmcraft_dnx::{ChromaFormat, DecodeOptions, Encoder, EncoderConfig, Frame, Profile, decode_frame, decode_frame_with, probe};
+
+/// A synthetic picture: gradients, a ring pattern and some hashed texture.
+fn picture(w: u32, h: u32, chroma: ChromaFormat, depth: u8, seed: u32) -> Frame {
+ let mut f = Frame::new(w, h, chroma, depth, false);
+ let max = (1u32 << depth) - 1;
+ let s = depth as u32 - 8;
+ let hash = |x: u32, y: u32| (x.wrapping_mul(73856093) ^ y.wrapping_mul(19349663) ^ seed.wrapping_mul(83492791)) % 17;
+ for y in 0..h {
+ for x in 0..w {
+ let r = (((x as f32 - w as f32 / 2.0).powi(2) + (y as f32 - h as f32 / 2.0).powi(2)).sqrt() / 6.0).sin();
+ let v = (16 << s) as f32 + (219 << s) as f32 * (0.5 + 0.3 * r + 0.2 * (x as f32 / w as f32 - 0.5)) + (hash(x, y) << s) as f32;
+ f.y[(y * w + x) as usize] = (v as u32).min(max) as u16;
+ }
+ }
+ let cw = f.chroma_width();
+ for y in 0..f.chroma_height() {
+ for x in 0..cw {
+ let i = (y * cw + x) as usize;
+ f.cb[i] = (((128 + (x * 90 / cw) as i32 - 45) as u32) << s) as u16;
+ f.cr[i] = (((128 + (y * 80 / f.chroma_height()) as i32 - 40) as u32) << s) as u16;
+ }
+ }
+ f
+}
+
+fn psnr(a: &[u16], b: &[u16], peak: f64) -> f64 {
+ let mse: f64 = a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).powi(2)).sum::<f64>() / a.len() as f64;
+ if mse == 0.0 { 99.0 } else { 10.0 * (peak * peak / mse).log10() }
+}
+
+#[test]
+fn roundtrip_all_profiles() {
+ for (profile, depth, w, h) in [
+ (Profile::Lb, 8, 640, 360),
+ (Profile::Sq, 8, 1280, 720),
+ (Profile::Hq, 8, 720, 486),
+ (Profile::Hqx, 10, 1000, 562),
+ (Profile::Hqx, 12, 512, 288),
+ (Profile::R444, 10, 400, 300),
+ (Profile::R444, 12, 64, 48),
+ ] {
+ let mut cfg = EncoderConfig::new(profile, w, h);
+ cfg.bit_depth = depth;
+ let chroma = cfg.chroma();
+ let mut enc = Encoder::with_config(cfg).unwrap();
+ for seed in 0..2 {
+ let src = picture(w, h, chroma, depth, seed);
+ let data = enc.encode(&src).unwrap();
+ assert_eq!(data.len() as u32, enc.frame_size());
+ assert_eq!(&data[data.len() - 4..], &[0x60, 0x0D, 0xC0, 0xDE]);
+ let hdr = probe(&data).unwrap();
+ assert_eq!((hdr.cid, hdr.width, hdr.lines, hdr.bit_depth), (profile.cid(), w, h, depth));
+ let dec = decode_frame(&data).unwrap();
+ let single = decode_frame_with(&data, &DecodeOptions { threads: false, ..Default::default() }).unwrap();
+ assert_eq!(dec, single, "threaded and single-threaded decodes differ");
+ assert_eq!((dec.width, dec.height, dec.chroma, dec.bit_depth, dec.rgb), (w, h, chroma, depth, false));
+ let peak = ((1u32 << depth) - 1) as f64;
+ let p = psnr(&src.y, &dec.y, peak);
+ let pc = psnr(&src.cb, &dec.cb, peak);
+ let min = if profile == Profile::Lb { 30.0 } else { 38.0 };
+ assert!(p > min && pc > min, "{profile:?} {depth}-bit {w}x{h}: PSNR {p:.1}/{pc:.1}");
+ }
+ }
+}
+
+#[test]
+fn rejects_bad_input() {
+ let mut enc = Encoder::new(Profile::Hq, 64, 64);
+ assert!(enc.encode(&Frame::new(32, 64, ChromaFormat::Yuv422, 8, false)).is_err());
+ assert!(enc.encode(&Frame::new(64, 64, ChromaFormat::Yuv444, 8, false)).is_err());
+ assert!(Encoder::with_config(EncoderConfig { bit_depth: 10, ..EncoderConfig::new(Profile::Hq, 64, 64) }).is_err());
+ assert!(decode_frame(&[0u8; 100]).is_err());
+ assert!(decode_frame(&[0u8; 1000]).is_err());
+}
+
+#[test]
+fn corrupt_streams_never_panic() {
+ let mut enc = Encoder::new(Profile::Hq, 256, 128);
+ let good = enc.encode(&picture(256, 128, ChromaFormat::Yuv422, 8, 1)).unwrap();
+ let mut seed = 0x1234_5678u32;
+ let mut rnd = || {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ seed
+ };
+ for i in 0..400 {
+ let mut d = good.clone();
+ let n = 1 + rnd() % 8;
+ for _ in 0..n {
+ // mostly the payload, sometimes the header
+ let pos = if i % 4 == 0 { rnd() as usize % 0x280 } else { 0x280 + rnd() as usize % (d.len() - 0x280) };
+ d[pos] ^= 1 << (rnd() % 8);
+ }
+ if i % 5 == 0 {
+ d.truncate(rnd() as usize % d.len());
+ }
+ let _ = decode_frame(&d);
+ }
+}
diff --git a/crates/dnx/tools/extract_tables.py b/crates/dnx/tools/extract_tables.py
new file mode 100644
index 000000000..56d73a6e1
--- /dev/null
+++ b/crates/dnx/tools/extract_tables.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python3
+"""Extract the VC-3 constant tables (Annex D quantization weights, Annex E VLC tables) from the
+text of the public SMPTE ST 2019-1:2016 standard.
+
+Usage:
+ curl -LO https://pub.smpte.org/doc/st2019-1/20160518-pub/st2019-1-20160518-pub.zip
+ unzip st2019-1-20160518-pub.zip
+ pdftotext -layout st2019-1-2016.pdf vc3.txt
+ python3 extract_tables.py vc3.txt > ../src/spec_tables.rs
+
+Only the standard's text is read. Every table's size is checked (63 AC weights per matrix, 4*64+1
+amplitude codewords including EOB, 62 run codewords) and every VLC table must be a complete
+prefix code.
+"""
+import re
+import sys
+
+text = open(sys.argv[1], encoding="utf-8").read()
+lines = text.split("\n")
+
+
+def section(start_pat, end_pat):
+ s = next(i for i, l in enumerate(lines) if re.search(start_pat, l))
+ e = next(i for i in range(s + 1, len(lines)) if re.search(end_pat, lines[i]))
+ return lines[s + 1:e]
+
+
+def weights(sec):
+ """The 63 AC weights of an 8x8 table printed in raster order with '-' for the DC entry."""
+ nums = []
+ for l in sec:
+ if "Page" in l or "SMPTE" in l or "Compression" in l:
+ continue
+ nums += [int(x) for x in re.findall(r"\b\d+\b", l)]
+ return nums
+
+
+def check_prefix(codes):
+ """Kraft sum of a prefix code (1.0 when complete)."""
+ for a in codes:
+ for b in codes:
+ if a is not b and b.startswith(a):
+ raise SystemExit("not a prefix code: %s %s" % (a, b))
+ return sum(2.0 ** -len(c) for c in codes)
+
+
+out = ["// Generated by tools/extract_tables.py from SMPTE ST 2019-1:2016 (VC-3), Annexes D and E.",
+ "// Do not edit by hand.", ""]
+
+# ---- Annex D: weights in raster order (v*8+u), DC entry omitted ----
+dtables = [("D_1", r"Table D\.1 – Compression ID 1235"), ("D_2", r"Table D\.2 – Compression ID 1237"),
+ ("D_3", r"^Table D\.3 – Compression"), ("D_4", r"Table D\.4 – Compression"),
+ ("D_5", r"Table D\.5 – Compression"), ("D_6", r"Table D\.6 – Compression"),
+ ("D_7", r"^Table D\.7 – Compression"), ("D_8", r"Table D\.8 – Compression"),
+ ("D_9", r"Table D\.9 – Compression"), ("D_10", r"Table D\.10 – Compression"),
+ ("D_11", r"^Table D\.11 – Compression")]
+for i, (name, pat) in enumerate(dtables):
+ end = dtables[i + 1][1] if i + 1 < len(dtables) else r"^Annex E VLC Tables"
+ sec = section(pat, end)
+ if name == "D_11":
+ sec = [l for l in sec if "Compression ID" not in l]
+ nums = weights(sec)
+ assert len(nums) == 63, (name, len(nums))
+ out.append("pub const W_%s: [[u8; 63]; 2] = [%s, %s];" % (name, nums, nums))
+ continue
+ li = next(j for j, l in enumerate(sec) if "Luma Quantization" in l)
+ ci = next(j for j, l in enumerate(sec) if "Chroma Quantization" in l)
+ luma = weights(sec[li + 1:ci])
+ chroma = weights(sec[ci + 1:])
+ assert len(luma) == 63 and len(chroma) == 63, (name, len(luma), len(chroma))
+ out.append("pub const W_%s: [[u8; 63]; 2] = [%s, %s];" % (name, luma, chroma))
+out.append("")
+
+# ---- Annex E ----
+etables = ["E.1", "E.4", "E.7", "E.10", "E.13", "E.16"]
+for n, t in enumerate(etables):
+ a = int(t[2:])
+ amp = section(r"^\s*Table E\.%d – Amplitude" % a, r"Table E\.%d – Run" % (a + 1))
+ run = section(r"Table E\.%d – Run" % (a + 1), r"Table E\.%d – DC" % (a + 2))
+ nxt = r"Table E\.%d – Amplitude" % (a + 3) if n + 1 < len(etables) else r"^Annex F System"
+ dc = section(r"Table E\.%d – DC" % (a + 2), nxt)
+ ent = []
+ for l in amp:
+ for m in re.finditer(r"\b([01]+)\s+(\d+)\s+(EOB1?|\d+)\s+([01])\s+([01])\b", l):
+ code, ln, am, fr, fi = m.groups()
+ assert len(code) == int(ln), m.group(0)
+ ent.append((code, 0 if am.startswith("EOB") else int(am), int(fr), int(fi), am.startswith("EOB")))
+ k = check_prefix([e[0] for e in ent])
+ assert abs(k - 1.0) < 1e-12, (t, k, len(ent))
+ assert sum(e[4] for e in ent) == 1 and len(ent) == 4 * 64 + 1, (t, len(ent))
+ rent = []
+ for l in run:
+ for m in re.finditer(r"\b([01]+)\s+(\d+)\s+(\d+)\b", l):
+ code, ln, r = m.groups()
+ if len(code) != int(ln):
+ continue
+ rent.append((code, int(r)))
+ assert len(rent) == 62 and sorted(r for _, r in rent) == list(range(1, 63)), (t, len(rent))
+ assert abs(check_prefix([c for c, _ in rent]) - 1.0) < 1e-12
+ dent = []
+ for l in dc:
+ m = re.match(r"^\s+([01]+)\s+(\d+)\s*$", l)
+ if m:
+ dent.append((m.group(1), int(m.group(2))))
+ assert [e for _, e in dent] == list(range(len(dent))), (t, dent)
+ assert abs(check_prefix([c for c, _ in dent]) - 1.0) < 1e-12, (t, dent)
+ name = t.replace(".", "_")
+ out.append("/// Table %s: (codeword, length, amplitude (0 = EOB), Frun, Findex)." % t)
+ out.append("pub const AMP_%s: [(u16, u8, u8, u8, u8); %d] = [" % (name, len(ent)))
+ for c, a_, fr, fi, _ in ent:
+ out.append(" (0b%s, %d, %d, %d, %d)," % (c, len(c), a_, fr, fi))
+ out.append("];")
+ out.append("/// Table E.%d: (codeword, length, run)." % (a + 1))
+ out.append("pub const RUN_%s: [(u16, u8, u8); 62] = [" % name)
+ for c, r in rent:
+ out.append(" (0b%s, %d, %d)," % (c, len(c), r))
+ out.append("];")
+ out.append("/// Table E.%d: (codeword, length) indexed by the DC size.", )
+ out[-1] = "/// Table E.%d: (codeword, length) indexed by the DC size (eta)." % (a + 2)
+ out.append("pub const DC_%s: [(u16, u8); %d] = [%s];" % (name, len(dent), ", ".join("(0b%s, %d)" % (c, len(c)) for c, _ in dent)))
+ out.append("")
+
+print("\n".join(out))
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 26e315515..0c2885cd3 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -686,7 +686,7 @@ fn build() -> Vec<CommandSpec> {
"Media…",
["File", "Export"],
None,
- r#"{"path":str,"format":"h264|prores|mjpeg|png|gif|wav","scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false}"#,
+ r#"{"path":str,"format":"h264|prores|dnxhr|mjpeg|png|gif|wav","scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"proresProfile":"proxy|lt|standard|hq"?,"dnxProfile":"lb|sq|hq|hqx"?}"#,
has_seq,
|s, p| export_media(s, p)
),
@@ -1902,6 +1902,7 @@ fn export_media(s: &mut Session, p: &Value) -> Result<Value> {
burn_captions: bool_p(p, "burnCaptions").unwrap_or(false),
part_of_batch: false,
prores_profile: str_p(p, "proresProfile").unwrap_or_default().to_string(),
+ dnx_profile: str_p(p, "dnxProfile").unwrap_or_default().to_string(),
sdr: bool_p(p, "sdr").unwrap_or(false),
..Default::default()
};
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 71365269d..9307c89e5 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -18,6 +18,7 @@ filmcraft-project = { workspace = true }
filmcraft-render = { workspace = true }
filmcraft-isobmff = { workspace = true }
filmcraft-prores = { workspace = true }
+filmcraft-dnx = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-h264enc = { workspace = true }
serde = { workspace = true }
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 0119aaa97..12f329ee1 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -40,6 +40,8 @@ pub enum Format {
H264,
/// QuickTime, Apple ProRes 422 HQ + PCM (needs the ProRes encoder registered).
ProRes,
+ /// QuickTime, Avid DNxHR (HQ unless the settings pick another profile) + PCM.
+ DnxHr,
/// QuickTime, Motion-JPEG + 16-bit PCM.
Mjpeg,
PngSequence,
@@ -52,6 +54,7 @@ impl Format {
Some(match s.to_ascii_lowercase().replace([' ', '-', '_', '.'], "").as_str() {
"h264" | "mp4" | "avc" => Format::H264,
"prores" | "mov" => Format::ProRes,
+ "dnxhr" | "dnxhd" | "dnx" | "avid" | "vc3" => Format::DnxHr,
"mjpeg" | "motionjpeg" | "jpeg" => Format::Mjpeg,
"png" | "pngsequence" => Format::PngSequence,
"gif" | "animatedgif" => Format::Gif,
@@ -62,7 +65,7 @@ impl Format {
pub fn extension(self) -> &'static str {
match self {
Format::H264 => "mp4",
- Format::ProRes | Format::Mjpeg => "mov",
+ Format::ProRes | Format::DnxHr | Format::Mjpeg => "mov",
Format::PngSequence => "png",
Format::Gif => "gif",
Format::Wav => "wav",
@@ -72,13 +75,14 @@ impl Format {
match self {
Format::H264 => "H.264",
Format::ProRes => "Apple ProRes",
+ Format::DnxHr => "Avid DNxHR",
Format::Mjpeg => "QuickTime (Motion JPEG)",
Format::PngSequence => "PNG Sequence",
Format::Gif => "Animated GIF",
Format::Wav => "Waveform Audio",
}
}
- pub const ALL: [Format; 6] = [Format::H264, Format::ProRes, Format::Mjpeg, Format::PngSequence, Format::Gif, Format::Wav];
+ pub const ALL: [Format; 7] = [Format::H264, Format::ProRes, Format::DnxHr, Format::Mjpeg, Format::PngSequence, Format::Gif, Format::Wav];
}
#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -104,6 +108,9 @@ pub struct ExportSettings {
/// ProRes flavour: `proxy`, `lt`, `standard` or `hq` (empty = HQ).
#[serde(default)]
pub prores_profile: String,
+ /// DNxHR profile: `lb`, `sq`, `hq` or `hqx` (empty = HQ).
+ #[serde(default)]
+ pub dnx_profile: String,
/// Encode display-referred SDR (Rec. 709, tone mapped) even when the sequence works in
/// Rec. 2100 PQ/HLG. Otherwise H.264 and ProRes exports of an HDR sequence are encoded in the
/// sequence's HDR space and signal it (VUI / `colr` / `mdcv` / `clli` / SEI).
@@ -172,6 +179,7 @@ impl Default for ExportSettings {
burn_captions: false,
part_of_batch: false,
prores_profile: String::new(),
+ dnx_profile: String::new(),
sdr: false,
signal: ColorSignal::default(),
}
@@ -256,7 +264,7 @@ pub type AudioEncoderFactory = fn(format: Format, sample_rate: u32, channels: u3
fn video_factories() -> &'static RwLock<Vec<EncoderFactory>> {
static F: OnceLock<RwLock<Vec<EncoderFactory>>> = OnceLock::new();
- F.get_or_init(|| RwLock::new(vec![h264_factory, prores_factory, mjpeg_factory]))
+ F.get_or_init(|| RwLock::new(vec![h264_factory, prores_factory, dnx_factory, mjpeg_factory]))
}
fn audio_factories() -> &'static RwLock<Vec<AudioEncoderFactory>> {
static F: OnceLock<RwLock<Vec<AudioEncoderFactory>>> = OnceLock::new();
@@ -451,6 +459,65 @@ fn prores_factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSet
})
}
+/// The DNxHR profile named by [`ExportSettings::dnx_profile`].
+pub fn dnx_profile(name: &str) -> filmcraft_dnx::Profile {
+ use filmcraft_dnx::Profile;
+ match name.to_ascii_lowercase().as_str() {
+ "lb" => Profile::Lb,
+ "sq" => Profile::Sq,
+ "hqx" => Profile::Hqx,
+ _ => Profile::Hq,
+ }
+}
+
+/// DNxHR encoder (RGBA8 or HDR floats → BT.709 / BT.2020 limited-range 4:2:2; 8-bit for
+/// LB/SQ/HQ, 10-bit for HQX).
+struct DnxEncoder {
+ enc: filmcraft_dnx::Encoder,
+ w: u32,
+ h: u32,
+ rate: FrameRate,
+ signal: ColorSignal,
+}
+
+impl VideoEncoder for DnxEncoder {
+ fn sample_entry(&self) -> SampleEntry {
+ let mut e = SampleEntry::dnx(filmcraft_isobmff::FourCc(*b"AVdh"), self.w as u16, self.h as u16);
+ self.signal.apply_to(&mut e, true);
+ e
+ }
+ fn timescale(&self) -> u32 {
+ self.rate.num as u32
+ }
+ fn encode(&mut self, f: &EncoderFrame) -> Result<Vec<EncodedPacket>> {
+ let mut fr = filmcraft_dnx::Frame::new(f.width, f.height, filmcraft_dnx::ChromaFormat::Yuv422, 10, false);
+ match f.hdr {
+ Some(rgb) => {
+ let (kr, kb) = self.signal.kr_kb();
+ rgbf_to_yuv422_10(rgb, f.width as usize, f.height as usize, kr, kb, &mut fr.y, &mut fr.cb, &mut fr.cr)
+ }
+ None => rgba_to_yuv422_10(f.rgba, f.width as usize, f.height as usize, &mut fr.y, &mut fr.cb, &mut fr.cr),
+ }
+ // the encoder rescales 10-bit input to its coded depth
+ let data = self.enc.encode(&fr).map_err(|e| ExportError::Encode(e.to_string()))?;
+ Ok(vec![EncodedPacket { data, key: true, duration: self.rate.den as u32, composition_offset: 0 }])
+ }
+ fn flush(&mut self) -> Result<Vec<EncodedPacket>> {
+ Ok(Vec::new())
+ }
+}
+
+fn dnx_factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> Option<Result<Box<dyn VideoEncoder>>> {
+ (format == Format::DnxHr).then(|| {
+ let mut cfg = filmcraft_dnx::EncoderConfig::new(dnx_profile(&s.dnx_profile), w, h);
+ if s.signal.primaries == 9 {
+ cfg.color_volume = filmcraft_dnx::ColorVolume::Bt2020Ncl;
+ }
+ let enc = filmcraft_dnx::Encoder::with_config(cfg).map_err(|e| ExportError::Encode(e.to_string()))?;
+ Ok(Box::new(DnxEncoder { enc, w, h, rate, signal: s.signal }) as Box<dyn VideoEncoder>)
+ })
+}
+
/// H.264 High (our encoder): sRGB/709 RGBA8 → 8-bit limited-range BT.709 4:2:0, VBR at the
/// requested bitrate, length-prefixed samples with the `avcC` in the sample entry.
struct H264Encoder {
@@ -616,7 +683,7 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
let q = project.sequence(seq).ok_or(ExportError::NoSequence)?;
// HDR sequences export HDR (H.264 / ProRes) unless SDR is asked for
let pipe = q.settings.color;
- let hdr_out = pipe.working.is_hdr() && !settings.sdr && matches!(settings.format, Format::H264 | Format::ProRes);
+ let hdr_out = pipe.working.is_hdr() && !settings.sdr && matches!(settings.format, Format::H264 | Format::ProRes | Format::DnxHr);
let mut settings = settings.clone();
settings.signal = match (hdr_out, pipe.working) {
(true, filmcraft_color::WorkingSpace::Rec2100Pq) => ColorSignal::PQ,
@@ -729,7 +796,7 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
drop(enc);
std::fs::metadata(&settings.path).map(|m| m.len()).unwrap_or(0)
}
- Format::H264 | Format::ProRes | Format::Mjpeg => {
+ Format::H264 | Format::ProRes | Format::DnxHr | Format::Mjpeg => {
let mut venc = video_factories()
.read()
.unwrap_or_else(|e| e.into_inner())
diff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rs
index 7e095e71d..89f7c2078 100644
--- a/crates/export/src/tests.rs
+++ b/crates/export/src/tests.rs
@@ -101,6 +101,24 @@ fn prores_export_roundtrip() {
assert!(f[0] > 240 && f[1] < 15 && f[2] < 15, "{:?}", &f[..4]);
}
+#[test]
+fn dnxhr_export_roundtrip() {
+ let (p, seq, m) = project();
+ for (profile, label) in [("hq", "DNxHR HQ"), ("hqx", "DNxHR HQX"), ("sq", "DNxHR SQ")] {
+ let path = tmp(&format!("dnx_{profile}.mov"));
+ let s = ExportSettings { format: Format::DnxHr, path: path.clone(), dnx_profile: profile.into(), ..Default::default() };
+ export(&p, seq, &s, &m, &Progress::default()).unwrap();
+ let bytes: Arc<[u8]> = std::fs::read(&path).unwrap().into();
+ let src = filmcraft_codecs::open_bytes("dnx.mov", bytes).unwrap();
+ let info = src.info().video.clone().unwrap();
+ assert_eq!(info.codec, label);
+ let f = src.video_frame(FrameRequest::full(Tick(TICKS_PER_SECOND / 3))).unwrap();
+ assert!(f.format_label().contains("4:2:2"), "{}", f.format_label());
+ let px = f.to_rgba8();
+ assert!(px[0] > 240 && px[1] < 15 && px[2] < 15, "{profile}: {:?}", &px[..4]);
+ }
+}
+
/// Burn-in: an H.264 export of a dark-blue matte with a caption, decoded by ffmpeg (external test
/// oracle only), has bright caption pixels in the lower part of the frame, and none without
/// `burn_captions` or above the caption.
diff --git a/crates/isobmff/src/codec.rs b/crates/isobmff/src/codec.rs
index d55a621d2..801652802 100644
--- a/crates/isobmff/src/codec.rs
+++ b/crates/isobmff/src/codec.rs
@@ -1173,6 +1173,14 @@ impl SampleEntry {
}
e
}
+ /// Avid DNxHD / DNxHR entry (`AVdn`, or `AVdh` for DNxHR).
+ pub fn dnx(fourcc: FourCc, width: u16, height: u16) -> Self {
+ let mut e = Self::video(fourcc, CodecConfig::Dnx { fourcc }, width, height);
+ if let Some(v) = e.video.as_mut() {
+ v.depth = 24;
+ }
+ e
+ }
/// Motion-JPEG entry (`jpeg`).
pub fn jpeg(width: u16, height: u16) -> Self {
let f = FourCc(*b"jpeg");
diff --git a/docs/architecture.md b/docs/architecture.md
index a421d476d..9acfeef7d 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -27,7 +27,7 @@ Design principles:
L2 edit · codecs · interchange · captions
L1 frame · media · project · audio-dsp · text
L0 foundation: time · geom · color · bitstream · testkit (dev-dependency only)
- codecs/containers: isobmff · matroska · h264 · h264enc · hevc · prores · aac
+ codecs/containers: isobmff · matroska · h264 · h264enc · hevc · vp9 · prores · dnx · aac · opus
```
Crates are named `filmcraft-<dir>` (`crates/time` is `filmcraft-time`). The apps are `filmcraft`
@@ -44,6 +44,7 @@ and `filmcraft-cli`.
| `h264`, `h264enc` | L0 | H.264 decoder; H.264 encoder |
| `hevc` | L0 | H.265 Main/Main 10 decoder |
| `prores` | L0 | ProRes decoder and encoder |
+| `dnx` | L0 | DNxHD / DNxHR (SMPTE ST 2019-1 VC-3) decoder and DNxHR encoder |
| `aac` | L0 | AAC-LC decoder and encoder |
| `testkit` | L0 | test-only helpers, used only as a dev-dependency: ffmpeg/ffprobe discovery, fixture dirs, golden images ([testing.md](testing.md)) |
| `frame` | L1 | `VideoFrame` (planar YUV / RGBA8 / linear RGBA f32, colour metadata), `AudioBuffer` |
@@ -179,7 +180,7 @@ pub struct CommandSpec {
```text
file ──► codecs (MP4/MOV, MKV, audio) demux + decode, GOP-aware seek
- │ decoder registry: h264, hevc, prores, mjpeg (+ any registered first)
+ │ decoder registry: h264, hevc, vp9, prores, dnx, mjpeg (+ any registered first)
▼
media::MediaSource ──► frame cache (byte-budgeted LRU, shared)
▼
@@ -367,6 +368,7 @@ file.exportMedia {path, format, scale, audio, quality}
|---|---|---|
| `h264` | `filmcraft-h264enc` + `filmcraft-aac` | MP4 (`isobmff`) |
| `prores` | `filmcraft-prores` | MOV |
+| `dnxhr` | `filmcraft-dnx` (LB / SQ / HQ / HQX) | MOV (`AVdh`) |
| `mjpeg` | built in | MOV |
| `png`, `gif`, `wav` | built in | image sequence / GIF / WAV |
@@ -399,7 +401,7 @@ Protocol reference: [control-protocol.md](control-protocol.md). Agent guide: [ag
## 8. Not built yet
-The layer table reserves names for crates that don't exist yet: `riff`, `mjpeg`, `dnx`,
+The layer table reserves names for crates that don't exist yet: `riff`, `mjpeg`,
`keyframe`, `effects`, `audio`, `scopes`, `playback`, `format` and `platform`.
Until they exist, that work lives elsewhere: keyframes and effect definitions in `project`, effects
and the audio mix in `render`, scopes and playback in `ui-egui`, and OS integration (cpal, rfd,
diff --git a/docs/testing.md b/docs/testing.md
index 342168768..e0c561749 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -50,7 +50,7 @@ are never linked or shipped ([AGENTS.md](../AGENTS.md) §2).
concurrently; migrate it when convenient).
- `cargo xtask fixtures [crate…]` pre-generates the whole fixture matrix up front (useful before a
parallel test run or on a fresh machine). It runs each crate's ignored `generate_fixtures` test —
- the same generators the oracle tests call — for `h264`, `hevc`, `isobmff`, `matroska` and
+ the same generators the oracle tests call — for `h264`, `hevc`, `isobmff`, `matroska`, `dnx` and
`prores`, and prints one `made` / `cached` / `skipped` line per fixture plus a summary. The
`aac`, `opus` and `h264enc` oracles generate small per-test signals on demand and are not part of
the matrix.
@@ -67,6 +67,8 @@ are never linked or shipped ([AGENTS.md](../AGENTS.md) §2).
| `h264enc` | `ffmpeg -ec 0` decodes our stream | no errors, exact frame count, **bit-identical to the encoder's reconstruction**; B-frame order checked with ffprobe; rate-control targets |
| `prores` decode | ffmpeg `prores_ks` / `prores_aw` fixtures, compared at native depth | within **±1 LSB** (different integer IDCT); alpha bit-exact |
| `prores` encode | ffmpeg decodes with `-xerror` | no errors; agrees with our decoder within ±1 |
+| `dnx` decode | ffmpeg VC-3 fixtures (13 DNxHD CIDs, DNxHR LB/SQ/HQ/HQX/444), compared at native depth | within **±2 LSB**, ≤ 100 samples per million beyond ±1 (ffmpeg's integer IDCT; we evaluate the exact IDCT) |
+| `dnx` encode | ffmpeg decodes with `-xerror` | no errors; agrees with our decoder within ±2; HQ luma PSNR ≥ 45 dB |
| `aac` decode | ffmpeg's decode of the same stream | max abs error ~1e-7 (float) |
| `aac` encode | ffmpeg decodes our stream | no errors, no clipping, CBR within ±5% of target; SNR reported |
| `isobmff` | `ffprobe -show_packets` on ffmpeg-made MP4/MOV | packet offsets, sizes, pts/dts, durations, key flags and stream parameters equal; remuxed files decode with `ffmpeg -v error` silent |
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index b5094c775..4a9c45133 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -243,8 +243,14 @@ fn wasm() -> Result<(), String> {
}
/// (crate, test target) whose ignored `generate_fixtures` test builds that crate's fixture matrix.
-const FIXTURE_GENERATORS: &[(&str, &str)] =
- &[("h264", "conformance"), ("hevc", "conformance"), ("isobmff", "oracle_demux"), ("matroska", "oracle"), ("prores", "oracle_decode")];
+const FIXTURE_GENERATORS: &[(&str, &str)] = &[
+ ("h264", "conformance"),
+ ("hevc", "conformance"),
+ ("isobmff", "oracle_demux"),
+ ("matroska", "oracle"),
+ ("prores", "oracle_decode"),
+ ("dnx", "oracle_decode"),
+];
fn fixtures(only: &[String]) -> Result<(), String> {
let unknown: Vec<&String> = only.iter().filter(|o| !FIXTURE_GENERATORS.iter().any(|(c, _)| *c == short(o))).collect();