nx_vcodec.nx source
↩ module page · 2508 lines · 152709 B
1// nx_vcodec.nx -- the reusable sovereign video codec MODULE. The proven end-to-end encoder (intra keyframe with
2// H.264-style DC prediction + inter-frame 16x16 motion compensation + 4x4 WHT transform + deadzone quant + zig-zag/RLE
3// entropy), EXTRACTED from nx_vcodec_gate (V-R5, GREEN: keyframe 459B, inter avg 114B, 7x less than full-JPEG/frame,
4// inter max-err 4/255) so the vroom daemon and the gate share ONE codec instead of duplicating it (DRY). The current
5// nishifamily.com/video 8fps sends a full JPEG every frame; this is the delta-chain encoder that replaces it.
6// Caller owns all scratch: ebuf (per-block bitstream bytes), blk (16 i64), mv (2 i64). The codec allocates nothing.
7// license_tier: ORIGINAL
8import "nx_vmotion.nx"
9import "nx_vtransform.nx"
10import "nx_vtransform_dct.nx"
11import "nx_vtransform_dct2.nx"
12import "nx_dct8.nx" // 8x8 integer DCT-II -- the variable-transform-size residual path (task #46 rung 2)
13import "nx_ventropy.nx"
14import "nx_rangecoder.nx" // rc_block_encode/decode + rc_enc/dec state -- the CABAC-class entropy path (task #31)
15import "nx_rangecoder_sig.nx" // rc_sig_encode/decode -- neighbor-context significance-map coder (vcv-6, emode bit5; +3% measured, gate-proven)
16import "nx_vskip.nx"
17import "nx_vsubpel.nx"
18const VC_MAGIC_2147483647: i64 = 2147483647
19const VC_MAGIC_8192: i64 = 8192
20const VC_MAGIC_4096: i64 = 4096
21const VC_MAGIC_5008: i64 = 5008
22const VC_MAGIC_1152921504606846976: i64 = 1152921504606846976
23const VC_MAGIC_5392: i64 = 5392
24const VC_MAGIC_2048: i64 = 2048
25const VC_MAGIC_5440: i64 = 5440
26
27// bits a varint level / MV component costs (5-bit length prefix + the zig-zag magnitude bits) -- the entropy-cost proxy
28func vc_vbits(v: i64) -> i64 { return 5 + ve_blen(ve_zze(v)) }
29
30// encode a 4x4 residual sub-block: transform+quant+entropy -> returns bits; leaves the RECON residual in blk (so the
31// caller can add it back to the predictor to reconstruct exactly what the decoder will).
32func vc_enc_sub(blk: *i64, qp: i64, ebuf: *u8) -> i64 {
33 vt_fwd(blk)
34 vt_quant(blk, qp)
35 let bits: i64 = ve_encode(blk, ebuf) // entropy is lossless -> blk still holds the quantized coeffs
36 vt_dequant(blk, qp)
37 vt_inv(blk)
38 return bits
39}
40// H.264-style intra DC prediction: a 4x4 sub-block's predictor = mean of the already-reconstructed neighbour pixels
41// above + to the left (raster order guarantees they exist). Frame corner -> 128. Makes the intra residual small.
42func vc_dc_pred(recon: *u8, W: i64, sx: i64, sy: i64) -> i64 {
43 var sum: i64 = 0
44 var cnt: i64 = 0
45 if sy > 0 { var k: i64 = 0; while k < 4 { sum = sum + (recon[(sy-1)*W + (sx+k)] as i64); cnt = cnt + 1; k = k + 1 } }
46 if sx > 0 { var k: i64 = 0; while k < 4 { sum = sum + (recon[(sy+k)*W + (sx-1)] as i64); cnt = cnt + 1; k = k + 1 } }
47 if cnt == 0 { return 128 }
48 return sum / cnt
49}
50// One pixel (xx,yy) of a 4x4 intra block predicted from already-reconstructed, edge-substituted neighbors.
51// mode 0=DC (mean), 1=vertical (copy top), 2=horizontal (copy left), 3=diagonal-down-right. This is the directional
52// intra-prediction lever (RT-003 R1b: best-of-4 cut the real-frame intra residual up to 83% vs DC-only). All-scalar
53// args keep the codec allocation-free and wasm-clean. Encoder + decoder call this identically -> bit-exact.
54func vc_pred_px(mode: i64, xx: i64, yy: i64, t0: i64, t1: i64, t2: i64, t3: i64, l0: i64, l1: i64, l2: i64, l3: i64, corner: i64, dc: i64) -> i64 {
55 if mode == 0 { return dc }
56 if mode == 1 { if xx==0 { return t0 } if xx==1 { return t1 } if xx==2 { return t2 } return t3 }
57 if mode == 2 { if yy==0 { return l0 } if yy==1 { return l1 } if yy==2 { return l2 } return l3 }
58 // mode 3 -- diagonal down-right: x>y reads the top edge, x<y the left edge, x==y the corner
59 if xx > yy { let i: i64 = xx-yy-1; if i==0 { return t0 } if i==1 { return t1 } if i==2 { return t2 } return t3 }
60 if xx < yy { let j: i64 = yy-xx-1; if j==0 { return l0 } if j==1 { return l1 } if j==2 { return l2 } return l3 }
61 return corner
62}
63// encode one 16x16 macroblock (bx,by in 16-units); reconstructs into `recon`; returns bits. keyframe=1 -> intra (DC
64// prediction), keyframe=0 -> inter (16x16 motion search +/-8 against prev, residual coded).
65func vc_enc_block(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, bx: i64, by: i64, qp: i64, keyframe: i64, sad_thresh: i64, ebuf: *u8, blk: *i64, mv: *i64) -> i64 {
66 let cx: i64 = bx*16
67 let cy: i64 = by*16
68 var bits: i64 = 1 // 1 bit: intra/inter flag
69 mv[0] = 0; mv[1] = 0
70 if keyframe == 0 {
71 // SKIP-block (V-R6): if the macroblock is UNCHANGED at its own position (the zero-motion residual SAD is
72 // below threshold) code it as a single skip bit and reconstruct by copying prev. A talking-head's static
73 // background skips almost everywhere, so a near-static frame costs a handful of bits instead of the
74 // per-block flag+MV+EOB floor. (Decision is on the ZERO-MV SAD, not the search MV: a linear-gradient region
75 // has many equal-SAD motion vectors, so the search MV may be nonzero even when the block didn't change.)
76 bits = bits + 1 // skip flag (1 bit, inter only)
77 if vs_skip(vm_sad_zero(cur, prev, W, bx, by, 16), 0, 0, sad_thresh) == 1 {
78 var cy0: i64 = 0
79 while cy0 < 16 {
80 var cx0: i64 = 0
81 while cx0 < 16 { recon[(cy+cy0)*W + (cx+cx0)] = prev[(cy+cy0)*W + (cx+cx0)]; cx0 = cx0 + 1 }
82 cy0 = cy0 + 1
83 }
84 return bits // SKIP: 2 bits total (inter flag + skip flag), recon = prev
85 }
86 vm_search(cur, prev, W, H, bx, by, 16, 8, mv, blk) // not skipped -> 16x16 motion search +/-8, code MV + residual
87 bits = bits + vc_vbits(mv[0]) + vc_vbits(mv[1])
88 }
89 var sj: i64 = 0
90 while sj < 4 {
91 var si: i64 = 0
92 while si < 4 {
93 let sx: i64 = cx + si*4
94 let sy: i64 = cy + sj*4
95 var dcp: i64 = 128
96 if keyframe == 1 { dcp = vc_dc_pred(recon, W, sx, sy) } // intra spatial predictor (DC of neighbours)
97 // build the 4x4 residual (cur - predictor)
98 var yy: i64 = 0
99 while yy < 4 {
100 var xx: i64 = 0
101 while xx < 4 {
102 let c: i64 = cur[(sy+yy)*W + (sx+xx)] as i64
103 var pred: i64 = dcp
104 if keyframe == 0 { pred = prev[(sy+yy+mv[1])*W + (sx+xx+mv[0])] as i64 }
105 blk[yy*4 + xx] = c - pred
106 xx = xx + 1
107 }
108 yy = yy + 1
109 }
110 bits = bits + vc_enc_sub(blk, qp, ebuf) // blk now = recon residual
111 // reconstruct pixels = predictor + recon residual (clamped)
112 yy = 0
113 while yy < 4 {
114 var xx: i64 = 0
115 while xx < 4 {
116 var pred: i64 = dcp
117 if keyframe == 0 { pred = prev[(sy+yy+mv[1])*W + (sx+xx+mv[0])] as i64 }
118 var v: i64 = pred + blk[yy*4 + xx]
119 if v < 0 { v = 0 }
120 if v > 255 { v = 255 }
121 recon[(sy+yy)*W + (sx+xx)] = v as u8
122 xx = xx + 1
123 }
124 yy = yy + 1
125 }
126 si = si + 1
127 }
128 sj = sj + 1
129 }
130 return bits
131}
132// encode a whole frame; reconstructs into recon; returns total bits.
133func vc_enc_frame(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, keyframe: i64, sad_thresh: i64, ebuf: *u8, blk: *i64, mv: *i64) -> i64 {
134 var bits: i64 = 0
135 let BW: i64 = W / 16
136 let BH: i64 = H / 16
137 var by: i64 = 0
138 while by < BH { var bx: i64 = 0
139 while bx < BW { bits = bits + vc_enc_block(cur, prev, recon, W, H, bx, by, qp, keyframe, sad_thresh, ebuf, blk, mv); bx = bx + 1 } by = by + 1 }
140 return bits
141}
142
143// ============================================================================================================
144// TRANSMITTABLE CODEC: a self-describing contiguous bitstream + an INDEPENDENT decoder. vc_enc_frame above only
145// MEASURES bits + reconstructs encoder-side; these write the actual stream the daemon relays and reconstruct it on
146// the far side from ONLY (prev frame + stream) -- no access to the original. Stream = [keyframe:1] then per-MB raster:
147// intra MB : per 4x4 sub-block, the entropy-coded DC-prediction residual
148// inter MB : [skip:1]; if skip -> copy prev; else [mv_dx:vlen][mv_dy:vlen] + per-sub-block residual
149// Encoder + decoder run identical prediction in identical order, so their reconstructions are bit-exact.
150// ============================================================================================================
151
152// RDOQ LAGRANGIAN DIVISOR (declared HERE, above every reader, per the fwd-const law). 4 = the
153// measured optimum (2026-07-29 sweep {8,4,2} + matched-rate LOOK; derivation history at the retired
154// site ~line 380). seq1283 TOMBSTONE: an AQ-PER-CLASS divisor table (rctx[10] thread) was BUILT,
155// proven bit-inert at the null table, then REFUTED BY MEASUREMENT -- every per-class arm LOST on
156// every sequence (up to +95 permille) because vc_aq_qp ALREADY couples lambda to the class through
157// the adapted step (flat qp*0.7 => lambda already ~2x smaller); a per-class divisor double-counts.
158// Evidence: _build/aq/*.pts + the ws=video-aq-lambda journal. Machinery stripped per the
159// proven-zero law.
160const VC_RDOQ_LAM_DIV: i64 = 4
161// EXACT-RATE TRAILING TRIM (trellis rung 1, 2026-07-29): the per-coeff RDOQ prices a removal with
162// a ~12-bit MODEL; the sig-map coder pays a REAL rate for the last nonzero that includes the
163// EOB/run structure the model cannot see. When armed, after RDOQ the sig path (tf==1, 4x4) drops
164// trailing nonzeros while the EXACT rate saving (rc_sig_cost_q8, the coder's own read-only cost
165// with the LIVE adaptive probs) beats the distortion, iterating until unprofitable. Encoder-only.
166// ARMED BY EMODE BIT12 (4096): MEASURED 2026-07-29 = BD -28/-18/-8/-6 permille (AVG -1.5%) at
167// +17.6% encode cost (two full-block exact-cost calls per 4x4) => the ARCHIVAL profile (stored
168// content, no fps budget) arms it; RTC (2593) does NOT. The RTC-cheap version = incremental
169// delta-rate (own bits + the two neighbor-context deltas), filed on the board.
170// threaded sub-block encode: transform+quant -> write coeffs into buf at bp -> dequant+inv (recon residual left in blk)
171func vc_enc_sub_at(blk: *i64, qp: i64, buf: *u8, bp: i64) -> i64 { return vc_enc_sub_at_tf(blk, qp, buf, bp, 0) }
172// threaded sub-block encode with TRANSFORM SELECT: tf=0 clean Walsh-Hadamard (shipped default; Walsh 1923 /
173// Hadamard 1893, pure math, no patent); tf=1 clean royalty-free integer DCT-II (nx_vtransform_dct2 -- 1974 prior
174// art, non-standard scale; NOT the H.264/AVC Cf/Ci core + Mf/Vi quant tables, NOT HEVC). Measured head-to-head by
175// nx_vcodec_dct2_rd_gate; the shipped daemon + existing gates call the tf=0 delegator above -> WHT, unchanged.
176func vc_enc_sub_at_tf(blk: *i64, qp: i64, buf: *u8, bp: i64, tf: i64) -> i64 {
177 // RDOQ on the DCT path (encoder-only, decoder-transparent -- the decoder just dequantizes the levels it
178 // receives, so this ships with NO wire-version bump; x264-trellis-class). The "unmeasurable/hung" saga
179 // was a MISSING LOOP INCREMENT in vt2_quant_rdoq (not CPU contention) -- fixed + gated by rdoq2 + rd_bench.
180 if tf == 1 { vt2_fwd(blk); vt2_quant_rdoq(blk, qp) } else { vt_fwd(blk); vt_quant(blk, qp) }
181 let bp2: i64 = ve_encode_at(blk, buf, bp)
182 if tf == 1 { vt2_dequant(blk, qp); vt2_inv(blk) } else { vt_dequant(blk, qp); vt_inv(blk) }
183 return bp2
184}
185// threaded sub-block decode: read coeffs from buf at bp -> dequant+inv (recon residual left in blk)
186func vc_dec_sub_at(buf: *u8, bp: i64, qp: i64, blk: *i64) -> i64 { return vc_dec_sub_at_tf(buf, bp, qp, blk, 0) }
187func vc_dec_sub_at_tf(buf: *u8, bp: i64, qp: i64, blk: *i64, tf: i64) -> i64 {
188 let bp2: i64 = ve_decode_at(buf, blk, bp)
189 if tf == 1 { vt2_dequant(blk, qp); vt2_inv(blk) } else { vt_dequant(blk, qp); vt_inv(blk) }
190 return bp2
191}
192// RANGE-CODER coeff variants (task #31): identical transform/quant/reconstruct, but the quantized coeffs go
193// through the adaptive binary range coder (est state + probs contexts, writing to/from rcbuf) instead of CAVLC.
194// The ~36% smaller coefficient stream (nx_rangecoder_gain_gate) with zero change to the reconstruction path.
195func vc_enc_sub_rc(blk: *i64, qp: i64, est: *i64, rcbuf: *u8, probs: *i64, tf: i64) -> i64 {
196 if tf == 1 { vt2_fwd(blk); vt2_quant_rdoq(blk, qp) } else { vt_fwd(blk); vt_quant(blk, qp) } // RDOQ (see vc_enc_sub_at_tf)
197 rc_block_encode(blk, est, rcbuf, probs)
198 if tf == 1 { vt2_dequant(blk, qp); vt2_inv(blk) } else { vt_dequant(blk, qp); vt_inv(blk) }
199 return 0
200}
201func vc_dec_sub_rc(est: *i64, rcbuf: *u8, probs: *i64, qp: i64, blk: *i64, tf: i64) -> i64 {
202 rc_block_decode(blk, est, rcbuf, probs)
203 if tf == 1 { vt2_dequant(blk, qp); vt2_inv(blk) } else { vt_dequant(blk, qp); vt_inv(blk) }
204 return 0
205}
206// SIG-MAP variants (emode bit5, vcv-6): identical transform/quant/reconstruct but coefficients go through the
207// NEIGHBOR-CONTEXT significance-map coder (rc_sig, +3% vs run-length, bit-exact -- nx_vcodec_sigcoder_gate).
208// n=coeff count (16 for 4x4, 64 for 8x8), wd=row width (4/8), sigmap=caller i64[>=n] scratch. raster order.
209func vc_enc_sub_sig(blk: *i64, qp: i64, est: *i64, rcbuf: *u8, probs: *i64, tf: i64, n: i64, wd: i64, sigmap: *i64) -> i64 {
210 if tf == 1 { vt2_fwd(blk); vt2_quant_rdoq(blk, qp) } else { vt_fwd(blk); vt_quant(blk, qp) } // RDOQ: same levels as the rl path (fair + optimal)
211 rc_sig_encode(blk, n, wd, est, rcbuf, probs, sigmap)
212 if tf == 1 { vt2_dequant(blk, qp); vt2_inv(blk) } else { vt_dequant(blk, qp); vt_inv(blk) }
213 return 0
214}
215func vc_dec_sub_sig(est: *i64, rcbuf: *u8, probs: *i64, qp: i64, blk: *i64, tf: i64, n: i64, wd: i64, sigmap: *i64) -> i64 {
216 rc_sig_decode(blk, n, wd, est, rcbuf, probs, sigmap)
217 if tf == 1 { vt2_dequant(blk, qp); vt2_inv(blk) } else { vt_dequant(blk, qp); vt_inv(blk) }
218 return 0
219}
220// COEFF ENTROPY DISPATCH: rctx=0 (or emode bit0 clear) -> CAVLC (bp-threaded, returns new bp); emode bit0
221// set -> RANGE (coeffs go to est/rcbuf with probs, bp unchanged). rctx layout = [emode, est, probs, rcbuf, ...]
222// (emode is a bitfield -- bit0 = range; other bits are encoder-side flags this dispatch ignores).
223func vc_coeff_enc(blk: *i64, qp: i64, buf: *u8, bp: i64, tf: i64, rctx: *i64) -> i64 {
224 if (rctx as i64) != 0 { if (rctx[0] & 1) == 1 {
225 if (rctx[0] & 32) != 0 { // bit5 = sig-map (vcv-6); sigmap scratch = t8c RES slab @i64-index 370 (literal: the const is defined below this fn, forward-ref mis-resolves)
226 vc_enc_sub_sig(blk, qp, rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, tf, 16, 4, (rctx[4] + 370*8) as *i64); return bp }
227 vc_enc_sub_rc(blk, qp, rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, tf); return bp } }
228 return vc_enc_sub_at_tf(blk, qp, buf, bp, tf)
229}
230func vc_coeff_dec(buf: *u8, bp: i64, qp: i64, blk: *i64, tf: i64, rctx: *i64) -> i64 {
231 if (rctx as i64) != 0 { if (rctx[0] & 1) == 1 {
232 if (rctx[0] & 32) != 0 {
233 vc_dec_sub_sig(rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, qp, blk, tf, 16, 4, (rctx[4] + 370*8) as *i64); return bp }
234 vc_dec_sub_rc(rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, qp, blk, tf); return bp } }
235 return vc_dec_sub_at_tf(buf, bp, qp, blk, tf)
236}
237// encode one macroblock into the stream at bp; reconstructs into recon; returns the new bit position.
238// ---- ADAPTIVE QUANTIZATION (task #46/#31 rung: the #1 quality-per-bit lever for blockiness -- x264's AQ).
239// Spend FINER quant on FLAT macroblocks (skin, gradients, background) where block edges are glaringly
240// visible; COARSER on busy/textured MBs where the eye can't see it. Net bitrate ~unchanged (redistribution).
241// A 2-bit level per MB is signalled so the decoder dequantises identically. mad = mean-abs-deviation (cheap
242// proxy for variance). ----
243func vc_mb_mad(cur: *u8, W: i64, cx: i64, cy: i64) -> i64 {
244 var sum: i64 = 0; var yy: i64 = 0
245 while yy < 16 { var xx: i64 = 0
246 while xx < 16 { sum = sum + (cur[(cy+yy)*W + cx+xx] & 0xff); xx = xx + 1 } yy = yy + 1 }
247 let mean: i64 = sum / 256
248 var mad: i64 = 0; yy = 0
249 while yy < 16 { var xx: i64 = 0
250 while xx < 16 { let d: i64 = (cur[(cy+yy)*W + cx+xx] & 0xff) - mean; if d < 0 { mad = mad - d } else { mad = mad + d } xx = xx + 1 } yy = yy + 1 }
251 return mad / 256 }
252func vc_aq_level(mad: i64) -> i64 {
253 if mad < 4 { return 0 } // very flat -> finest quant (blocking most visible here)
254 if mad < 10 { return 1 }
255 if mad < 22 { return 2 }
256 return 3 } // busy -> coarsest (eye masks it)
257func vc_aq_qp(qp: i64, level: i64) -> i64 { // IDENTICAL on enc + dec
258 var q: i64 = qp
259 // AQ AUDIT (MSU-measured): the old qp*1.3 COARSENING of busy MBs cost 28-30pct PSNR-BD-rate on detail content
260 // (foreman/bus/mobile) -- it threw away the very detail the eye tracks. KEEP finer quant on FLAT MBs (fights
261 // visible blocking on faces/gradients = the perceptual win, esp. for comms) but DROP the coarsening.
262 if level == 0 { q = (qp * 7) / 10 } else { if level == 1 { q = (qp * 9) / 10 } }
263 if q < 2 { q = 2 }
264 return q }
265
266// ============================================================================================================
267// PER-MB VARIABLE TRANSFORM SIZE (task #46 rung 2 -- the HEVC-jump lever). nx_vcodec_tsize_rd_gate measured
268// the 8x8 DCT (nx_dct8) at 44-75% fewer bytes than 4x4 at matched PSNR on FLAT content (energy compaction),
269// ~parity on textured. So: per macroblock, flat -> 8x8 (4 sub-blocks), textured -> 4x4 (16 sub-blocks),
270// signalled by an EXPLICIT 1 bit/MB (policy can evolve to true RD-select later with zero decoder change).
271// All 8x8 scratch lives in ONE caller-allocated i64[VC_T8_SIZE] slab (the codec allocates nothing), carried
272// to the block coder in rctx[4]. rctx = i64[>=6] = [emode, est, probs, rcbuf, t8c, t8bitpos]; emode is a
273// BITFIELD: bit0 = range coder (0=CAVLC), bit2 = encoder RD-AUTO transform select on inter MBs (the frame
274// fn reserves the t8 bit and the block coder patches it post-ME; decoders NEVER see bit2 -- the stream is
275// identical either way, which is the whole point of the explicit per-MB bit).
276// ============================================================================================================
277const VC_T8_M: i64 = 0 // [0..63] DCT8 basis matrix (nx_dct8_init)
278const VC_T8_ZZ: i64 = 64 // [64..127] 8x8 zig-zag scan table
279const VC_T8_WORK: i64 = 128 // [128..191] spatial residual in / recon residual out
280const VC_T8_FREQ: i64 = 192 // [192..255] frequency coeffs / quant indices
281const VC_T8_SCR: i64 = 256 // [256..319] 2D transform scratch (first 16 doubling as the RD 4x4 trial block)
282const VC_T8_TA: i64 = 320 // [320..327] 1D transform tmp in
283const VC_T8_TB: i64 = 328 // [328..335] 1D transform tmp out
284const VC_T8_TE: i64 = 336 // [336..351] intra top edge incl above-right (up to 2n = 16 px)
285const VC_T8_LE: i64 = 352 // [352..359] intra left edge (up to 8 px)
286const VC_T8_MM: i64 = 360 // [360..367] in-MB mode memory (above-mode per sub-block column, MPM)
287const VC_T8_EO: i64 = 368 // [368..369] edge-gather out: [corner, dc] (survives the transform temps)
288const VC_T8_RES: i64 = 370 // [370..625] 16x16 MB residual for the RD transform-size trial
289const VC_T8_SIZE: i64 = 626 // slab length in i64 elements
290
291// MOTION SEARCH RADIUS (F1111, rule-11: this was the literal 16 hardcoded at six vm_search_q call sites).
292// R is the dominant encode cost: the window is (2R+1)^2 candidates PER BLOCK -- R=16 is 1089, R=8 is 289,
293// R=4 is 81. The 825 deadzone-floor prune only trims rings r>2 and only once b[0] falls under the quant
294// floor, so on detailed content the full window is walked. Declared HERE, above every reader (the first is
295// nx_vcodec.nx:970) -- the VC_EO_* fwd-const miscompile proved a const below its readers silently reads 0.
296const VC_ME_R: i64 = 16
297
298func vc_t8p(t8c: *i64, off: i64) -> *i64 { return ((t8c as i64) + off * 8) as *i64 }
299
300// t8 DETAIL GUARD (field 786/787 "still blocky/low quality", root-caused): the MB-mean mad classifies an
301// MB holding one small high-contrast feature (an eye on flat skin) as FLAT -> 8x8 -> the feature's energy
302// spreads across many individually sub-threshold 8x8 coefficients -> the deadzone kills them ALL -> the
303// detail VANISHES and the surviving low-frequency approximation shows 8x8 structure. Energy compaction
304// helps smooth content and HURTS localized detail -- and PSNR barely sees a 16-px feature while the eye
305// stares at it. So a large transform requires UNIFORM flatness: every 4x4 sub-block's own summed
306// deviation must sit inside the flat-noise band (sum|d| < 128 over 16 px = mean-abs-dev < 8, i.e. below
307// the vc_aq_level lv2 texture bound), else the MB keeps 4x4. Encoder-only policy: the explicit per-MB
308// bits keep every decoder oblivious.
309func vc_mb_t8_ok(cur: *u8, W: i64, cx: i64, cy: i64) -> i64 {
310 var sj: i64 = 0
311 while sj < 4 {
312 var si: i64 = 0
313 while si < 4 {
314 let sx: i64 = cx + si*4
315 let sy: i64 = cy + sj*4
316 var sum: i64 = 0
317 var yy: i64 = 0
318 while yy < 4 { var xx: i64 = 0
319 while xx < 4 { sum = sum + (cur[(sy+yy)*W + sx+xx] & 0xff); xx = xx + 1 } yy = yy + 1 }
320 let mean: i64 = sum / 16
321 var mad: i64 = 0
322 yy = 0
323 while yy < 4 { var xx: i64 = 0
324 while xx < 4 {
325 let d: i64 = (cur[(sy+yy)*W + sx+xx] & 0xff) - mean
326 if d < 0 { mad = mad - d } else { mad = mad + d }
327 xx = xx + 1 } yy = yy + 1 }
328 if mad >= 128 { return 0 }
329 si = si + 1
330 }
331 sj = sj + 1
332 }
333 return 1
334}
335
336// fill the slab's constant parts: DCT8 matrix + the JPEG 8x8 zig-zag (generated algorithmically -- no
337// literal table, no const-ptr-index footgun). Call once per session/thread before any t8 frame call.
338func vc_t8_init(t8c: *i64) -> i64 {
339 nx_dct8_init(vc_t8p(t8c, VC_T8_M))
340 let zz: *i64 = vc_t8p(t8c, VC_T8_ZZ)
341 var zi: i64 = 0
342 var zr: i64 = 0
343 var zc: i64 = 0
344 var up: i64 = 1
345 while zi < 64 { zz[zi] = zr*8 + zc; zi = zi + 1
346 if up == 1 { if zc == 7 { zr = zr + 1; up = 0 } else { if zr == 0 { zc = zc + 1; up = 0 } else { zr = zr - 1; zc = zc + 1 } } }
347 else { if zr == 7 { zc = zc + 1; up = 1 } else { if zc == 0 { zr = zr + 1; up = 1 } else { zr = zr + 1; zc = zc - 1 } } } }
348 return 0
349}
350// 8x8 quant/dequant: nx_dct8 coeffs are ~orthonormal scale, so quantize in a x4 domain with deadzone
351// truncation and divisor q -> effective step q/4 = IDENTICAL to the 4x4 vt2 path's effective step
352// (q<<10 over 2D scale 4096). One qp therefore means one quality on BOTH transform sizes, and the
353// vc_aq_qp per-MB adaptation carries over unchanged. Uniform matrix (matches the 4x4 path; perceptual
354// per-frequency matrices are the separate quant-matrix task).
355func vc_quant8(f: *i64, q: i64) -> i64 {
356 // F1116 twin: same near-centered rounding offset as vt2_quant/vt2_quant_rdoq (knee measured there;
357 // encoder-only -- vc_dequant8 and every decoder untouched, vc_rdoq8 still rate-trims on top).
358 let f0: i64 = (q * VC_QOFF_24) / 24
359 var i: i64 = 0
360 while i < 64 {
361 let v: i64 = f[i] << 2
362 var r: i64 = 0
363 if v >= 0 { r = (v + f0) / q } else { r = 0 - ((0 - v + f0) / q) }
364 f[i] = r
365 i = i + 1
366 }
367 return 0
368}
369func vc_dequant8(f: *i64, q: i64) -> i64 {
370 var i: i64 = 0
371 while i < 64 {
372 let v: i64 = f[i] * q
373 if v >= 0 { f[i] = (v + 2) >> 2 } else { f[i] = 0 - ((2 - v) >> 2) }
374 i = i + 1
375 }
376 return 0
377}
378// 8x8 residual sub-block encode: WORK (spatial residual) -> DCT8 -> quant -> entropy (CAVLC-64 or range
379// via rctx, same dispatch rule as vc_coeff_enc) -> dequant -> inverse -> WORK holds the decoder-exact
380// recon residual (the caller adds it back to the predictor). Returns the new bit position.
381// RDOQ (rate-distortion optimized quantization) -- the classic DECODER-TRANSPARENT encoder win: after
382// deadzone quant, greedily reduce each coefficient's magnitude by 1 (toward 0) whenever the distortion it
383// adds is worth less than lambda * the bits it saves. The decoder only ever sees the final levels and
384// dequantizes them normally -> ZERO decoder change, ZERO wire-version bump, works in EVERY room including
385// old clients. The encoder reconstructs from these same RDOQ'd levels so enc==dec bit-exactness holds by
386// construction. Distortion is transform-domain SSE (Parseval: minimizing it minimizes spatial SSE for an
387// orthogonal transform); rate is the exact CAVLC token cost (the range coder tracks it monotonically).
388// c8[] = pre-quant coeffs in the f<<2 domain, lev[] = deadzone levels (modified in place), q = quant step.
389// RDOQ LAGRANGIAN DIVISOR (2026-07-29, MEASURED then LOOKED): lambda = step^2 / VC_RDOQ_LAM_DIV in
390// each transform's own domain (identical per-pixel aggression both paths: 4x4 d^2 at scale-4096^2 ==
391// 8x8 q^2 in the x4 domain). History: 16 was mathematically inert (below the q^2 minimum), 8 fired
392// and shipped through build 860. DERIVATION OF 4: the mode/skip plane trades at lam ~ q^2/32
393// pixel^2/bit (J = 32*sse*256 + qp^2*bits_q8) while divisor-8 RDOQ trades at q^2/128 -- 4x less
394// bit-averse than the decisions above it. The sweep {8,4,2} on the 4-seq at the SHIPPED emode 2593:
395// div4 = BD -7.30% avg (foreman -14.8 akiyo -10.2 bus -2.9 mobile -1.3); div2 overshoots (texture
396// loses) => the optimum is bracketed at 4. Perceptual gate (the fixed-q sse rise was a q-axis
397// illusion): matched-RATE frame pairs (nx_vcodec_look_dump, cumbytes-picked) PASS on face + speckle
398// + foliage + rail crops, and the per-frame sse trace shows NO flicker (foreman smoother than div8).
399// Evidence: _offc/rung2/look/ + bd_lam.txt; ws=video-look-gate 2026-07-29.
400// (const VC_RDOQ_LAM_DIV lives at the TOP of the file, above every reader, per the fwd-const law.)
401// 4x4 DCT-II RDOQ (the DOMINANT residual path on real content -- most MBs go 4x4, not 8x8). Combined
402// quant+RDOQ so the pre-quant coeff `v` is in hand (no scratch needed). Decoder-transparent: same recon
403// from the same levels. d = q<<DCT2_QSHIFT is the vt2 quant step; lambda ~ (d/4)^2 (measured via rd_bench).
404func vt2_quant_rdoq(blk: *i64, q: i64) -> i64 {
405 let d: i64 = q << DCT2_QSHIFT
406 let f0: i64 = (d * VC_QOFF_24) / 24 // F1116 encoder-side rounding offset (see nx_vtransform_dct2.nx)
407 // lambda = d^2 / VC_RDOQ_LAM_DIV -- history + the divisor-4 derivation (cross-plane consistency,
408 // BD sweep, matched-rate LOOK + flicker trace) live at the const's declaration. The original /8
409 // note: zeroing a deadzone level-1 costs D in [d^2, 3d^2) and saves ~12 bits; /16 could never fire.
410 let lam: i64 = (d * d) / VC_RDOQ_LAM_DIV
411 var nz: i64 = 0
412 var i: i64 = 0
413 while i < 16 {
414 let v: i64 = blk[i]
415 var r: i64 = 0
416 if v >= 0 { r = (v + f0) / d } else { r = 0 - ((0 - v + f0) / d) }
417 // (2026-07-29 negative result, MEASURED: a greedy multi-step descent here is BIT-INERT -- after
418 // deadzone quant |v-r*d| < d, so a second step costs ~3d^2 against lam*dRt ~ d^2/8 * <=4 bits;
419 // it can never fire. Single-step IS complete at this lambda. 4-seq + wasm A/B byte-identical.)
420 if r != 0 {
421 var aR: i64 = r; var sgn: i64 = 1
422 if r < 0 { aR = 0 - r; sgn = 0 - 1 }
423 let ce: i64 = v - r * d; let Dcur: i64 = ce * ce
424 let nR: i64 = (aR - 1) * sgn
425 let ne: i64 = v - nR * d; let Dnew: i64 = ne * ne
426 var dRt: i64 = 0
427 if nR == 0 { dRt = 10 + ve_blen(ve_zze(r)) } else { dRt = ve_blen(ve_zze(r)) - ve_blen(ve_zze(nR)) }
428 if Dnew - Dcur < lam * dRt { r = nR }
429 }
430 if r != 0 { nz = nz + 1 }
431 blk[i] = r
432 i = i + 1
433 }
434 return nz
435}
436func vc_rdoq8(lev: *i64, c8: *i64, q: i64, zz8: *i64) -> i64 {
437 let lam: i64 = (q * q) / VC_RDOQ_LAM_DIV
438 var k: i64 = 0
439 while k < 64 {
440 let idx: i64 = zz8[k]
441 let L: i64 = lev[idx]
442 if L != 0 {
443 var aL: i64 = L; var sgn: i64 = 1
444 if L < 0 { aL = 0 - L; sgn = 0 - 1 }
445 let Cc: i64 = c8[idx]
446 let ce: i64 = Cc - L * q; let Dcur: i64 = ce * ce
447 let nL: i64 = (aL - 1) * sgn
448 let ne: i64 = Cc - nL * q; let Dnew: i64 = ne * ne
449 var dR: i64 = 0
450 if nL == 0 { dR = 12 + ve_blen(ve_zze(L)) } // whole token removed (1+6+5 header + level bits)
451 else { dR = ve_blen(ve_zze(L)) - ve_blen(ve_zze(nL)) } // magnitude bits saved
452 if Dnew - Dcur < lam * dR { lev[idx] = nL }
453 }
454 k = k + 1
455 }
456 return 0
457}
458// F1114b split: the ENCODE+RECON tail of the 8x8 sub emit, with the sig-map scratch as a PARAMETER.
459// vc_enc_sub8 passes RES (its csave there is dead by encode time -- historical placement); the levels
460// path passes SCR (RES holds the banked trial levels for the OTHER quadrants and must survive; SCR is
461// free until inverse_2d claims it, strictly after the encode). Scratch choice cannot touch the bits.
462// PRECONDITION: freq holds the final (RDOQ'd) levels; postcondition: work = decoder-exact recon residual.
463func vc_enc_sub8_tail(t8c: *i64, qp: i64, buf: *u8, bp0: i64, rctx: *i64, sigscr: *i64) -> i64 {
464 let M: *i64 = vc_t8p(t8c, VC_T8_M)
465 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
466 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ)
467 let scr: *i64 = vc_t8p(t8c, VC_T8_SCR)
468 let ta: *i64 = vc_t8p(t8c, VC_T8_TA)
469 let tb: *i64 = vc_t8p(t8c, VC_T8_TB)
470 let zz8: *i64 = vc_t8p(t8c, VC_T8_ZZ)
471 var bp: i64 = bp0
472 var rcmode: i64 = 0
473 if (rctx as i64) != 0 { if (rctx[0] & 1) == 1 { rcmode = 1 } }
474 if rcmode == 1 {
475 if (rctx[0] & 32) != 0 { rc_sig_encode(freq, 64, 8, rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, sigscr) } // bit5 sig-map (vcv-6)
476 else { rc_block64_encode(freq, rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, zz8) }
477 }
478 else { bp = ve64_encode_at(freq, buf, bp, zz8) }
479 vc_dequant8(freq, qp)
480 nx_dct8_inverse_2d(M, freq, work, scr, ta, tb)
481 return bp
482}
483func vc_enc_sub8(t8c: *i64, qp: i64, buf: *u8, bp0: i64, rctx: *i64) -> i64 {
484 let M: *i64 = vc_t8p(t8c, VC_T8_M)
485 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
486 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ)
487 let scr: *i64 = vc_t8p(t8c, VC_T8_SCR)
488 let ta: *i64 = vc_t8p(t8c, VC_T8_TA)
489 let tb: *i64 = vc_t8p(t8c, VC_T8_TB)
490 nx_dct8_forward_2d(M, work, freq, scr, ta, tb)
491 let csave: *i64 = vc_t8p(t8c, VC_T8_RES) // pre-quant coeffs in the f<<2 domain; RES is
492 var ci: i64 = 0; while ci < 64 { csave[ci] = freq[ci] << 2; ci = ci + 1 } // used SEQUENTIALLY (csave -> rdoq
493 vc_quant8(freq, qp) // consumes it BEFORE the sig-map coder reuses
494 vc_rdoq8(freq, csave, qp, vc_t8p(t8c, VC_T8_ZZ)) // RES as its sigmap scratch in the tail)
495 return vc_enc_sub8_tail(t8c, qp, buf, bp0, rctx, vc_t8p(t8c, VC_T8_RES))
496}
497func vc_dec_sub8(buf: *u8, bp0: i64, qp: i64, t8c: *i64, rctx: *i64) -> i64 {
498 let M: *i64 = vc_t8p(t8c, VC_T8_M)
499 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
500 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ)
501 let scr: *i64 = vc_t8p(t8c, VC_T8_SCR)
502 let ta: *i64 = vc_t8p(t8c, VC_T8_TA)
503 let tb: *i64 = vc_t8p(t8c, VC_T8_TB)
504 let zz8: *i64 = vc_t8p(t8c, VC_T8_ZZ)
505 var bp: i64 = bp0
506 var rcmode: i64 = 0
507 if (rctx as i64) != 0 { if (rctx[0] & 1) == 1 { rcmode = 1 } }
508 if rcmode == 1 {
509 if (rctx[0] & 32) != 0 { rc_sig_decode(freq, 64, 8, rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, vc_t8p(t8c, VC_T8_RES)) } // bit5 sig-map (vcv-6)
510 else { rc_block64_decode(freq, rctx[1] as *i64, rctx[3] as *u8, rctx[2] as *i64, zz8) }
511 }
512 else { bp = ve64_decode_at(buf, freq, bp, zz8) }
513 vc_dequant8(freq, qp)
514 nx_dct8_inverse_2d(M, freq, work, scr, ta, tb)
515 return bp
516}
517// ============================================================================================================
518// RICH INTRA (task #46 rung 3 -- the "4 -> more modes" half of the HEVC-jump line). NINE modes, one
519// n-generic predictor (n = 4 or 8), used by BOTH sub-block sizes inside the (not-yet-deployed) t8 stream
520// syntax -- legacy streams keep the 4-mode vc_pred_px path bit-for-bit. Mode field is MPM-coded (below):
521// 9 modes = 1-bit most-probable hit, else exactly 3 bits over the 8 others. Formula provenance = public
522// math re-derivation: DC mean; V/H copy extrapolation; DDR/DDL 3-tap diagonal smoothing (AVC-2003-era,
523// patents expired) with index clamping; VL/HU half-pel 2/3-tap diagonals mirrored onto top/left; PLANAR =
524// textbook bilinear surface interpolation between the two edges (Coons-patch lineage); BIAVG = plain
525// top/left average. Edges: T[0..2n-1] (top + above-right, padded), L[0..n-1], corner.
526// 0=DC 1=V 2=H 3=DDR 4=PLANAR 5=DDL 6=VL 7=HU 8=BIAVG
527func vc_pred_rich(mode: i64, xx: i64, yy: i64, n: i64, T: *i64, L: *i64, corner: i64, dc: i64) -> i64 {
528 if mode == 0 { return dc }
529 if mode == 1 { return T[xx] }
530 if mode == 2 { return L[yy] }
531 if mode == 3 {
532 // COPY down-right diagonal -- IDENTICAL semantics to the legacy 4-mode DDR (proven on hard edges:
533 // a copy propagates an aligned band with ZERO residual; a smoothing tap blurs every band edge).
534 if xx > yy { return T[xx - yy - 1] }
535 if xx < yy { return L[yy - xx - 1] }
536 return corner
537 }
538 if mode == 4 {
539 var sh: i64 = 3
540 if n == 8 { sh = 4 }
541 return ((n-1-xx)*L[yy] + (xx+1)*T[n-1] + (n-1-yy)*T[xx] + (yy+1)*L[n-1] + n) >> sh
542 }
543 if mode == 5 {
544 // COPY down-left diagonal (extends the top + above-right edge; the direction legacy lacks entirely)
545 var a: i64 = xx + yy + 1
546 let m: i64 = 2*n - 1
547 if a > m { a = m }
548 return T[a]
549 }
550 if mode == 6 {
551 let m: i64 = 2*n - 1
552 let h: i64 = yy >> 1
553 var a: i64 = xx + h
554 var b: i64 = a + 1
555 var c: i64 = a + 2
556 if a > m { a = m }
557 if b > m { b = m }
558 if c > m { c = m }
559 if (yy & 1) == 0 { return (T[a] + T[b] + 1) >> 1 }
560 return (T[a] + 2*T[b] + T[c] + 2) >> 2
561 }
562 if mode == 7 {
563 let m: i64 = n - 1
564 let h: i64 = xx >> 1
565 var a: i64 = yy + h
566 var b: i64 = a + 1
567 var c: i64 = a + 2
568 if a > m { a = m }
569 if b > m { b = m }
570 if c > m { c = m }
571 if (xx & 1) == 0 { return (L[a] + L[b] + 1) >> 1 }
572 return (L[a] + 2*L[b] + L[c] + 2) >> 2
573 }
574 return (T[xx] + L[yy] + 1) >> 1
575}
576// gather the edge-substituted reconstructed neighbours for an n x n sub-block at (sx,sy): T[0..n-1] = row
577// above, T[n..2n-1] = above-right (real pixels when `ar`==1 and inside the frame, else replicate T[n-1]),
578// L[0..n-1] = column left, out[0]=corner, out[1]=dc (mean of available T[0..n-1] + L, 128 when neither --
579// identical rule to the legacy path). Availability: top iff sy>ytop, left iff sx>0; `ar` is the caller's
580// raster-decodedness verdict for the above-right block.
581func vc_gather_edges(recon: *u8, W: i64, sx: i64, sy: i64, n: i64, ytop: i64, ar: i64, T: *i64, L: *i64, out: *i64) -> i64 {
582 var k: i64 = 0
583 while k < 2*n { T[k] = 128; k = k + 1 }
584 k = 0
585 while k < n { L[k] = 128; k = k + 1 }
586 out[0] = 128
587 var dcsum: i64 = 0
588 var dccnt: i64 = 0
589 if sy > ytop {
590 k = 0
591 while k < n { let tv: i64 = recon[(sy-1)*W + sx + k] as i64; T[k] = tv; dcsum = dcsum + tv; k = k + 1 }
592 dccnt = dccnt + n
593 k = n
594 while k < 2*n {
595 var tv2: i64 = T[n-1]
596 if ar == 1 { if sx + k < W { tv2 = recon[(sy-1)*W + sx + k] as i64 } }
597 T[k] = tv2
598 k = k + 1 }
599 }
600 if sx > 0 {
601 k = 0
602 while k < n { let le: i64 = recon[(sy+k)*W + sx - 1] as i64; L[k] = le; dcsum = dcsum + le; k = k + 1 }
603 dccnt = dccnt + n
604 }
605 if sx > 0 { if sy > ytop { out[0] = recon[(sy-1)*W + sx - 1] as i64 } }
606 var dc: i64 = 128
607 if dccnt > 0 { dc = dcsum / dccnt }
608 out[1] = dc
609 // REFERENCE SMOOTHING (field 789 root cause: raw COPY extrapolation streaks single noisy camera
610 // pixels diagonally across the whole block, and 9 near-tied modes on noise pick DIFFERENT streaks in
611 // adjacent blocks -> mode-seam structure the deadzone residual cannot afford to fix at field qp 24-33.
612 // H.264 Intra8x8 mandates exactly this [1 2 1]/4 low-pass over the whole L-corner-T boundary before
613 // prediction). Deterministic from recon on BOTH sides -> bit-exactness + syntax unchanged. dc stays
614 // on the UNsmoothed edges (a mean of a mean; smoothing would not change it materially).
615 let x0: i64 = out[0]
616 var pv: i64 = L[0] // smooth L (neighbor toward corner at index 0)
617 if n >= 2 {
618 var i2: i64 = 0
619 while i2 < n {
620 var nx: i64 = x0
621 if i2 < n - 1 { nx = L[i2 + 1] } // L[n-1]'s outer neighbor: replicate itself
622 if i2 == n - 1 { nx = L[i2] }
623 let sm: i64 = (pv + 2*L[i2] + nx + 2) >> 2
624 pv = L[i2]
625 L[i2] = sm
626 i2 = i2 + 1
627 }
628 }
629 pv = out[0] // smooth T (T[-1] = corner)
630 var i3: i64 = 0
631 while i3 < 2*n {
632 var nx2: i64 = T[i3]
633 if i3 < 2*n - 1 { nx2 = T[i3 + 1] }
634 let sm2: i64 = (pv + 2*T[i3] + nx2 + 2) >> 2
635 pv = T[i3]
636 T[i3] = sm2
637 i3 = i3 + 1
638 }
639 out[0] = (L[0] + 2*x0 + T[0] + 2) >> 2 // corner smoothed against its two (now smoothed) neighbours
640 return 0
641}
642// MPM mode coding: [1]=mode==pred, else [0][idx:3] where idx skips pred among the 9 modes.
643func vc_mpm_put(buf: *u8, bp: i64, mode: i64, pred: i64) -> i64 {
644 if mode == pred { return nx_bw_put(buf, bp, 1, 1) }
645 var p: i64 = nx_bw_put(buf, bp, 0, 1)
646 var idx: i64 = mode
647 if mode > pred { idx = mode - 1 }
648 return nx_bw_put(buf, p, idx, 3)
649}
650func vc_mpm_val(buf: *u8, bp: i64, pred: i64) -> i64 {
651 if nx_br_get(buf, bp, 1) == 1 { return pred }
652 var idx: i64 = nx_br_get(buf, bp + 1, 3)
653 if idx >= pred { idx = idx + 1 }
654 return idx
655}
656func vc_mpm_len(buf: *u8, bp: i64) -> i64 {
657 if nx_br_get(buf, bp, 1) == 1 { return 1 }
658 return 4
659}
660// in-MB most-probable mode = min(above, left) with unavailable neighbours defaulting to DC(0); above comes
661// from the slab MM column memory (valid when sj>0), left from the previous sub-block in this row (si>0).
662// Stateless ACROSS MBs by design -- keeps every MB independently decodable (the tile-parallel invariant).
663func vc_mpm_pred(mm: *i64, si: i64, sj: i64, leftmode: i64) -> i64 {
664 var pa: i64 = 0
665 var pl: i64 = 0
666 if sj > 0 { pa = mm[si] }
667 if si > 0 { pl = leftmode }
668 if pa < pl { return pa }
669 return pl
670}
671// t8 INTRA macroblock: 4 8x8 sub-blocks in raster order, each best-of-NINE prediction (vc_pred_rich) from
672// the already-reconstructed neighbours, mode MPM-coded (1 bit hit / 4 bits miss), + DCT8-coded residual.
673// Encoder and decoder gather identical edge-substituted neighbours in identical order -> bit-exact.
674func vc_enc_mb8_intra(cur: *u8, recon: *u8, W: i64, cx: i64, cy: i64, ytop: i64, qp: i64, buf: *u8, bp0: i64, t8c: *i64, rctx: *i64) -> i64 {
675 var bp: i64 = bp0
676 let T: *i64 = vc_t8p(t8c, VC_T8_TE)
677 let L: *i64 = vc_t8p(t8c, VC_T8_LE)
678 let mm: *i64 = vc_t8p(t8c, VC_T8_MM)
679 let eo: *i64 = vc_t8p(t8c, VC_T8_EO)
680 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
681 var sj: i64 = 0
682 while sj < 2 {
683 var leftmode: i64 = 0
684 var si: i64 = 0
685 while si < 2 {
686 let sx: i64 = cx + si*8
687 let sy: i64 = cy + sj*8
688 var ar: i64 = 0
689 if sj == 0 { ar = 1 } else { if si < 1 { ar = 1 } } // above-right decoded in raster order?
690 vc_gather_edges(recon, W, sx, sy, 8, ytop, ar, T, L, eo)
691 let corner: i64 = eo[0]
692 let dc: i64 = eo[1]
693 let mpred: i64 = vc_mpm_pred(mm, si, sj, leftmode)
694 var bestmode: i64 = 0
695 var bestsad: i64 = VC_MAGIC_2147483647
696 var m: i64 = 0
697 while m < 9 {
698 var sad: i64 = 0
699 if m != mpred { sad = qp } // MPM miss = 3 extra mode bits ~ one qp of SAD (deadzone-step scale). AUDIT: qp/2 measured +0.2-1.8pt intra -- marginal, bundle into a future intra-heuristic ship, not worth a standalone wasm deploy
700 if m != 0 { if m != 4 { sad = sad + (qp / 4) } } // AUDIT: noise-margin penalty was a FULL qp = too aggressive (cost 6-16pt intra BD-rate MEASURED). qp/4 keeps a gentle margin vs // NOISE MARGIN (field 789): real camera noise makes the
701 // 9 modes near-tie and adjacent blocks streak different directions
702 // (mode seams). A directional mode must beat DC/planar by more
703 // than one quant step of SAD to be believed real, not noise.
704 var ay: i64 = 0
705 while ay < 8 { var ax: i64 = 0
706 while ax < 8 {
707 let d: i64 = (cur[(sy+ay)*W + sx + ax] as i64) - vc_pred_rich(m, ax, ay, 8, T, L, corner, dc)
708 if d < 0 { sad = sad - d } else { sad = sad + d }
709 ax = ax + 1 } ay = ay + 1 }
710 if sad < bestsad { bestsad = sad; bestmode = m }
711 m = m + 1
712 }
713 bp = vc_mpm_put(buf, bp, bestmode, mpred)
714 var ry: i64 = 0
715 while ry < 8 { var rx: i64 = 0
716 while rx < 8 { work[ry*8 + rx] = (cur[(sy+ry)*W + sx + rx] as i64) - vc_pred_rich(bestmode, rx, ry, 8, T, L, corner, dc); rx = rx + 1 } ry = ry + 1 }
717 bp = vc_enc_sub8(t8c, qp, buf, bp, rctx)
718 ry = 0
719 while ry < 8 { var rx: i64 = 0
720 while rx < 8 {
721 var v: i64 = vc_pred_rich(bestmode, rx, ry, 8, T, L, corner, dc) + work[ry*8 + rx]
722 if v < 0 { v = 0 }
723 if v > 255 { v = 255 }
724 recon[(sy+ry)*W + sx + rx] = v as u8
725 rx = rx + 1 } ry = ry + 1 }
726 mm[si] = bestmode
727 leftmode = bestmode
728 si = si + 1
729 }
730 sj = sj + 1
731 }
732 return bp
733}
734func vc_dec_mb8_intra(recon: *u8, W: i64, cx: i64, cy: i64, ytop: i64, qp: i64, buf: *u8, bp0: i64, t8c: *i64, rctx: *i64) -> i64 {
735 var bp: i64 = bp0
736 let T: *i64 = vc_t8p(t8c, VC_T8_TE)
737 let L: *i64 = vc_t8p(t8c, VC_T8_LE)
738 let mm: *i64 = vc_t8p(t8c, VC_T8_MM)
739 let eo: *i64 = vc_t8p(t8c, VC_T8_EO)
740 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
741 var sj: i64 = 0
742 while sj < 2 {
743 var leftmode: i64 = 0
744 var si: i64 = 0
745 while si < 2 {
746 let sx: i64 = cx + si*8
747 let sy: i64 = cy + sj*8
748 var ar: i64 = 0
749 if sj == 0 { ar = 1 } else { if si < 1 { ar = 1 } }
750 vc_gather_edges(recon, W, sx, sy, 8, ytop, ar, T, L, eo)
751 let corner: i64 = eo[0]
752 let dc: i64 = eo[1]
753 let mpred: i64 = vc_mpm_pred(mm, si, sj, leftmode)
754 let bestmode: i64 = vc_mpm_val(buf, bp, mpred)
755 bp = bp + vc_mpm_len(buf, bp)
756 bp = vc_dec_sub8(buf, bp, qp, t8c, rctx)
757 var ry: i64 = 0
758 while ry < 8 { var rx: i64 = 0
759 while rx < 8 {
760 var v: i64 = vc_pred_rich(bestmode, rx, ry, 8, T, L, corner, dc) + work[ry*8 + rx]
761 if v < 0 { v = 0 }
762 if v > 255 { v = 255 }
763 recon[(sy+ry)*W + sx + rx] = v as u8
764 rx = rx + 1 } ry = ry + 1 }
765 mm[si] = bestmode
766 leftmode = bestmode
767 si = si + 1
768 }
769 sj = sj + 1
770 }
771 return bp
772}
773// RICH 4x4 intra macroblock (t8-stream syntax only): the same nine modes + MPM at 4x4 granularity -- the
774// finer prediction grid for textured/edge MBs where 4x4 residual coding is kept. 16 sub-blocks raster.
775func vc_enc_mb4r_intra(cur: *u8, recon: *u8, W: i64, cx: i64, cy: i64, ytop: i64, qp: i64, tf: i64, buf: *u8, bp0: i64, blk: *i64, t8c: *i64, rctx: *i64) -> i64 {
776 var bp: i64 = bp0
777 let T: *i64 = vc_t8p(t8c, VC_T8_TE)
778 let L: *i64 = vc_t8p(t8c, VC_T8_LE)
779 let mm: *i64 = vc_t8p(t8c, VC_T8_MM)
780 let eo: *i64 = vc_t8p(t8c, VC_T8_EO)
781 var sj: i64 = 0
782 while sj < 4 {
783 var leftmode: i64 = 0
784 var si: i64 = 0
785 while si < 4 {
786 let sx: i64 = cx + si*4
787 let sy: i64 = cy + sj*4
788 var ar: i64 = 0
789 if sj == 0 { ar = 1 } else { if si < 3 { ar = 1 } }
790 vc_gather_edges(recon, W, sx, sy, 4, ytop, ar, T, L, eo)
791 let corner: i64 = eo[0]
792 let dc: i64 = eo[1]
793 let mpred: i64 = vc_mpm_pred(mm, si, sj, leftmode)
794 var bestmode: i64 = 0
795 var bestsad: i64 = VC_MAGIC_2147483647
796 var m: i64 = 0
797 while m < 9 {
798 var sad: i64 = 0
799 if m != mpred { sad = qp } // MPM miss = 3 extra mode bits ~ one qp of SAD (deadzone-step scale). AUDIT: qp/2 measured +0.2-1.8pt intra -- marginal, bundle into a future intra-heuristic ship, not worth a standalone wasm deploy
800 if m != 0 { if m != 4 { sad = sad + (qp / 4) } } // AUDIT: noise-margin penalty was a FULL qp = too aggressive (cost 6-16pt intra BD-rate MEASURED). qp/4 keeps a gentle margin vs // NOISE MARGIN (field 789): real camera noise makes the
801 // 9 modes near-tie and adjacent blocks streak different directions
802 // (mode seams). A directional mode must beat DC/planar by more
803 // than one quant step of SAD to be believed real, not noise.
804 var ay: i64 = 0
805 while ay < 4 { var ax: i64 = 0
806 while ax < 4 {
807 let d: i64 = (cur[(sy+ay)*W + sx + ax] as i64) - vc_pred_rich(m, ax, ay, 4, T, L, corner, dc)
808 if d < 0 { sad = sad - d } else { sad = sad + d }
809 ax = ax + 1 } ay = ay + 1 }
810 if sad < bestsad { bestsad = sad; bestmode = m }
811 m = m + 1
812 }
813 bp = vc_mpm_put(buf, bp, bestmode, mpred)
814 var ry: i64 = 0
815 while ry < 4 { var rx: i64 = 0
816 while rx < 4 { blk[ry*4 + rx] = (cur[(sy+ry)*W + sx + rx] as i64) - vc_pred_rich(bestmode, rx, ry, 4, T, L, corner, dc); rx = rx + 1 } ry = ry + 1 }
817 bp = vc_coeff_enc(blk, qp, buf, bp, tf, rctx)
818 ry = 0
819 while ry < 4 { var rx: i64 = 0
820 while rx < 4 {
821 var v: i64 = vc_pred_rich(bestmode, rx, ry, 4, T, L, corner, dc) + blk[ry*4 + rx]
822 if v < 0 { v = 0 }
823 if v > 255 { v = 255 }
824 recon[(sy+ry)*W + sx + rx] = v as u8
825 rx = rx + 1 } ry = ry + 1 }
826 mm[si] = bestmode
827 leftmode = bestmode
828 si = si + 1
829 }
830 sj = sj + 1
831 }
832 return bp
833}
834func vc_dec_mb4r_intra(recon: *u8, W: i64, cx: i64, cy: i64, ytop: i64, qp: i64, tf: i64, buf: *u8, bp0: i64, blk: *i64, t8c: *i64, rctx: *i64) -> i64 {
835 var bp: i64 = bp0
836 let T: *i64 = vc_t8p(t8c, VC_T8_TE)
837 let L: *i64 = vc_t8p(t8c, VC_T8_LE)
838 let mm: *i64 = vc_t8p(t8c, VC_T8_MM)
839 let eo: *i64 = vc_t8p(t8c, VC_T8_EO)
840 var sj: i64 = 0
841 while sj < 4 {
842 var leftmode: i64 = 0
843 var si: i64 = 0
844 while si < 4 {
845 let sx: i64 = cx + si*4
846 let sy: i64 = cy + sj*4
847 var ar: i64 = 0
848 if sj == 0 { ar = 1 } else { if si < 3 { ar = 1 } }
849 vc_gather_edges(recon, W, sx, sy, 4, ytop, ar, T, L, eo)
850 let corner: i64 = eo[0]
851 let dc: i64 = eo[1]
852 let mpred: i64 = vc_mpm_pred(mm, si, sj, leftmode)
853 let bestmode: i64 = vc_mpm_val(buf, bp, mpred)
854 bp = bp + vc_mpm_len(buf, bp)
855 bp = vc_coeff_dec(buf, bp, qp, blk, tf, rctx)
856 var ry: i64 = 0
857 while ry < 4 { var rx: i64 = 0
858 while rx < 4 {
859 var v: i64 = vc_pred_rich(bestmode, rx, ry, 4, T, L, corner, dc) + blk[ry*4 + rx]
860 if v < 0 { v = 0 }
861 if v > 255 { v = 255 }
862 recon[(sy+ry)*W + sx + rx] = v as u8
863 rx = rx + 1 } ry = ry + 1 }
864 mm[si] = bestmode
865 leftmode = bestmode
866 si = si + 1
867 }
868 sj = sj + 1
869 }
870 return bp
871}
872// t8 INTER residual: the SAME quarter-pel motion-compensated predictor pixels as the 4x4 path (same
873// mv/bqx/bqy, decided by the shared MB header) -- only the residual transform granularity changes
874// (4 8x8 blocks instead of 16 4x4).
875// pfresh (F1114b): 1 = the bit2 trial ran for THIS MB -- recon holds the banked predictor (pred=cur-res)
876// and res[] holds the trial's final 8x8 LEVELS per quadrant (identical to what the recompute would
877// produce: same forward+quant+RDOQ sequence on the same residual). Consume both: the whole per-sub
878// forward+quant+RDOQ and all 512 qp_pixel bilinears disappear. Bits identical by identity.
879// pfresh=0 (t8 policy path / trial early-out): the original full pipeline.
880func vc_enc_mb8_inter(cur: *u8, prev: *u8, recon: *u8, W: i64, cx: i64, cy: i64, qp: i64, mvx: i64, mvy: i64, bqx: i64, bqy: i64, buf: *u8, bp0: i64, t8c: *i64, rctx: *i64, pfresh: i64) -> i64 {
881 var bp: i64 = bp0
882 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
883 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ)
884 let res: *i64 = vc_t8p(t8c, VC_T8_RES)
885 var sj: i64 = 0
886 while sj < 2 {
887 var si: i64 = 0
888 while si < 2 {
889 let sx: i64 = cx + si*8
890 let sy: i64 = cy + sj*8
891 if pfresh == 1 {
892 var k: i64 = 0
893 while k < 64 { freq[k] = res[(sj*8 + k/8)*16 + si*8 + (k%8)]; k = k + 1 }
894 bp = vc_enc_sub8_tail(t8c, qp, buf, bp, rctx, vc_t8p(t8c, VC_T8_SCR))
895 } else {
896 var yy: i64 = 0
897 while yy < 8 { var xx: i64 = 0
898 while xx < 8 {
899 let c: i64 = cur[(sy+yy)*W + (sx+xx)] as i64
900 let pred: i64 = qp_pixel(prev, W, sx+xx+mvx, sy+yy+mvy, bqx, bqy)
901 work[yy*8 + xx] = c - pred
902 xx = xx + 1 } yy = yy + 1 }
903 bp = vc_enc_sub8(t8c, qp, buf, bp, rctx)
904 }
905 var yy2: i64 = 0
906 while yy2 < 8 { var xx2: i64 = 0
907 while xx2 < 8 {
908 var pred: i64 = 0
909 if pfresh == 1 { pred = recon[(sy+yy2)*W + (sx+xx2)] as i64 }
910 else { pred = qp_pixel(prev, W, sx+xx2+mvx, sy+yy2+mvy, bqx, bqy) }
911 var v: i64 = pred + work[yy2*8 + xx2]
912 if v < 0 { v = 0 }
913 if v > 255 { v = 255 }
914 recon[(sy+yy2)*W + (sx+xx2)] = v as u8
915 xx2 = xx2 + 1 } yy2 = yy2 + 1 }
916 si = si + 1
917 }
918 sj = sj + 1
919 }
920 return bp
921}
922func vc_dec_mb8_inter(prev: *u8, recon: *u8, W: i64, cx: i64, cy: i64, qp: i64, mvx: i64, mvy: i64, bqx: i64, bqy: i64, buf: *u8, bp0: i64, t8c: *i64, rctx: *i64) -> i64 {
923 var bp: i64 = bp0
924 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
925 var sj: i64 = 0
926 while sj < 2 {
927 var si: i64 = 0
928 while si < 2 {
929 let sx: i64 = cx + si*8
930 let sy: i64 = cy + sj*8
931 bp = vc_dec_sub8(buf, bp, qp, t8c, rctx)
932 var yy: i64 = 0
933 while yy < 8 { var xx: i64 = 0
934 while xx < 8 {
935 let pred: i64 = qp_pixel(prev, W, sx+xx+mvx, sy+yy+mvy, bqx, bqy)
936 var v: i64 = pred + work[yy*8 + xx]
937 if v < 0 { v = 0 }
938 if v > 255 { v = 255 }
939 recon[(sy+yy)*W + (sx+xx)] = v as u8
940 xx = xx + 1 } yy = yy + 1 }
941 si = si + 1
942 }
943 sj = sj + 1
944 }
945 return bp
946}
947
948// ============================================================================================================
949// vcv-7 RUNG 1 -- P_8x8 MOTION PARTITION. MEASURED lever (nx_vcodec_predceiling_gate): giving each 8x8 sub-block
950// its OWN motion vector cuts the MC-residual SAD 10-19% on motion content (transform-size was 0.3%) -- the real
951// P-frame gap vs H.264/HEVC, which we lacked (one MV per 16x16). A luma P-MB may now be coded as 4 independent
952// 8x8 partitions, each with its own integer+quarter-pel MV and its own 8x8 residual (vc_enc_sub8 -> rides sig-map
953// + RDOQ). New wire syntax (a per-MB `part` bit, then per-partition MV+qpel+residual) => GENERATION vcv-7, gated
954// by emode bit7 (partition-enabled) which the client only sets when every peer is >= vcv-7 (partAll()); bit7 off
955// => not a single bit changes (byte-identical to vcv-6). Chroma (bit4) never partitions. Decoder mirror below.
956func vc_mvcost(v: i64) -> i64 { return 5 + ve_blen(ve_zze(v)) } // bits ve_vput(v) would emit (RD MV cost, no write)
957// ---- exp-Golomb MV-delta verbs (F608 vcv-10 MVD bundle; Elias-gamma lineage 1975, patent-free) --------
958// MEASURED (nx_vcodec_mvbits_probe 2026-07-20): abs ve_vput MV bits = 25permille of P bytes; median-pred
959// deltas under the SAME VLC save only 1permille (the flat 5-bit length field eats the win); median-pred
960// + THIS code saves 9permille as a floor (16x16 census; partition sub-MVs excluded). Syntax flip rides
961// vcv-10 (rct9) ONLY -- these verbs are inert until the MVD bundle wires them behind rctx[0] bit13.
962// ue(zze(v)): z+1 has n bits -> (n-1) zero bits then the n bits of z+1. Cost mirror = 2*blen(zze+1)-1.
963func vc_gput(buf: *u8, bp0: i64, v: i64) -> i64 {
964 let z: i64 = ve_zze(v)
965 let n: i64 = ve_blen(z + 1)
966 var bp: i64 = bp0
967 var i: i64 = 0
968 while i < n - 1 { bp = nx_bw_put(buf, bp, 0, 1); i = i + 1 }
969 bp = nx_bw_put(buf, bp, z + 1, n)
970 return bp
971}
972// decode one value at bit pos bpbox[0]; advances bpbox[0]. Leading-zero run bounded (corrupt input
973// terminates; recon-hash conformance catches the garbage downstream -- rule 12 at the wire boundary).
974func vc_gget(buf: *u8, bpbox: *i64) -> i64 {
975 var bp: i64 = bpbox[0]
976 var lead: i64 = 0
977 var sc: i64 = 0
978 while sc == 0 {
979 if nx_br_get(buf, bp, 1) == 1 { sc = 1 } else { lead = lead + 1; bp = bp + 1; if lead > 40 { sc = 1 } }
980 }
981 let zp1: i64 = nx_br_get(buf, bp, lead + 1)
982 bp = bp + lead + 1
983 bpbox[0] = bp
984 let z: i64 = zp1 - 1
985 if (z & 1) == 1 { return 0 - ((z + 1) / 2) }
986 return z / 2
987}
988// ---- vcv-10 MVD-MEDIAN plumbing (F608; active ONLY under rctx[0] bit13, set by the rct9 frame fns) ----
989// rctx[9] = caller-provided MV row-plane (rctx[6]/[7] are TAKEN by the trained-nf table+scratch, [8] by heat): [top row: BW i64][cur row: BW i64], one packed entry per MB
990// column. pack = (mvx+4096)*8192 + (mvy+4096) (offset-binary: all-positive arithmetic; qpel-scale MVs
991// live far inside +-4096). Rows PRESET to packed (0,0) at frame start + row advance, so skip / intra /
992// partition MBs contribute (0,0) BY CONSTRUCTION (no per-branch writes; deterministic enc==dec; the
993// nx_vcodec_mvbits_probe census model). Only a coded 16x16 MB overwrites its column.
994const VC_MVPACK0: i64 = 33558528 // (0+4096)*8192 + (0+4096)
995// RD-SKIP TRIAL BAND (rule-11; was literal /4 and *8): only MBs with zero-SAD inside
996// [thresh/LO_DIV, thresh*HI_MUL] pay the RD trial. The quality win lives BELOW thresh (un-skipping
997// smeared MBs); the upper band mostly re-confirms CODE at trial cost -- HI_MUL is the fps knob.
998const VC_RDSK_LO_DIV: i64 = 4
999const VC_RDSK_HI_MUL: i64 = 8
1000// QUIET-QUADRANT EARLY SKIP (emode bit14, encoder-only, 2026-09-02 -- MEASURED by nx_vcodec_stage_bench on the live
1001// h2h card at the live point qp24/thresh qp*30: the lower trial sub-band [thr/4, thr) held 291 of 396 MBs per frame
1002// because thr/4 = 180 SAD sits BELOW the recon quantisation-noise floor of a static block, so 88 percent of the frame
1003// paid the ~55 us code-arm trial and re-skipped -- 23.7 ms per 352x288 frame against 8.9 ms with the trial off, for
1004// 1746 vs 1749 bytes). With bit14 set, a lower-sub-band MB is trialed only when at least one 8x8 quadrant moves
1005// (quadrant zero-SAD >= thr/4, the same area-scaled rule the partition gate uses); a block whose four quadrants are
1006// all quiet takes the threshold skip directly. The UPPER sub-band [thr, 8*thr] is untouched (that is where the
1007// RD-skip-above-thresh saving lives). Decoder-transparent: the skip bit is the same syntax either way.
1008const VC_EMODE_QQSKIP: i64 = 16384
1009// HEXAGON MOTION SEARCH (emode bit15, encoder-only, 2026-09-02): the block coder's 16x16 integer search rides vm_search_hex
1010// instead of the exhaustive vm_search_q. Decisions can differ, so it ships only behind a BD-rate measurement (see nx_vmotion.nx).
1011const VC_EMODE_HEXME: i64 = 32768
1012// TE-scratch HANDBACK SLOTS (F1112, vc_rd_part_inter -> vc_enc_block_packed_i): the partition trial's
1013// 16x16 search result rides the caller-owned TE region it already uses for mv/bq work. Slot units are
1014// i64 indices into the TE base. Slots 2,3 = bq; 4,5 = the dormant _rc variant's jout; pxy10/bpb10 live
1015// at byte offsets +48/+64 (slots 6,8) by the decoder-shared vcv-10 convention -- do not collide.
1016const VC_TE_H16_MV0: i64 = 0 // 16x16 argmin dx (restored around the quadrant trial)
1017const VC_TE_H16_MV1: i64 = 1 // 16x16 argmin dy
1018const VC_TE_H16_SAD: i64 = 4 // 16x16 integer-search SAD
1019func vc_mvplane_row0(mvp: *i64, BW: i64) -> i64 {
1020 var i: i64 = 0
1021 while i < BW*2 { mvp[i] = VC_MVPACK0; i = i + 1 }
1022 return 0
1023}
1024func vc_mvplane_nextrow(mvp: *i64, BW: i64) -> i64 {
1025 var i: i64 = 0
1026 while i < BW { mvp[i] = mvp[BW + i]; mvp[BW + i] = VC_MVPACK0; i = i + 1 }
1027 return 0
1028}
1029func vc_mvmed3(a: i64, b: i64, c: i64) -> i64 {
1030 var lo: i64 = a; if b < lo { lo = b } if c < lo { lo = c }
1031 var hi: i64 = a; if b > hi { hi = b } if c > hi { hi = c }
1032 return a + b + c - lo - hi
1033}
1034// component-wise median of {left(cur row), top, top-right} for MB column bx -> pxy[0..1]; edges see the
1035// preset (0,0) entries (H.263-era median prediction lineage, pre-2000, patent-free).
1036func vc_mvpred(mvp: *i64, BW: i64, bx: i64, pxy: *i64) -> i64 {
1037 var lx: i64 = 0
1038 var ly: i64 = 0
1039 if bx > 0 { let pl: i64 = mvp[BW + bx - 1]; lx = pl/VC_MAGIC_8192 - VC_MAGIC_4096; ly = pl%VC_MAGIC_8192 - VC_MAGIC_4096 }
1040 let pt: i64 = mvp[bx]
1041 let tx: i64 = pt/VC_MAGIC_8192 - VC_MAGIC_4096
1042 let ty: i64 = pt%VC_MAGIC_8192 - VC_MAGIC_4096
1043 var rx: i64 = 0
1044 var ry: i64 = 0
1045 if bx < BW - 1 { let pr: i64 = mvp[bx + 1]; rx = pr/VC_MAGIC_8192 - VC_MAGIC_4096; ry = pr%VC_MAGIC_8192 - VC_MAGIC_4096 }
1046 pxy[0] = vc_mvmed3(lx, tx, rx)
1047 pxy[1] = vc_mvmed3(ly, ty, ry)
1048 return 0
1049}
1050func vc_mvplane_set(mvp: *i64, BW: i64, bx: i64, mvx: i64, mvy: i64) -> i64 {
1051 mvp[BW + bx] = (mvx + VC_MAGIC_4096)*VC_MAGIC_8192 + (mvy + VC_MAGIC_4096)
1052 return 0
1053}
1054// vcv-8 INTRA-IN-P decision estimate: SAD of the 16x16 MB vs a DC prediction from its already-reconstructed top
1055// row + left col (raster order guarantees they exist for an interior MB). This is a PESSIMISTIC lower bound on
1056// what real 9-mode intra achieves, so intra is chosen only when even flat DC beats the best inter -> a safe gate.
1057// Encoder-only (the explicit mode bit makes the decoder oblivious to how we decided). frame edge -> dc=128.
1058func vc_intra_dc_sad(cur: *u8, recon: *u8, W: i64, cx: i64, cy: i64) -> i64 {
1059 var sum: i64 = 0; var cnt: i64 = 0
1060 if cy > 0 { var i: i64 = 0; while i < 16 { sum = sum + (recon[(cy-1)*W + cx + i] as i64); cnt = cnt + 1; i = i + 1 } }
1061 if cx > 0 { var j: i64 = 0; while j < 16 { sum = sum + (recon[(cy+j)*W + cx - 1] as i64); cnt = cnt + 1; j = j + 1 } }
1062 var dc: i64 = 128
1063 if cnt > 0 { dc = sum / cnt }
1064 var sad: i64 = 0; var y: i64 = 0
1065 while y < 16 { var x: i64 = 0
1066 while x < 16 { let d: i64 = (cur[(cy+y)*W + cx + x] as i64) - dc; if d < 0 { sad = sad - d } else { sad = sad + d } x = x + 1 } y = y + 1 }
1067 return sad
1068}
1069// integer search (T=8) + quarter-pel refine for ONE 8x8 block at (sx,sy); fills mv[0..1] (integer) + bq[0..1]
1070// (quarter-pel frac 0..3); returns the refined SAD. Mirrors the 16x16 path's refine, scoped to 8x8.
1071func vc_me8(cur: *u8, prev: *u8, W: i64, H: i64, sx: i64, sy: i64, mv: *i64, bq: *i64, qp: i64, scr3: *i64) -> i64 {
1072 vm_search_q(cur, prev, W, H, sx/8, sy/8, 8, VC_ME_R, mv, qp, scr3)
1073 let px: i64 = sx + mv[0]; let py: i64 = sy + mv[1]
1074 var bestsad: i64 = VC_MAGIC_2147483647; var bx4: i64 = 0; var by4: i64 = 0
1075 var tqy: i64 = 0
1076 while tqy <= 3 {
1077 var tqx: i64 = 0
1078 while tqx <= 3 {
1079 var ok: i64 = 1
1080 if tqx > 0 { if px + 8 >= W { ok = 0 } }
1081 if tqy > 0 { if py + 8 >= H { ok = 0 } }
1082 if ok == 1 {
1083 var sad: i64 = 0; var yy: i64 = 0
1084 while yy < 8 { var xx: i64 = 0
1085 while xx < 8 {
1086 let d: i64 = (cur[(sy+yy)*W + (sx+xx)] as i64) - qp_pixel(prev, W, px+xx, py+yy, tqx, tqy)
1087 if d < 0 { sad = sad - d } else { sad = sad + d }
1088 xx = xx + 1 } yy = yy + 1 }
1089 if sad < bestsad { bestsad = sad; bx4 = tqx; by4 = tqy }
1090 }
1091 tqx = tqx + 1 }
1092 tqy = tqy + 1 }
1093 bq[0] = bx4; bq[1] = by4
1094 return bestsad
1095}
1096// DECISION EARLY-OUTS (2026-07-12, encoder-only speed heuristics -- decoder-transparent; the wire carries
1097// explicit bits either way). The per-CODED-MB decision stack (partition-RD = 5 motion searches + the t8
1098// transform trial) measured ~0.3ms/MB = the HD-band wall (81ms = 12.3fps at 1152x640 K=4) AND most of the
1099// RTC trial cost (143->119fps). Both gates are qp-SCALED on the same ladder as the proven thresholds
1100// (skip band = qp*30, real translation = qp*188): a decision is only WORTH TRIALING when the 16x16 residual
1101// says it could change the outcome. Partition pays only when ONE 16x16 MV fails (high refined SAD); the
1102// transform choice only matters when there is real residual energy. MEASURED (MSU 4-seq, emitter 4781):
1103// BD-rate cost of the gates ~0 (see roadmap cont.25) for a 1.5-2x decision-stack cut.
1104// CALIBRATION (measured): first-try T=90/60 cost +4.53% avg BD-rate (bus +8.12 -- partition matters on real
1105// motion; akiyo +3.55 -- the 8x8 trial matters on smooth content) = the gates fired inside decision-relevant
1106// territory. The principled band is BELOW THE SKIP THRESHOLD (qp*30): a block coded with refined SAD under it
1107// only exists via heat-protection (halved threshold) and is near-skip -- decisions provably marginal there.
1108// F618 SESSION NOTE (2026-07-20): this block MOVED here from below (was after the heat consts, lines ~1900-1913)
1109// because BOTH readers (vc_rd_part_inter, vc_enc_mb_t8auto path) sat ABOVE the declarations -- the pre-diagnostic
1110// compiler silently read 0 for both (fwd-const miscompile class), so these early-outs were DEAD in every binary
1111// built since 2026-07-12 incl the shipped wasm. Moving them arms the DESIGNED, measured (~0 BD) behavior.
1112const VC_EO_PART: i64 = 30 // skip partition evaluation when refined-16x16-adjacent SAD < qp*30
1113const VC_EO_T8: i64 = 20 // skip the transform trial (default 4x4) when refined 16x16 SAD < qp*20
1114// RD decide 16x16-single-MV vs 4x-8x8-partition (encoder-only; the explicit part bit makes the decoder oblivious).
1115// SAD-domain Lagrangian J = SAD + lambda*mvbits with lambda = qp (the quantizer step = the SAD-per-bit RD slope,
1116// same qp-scaling as the deadzone; the one RD knob, to be BD-rate-verified). Partition wins only when its residual
1117// drop beats its extra MV cost. Returns 1 = partition.
1118func vc_rd_part_inter(cur: *u8, prev: *u8, W: i64, H: i64, cx: i64, cy: i64, qp: i64, scr: *i64) -> i64 {
1119 // scr = caller scratch (>= 4 i64; the slab's intra-only TE region). Was 2x sys_mmap(32) -- in the WASM
1120 // build sys_mmap is a 0-stub (TODO opcode), so mv and bq ALIASED at address 0 and the mv-cost side of
1121 // this J read qpel values (partition-favoring skew, live since 810). Same fix family as enc_mb_part8.
1122 let mv: *i64 = scr
1123 let bq: *i64 = ((scr as i64) + 16) as *i64
1124 let sad16: i64 = vm_search_q(cur, prev, W, H, cx/16, cy/16, 16, VC_ME_R, mv, qp, ((scr as i64) + 40) as *i64)
1125 // F1112 RESULT HANDBACK (encoder-only): the caller used to re-run this EXACT search (same refs, same
1126 // window, same qp; cx/16==bx by construction, and priming is result-inert by proof) on every rejected
1127 // trial -- pure duplicate work on the hottest path. CONTRACT: return 0 => scr[0..1] = the 16x16 argmin
1128 // MV (restored around the quadrant trial, which reuses the slots) and scr[4] = its SAD.
1129 scr[VC_TE_H16_SAD] = sad16
1130 // EARLY-OUT: partition only pays when ONE 16x16 MV FAILS the block (quadrants moving differently -> high
1131 // 16x16 SAD). A well-explained block skips the 4x vc_me8 sub-searches = the dominant decision-stack cost.
1132 if sad16 < qp * VC_EO_PART { return 0 }
1133 let j16: i64 = sad16 + qp * (vc_mvcost(mv[0]) + vc_mvcost(mv[1]) + 4)
1134 let m160: i64 = mv[VC_TE_H16_MV0]
1135 let m161: i64 = mv[VC_TE_H16_MV1]
1136 var sadp: i64 = 0; var mvbp: i64 = 0
1137 var pmv0: i64 = 0; var pmv1: i64 = 0 // same running-predictor cost model the partition encoder uses
1138 var sj: i64 = 0
1139 while sj < 2 { var si: i64 = 0
1140 while si < 2 {
1141 let s: i64 = vc_me8(cur, prev, W, H, cx+si*8, cy+sj*8, mv, bq, qp, ((scr as i64) + 40) as *i64)
1142 sadp = sadp + s; mvbp = mvbp + vc_mvcost(mv[0]-pmv0) + vc_mvcost(mv[1]-pmv1) + 4
1143 pmv0 = mv[0]; pmv1 = mv[1]
1144 si = si + 1 } sj = sj + 1 }
1145 let jpart: i64 = sadp + qp * mvbp
1146 if jpart < j16 { return 1 }
1147 mv[VC_TE_H16_MV0] = m160
1148 mv[VC_TE_H16_MV1] = m161
1149 return 0
1150}
1151// encode a luma P-MB as 4 independent 8x8 partitions. Per quadrant: search its own MV, code MV (ve_vput) + qpel
1152// (2+2 bits) into CAVLC, code the 8x8 residual via vc_enc_sub8 (range/sig-map), reconstruct. Mirrors vc_enc_mb8_inter
1153// but with a distinct MV per 8x8 instead of one shared MV.
1154func vc_enc_mb_part8_inter(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, cx: i64, cy: i64, qp: i64, buf: *u8, bp0: i64, t8c: *i64, rctx: *i64) -> i64 {
1155 var bp: i64 = bp0
1156 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
1157 // ⚠LIVE-BUG FIX (2026-07-12, found porting P3b): these were sys_mmap(32) each -- but in the WASM build
1158 // sys_mmap is a 0-STUB, so mv and bq both pointed at address 0 and vc_me8's bq write (LAST) STOMPED the
1159 // searched MV before ve_vput coded it. The browser encoder shipped partition MVs of (0..3,0..3) qpel-only
1160 // = near-zero motion (self-consistent recon + wire, so bit-exact/drift-green -- just silently worse RD on
1161 // motion content; the native gates, with a real mmap, never saw it). Scratch now rides the slab's
1162 // intra-only TE region (free during inter) -- real memory in BOTH builds, and no per-MB mmap.
1163 let mv: *i64 = vc_t8p(t8c, VC_T8_TE)
1164 let bq: *i64 = ((vc_t8p(t8c, VC_T8_TE) as i64) + 16) as *i64
1165 var pmv0: i64 = 0; var pmv1: i64 = 0 // running MV predictor (prev quadrant); 4 quadrants of an MB share motion
1166 var sj: i64 = 0
1167 while sj < 2 { var si: i64 = 0
1168 while si < 2 {
1169 let sx: i64 = cx + si*8; let sy: i64 = cy + sj*8
1170 vc_me8(cur, prev, W, H, sx, sy, mv, bq, qp, ((vc_t8p(t8c, VC_T8_TE) as i64) + 40) as *i64)
1171 bp = ve_vput(buf, bp, mv[0]-pmv0); bp = ve_vput(buf, bp, mv[1]-pmv1) // differential MV (H.264-style)
1172 pmv0 = mv[0]; pmv1 = mv[1]
1173 bp = nx_bw_put(buf, bp, bq[0], 2); bp = nx_bw_put(buf, bp, bq[1], 2)
1174 var yy: i64 = 0
1175 while yy < 8 { var xx: i64 = 0
1176 while xx < 8 { work[yy*8 + xx] = (cur[(sy+yy)*W + (sx+xx)] as i64) - qp_pixel(prev, W, sx+mv[0]+xx, sy+mv[1]+yy, bq[0], bq[1]); xx = xx + 1 } yy = yy + 1 }
1177 bp = vc_enc_sub8(t8c, qp, buf, bp, rctx)
1178 yy = 0
1179 while yy < 8 { var xx: i64 = 0
1180 while xx < 8 { var v: i64 = qp_pixel(prev, W, sx+mv[0]+xx, sy+mv[1]+yy, bq[0], bq[1]) + work[yy*8 + xx]; if v < 0 { v = 0 } if v > 255 { v = 255 } recon[(sy+yy)*W + (sx+xx)] = v as u8; xx = xx + 1 } yy = yy + 1 }
1181 si = si + 1 } sj = sj + 1 }
1182 return bp
1183}
1184// decode mirror of vc_enc_mb_part8_inter: per quadrant read MV+qpel, decode 8x8 residual, reconstruct.
1185func vc_dec_mb_part8_inter(prev: *u8, recon: *u8, W: i64, cx: i64, cy: i64, qp: i64, buf: *u8, bp0: i64, t8c: *i64, rctx: *i64) -> i64 {
1186 var bp: i64 = bp0
1187 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
1188 var pmv0: i64 = 0; var pmv1: i64 = 0 // running MV predictor -- MUST mirror the encoder's chain exactly
1189 var sj: i64 = 0
1190 while sj < 2 { var si: i64 = 0
1191 while si < 2 {
1192 let sx: i64 = cx + si*8; let sy: i64 = cy + sj*8
1193 let mv0: i64 = ve_vval(buf, bp) + pmv0; bp = bp + ve_vlen(buf, bp)
1194 let mv1: i64 = ve_vval(buf, bp) + pmv1; bp = bp + ve_vlen(buf, bp)
1195 pmv0 = mv0; pmv1 = mv1
1196 let bqx: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
1197 let bqy: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
1198 bp = vc_dec_sub8(buf, bp, qp, t8c, rctx)
1199 var yy: i64 = 0
1200 while yy < 8 { var xx: i64 = 0
1201 while xx < 8 { var v: i64 = qp_pixel(prev, W, sx+mv0+xx, sy+mv1+yy, bqx, bqy) + work[yy*8 + xx]; if v < 0 { v = 0 } if v > 255 { v = 255 } recon[(sy+yy)*W + (sx+xx)] = v as u8; xx = xx + 1 } yy = yy + 1 }
1202 si = si + 1 } sj = sj + 1 }
1203 return bp
1204}
1205
1206// ---- RD TRANSFORM-SIZE SELECT for an INTER MB (encoder-only; the explicit t8 bit makes the decoder
1207// oblivious). The mad-of-SOURCE policy classifies the source, but a P-frame codes the RESIDUAL, whose
1208// character differs (motion mismatch / quant noise). So: build the actual MC residual once, cost BOTH
1209// transforms on it via the exact CAVLC bit counters + reconstruction SSE, pick the lower J. Lagrangian:
1210// J = 32*SSE + q*q*bits <=> SSE + bits*lambda with lambda = q^2/32 = (s^2)/2 for our deadzone step
1211// s = q/4 -- the classic ~0.5-0.85*Qstep^2 RD slope, integer-exact, derived from the step (no free knob).
1212// Uses RES16 for the residual, SCR[0..15] for the 4x4 trial, WORK/FREQ for the 8x8 trial. Returns 1 = 8x8.
1213// P3 (2026-07-12): the trial is now BYTE-FAITHFUL to the real emit paths on both axes -- (a) LEVELS: the 4x4
1214// arm quantizes via vt2_quant_rdoq and the 8x8 arm via vc_quant8+vc_rdoq8, exactly like vc_enc_sub_sig /
1215// vc_enc_sub8 (the old trial used plain quant = wrong levels under RDOQ); (b) BITS: when the sig-map syntax is
1216// active (emode bit5, the shipped config) each arm is costed by rc_sig_cost_q8 -- the coder's OWN adaptive-
1217// context bits (read-only walk of the exact bins) -- instead of the CAVLC ve_cost tables that mismatched the
1218// range-coded stream (why 803 sat dormant). Legacy non-sig rooms keep the CAVLC tables (their stream matches).
1219// rctx: [0] emode (bit5 = sig), [2] live probs, [4] t8c slab. J in Q8 bit units both arms.
1220// jout[0] receives min(jA, jB) -- the MB's best coeff-side J -- so the partition RD (P3b) can reuse this
1221// whole faithful trial as its 16x16 arm without recomputation drift.
1222// recon (F1114b): when non-null, the residual fill ALSO banks the predictor into recon (it is in hand
1223// per pixel anyway) -- the caller's emits read it back. Must be banked HERE: the B arm below overwrites
1224// res[] with its levels, so pred is unrecoverable from res after this function returns. The dormant
1225// vc_rd_part_inter_rc caller passes 0 (its recon is not in scope; P3b is refuted + caller-free).
1226func vc_rd_t8_inter(cur: *u8, prev: *u8, recon: *u8, W: i64, cx: i64, cy: i64, qp: i64, mvx: i64, mvy: i64, bqx: i64, bqy: i64, tf: i64, rctx: *i64, jout: *i64) -> i64 {
1227 let t8c: *i64 = rctx[4] as *i64
1228 let probs: *i64 = rctx[2] as *i64
1229 var sig: i64 = 0
1230 if (rctx[0] & 32) != 0 { sig = 1 }
1231 let res: *i64 = vc_t8p(t8c, VC_T8_RES)
1232 let tr4: *i64 = vc_t8p(t8c, VC_T8_SCR)
1233 let c4s: *i64 = ((vc_t8p(t8c, VC_T8_SCR) as i64) + 128) as *i64 // SCR+16..31: A-arm pre-quant copy (dead before B's forward_2d scratch use)
1234 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
1235 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ)
1236 let zz8: *i64 = vc_t8p(t8c, VC_T8_ZZ)
1237 var dobank: i64 = 0
1238 if (recon as i64) != 0 { dobank = 1 }
1239 var yy: i64 = 0
1240 while yy < 16 { var xx: i64 = 0
1241 while xx < 16 {
1242 let c: i64 = cur[(cy+yy)*W + (cx+xx)] as i64
1243 let pred: i64 = qp_pixel(prev, W, cx+xx+mvx, cy+yy+mvy, bqx, bqy)
1244 res[yy*16 + xx] = c - pred
1245 if dobank == 1 { recon[(cy+yy)*W + (cx+xx)] = pred as u8 }
1246 xx = xx + 1 } yy = yy + 1 }
1247 // option A: 16x 4x4 (the shipping transform at this tf; RDOQ levels exactly like vc_enc_sub_sig/_rc).
1248 // F1114b: distortion = TRANSFORM-DOMAIN quant error (Parseval -- the doctrine vc_rdoq8's own comment
1249 // already states). e = v - r*d at 2D scale 4096 (tf==1) => spatial SSE = sum(e*e) >> 24. The
1250 // dequant+inverse+spatial-diff halves of both arms measured ~14% of the ENTIRE 677/2597 P-encode
1251 // (V8 profile 2026-07-29) and existed only to produce this number. Near-tie decisions may flip --
1252 // both arms are RD-equivalent there by definition -- BD-gated, encoder-only. tf==0 (legacy WHT;
1253 // no gated config reaches the bit2 trial with it) keeps the spatial pipeline.
1254 var bitsA: i64 = 0
1255 var sseA: i64 = 0
1256 var eA: i64 = 0
1257 let dA: i64 = qp << DCT2_QSHIFT
1258 var sj: i64 = 0
1259 while sj < 4 { var si: i64 = 0
1260 while si < 4 {
1261 var k: i64 = 0
1262 while k < 16 { tr4[k] = res[(sj*4 + k/4)*16 + si*4 + (k%4)]; k = k + 1 }
1263 if tf == 1 {
1264 vt2_fwd(tr4)
1265 k = 0
1266 while k < 16 { c4s[k] = tr4[k]; k = k + 1 }
1267 vt2_quant_rdoq(tr4, qp)
1268 } else { vt_fwd(tr4); vt_quant(tr4, qp) }
1269 if sig == 1 { bitsA = bitsA + rc_sig_cost_q8(tr4, 16, 4, probs) } else { bitsA = bitsA + (ve_cost(tr4) << 8) }
1270 if tf == 1 {
1271 k = 0
1272 while k < 16 { let e: i64 = c4s[k] - tr4[k]*dA; eA = eA + e*e; k = k + 1 }
1273 } else {
1274 vt_dequant(tr4, qp); vt_inv(tr4)
1275 k = 0
1276 while k < 16 { let d: i64 = tr4[k] - res[(sj*4 + k/4)*16 + si*4 + (k%4)]; sseA = sseA + d*d; k = k + 1 }
1277 }
1278 si = si + 1 }
1279 sj = sj + 1 }
1280 if tf == 1 { sseA = eA >> 24 }
1281 // option B: 4x 8x8 (DCT8; levels EXACTLY like the real 8x8 emit: same forward_2d + <<2 ref + vc_quant8
1282 // + vc_rdoq8 sequence as vc_enc_sub8, so banked levels == emit levels by identity). Transform-domain
1283 // distortion: e = c8 - L*q in the x4-orthonormal domain => spatial SSE = sum(e*e) >> 4.
1284 // F1114b LEVELS HANDBACK: freq (the final levels -- no dequant destroys them now) is written back into
1285 // THIS quadrant's res[] slots. res is dead after this loop (the caller banks pred=cur-res into recon
1286 // BEFORE any emit), so a bit2 winner's emit consumes these levels via vc_enc_sub8_tail and skips its
1287 // whole forward+quant+RDOQ recompute.
1288 var bitsB: i64 = 0
1289 var eB: i64 = 0
1290 sj = 0
1291 while sj < 2 { var si: i64 = 0
1292 while si < 2 {
1293 var k: i64 = 0
1294 while k < 64 { work[k] = res[(sj*8 + k/8)*16 + si*8 + (k%8)]; k = k + 1 }
1295 nx_dct8_forward_2d(vc_t8p(t8c, VC_T8_M), work, freq, vc_t8p(t8c, VC_T8_SCR), vc_t8p(t8c, VC_T8_TA), vc_t8p(t8c, VC_T8_TB))
1296 k = 0
1297 while k < 64 { work[k] = freq[k] << 2; k = k + 1 }
1298 vc_quant8(freq, qp)
1299 vc_rdoq8(freq, work, qp, zz8)
1300 if sig == 1 { bitsB = bitsB + rc_sig_cost_q8(freq, 64, 8, probs) } else { bitsB = bitsB + (ve64_cost(freq, zz8) << 8) }
1301 k = 0
1302 while k < 64 { let e: i64 = work[k] - freq[k]*qp; eB = eB + e*e; k = k + 1 }
1303 k = 0
1304 while k < 64 { res[(sj*8 + k/8)*16 + si*8 + (k%8)] = freq[k]; k = k + 1 }
1305 si = si + 1 }
1306 sj = sj + 1 }
1307 let sseB: i64 = eB >> 4
1308 // jout is in the SAME estimated-spatial-SSE units both arms; sole consumer vc_rd_part_inter_rc is
1309 // dormant (P3b refuted, zero callers) -- if re-armed its part arm must move to the same estimate.
1310 let jA: i64 = 32*sseA*256 + qp*qp*bitsA
1311 let jB: i64 = 32*sseB*256 + qp*qp*bitsB
1312 jout[0] = jA
1313 if jB < jA { jout[0] = jB; return 1 }
1314 return 0
1315}
1316// P3b (2026-07-12): REAL-BIT PARTITION RD. The SAD-domain vc_rd_part_inter above models neither the transform,
1317// the real bits, nor reconstruction -- the same fidelity gaps P3 closed for the transform decision. This
1318// variant trials BOTH arms byte-faithfully and compares true J:
1319// 16x16 arm = full-pel search + the SAME 16-candidate qpel refine policy as the block coder (qp_refine)
1320// + the faithful t8-pair trial above (RDOQ levels, rc_sig_cost_q8 bits) via jout;
1321// part arm = per-quadrant vc_me8 (its own qpel, the exact MVs vc_enc_mb_part8_inter will re-find)
1322// + the exact 8x8 emit transform (dct8 + vc_quant8 + vc_rdoq8) costed the same way + recon SSE,
1323// with the running-MV-predictor header cost the partition encoder pays.
1324// J = 32*SSE*256 + qp^2*(coeff_bits_q8 + hdr_bits<<8). rc rooms only (bit0); legacy rooms keep the SAD J.
1325func vc_rd_part_inter_rc(cur: *u8, prev: *u8, W: i64, H: i64, cx: i64, cy: i64, qp: i64, tf: i64, rctx: *i64) -> i64 {
1326 let t8c: *i64 = rctx[4] as *i64
1327 let probs: *i64 = rctx[2] as *i64
1328 var sig: i64 = 0
1329 if (rctx[0] & 32) != 0 { sig = 1 }
1330 // scratch rides the slab's intra-only TE region (free during inter) -- NEVER sys_mmap here: in the wasm
1331 // build sys_mmap is a 0-stub, so mmap'd pointers ALIAS at address 0 (the bug that silently zeroed the
1332 // partition MVs in the LIVE wasm -- see vc_enc_mb_part8_inter below, fixed the same day)
1333 let mv: *i64 = vc_t8p(t8c, VC_T8_TE)
1334 let bq: *i64 = ((vc_t8p(t8c, VC_T8_TE) as i64) + 16) as *i64
1335 let jout: *i64 = ((vc_t8p(t8c, VC_T8_TE) as i64) + 32) as *i64
1336 // ---- 16x16 arm ----
1337 vm_search_q(cur, prev, W, H, cx/16, cy/16, 16, VC_ME_R, mv, qp, ((vc_t8p(t8c, VC_T8_TE) as i64) + 40) as *i64)
1338 qp_refine(cur, prev, W, H, cx, cy, mv[0], mv[1], 16, bq)
1339 vc_rd_t8_inter(cur, prev, 0 as *u8, W, cx, cy, qp, mv[0], mv[1], bq[0], bq[1], tf, rctx, jout)
1340 let j16: i64 = jout[0] + qp*qp*((vc_mvcost(mv[0]) + vc_mvcost(mv[1]) + 4) << 8)
1341 // ---- partition arm: 4 quadrants, exact emit transform + real bits + recon SSE ----
1342 let res8: *i64 = vc_t8p(t8c, VC_T8_RES)
1343 let work: *i64 = vc_t8p(t8c, VC_T8_WORK)
1344 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ)
1345 let zz8: *i64 = vc_t8p(t8c, VC_T8_ZZ)
1346 var jpart: i64 = 0
1347 var mvb: i64 = 0
1348 var pmv0: i64 = 0
1349 var pmv1: i64 = 0
1350 var sj: i64 = 0
1351 while sj < 2 { var si: i64 = 0
1352 while si < 2 {
1353 let sx: i64 = cx + si*8
1354 let sy: i64 = cy + sj*8
1355 vc_me8(cur, prev, W, H, sx, sy, mv, bq, qp, ((vc_t8p(t8c, VC_T8_TE) as i64) + 40) as *i64)
1356 mvb = mvb + vc_mvcost(mv[0]-pmv0) + vc_mvcost(mv[1]-pmv1) + 4
1357 pmv0 = mv[0]
1358 pmv1 = mv[1]
1359 var yy: i64 = 0
1360 while yy < 8 { var xx: i64 = 0
1361 while xx < 8 {
1362 let r: i64 = (cur[(sy+yy)*W + (sx+xx)] as i64) - qp_pixel(prev, W, sx+mv[0]+xx, sy+mv[1]+yy, bq[0], bq[1])
1363 work[yy*8 + xx] = r
1364 res8[yy*8 + xx] = r
1365 xx = xx + 1 } yy = yy + 1 }
1366 nx_dct8_forward_2d(vc_t8p(t8c, VC_T8_M), work, freq, vc_t8p(t8c, VC_T8_SCR), vc_t8p(t8c, VC_T8_TA), vc_t8p(t8c, VC_T8_TB))
1367 var k: i64 = 0
1368 while k < 64 { work[k] = freq[k] << 2; k = k + 1 }
1369 vc_quant8(freq, qp)
1370 vc_rdoq8(freq, work, qp, zz8)
1371 if sig == 1 { jpart = jpart + qp*qp*rc_sig_cost_q8(freq, 64, 8, probs) } else { jpart = jpart + qp*qp*(ve64_cost(freq, zz8) << 8) }
1372 vc_dequant8(freq, qp)
1373 nx_dct8_inverse_2d(vc_t8p(t8c, VC_T8_M), freq, work, vc_t8p(t8c, VC_T8_SCR), vc_t8p(t8c, VC_T8_TA), vc_t8p(t8c, VC_T8_TB))
1374 k = 0
1375 var sse: i64 = 0
1376 while k < 64 { let d: i64 = work[k] - res8[k]; sse = sse + d*d; k = k + 1 }
1377 jpart = jpart + 32*sse*256
1378 si = si + 1 } sj = sj + 1 }
1379 jpart = jpart + qp*qp*(mvb << 8)
1380 if jpart < j16 { return 1 }
1381 return 0
1382}
1383// 4x4 Hadamard SATD of a prefilled residual d[16] (IN-PLACE butterflies; caller's buffer is scratch). Sum of
1384// |transform coeffs| / 2 (x264 normalization). SATD is a RATE proxy: the transform concentrates a structured
1385// residual into few coefficients, so argmin-by-SATD picks the MV whose residual is CHEAPEST TO CODE, where
1386// argmin-by-SAD picks the numerically smallest -- the classic x264 refinement win. Any orthogonal Hadamard
1387// ordering gives the same |coeff| multiset, so the unordered butterfly below is exact for SATD.
1388func vc_satd4_d(d: *i64) -> i64 {
1389 var i: i64 = 0
1390 while i < 4 {
1391 let b: i64 = i * 4
1392 let t0: i64 = d[b] + d[b+2]
1393 let t1: i64 = d[b+1] + d[b+3]
1394 let t2: i64 = d[b] - d[b+2]
1395 let t3: i64 = d[b+1] - d[b+3]
1396 d[b] = t0 + t1
1397 d[b+1] = t0 - t1
1398 d[b+2] = t2 + t3
1399 d[b+3] = t2 - t3
1400 i = i + 1
1401 }
1402 var j: i64 = 0
1403 while j < 4 {
1404 let u0: i64 = d[j] + d[8+j]
1405 let u1: i64 = d[4+j] + d[12+j]
1406 let u2: i64 = d[j] - d[8+j]
1407 let u3: i64 = d[4+j] - d[12+j]
1408 d[j] = u0 + u1
1409 d[4+j] = u0 - u1
1410 d[8+j] = u2 + u3
1411 d[12+j] = u2 - u3
1412 j = j + 1
1413 }
1414 var s: i64 = 0
1415 var k: i64 = 0
1416 while k < 16 {
1417 let v: i64 = d[k]
1418 if v < 0 { s = s - v } else { s = s + v }
1419 k = k + 1
1420 }
1421 return s / 2
1422}
1423// SATD cost of ONE 16x16 quarter-pel candidate (tqx,tqy) at full-pel base (px,py): 16 x satd4 over the same
1424// inlined-bilinear predictor as the SAD path ((acc+8)/16, w00..w11 hoisted) so the residual matches what the
1425// coder will actually produce. Early-exits vs `limit` (SATD only grows; a partial >= limit loses the strict <).
1426func vc_satd16_cand(cur: *u8, prev: *u8, W: i64, cx: i64, cy: i64, px: i64, py: i64, tqx: i64, tqy: i64, limit: i64, sd: *i64) -> i64 {
1427 let wxc: i64 = 4 - tqx
1428 let wyc: i64 = 4 - tqy
1429 let w00: i64 = wxc * wyc
1430 let w10: i64 = tqx * wyc
1431 let w01: i64 = wxc * tqy
1432 let w11: i64 = tqx * tqy
1433 var acc: i64 = 0
1434 var qy: i64 = 0
1435 while qy < 4 {
1436 var qx: i64 = 0
1437 while qx < 4 {
1438 var iy: i64 = 0
1439 while iy < 4 {
1440 let crow: i64 = (cy + qy*4 + iy) * W + cx + qx*4
1441 let prow: i64 = (py + qy*4 + iy) * W + px + qx*4
1442 let prow1: i64 = prow + W
1443 var ix: i64 = 0
1444 while ix < 4 {
1445 var a: i64 = w00 * (prev[prow + ix] as i64)
1446 if tqx > 0 { a = a + w10 * (prev[prow + ix + 1] as i64) }
1447 if tqy > 0 { a = a + w01 * (prev[prow1 + ix] as i64) }
1448 if w11 > 0 { a = a + w11 * (prev[prow1 + ix + 1] as i64) }
1449 sd[iy*4 + ix] = (cur[crow + ix] as i64) - ((a + 8) / 16)
1450 ix = ix + 1
1451 }
1452 iy = iy + 1
1453 }
1454 acc = acc + vc_satd4_d(sd)
1455 if acc >= limit { return acc }
1456 qx = qx + 1
1457 }
1458 qy = qy + 1
1459 }
1460 return acc
1461}
1462func vc_enc_block_packed(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, bx: i64, by: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, bp0: i64, blk: *i64, mv: *i64, tfy: i64) -> i64 {
1463 return vc_enc_block_packed_e(cur, prev, recon, W, H, bx, by, qp, keyframe, sad_thresh, buf, bp0, blk, mv, tfy, 0 as *i64)
1464}
1465// ---- RD-SKIP (gen-2 rung-0 P0c -> gen-1 ship; emode bit11=2048, ENCODER-ONLY = decoder-transparent, no vcv
1466// bump: the skip bit is on the wire either way). Replaces the qp*30 skip threshold with TRUE rate-distortion
1467// skip: trial-code the P-MB both ways through the live coder (range-coder est/probs snapshot/restore; real bits
1468// from a flush-length probe on a COPY of est, tail bytes land in the dead zone past the live rcbuf position) and
1469// commit the J = 32*SSE + qp^2*bits winner (the same Lagrangian as vc_rd_t8_inter). MEASURED RD-DOMINANT
1470// (nx_vcodec_rdskip_gate, fidelity-proven): akiyo qp20 -6.9% bits AND -3.2% MSE; foreman qp32 -31% MSE for
1471// +4.3% bits; the fixed threshold leaks BOTH ways (wrongly-skips 4002 MBs foreman qp32, wrongly-codes 1984
1472// akiyo qp8 -- the audit's predicted content-dependence). bit11 off = byte-identical legacy (_i is the old _e).
1473// trial scratch lives at t8c+5008 (t8c = rctx[4] = a 626-i64=5008B slab; in the wasm region layout a 560B pad
1474// sits before rcbuf, and the gates' page-rounded mmap gives the same room) -- NO runtime mmap (sys_mmap is a
1475// 0-stub in wasm; and per-MB mmap would leak over live hours). 48 i64: est snap[0..7] + est copy[8..15] + probs
1476// snap[16..16+RC_NCTX8]. vc_t8_init never writes past index 626, so this tail is dead space.
1477func vc_rdskip_len(est: *i64, scr: *i64, rcbuf: *u8) -> i64 {
1478 var i: i64 = 0
1479 while i < 8 { scr[8 + i] = est[i]; i = i + 1 }
1480 let rb: i64 = rc_enc_flush(((scr as i64) + 64) as *i64, rcbuf)
1481 return rb * 8
1482}
1483func vc_enc_block_packed_e(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, bx: i64, by: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, bp0: i64, blk: *i64, mv: *i64, tfy: i64, rctx: *i64) -> i64 {
1484 var rdsk: i64 = 0
1485 if (rctx as i64) != 0 { if keyframe == 0 { rdsk = (rctx[0] >> 11) & 1 } }
1486 if rdsk == 0 { return vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, qp, keyframe, sad_thresh, buf, bp0, blk, mv, tfy, rctx) }
1487 // ---- FPS BAND (817; the 816 trial-everything COLLAPSED live fps: the CODE arm forces full ME on EVERY
1488 // MB, including the static majority the do_me gate used to spare). Only MBs NEAR the skip boundary are
1489 // genuinely ambiguous (the measured flips cluster there); obvious-skip and obvious-code MBs take the
1490 // legacy threshold path at legacy cost. Band [thresh/4, 8*thresh] chosen to cover both measured flip
1491 // populations (RD-codes below thresh at high qp; RD-skips above thresh at low qp) -- BD-rate retention
1492 // + fps both MEASURED before ship.
1493 let zs: i64 = vm_sad_zero(cur, prev, W, bx, by, 16)
1494 var intrial: i64 = 1
1495 if zs < sad_thresh / VC_RDSK_LO_DIV { intrial = 0 }
1496 if zs > sad_thresh * VC_RDSK_HI_MUL { intrial = 0 }
1497 if intrial == 1 { if zs < sad_thresh { if (rctx[0] & VC_EMODE_QQSKIP) != 0 {
1498 // bit14: lower sub-band -- trial only if a quadrant moves (see VC_EMODE_QQSKIP)
1499 let qcx: i64 = bx * 16
1500 let qcy: i64 = by * 16
1501 let qqt: i64 = sad_thresh / VC_RDSK_LO_DIV
1502 var qmov: i64 = 0
1503 if vm_sad(cur, prev, W, qcx, qcy, qcx, qcy, 8) >= qqt { qmov = 1 }
1504 if vm_sad(cur, prev, W, qcx + 8, qcy, qcx + 8, qcy, 8) >= qqt { qmov = 1 }
1505 if vm_sad(cur, prev, W, qcx, qcy + 8, qcx, qcy + 8, 8) >= qqt { qmov = 1 }
1506 if vm_sad(cur, prev, W, qcx + 8, qcy + 8, qcx + 8, qcy + 8, 8) >= qqt { qmov = 1 }
1507 if qmov == 0 { intrial = 0 }
1508 } } }
1509 if intrial == 0 { return vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, qp, keyframe, sad_thresh, buf, bp0, blk, mv, tfy, rctx) }
1510 let scr: *i64 = (rctx[4] + VC_MAGIC_5008) as *i64
1511 let est: *i64 = rctx[1] as *i64
1512 let probs: *i64 = rctx[2] as *i64
1513 let rcbuf: *u8 = rctx[3] as *u8
1514 var i: i64 = 0
1515 while i < 8 { scr[i] = est[i]; i = i + 1 }
1516 i = 0
1517 while i < RC_NCTX8 { scr[16 + i] = probs[i]; i = i + 1 }
1518 let r5: i64 = rctx[5]
1519 let rc0: i64 = vc_rdskip_len(est, scr, rcbuf)
1520 // arm CODE (F1113: NEGATIVE sad_thresh = skip disabled, do_me/partition gates at the REAL threshold --
1521 // the old 0 also forced full search + partition RD on sub-threshold band MBs = gratuitous fps cost)
1522 let bpc: i64 = vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, qp, 0, 0 - sad_thresh, buf, bp0, blk, mv, tfy, rctx)
1523 let rc1: i64 = vc_rdskip_len(est, scr, rcbuf)
1524 let cx: i64 = bx * 16
1525 let cy: i64 = by * 16
1526 var dcode: i64 = 0
1527 var y: i64 = 0
1528 while y < 16 {
1529 var x: i64 = 0
1530 while x < 16 { let d: i64 = (recon[(cy+y)*W + cx+x] as i64) - (cur[(cy+y)*W + cx+x] as i64); dcode = dcode + d*d; x = x + 1 }
1531 y = y + 1 }
1532 let bits_code: i64 = (bpc - bp0) + (rc1 - rc0)
1533 // FAST RD-skip (2026-07-14, the "un-cripple" lever): skip freezes recon to prev at zero-MV, so the skip
1534 // distortion is dskip = SSD(cur, prev) computed DIRECTLY -- NO skip trial-encode. And the CODE arm already
1535 // ran once above and IS the committed stream, so if CODE wins we return it with NO re-encode (the old path
1536 // re-ran the full code arm = the measured 2x cost that kept RD-skip out of RTC). Only the losing-SKIP case
1537 // pays a cheap skip encode. Decoder-transparent: same code/skip choice, same output bytes as full RD-skip
1538 // (the skip-bit cost is ~1 and J is distortion-dominated, so the decision matches; verified vs handoff bench).
1539 var dskip: i64 = 0
1540 y = 0
1541 while y < 16 {
1542 var x: i64 = 0
1543 while x < 16 { let d: i64 = (prev[(cy+y)*W + cx+x] as i64) - (cur[(cy+y)*W + cx+x] as i64); dskip = dskip + d*d; x = x + 1 }
1544 y = y + 1 }
1545 let jc: i64 = 32*dcode + qp*qp*bits_code
1546 let js: i64 = 32*dskip + qp*qp
1547 if jc < js { return bpc }
1548 // SKIP wins -> undo the code arm (restore pre-code rc state + rewind bp to bp0) and encode the cheap skip
1549 i = 0
1550 while i < 8 { est[i] = scr[i]; i = i + 1 }
1551 i = 0
1552 while i < RC_NCTX8 { probs[i] = scr[16 + i]; i = i + 1 }
1553 rctx[5] = r5
1554 return vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, qp, 0, VC_MAGIC_1152921504606846976, buf, bp0, blk, mv, tfy, rctx)
1555}
1556func vc_enc_block_packed_i(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, bx: i64, by: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, bp0: i64, blk: *i64, mv: *i64, tfy: i64, rctx: *i64) -> i64 {
1557 let tf: i64 = tfy & 1; let t8: i64 = (tfy >> 1) & 1; let ytop: i64 = tfy >> 2 // tfy packs bit0=4x4-transform-select, bit1=this-MB-is-8x8-coded (t8 frame fns only), >>2 = strip top pixel-row: intra must not read above it (TILE-PARALLEL independence)
1558 let cx: i64 = bx*16
1559 let cy: i64 = by*16
1560 var bp: i64 = bp0
1561 // 865-hex: the previous macroblock's vector (this scratch is shared across the frame loop) is the spatial predictor the
1562 // hexagon search seeds from; blk is dead during the search, so blk[3..4] carries it (see vm_search_hex).
1563 blk[3] = mv[0]
1564 blk[4] = mv[1]
1565 mv[0] = 0; mv[1] = 0
1566 var bqx: i64 = 0
1567 var bqy: i64 = 0
1568 // F1113 RD-TRIAL MODE: sad_thresh < 0 = "skip DISABLED, every OTHER gate at |sad_thresh|". The old
1569 // trial convention passed 0, which also forced do_me=1 (full search + refine on static MBs the
1570 // legacy path codes ungated at (0,0)) and pgo=1 (partition RD on EVERY trial MB) -- gratuitous
1571 // integration cost that was most of the RD-skip fps bill (817-law re-measure 2026-07-27).
1572 var thr: i64 = sad_thresh
1573 var noskip: i64 = 0
1574 if thr < 0 { thr = 0 - thr; noskip = 1 }
1575 if keyframe == 0 {
1576 let zsad: i64 = vm_sad_zero(cur, prev, W, bx, by, 16)
1577 var doskip: i64 = vs_skip(zsad, 0, 0, thr)
1578 if noskip == 1 { doskip = 0 }
1579 bp = nx_bw_put(buf, bp, doskip, 1)
1580 if doskip == 1 {
1581 var cy0: i64 = 0
1582 while cy0 < 16 { var cx0: i64 = 0
1583 while cx0 < 16 { recon[(cy+cy0)*W + (cx+cx0)] = prev[(cy+cy0)*W + (cx+cx0)]; cx0 = cx0 + 1 } cy0 = cy0 + 1 }
1584 return bp
1585 }
1586 // vcv-8 INTRA-IN-P (emode bit8, LUMA only). A non-skip P-MB may be coded as INTRA (9-mode rich-intra, NO
1587 // MV) when even a flat-DC intra estimate beats the best inter -- x264-class I-in-P, shrinking the residual
1588 // on hard-to-predict MBs at ZERO MV cost. Mode bit emitted ONLY when bit8 is set (gen>=8), BEFORE the
1589 // partition/inter header, so lower generations see a byte-identical stream. dmv is a separate search
1590 // scratch so the inter fall-through still sees mv=(0,0) for its own do_me gate.
1591 if (rctx as i64) != 0 { if (rctx[0] & 256) != 0 { if (rctx[0] & 16) == 0 {
1592 let isad: i64 = vc_intra_dc_sad(cur, recon, W, cx, cy)
1593 // dmv scratch on the rctx[4] slab (+5392, past the 48-i64 RD-skip scr): a sys_mmap here ran PER
1594 // NON-SKIP MB -> map-count exhaustion on threshold-retune benches (crash) + wasm sys_mmap is a
1595 // 0-stub. Slab fits both layouts (wasm: 5008+560B pad >= 5408). Guarded: bit8 => rct8 path => rctx[4] valid.
1596 let dmv: *i64 = (rctx[4] + VC_MAGIC_5392) as *i64
1597 let msad: i64 = vm_search(cur, prev, W, H, bx, by, 16, 8, dmv, blk)
1598 var imode: i64 = 0; if isad < msad { imode = 1 }
1599 bp = nx_bw_put(buf, bp, imode, 1)
1600 if imode == 1 { return vc_enc_mb4r_intra(cur, recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx) }
1601 } } }
1602 // F1112: have16 = the partition trial already ran (and rejected) => scr TE[0..1] holds THIS block's
1603 // 16x16 argmin, byte-for-byte what the search below would recompute.
1604 var have16: i64 = 0
1605 // vcv-7 P_8x8 MOTION PARTITION (emode bit7, LUMA only -- chroma bit4 never partitions). part bit emitted
1606 // ONLY when bit7 is set (client partAll()), so a vcv-6 room sees a byte-identical stream. RD picks 16x16
1607 // vs 4x-8x8; if partition, code it and return (its MVs+residual replace the 16x16 header below).
1608 if (rctx as i64) != 0 { if (rctx[0] & 128) != 0 { if (rctx[0] & 16) == 0 {
1609 // P3b real-bit partition J (vc_rd_part_inter_rc) MEASURED +5.45% avg vs the SAD J = REFUTED
1610 // 2026-07-12 (per-quadrant qpel-refined trial residuals flatter the partition arm; the fn stays
1611 // in-tree dormant with the analysis in the roadmap). The SAD J stays -- now with real scratch.
1612 // 825 ORDERING FIX (live-incident follow-up): the partition evaluation (5 motion searches) used to
1613 // run BEFORE the static gate, so on real sensor noise every noise-static block paid it -- MEASURED
1614 // 41% of the noise frame time (320x256: 51.4 -> 30.2 ms without it). Gate on motion -- but the
1615 // whole-MB zsad alone is BLIND to a single moving QUADRANT inside a quiet block (exactly what
1616 // partitions exist for; zsad-only gating measured +2.0% avg BD, bus +4.5). So: evaluate when the
1617 // MB moves OR any 8x8 quadrant does (four zero-SADs = 256 adds, trivial next to 5 searches;
1618 // per-quadrant threshold = thresh/4 by area). The partition BIT stays in the syntax either way.
1619 var usepart: i64 = 0
1620 var pgo: i64 = 0
1621 if zsad >= thr { pgo = 1 }
1622 if pgo == 0 {
1623 let qt: i64 = thr / 4
1624 if vm_sad(cur, prev, W, cx, cy, cx, cy, 8) >= qt { pgo = 1 }
1625 if vm_sad(cur, prev, W, cx+8, cy, cx+8, cy, 8) >= qt { pgo = 1 }
1626 if vm_sad(cur, prev, W, cx, cy+8, cx, cy+8, 8) >= qt { pgo = 1 }
1627 if vm_sad(cur, prev, W, cx+8, cy+8, cx+8, cy+8, 8) >= qt { pgo = 1 }
1628 }
1629 if pgo == 1 {
1630 usepart = vc_rd_part_inter(cur, prev, W, H, cx, cy, qp, vc_t8p(rctx[4] as *i64, VC_T8_TE))
1631 // F1112: a rejected trial already searched THIS block's 16x16 window -- reuse it below
1632 if usepart == 0 { have16 = 1 }
1633 }
1634 bp = nx_bw_put(buf, bp, usepart, 1)
1635 if usepart == 1 { return vc_enc_mb_part8_inter(cur, prev, recon, W, H, cx, cy, qp, buf, bp, rctx[4] as *i64, rctx) }
1636 } } }
1637 // ME GATE (2026-07-03 stage profile: skip never fires vs recon refs -- quant noise alone is
1638 // ~QP*avg-err*256 SAD -- so EVERY block paid the 289-SAD search + 16-candidate refine = the
1639 // measured 74%+54% of P-encode). Near-static block => motion is (0,0); STILL CODE THE RESIDUAL
1640 // (that is where the quality lives -- full-skip cost a measured 2.8-4.1dB, this costs ~0 by
1641 // construction: the residual coder captures whatever the gate misses, only BITS are at risk,
1642 // and for texture-evolution content ME finds nothing anyway, zsad ~= searched-sad). Gate is
1643 // QP-SCALED like the quant deadzone (no magic constant): qp*188 sits above the measured
1644 // static-with-quant-noise band (~2-3k at QP32) and below real translation (edge slivers ~11k),
1645 // so genuinely moving blocks still get the full search + quarter-pel refine.
1646 var do_me: i64 = 1
1647 // F1113 refinement (MEASURED, foreman): in RD-trial mode the search must stay ON -- gating it made
1648 // band MBs code at (0,0) with fat residuals, losing BOTH axes (-0.6dB at +25-70% bits vs searched
1649 // trials). Only the PARTITION forcing was pure waste. So noskip keeps do_me=1 unconditionally.
1650 if noskip == 0 { if zsad < thr { do_me = 0 } } // 811-followup: tie the motion-search gate to the SKIP threshold (was
1651 // hardcoded qp*188 -- after the skip fix that left [skip,188) blocks CODED with (0,0) motion + no search =
1652 // huge residual on moving blocks). Now every coded (non-skip) block gets the full search + qpel refine.
1653 // MEASURED I+P BD-rate vs x264: foreman +459->+240% · akiyo +302->+238% · bus +259->+183% · mobile +238->+178%.
1654 var mvd10: i64 = 0
1655 if (rctx as i64) != 0 { if (rctx[0] & VC_MAGIC_8192) != 0 { mvd10 = 1 } }
1656 if do_me == 1 {
1657 if have16 == 1 {
1658 // F1112: the partition trial's 16x16 search IS this search (same refs, same window, same
1659 // qp, cx/16==bx by construction; vm_search_q is pure in its inputs) -- take the trial's
1660 // argmin from the handback slots instead of re-running the candidate walk.
1661 let scr16: *i64 = vc_t8p(rctx[4] as *i64, VC_T8_TE)
1662 mv[0] = scr16[VC_TE_H16_MV0]
1663 mv[1] = scr16[VC_TE_H16_MV1]
1664 } else {
1665 var hexme: i64 = 0
1666 if (rctx as i64) != 0 { if (rctx[0] & VC_EMODE_HEXME) != 0 { hexme = 1 } }
1667 if hexme == 1 { vm_search_hex(cur, prev, W, H, bx, by, 16, VC_ME_R, mv, qp, blk) } else { vm_search_q(cur, prev, W, H, bx, by, 16, VC_ME_R, mv, qp, blk) }
1668 }
1669 }
1670 if mvd10 == 1 {
1671 // vcv-10 MVD: median-predicted delta in exp-Golomb (MEASURED 9permille-of-P-bytes floor vs
1672 // absolute ve_vput -- nx_vcodec_mvbits_probe 2026-07-20). pxy scratch = TE+48 (past the
1673 // rd_part mv/bq/jout slots, all dead by this point). Plane set = the EMITTED mv (pre-clamp
1674 // truth; the decoder mirrors from the wire).
1675 let mvp10: *i64 = rctx[9] as *i64
1676 let pxy10: *i64 = ((vc_t8p(rctx[4] as *i64, VC_T8_TE) as i64) + 48) as *i64
1677 vc_mvpred(mvp10, W/16, bx, pxy10)
1678 bp = vc_gput(buf, bp, mv[0] - pxy10[0])
1679 bp = vc_gput(buf, bp, mv[1] - pxy10[1])
1680 vc_mvplane_set(mvp10, W/16, bx, mv[0], mv[1])
1681 } else {
1682 bp = ve_vput(buf, bp, mv[0])
1683 bp = ve_vput(buf, bp, mv[1])
1684 }
1685 // QUARTER-PEL refine over the 16x16 MB (streaming SAD, no scratch): qp_pixel subsumes integer (0,0) and half
1686 // (2,*) EXACTLY, so (0,0) reduces to integer motion (bit-exact invariant preserved) and a sub-pixel shift ->
1687 // smaller residual -> fewer bits (H.264/VP9 motion precision). qp_pixel matches the decoder, so recon is exact.
1688 let px: i64 = cx + mv[0]
1689 let py: i64 = cy + mv[1]
1690 // SATD REFINE (emode bit10, 2026-07-11, ENCODER-ONLY -> decoder-transparent, NO vcv bump: the wire
1691 // carries whatever MV wins; any decoder reproduces it). Argmin by Hadamard SATD (rate proxy -- picks the
1692 // candidate whose residual is cheapest to CODE) instead of raw SAD. bestsad is INTERNAL to this argmin
1693 // (nothing downstream reads it), so the scale difference (SATD ~2x SAD) contaminates no threshold.
1694 var use_satd: i64 = 0
1695 if (rctx as i64) != 0 { use_satd = (rctx[0] >> 10) & 1 }
1696 var sdp: i64 = 0
1697 if use_satd == 1 { sdp = vc_t8p(rctx[4] as *i64, VC_T8_SCR) as i64 } // slab, NEVER sys_mmap (wasm 0-stub class; SCR 128B dead during refine) -- eats seq234
1698 var bestsad: i64 = VC_MAGIC_2147483647
1699 var tqy: i64 = 0
1700 if do_me == 0 { tqy = 4; bestsad = zsad } // ME-gated: (0,0) integer motion, no refine (bqx=bqy=0 coded below);
1701 // bestsad = the honest residual scale so downstream gates (t8 early-out) see reality, not 2^31
1702 while tqy <= 3 {
1703 var tqx: i64 = 0
1704 while tqx <= 3 {
1705 var ok: i64 = 1
1706 if tqx > 0 { if px + 16 >= W { ok = 0 } }
1707 if tqy > 0 { if py + 16 >= H { ok = 0 } }
1708 if ok == 1 {
1709 if use_satd == 1 {
1710 let scost: i64 = vc_satd16_cand(cur, prev, W, cx, cy, px, py, tqx, tqy, bestsad, sdp as *i64)
1711 if scost < bestsad { bestsad = scost; bqx = tqx; bqy = tqy }
1712 } else {
1713 // INLINED qp_pixel bilinear with per-candidate hoisted weights + per-row hoisted
1714 // bases: identical arithmetic to qp_pixel (acc = w00*p00 + w10*p10 + w01*p01 +
1715 // w11*p11; (acc+8)/16; (0,0) reduces to (16a+8)/16 == a) so every SAD -- and thus
1716 // the selected candidate and the BITSTREAM -- is unchanged. What it removes is the
1717 // per-pixel CALL + the y*W recomputation, the measured hot core of the 76ms frame.
1718 let wxc: i64 = 4 - tqx
1719 let wyc: i64 = 4 - tqy
1720 let w00: i64 = wxc * wyc
1721 let w10: i64 = tqx * wyc
1722 let w01: i64 = wxc * tqy
1723 let w11: i64 = tqx * tqy
1724 var sad: i64 = 0
1725 var ry: i64 = 0
1726 while ry < 16 {
1727 let crow: i64 = (cy + ry) * W + cx
1728 let prow: i64 = (py + ry) * W + px
1729 let prow1: i64 = prow + W
1730 var rx: i64 = 0
1731 while rx < 16 {
1732 var acc: i64 = w00 * (prev[prow + rx] as i64)
1733 if tqx > 0 { acc = acc + w10 * (prev[prow + rx + 1] as i64) }
1734 if tqy > 0 { acc = acc + w01 * (prev[prow1 + rx] as i64) }
1735 if w11 > 0 { acc = acc + w11 * (prev[prow1 + rx + 1] as i64) }
1736 let dd: i64 = (cur[crow + rx] as i64) - ((acc + 8) / 16)
1737 if dd < 0 { sad = sad - dd } else { sad = sad + dd }
1738 rx = rx + 1
1739 }
1740 // early-exit (bit-exact): sad only grows; a candidate already >= bestsad loses
1741 // under the strict < below whether finished or not. (0,0) runs first with
1742 // bestsad=MAX so the integer-motion baseline is always fully evaluated.
1743 if sad >= bestsad { ry = 16 } else { ry = ry + 1 }
1744 }
1745 if sad < bestsad { bestsad = sad; bqx = tqx; bqy = tqy }
1746 }
1747 }
1748 tqx = tqx + 1
1749 }
1750 tqy = tqy + 1
1751 }
1752 bp = nx_bw_put(buf, bp, bqx, 2)
1753 bp = nx_bw_put(buf, bp, bqy, 2)
1754 }
1755 var t8x: i64 = t8
1756 var resfresh: i64 = 0
1757 if (rctx as i64) != 0 { if (rctx[0] & 4) != 0 { if keyframe == 0 { if bestsad >= qp * VC_EO_T8 {
1758 // RD-AUTO (encoder-only, emode bit2): decide per-MB from the ACTUAL MC residual and patch the
1759 // reserved t8 bit at rctx[5] (frame fn wrote a 0 placeholder). The decoder just reads the bit.
1760 // EARLY-OUT: a low refined-SAD residual has too little energy for the transform choice to matter --
1761 // default 4x4 (the majority winner) and save both trial passes (the measured decision-stack cost).
1762 // F1114b: the trial banks its exact PREDICTOR into recon (during its residual fill -- res[] is
1763 // levels, not residual, once its B arm finishes) and leaves its final 8x8 LEVELS in res[]'s
1764 // quadrants. Both emits below consume the bank: the 8x8 winner skips forward+quant+RDOQ AND all
1765 // 512 bilinears (vc_enc_mb8_inter pfresh); the 4x4 path derives its residual as cur - recon.
1766 // (History: the residual-only handback measured 1.00x alone -- bilinears were ~5% -- and was
1767 // stripped same-day; it returned as the enabling leg of this levels handback.)
1768 t8x = vc_rd_t8_inter(cur, prev, recon, W, cx, cy, qp, mv[0], mv[1], bqx, bqy, tf, rctx, vc_t8p(rctx[4] as *i64, VC_T8_EO))
1769 if t8x == 1 { nx_bw_put(buf, rctx[5], 1, 1) }
1770 resfresh = 1
1771 } } } }
1772 if t8x == 1 {
1773 // ---- 8x8 path (task #46 rung 2): the MB header above (skip/MV/quarter-pel) is SHARED -- only the
1774 // prediction granularity + residual transform change. The t8c slab rides rctx[4] (the t8 frame fns
1775 // guarantee rctx is i64[>=6]; no other caller ever sets tfy bit1 or emode bit2). ----
1776 let t8c: *i64 = rctx[4] as *i64
1777 if keyframe == 1 { return vc_enc_mb8_intra(cur, recon, W, cx, cy, ytop, qp, buf, bp, t8c, rctx) }
1778 return vc_enc_mb8_inter(cur, prev, recon, W, cx, cy, qp, mv[0], mv[1], bqx, bqy, buf, bp, t8c, rctx, resfresh)
1779 }
1780 if keyframe == 1 { if (rctx as i64) != 0 { if (rctx[0] & 8) != 0 { if (rctx[0] & 16) == 0 {
1781 // RICH-INTRA stream (emode bit3, set by the t8 frame fns on BOTH sides): 4x4 intra MBs get the
1782 // 9-mode MPM engine too. Legacy streams (bit3 never set) keep the inline 4-mode path below.
1783 // bit4 (conservative plane -- CHROMA) opts OUT back to the legacy 4-mode syntax: the field noise
1784 // gate measured rich-intra chroma at +26% blockiness under temporal noise at qp33 (mode structure
1785 // persists through skip-heavy chroma P frames). BOTH vv wrappers set bit4 for U/V deterministically,
1786 // so encoder and decoder agree on the per-plane syntax by construction.
1787 return vc_enc_mb4r_intra(cur, recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx)
1788 } } } }
1789 var sj: i64 = 0
1790 while sj < 4 {
1791 var si: i64 = 0
1792 while si < 4 {
1793 let sx: i64 = cx + si*4
1794 let sy: i64 = cy + sj*4
1795 if keyframe == 1 {
1796 // ---- directional intra: gather edge-substituted reconstructed neighbors (scalars, no alloc) ----
1797 var t0: i64=128; var t1: i64=128; var t2: i64=128; var t3: i64=128
1798 var l0: i64=128; var l1: i64=128; var l2: i64=128; var l3: i64=128
1799 var corner: i64=128
1800 if sy > ytop { t0=recon[(sy-1)*W+sx] as i64; t1=recon[(sy-1)*W+sx+1] as i64; t2=recon[(sy-1)*W+sx+2] as i64; t3=recon[(sy-1)*W+sx+3] as i64 }
1801 if sx > 0 { l0=recon[sy*W+sx-1] as i64; l1=recon[(sy+1)*W+sx-1] as i64; l2=recon[(sy+2)*W+sx-1] as i64; l3=recon[(sy+3)*W+sx-1] as i64 }
1802 if sx > 0 { if sy > ytop { corner=recon[(sy-1)*W+sx-1] as i64 } }
1803 var dcsum: i64=0; var dccnt: i64=0
1804 if sy > ytop { dcsum=dcsum+t0+t1+t2+t3; dccnt=dccnt+4 }
1805 if sx > 0 { dcsum=dcsum+l0+l1+l2+l3; dccnt=dccnt+4 }
1806 var dc: i64=128; if dccnt > 0 { dc=dcsum/dccnt } // mode 0 == vc_dc_pred's rule (old behavior preserved)
1807 // pick the lowest-SAD mode of {DC,V,H,DDR}
1808 var bestmode: i64=0; var bestsad: i64=VC_MAGIC_2147483647; var m: i64=0
1809 while m < 4 {
1810 var sad: i64=0; var ay: i64=0
1811 while ay < 4 { var ax: i64=0
1812 while ax < 4 { let d: i64=(cur[(sy+ay)*W+sx+ax] as i64) - vc_pred_px(m, ax, ay, t0,t1,t2,t3, l0,l1,l2,l3, corner, dc); if d<0 { sad=sad-d } else { sad=sad+d } ax=ax+1 } ay=ay+1 }
1813 if sad < bestsad { bestsad=sad; bestmode=m }
1814 m=m+1
1815 }
1816 bp = nx_bw_put(buf, bp, bestmode, 2)
1817 var ry: i64=0
1818 while ry < 4 { var rx: i64=0
1819 while rx < 4 { blk[ry*4+rx]=(cur[(sy+ry)*W+sx+rx] as i64) - vc_pred_px(bestmode, rx, ry, t0,t1,t2,t3, l0,l1,l2,l3, corner, dc); rx=rx+1 } ry=ry+1 }
1820 bp = vc_coeff_enc(blk, qp, buf, bp, tf, rctx)
1821 var cy2: i64=0
1822 while cy2 < 4 { var cx2: i64=0
1823 while cx2 < 4 {
1824 var v: i64=vc_pred_px(bestmode, cx2, cy2, t0,t1,t2,t3, l0,l1,l2,l3, corner, dc) + blk[cy2*4+cx2]
1825 if v < 0 { v=0 } if v > 255 { v=255 }
1826 recon[(sy+cy2)*W+sx+cx2]=v as u8
1827 cx2=cx2+1 } cy2=cy2+1 }
1828 } else {
1829 // ---- inter: quarter-pel motion-compensated predictor. F1114b: when the bit2 trial ran,
1830 // its exact predictor is banked in recon (res[] holds levels by now, NOT residual) --
1831 // recon[pix] keeps pred until the write below replaces it, per-pixel read-then-write ----
1832 var yy: i64 = 0
1833 while yy < 4 {
1834 var xx: i64 = 0
1835 while xx < 4 {
1836 let c: i64 = cur[(sy+yy)*W + (sx+xx)] as i64
1837 var pred: i64 = 0
1838 if resfresh == 1 { pred = recon[(sy+yy)*W + (sx+xx)] as i64 }
1839 else { pred = qp_pixel(prev, W, sx+xx+mv[0], sy+yy+mv[1], bqx, bqy) }
1840 blk[yy*4 + xx] = c - pred
1841 xx = xx + 1
1842 }
1843 yy = yy + 1
1844 }
1845 bp = vc_coeff_enc(blk, qp, buf, bp, tf, rctx)
1846 yy = 0
1847 while yy < 4 {
1848 var xx: i64 = 0
1849 while xx < 4 {
1850 var pred: i64 = 0
1851 if resfresh == 1 { pred = recon[(sy+yy)*W + (sx+xx)] as i64 }
1852 else { pred = qp_pixel(prev, W, sx+xx+mv[0], sy+yy+mv[1], bqx, bqy) }
1853 var v: i64 = pred + blk[yy*4 + xx]
1854 if v < 0 { v = 0 }
1855 if v > 255 { v = 255 }
1856 recon[(sy+yy)*W + (sx+xx)] = v as u8
1857 xx = xx + 1
1858 }
1859 yy = yy + 1
1860 }
1861 }
1862 si = si + 1
1863 }
1864 sj = sj + 1
1865 }
1866 return bp
1867}
1868// decode one macroblock from the stream at bp into recon (using prev only); returns the new bit position.
1869func vc_dec_block_packed(prev: *u8, recon: *u8, W: i64, H: i64, bx: i64, by: i64, qp: i64, keyframe: i64, buf: *u8, bp0: i64, blk: *i64, mv: *i64, tfy: i64) -> i64 {
1870 return vc_dec_block_packed_e(prev, recon, W, H, bx, by, qp, keyframe, buf, bp0, blk, mv, tfy, 0 as *i64)
1871}
1872func vc_dec_block_packed_e(prev: *u8, recon: *u8, W: i64, H: i64, bx: i64, by: i64, qp: i64, keyframe: i64, buf: *u8, bp0: i64, blk: *i64, mv: *i64, tfy: i64, rctx: *i64) -> i64 {
1873 let tf: i64 = tfy & 1; let t8: i64 = (tfy >> 1) & 1; let ytop: i64 = tfy >> 2 // MUST match vc_enc_block_packed's unpack exactly
1874 let cx: i64 = bx*16
1875 let cy: i64 = by*16
1876 var bp: i64 = bp0
1877 mv[0] = 0; mv[1] = 0
1878 var bqx: i64 = 0
1879 var bqy: i64 = 0
1880 if keyframe == 0 {
1881 let doskip: i64 = nx_br_get(buf, bp, 1)
1882 bp = bp + 1
1883 if doskip == 1 {
1884 var cy0: i64 = 0
1885 while cy0 < 16 { var cx0: i64 = 0
1886 while cx0 < 16 { recon[(cy+cy0)*W + (cx+cx0)] = prev[(cy+cy0)*W + (cx+cx0)]; cx0 = cx0 + 1 } cy0 = cy0 + 1 }
1887 return bp
1888 }
1889 // vcv-8 INTRA-IN-P -- MUST mirror vc_enc_block_packed_e's mode-bit routing (bit8, luma-only) exactly, BEFORE the part bit.
1890 if (rctx as i64) != 0 { if (rctx[0] & 256) != 0 { if (rctx[0] & 16) == 0 {
1891 let imode: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
1892 if imode == 1 { return vc_dec_mb4r_intra(recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx) }
1893 } } }
1894 // vcv-7 P_8x8 MOTION PARTITION -- MUST mirror vc_enc_block_packed_e's part-bit routing (bit7, luma-only) exactly.
1895 if (rctx as i64) != 0 { if (rctx[0] & 128) != 0 { if (rctx[0] & 16) == 0 {
1896 let usepart: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
1897 if usepart == 1 { return vc_dec_mb_part8_inter(prev, recon, W, cx, cy, qp, buf, bp, rctx[4] as *i64, rctx) }
1898 } } }
1899 var mvd10d: i64 = 0
1900 if (rctx as i64) != 0 { if (rctx[0] & VC_MAGIC_8192) != 0 { mvd10d = 1 } }
1901 if mvd10d == 1 {
1902 // vcv-10 MVD twin: MUST mirror the encoder's median + golomb + plane chain EXACTLY. Plane is
1903 // set from the DECODED (pre-clamp) mv = the wire truth the encoder's plane carried.
1904 let mvp10: *i64 = rctx[9] as *i64
1905 let pxy10: *i64 = ((vc_t8p(rctx[4] as *i64, VC_T8_TE) as i64) + 48) as *i64
1906 let bpb10: *i64 = ((vc_t8p(rctx[4] as *i64, VC_T8_TE) as i64) + 64) as *i64
1907 vc_mvpred(mvp10, W/16, bx, pxy10)
1908 bpb10[0] = bp
1909 mv[0] = vc_gget(buf, bpb10) + pxy10[0]
1910 mv[1] = vc_gget(buf, bpb10) + pxy10[1]
1911 bp = bpb10[0]
1912 vc_mvplane_set(mvp10, W/16, bx, mv[0], mv[1])
1913 } else {
1914 mv[0] = ve_vval(buf, bp); bp = bp + ve_vlen(buf, bp)
1915 mv[1] = ve_vval(buf, bp); bp = bp + ve_vlen(buf, bp)
1916 }
1917 bqx = nx_br_get(buf, bp, 2); bp = bp + 2
1918 bqy = nx_br_get(buf, bp, 2); bp = bp + 2
1919 // DECODER ROBUSTNESS (rule 12: the wire is external input): a CORRUPTED motion vector must never
1920 // index prev out of bounds. qp_pixel reads prev[y*W+x] and the +1 quarter-pel taps, so the far
1921 // corner touches col cx+16+mv0 and row cy+16+mv1. Bound = W-16-cx / H-16-cy: this ALLOWS the valid
1922 // edge MV the encoder emits (rightmost interp tap lands at col W == the in-buffer chroma start, read
1923 // IDENTICALLY by enc + dec -> bit-exact, proven by xinst + t8noise), while a fuzzed/huge MV is
1924 // clamped into the YUV buffer (max read index W*(H+1) < W*H*3/2). Refuse-quality, never a trap.
1925 let mvxlo: i64 = 0 - cx
1926 let mvxhi: i64 = W - 16 - cx
1927 let mvylo: i64 = 0 - cy
1928 let mvyhi: i64 = H - 16 - cy
1929 if mv[0] < mvxlo { mv[0] = mvxlo }
1930 if mv[0] > mvxhi { mv[0] = mvxhi }
1931 if mv[1] < mvylo { mv[1] = mvylo }
1932 if mv[1] > mvyhi { mv[1] = mvyhi }
1933 }
1934 if t8 == 1 {
1935 // ---- 8x8 path: MUST mirror vc_enc_block_packed_e's routing exactly ----
1936 let t8c: *i64 = rctx[4] as *i64
1937 if keyframe == 1 { return vc_dec_mb8_intra(recon, W, cx, cy, ytop, qp, buf, bp, t8c, rctx) }
1938 return vc_dec_mb8_inter(prev, recon, W, cx, cy, qp, mv[0], mv[1], bqx, bqy, buf, bp, t8c, rctx)
1939 }
1940 if keyframe == 1 { if (rctx as i64) != 0 { if (rctx[0] & 8) != 0 { if (rctx[0] & 16) == 0 {
1941 // RICH-INTRA stream: MUST mirror the encoder's routing exactly (incl the bit4 chroma opt-out)
1942 return vc_dec_mb4r_intra(recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx)
1943 } } } }
1944 var sj: i64 = 0
1945 while sj < 4 {
1946 var si: i64 = 0
1947 while si < 4 {
1948 let sx: i64 = cx + si*4
1949 let sy: i64 = cy + sj*4
1950 if keyframe == 1 {
1951 // gather the SAME edge-substituted reconstructed neighbors as the encoder (raster order keeps them in sync)
1952 var t0: i64=128; var t1: i64=128; var t2: i64=128; var t3: i64=128
1953 var l0: i64=128; var l1: i64=128; var l2: i64=128; var l3: i64=128
1954 var corner: i64=128
1955 if sy > ytop { t0=recon[(sy-1)*W+sx] as i64; t1=recon[(sy-1)*W+sx+1] as i64; t2=recon[(sy-1)*W+sx+2] as i64; t3=recon[(sy-1)*W+sx+3] as i64 }
1956 if sx > 0 { l0=recon[sy*W+sx-1] as i64; l1=recon[(sy+1)*W+sx-1] as i64; l2=recon[(sy+2)*W+sx-1] as i64; l3=recon[(sy+3)*W+sx-1] as i64 }
1957 if sx > 0 { if sy > ytop { corner=recon[(sy-1)*W+sx-1] as i64 } }
1958 var dcsum: i64=0; var dccnt: i64=0
1959 if sy > ytop { dcsum=dcsum+t0+t1+t2+t3; dccnt=dccnt+4 }
1960 if sx > 0 { dcsum=dcsum+l0+l1+l2+l3; dccnt=dccnt+4 }
1961 var dc: i64=128; if dccnt > 0 { dc=dcsum/dccnt }
1962 // read the chosen mode THEN the residual (same order the encoder wrote them)
1963 let bestmode: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
1964 bp = vc_coeff_dec(buf, bp, qp, blk, tf, rctx)
1965 var cy2: i64=0
1966 while cy2 < 4 { var cx2: i64=0
1967 while cx2 < 4 {
1968 var v: i64=vc_pred_px(bestmode, cx2, cy2, t0,t1,t2,t3, l0,l1,l2,l3, corner, dc) + blk[cy2*4+cx2]
1969 if v < 0 { v=0 } if v > 255 { v=255 }
1970 recon[(sy+cy2)*W+sx+cx2]=v as u8
1971 cx2=cx2+1 } cy2=cy2+1 }
1972 } else {
1973 bp = vc_coeff_dec(buf, bp, qp, blk, tf, rctx)
1974 var yy: i64 = 0
1975 while yy < 4 {
1976 var xx: i64 = 0
1977 while xx < 4 {
1978 let pred: i64 = qp_pixel(prev, W, sx+xx+mv[0], sy+yy+mv[1], bqx, bqy)
1979 var v: i64 = pred + blk[yy*4 + xx]
1980 if v < 0 { v = 0 }
1981 if v > 255 { v = 255 }
1982 recon[(sy+yy)*W + (sx+xx)] = v as u8
1983 xx = xx + 1
1984 }
1985 yy = yy + 1
1986 }
1987 }
1988 si = si + 1
1989 }
1990 sj = sj + 1
1991 }
1992 return bp
1993}
1994// encode a whole frame into a transmittable stream (buf); reconstructs into recon; returns total bits.
1995func vc_enc_frame_packed(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64) -> i64 {
1996 return vc_enc_frame_packed_tf(cur, prev, recon, W, H, qp, keyframe, sad_thresh, buf, blk, mv, 0)
1997}
1998func vc_enc_frame_packed_tf(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64) -> i64 {
1999 var bp: i64 = nx_bw_put(buf, 0, keyframe, 1)
2000 let BW: i64 = W / 16
2001 let BH: i64 = H / 16
2002 var by: i64 = 0
2003 while by < BH { var bx: i64 = 0
2004 while bx < BW { let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)); bp = nx_bw_put(buf, bp, lv, 2); bp = vc_enc_block_packed(cur, prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, sad_thresh, buf, bp, blk, mv, tf); bx = bx + 1 } by = by + 1 }
2005 return bp
2006}
2007// decode a whole frame from the stream (buf) into recon using prev only; returns total bits consumed. The keyframe
2008// flag is read from the stream head; qp is a session parameter shared out of band.
2009func vc_dec_frame_packed(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64) -> i64 {
2010 return vc_dec_frame_packed_tf(prev, recon, W, H, qp, buf, blk, mv, 0)
2011}
2012func vc_dec_frame_packed_tf(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64) -> i64 {
2013 let keyframe: i64 = nx_br_get(buf, 0, 1)
2014 var bp: i64 = 1
2015 let BW: i64 = W / 16
2016 let BH: i64 = H / 16
2017 var by: i64 = 0
2018 while by < BH { var bx: i64 = 0
2019 while bx < BW { let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2; bp = vc_dec_block_packed(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, buf, bp, blk, mv, tf); bx = bx + 1 } by = by + 1 }
2020 return bp
2021}
2022// RANGE-CODED frame (task #31): two sections in buf -> [range_start:u16][CAVLC bits from bit16: keyframe +
2023// per-MB AQ-level/skip/MV/mode/bqx][range bytes: all coeff blocks]. rctx = i64[>=5] = [1, est, probs, rcbuf].
2024// CAVLC path is a SEPARATE function (vc_enc_frame_packed_tf) -> untouched -> zero regression. Returns bytes*8.
2025func vc_enc_frame_packed_rc(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2026 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2027 rc_enc_init(est)
2028 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } // seed ALL contexts (incl the flag-by-count buckets 24..31)
2029 var bp: i64 = nx_bw_put(buf, 16, keyframe, 1) // CAVLC starts at bit 16 (byte 2 reserved for range_start)
2030 let BW: i64 = W / 16; let BH: i64 = H / 16
2031 var by: i64 = 0
2032 while by < BH { var bx: i64 = 0
2033 while bx < BW { let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)); bp = nx_bw_put(buf, bp, lv, 2)
2034 bp = vc_enc_block_packed_e(cur, prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, sad_thresh, buf, bp, blk, mv, tf, rctx); bx = bx + 1 } by = by + 1 }
2035 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8)
2036 let cavlc_end: i64 = (bp + 7) / 8
2037 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8
2038 let rcbuf: *u8 = rctx[3] as *u8; var i: i64 = 0
2039 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 }
2040 return (cavlc_end + rbytes) * 8
2041}
2042func vc_dec_frame_packed_rc(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2043 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2044 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8)
2045 rctx[3] = (buf as i64) + cavlc_end // the block's coeff decoder reads the range section here
2046 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } // seed ALL contexts (incl the flag-by-count buckets 24..31)
2047 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8)
2048 let keyframe: i64 = nx_br_get(buf, 16, 1)
2049 var bp: i64 = 17
2050 let BW: i64 = W / 16; let BH: i64 = H / 16
2051 var by: i64 = 0
2052 while by < BH { var bx: i64 = 0
2053 while bx < BW { let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
2054 bp = vc_dec_block_packed_e(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, buf, bp, blk, mv, tf, rctx); bx = bx + 1 } by = by + 1 }
2055 return 0
2056}
2057// ---- PER-MB VARIABLE-TRANSFORM frames (task #46 rung 2). Stream = [keyframe:1] then per-MB raster
2058// [aq_level:2][t8:1][MB]. Encoder select: emode bit2 CLEAR = mad policy (t8 = aq_level<=1, the classifier
2059// the tsize RD gate validated); emode bit2 SET = RD-AUTO on inter MBs (vc_rd_t8_inter costs BOTH transforms
2060// on the real MC residual; keyframes keep the policy). The bit is EXPLICIT in the stream so either encoder
2061// produces a stream ANY t8 decoder reads -- decoders never see emode bit2.
2062// rctx = i64[>=6] = [emode, est, probs, rcbuf, t8c, t8bitpos]; emode here: 0=CAVLC, 4=CAVLC+auto (bit0
2063// MUST be clear -- est/probs/rcbuf unused); t8c = i64[VC_T8_SIZE] slab, vc_t8_init'd by the caller;
2064// t8bitpos is internal (frame fn -> block coder). The CAVLC/RC frame fns above are SEPARATE and
2065// untouched -> zero regression on every existing stream. ----
2066func vc_enc_frame_packed_t8(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2067 rctx[0] = rctx[0] | 8 // t8-stream syntax = RICH INTRA (9-mode MPM) on both block sizes, both sides
2068 rctx[0] = (rctx[0] | 4) - 4 // RD-auto (bit2) is INERT under the keyframes-only policy: strip it so the
2069 // block coder can never patch an un-reserved bit position (rctx[5] stale)
2070 var bp: i64 = nx_bw_put(buf, 0, keyframe, 1)
2071 bp = nx_bw_put(buf, bp, 0, 1) // nf bit (in-loop restoration): 0 placeholder; the vv layer patches it
2072 // on the LUMA stream only, after MEASURING a win vs the source
2073 let BW: i64 = W / 16
2074 let BH: i64 = H / 16
2075 var by: i64 = 0
2076 while by < BH { var bx: i64 = 0
2077 while bx < BW {
2078 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16))
2079 bp = nx_bw_put(buf, bp, lv, 2)
2080 var t8: i64 = 0
2081 if (rctx[0] & 16) == 0 { if keyframe == 1 {
2082 // t8 = KEYFRAMES ONLY (field 788, third round: P-frame 8x8 still read blocky at long GOP +
2083 // the t8 path cost fps on phones). Keyframes keep the PROVEN, large win (flat intra -52%
2084 // bytes = join/recovery cost) under the uniform-flatness guard; P frames ride the exact
2085 // legacy 4x4 residual path (byte-identical speed + structure). Chroma additionally stays
2086 // 4x4 (emode bit4, field round 1). RD-auto (bit2) is inert under this policy. All of this
2087 // is ENCODER POLICY -- the explicit per-MB bits keep every decoder compatible.
2088 if lv <= 1 { t8 = vc_mb_t8_ok(cur, W, bx*16, by*16) } // AUDIT: force-t8=1 measured IDENTICAL BD-rate -> gate is correctly tuned (8x8 fires where it helps; 8x8==4x4 on texture). Not a mis-tuned constant.
2089 } }
2090 bp = nx_bw_put(buf, bp, t8, 1)
2091 bp = vc_enc_block_packed_e(cur, prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, sad_thresh, buf, bp, blk, mv, tf + (t8 << 1), rctx)
2092 bx = bx + 1 } by = by + 1 }
2093 return bp
2094}
2095func vc_dec_frame_packed_t8(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2096 rctx[0] = rctx[0] | 8 // MUST match the encoder's syntax bit
2097 let keyframe: i64 = nx_br_get(buf, 0, 1)
2098 var bp: i64 = 2 // bit1 = nf flag (read by the vv layer; MB syntax starts after it)
2099 let BW: i64 = W / 16
2100 let BH: i64 = H / 16
2101 var by: i64 = 0
2102 while by < BH { var bx: i64 = 0
2103 while bx < BW {
2104 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
2105 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
2106 bp = vc_dec_block_packed_e(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, buf, bp, blk, mv, tf + (t8 << 1), rctx)
2107 bx = bx + 1 } by = by + 1 }
2108 return bp
2109}
2110// RANGE-CODED + variable-transform frame: the _rc two-section layout ([range_start:u16][CAVLC bits from
2111// bit16: keyframe + per-MB aq/t8/skip/MV/mode][range bytes: all coeff blocks, 4x4 AND 8x8 contexts]) with
2112// the per-MB t8 select. rctx = [1, est, probs, rcbuf, t8c]; probs sized >= RC_NCTX8 (24), seeded here.
2113// P2 HEAT-AQ (2026-07-12, MEASURED −1.72% avg BD-rate, akiyo −3.53/foreman −2.86, never-negative on the MSU
2114// grid): protect PERSISTENT content from drift -- once an MB's consecutive-skip streak reaches VC_HEAT_STREAK,
2115// halve its skip threshold so a drifting static block is re-coded sooner; the PSNR payback amortizes across the
2116// whole following streak. The CHURN direction (cheapening active MBs) measured +6.4% = REFUTED -- never do it.
2117// ENCODER-ONLY (no wire/syntax change, decoder-transparent). CONTRACT: emode bit12 (4096) = heat-AQ on AND the
2118// rctx block has a 9th slot: rctx[8] = heat-plane pointer (i64 per LUMA MB, caller-owned). Slot 8 is read ONLY
2119// under bit12, so every legacy 64-byte rctx block (gates, emitters, old clients) stays valid -- feature off by
2120// default. (rctx[6]/[7] are TAKEN: the trained-nf table + scratch -- a probe-invisible collision caught in port.)
2121// Skip detect = CAVLC bits for the MB <= VC_HEAT_SKIPBITS (coeffs ride the range section, so a skipped MB writes
2122// only its flag bits). Streaks reset on keyframes. Constants are MEASURED (sweep sn{4,8,12}xdiv{2,3}): 4/2 best.
2123const VC_HEAT_STREAK: i64 = 4
2124const VC_HEAT_DIV: i64 = 2
2125const VC_HEAT_SKIPBITS: i64 = 4
2126func vc_enc_frame_packed_rct8(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2127 rctx[0] = rctx[0] | 8 // t8-stream syntax = RICH INTRA (9-mode MPM) on both block sizes, both sides
2128 // RD-auto (bit2): HONORED for LUMA (emode 45 already requests it), STRIPPED for CHROMA (bit4 conservative
2129 // 4x4 plane). 803 debt-eat -- the keyframes-only t8 policy (field 788) was never RD-measured against the MSU
2130 // foundation and stripped the bit2 the caller asked for; on motion/detail P-frames (foreman/bus/mobile:
2131 // 55-92% coded MBs) forcing 4x4 leaves real bitrate on the table. The 8x8-inter path is FULLY BUILT on BOTH
2132 // sides (vc_enc_mb8_inter / vc_dec_mb8_inter) and the decoder already reads the t8 bit + routes P t8==1 -> so
2133 // per-MB RD 4x4-vs-8x8 selection is DECODER-TRANSPARENT (no vcv bump, works in every room like RDOQ). The
2134 // stale-rctx[5] hazard that motivated the old strip is fixed below: the frame fn records the t8-bit position
2135 // in rctx[5] per MB so the block coder's patch always lands on the reserved bit.
2136 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 }
2137 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2138 rc_enc_init(est)
2139 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2140 var bp: i64 = nx_bw_put(buf, 16, keyframe, 1) // CAVLC starts at bit 16 (byte 2 reserved for range_start)
2141 bp = nx_bw_put(buf, bp, 0, 1) // nf bit placeholder (see _t8; vv layer patches luma's)
2142 let BW: i64 = W / 16; let BH: i64 = H / 16
2143 var heatp: *i64 = 0 as *i64 // P2 heat plane: bit12-gated 9th slot (the vv layer clears bit12 for chroma)
2144 if (rctx[0] & VC_MAGIC_4096) != 0 { heatp = rctx[8] as *i64 }
2145 var by: i64 = 0
2146 while by < BH { var bx: i64 = 0
2147 while bx < BW {
2148 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16))
2149 bp = nx_bw_put(buf, bp, lv, 2)
2150 var t8: i64 = 0
2151 if (rctx[0] & 16) == 0 { if keyframe == 1 {
2152 // KEYFRAME t8: flat-intra RD gate (uniform-flatness guard) -- the PROVEN -52%-bytes win on
2153 // join/recovery. P-FRAME t8 is no longer forced off: once the MV is known the block coder's
2154 // RD-auto (bit2, luma) picks 4x4-vs-8x8 per MB and patches the placeholder at rctx[5]. Chroma
2155 // (bit4) stays 4x4 both frame types. Every per-MB t8 bit is explicit on the wire -> the decoder
2156 // already routes it (vc_dec_mb8_inter for P t8==1), so this is decoder-transparent (803).
2157 if lv <= 1 { t8 = vc_mb_t8_ok(cur, W, bx*16, by*16) }
2158 } }
2159 rctx[5] = bp // reserve the t8-bit position for the block coder's P-frame RD-auto patch (803)
2160 bp = nx_bw_put(buf, bp, t8, 1)
2161 let mi: i64 = by * BW + bx
2162 var th: i64 = sad_thresh
2163 if (heatp as i64) != 0 { if keyframe == 0 { if heatp[mi] >= VC_HEAT_STREAK { th = sad_thresh / VC_HEAT_DIV } } }
2164 let hbp0: i64 = bp
2165 bp = vc_enc_block_packed_e(cur, prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, th, buf, bp, blk, mv, tf + (t8 << 1), rctx)
2166 if (heatp as i64) != 0 {
2167 if keyframe == 1 { heatp[mi] = 0 } else {
2168 if bp - hbp0 <= VC_HEAT_SKIPBITS { heatp[mi] = heatp[mi] + 1 } else { heatp[mi] = 0 }
2169 }
2170 }
2171 bx = bx + 1 } by = by + 1 }
2172 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8)
2173 let cavlc_end: i64 = (bp + 7) / 8
2174 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8
2175 let rcbuf: *u8 = rctx[3] as *u8; var i: i64 = 0
2176 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 }
2177 return (cavlc_end + rbytes) * 8
2178}
2179// 824 RICH-BAND REGION pair (720p rung B): the FULL rct8 codec (rc + t8-RD + sig-map + partition + heat-AQ)
2180// over MB rows [by0,by1) as a SELF-CONTAINED section -- own rc_enc_init + probs reseed per band, so K bands
2181// are INDEPENDENT (tile-parallel across workers; the context reset costs a few % bits vs whole-frame --
2182// measured by the gate, it buys the ~4x encode wall-clock that unlocks 720p-class live). Intra never reads
2183// above the band top via the tfy ytop mechanism (same convention as the legacy region pair). Per-band wire =
2184// the whole-frame rct8 layout: [range_start:u16][CAVLC from bit16][range bytes]. Heat plane indexes the
2185// GLOBAL MB grid, so a worker that owns a stable band keeps valid streaks.
2186func vc_enc_frame_packed_rct8_region(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, by0: i64, by1: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2187 rctx[0] = rctx[0] | 8
2188 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 }
2189 let est: *i64 = rctx[1] as *i64
2190 let probs: *i64 = rctx[2] as *i64
2191 rc_enc_init(est)
2192 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2193 var bp: i64 = nx_bw_put(buf, 16, keyframe, 1)
2194 bp = nx_bw_put(buf, bp, 0, 1)
2195 let BW: i64 = W / 16
2196 var heatp: *i64 = 0 as *i64
2197 if (rctx[0] & VC_MAGIC_4096) != 0 { heatp = rctx[8] as *i64 }
2198 let ytop2: i64 = (by0 * 16) << 2
2199 var by: i64 = by0
2200 while by < by1 { var bx: i64 = 0
2201 while bx < BW {
2202 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16))
2203 bp = nx_bw_put(buf, bp, lv, 2)
2204 var t8: i64 = 0
2205 if (rctx[0] & 16) == 0 { if keyframe == 1 {
2206 if lv <= 1 { t8 = vc_mb_t8_ok(cur, W, bx*16, by*16) }
2207 } }
2208 rctx[5] = bp
2209 bp = nx_bw_put(buf, bp, t8, 1)
2210 let mi: i64 = by * BW + bx
2211 var th: i64 = sad_thresh
2212 if (heatp as i64) != 0 { if keyframe == 0 { if heatp[mi] >= VC_HEAT_STREAK { th = sad_thresh / VC_HEAT_DIV } } }
2213 let hbp0: i64 = bp
2214 bp = vc_enc_block_packed_e(cur, prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, th, buf, bp, blk, mv, tf + (t8 << 1) + ytop2, rctx)
2215 if (heatp as i64) != 0 {
2216 if keyframe == 1 { heatp[mi] = 0 } else {
2217 if bp - hbp0 <= VC_HEAT_SKIPBITS { heatp[mi] = heatp[mi] + 1 } else { heatp[mi] = 0 }
2218 }
2219 }
2220 bx = bx + 1 } by = by + 1 }
2221 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8)
2222 let cavlc_end: i64 = (bp + 7) / 8
2223 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8
2224 let rcbuf: *u8 = rctx[3] as *u8
2225 var i: i64 = 0
2226 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 }
2227 return (cavlc_end + rbytes) * 8
2228}
2229func vc_dec_frame_packed_rct8_region(prev: *u8, recon: *u8, W: i64, H: i64, by0: i64, by1: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2230 rctx[0] = rctx[0] | 8
2231 let est: *i64 = rctx[1] as *i64
2232 let probs: *i64 = rctx[2] as *i64
2233 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8)
2234 rctx[3] = (buf as i64) + cavlc_end
2235 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2236 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8)
2237 let keyframe: i64 = nx_br_get(buf, 16, 1)
2238 var bp: i64 = 18
2239 let BW: i64 = W / 16
2240 let ytop2: i64 = (by0 * 16) << 2
2241 var by: i64 = by0
2242 while by < by1 { var bx: i64 = 0
2243 while bx < BW {
2244 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
2245 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
2246 bp = vc_dec_block_packed_e(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, buf, bp, blk, mv, tf + (t8 << 1) + ytop2, rctx)
2247 bx = bx + 1 } by = by + 1 }
2248 return bp
2249}
2250func vc_dec_frame_packed_rct8(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2251 rctx[0] = rctx[0] | 8 // MUST match the encoder's syntax bit
2252 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2253 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8)
2254 rctx[3] = (buf as i64) + cavlc_end // the block's coeff decoder reads the range section here
2255 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2256 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8)
2257 let keyframe: i64 = nx_br_get(buf, 16, 1)
2258 var bp: i64 = 18 // bit17 = nf flag (read by the vv layer)
2259 let BW: i64 = W / 16; let BH: i64 = H / 16
2260 var by: i64 = 0
2261 while by < BH { var bx: i64 = 0
2262 while bx < BW {
2263 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
2264 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
2265 bp = vc_dec_block_packed_e(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, buf, bp, blk, mv, tf + (t8 << 1), rctx)
2266 bx = bx + 1 } by = by + 1 }
2267 return 0
2268}
2269// ---- B-FRAME pair (vcv-9 VOD generation; 2026-07-14) -----------------------------------------------------
2270// Bidirectional frame = the measured -43%-residual structural lever (nx_vcodec_bframe_ceiling: past-only SAD
2271// 1102199 -> best-of-{past,future} 623502; naive bi-AVERAGE only -17% -- the win is per-MB DIRECTION SELECTION
2272// on reveal/occlusion, so that is exactly what this codes). Design: ONE direction bit per MB choosing which
2273// reference the ENTIRE existing P-MB coder runs against -- skip/intra-in-P/partition/MV/qpel/t8/sig-map/RDOQ
2274// are all inherited unchanged via the ref pointer, so the B syntax is [lv:2][t8:1][dir:1][P-MB syntax]. A
2275// B-frame is DISPOSABLE (never a reference -> no drift contribution, anchors chain exactly as today's P) and
2276// never a keyframe (no nf). Wire framing identical to rct8 ([range_start:u16][CAVLC@bit16][range section]).
2277// VOD/archival profile: the future ref costs one anchor of latency -- the RTC path never calls these.
2278func vc_enc_frame_packed_b(cur: *u8, past: *u8, fut: *u8, recon: *u8, W: i64, H: i64, qp: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2279 rctx[0] = rctx[0] | 8
2280 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 }
2281 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2282 rc_enc_init(est)
2283 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2284 var bp: i64 = nx_bw_put(buf, 16, 0, 1) // keyframe=0: a B-frame is never key
2285 bp = nx_bw_put(buf, bp, 0, 1) // nf bit stays 0 (nf is keyframe-only)
2286 let BW: i64 = W / 16; let BH: i64 = H / 16
2287 var by: i64 = 0
2288 while by < BH { var bx: i64 = 0
2289 while bx < BW {
2290 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16))
2291 bp = nx_bw_put(buf, bp, lv, 2)
2292 rctx[5] = bp // reserve the t8-bit position (RD-auto patch, same as rct8 P)
2293 bp = nx_bw_put(buf, bp, 0, 1)
2294 // DIRECTION: integer-ME vs both refs, pick the smaller residual = the measured -43% selector
2295 let sp: i64 = vm_search_q(cur, past, W, H, bx, by, 16, VC_ME_R, mv, qp, blk)
2296 let sf: i64 = vm_search_q(cur, fut, W, H, bx, by, 16, VC_ME_R, mv, qp, blk)
2297 var dir: i64 = 0
2298 if sf < sp { dir = 1 }
2299 bp = nx_bw_put(buf, bp, dir, 1)
2300 var ref: *u8 = past
2301 if dir == 1 { ref = fut }
2302 bp = vc_enc_block_packed_e(cur, ref, recon, W, H, bx, by, vc_aq_qp(qp, lv), 0, sad_thresh, buf, bp, blk, mv, tf, rctx)
2303 bx = bx + 1 } by = by + 1 }
2304 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8)
2305 let cavlc_end: i64 = (bp + 7) / 8
2306 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8
2307 let rcbuf: *u8 = rctx[3] as *u8; var i: i64 = 0
2308 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 }
2309 return (cavlc_end + rbytes) * 8
2310}
2311func vc_dec_frame_packed_b(past: *u8, fut: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2312 rctx[0] = rctx[0] | 8 // MUST match the encoder's syntax bit
2313 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2314 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8)
2315 rctx[3] = (buf as i64) + cavlc_end
2316 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2317 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8)
2318 var bp: i64 = 18 // bit16 keyframe(0) + bit17 nf placeholder
2319 let BW: i64 = W / 16; let BH: i64 = H / 16
2320 var by: i64 = 0
2321 while by < BH { var bx: i64 = 0
2322 while bx < BW {
2323 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
2324 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
2325 let dir: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
2326 var ref: *u8 = past
2327 if dir == 1 { ref = fut }
2328 bp = vc_dec_block_packed_e(ref, recon, W, H, bx, by, vc_aq_qp(qp, lv), 0, buf, bp, blk, mv, tf + (t8 << 1), rctx)
2329 bx = bx + 1 } by = by + 1 }
2330 return 0
2331}
2332// ---- rct9 LEAN-SKIP syntax (vcv-10 candidate; 2026-07-14) ------------------------------------------------
2333// MEASURED (nx_vcodec_mvbits_probe wire decomposition): the per-MB CAVLC header [lv:2][t8:1][skip:1] costs
2334// 4 bits on EVERY MB even when skipped -- ~2240 skip MBs/frame x 4 bits ~= 1.1KB/frame ~= 8-13% of P bytes
2335// (worst at LOW bitrate = the external-gap shape), and ~94% of a typical chroma stream. x264 pays ~0.2 bits
2336// per skip via a CABAC context. rct9 P-MB layout: ONE rc-context-coded skip flag (ctx = left_skip+top_skip,
2337// probs[24..26] adaptive, on TOP of the RC_NCTX8 residual contexts); skip => recon copy, NOTHING else on the
2338// wire; coded => [lv:2][t8:1] + the UNCHANGED block payload (still leads with its vestigial in-payload skip
2339// bit, forced 0 via sad_thresh=0 -- 1 bit x coded MBs only, vs forking the 300-line block coder). The RD-skip
2340// band trial (emode bit11) moves HERE: est/probs/bp snapshot -> trial-code -> J -> commit/rewind, the exact
2341// _e idiom on the same 48-i64 scr slab (16 est + 24+3 probs = 43 <= 48). Keyframes stay plain rct8 (nothing
2342// to lean out). ⚠ship note: skip-row scratch is sys_mmap here (bench-native); the wasm build needs a slab.
2343const VC_SKIPCTX: i64 = 24
2344func vc_mbcopy(recon: *u8, prev: *u8, W: i64, cx: i64, cy: i64) -> i64 {
2345 var y: i64 = 0
2346 while y < 16 { var x: i64 = 0
2347 while x < 16 { recon[(cy+y)*W + cx+x] = prev[(cy+y)*W + cx+x]; x = x + 1 } y = y + 1 }
2348 return 0 }
2349func vc_mbssd(a: *u8, b: *u8, W: i64, cx: i64, cy: i64) -> i64 {
2350 var s: i64 = 0
2351 var y: i64 = 0
2352 while y < 16 { var x: i64 = 0
2353 while x < 16 { let d: i64 = (a[(cy+y)*W + cx+x] as i64) - (b[(cy+y)*W + cx+x] as i64); s = s + d*d; x = x + 1 } y = y + 1 }
2354 return s }
2355func vc_enc_frame_packed_rct9(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2356 rctx[0] = rctx[0] | 8
2357 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 }
2358 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2359 rc_enc_init(est)
2360 var ci: i64 = 0; while ci < RC_NCTX8 + 3 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2361 var bp: i64 = nx_bw_put(buf, 16, 0, 1) // keyframe=0 always (keys ride rct8)
2362 bp = nx_bw_put(buf, bp, 0, 1) // nf placeholder (never set: non-key)
2363 let BW: i64 = W / 16; let BH: i64 = H / 16
2364 // top-neighbour skip row: u8 slab at rctx[4]+5440 (past RD-skip scr 5008..5392 + dmv 5392..5408; the
2365 // wasm t8c region ends ~5504 -> ENVELOPE BW<=60 i.e. W<=960, DECLARED; wasm ceiling is 640 -> 40B used).
2366 // NEVER sys_mmap in frame code: wasm sys_mmap is a 0-stub -> the pointer aliases address 0 (the live
2367 // partition-MV zeroing bug class). Slab is dirty -> explicit zero (mmap's zero-init did this before).
2368 let sktop: *u8 = (rctx[4] + VC_MAGIC_5440) as *u8
2369 var zk: i64 = 0
2370 while zk < BW { sktop[zk] = 0 as u8; zk = zk + 1 }
2371 // vcv-10 MVD-median: arm bit13 + reset the caller-provided MV row-plane (rctx[9], REQUIRED for rct9)
2372 rctx[0] = rctx[0] | VC_MAGIC_8192
2373 vc_mvplane_row0(rctx[9] as *i64, BW)
2374 let rdsk: i64 = (rctx[0] >> 11) & 1
2375 let scr: *i64 = (rctx[4] + VC_MAGIC_5008) as *i64
2376 let rcbuf: *u8 = rctx[3] as *u8
2377 var by: i64 = 0
2378 while by < BH { var bx: i64 = 0
2379 var skleft: i64 = 0
2380 while bx < BW {
2381 let cx: i64 = bx*16; let cy: i64 = by*16
2382 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, cx, cy))
2383 let aqp: i64 = vc_aq_qp(qp, lv)
2384 let zs: i64 = vm_sad_zero(cur, prev, W, bx, by, 16)
2385 let ctx: i64 = VC_SKIPCTX + skleft + (sktop[bx] as i64)
2386 var dosk: i64 = 0
2387 var trial: i64 = 0
2388 if rdsk == 1 { if zs >= sad_thresh/4 { if zs <= sad_thresh*8 { trial = 1 } } }
2389 if trial == 0 { if zs <= sad_thresh { dosk = 1 } }
2390 var committed: i64 = 0
2391 if trial == 1 {
2392 var i: i64 = 0
2393 while i < 8 { scr[i] = est[i]; i = i + 1 }
2394 i = 0
2395 while i < RC_NCTX8 + 3 { scr[16 + i] = probs[i]; i = i + 1 }
2396 let r5: i64 = rctx[5]
2397 let rc0: i64 = vc_rdskip_len(est, scr, rcbuf)
2398 rc_enc_ctx(est, rcbuf, probs, ctx, 0) // CODE arm: skip=0
2399 var bpt: i64 = nx_bw_put(buf, bp, lv, 2)
2400 rctx[5] = bpt
2401 bpt = nx_bw_put(buf, bpt, 0, 1)
2402 bpt = vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, aqp, 0, 0 - sad_thresh, buf, bpt, blk, mv, tf, rctx)
2403 let rc1: i64 = vc_rdskip_len(est, scr, rcbuf)
2404 let dcode: i64 = vc_mbssd(recon, cur, W, cx, cy)
2405 let dskip: i64 = vc_mbssd(prev, cur, W, cx, cy)
2406 let jc: i64 = 32*dcode + qp*qp*((bpt - bp) + (rc1 - rc0))
2407 let js: i64 = 32*dskip + qp*qp
2408 if jc < js {
2409 bp = bpt; skleft = 0; sktop[bx] = 0 as u8; committed = 1
2410 } else {
2411 i = 0
2412 while i < 8 { est[i] = scr[i]; i = i + 1 }
2413 i = 0
2414 while i < RC_NCTX8 + 3 { probs[i] = scr[16 + i]; i = i + 1 }
2415 rctx[5] = r5
2416 // undo the trial CODE arm's MV-plane write (this MB ends SKIP = contributes (0,0));
2417 // without this the encoder plane diverges from the decoder's -> wire corruption
2418 let mvpu: *i64 = rctx[9] as *i64
2419 mvpu[BW + bx] = VC_MVPACK0
2420 dosk = 1
2421 }
2422 }
2423 if committed == 0 {
2424 if dosk == 1 {
2425 rc_enc_ctx(est, rcbuf, probs, ctx, 1) // skip: ONE context-coded flag, nothing else
2426 vc_mbcopy(recon, prev, W, cx, cy)
2427 skleft = 1; sktop[bx] = 1 as u8
2428 } else {
2429 rc_enc_ctx(est, rcbuf, probs, ctx, 0)
2430 bp = nx_bw_put(buf, bp, lv, 2)
2431 rctx[5] = bp
2432 bp = nx_bw_put(buf, bp, 0, 1)
2433 bp = vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, aqp, 0, 0 - sad_thresh, buf, bp, blk, mv, tf, rctx)
2434 skleft = 0; sktop[bx] = 0 as u8
2435 }
2436 }
2437 bx = bx + 1 }
2438 vc_mvplane_nextrow(rctx[9] as *i64, BW)
2439 by = by + 1 }
2440 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8)
2441 let cavlc_end: i64 = (bp + 7) / 8
2442 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8
2443 let rcb2: *u8 = rctx[3] as *u8; var k: i64 = 0
2444 while k < rbytes { buf[cavlc_end + k] = rcb2[k]; k = k + 1 }
2445 return (cavlc_end + rbytes) * 8
2446}
2447func vc_dec_frame_packed_rct9(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64, rctx: *i64) -> i64 {
2448 rctx[0] = rctx[0] | 8
2449 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64
2450 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8)
2451 let rsec: *u8 = ((buf as i64) + cavlc_end) as *u8
2452 rctx[3] = rsec as i64
2453 var ci: i64 = 0; while ci < RC_NCTX8 + 3 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 }
2454 rc_dec_init(est, rsec)
2455 var bp: i64 = 18
2456 let BW: i64 = W / 16; let BH: i64 = H / 16
2457 // u8 slab, same placement + envelope as the encoder (MUST mirror: the skip contexts are syntax)
2458 let sktop: *u8 = (rctx[4] + VC_MAGIC_5440) as *u8
2459 var zk: i64 = 0
2460 while zk < BW { sktop[zk] = 0 as u8; zk = zk + 1 }
2461 // vcv-10 MVD-median twin: arm bit13 + reset the MV row-plane (rctx[9], REQUIRED for rct9)
2462 rctx[0] = rctx[0] | VC_MAGIC_8192
2463 vc_mvplane_row0(rctx[9] as *i64, BW)
2464 var by: i64 = 0
2465 while by < BH { var bx: i64 = 0
2466 var skleft: i64 = 0
2467 while bx < BW {
2468 let ctx: i64 = VC_SKIPCTX + skleft + (sktop[bx] as i64)
2469 let sk: i64 = rc_dec_ctx(est, rsec, probs, ctx)
2470 if sk == 1 {
2471 vc_mbcopy(recon, prev, W, bx*16, by*16)
2472 skleft = 1; sktop[bx] = 1 as u8
2473 } else {
2474 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2
2475 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1
2476 bp = vc_dec_block_packed_e(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), 0, buf, bp, blk, mv, tf + (t8 << 1), rctx)
2477 skleft = 0; sktop[bx] = 0 as u8
2478 }
2479 bx = bx + 1 }
2480 vc_mvplane_nextrow(rctx[9] as *i64, BW)
2481 by = by + 1 }
2482 return 0
2483}
2484// ---- TILE-PARALLEL primitive (task #47 rung 1) ----------------------------------------------------------
2485// Encode/decode ONLY macroblock-rows [by0, by1) as a SELF-CONTAINED tile: intra prediction is clamped so it
2486// never reads above by0 (the tfy pack carries the tile top), and motion reads the full PREV frame (already
2487// reconstructed + available on both sides). So K calls over disjoint row-ranges have ZERO shared writes and
2488// ZERO cross-tile reads of the CURRENT frame -> each runs on its own core/thread now, its own GPU workgroup
2489// later. This is the architecture that scales toward 4K@60 (a serial frame loop never can).
2490func vc_enc_frame_packed_region(cur: *u8, prev: *u8, recon: *u8, W: i64, H: i64, by0: i64, by1: i64, qp: i64, keyframe: i64, sad_thresh: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64) -> i64 {
2491 var bp: i64 = nx_bw_put(buf, 0, keyframe, 1)
2492 let BW: i64 = W / 16
2493 let tfy: i64 = tf + ((by0 * 16) << 2) // bit1 (t8) stays 0: bands stay 4x4 until the t8 rung proves out there
2494 var by: i64 = by0
2495 while by < by1 { var bx: i64 = 0
2496 while bx < BW { let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)); bp = nx_bw_put(buf, bp, lv, 2); bp = vc_enc_block_packed(cur, prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, sad_thresh, buf, bp, blk, mv, tfy); bx = bx + 1 } by = by + 1 }
2497 return bp
2498}
2499func vc_dec_frame_packed_region(prev: *u8, recon: *u8, W: i64, H: i64, by0: i64, by1: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64) -> i64 {
2500 let keyframe: i64 = nx_br_get(buf, 0, 1)
2501 var bp: i64 = 1
2502 let BW: i64 = W / 16
2503 let tfy: i64 = tf + ((by0 * 16) << 2) // bit1 (t8) stays 0: bands stay 4x4 until the t8 rung proves out there
2504 var by: i64 = by0
2505 while by < by1 { var bx: i64 = 0
2506 while bx < BW { let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2; bp = vc_dec_block_packed(prev, recon, W, H, bx, by, vc_aq_qp(qp, lv), keyframe, buf, bp, blk, mv, tfy); bx = bx + 1 } by = by + 1 }
2507 return bp
2508}