code wiki / (root) / nx_vcodec.nx

nx_vcodec.nx source

↩ module page · 2476 lines · 150261 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// TE-scratch HANDBACK SLOTS (F1112, vc_rd_part_inter -> vc_enc_block_packed_i): the partition trial's 1001// 16x16 search result rides the caller-owned TE region it already uses for mv/bq work. Slot units are 1002// i64 indices into the TE base. Slots 2,3 = bq; 4,5 = the dormant _rc variant's jout; pxy10/bpb10 live 1003// at byte offsets +48/+64 (slots 6,8) by the decoder-shared vcv-10 convention -- do not collide. 1004const VC_TE_H16_MV0: i64 = 0 // 16x16 argmin dx (restored around the quadrant trial) 1005const VC_TE_H16_MV1: i64 = 1 // 16x16 argmin dy 1006const VC_TE_H16_SAD: i64 = 4 // 16x16 integer-search SAD 1007func vc_mvplane_row0(mvp: *i64, BW: i64) -> i64 { 1008 var i: i64 = 0 1009 while i < BW*2 { mvp[i] = VC_MVPACK0; i = i + 1 } 1010 return 0 1011} 1012func vc_mvplane_nextrow(mvp: *i64, BW: i64) -> i64 { 1013 var i: i64 = 0 1014 while i < BW { mvp[i] = mvp[BW + i]; mvp[BW + i] = VC_MVPACK0; i = i + 1 } 1015 return 0 1016} 1017func vc_mvmed3(a: i64, b: i64, c: i64) -> i64 { 1018 var lo: i64 = a; if b < lo { lo = b } if c < lo { lo = c } 1019 var hi: i64 = a; if b > hi { hi = b } if c > hi { hi = c } 1020 return a + b + c - lo - hi 1021} 1022// component-wise median of {left(cur row), top, top-right} for MB column bx -> pxy[0..1]; edges see the 1023// preset (0,0) entries (H.263-era median prediction lineage, pre-2000, patent-free). 1024func vc_mvpred(mvp: *i64, BW: i64, bx: i64, pxy: *i64) -> i64 { 1025 var lx: i64 = 0 1026 var ly: i64 = 0 1027 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 } 1028 let pt: i64 = mvp[bx] 1029 let tx: i64 = pt/VC_MAGIC_8192 - VC_MAGIC_4096 1030 let ty: i64 = pt%VC_MAGIC_8192 - VC_MAGIC_4096 1031 var rx: i64 = 0 1032 var ry: i64 = 0 1033 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 } 1034 pxy[0] = vc_mvmed3(lx, tx, rx) 1035 pxy[1] = vc_mvmed3(ly, ty, ry) 1036 return 0 1037} 1038func vc_mvplane_set(mvp: *i64, BW: i64, bx: i64, mvx: i64, mvy: i64) -> i64 { 1039 mvp[BW + bx] = (mvx + VC_MAGIC_4096)*VC_MAGIC_8192 + (mvy + VC_MAGIC_4096) 1040 return 0 1041} 1042// vcv-8 INTRA-IN-P decision estimate: SAD of the 16x16 MB vs a DC prediction from its already-reconstructed top 1043// row + left col (raster order guarantees they exist for an interior MB). This is a PESSIMISTIC lower bound on 1044// what real 9-mode intra achieves, so intra is chosen only when even flat DC beats the best inter -> a safe gate. 1045// Encoder-only (the explicit mode bit makes the decoder oblivious to how we decided). frame edge -> dc=128. 1046func vc_intra_dc_sad(cur: *u8, recon: *u8, W: i64, cx: i64, cy: i64) -> i64 { 1047 var sum: i64 = 0; var cnt: i64 = 0 1048 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 } } 1049 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 } } 1050 var dc: i64 = 128 1051 if cnt > 0 { dc = sum / cnt } 1052 var sad: i64 = 0; var y: i64 = 0 1053 while y < 16 { var x: i64 = 0 1054 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 } 1055 return sad 1056} 1057// integer search (T=8) + quarter-pel refine for ONE 8x8 block at (sx,sy); fills mv[0..1] (integer) + bq[0..1] 1058// (quarter-pel frac 0..3); returns the refined SAD. Mirrors the 16x16 path's refine, scoped to 8x8. 1059func vc_me8(cur: *u8, prev: *u8, W: i64, H: i64, sx: i64, sy: i64, mv: *i64, bq: *i64, qp: i64, scr3: *i64) -> i64 { 1060 vm_search_q(cur, prev, W, H, sx/8, sy/8, 8, VC_ME_R, mv, qp, scr3) 1061 let px: i64 = sx + mv[0]; let py: i64 = sy + mv[1] 1062 var bestsad: i64 = VC_MAGIC_2147483647; var bx4: i64 = 0; var by4: i64 = 0 1063 var tqy: i64 = 0 1064 while tqy <= 3 { 1065 var tqx: i64 = 0 1066 while tqx <= 3 { 1067 var ok: i64 = 1 1068 if tqx > 0 { if px + 8 >= W { ok = 0 } } 1069 if tqy > 0 { if py + 8 >= H { ok = 0 } } 1070 if ok == 1 { 1071 var sad: i64 = 0; var yy: i64 = 0 1072 while yy < 8 { var xx: i64 = 0 1073 while xx < 8 { 1074 let d: i64 = (cur[(sy+yy)*W + (sx+xx)] as i64) - qp_pixel(prev, W, px+xx, py+yy, tqx, tqy) 1075 if d < 0 { sad = sad - d } else { sad = sad + d } 1076 xx = xx + 1 } yy = yy + 1 } 1077 if sad < bestsad { bestsad = sad; bx4 = tqx; by4 = tqy } 1078 } 1079 tqx = tqx + 1 } 1080 tqy = tqy + 1 } 1081 bq[0] = bx4; bq[1] = by4 1082 return bestsad 1083} 1084// DECISION EARLY-OUTS (2026-07-12, encoder-only speed heuristics -- decoder-transparent; the wire carries 1085// explicit bits either way). The per-CODED-MB decision stack (partition-RD = 5 motion searches + the t8 1086// transform trial) measured ~0.3ms/MB = the HD-band wall (81ms = 12.3fps at 1152x640 K=4) AND most of the 1087// RTC trial cost (143->119fps). Both gates are qp-SCALED on the same ladder as the proven thresholds 1088// (skip band = qp*30, real translation = qp*188): a decision is only WORTH TRIALING when the 16x16 residual 1089// says it could change the outcome. Partition pays only when ONE 16x16 MV fails (high refined SAD); the 1090// transform choice only matters when there is real residual energy. MEASURED (MSU 4-seq, emitter 4781): 1091// BD-rate cost of the gates ~0 (see roadmap cont.25) for a 1.5-2x decision-stack cut. 1092// CALIBRATION (measured): first-try T=90/60 cost +4.53% avg BD-rate (bus +8.12 -- partition matters on real 1093// motion; akiyo +3.55 -- the 8x8 trial matters on smooth content) = the gates fired inside decision-relevant 1094// territory. The principled band is BELOW THE SKIP THRESHOLD (qp*30): a block coded with refined SAD under it 1095// only exists via heat-protection (halved threshold) and is near-skip -- decisions provably marginal there. 1096// F618 SESSION NOTE (2026-07-20): this block MOVED here from below (was after the heat consts, lines ~1900-1913) 1097// because BOTH readers (vc_rd_part_inter, vc_enc_mb_t8auto path) sat ABOVE the declarations -- the pre-diagnostic 1098// compiler silently read 0 for both (fwd-const miscompile class), so these early-outs were DEAD in every binary 1099// built since 2026-07-12 incl the shipped wasm. Moving them arms the DESIGNED, measured (~0 BD) behavior. 1100const VC_EO_PART: i64 = 30 // skip partition evaluation when refined-16x16-adjacent SAD < qp*30 1101const VC_EO_T8: i64 = 20 // skip the transform trial (default 4x4) when refined 16x16 SAD < qp*20 1102// RD decide 16x16-single-MV vs 4x-8x8-partition (encoder-only; the explicit part bit makes the decoder oblivious). 1103// SAD-domain Lagrangian J = SAD + lambda*mvbits with lambda = qp (the quantizer step = the SAD-per-bit RD slope, 1104// same qp-scaling as the deadzone; the one RD knob, to be BD-rate-verified). Partition wins only when its residual 1105// drop beats its extra MV cost. Returns 1 = partition. 1106func vc_rd_part_inter(cur: *u8, prev: *u8, W: i64, H: i64, cx: i64, cy: i64, qp: i64, scr: *i64) -> i64 { 1107 // scr = caller scratch (>= 4 i64; the slab's intra-only TE region). Was 2x sys_mmap(32) -- in the WASM 1108 // build sys_mmap is a 0-stub (TODO opcode), so mv and bq ALIASED at address 0 and the mv-cost side of 1109 // this J read qpel values (partition-favoring skew, live since 810). Same fix family as enc_mb_part8. 1110 let mv: *i64 = scr 1111 let bq: *i64 = ((scr as i64) + 16) as *i64 1112 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) 1113 // F1112 RESULT HANDBACK (encoder-only): the caller used to re-run this EXACT search (same refs, same 1114 // window, same qp; cx/16==bx by construction, and priming is result-inert by proof) on every rejected 1115 // trial -- pure duplicate work on the hottest path. CONTRACT: return 0 => scr[0..1] = the 16x16 argmin 1116 // MV (restored around the quadrant trial, which reuses the slots) and scr[4] = its SAD. 1117 scr[VC_TE_H16_SAD] = sad16 1118 // EARLY-OUT: partition only pays when ONE 16x16 MV FAILS the block (quadrants moving differently -> high 1119 // 16x16 SAD). A well-explained block skips the 4x vc_me8 sub-searches = the dominant decision-stack cost. 1120 if sad16 < qp * VC_EO_PART { return 0 } 1121 let j16: i64 = sad16 + qp * (vc_mvcost(mv[0]) + vc_mvcost(mv[1]) + 4) 1122 let m160: i64 = mv[VC_TE_H16_MV0] 1123 let m161: i64 = mv[VC_TE_H16_MV1] 1124 var sadp: i64 = 0; var mvbp: i64 = 0 1125 var pmv0: i64 = 0; var pmv1: i64 = 0 // same running-predictor cost model the partition encoder uses 1126 var sj: i64 = 0 1127 while sj < 2 { var si: i64 = 0 1128 while si < 2 { 1129 let s: i64 = vc_me8(cur, prev, W, H, cx+si*8, cy+sj*8, mv, bq, qp, ((scr as i64) + 40) as *i64) 1130 sadp = sadp + s; mvbp = mvbp + vc_mvcost(mv[0]-pmv0) + vc_mvcost(mv[1]-pmv1) + 4 1131 pmv0 = mv[0]; pmv1 = mv[1] 1132 si = si + 1 } sj = sj + 1 } 1133 let jpart: i64 = sadp + qp * mvbp 1134 if jpart < j16 { return 1 } 1135 mv[VC_TE_H16_MV0] = m160 1136 mv[VC_TE_H16_MV1] = m161 1137 return 0 1138} 1139// encode a luma P-MB as 4 independent 8x8 partitions. Per quadrant: search its own MV, code MV (ve_vput) + qpel 1140// (2+2 bits) into CAVLC, code the 8x8 residual via vc_enc_sub8 (range/sig-map), reconstruct. Mirrors vc_enc_mb8_inter 1141// but with a distinct MV per 8x8 instead of one shared MV. 1142func 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 { 1143 var bp: i64 = bp0 1144 let work: *i64 = vc_t8p(t8c, VC_T8_WORK) 1145 // ⚠LIVE-BUG FIX (2026-07-12, found porting P3b): these were sys_mmap(32) each -- but in the WASM build 1146 // sys_mmap is a 0-STUB, so mv and bq both pointed at address 0 and vc_me8's bq write (LAST) STOMPED the 1147 // searched MV before ve_vput coded it. The browser encoder shipped partition MVs of (0..3,0..3) qpel-only 1148 // = near-zero motion (self-consistent recon + wire, so bit-exact/drift-green -- just silently worse RD on 1149 // motion content; the native gates, with a real mmap, never saw it). Scratch now rides the slab's 1150 // intra-only TE region (free during inter) -- real memory in BOTH builds, and no per-MB mmap. 1151 let mv: *i64 = vc_t8p(t8c, VC_T8_TE) 1152 let bq: *i64 = ((vc_t8p(t8c, VC_T8_TE) as i64) + 16) as *i64 1153 var pmv0: i64 = 0; var pmv1: i64 = 0 // running MV predictor (prev quadrant); 4 quadrants of an MB share motion 1154 var sj: i64 = 0 1155 while sj < 2 { var si: i64 = 0 1156 while si < 2 { 1157 let sx: i64 = cx + si*8; let sy: i64 = cy + sj*8 1158 vc_me8(cur, prev, W, H, sx, sy, mv, bq, qp, ((vc_t8p(t8c, VC_T8_TE) as i64) + 40) as *i64) 1159 bp = ve_vput(buf, bp, mv[0]-pmv0); bp = ve_vput(buf, bp, mv[1]-pmv1) // differential MV (H.264-style) 1160 pmv0 = mv[0]; pmv1 = mv[1] 1161 bp = nx_bw_put(buf, bp, bq[0], 2); bp = nx_bw_put(buf, bp, bq[1], 2) 1162 var yy: i64 = 0 1163 while yy < 8 { var xx: i64 = 0 1164 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 } 1165 bp = vc_enc_sub8(t8c, qp, buf, bp, rctx) 1166 yy = 0 1167 while yy < 8 { var xx: i64 = 0 1168 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 } 1169 si = si + 1 } sj = sj + 1 } 1170 return bp 1171} 1172// decode mirror of vc_enc_mb_part8_inter: per quadrant read MV+qpel, decode 8x8 residual, reconstruct. 1173func 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 { 1174 var bp: i64 = bp0 1175 let work: *i64 = vc_t8p(t8c, VC_T8_WORK) 1176 var pmv0: i64 = 0; var pmv1: i64 = 0 // running MV predictor -- MUST mirror the encoder's chain exactly 1177 var sj: i64 = 0 1178 while sj < 2 { var si: i64 = 0 1179 while si < 2 { 1180 let sx: i64 = cx + si*8; let sy: i64 = cy + sj*8 1181 let mv0: i64 = ve_vval(buf, bp) + pmv0; bp = bp + ve_vlen(buf, bp) 1182 let mv1: i64 = ve_vval(buf, bp) + pmv1; bp = bp + ve_vlen(buf, bp) 1183 pmv0 = mv0; pmv1 = mv1 1184 let bqx: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 1185 let bqy: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 1186 bp = vc_dec_sub8(buf, bp, qp, t8c, rctx) 1187 var yy: i64 = 0 1188 while yy < 8 { var xx: i64 = 0 1189 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 } 1190 si = si + 1 } sj = sj + 1 } 1191 return bp 1192} 1193 1194// ---- RD TRANSFORM-SIZE SELECT for an INTER MB (encoder-only; the explicit t8 bit makes the decoder 1195// oblivious). The mad-of-SOURCE policy classifies the source, but a P-frame codes the RESIDUAL, whose 1196// character differs (motion mismatch / quant noise). So: build the actual MC residual once, cost BOTH 1197// transforms on it via the exact CAVLC bit counters + reconstruction SSE, pick the lower J. Lagrangian: 1198// J = 32*SSE + q*q*bits <=> SSE + bits*lambda with lambda = q^2/32 = (s^2)/2 for our deadzone step 1199// s = q/4 -- the classic ~0.5-0.85*Qstep^2 RD slope, integer-exact, derived from the step (no free knob). 1200// Uses RES16 for the residual, SCR[0..15] for the 4x4 trial, WORK/FREQ for the 8x8 trial. Returns 1 = 8x8. 1201// P3 (2026-07-12): the trial is now BYTE-FAITHFUL to the real emit paths on both axes -- (a) LEVELS: the 4x4 1202// arm quantizes via vt2_quant_rdoq and the 8x8 arm via vc_quant8+vc_rdoq8, exactly like vc_enc_sub_sig / 1203// vc_enc_sub8 (the old trial used plain quant = wrong levels under RDOQ); (b) BITS: when the sig-map syntax is 1204// active (emode bit5, the shipped config) each arm is costed by rc_sig_cost_q8 -- the coder's OWN adaptive- 1205// context bits (read-only walk of the exact bins) -- instead of the CAVLC ve_cost tables that mismatched the 1206// range-coded stream (why 803 sat dormant). Legacy non-sig rooms keep the CAVLC tables (their stream matches). 1207// rctx: [0] emode (bit5 = sig), [2] live probs, [4] t8c slab. J in Q8 bit units both arms. 1208// jout[0] receives min(jA, jB) -- the MB's best coeff-side J -- so the partition RD (P3b) can reuse this 1209// whole faithful trial as its 16x16 arm without recomputation drift. 1210// recon (F1114b): when non-null, the residual fill ALSO banks the predictor into recon (it is in hand 1211// per pixel anyway) -- the caller's emits read it back. Must be banked HERE: the B arm below overwrites 1212// res[] with its levels, so pred is unrecoverable from res after this function returns. The dormant 1213// vc_rd_part_inter_rc caller passes 0 (its recon is not in scope; P3b is refuted + caller-free). 1214func 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 { 1215 let t8c: *i64 = rctx[4] as *i64 1216 let probs: *i64 = rctx[2] as *i64 1217 var sig: i64 = 0 1218 if (rctx[0] & 32) != 0 { sig = 1 } 1219 let res: *i64 = vc_t8p(t8c, VC_T8_RES) 1220 let tr4: *i64 = vc_t8p(t8c, VC_T8_SCR) 1221 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) 1222 let work: *i64 = vc_t8p(t8c, VC_T8_WORK) 1223 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ) 1224 let zz8: *i64 = vc_t8p(t8c, VC_T8_ZZ) 1225 var dobank: i64 = 0 1226 if (recon as i64) != 0 { dobank = 1 } 1227 var yy: i64 = 0 1228 while yy < 16 { var xx: i64 = 0 1229 while xx < 16 { 1230 let c: i64 = cur[(cy+yy)*W + (cx+xx)] as i64 1231 let pred: i64 = qp_pixel(prev, W, cx+xx+mvx, cy+yy+mvy, bqx, bqy) 1232 res[yy*16 + xx] = c - pred 1233 if dobank == 1 { recon[(cy+yy)*W + (cx+xx)] = pred as u8 } 1234 xx = xx + 1 } yy = yy + 1 } 1235 // option A: 16x 4x4 (the shipping transform at this tf; RDOQ levels exactly like vc_enc_sub_sig/_rc). 1236 // F1114b: distortion = TRANSFORM-DOMAIN quant error (Parseval -- the doctrine vc_rdoq8's own comment 1237 // already states). e = v - r*d at 2D scale 4096 (tf==1) => spatial SSE = sum(e*e) >> 24. The 1238 // dequant+inverse+spatial-diff halves of both arms measured ~14% of the ENTIRE 677/2597 P-encode 1239 // (V8 profile 2026-07-29) and existed only to produce this number. Near-tie decisions may flip -- 1240 // both arms are RD-equivalent there by definition -- BD-gated, encoder-only. tf==0 (legacy WHT; 1241 // no gated config reaches the bit2 trial with it) keeps the spatial pipeline. 1242 var bitsA: i64 = 0 1243 var sseA: i64 = 0 1244 var eA: i64 = 0 1245 let dA: i64 = qp << DCT2_QSHIFT 1246 var sj: i64 = 0 1247 while sj < 4 { var si: i64 = 0 1248 while si < 4 { 1249 var k: i64 = 0 1250 while k < 16 { tr4[k] = res[(sj*4 + k/4)*16 + si*4 + (k%4)]; k = k + 1 } 1251 if tf == 1 { 1252 vt2_fwd(tr4) 1253 k = 0 1254 while k < 16 { c4s[k] = tr4[k]; k = k + 1 } 1255 vt2_quant_rdoq(tr4, qp) 1256 } else { vt_fwd(tr4); vt_quant(tr4, qp) } 1257 if sig == 1 { bitsA = bitsA + rc_sig_cost_q8(tr4, 16, 4, probs) } else { bitsA = bitsA + (ve_cost(tr4) << 8) } 1258 if tf == 1 { 1259 k = 0 1260 while k < 16 { let e: i64 = c4s[k] - tr4[k]*dA; eA = eA + e*e; k = k + 1 } 1261 } else { 1262 vt_dequant(tr4, qp); vt_inv(tr4) 1263 k = 0 1264 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 } 1265 } 1266 si = si + 1 } 1267 sj = sj + 1 } 1268 if tf == 1 { sseA = eA >> 24 } 1269 // option B: 4x 8x8 (DCT8; levels EXACTLY like the real 8x8 emit: same forward_2d + <<2 ref + vc_quant8 1270 // + vc_rdoq8 sequence as vc_enc_sub8, so banked levels == emit levels by identity). Transform-domain 1271 // distortion: e = c8 - L*q in the x4-orthonormal domain => spatial SSE = sum(e*e) >> 4. 1272 // F1114b LEVELS HANDBACK: freq (the final levels -- no dequant destroys them now) is written back into 1273 // THIS quadrant's res[] slots. res is dead after this loop (the caller banks pred=cur-res into recon 1274 // BEFORE any emit), so a bit2 winner's emit consumes these levels via vc_enc_sub8_tail and skips its 1275 // whole forward+quant+RDOQ recompute. 1276 var bitsB: i64 = 0 1277 var eB: i64 = 0 1278 sj = 0 1279 while sj < 2 { var si: i64 = 0 1280 while si < 2 { 1281 var k: i64 = 0 1282 while k < 64 { work[k] = res[(sj*8 + k/8)*16 + si*8 + (k%8)]; k = k + 1 } 1283 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)) 1284 k = 0 1285 while k < 64 { work[k] = freq[k] << 2; k = k + 1 } 1286 vc_quant8(freq, qp) 1287 vc_rdoq8(freq, work, qp, zz8) 1288 if sig == 1 { bitsB = bitsB + rc_sig_cost_q8(freq, 64, 8, probs) } else { bitsB = bitsB + (ve64_cost(freq, zz8) << 8) } 1289 k = 0 1290 while k < 64 { let e: i64 = work[k] - freq[k]*qp; eB = eB + e*e; k = k + 1 } 1291 k = 0 1292 while k < 64 { res[(sj*8 + k/8)*16 + si*8 + (k%8)] = freq[k]; k = k + 1 } 1293 si = si + 1 } 1294 sj = sj + 1 } 1295 let sseB: i64 = eB >> 4 1296 // jout is in the SAME estimated-spatial-SSE units both arms; sole consumer vc_rd_part_inter_rc is 1297 // dormant (P3b refuted, zero callers) -- if re-armed its part arm must move to the same estimate. 1298 let jA: i64 = 32*sseA*256 + qp*qp*bitsA 1299 let jB: i64 = 32*sseB*256 + qp*qp*bitsB 1300 jout[0] = jA 1301 if jB < jA { jout[0] = jB; return 1 } 1302 return 0 1303} 1304// P3b (2026-07-12): REAL-BIT PARTITION RD. The SAD-domain vc_rd_part_inter above models neither the transform, 1305// the real bits, nor reconstruction -- the same fidelity gaps P3 closed for the transform decision. This 1306// variant trials BOTH arms byte-faithfully and compares true J: 1307// 16x16 arm = full-pel search + the SAME 16-candidate qpel refine policy as the block coder (qp_refine) 1308// + the faithful t8-pair trial above (RDOQ levels, rc_sig_cost_q8 bits) via jout; 1309// part arm = per-quadrant vc_me8 (its own qpel, the exact MVs vc_enc_mb_part8_inter will re-find) 1310// + the exact 8x8 emit transform (dct8 + vc_quant8 + vc_rdoq8) costed the same way + recon SSE, 1311// with the running-MV-predictor header cost the partition encoder pays. 1312// J = 32*SSE*256 + qp^2*(coeff_bits_q8 + hdr_bits<<8). rc rooms only (bit0); legacy rooms keep the SAD J. 1313func vc_rd_part_inter_rc(cur: *u8, prev: *u8, W: i64, H: i64, cx: i64, cy: i64, qp: i64, tf: i64, rctx: *i64) -> i64 { 1314 let t8c: *i64 = rctx[4] as *i64 1315 let probs: *i64 = rctx[2] as *i64 1316 var sig: i64 = 0 1317 if (rctx[0] & 32) != 0 { sig = 1 } 1318 // scratch rides the slab's intra-only TE region (free during inter) -- NEVER sys_mmap here: in the wasm 1319 // build sys_mmap is a 0-stub, so mmap'd pointers ALIAS at address 0 (the bug that silently zeroed the 1320 // partition MVs in the LIVE wasm -- see vc_enc_mb_part8_inter below, fixed the same day) 1321 let mv: *i64 = vc_t8p(t8c, VC_T8_TE) 1322 let bq: *i64 = ((vc_t8p(t8c, VC_T8_TE) as i64) + 16) as *i64 1323 let jout: *i64 = ((vc_t8p(t8c, VC_T8_TE) as i64) + 32) as *i64 1324 // ---- 16x16 arm ---- 1325 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) 1326 qp_refine(cur, prev, W, H, cx, cy, mv[0], mv[1], 16, bq) 1327 vc_rd_t8_inter(cur, prev, 0 as *u8, W, cx, cy, qp, mv[0], mv[1], bq[0], bq[1], tf, rctx, jout) 1328 let j16: i64 = jout[0] + qp*qp*((vc_mvcost(mv[0]) + vc_mvcost(mv[1]) + 4) << 8) 1329 // ---- partition arm: 4 quadrants, exact emit transform + real bits + recon SSE ---- 1330 let res8: *i64 = vc_t8p(t8c, VC_T8_RES) 1331 let work: *i64 = vc_t8p(t8c, VC_T8_WORK) 1332 let freq: *i64 = vc_t8p(t8c, VC_T8_FREQ) 1333 let zz8: *i64 = vc_t8p(t8c, VC_T8_ZZ) 1334 var jpart: i64 = 0 1335 var mvb: i64 = 0 1336 var pmv0: i64 = 0 1337 var pmv1: i64 = 0 1338 var sj: i64 = 0 1339 while sj < 2 { var si: i64 = 0 1340 while si < 2 { 1341 let sx: i64 = cx + si*8 1342 let sy: i64 = cy + sj*8 1343 vc_me8(cur, prev, W, H, sx, sy, mv, bq, qp, ((vc_t8p(t8c, VC_T8_TE) as i64) + 40) as *i64) 1344 mvb = mvb + vc_mvcost(mv[0]-pmv0) + vc_mvcost(mv[1]-pmv1) + 4 1345 pmv0 = mv[0] 1346 pmv1 = mv[1] 1347 var yy: i64 = 0 1348 while yy < 8 { var xx: i64 = 0 1349 while xx < 8 { 1350 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]) 1351 work[yy*8 + xx] = r 1352 res8[yy*8 + xx] = r 1353 xx = xx + 1 } yy = yy + 1 } 1354 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)) 1355 var k: i64 = 0 1356 while k < 64 { work[k] = freq[k] << 2; k = k + 1 } 1357 vc_quant8(freq, qp) 1358 vc_rdoq8(freq, work, qp, zz8) 1359 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) } 1360 vc_dequant8(freq, qp) 1361 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)) 1362 k = 0 1363 var sse: i64 = 0 1364 while k < 64 { let d: i64 = work[k] - res8[k]; sse = sse + d*d; k = k + 1 } 1365 jpart = jpart + 32*sse*256 1366 si = si + 1 } sj = sj + 1 } 1367 jpart = jpart + qp*qp*(mvb << 8) 1368 if jpart < j16 { return 1 } 1369 return 0 1370} 1371// 4x4 Hadamard SATD of a prefilled residual d[16] (IN-PLACE butterflies; caller's buffer is scratch). Sum of 1372// |transform coeffs| / 2 (x264 normalization). SATD is a RATE proxy: the transform concentrates a structured 1373// residual into few coefficients, so argmin-by-SATD picks the MV whose residual is CHEAPEST TO CODE, where 1374// argmin-by-SAD picks the numerically smallest -- the classic x264 refinement win. Any orthogonal Hadamard 1375// ordering gives the same |coeff| multiset, so the unordered butterfly below is exact for SATD. 1376func vc_satd4_d(d: *i64) -> i64 { 1377 var i: i64 = 0 1378 while i < 4 { 1379 let b: i64 = i * 4 1380 let t0: i64 = d[b] + d[b+2] 1381 let t1: i64 = d[b+1] + d[b+3] 1382 let t2: i64 = d[b] - d[b+2] 1383 let t3: i64 = d[b+1] - d[b+3] 1384 d[b] = t0 + t1 1385 d[b+1] = t0 - t1 1386 d[b+2] = t2 + t3 1387 d[b+3] = t2 - t3 1388 i = i + 1 1389 } 1390 var j: i64 = 0 1391 while j < 4 { 1392 let u0: i64 = d[j] + d[8+j] 1393 let u1: i64 = d[4+j] + d[12+j] 1394 let u2: i64 = d[j] - d[8+j] 1395 let u3: i64 = d[4+j] - d[12+j] 1396 d[j] = u0 + u1 1397 d[4+j] = u0 - u1 1398 d[8+j] = u2 + u3 1399 d[12+j] = u2 - u3 1400 j = j + 1 1401 } 1402 var s: i64 = 0 1403 var k: i64 = 0 1404 while k < 16 { 1405 let v: i64 = d[k] 1406 if v < 0 { s = s - v } else { s = s + v } 1407 k = k + 1 1408 } 1409 return s / 2 1410} 1411// SATD cost of ONE 16x16 quarter-pel candidate (tqx,tqy) at full-pel base (px,py): 16 x satd4 over the same 1412// inlined-bilinear predictor as the SAD path ((acc+8)/16, w00..w11 hoisted) so the residual matches what the 1413// coder will actually produce. Early-exits vs `limit` (SATD only grows; a partial >= limit loses the strict <). 1414func 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 { 1415 let wxc: i64 = 4 - tqx 1416 let wyc: i64 = 4 - tqy 1417 let w00: i64 = wxc * wyc 1418 let w10: i64 = tqx * wyc 1419 let w01: i64 = wxc * tqy 1420 let w11: i64 = tqx * tqy 1421 var acc: i64 = 0 1422 var qy: i64 = 0 1423 while qy < 4 { 1424 var qx: i64 = 0 1425 while qx < 4 { 1426 var iy: i64 = 0 1427 while iy < 4 { 1428 let crow: i64 = (cy + qy*4 + iy) * W + cx + qx*4 1429 let prow: i64 = (py + qy*4 + iy) * W + px + qx*4 1430 let prow1: i64 = prow + W 1431 var ix: i64 = 0 1432 while ix < 4 { 1433 var a: i64 = w00 * (prev[prow + ix] as i64) 1434 if tqx > 0 { a = a + w10 * (prev[prow + ix + 1] as i64) } 1435 if tqy > 0 { a = a + w01 * (prev[prow1 + ix] as i64) } 1436 if w11 > 0 { a = a + w11 * (prev[prow1 + ix + 1] as i64) } 1437 sd[iy*4 + ix] = (cur[crow + ix] as i64) - ((a + 8) / 16) 1438 ix = ix + 1 1439 } 1440 iy = iy + 1 1441 } 1442 acc = acc + vc_satd4_d(sd) 1443 if acc >= limit { return acc } 1444 qx = qx + 1 1445 } 1446 qy = qy + 1 1447 } 1448 return acc 1449} 1450func 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 { 1451 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) 1452} 1453// ---- RD-SKIP (gen-2 rung-0 P0c -> gen-1 ship; emode bit11=2048, ENCODER-ONLY = decoder-transparent, no vcv 1454// bump: the skip bit is on the wire either way). Replaces the qp*30 skip threshold with TRUE rate-distortion 1455// skip: trial-code the P-MB both ways through the live coder (range-coder est/probs snapshot/restore; real bits 1456// from a flush-length probe on a COPY of est, tail bytes land in the dead zone past the live rcbuf position) and 1457// commit the J = 32*SSE + qp^2*bits winner (the same Lagrangian as vc_rd_t8_inter). MEASURED RD-DOMINANT 1458// (nx_vcodec_rdskip_gate, fidelity-proven): akiyo qp20 -6.9% bits AND -3.2% MSE; foreman qp32 -31% MSE for 1459// +4.3% bits; the fixed threshold leaks BOTH ways (wrongly-skips 4002 MBs foreman qp32, wrongly-codes 1984 1460// akiyo qp8 -- the audit's predicted content-dependence). bit11 off = byte-identical legacy (_i is the old _e). 1461// trial scratch lives at t8c+5008 (t8c = rctx[4] = a 626-i64=5008B slab; in the wasm region layout a 560B pad 1462// sits before rcbuf, and the gates' page-rounded mmap gives the same room) -- NO runtime mmap (sys_mmap is a 1463// 0-stub in wasm; and per-MB mmap would leak over live hours). 48 i64: est snap[0..7] + est copy[8..15] + probs 1464// snap[16..16+RC_NCTX8]. vc_t8_init never writes past index 626, so this tail is dead space. 1465func vc_rdskip_len(est: *i64, scr: *i64, rcbuf: *u8) -> i64 { 1466 var i: i64 = 0 1467 while i < 8 { scr[8 + i] = est[i]; i = i + 1 } 1468 let rb: i64 = rc_enc_flush(((scr as i64) + 64) as *i64, rcbuf) 1469 return rb * 8 1470} 1471func 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 { 1472 var rdsk: i64 = 0 1473 if (rctx as i64) != 0 { if keyframe == 0 { rdsk = (rctx[0] >> 11) & 1 } } 1474 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) } 1475 // ---- FPS BAND (817; the 816 trial-everything COLLAPSED live fps: the CODE arm forces full ME on EVERY 1476 // MB, including the static majority the do_me gate used to spare). Only MBs NEAR the skip boundary are 1477 // genuinely ambiguous (the measured flips cluster there); obvious-skip and obvious-code MBs take the 1478 // legacy threshold path at legacy cost. Band [thresh/4, 8*thresh] chosen to cover both measured flip 1479 // populations (RD-codes below thresh at high qp; RD-skips above thresh at low qp) -- BD-rate retention 1480 // + fps both MEASURED before ship. 1481 let zs: i64 = vm_sad_zero(cur, prev, W, bx, by, 16) 1482 var intrial: i64 = 1 1483 if zs < sad_thresh / VC_RDSK_LO_DIV { intrial = 0 } 1484 if zs > sad_thresh * VC_RDSK_HI_MUL { intrial = 0 } 1485 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) } 1486 let scr: *i64 = (rctx[4] + VC_MAGIC_5008) as *i64 1487 let est: *i64 = rctx[1] as *i64 1488 let probs: *i64 = rctx[2] as *i64 1489 let rcbuf: *u8 = rctx[3] as *u8 1490 var i: i64 = 0 1491 while i < 8 { scr[i] = est[i]; i = i + 1 } 1492 i = 0 1493 while i < RC_NCTX8 { scr[16 + i] = probs[i]; i = i + 1 } 1494 let r5: i64 = rctx[5] 1495 let rc0: i64 = vc_rdskip_len(est, scr, rcbuf) 1496 // arm CODE (F1113: NEGATIVE sad_thresh = skip disabled, do_me/partition gates at the REAL threshold -- 1497 // the old 0 also forced full search + partition RD on sub-threshold band MBs = gratuitous fps cost) 1498 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) 1499 let rc1: i64 = vc_rdskip_len(est, scr, rcbuf) 1500 let cx: i64 = bx * 16 1501 let cy: i64 = by * 16 1502 var dcode: i64 = 0 1503 var y: i64 = 0 1504 while y < 16 { 1505 var x: i64 = 0 1506 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 } 1507 y = y + 1 } 1508 let bits_code: i64 = (bpc - bp0) + (rc1 - rc0) 1509 // FAST RD-skip (2026-07-14, the "un-cripple" lever): skip freezes recon to prev at zero-MV, so the skip 1510 // distortion is dskip = SSD(cur, prev) computed DIRECTLY -- NO skip trial-encode. And the CODE arm already 1511 // ran once above and IS the committed stream, so if CODE wins we return it with NO re-encode (the old path 1512 // re-ran the full code arm = the measured 2x cost that kept RD-skip out of RTC). Only the losing-SKIP case 1513 // pays a cheap skip encode. Decoder-transparent: same code/skip choice, same output bytes as full RD-skip 1514 // (the skip-bit cost is ~1 and J is distortion-dominated, so the decision matches; verified vs handoff bench). 1515 var dskip: i64 = 0 1516 y = 0 1517 while y < 16 { 1518 var x: i64 = 0 1519 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 } 1520 y = y + 1 } 1521 let jc: i64 = 32*dcode + qp*qp*bits_code 1522 let js: i64 = 32*dskip + qp*qp 1523 if jc < js { return bpc } 1524 // SKIP wins -> undo the code arm (restore pre-code rc state + rewind bp to bp0) and encode the cheap skip 1525 i = 0 1526 while i < 8 { est[i] = scr[i]; i = i + 1 } 1527 i = 0 1528 while i < RC_NCTX8 { probs[i] = scr[16 + i]; i = i + 1 } 1529 rctx[5] = r5 1530 return vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, qp, 0, VC_MAGIC_1152921504606846976, buf, bp0, blk, mv, tfy, rctx) 1531} 1532func 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 { 1533 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) 1534 let cx: i64 = bx*16 1535 let cy: i64 = by*16 1536 var bp: i64 = bp0 1537 mv[0] = 0; mv[1] = 0 1538 var bqx: i64 = 0 1539 var bqy: i64 = 0 1540 // F1113 RD-TRIAL MODE: sad_thresh < 0 = "skip DISABLED, every OTHER gate at |sad_thresh|". The old 1541 // trial convention passed 0, which also forced do_me=1 (full search + refine on static MBs the 1542 // legacy path codes ungated at (0,0)) and pgo=1 (partition RD on EVERY trial MB) -- gratuitous 1543 // integration cost that was most of the RD-skip fps bill (817-law re-measure 2026-07-27). 1544 var thr: i64 = sad_thresh 1545 var noskip: i64 = 0 1546 if thr < 0 { thr = 0 - thr; noskip = 1 } 1547 if keyframe == 0 { 1548 let zsad: i64 = vm_sad_zero(cur, prev, W, bx, by, 16) 1549 var doskip: i64 = vs_skip(zsad, 0, 0, thr) 1550 if noskip == 1 { doskip = 0 } 1551 bp = nx_bw_put(buf, bp, doskip, 1) 1552 if doskip == 1 { 1553 var cy0: i64 = 0 1554 while cy0 < 16 { var cx0: i64 = 0 1555 while cx0 < 16 { recon[(cy+cy0)*W + (cx+cx0)] = prev[(cy+cy0)*W + (cx+cx0)]; cx0 = cx0 + 1 } cy0 = cy0 + 1 } 1556 return bp 1557 } 1558 // vcv-8 INTRA-IN-P (emode bit8, LUMA only). A non-skip P-MB may be coded as INTRA (9-mode rich-intra, NO 1559 // MV) when even a flat-DC intra estimate beats the best inter -- x264-class I-in-P, shrinking the residual 1560 // on hard-to-predict MBs at ZERO MV cost. Mode bit emitted ONLY when bit8 is set (gen>=8), BEFORE the 1561 // partition/inter header, so lower generations see a byte-identical stream. dmv is a separate search 1562 // scratch so the inter fall-through still sees mv=(0,0) for its own do_me gate. 1563 if (rctx as i64) != 0 { if (rctx[0] & 256) != 0 { if (rctx[0] & 16) == 0 { 1564 let isad: i64 = vc_intra_dc_sad(cur, recon, W, cx, cy) 1565 // dmv scratch on the rctx[4] slab (+5392, past the 48-i64 RD-skip scr): a sys_mmap here ran PER 1566 // NON-SKIP MB -> map-count exhaustion on threshold-retune benches (crash) + wasm sys_mmap is a 1567 // 0-stub. Slab fits both layouts (wasm: 5008+560B pad >= 5408). Guarded: bit8 => rct8 path => rctx[4] valid. 1568 let dmv: *i64 = (rctx[4] + VC_MAGIC_5392) as *i64 1569 let msad: i64 = vm_search(cur, prev, W, H, bx, by, 16, 8, dmv, blk) 1570 var imode: i64 = 0; if isad < msad { imode = 1 } 1571 bp = nx_bw_put(buf, bp, imode, 1) 1572 if imode == 1 { return vc_enc_mb4r_intra(cur, recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx) } 1573 } } } 1574 // F1112: have16 = the partition trial already ran (and rejected) => scr TE[0..1] holds THIS block's 1575 // 16x16 argmin, byte-for-byte what the search below would recompute. 1576 var have16: i64 = 0 1577 // vcv-7 P_8x8 MOTION PARTITION (emode bit7, LUMA only -- chroma bit4 never partitions). part bit emitted 1578 // ONLY when bit7 is set (client partAll()), so a vcv-6 room sees a byte-identical stream. RD picks 16x16 1579 // vs 4x-8x8; if partition, code it and return (its MVs+residual replace the 16x16 header below). 1580 if (rctx as i64) != 0 { if (rctx[0] & 128) != 0 { if (rctx[0] & 16) == 0 { 1581 // P3b real-bit partition J (vc_rd_part_inter_rc) MEASURED +5.45% avg vs the SAD J = REFUTED 1582 // 2026-07-12 (per-quadrant qpel-refined trial residuals flatter the partition arm; the fn stays 1583 // in-tree dormant with the analysis in the roadmap). The SAD J stays -- now with real scratch. 1584 // 825 ORDERING FIX (live-incident follow-up): the partition evaluation (5 motion searches) used to 1585 // run BEFORE the static gate, so on real sensor noise every noise-static block paid it -- MEASURED 1586 // 41% of the noise frame time (320x256: 51.4 -> 30.2 ms without it). Gate on motion -- but the 1587 // whole-MB zsad alone is BLIND to a single moving QUADRANT inside a quiet block (exactly what 1588 // partitions exist for; zsad-only gating measured +2.0% avg BD, bus +4.5). So: evaluate when the 1589 // MB moves OR any 8x8 quadrant does (four zero-SADs = 256 adds, trivial next to 5 searches; 1590 // per-quadrant threshold = thresh/4 by area). The partition BIT stays in the syntax either way. 1591 var usepart: i64 = 0 1592 var pgo: i64 = 0 1593 if zsad >= thr { pgo = 1 } 1594 if pgo == 0 { 1595 let qt: i64 = thr / 4 1596 if vm_sad(cur, prev, W, cx, cy, cx, cy, 8) >= qt { pgo = 1 } 1597 if vm_sad(cur, prev, W, cx+8, cy, cx+8, cy, 8) >= qt { pgo = 1 } 1598 if vm_sad(cur, prev, W, cx, cy+8, cx, cy+8, 8) >= qt { pgo = 1 } 1599 if vm_sad(cur, prev, W, cx+8, cy+8, cx+8, cy+8, 8) >= qt { pgo = 1 } 1600 } 1601 if pgo == 1 { 1602 usepart = vc_rd_part_inter(cur, prev, W, H, cx, cy, qp, vc_t8p(rctx[4] as *i64, VC_T8_TE)) 1603 // F1112: a rejected trial already searched THIS block's 16x16 window -- reuse it below 1604 if usepart == 0 { have16 = 1 } 1605 } 1606 bp = nx_bw_put(buf, bp, usepart, 1) 1607 if usepart == 1 { return vc_enc_mb_part8_inter(cur, prev, recon, W, H, cx, cy, qp, buf, bp, rctx[4] as *i64, rctx) } 1608 } } } 1609 // ME GATE (2026-07-03 stage profile: skip never fires vs recon refs -- quant noise alone is 1610 // ~QP*avg-err*256 SAD -- so EVERY block paid the 289-SAD search + 16-candidate refine = the 1611 // measured 74%+54% of P-encode). Near-static block => motion is (0,0); STILL CODE THE RESIDUAL 1612 // (that is where the quality lives -- full-skip cost a measured 2.8-4.1dB, this costs ~0 by 1613 // construction: the residual coder captures whatever the gate misses, only BITS are at risk, 1614 // and for texture-evolution content ME finds nothing anyway, zsad ~= searched-sad). Gate is 1615 // QP-SCALED like the quant deadzone (no magic constant): qp*188 sits above the measured 1616 // static-with-quant-noise band (~2-3k at QP32) and below real translation (edge slivers ~11k), 1617 // so genuinely moving blocks still get the full search + quarter-pel refine. 1618 var do_me: i64 = 1 1619 // F1113 refinement (MEASURED, foreman): in RD-trial mode the search must stay ON -- gating it made 1620 // band MBs code at (0,0) with fat residuals, losing BOTH axes (-0.6dB at +25-70% bits vs searched 1621 // trials). Only the PARTITION forcing was pure waste. So noskip keeps do_me=1 unconditionally. 1622 if noskip == 0 { if zsad < thr { do_me = 0 } } // 811-followup: tie the motion-search gate to the SKIP threshold (was 1623 // hardcoded qp*188 -- after the skip fix that left [skip,188) blocks CODED with (0,0) motion + no search = 1624 // huge residual on moving blocks). Now every coded (non-skip) block gets the full search + qpel refine. 1625 // MEASURED I+P BD-rate vs x264: foreman +459->+240% · akiyo +302->+238% · bus +259->+183% · mobile +238->+178%. 1626 var mvd10: i64 = 0 1627 if (rctx as i64) != 0 { if (rctx[0] & VC_MAGIC_8192) != 0 { mvd10 = 1 } } 1628 if do_me == 1 { 1629 if have16 == 1 { 1630 // F1112: the partition trial's 16x16 search IS this search (same refs, same window, same 1631 // qp, cx/16==bx by construction; vm_search_q is pure in its inputs) -- take the trial's 1632 // argmin from the handback slots instead of re-running the candidate walk. 1633 let scr16: *i64 = vc_t8p(rctx[4] as *i64, VC_T8_TE) 1634 mv[0] = scr16[VC_TE_H16_MV0] 1635 mv[1] = scr16[VC_TE_H16_MV1] 1636 } else { vm_search_q(cur, prev, W, H, bx, by, 16, VC_ME_R, mv, qp, blk) } 1637 } 1638 if mvd10 == 1 { 1639 // vcv-10 MVD: median-predicted delta in exp-Golomb (MEASURED 9permille-of-P-bytes floor vs 1640 // absolute ve_vput -- nx_vcodec_mvbits_probe 2026-07-20). pxy scratch = TE+48 (past the 1641 // rd_part mv/bq/jout slots, all dead by this point). Plane set = the EMITTED mv (pre-clamp 1642 // truth; the decoder mirrors from the wire). 1643 let mvp10: *i64 = rctx[9] as *i64 1644 let pxy10: *i64 = ((vc_t8p(rctx[4] as *i64, VC_T8_TE) as i64) + 48) as *i64 1645 vc_mvpred(mvp10, W/16, bx, pxy10) 1646 bp = vc_gput(buf, bp, mv[0] - pxy10[0]) 1647 bp = vc_gput(buf, bp, mv[1] - pxy10[1]) 1648 vc_mvplane_set(mvp10, W/16, bx, mv[0], mv[1]) 1649 } else { 1650 bp = ve_vput(buf, bp, mv[0]) 1651 bp = ve_vput(buf, bp, mv[1]) 1652 } 1653 // QUARTER-PEL refine over the 16x16 MB (streaming SAD, no scratch): qp_pixel subsumes integer (0,0) and half 1654 // (2,*) EXACTLY, so (0,0) reduces to integer motion (bit-exact invariant preserved) and a sub-pixel shift -> 1655 // smaller residual -> fewer bits (H.264/VP9 motion precision). qp_pixel matches the decoder, so recon is exact. 1656 let px: i64 = cx + mv[0] 1657 let py: i64 = cy + mv[1] 1658 // SATD REFINE (emode bit10, 2026-07-11, ENCODER-ONLY -> decoder-transparent, NO vcv bump: the wire 1659 // carries whatever MV wins; any decoder reproduces it). Argmin by Hadamard SATD (rate proxy -- picks the 1660 // candidate whose residual is cheapest to CODE) instead of raw SAD. bestsad is INTERNAL to this argmin 1661 // (nothing downstream reads it), so the scale difference (SATD ~2x SAD) contaminates no threshold. 1662 var use_satd: i64 = 0 1663 if (rctx as i64) != 0 { use_satd = (rctx[0] >> 10) & 1 } 1664 var sdp: i64 = 0 1665 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 1666 var bestsad: i64 = VC_MAGIC_2147483647 1667 var tqy: i64 = 0 1668 if do_me == 0 { tqy = 4; bestsad = zsad } // ME-gated: (0,0) integer motion, no refine (bqx=bqy=0 coded below); 1669 // bestsad = the honest residual scale so downstream gates (t8 early-out) see reality, not 2^31 1670 while tqy <= 3 { 1671 var tqx: i64 = 0 1672 while tqx <= 3 { 1673 var ok: i64 = 1 1674 if tqx > 0 { if px + 16 >= W { ok = 0 } } 1675 if tqy > 0 { if py + 16 >= H { ok = 0 } } 1676 if ok == 1 { 1677 if use_satd == 1 { 1678 let scost: i64 = vc_satd16_cand(cur, prev, W, cx, cy, px, py, tqx, tqy, bestsad, sdp as *i64) 1679 if scost < bestsad { bestsad = scost; bqx = tqx; bqy = tqy } 1680 } else { 1681 // INLINED qp_pixel bilinear with per-candidate hoisted weights + per-row hoisted 1682 // bases: identical arithmetic to qp_pixel (acc = w00*p00 + w10*p10 + w01*p01 + 1683 // w11*p11; (acc+8)/16; (0,0) reduces to (16a+8)/16 == a) so every SAD -- and thus 1684 // the selected candidate and the BITSTREAM -- is unchanged. What it removes is the 1685 // per-pixel CALL + the y*W recomputation, the measured hot core of the 76ms frame. 1686 let wxc: i64 = 4 - tqx 1687 let wyc: i64 = 4 - tqy 1688 let w00: i64 = wxc * wyc 1689 let w10: i64 = tqx * wyc 1690 let w01: i64 = wxc * tqy 1691 let w11: i64 = tqx * tqy 1692 var sad: i64 = 0 1693 var ry: i64 = 0 1694 while ry < 16 { 1695 let crow: i64 = (cy + ry) * W + cx 1696 let prow: i64 = (py + ry) * W + px 1697 let prow1: i64 = prow + W 1698 var rx: i64 = 0 1699 while rx < 16 { 1700 var acc: i64 = w00 * (prev[prow + rx] as i64) 1701 if tqx > 0 { acc = acc + w10 * (prev[prow + rx + 1] as i64) } 1702 if tqy > 0 { acc = acc + w01 * (prev[prow1 + rx] as i64) } 1703 if w11 > 0 { acc = acc + w11 * (prev[prow1 + rx + 1] as i64) } 1704 let dd: i64 = (cur[crow + rx] as i64) - ((acc + 8) / 16) 1705 if dd < 0 { sad = sad - dd } else { sad = sad + dd } 1706 rx = rx + 1 1707 } 1708 // early-exit (bit-exact): sad only grows; a candidate already >= bestsad loses 1709 // under the strict < below whether finished or not. (0,0) runs first with 1710 // bestsad=MAX so the integer-motion baseline is always fully evaluated. 1711 if sad >= bestsad { ry = 16 } else { ry = ry + 1 } 1712 } 1713 if sad < bestsad { bestsad = sad; bqx = tqx; bqy = tqy } 1714 } 1715 } 1716 tqx = tqx + 1 1717 } 1718 tqy = tqy + 1 1719 } 1720 bp = nx_bw_put(buf, bp, bqx, 2) 1721 bp = nx_bw_put(buf, bp, bqy, 2) 1722 } 1723 var t8x: i64 = t8 1724 var resfresh: i64 = 0 1725 if (rctx as i64) != 0 { if (rctx[0] & 4) != 0 { if keyframe == 0 { if bestsad >= qp * VC_EO_T8 { 1726 // RD-AUTO (encoder-only, emode bit2): decide per-MB from the ACTUAL MC residual and patch the 1727 // reserved t8 bit at rctx[5] (frame fn wrote a 0 placeholder). The decoder just reads the bit. 1728 // EARLY-OUT: a low refined-SAD residual has too little energy for the transform choice to matter -- 1729 // default 4x4 (the majority winner) and save both trial passes (the measured decision-stack cost). 1730 // F1114b: the trial banks its exact PREDICTOR into recon (during its residual fill -- res[] is 1731 // levels, not residual, once its B arm finishes) and leaves its final 8x8 LEVELS in res[]'s 1732 // quadrants. Both emits below consume the bank: the 8x8 winner skips forward+quant+RDOQ AND all 1733 // 512 bilinears (vc_enc_mb8_inter pfresh); the 4x4 path derives its residual as cur - recon. 1734 // (History: the residual-only handback measured 1.00x alone -- bilinears were ~5% -- and was 1735 // stripped same-day; it returned as the enabling leg of this levels handback.) 1736 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)) 1737 if t8x == 1 { nx_bw_put(buf, rctx[5], 1, 1) } 1738 resfresh = 1 1739 } } } } 1740 if t8x == 1 { 1741 // ---- 8x8 path (task #46 rung 2): the MB header above (skip/MV/quarter-pel) is SHARED -- only the 1742 // prediction granularity + residual transform change. The t8c slab rides rctx[4] (the t8 frame fns 1743 // guarantee rctx is i64[>=6]; no other caller ever sets tfy bit1 or emode bit2). ---- 1744 let t8c: *i64 = rctx[4] as *i64 1745 if keyframe == 1 { return vc_enc_mb8_intra(cur, recon, W, cx, cy, ytop, qp, buf, bp, t8c, rctx) } 1746 return vc_enc_mb8_inter(cur, prev, recon, W, cx, cy, qp, mv[0], mv[1], bqx, bqy, buf, bp, t8c, rctx, resfresh) 1747 } 1748 if keyframe == 1 { if (rctx as i64) != 0 { if (rctx[0] & 8) != 0 { if (rctx[0] & 16) == 0 { 1749 // RICH-INTRA stream (emode bit3, set by the t8 frame fns on BOTH sides): 4x4 intra MBs get the 1750 // 9-mode MPM engine too. Legacy streams (bit3 never set) keep the inline 4-mode path below. 1751 // bit4 (conservative plane -- CHROMA) opts OUT back to the legacy 4-mode syntax: the field noise 1752 // gate measured rich-intra chroma at +26% blockiness under temporal noise at qp33 (mode structure 1753 // persists through skip-heavy chroma P frames). BOTH vv wrappers set bit4 for U/V deterministically, 1754 // so encoder and decoder agree on the per-plane syntax by construction. 1755 return vc_enc_mb4r_intra(cur, recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx) 1756 } } } } 1757 var sj: i64 = 0 1758 while sj < 4 { 1759 var si: i64 = 0 1760 while si < 4 { 1761 let sx: i64 = cx + si*4 1762 let sy: i64 = cy + sj*4 1763 if keyframe == 1 { 1764 // ---- directional intra: gather edge-substituted reconstructed neighbors (scalars, no alloc) ---- 1765 var t0: i64=128; var t1: i64=128; var t2: i64=128; var t3: i64=128 1766 var l0: i64=128; var l1: i64=128; var l2: i64=128; var l3: i64=128 1767 var corner: i64=128 1768 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 } 1769 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 } 1770 if sx > 0 { if sy > ytop { corner=recon[(sy-1)*W+sx-1] as i64 } } 1771 var dcsum: i64=0; var dccnt: i64=0 1772 if sy > ytop { dcsum=dcsum+t0+t1+t2+t3; dccnt=dccnt+4 } 1773 if sx > 0 { dcsum=dcsum+l0+l1+l2+l3; dccnt=dccnt+4 } 1774 var dc: i64=128; if dccnt > 0 { dc=dcsum/dccnt } // mode 0 == vc_dc_pred's rule (old behavior preserved) 1775 // pick the lowest-SAD mode of {DC,V,H,DDR} 1776 var bestmode: i64=0; var bestsad: i64=VC_MAGIC_2147483647; var m: i64=0 1777 while m < 4 { 1778 var sad: i64=0; var ay: i64=0 1779 while ay < 4 { var ax: i64=0 1780 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 } 1781 if sad < bestsad { bestsad=sad; bestmode=m } 1782 m=m+1 1783 } 1784 bp = nx_bw_put(buf, bp, bestmode, 2) 1785 var ry: i64=0 1786 while ry < 4 { var rx: i64=0 1787 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 } 1788 bp = vc_coeff_enc(blk, qp, buf, bp, tf, rctx) 1789 var cy2: i64=0 1790 while cy2 < 4 { var cx2: i64=0 1791 while cx2 < 4 { 1792 var v: i64=vc_pred_px(bestmode, cx2, cy2, t0,t1,t2,t3, l0,l1,l2,l3, corner, dc) + blk[cy2*4+cx2] 1793 if v < 0 { v=0 } if v > 255 { v=255 } 1794 recon[(sy+cy2)*W+sx+cx2]=v as u8 1795 cx2=cx2+1 } cy2=cy2+1 } 1796 } else { 1797 // ---- inter: quarter-pel motion-compensated predictor. F1114b: when the bit2 trial ran, 1798 // its exact predictor is banked in recon (res[] holds levels by now, NOT residual) -- 1799 // recon[pix] keeps pred until the write below replaces it, per-pixel read-then-write ---- 1800 var yy: i64 = 0 1801 while yy < 4 { 1802 var xx: i64 = 0 1803 while xx < 4 { 1804 let c: i64 = cur[(sy+yy)*W + (sx+xx)] as i64 1805 var pred: i64 = 0 1806 if resfresh == 1 { pred = recon[(sy+yy)*W + (sx+xx)] as i64 } 1807 else { pred = qp_pixel(prev, W, sx+xx+mv[0], sy+yy+mv[1], bqx, bqy) } 1808 blk[yy*4 + xx] = c - pred 1809 xx = xx + 1 1810 } 1811 yy = yy + 1 1812 } 1813 bp = vc_coeff_enc(blk, qp, buf, bp, tf, rctx) 1814 yy = 0 1815 while yy < 4 { 1816 var xx: i64 = 0 1817 while xx < 4 { 1818 var pred: i64 = 0 1819 if resfresh == 1 { pred = recon[(sy+yy)*W + (sx+xx)] as i64 } 1820 else { pred = qp_pixel(prev, W, sx+xx+mv[0], sy+yy+mv[1], bqx, bqy) } 1821 var v: i64 = pred + blk[yy*4 + xx] 1822 if v < 0 { v = 0 } 1823 if v > 255 { v = 255 } 1824 recon[(sy+yy)*W + (sx+xx)] = v as u8 1825 xx = xx + 1 1826 } 1827 yy = yy + 1 1828 } 1829 } 1830 si = si + 1 1831 } 1832 sj = sj + 1 1833 } 1834 return bp 1835} 1836// decode one macroblock from the stream at bp into recon (using prev only); returns the new bit position. 1837func 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 { 1838 return vc_dec_block_packed_e(prev, recon, W, H, bx, by, qp, keyframe, buf, bp0, blk, mv, tfy, 0 as *i64) 1839} 1840func 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 { 1841 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 1842 let cx: i64 = bx*16 1843 let cy: i64 = by*16 1844 var bp: i64 = bp0 1845 mv[0] = 0; mv[1] = 0 1846 var bqx: i64 = 0 1847 var bqy: i64 = 0 1848 if keyframe == 0 { 1849 let doskip: i64 = nx_br_get(buf, bp, 1) 1850 bp = bp + 1 1851 if doskip == 1 { 1852 var cy0: i64 = 0 1853 while cy0 < 16 { var cx0: i64 = 0 1854 while cx0 < 16 { recon[(cy+cy0)*W + (cx+cx0)] = prev[(cy+cy0)*W + (cx+cx0)]; cx0 = cx0 + 1 } cy0 = cy0 + 1 } 1855 return bp 1856 } 1857 // vcv-8 INTRA-IN-P -- MUST mirror vc_enc_block_packed_e's mode-bit routing (bit8, luma-only) exactly, BEFORE the part bit. 1858 if (rctx as i64) != 0 { if (rctx[0] & 256) != 0 { if (rctx[0] & 16) == 0 { 1859 let imode: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 1860 if imode == 1 { return vc_dec_mb4r_intra(recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx) } 1861 } } } 1862 // vcv-7 P_8x8 MOTION PARTITION -- MUST mirror vc_enc_block_packed_e's part-bit routing (bit7, luma-only) exactly. 1863 if (rctx as i64) != 0 { if (rctx[0] & 128) != 0 { if (rctx[0] & 16) == 0 { 1864 let usepart: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 1865 if usepart == 1 { return vc_dec_mb_part8_inter(prev, recon, W, cx, cy, qp, buf, bp, rctx[4] as *i64, rctx) } 1866 } } } 1867 var mvd10d: i64 = 0 1868 if (rctx as i64) != 0 { if (rctx[0] & VC_MAGIC_8192) != 0 { mvd10d = 1 } } 1869 if mvd10d == 1 { 1870 // vcv-10 MVD twin: MUST mirror the encoder's median + golomb + plane chain EXACTLY. Plane is 1871 // set from the DECODED (pre-clamp) mv = the wire truth the encoder's plane carried. 1872 let mvp10: *i64 = rctx[9] as *i64 1873 let pxy10: *i64 = ((vc_t8p(rctx[4] as *i64, VC_T8_TE) as i64) + 48) as *i64 1874 let bpb10: *i64 = ((vc_t8p(rctx[4] as *i64, VC_T8_TE) as i64) + 64) as *i64 1875 vc_mvpred(mvp10, W/16, bx, pxy10) 1876 bpb10[0] = bp 1877 mv[0] = vc_gget(buf, bpb10) + pxy10[0] 1878 mv[1] = vc_gget(buf, bpb10) + pxy10[1] 1879 bp = bpb10[0] 1880 vc_mvplane_set(mvp10, W/16, bx, mv[0], mv[1]) 1881 } else { 1882 mv[0] = ve_vval(buf, bp); bp = bp + ve_vlen(buf, bp) 1883 mv[1] = ve_vval(buf, bp); bp = bp + ve_vlen(buf, bp) 1884 } 1885 bqx = nx_br_get(buf, bp, 2); bp = bp + 2 1886 bqy = nx_br_get(buf, bp, 2); bp = bp + 2 1887 // DECODER ROBUSTNESS (rule 12: the wire is external input): a CORRUPTED motion vector must never 1888 // index prev out of bounds. qp_pixel reads prev[y*W+x] and the +1 quarter-pel taps, so the far 1889 // corner touches col cx+16+mv0 and row cy+16+mv1. Bound = W-16-cx / H-16-cy: this ALLOWS the valid 1890 // edge MV the encoder emits (rightmost interp tap lands at col W == the in-buffer chroma start, read 1891 // IDENTICALLY by enc + dec -> bit-exact, proven by xinst + t8noise), while a fuzzed/huge MV is 1892 // clamped into the YUV buffer (max read index W*(H+1) < W*H*3/2). Refuse-quality, never a trap. 1893 let mvxlo: i64 = 0 - cx 1894 let mvxhi: i64 = W - 16 - cx 1895 let mvylo: i64 = 0 - cy 1896 let mvyhi: i64 = H - 16 - cy 1897 if mv[0] < mvxlo { mv[0] = mvxlo } 1898 if mv[0] > mvxhi { mv[0] = mvxhi } 1899 if mv[1] < mvylo { mv[1] = mvylo } 1900 if mv[1] > mvyhi { mv[1] = mvyhi } 1901 } 1902 if t8 == 1 { 1903 // ---- 8x8 path: MUST mirror vc_enc_block_packed_e's routing exactly ---- 1904 let t8c: *i64 = rctx[4] as *i64 1905 if keyframe == 1 { return vc_dec_mb8_intra(recon, W, cx, cy, ytop, qp, buf, bp, t8c, rctx) } 1906 return vc_dec_mb8_inter(prev, recon, W, cx, cy, qp, mv[0], mv[1], bqx, bqy, buf, bp, t8c, rctx) 1907 } 1908 if keyframe == 1 { if (rctx as i64) != 0 { if (rctx[0] & 8) != 0 { if (rctx[0] & 16) == 0 { 1909 // RICH-INTRA stream: MUST mirror the encoder's routing exactly (incl the bit4 chroma opt-out) 1910 return vc_dec_mb4r_intra(recon, W, cx, cy, ytop, qp, tf, buf, bp, blk, rctx[4] as *i64, rctx) 1911 } } } } 1912 var sj: i64 = 0 1913 while sj < 4 { 1914 var si: i64 = 0 1915 while si < 4 { 1916 let sx: i64 = cx + si*4 1917 let sy: i64 = cy + sj*4 1918 if keyframe == 1 { 1919 // gather the SAME edge-substituted reconstructed neighbors as the encoder (raster order keeps them in sync) 1920 var t0: i64=128; var t1: i64=128; var t2: i64=128; var t3: i64=128 1921 var l0: i64=128; var l1: i64=128; var l2: i64=128; var l3: i64=128 1922 var corner: i64=128 1923 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 } 1924 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 } 1925 if sx > 0 { if sy > ytop { corner=recon[(sy-1)*W+sx-1] as i64 } } 1926 var dcsum: i64=0; var dccnt: i64=0 1927 if sy > ytop { dcsum=dcsum+t0+t1+t2+t3; dccnt=dccnt+4 } 1928 if sx > 0 { dcsum=dcsum+l0+l1+l2+l3; dccnt=dccnt+4 } 1929 var dc: i64=128; if dccnt > 0 { dc=dcsum/dccnt } 1930 // read the chosen mode THEN the residual (same order the encoder wrote them) 1931 let bestmode: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 1932 bp = vc_coeff_dec(buf, bp, qp, blk, tf, rctx) 1933 var cy2: i64=0 1934 while cy2 < 4 { var cx2: i64=0 1935 while cx2 < 4 { 1936 var v: i64=vc_pred_px(bestmode, cx2, cy2, t0,t1,t2,t3, l0,l1,l2,l3, corner, dc) + blk[cy2*4+cx2] 1937 if v < 0 { v=0 } if v > 255 { v=255 } 1938 recon[(sy+cy2)*W+sx+cx2]=v as u8 1939 cx2=cx2+1 } cy2=cy2+1 } 1940 } else { 1941 bp = vc_coeff_dec(buf, bp, qp, blk, tf, rctx) 1942 var yy: i64 = 0 1943 while yy < 4 { 1944 var xx: i64 = 0 1945 while xx < 4 { 1946 let pred: i64 = qp_pixel(prev, W, sx+xx+mv[0], sy+yy+mv[1], bqx, bqy) 1947 var v: i64 = pred + blk[yy*4 + xx] 1948 if v < 0 { v = 0 } 1949 if v > 255 { v = 255 } 1950 recon[(sy+yy)*W + (sx+xx)] = v as u8 1951 xx = xx + 1 1952 } 1953 yy = yy + 1 1954 } 1955 } 1956 si = si + 1 1957 } 1958 sj = sj + 1 1959 } 1960 return bp 1961} 1962// encode a whole frame into a transmittable stream (buf); reconstructs into recon; returns total bits. 1963func 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 { 1964 return vc_enc_frame_packed_tf(cur, prev, recon, W, H, qp, keyframe, sad_thresh, buf, blk, mv, 0) 1965} 1966func 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 { 1967 var bp: i64 = nx_bw_put(buf, 0, keyframe, 1) 1968 let BW: i64 = W / 16 1969 let BH: i64 = H / 16 1970 var by: i64 = 0 1971 while by < BH { var bx: i64 = 0 1972 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 } 1973 return bp 1974} 1975// decode a whole frame from the stream (buf) into recon using prev only; returns total bits consumed. The keyframe 1976// flag is read from the stream head; qp is a session parameter shared out of band. 1977func vc_dec_frame_packed(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64) -> i64 { 1978 return vc_dec_frame_packed_tf(prev, recon, W, H, qp, buf, blk, mv, 0) 1979} 1980func vc_dec_frame_packed_tf(prev: *u8, recon: *u8, W: i64, H: i64, qp: i64, buf: *u8, blk: *i64, mv: *i64, tf: i64) -> i64 { 1981 let keyframe: i64 = nx_br_get(buf, 0, 1) 1982 var bp: i64 = 1 1983 let BW: i64 = W / 16 1984 let BH: i64 = H / 16 1985 var by: i64 = 0 1986 while by < BH { var bx: i64 = 0 1987 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 } 1988 return bp 1989} 1990// RANGE-CODED frame (task #31): two sections in buf -> [range_start:u16][CAVLC bits from bit16: keyframe + 1991// per-MB AQ-level/skip/MV/mode/bqx][range bytes: all coeff blocks]. rctx = i64[>=5] = [1, est, probs, rcbuf]. 1992// CAVLC path is a SEPARATE function (vc_enc_frame_packed_tf) -> untouched -> zero regression. Returns bytes*8. 1993func 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 { 1994 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 1995 rc_enc_init(est) 1996 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) 1997 var bp: i64 = nx_bw_put(buf, 16, keyframe, 1) // CAVLC starts at bit 16 (byte 2 reserved for range_start) 1998 let BW: i64 = W / 16; let BH: i64 = H / 16 1999 var by: i64 = 0 2000 while by < BH { var bx: i64 = 0 2001 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) 2002 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 } 2003 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8) 2004 let cavlc_end: i64 = (bp + 7) / 8 2005 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8 2006 let rcbuf: *u8 = rctx[3] as *u8; var i: i64 = 0 2007 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 } 2008 return (cavlc_end + rbytes) * 8 2009} 2010func 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 { 2011 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2012 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) 2013 rctx[3] = (buf as i64) + cavlc_end // the block's coeff decoder reads the range section here 2014 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) 2015 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8) 2016 let keyframe: i64 = nx_br_get(buf, 16, 1) 2017 var bp: i64 = 17 2018 let BW: i64 = W / 16; let BH: i64 = H / 16 2019 var by: i64 = 0 2020 while by < BH { var bx: i64 = 0 2021 while bx < BW { let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 2022 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 } 2023 return 0 2024} 2025// ---- PER-MB VARIABLE-TRANSFORM frames (task #46 rung 2). Stream = [keyframe:1] then per-MB raster 2026// [aq_level:2][t8:1][MB]. Encoder select: emode bit2 CLEAR = mad policy (t8 = aq_level<=1, the classifier 2027// the tsize RD gate validated); emode bit2 SET = RD-AUTO on inter MBs (vc_rd_t8_inter costs BOTH transforms 2028// on the real MC residual; keyframes keep the policy). The bit is EXPLICIT in the stream so either encoder 2029// produces a stream ANY t8 decoder reads -- decoders never see emode bit2. 2030// rctx = i64[>=6] = [emode, est, probs, rcbuf, t8c, t8bitpos]; emode here: 0=CAVLC, 4=CAVLC+auto (bit0 2031// MUST be clear -- est/probs/rcbuf unused); t8c = i64[VC_T8_SIZE] slab, vc_t8_init'd by the caller; 2032// t8bitpos is internal (frame fn -> block coder). The CAVLC/RC frame fns above are SEPARATE and 2033// untouched -> zero regression on every existing stream. ---- 2034func 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 { 2035 rctx[0] = rctx[0] | 8 // t8-stream syntax = RICH INTRA (9-mode MPM) on both block sizes, both sides 2036 rctx[0] = (rctx[0] | 4) - 4 // RD-auto (bit2) is INERT under the keyframes-only policy: strip it so the 2037 // block coder can never patch an un-reserved bit position (rctx[5] stale) 2038 var bp: i64 = nx_bw_put(buf, 0, keyframe, 1) 2039 bp = nx_bw_put(buf, bp, 0, 1) // nf bit (in-loop restoration): 0 placeholder; the vv layer patches it 2040 // on the LUMA stream only, after MEASURING a win vs the source 2041 let BW: i64 = W / 16 2042 let BH: i64 = H / 16 2043 var by: i64 = 0 2044 while by < BH { var bx: i64 = 0 2045 while bx < BW { 2046 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)) 2047 bp = nx_bw_put(buf, bp, lv, 2) 2048 var t8: i64 = 0 2049 if (rctx[0] & 16) == 0 { if keyframe == 1 { 2050 // t8 = KEYFRAMES ONLY (field 788, third round: P-frame 8x8 still read blocky at long GOP + 2051 // the t8 path cost fps on phones). Keyframes keep the PROVEN, large win (flat intra -52% 2052 // bytes = join/recovery cost) under the uniform-flatness guard; P frames ride the exact 2053 // legacy 4x4 residual path (byte-identical speed + structure). Chroma additionally stays 2054 // 4x4 (emode bit4, field round 1). RD-auto (bit2) is inert under this policy. All of this 2055 // is ENCODER POLICY -- the explicit per-MB bits keep every decoder compatible. 2056 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. 2057 } } 2058 bp = nx_bw_put(buf, bp, t8, 1) 2059 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) 2060 bx = bx + 1 } by = by + 1 } 2061 return bp 2062} 2063func 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 { 2064 rctx[0] = rctx[0] | 8 // MUST match the encoder's syntax bit 2065 let keyframe: i64 = nx_br_get(buf, 0, 1) 2066 var bp: i64 = 2 // bit1 = nf flag (read by the vv layer; MB syntax starts after it) 2067 let BW: i64 = W / 16 2068 let BH: i64 = H / 16 2069 var by: i64 = 0 2070 while by < BH { var bx: i64 = 0 2071 while bx < BW { 2072 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 2073 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 2074 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) 2075 bx = bx + 1 } by = by + 1 } 2076 return bp 2077} 2078// RANGE-CODED + variable-transform frame: the _rc two-section layout ([range_start:u16][CAVLC bits from 2079// bit16: keyframe + per-MB aq/t8/skip/MV/mode][range bytes: all coeff blocks, 4x4 AND 8x8 contexts]) with 2080// the per-MB t8 select. rctx = [1, est, probs, rcbuf, t8c]; probs sized >= RC_NCTX8 (24), seeded here. 2081// P2 HEAT-AQ (2026-07-12, MEASURED −1.72% avg BD-rate, akiyo −3.53/foreman −2.86, never-negative on the MSU 2082// grid): protect PERSISTENT content from drift -- once an MB's consecutive-skip streak reaches VC_HEAT_STREAK, 2083// halve its skip threshold so a drifting static block is re-coded sooner; the PSNR payback amortizes across the 2084// whole following streak. The CHURN direction (cheapening active MBs) measured +6.4% = REFUTED -- never do it. 2085// ENCODER-ONLY (no wire/syntax change, decoder-transparent). CONTRACT: emode bit12 (4096) = heat-AQ on AND the 2086// rctx block has a 9th slot: rctx[8] = heat-plane pointer (i64 per LUMA MB, caller-owned). Slot 8 is read ONLY 2087// under bit12, so every legacy 64-byte rctx block (gates, emitters, old clients) stays valid -- feature off by 2088// default. (rctx[6]/[7] are TAKEN: the trained-nf table + scratch -- a probe-invisible collision caught in port.) 2089// Skip detect = CAVLC bits for the MB <= VC_HEAT_SKIPBITS (coeffs ride the range section, so a skipped MB writes 2090// only its flag bits). Streaks reset on keyframes. Constants are MEASURED (sweep sn{4,8,12}xdiv{2,3}): 4/2 best. 2091const VC_HEAT_STREAK: i64 = 4 2092const VC_HEAT_DIV: i64 = 2 2093const VC_HEAT_SKIPBITS: i64 = 4 2094func 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 { 2095 rctx[0] = rctx[0] | 8 // t8-stream syntax = RICH INTRA (9-mode MPM) on both block sizes, both sides 2096 // RD-auto (bit2): HONORED for LUMA (emode 45 already requests it), STRIPPED for CHROMA (bit4 conservative 2097 // 4x4 plane). 803 debt-eat -- the keyframes-only t8 policy (field 788) was never RD-measured against the MSU 2098 // foundation and stripped the bit2 the caller asked for; on motion/detail P-frames (foreman/bus/mobile: 2099 // 55-92% coded MBs) forcing 4x4 leaves real bitrate on the table. The 8x8-inter path is FULLY BUILT on BOTH 2100 // sides (vc_enc_mb8_inter / vc_dec_mb8_inter) and the decoder already reads the t8 bit + routes P t8==1 -> so 2101 // per-MB RD 4x4-vs-8x8 selection is DECODER-TRANSPARENT (no vcv bump, works in every room like RDOQ). The 2102 // stale-rctx[5] hazard that motivated the old strip is fixed below: the frame fn records the t8-bit position 2103 // in rctx[5] per MB so the block coder's patch always lands on the reserved bit. 2104 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 } 2105 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2106 rc_enc_init(est) 2107 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2108 var bp: i64 = nx_bw_put(buf, 16, keyframe, 1) // CAVLC starts at bit 16 (byte 2 reserved for range_start) 2109 bp = nx_bw_put(buf, bp, 0, 1) // nf bit placeholder (see _t8; vv layer patches luma's) 2110 let BW: i64 = W / 16; let BH: i64 = H / 16 2111 var heatp: *i64 = 0 as *i64 // P2 heat plane: bit12-gated 9th slot (the vv layer clears bit12 for chroma) 2112 if (rctx[0] & VC_MAGIC_4096) != 0 { heatp = rctx[8] as *i64 } 2113 var by: i64 = 0 2114 while by < BH { var bx: i64 = 0 2115 while bx < BW { 2116 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)) 2117 bp = nx_bw_put(buf, bp, lv, 2) 2118 var t8: i64 = 0 2119 if (rctx[0] & 16) == 0 { if keyframe == 1 { 2120 // KEYFRAME t8: flat-intra RD gate (uniform-flatness guard) -- the PROVEN -52%-bytes win on 2121 // join/recovery. P-FRAME t8 is no longer forced off: once the MV is known the block coder's 2122 // RD-auto (bit2, luma) picks 4x4-vs-8x8 per MB and patches the placeholder at rctx[5]. Chroma 2123 // (bit4) stays 4x4 both frame types. Every per-MB t8 bit is explicit on the wire -> the decoder 2124 // already routes it (vc_dec_mb8_inter for P t8==1), so this is decoder-transparent (803). 2125 if lv <= 1 { t8 = vc_mb_t8_ok(cur, W, bx*16, by*16) } 2126 } } 2127 rctx[5] = bp // reserve the t8-bit position for the block coder's P-frame RD-auto patch (803) 2128 bp = nx_bw_put(buf, bp, t8, 1) 2129 let mi: i64 = by * BW + bx 2130 var th: i64 = sad_thresh 2131 if (heatp as i64) != 0 { if keyframe == 0 { if heatp[mi] >= VC_HEAT_STREAK { th = sad_thresh / VC_HEAT_DIV } } } 2132 let hbp0: i64 = bp 2133 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) 2134 if (heatp as i64) != 0 { 2135 if keyframe == 1 { heatp[mi] = 0 } else { 2136 if bp - hbp0 <= VC_HEAT_SKIPBITS { heatp[mi] = heatp[mi] + 1 } else { heatp[mi] = 0 } 2137 } 2138 } 2139 bx = bx + 1 } by = by + 1 } 2140 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8) 2141 let cavlc_end: i64 = (bp + 7) / 8 2142 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8 2143 let rcbuf: *u8 = rctx[3] as *u8; var i: i64 = 0 2144 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 } 2145 return (cavlc_end + rbytes) * 8 2146} 2147// 824 RICH-BAND REGION pair (720p rung B): the FULL rct8 codec (rc + t8-RD + sig-map + partition + heat-AQ) 2148// over MB rows [by0,by1) as a SELF-CONTAINED section -- own rc_enc_init + probs reseed per band, so K bands 2149// are INDEPENDENT (tile-parallel across workers; the context reset costs a few % bits vs whole-frame -- 2150// measured by the gate, it buys the ~4x encode wall-clock that unlocks 720p-class live). Intra never reads 2151// above the band top via the tfy ytop mechanism (same convention as the legacy region pair). Per-band wire = 2152// the whole-frame rct8 layout: [range_start:u16][CAVLC from bit16][range bytes]. Heat plane indexes the 2153// GLOBAL MB grid, so a worker that owns a stable band keeps valid streaks. 2154func 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 { 2155 rctx[0] = rctx[0] | 8 2156 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 } 2157 let est: *i64 = rctx[1] as *i64 2158 let probs: *i64 = rctx[2] as *i64 2159 rc_enc_init(est) 2160 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2161 var bp: i64 = nx_bw_put(buf, 16, keyframe, 1) 2162 bp = nx_bw_put(buf, bp, 0, 1) 2163 let BW: i64 = W / 16 2164 var heatp: *i64 = 0 as *i64 2165 if (rctx[0] & VC_MAGIC_4096) != 0 { heatp = rctx[8] as *i64 } 2166 let ytop2: i64 = (by0 * 16) << 2 2167 var by: i64 = by0 2168 while by < by1 { var bx: i64 = 0 2169 while bx < BW { 2170 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)) 2171 bp = nx_bw_put(buf, bp, lv, 2) 2172 var t8: i64 = 0 2173 if (rctx[0] & 16) == 0 { if keyframe == 1 { 2174 if lv <= 1 { t8 = vc_mb_t8_ok(cur, W, bx*16, by*16) } 2175 } } 2176 rctx[5] = bp 2177 bp = nx_bw_put(buf, bp, t8, 1) 2178 let mi: i64 = by * BW + bx 2179 var th: i64 = sad_thresh 2180 if (heatp as i64) != 0 { if keyframe == 0 { if heatp[mi] >= VC_HEAT_STREAK { th = sad_thresh / VC_HEAT_DIV } } } 2181 let hbp0: i64 = bp 2182 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) 2183 if (heatp as i64) != 0 { 2184 if keyframe == 1 { heatp[mi] = 0 } else { 2185 if bp - hbp0 <= VC_HEAT_SKIPBITS { heatp[mi] = heatp[mi] + 1 } else { heatp[mi] = 0 } 2186 } 2187 } 2188 bx = bx + 1 } by = by + 1 } 2189 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8) 2190 let cavlc_end: i64 = (bp + 7) / 8 2191 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8 2192 let rcbuf: *u8 = rctx[3] as *u8 2193 var i: i64 = 0 2194 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 } 2195 return (cavlc_end + rbytes) * 8 2196} 2197func 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 { 2198 rctx[0] = rctx[0] | 8 2199 let est: *i64 = rctx[1] as *i64 2200 let probs: *i64 = rctx[2] as *i64 2201 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) 2202 rctx[3] = (buf as i64) + cavlc_end 2203 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2204 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8) 2205 let keyframe: i64 = nx_br_get(buf, 16, 1) 2206 var bp: i64 = 18 2207 let BW: i64 = W / 16 2208 let ytop2: i64 = (by0 * 16) << 2 2209 var by: i64 = by0 2210 while by < by1 { var bx: i64 = 0 2211 while bx < BW { 2212 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 2213 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 2214 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) 2215 bx = bx + 1 } by = by + 1 } 2216 return bp 2217} 2218func 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 { 2219 rctx[0] = rctx[0] | 8 // MUST match the encoder's syntax bit 2220 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2221 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) 2222 rctx[3] = (buf as i64) + cavlc_end // the block's coeff decoder reads the range section here 2223 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2224 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8) 2225 let keyframe: i64 = nx_br_get(buf, 16, 1) 2226 var bp: i64 = 18 // bit17 = nf flag (read by the vv layer) 2227 let BW: i64 = W / 16; let BH: i64 = H / 16 2228 var by: i64 = 0 2229 while by < BH { var bx: i64 = 0 2230 while bx < BW { 2231 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 2232 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 2233 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) 2234 bx = bx + 1 } by = by + 1 } 2235 return 0 2236} 2237// ---- B-FRAME pair (vcv-9 VOD generation; 2026-07-14) ----------------------------------------------------- 2238// Bidirectional frame = the measured -43%-residual structural lever (nx_vcodec_bframe_ceiling: past-only SAD 2239// 1102199 -> best-of-{past,future} 623502; naive bi-AVERAGE only -17% -- the win is per-MB DIRECTION SELECTION 2240// on reveal/occlusion, so that is exactly what this codes). Design: ONE direction bit per MB choosing which 2241// reference the ENTIRE existing P-MB coder runs against -- skip/intra-in-P/partition/MV/qpel/t8/sig-map/RDOQ 2242// are all inherited unchanged via the ref pointer, so the B syntax is [lv:2][t8:1][dir:1][P-MB syntax]. A 2243// B-frame is DISPOSABLE (never a reference -> no drift contribution, anchors chain exactly as today's P) and 2244// never a keyframe (no nf). Wire framing identical to rct8 ([range_start:u16][CAVLC@bit16][range section]). 2245// VOD/archival profile: the future ref costs one anchor of latency -- the RTC path never calls these. 2246func 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 { 2247 rctx[0] = rctx[0] | 8 2248 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 } 2249 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2250 rc_enc_init(est) 2251 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2252 var bp: i64 = nx_bw_put(buf, 16, 0, 1) // keyframe=0: a B-frame is never key 2253 bp = nx_bw_put(buf, bp, 0, 1) // nf bit stays 0 (nf is keyframe-only) 2254 let BW: i64 = W / 16; let BH: i64 = H / 16 2255 var by: i64 = 0 2256 while by < BH { var bx: i64 = 0 2257 while bx < BW { 2258 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, bx*16, by*16)) 2259 bp = nx_bw_put(buf, bp, lv, 2) 2260 rctx[5] = bp // reserve the t8-bit position (RD-auto patch, same as rct8 P) 2261 bp = nx_bw_put(buf, bp, 0, 1) 2262 // DIRECTION: integer-ME vs both refs, pick the smaller residual = the measured -43% selector 2263 let sp: i64 = vm_search_q(cur, past, W, H, bx, by, 16, VC_ME_R, mv, qp, blk) 2264 let sf: i64 = vm_search_q(cur, fut, W, H, bx, by, 16, VC_ME_R, mv, qp, blk) 2265 var dir: i64 = 0 2266 if sf < sp { dir = 1 } 2267 bp = nx_bw_put(buf, bp, dir, 1) 2268 var ref: *u8 = past 2269 if dir == 1 { ref = fut } 2270 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) 2271 bx = bx + 1 } by = by + 1 } 2272 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8) 2273 let cavlc_end: i64 = (bp + 7) / 8 2274 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8 2275 let rcbuf: *u8 = rctx[3] as *u8; var i: i64 = 0 2276 while i < rbytes { buf[cavlc_end + i] = rcbuf[i]; i = i + 1 } 2277 return (cavlc_end + rbytes) * 8 2278} 2279func 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 { 2280 rctx[0] = rctx[0] | 8 // MUST match the encoder's syntax bit 2281 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2282 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) 2283 rctx[3] = (buf as i64) + cavlc_end 2284 var ci: i64 = 0; while ci < RC_NCTX8 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2285 rc_dec_init(est, (buf as i64 + cavlc_end) as *u8) 2286 var bp: i64 = 18 // bit16 keyframe(0) + bit17 nf placeholder 2287 let BW: i64 = W / 16; let BH: i64 = H / 16 2288 var by: i64 = 0 2289 while by < BH { var bx: i64 = 0 2290 while bx < BW { 2291 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 2292 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 2293 let dir: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 2294 var ref: *u8 = past 2295 if dir == 1 { ref = fut } 2296 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) 2297 bx = bx + 1 } by = by + 1 } 2298 return 0 2299} 2300// ---- rct9 LEAN-SKIP syntax (vcv-10 candidate; 2026-07-14) ------------------------------------------------ 2301// MEASURED (nx_vcodec_mvbits_probe wire decomposition): the per-MB CAVLC header [lv:2][t8:1][skip:1] costs 2302// 4 bits on EVERY MB even when skipped -- ~2240 skip MBs/frame x 4 bits ~= 1.1KB/frame ~= 8-13% of P bytes 2303// (worst at LOW bitrate = the external-gap shape), and ~94% of a typical chroma stream. x264 pays ~0.2 bits 2304// per skip via a CABAC context. rct9 P-MB layout: ONE rc-context-coded skip flag (ctx = left_skip+top_skip, 2305// probs[24..26] adaptive, on TOP of the RC_NCTX8 residual contexts); skip => recon copy, NOTHING else on the 2306// wire; coded => [lv:2][t8:1] + the UNCHANGED block payload (still leads with its vestigial in-payload skip 2307// bit, forced 0 via sad_thresh=0 -- 1 bit x coded MBs only, vs forking the 300-line block coder). The RD-skip 2308// band trial (emode bit11) moves HERE: est/probs/bp snapshot -> trial-code -> J -> commit/rewind, the exact 2309// _e idiom on the same 48-i64 scr slab (16 est + 24+3 probs = 43 <= 48). Keyframes stay plain rct8 (nothing 2310// to lean out). ⚠ship note: skip-row scratch is sys_mmap here (bench-native); the wasm build needs a slab. 2311const VC_SKIPCTX: i64 = 24 2312func vc_mbcopy(recon: *u8, prev: *u8, W: i64, cx: i64, cy: i64) -> i64 { 2313 var y: i64 = 0 2314 while y < 16 { var x: i64 = 0 2315 while x < 16 { recon[(cy+y)*W + cx+x] = prev[(cy+y)*W + cx+x]; x = x + 1 } y = y + 1 } 2316 return 0 } 2317func vc_mbssd(a: *u8, b: *u8, W: i64, cx: i64, cy: i64) -> i64 { 2318 var s: i64 = 0 2319 var y: i64 = 0 2320 while y < 16 { var x: i64 = 0 2321 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 } 2322 return s } 2323func 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 { 2324 rctx[0] = rctx[0] | 8 2325 if (rctx[0] & 16) != 0 { rctx[0] = (rctx[0] | 4) - 4 } 2326 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2327 rc_enc_init(est) 2328 var ci: i64 = 0; while ci < RC_NCTX8 + 3 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2329 var bp: i64 = nx_bw_put(buf, 16, 0, 1) // keyframe=0 always (keys ride rct8) 2330 bp = nx_bw_put(buf, bp, 0, 1) // nf placeholder (never set: non-key) 2331 let BW: i64 = W / 16; let BH: i64 = H / 16 2332 // top-neighbour skip row: u8 slab at rctx[4]+5440 (past RD-skip scr 5008..5392 + dmv 5392..5408; the 2333 // wasm t8c region ends ~5504 -> ENVELOPE BW<=60 i.e. W<=960, DECLARED; wasm ceiling is 640 -> 40B used). 2334 // NEVER sys_mmap in frame code: wasm sys_mmap is a 0-stub -> the pointer aliases address 0 (the live 2335 // partition-MV zeroing bug class). Slab is dirty -> explicit zero (mmap's zero-init did this before). 2336 let sktop: *u8 = (rctx[4] + VC_MAGIC_5440) as *u8 2337 var zk: i64 = 0 2338 while zk < BW { sktop[zk] = 0 as u8; zk = zk + 1 } 2339 // vcv-10 MVD-median: arm bit13 + reset the caller-provided MV row-plane (rctx[9], REQUIRED for rct9) 2340 rctx[0] = rctx[0] | VC_MAGIC_8192 2341 vc_mvplane_row0(rctx[9] as *i64, BW) 2342 let rdsk: i64 = (rctx[0] >> 11) & 1 2343 let scr: *i64 = (rctx[4] + VC_MAGIC_5008) as *i64 2344 let rcbuf: *u8 = rctx[3] as *u8 2345 var by: i64 = 0 2346 while by < BH { var bx: i64 = 0 2347 var skleft: i64 = 0 2348 while bx < BW { 2349 let cx: i64 = bx*16; let cy: i64 = by*16 2350 let lv: i64 = vc_aq_level(vc_mb_mad(cur, W, cx, cy)) 2351 let aqp: i64 = vc_aq_qp(qp, lv) 2352 let zs: i64 = vm_sad_zero(cur, prev, W, bx, by, 16) 2353 let ctx: i64 = VC_SKIPCTX + skleft + (sktop[bx] as i64) 2354 var dosk: i64 = 0 2355 var trial: i64 = 0 2356 if rdsk == 1 { if zs >= sad_thresh/4 { if zs <= sad_thresh*8 { trial = 1 } } } 2357 if trial == 0 { if zs <= sad_thresh { dosk = 1 } } 2358 var committed: i64 = 0 2359 if trial == 1 { 2360 var i: i64 = 0 2361 while i < 8 { scr[i] = est[i]; i = i + 1 } 2362 i = 0 2363 while i < RC_NCTX8 + 3 { scr[16 + i] = probs[i]; i = i + 1 } 2364 let r5: i64 = rctx[5] 2365 let rc0: i64 = vc_rdskip_len(est, scr, rcbuf) 2366 rc_enc_ctx(est, rcbuf, probs, ctx, 0) // CODE arm: skip=0 2367 var bpt: i64 = nx_bw_put(buf, bp, lv, 2) 2368 rctx[5] = bpt 2369 bpt = nx_bw_put(buf, bpt, 0, 1) 2370 bpt = vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, aqp, 0, 0 - sad_thresh, buf, bpt, blk, mv, tf, rctx) 2371 let rc1: i64 = vc_rdskip_len(est, scr, rcbuf) 2372 let dcode: i64 = vc_mbssd(recon, cur, W, cx, cy) 2373 let dskip: i64 = vc_mbssd(prev, cur, W, cx, cy) 2374 let jc: i64 = 32*dcode + qp*qp*((bpt - bp) + (rc1 - rc0)) 2375 let js: i64 = 32*dskip + qp*qp 2376 if jc < js { 2377 bp = bpt; skleft = 0; sktop[bx] = 0 as u8; committed = 1 2378 } else { 2379 i = 0 2380 while i < 8 { est[i] = scr[i]; i = i + 1 } 2381 i = 0 2382 while i < RC_NCTX8 + 3 { probs[i] = scr[16 + i]; i = i + 1 } 2383 rctx[5] = r5 2384 // undo the trial CODE arm's MV-plane write (this MB ends SKIP = contributes (0,0)); 2385 // without this the encoder plane diverges from the decoder's -> wire corruption 2386 let mvpu: *i64 = rctx[9] as *i64 2387 mvpu[BW + bx] = VC_MVPACK0 2388 dosk = 1 2389 } 2390 } 2391 if committed == 0 { 2392 if dosk == 1 { 2393 rc_enc_ctx(est, rcbuf, probs, ctx, 1) // skip: ONE context-coded flag, nothing else 2394 vc_mbcopy(recon, prev, W, cx, cy) 2395 skleft = 1; sktop[bx] = 1 as u8 2396 } else { 2397 rc_enc_ctx(est, rcbuf, probs, ctx, 0) 2398 bp = nx_bw_put(buf, bp, lv, 2) 2399 rctx[5] = bp 2400 bp = nx_bw_put(buf, bp, 0, 1) 2401 bp = vc_enc_block_packed_i(cur, prev, recon, W, H, bx, by, aqp, 0, 0 - sad_thresh, buf, bp, blk, mv, tf, rctx) 2402 skleft = 0; sktop[bx] = 0 as u8 2403 } 2404 } 2405 bx = bx + 1 } 2406 vc_mvplane_nextrow(rctx[9] as *i64, BW) 2407 by = by + 1 } 2408 let rbytes: i64 = rc_enc_flush(est, rctx[3] as *u8) 2409 let cavlc_end: i64 = (bp + 7) / 8 2410 buf[0] = (cavlc_end & 0xff) as u8; buf[1] = ((cavlc_end >> 8) & 0xff) as u8 2411 let rcb2: *u8 = rctx[3] as *u8; var k: i64 = 0 2412 while k < rbytes { buf[cavlc_end + k] = rcb2[k]; k = k + 1 } 2413 return (cavlc_end + rbytes) * 8 2414} 2415func 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 { 2416 rctx[0] = rctx[0] | 8 2417 let est: *i64 = rctx[1] as *i64; let probs: *i64 = rctx[2] as *i64 2418 let cavlc_end: i64 = (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) 2419 let rsec: *u8 = ((buf as i64) + cavlc_end) as *u8 2420 rctx[3] = rsec as i64 2421 var ci: i64 = 0; while ci < RC_NCTX8 + 3 { probs[ci] = VC_MAGIC_2048; ci = ci + 1 } 2422 rc_dec_init(est, rsec) 2423 var bp: i64 = 18 2424 let BW: i64 = W / 16; let BH: i64 = H / 16 2425 // u8 slab, same placement + envelope as the encoder (MUST mirror: the skip contexts are syntax) 2426 let sktop: *u8 = (rctx[4] + VC_MAGIC_5440) as *u8 2427 var zk: i64 = 0 2428 while zk < BW { sktop[zk] = 0 as u8; zk = zk + 1 } 2429 // vcv-10 MVD-median twin: arm bit13 + reset the MV row-plane (rctx[9], REQUIRED for rct9) 2430 rctx[0] = rctx[0] | VC_MAGIC_8192 2431 vc_mvplane_row0(rctx[9] as *i64, BW) 2432 var by: i64 = 0 2433 while by < BH { var bx: i64 = 0 2434 var skleft: i64 = 0 2435 while bx < BW { 2436 let ctx: i64 = VC_SKIPCTX + skleft + (sktop[bx] as i64) 2437 let sk: i64 = rc_dec_ctx(est, rsec, probs, ctx) 2438 if sk == 1 { 2439 vc_mbcopy(recon, prev, W, bx*16, by*16) 2440 skleft = 1; sktop[bx] = 1 as u8 2441 } else { 2442 let lv: i64 = nx_br_get(buf, bp, 2); bp = bp + 2 2443 let t8: i64 = nx_br_get(buf, bp, 1); bp = bp + 1 2444 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) 2445 skleft = 0; sktop[bx] = 0 as u8 2446 } 2447 bx = bx + 1 } 2448 vc_mvplane_nextrow(rctx[9] as *i64, BW) 2449 by = by + 1 } 2450 return 0 2451} 2452// ---- TILE-PARALLEL primitive (task #47 rung 1) ---------------------------------------------------------- 2453// Encode/decode ONLY macroblock-rows [by0, by1) as a SELF-CONTAINED tile: intra prediction is clamped so it 2454// never reads above by0 (the tfy pack carries the tile top), and motion reads the full PREV frame (already 2455// reconstructed + available on both sides). So K calls over disjoint row-ranges have ZERO shared writes and 2456// ZERO cross-tile reads of the CURRENT frame -> each runs on its own core/thread now, its own GPU workgroup 2457// later. This is the architecture that scales toward 4K@60 (a serial frame loop never can). 2458func 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 { 2459 var bp: i64 = nx_bw_put(buf, 0, keyframe, 1) 2460 let BW: i64 = W / 16 2461 let tfy: i64 = tf + ((by0 * 16) << 2) // bit1 (t8) stays 0: bands stay 4x4 until the t8 rung proves out there 2462 var by: i64 = by0 2463 while by < by1 { var bx: i64 = 0 2464 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 } 2465 return bp 2466} 2467func 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 { 2468 let keyframe: i64 = nx_br_get(buf, 0, 1) 2469 var bp: i64 = 1 2470 let BW: i64 = W / 16 2471 let tfy: i64 = tf + ((by0 * 16) << 2) // bit1 (t8) stays 0: bands stay 4x4 until the t8 rung proves out there 2472 var by: i64 = by0 2473 while by < by1 { var bx: i64 = 0 2474 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 } 2475 return bp 2476}