From 11a055240fc01643673e9abbb422ddb974a9beb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:33:32 +0300 Subject: [PATCH] U2: delete scripts no crate, tool, cargo config or DONE.md names (dead probes, one-off gens, duplicate cmp422-ffmpeg, stale lane harnesses); keep fixtures.sh chain, remote-run.sh and anything referenced by a kept file --- scripts/aac-tables/aacprobe.py | 132 ------------ scripts/aac-tables/sbrnoise.py | 111 ---------- scripts/aac-tables/sbrprobe.py | 231 --------------------- scripts/aac-tables/swb.py | 119 ----------- scripts/aac-tables/tns.py | 34 ---- scripts/av1-stage-suite.sh | 124 ------------ scripts/av1-suite-preflight.sh | 248 ----------------------- scripts/bench-benchaudio.sh | 237 ---------------------- scripts/bench-benchhw.sh | 173 ---------------- scripts/bench-benchp1-clips.sh | 53 ----- scripts/bench-benchrest.sh | 246 ----------------------- scripts/bench-rows-clips.sh | 42 ---- scripts/bench-rows-parity.py | 22 -- scripts/bench-rows-vp8.rs | 60 ------ scripts/bench-rows.sh | 128 ------------ scripts/bench_hevc_enc.sh | 20 -- scripts/changed-crates.sh | 48 ----- scripts/cmp422-ffmpeg.py | 313 ----------------------------- scripts/cmpff.py | 1 - scripts/flipctl-422.py | 141 ------------- scripts/gen-aac-layouts.sh | 19 -- scripts/gen-bitmap-sub-fixtures.py | 93 --------- scripts/gen-bitmap-sub-fixtures.sh | 22 -- scripts/gen-mp4-parity-corpus.sh | 40 ---- scripts/h264-bd.sh | 18 -- scripts/h264-speed.sh | 20 -- scripts/h264-sweep.sh | 8 - scripts/hevc-intra-bd.sh | 36 ---- scripts/hevc-preset-quick.sh | 9 - scripts/hevc-rc-bdrate.sh | 66 ------ scripts/hevc-speed-sweep.sh | 36 ---- scripts/hevc-thread-bench.sh | 72 ------- scripts/lr-sgr-pin-harness.c | 113 ----------- scripts/mp3-tables/mp3probe.py | 211 ------------------- scripts/mp3-tables/probe_engine.py | 54 ----- scripts/raw_to_y4m.py | 63 ------ scripts/run422-ffmpeg.py | 54 ----- scripts/shape422-diff.py | 28 --- scripts/stress-mp4-fixtures.sh | 33 --- scripts/vp9-bench.sh | 31 --- 40 files changed, 3509 deletions(-) delete mode 100644 scripts/aac-tables/aacprobe.py delete mode 100644 scripts/aac-tables/sbrnoise.py delete mode 100644 scripts/aac-tables/sbrprobe.py delete mode 100644 scripts/aac-tables/swb.py delete mode 100644 scripts/aac-tables/tns.py delete mode 100755 scripts/av1-stage-suite.sh delete mode 100755 scripts/av1-suite-preflight.sh delete mode 100755 scripts/bench-benchaudio.sh delete mode 100755 scripts/bench-benchhw.sh delete mode 100755 scripts/bench-benchp1-clips.sh delete mode 100755 scripts/bench-benchrest.sh delete mode 100755 scripts/bench-rows-clips.sh delete mode 100644 scripts/bench-rows-parity.py delete mode 100644 scripts/bench-rows-vp8.rs delete mode 100755 scripts/bench-rows.sh delete mode 100755 scripts/bench_hevc_enc.sh delete mode 100755 scripts/changed-crates.sh delete mode 100755 scripts/cmp422-ffmpeg.py delete mode 120000 scripts/cmpff.py delete mode 100755 scripts/flipctl-422.py delete mode 100755 scripts/gen-aac-layouts.sh delete mode 100644 scripts/gen-bitmap-sub-fixtures.py delete mode 100755 scripts/gen-bitmap-sub-fixtures.sh delete mode 100755 scripts/gen-mp4-parity-corpus.sh delete mode 100755 scripts/h264-bd.sh delete mode 100755 scripts/h264-speed.sh delete mode 100755 scripts/h264-sweep.sh delete mode 100755 scripts/hevc-intra-bd.sh delete mode 100644 scripts/hevc-preset-quick.sh delete mode 100755 scripts/hevc-rc-bdrate.sh delete mode 100755 scripts/hevc-speed-sweep.sh delete mode 100755 scripts/hevc-thread-bench.sh delete mode 100644 scripts/lr-sgr-pin-harness.c delete mode 100644 scripts/mp3-tables/mp3probe.py delete mode 100644 scripts/mp3-tables/probe_engine.py delete mode 100755 scripts/raw_to_y4m.py delete mode 100755 scripts/run422-ffmpeg.py delete mode 100644 scripts/shape422-diff.py delete mode 100755 scripts/stress-mp4-fixtures.sh delete mode 100755 scripts/vp9-bench.sh diff --git a/scripts/aac-tables/aacprobe.py b/scripts/aac-tables/aacprobe.py deleted file mode 100644 index 7d6852da..00000000 --- a/scripts/aac-tables/aacprobe.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python3 -"""Black-box derivation of the ISO/IEC 14496-3 AAC-LC Huffman codebooks. - -Clean-room: no AAC implementation source is read. The only oracle is ffmpeg's -`aac` decoder driven as a black box. We synthesise ADTS frames whose spectral -payload is a bit string we choose, decode them, invert the (windowed) MDCT to -recover the quantised spectrum, and learn the prefix code from bits -> tuple. - -Frame shape (mono, 48 kHz, ONLY_LONG, sine window): - SCE(3)=0 tag(4)=0 global_gain(8) ics_info section_data sf_data flags spectral -max_sfb=2 gives one section of 8 coefficients, so the spectral field always -outlives the probe prefix and the trailing all-ones run lands on an END element -(id 7 = 0b111). The ones run is bounded -- a long 0xFF tail makes ffmpeg's ADTS -parser resync on a false 0xFFF sync word. -""" - -import numpy as np -import subprocess -import os - -SR = 48000 -N = 1024 -ONES_RUN = 96 # bits of `1` filler after the probe, then zero padding - - -class BitW: - def __init__(self): - self.bits = [] - - def w(self, val, n): - for i in range(n - 1, -1, -1): - self.bits.append((val >> i) & 1) - return self - - def wbits(self, seq): - self.bits.extend(seq) - return self - - def __len__(self): - return len(self.bits) - - def pack(self, total_bytes=None, pad=0): - if total_bytes is None: - total_bytes = (len(self.bits) + 7) // 8 - b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8] - out = bytearray() - for i in range(0, len(b), 8): - v = 0 - for bit in b[i : i + 8]: - v = (v << 1) | bit - out.append(v) - return bytes(out) - - -def adts(payload: bytes, sf_index=3, chan_cfg=1) -> bytes: - h = BitW() - h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1) # sync, MPEG-4, layer, no CRC - h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3) # AAC-LC - h.w(0, 1).w(0, 1).w(0, 1).w(0, 1) # original, home, copyright id/start - h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2) - return h.pack(7) + payload - - -def probe_frame(cb, sf_bits, probe_bits, gg=200, max_sfb=2): - w = BitW() - w.w(0, 3).w(0, 4) # SCE, instance tag - w.w(gg, 8) - w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine window - w.w(cb, 4).w(max_sfb, 5) # one section covering every band - w.wbits(sf_bits) - w.w(0, 3) # pulse / tns / gain-control absent - w.wbits(probe_bits).wbits([1] * ONES_RUN) - return adts(w.pack(pad=0)) - - -def silent_frame(): - w = BitW() - w.w(0, 3).w(0, 4).w(128, 8) - w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1) # max_sfb = 0: nothing coded - w.w(0, 3).w(7, 3) # flags, END - return adts(w.pack(4)) - - -# --- MDCT read-back --------------------------------------------------------- - -_PINV = None - - -def recover(block, ncoef=12): - """Quantised-spectrum-proportional coefficients from 2048 output samples.""" - global _PINV - if _PINV is None: - cache = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pinv.npy") - if os.path.exists(cache): - _PINV = np.load(cache) - else: - n = np.arange(2 * N) - k = np.arange(N) - m = np.cos(2 * np.pi / N * np.outer(n + 0.5 + N / 2, k + 0.5)) - win = np.sin(np.pi / (2 * N) * (n + 0.5)) - _PINV = np.linalg.pinv(m * win[:, None])[:32].astype(np.float64) - np.save(cache, _PINV) - return _PINV[:ncoef] @ block - - -def decode_probes(frames, tag="p"): - """One 2048-sample block per probe frame, or None when ffmpeg refused it.""" - d = os.path.dirname(os.path.abspath(__file__)) - src = os.path.join(d, f"probe-{tag}.aac") - sil = silent_frame() - with open(src, "wb") as f: - f.write(sil + b"".join(fr + sil + sil for fr in frames)) - raw = subprocess.run( - ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"], - capture_output=True, - ) - pcm = np.frombuffer(raw.stdout, dtype="= 15: - w.w(15, 4) - w.w(cnt - 15 + 1, 8) - else: - w.w(cnt, 4) - start = len(w) - w.w(13, 4) - w.wbits(body.bits) - while len(w) - start < cnt * 8: - w.w(0, 1) - w.w(7, 3) - frames.append(C.P.adts(w.pack(pad=0), C.SF_INDEX)) - frames.append(C.P.silent(C.SF_INDEX)) - return frames - - -def band_power(pcm, lo_hz, hi_hz, skip=6, n_fft=8192): - start = skip * 1024 - seg = pcm[start : start + n_fft] - if len(seg) < n_fft: - seg = np.pad(seg, (0, n_fft - len(seg))) - spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2 - freqs = np.fft.rfftfreq(n_fft, 1 / RATE) - mask = (freqs >= lo_hz) & (freqs < hi_hz) - return float(np.sum(spec[mask])) - - -if __name__ == "__main__": - cfg0, tables0 = F.one_band_header() - lo, hi = 19 * RATE / 128, 23 * RATE / 128 - print(f"target region {lo:.1f}-{hi:.1f} Hz, RAW_NOISE bits={C.T.RAW_NOISE} (q range 0..{2**C.T.RAW_NOISE - 1})") - - print("\n== value-engagement check: envelope raw sweep (fixed q_q) must move power by orders ==") - for e in (10, 40, 60): - cfg = dict(cfg0) - frames = noise_stream(cfg, tables0, 20, 30, env=e) - pcm, err = C.decode(frames, f"env_check{e}") - pwr = band_power(pcm, lo, hi) - print(f" env0={e} (q_q=30, minimal noise) pwr={pwr:.4e} err={err.strip()[:60]!r}") - - print("\n== Task 1: noise-floor raw (q_q) sweep, fixed envelope ==") - qs = list(range(0, 31, 3)) - pwrs = {} - for q in qs: - cfg = dict(cfg0) - frames = noise_stream(cfg, tables0, 20, q) - pcm, err = C.decode(frames, f"q{q}") - pwr = band_power(pcm, lo, hi) - pwrs[q] = pwr - print(f" q_q={q:2d} pwr={pwr:.6e} err={err.strip()[:80]!r}") - - baseline = pwrs[qs[-1]] - print(f"\nbaseline (q_q={qs[-1]}, minimal noise) pwr={baseline:.6e}") - print("q_q, noise_energy=pwr-baseline, log2(noise_energy)") - fit_x, fit_y = [], [] - for q in qs[:-1]: - n = pwrs[q] - baseline - if n > 0: - l2 = np.log2(n) - print(f" {q:2d} {n:.6e} {l2:.4f}") - fit_x.append(q) - fit_y.append(l2) - else: - print(f" {q:2d} {n:.6e} (non-positive, skipped)") - if len(fit_x) >= 2: - slope, intercept = np.polyfit(fit_x, fit_y, 1) - print(f"\nfit: log2(noise_energy) = {slope:.4f} * q_q + {intercept:.4f}") - print(f"(spec/ours form: log2(noise_energy) = -1*q_q + 6 => slope~-1, intercept~6 expected if law matches)") diff --git a/scripts/aac-tables/sbrprobe.py b/scripts/aac-tables/sbrprobe.py deleted file mode 100644 index 056d62a6..00000000 --- a/scripts/aac-tables/sbrprobe.py +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env python3 -"""Black-box probing rig for the SBR (HE-AAC v1) tool. WORK IN PROGRESS. - -Same method as the AAC tables: the vehicle is an ADTS access unit whose core is -an AAC-LC frame of exactly known bit length -- so the FIL element carrying the -SBR payload starts at a position we control -- followed by a FIL element holding -an sbr_extension_data built field by field. A reference decoder is the only -oracle. - -State, so a successor does not repeat the ground already covered: - -* The core writer is correct: `sce_core` frames decode clean at every max_sfb, - and the FIL length accounting is right (the reference decoder reads the - element without complaint about its framing). -* `sbr_header` is parsed by the reference decoder -- `start_freq=14` comes back - as "Invalid n_master: 0", which is a semantic complaint about a field it read, - not a framing one. -* `sbr_data` is NOT yet accepted: the decoder consumes 16 bits more than this - writer emits ("Expected to read 7 SBR bytes actually read 9"), constant across - start_freq, stop_freq and freq_res. The gap is most likely the envelope - Huffman reads for bands beyond the first, whose codebooks are still unknown -- - which is the bootstrap problem: only the first envelope value of a - frequency-delta frame is raw (6 or 7 bits), every later one is coded. -* The decoder reports the exact byte count its parser consumed, which is a - precise, cheap observable: that is the instrument to bootstrap the ten SBR - codebooks by the same prefix walk the AAC tables came from. -""" - -import os -import re -import subprocess -import sys - -import numpy as np - -TABLES = "/home/user/Documents/Code/Rust/edith_codecs/crates/ec-aac/src/tables.rs" -SR_TABLE = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350] - - -def load_table(name): - src = open(TABLES).read() - body = re.search(rf"static {name}: \[\(u8, u32\); \d+\] = \[(.*?)\n\];", src, re.S).group(1) - return [tuple(int(x) for x in m) for m in re.findall(r"\((\d+),\s*(\d+)\)", body)] - - -def load_swb(kind): - src = open(TABLES).read() - body = re.search(rf"pub static SWB_{kind}: \[&\[u16\]; 12\] = \[(.*?)\n\];", src, re.S).group(1) - return [[int(x) for x in re.findall(r"\d+", row)] for row in re.findall(r"&\[([^\]]*?)\]", body, re.S)] - - -HCB3 = load_table("HCB3") -HCB_SF = load_table("HCB_SF") -SWB_LONG = load_swb("LONG") - - -class BitW: - def __init__(self): - self.bits = [] - - def w(self, val, n): - for i in range(n - 1, -1, -1): - self.bits.append((val >> i) & 1) - return self - - def wbits(self, seq): - self.bits.extend(seq) - return self - - def __len__(self): - return len(self.bits) - - def pack(self, total_bytes=None, pad=0): - if total_bytes is None: - total_bytes = (len(self.bits) + 7) // 8 - b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8] - out = bytearray() - for i in range(0, len(b), 8): - v = 0 - for bit in b[i : i + 8]: - v = (v << 1) | bit - out.append(v) - return bytes(out) - - -def adts(payload, sf_index, chan_cfg=1): - h = BitW() - h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1) - h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3) - h.w(0, 1).w(0, 1).w(0, 1).w(0, 1) - h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2) - return h.pack(7) + payload - - -def tuple_index_u(vals, lav, dim): - span = lav + 1 - idx = 0 - for i in range(dim): - idx = idx * span + min(abs(vals[i]), lav) - return idx - - -def sce_core(w, sf_index, max_sfb, gain=200, quad=(2, 0, 2, 2)): - """A single_channel_element of exactly known length: codebook 3 throughout, - the same tuple in every position, so the bit cost is arithmetic.""" - swb = SWB_LONG[sf_index] - max_sfb = min(max_sfb, len(swb) - 1) - w.w(0, 3).w(0, 4) # SCE, instance tag - w.w(gain, 8) - w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine - w.w(3, 4) # one section, codebook 3 - left = max_sfb - while left >= 31: - w.w(31, 5) - left -= 31 - w.w(left, 5) - for _ in range(max_sfb): - w.w(HCB_SF[60][1], HCB_SF[60][0]) # delta 0 - w.w(0, 3) # pulse / tns / gain-control absent - length, code = HCB3[tuple_index_u(quad, 2, 4)] - signs = [1 for v in quad if v != 0] - for _ in range(swb[max_sfb] // 4): - w.w(code, length) - for _ in signs: - w.w(0, 1) # positive - return w - - -def sbr_payload(cfg): - """sbr_extension_data for one single channel element, from `cfg`.""" - s = BitW() - s.w(1, 1) # bs_header_flag - s.w(cfg["amp_res"], 1) - s.w(cfg["start_freq"], 4) - s.w(cfg["stop_freq"], 4) - s.w(cfg["xover_band"], 3) - s.w(0, 2) # bs_reserved - s.w(1, 1) # bs_header_extra_1 - s.w(1, 1) # bs_header_extra_2 - s.w(cfg["freq_scale"], 2) - s.w(cfg["alter_scale"], 1) - s.w(cfg["noise_bands"], 2) - s.w(cfg["limiter_bands"], 2) - s.w(cfg["limiter_gains"], 2) - s.w(cfg["interpol_freq"], 1) - s.w(cfg["smoothing_mode"], 1) - # sbr_single_channel_element - s.w(0, 1) # bs_data_extra - # sbr_grid: FIXFIX with one envelope - s.w(0, 2) # bs_frame_class = FIXFIX - s.w(0, 2) # bs_num_env_raw -> num_env = 1 - s.w(cfg["freq_res"], 1) - # sbr_dtdf - s.w(0, 1) # bs_df_env[0] = frequency direction - s.w(0, 1) # bs_df_noise[0] - # sbr_invf: one mode per noise band - for _ in range(cfg["n_q"]): - s.w(cfg["invf"], 2) - # sbr_envelope: first value raw, the rest would need Huffman - s.w(cfg["env0"], 6 if cfg["amp_res"] else 7) - for value, (length, code) in cfg.get("env_deltas", []): - s.w(code, length) - # sbr_noise: first value raw, the rest Huffman - s.w(cfg["noise0"], 5) - for value, (length, code) in cfg.get("noise_deltas", []): - s.w(code, length) - # bs_add_harmonic_flag - if cfg.get("harmonics") is None: - s.w(0, 1) - else: - s.w(1, 1) - for bit in cfg["harmonics"]: - s.w(bit, 1) - s.w(0, 1) # bs_extended_data - return s - - -def frame(cfg, sf_index=7, max_sfb=20): - w = BitW() - sce_core(w, sf_index, max_sfb, gain=cfg.get("gain", 200)) - body = sbr_payload(cfg) - # extension_type nibble plus the payload, padded to whole bytes - payload_bits = 4 + len(body) - count = (payload_bits + 7) // 8 - w.w(6, 3) # FIL - if count >= 15: - w.w(15, 4) - w.w(count - 15 + 1, 8) - else: - w.w(count, 4) - start = len(w) - w.w(13, 4) # EXT_SBR_DATA - w.wbits(body.bits) - while len(w) - start < count * 8: - w.w(0, 1) - w.w(7, 3) # END - return adts(w.pack(pad=0), sf_index) - - -def silent(sf_index): - w = BitW() - w.w(0, 3).w(0, 4).w(128, 8) - w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1) - w.w(0, 3).w(7, 3) - return adts(w.pack(4), sf_index) - - -def decode(frames, sf_index, tag=None): - """(samples, stderr) from ffmpeg for a stream of frames.""" - src = f"/tmp/sbrprobe-{tag or os.getpid()}.aac" - with open(src, "wb") as f: - f.write(b"".join(frames)) - r = subprocess.run( - ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"], - capture_output=True, - ) - os.remove(src) - return np.frombuffer(r.stdout, dtype="= esc: - w.w(esc, bits) - left -= esc - w.w(left, bits) - - -def frame_long(k, sf_index): - w = A.BitW() - w.w(0, 3).w(0, 4).w(200, 8) - w.w(0, 1).w(0, 2).w(0, 1).w(k, 6).w(0, 1) - w.w(3, 4) - sect_len(w, k, 5) - w.wbits([0] * k) # the one-bit delta-zero scalefactor codeword per band - w.w(0, 3) - w.wbits([1] * 6000) - return A.adts(w.pack(pad=0), sf_index=sf_index) - - -def frame_short(k, sf_index): - w = A.BitW() - w.w(0, 3).w(0, 4).w(200, 8) - w.w(0, 1).w(2, 2).w(0, 1).w(k, 4).w(0x7F, 7) # EIGHT_SHORT, one group of 8 - w.w(3, 4) - sect_len(w, k, 3) - w.wbits([0] * k) - w.w(0, 3) - w.wbits([1] * 6000) - return A.adts(w.pack(pad=0), sf_index=sf_index) - - -def silent(sf_index): - w = A.BitW() - w.w(0, 3).w(0, 4).w(128, 8) - w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1) - w.w(0, 3).w(7, 3) - return A.adts(w.pack(4), sf_index=sf_index) - - -def blocks(frames, sf_index): - src = f"swb-{os.getpid()}.aac" - sil = silent(sf_index) - with open(src, "wb") as f: - f.write(sil + b"".join(fr + sil + sil for fr in frames)) - raw = subprocess.run( - ["ffmpeg", "-v", "quiet", "-i", src, "-f", "f32le", "-ac", "1", "-"], - capture_output=True, - ) - pcm = np.frombuffer(raw.stdout, dtype=" 1e-3)[0] - if len(nz) == 0: - break - out.append(int(nz.max()) + 1) - return out - - -def short_offsets(sf_index): - out = [] - got = blocks([frame_short(k, sf_index) for k in range(1, 17)], sf_index) - for blk in got: - if blk is None: - break - mag = np.abs(np.fft.rfft(blk * np.hanning(2048))) - top = np.where(mag > mag.max() * 3e-4)[0].max() - out.append(top / 8.0) - return out - - -if __name__ == "__main__": - out = {} - for idx in range(0, 12): - lo = long_offsets(idx) - sh = short_offsets(idx) - out[idx] = {"long": lo, "short": sh} - print(idx, "long", len(lo), lo, file=sys.stderr) - print(idx, "short", [round(v, 1) for v in sh], file=sys.stderr) - json.dump(out, open("swb.json", "w")) diff --git a/scripts/aac-tables/tns.py b/scripts/aac-tables/tns.py deleted file mode 100644 index 7b521452..00000000 --- a/scripts/aac-tables/tns.py +++ /dev/null @@ -1,34 +0,0 @@ -import swb, aacprobe as A, sys -def frame_tns(max_sfb, n_filt, coef_res, length, order, direction, compress, coefs, sf_index=3): - w=A.BitW() - w.w(0,3).w(0,4).w(200,8) - w.w(0,1).w(0,2).w(0,1).w(max_sfb,6).w(0,1) - w.w(3,4); swb.sect_len(w,max_sfb,5) - w.wbits([0]*max_sfb) - w.w(0,1) # pulse_data_present - w.w(1,1) # tns_data_present - w.w(n_filt,2) - if n_filt: - w.w(coef_res,1) - for f in range(n_filt): - w.w(length,6); w.w(order,5) - if order: - w.w(direction,1); w.w(compress,1) - bits = coef_res + 3 - compress - for c in coefs[:order]: - w.w(c & ((1< --tree [--tarball ] -# [--skip ]... [-- command...] -# -# Defaults: no cargo-test-arg means -# cargo test -p ec-av1 --lib -- --test-threads=1 -# -# Env (all passed to the unit): -# CARGO_TARGET_DIR, TMPDIR defaulted under $HOME/gates/-* -# EC_AV1_REQUIRE_AOMENC=1, EC_AV1_REQUIRE_FFMPEG=1, EC_REQUIRE_FIXTURES=1 -# SUITE_RUNG_WAIVER= required to accept rung_check=not-run -# -# Exit: 0 the unit was started; non-zero the preflight BLOCKED and no unit -# exists. `systemctl --user is-active -suite` is the only thing that -# starts a suite, so a blocked staging leaves the host idle on purpose. - -set -uo pipefail - -NAME="" -TREE="" -TARBALL="" -declare -a SKIPS=() -declare -a CMD=() -DRY_RUN=0 -while [ $# -gt 0 ]; do - case "$1" in - --name) NAME=$2; shift 2 ;; - --tree) TREE=$2; shift 2 ;; - --tarball) TARBALL=$2; shift 2 ;; - --skip) SKIPS+=(--skip "$2"); shift 2 ;; - --dry-run) DRY_RUN=1; shift ;; - --) shift; CMD=("$@"); break ;; - -h|--help) sed -n '2,28p' "$0"; exit 0 ;; - *) echo "unknown argument: $1" >&2; exit 2 ;; - esac -done -[ -n "$NAME" ] && [ -n "$TREE" ] || { echo "usage: --name --tree [--tarball ] [--skip ]... [-- cmd...]" >&2; exit 2; } -[ -d "$TREE" ] || { echo "no such tree: $TREE" >&2; exit 2; } - -# 1. The staged tree needs a real git checkout with a POPULATED index. A bare -# `git init` leaves the index empty and pin-gate-audit.py's -# `git ls-files --error-unmatch` then reports every pin as uncommitted — a -# staging artefact indistinguishable from the defect invariant 4 exists to -# catch (wave-3c-b correction). Test rev-parse, not `[ -d .git ]`: a worktree -# copy and a `git archive` untar both leave a `.git` FILE. -git -C "$TREE" rev-parse --git-dir >/dev/null 2>&1 || { - echo "staging defect: $TREE is not a git checkout; memguard-runner.sh dies with exit 128" >&2 - exit 2 -} -if [ -z "$(git -C "$TREE" ls-files | head -1)" ]; then - echo "staging defect: $TREE has an empty index; run git add -A after the untar" >&2 - exit 2 -fi - -# 2. Both gitignored lanes dumps: missing them fails exactly 2 tests that are -# not a decoder regression. -for f in intrarect_dump.expected.txt wedge_libaom.expected.txt; do - [ -f "$TREE/lanes/$f" ] || { echo "staging defect: $TREE/lanes/$f missing" >&2; exit 2; } -done - -TARGET=${CARGO_TARGET_DIR:-$HOME/gates/target-$NAME} -TMP=${TMPDIR:-$HOME/gates/tmp-$NAME} -mkdir -p "$TARGET" "$TMP" - -echo "=== host=$(hostname) commit=$(git -C "$TREE" rev-parse HEAD) date=$(date -Is)" -echo "=== cargo=$(command -v cargo || echo MISSING) aomenc=${EC_AV1_AOMENC:-unset} aomdec=${EC_AV1_AOMDEC:-unset} ffmpeg=$(command -v ffmpeg || echo MISSING)" -if [ -n "$TARBALL" ]; then - echo "=== tarball=$(sha256sum "$TARBALL" | cut -c1-16) -> $TREE" -fi - -# 3. THE GATE. `set -e` is the whole mechanism: a non-zero verdict aborts this -# script before systemd-run is ever reached, so no unit exists and no suite -# runs. There is no path from a blocked verdict to `=== SUITE`. -set -e -echo "=== PIN-GATE PREFLIGHT + ORACLE RUNG CHECKER" -EC_REQUIRE_FIXTURES=${EC_REQUIRE_FIXTURES:-1} \ -EC_FIXTURE_SHAPE_STRICT=${EC_FIXTURE_SHAPE_STRICT:-1} \ - bash "$TREE/scripts/av1-suite-preflight.sh" --tree "$TREE" -set +e - -echo "=== SUITE" -if [ "$DRY_RUN" = 1 ]; then - echo "dry-run: would start unit $NAME-suite in $TREE (target $TARGET, tmp $TMP)" - exit 0 -fi - -if [ ${#CMD[@]} -eq 0 ]; then - CMD=(cargo test -p ec-av1 --lib -- --test-threads=1) -fi -declare -a quoted=() -for a in "${SKIPS[@]}"; do quoted+=("$a"); done - -LOG=$HOME/gates/$NAME-suite.log -mkdir -p "$HOME/gates" -systemd-run --user --unit="$NAME-suite" -p MemoryMax=5G \ - -p WorkingDirectory="$TREE" \ - --setenv="CARGO_TARGET_DIR=$TARGET" \ - --setenv="TMPDIR=$TMP" \ - --setenv=EC_NOMEMGUARD=1 \ - --setenv=EC_AV1_REQUIRE_AOMENC=1 \ - --setenv=EC_AV1_REQUIRE_FFMPEG=1 \ - --setenv=EC_REQUIRE_FIXTURES=1 \ - --setenv="EC_FIXTURES=${EC_FIXTURES:-$TREE/fixtures}" \ - ${EC_AV1_AOMENC:+--setenv=EC_AV1_AOMENC=$EC_AV1_AOMENC} \ - ${EC_AV1_AOMDEC:+--setenv=EC_AV1_AOMDEC=$EC_AV1_AOMDEC} \ - --setenv="PATH=$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin" \ - /usr/bin/bash -lc "cd '$TREE' && ${CMD[*]} ${quoted[*]-} > '$LOG' 2>&1" -echo "started $NAME-suite; real test output: $LOG" diff --git a/scripts/av1-suite-preflight.sh b/scripts/av1-suite-preflight.sh deleted file mode 100755 index d8ac31f8..00000000 --- a/scripts/av1-suite-preflight.sh +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env bash -# av1-suite-preflight.sh — the gate a server staging must pass BEFORE `=== SUITE`. -# -# WHY (lane-av1stagegaps, measured 2026-09-30). Three hosts, three different -# preflight realities, one identical green suite: -# -# host C host-d the driver printed -# === ORACLE RUNG CHECKER -# rungs_exit=1 ok_count=0 -# === SUITE -# and the suite ran. The real cause, with stderr -# visible, was a MISSING PREREQUISITE: the host has -# `~/.cache/aom-oracle/build` (aomdec/aomenc binaries) -# and no `src/` tree, so the checker asserted nothing. -# host A host-a staged with a bare `cargo test -p ec-av1 --lib`. No -# pin-gate audit, no rung checker, no self-test: not a -# failure, an ABSENT check. -# so "green suite" meant checker-passed, checker-failed and no-checker-ran -# with equal confidence. -# -# WHAT THIS DOES. Runs both preflight pieces, prints one machine-readable state -# per piece, then a single VERDICT. Exit 0 only when every piece is GREEN or an -# explicitly waived NOT-RUN, so a `set -e` staging driver CANNOT reach -# `=== SUITE` on a failed or missing check. -# -# pin_audit = GREEN | FAIL | ABSENT (verify-fixture-library.sh: shape, -# resolve, drift, invariants 1-4 + -# census self-test) -# rung_check = GREEN | FAIL | NOT-RUN | ABSENT -# VERDICT = GREEN | WAIVED | BLOCKED -# -# NOT-RUN vs ABSENT is the distinction that matters. NOT-RUN means the checker -# RAN and reported a missing prerequisite (exit 3 from check-aom-oracle-rungs.sh) -# — a provisioning fact, not a code defect. ABSENT means the checker is not in -# this tree at all, which is exactly the host-A defect and is never waivable. -# -# WAIVER. not-run can be waived, but only with an explicit non-empty reason that -# is recorded in the verdict line, so a later reader can tell a deliberate -# waiver from a check that silently vanished: -# SUITE_RUNG_WAIVER="host host-d carries oracle binaries only; rung -# coverage verified on the build host, see report" -# An empty waiver counts as absent, so a unit's Environment= carrying a bare -# SUITE_RUNG_WAIVER= cannot accidentally authorise a run. -# -# Usage: -# scripts/av1-suite-preflight.sh [--tree DIR] [--self-test] -# -# Env: -# EC_FIXTURES= fixture root (default /fixtures) -# EC_REQUIRE_FIXTURES=1 make an absent/empty fixture path fatal -# SUITE_RUNG_WAIVER= waive rung_check=not-run (see above) -# SUITE_RUNG_CHECKER= override the rung checker (self-test stubs) -# SUITE_PIN_CHECKER= override the pin preflight (self-test stubs) - -set -uo pipefail - -ROOT_DEFAULT=$(cd -- "$(dirname -- "$0")/.." && pwd) -TREE=$ROOT_DEFAULT -SELF_TEST=0 -while [ $# -gt 0 ]; do - case "$1" in - --tree) TREE=$2; shift 2 ;; - --self-test) SELF_TEST=1; shift ;; - -h|--help) sed -n '2,40p' "$0"; exit 0 ;; - *) echo "unknown argument: $1" >&2; exit 2 ;; - esac -done -PIN_CHECKER=${SUITE_PIN_CHECKER:-$TREE/scripts/verify-fixture-library.sh} -RUNG_CHECKER=${SUITE_RUNG_CHECKER:-$TREE/scripts/check-aom-oracle-rungs.sh} - -pin_state=ABSENT -rung_state=ABSENT - -run_pin() { # sets pin_state, prints every detail line - pin_state=ABSENT - if [ ! -f "$PIN_CHECKER" ]; then - echo "pin_audit_state=ABSENT reason=pin preflight not in tree ($PIN_CHECKER)" >&2 - return - fi - local out rc - out=$("$PIN_CHECKER" 2>&1) - rc=$? - printf '%s\n' "$out" | sed 's/^/ /' - if [ $rc -eq 0 ]; then pin_state=GREEN; else pin_state=FAIL; fi - echo "pin_audit_exit=$rc state=$pin_state" -} - -run_rungs() { # sets rung_state, prints every detail line - rung_state=ABSENT - if [ ! -f "$RUNG_CHECKER" ]; then - echo "rung_check_state=ABSENT reason=checker not in tree ($RUNG_CHECKER)" >&2 - return - fi - local out rc ok_count - out=$("$RUNG_CHECKER" 2>&1) - rc=$? - ok_count=$(printf '%s\n' "$out" | grep -c '^ok ' || true) - # The detail lines are the whole point: the 2026-09-30 driver logged - # `rungs_exit=1 ok_count=0` and no reason at all. Every outcome here prints - # the checker's own stdout and stderr together, indented. - printf '%s\n' "$out" | sed 's/^/ /' - case $rc in - 0) rung_state=GREEN ;; - 3) rung_state=NOT-RUN ;; - *) rung_state=FAIL ;; - esac - echo "rungs_exit=$rc ok_count=$ok_count state=$rung_state" -} - -verdict() { # echoes VERDICT; returns 0 iff GREEN or WAIVED - # A pin audit that did not run or failed, and a rung check that is absent - # or failed, are all fatal: no waiver exists for any of them. Only - # rung_check=not-run (a missing prerequisite) is waivable, and only with a - # non-empty reason. - local v=BLOCKED - local waived="" - if [ "$pin_state" = GREEN ] && [ "$rung_state" = GREEN ]; then - v=GREEN - elif [ "$pin_state" = GREEN ] && [ "$rung_state" = NOT-RUN ]; then - if [ -n "${SUITE_RUNG_WAIVER:-}" ]; then - v=WAIVED - waived=" (rung_check=not-run waived: ${SUITE_RUNG_WAIVER})" - fi - fi - echo "VERDICT=$v$waived" - if [ "$v" = BLOCKED ]; then - { - echo "PREFLIGHT BLOCKED: pin_audit=$pin_state rung_check=$rung_state." - echo " A staging with a failed or missing check must NOT reach === SUITE." - echo " rung_check=not-run (missing oracle source) is waivable only via" - echo " SUITE_RUNG_WAIVER=''; an absent checker never is." - } >&2 - return 1 - fi - return 0 -} - -self_test() { - local d rc=0 out - d=$(mktemp -d "${TMPDIR:-/tmp}/av1-preflight-selftest.XXXXXX") - # shellcheck disable=SC2064 - trap "rm -rf '$d'" RETURN - - stub() { # name, exit-code, body - printf '#!/usr/bin/env bash\n%s\nexit %s\n' "$3" "$2" >"$d/$1" - chmod +x "$d/$1" - } - # `set -o pipefail` is on, so `verdict | grep -q ...` returns verdict's own - # non-zero status even when grep matched, and every BLOCKED case would read - # as a self-test failure. Capture first, then compare. - v_of() { verdict 2>/dev/null; } - expect() { # expected-verdict, label - out=$("${@:3}" 2>/dev/null || true) - : - } - - # 1. all green -> GREEN - stub pin-ok 0 'echo "verify-fixture-library: GREEN"' - stub rungs-ok 0 'echo "ok derives the rungs"' - PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1 - RUNG_CHECKER=$d/rungs-ok run_rungs >/dev/null 2>&1 - if [ "$(v_of)" = "VERDICT=GREEN" ]; then - echo "ok 1 an all-green staging is GREEN" - else - echo "FAIL 1 an all-green staging is GREEN"; rc=1 - fi - - # 2. rung checker FAILS (exit 1) -> BLOCKED. The mutation: red the checker - # and the gate must stop. - stub rungs-bad 1 'echo "FAIL derived file violates the rung contract"' - PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1 - RUNG_CHECKER=$d/rungs-bad run_rungs >/dev/null 2>&1 - if [ "$(v_of)" = "VERDICT=BLOCKED" ]; then - echo "ok 2 a FAILING rung checker blocks the suite" - else - echo "FAIL 2 a FAILING rung checker blocks the suite"; rc=1 - fi - - # 3. rung checker NOT-RUN (exit 3), no waiver -> BLOCKED. - stub rungs-notrun 3 'echo "PREREQ-ABSENT: no oracle source at ..."' - PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1 - RUNG_CHECKER=$d/rungs-notrun run_rungs >/dev/null 2>&1 - if [ "$(v_of)" = "VERDICT=BLOCKED" ]; then - echo "ok 3 not-run without a waiver blocks the suite" - else - echo "FAIL 3 not-run without a waiver blocks the suite"; rc=1 - fi - - # 4. not-run WITH a waiver -> WAIVED, and the reason lands in the verdict. - if [ "$(SUITE_RUNG_WAIVER='host C carries oracle binaries only' v_of)" \ - = "VERDICT=WAIVED (rung_check=not-run waived: host C carries oracle binaries only)" ] - then - echo "ok 4 not-run with a named waiver is WAIVED, reason recorded" - else - echo "FAIL 4 not-run with a named waiver is WAIVED, reason recorded"; rc=1 - fi - - # 5. an EMPTY waiver authorises nothing: a unit Environment= carrying a bare - # SUITE_RUNG_WAIVER= is a real staging shape. - if [ "$(SUITE_RUNG_WAIVER='' v_of)" = "VERDICT=BLOCKED" ]; then - echo "ok 5 an empty waiver does not authorise a run" - else - echo "FAIL 5 an empty waiver does not authorise a run"; rc=1 - fi - - # 6. an ABSENT checker is never waivable: the host-A defect. - PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1 - RUNG_CHECKER=$d/does-not-exist run_rungs >/dev/null 2>&1 - if [ "$(SUITE_RUNG_WAIVER='a waiver' v_of)" = "VERDICT=BLOCKED" ]; then - echo "ok 6 a tree with NO rung checker is blocked even with a waiver" - else - echo "FAIL 6 a tree with NO rung checker is blocked even with a waiver"; rc=1 - fi - - # 6b. an ABSENT pin audit is fatal too, and not waivable by the same knob. - PIN_CHECKER=$d/does-not-exist run_pin >/dev/null 2>&1 - RUNG_CHECKER=$d/rungs-ok run_rungs >/dev/null 2>&1 - if [ "$(SUITE_RUNG_WAIVER='a waiver' v_of)" = "VERDICT=BLOCKED" ]; then - echo "ok 7 a tree with NO pin audit is blocked even with a waiver" - else - echo "FAIL 7 a tree with NO pin audit is blocked even with a waiver"; rc=1 - fi - - # 8. pin audit FAILING -> BLOCKED even when the rungs are green. - stub pin-bad 1 'echo "FAIL [invariant 4]: census self-test did not pass"' - PIN_CHECKER=$d/pin-bad run_pin >/dev/null 2>&1 - RUNG_CHECKER=$d/rungs-ok run_rungs >/dev/null 2>&1 - if [ "$(v_of)" = "VERDICT=BLOCKED" ]; then - echo "ok 8 a FAILING pin audit blocks the suite" - else - echo "FAIL 8 a FAILING pin audit blocks the suite"; rc=1 - fi - - return $rc -} - -if [ "$SELF_TEST" = 1 ]; then - self_test - exit $? -fi - -echo "=== PIN-GATE PREFLIGHT (EC_REQUIRE_FIXTURES=${EC_REQUIRE_FIXTURES:-0})" -run_pin -echo "=== ORACLE RUNG CHECKER" -run_rungs -echo "=== VERDICT" -verdict -exit $? diff --git a/scripts/bench-benchaudio.sh b/scripts/bench-benchaudio.sh deleted file mode 100755 index 27d70f85..00000000 --- a/scripts/bench-benchaudio.sh +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env bash -# bench-benchaudio.sh: the audio rows of lanes/bench.md ("lane benchaudio", DONE.md gate G6). -# -# Local machine only (DONE.md D7 exception): build with -j6 into CARGO_TARGET_DIR and run each -# row as the best of 5 inside the bench binary. Before each row, wait until the 1-minute load is -# below 3. Clips are synthetic and generated here with the local ffmpeg (never personal media); -# they live in $BENCH_CLIPS (default ~/.cache/benchaudio-clips), outside the repo. -# -# Output: one "ROW|..." line per bench row (crate, op, content, best time, x realtime or rates, -# and the output check), then "CHECK|..." lines with the comparison details. The lanes/bench.md -# "lane benchaudio" table is written from these lines. -# -# usage: scripts/bench-benchaudio.sh [--no-clips] [--no-build] -set -euo pipefail - -cd "$(dirname "$0")/.." -REPO="$(pwd)" -CLIPS="${BENCH_CLIPS:-$HOME/.cache/benchaudio-clips}" -BIN="${BENCH_BIN:-$HOME/.cache/benchaudio-bin}" -OUT="$CLIPS/out" -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchaudio}" -export RUSTC_WRAPPER= -export TMPDIR="${TMPDIR:-$HOME/.cache/tmp-benchaudio}" -FF=(ffmpeg -hide_banner -loglevel error -y) -DO_CLIPS=1 -DO_BUILD=1 -for a in "$@"; do - case "$a" in - --no-clips) DO_CLIPS=0 ;; - --no-build) DO_BUILD=0 ;; - *) echo "unknown option: $a" >&2; exit 2 ;; - esac -done -mkdir -p "$CLIPS" "$BIN" "$OUT" "$TMPDIR" -COMMIT="$(git -C "$REPO" rev-parse --short HEAD)" -echo "# host=local cores=$(nproc) commit=$COMMIT ffmpeg=$(ffmpeg -version | head -1 | awk '{print $3}')" - -# ---- 1. synthetic clips ------------------------------------------------------------------- -if [ "$DO_CLIPS" = 1 ]; then - cd "$CLIPS" - if [ ! -f src_stereo.wav ]; then - # 60 s stereo: tones with a slow AM, plus two independent pink-noise channels. - "${FF[@]}" -f lavfi -i "aevalsrc='0.25*sin(2*PI*220*t)+0.12*sin(2*PI*277.18*t)*(0.5+0.5*sin(2*PI*2*t))+0.1*sin(2*PI*329.63*t)|0.25*sin(2*PI*222*t)+0.12*sin(2*PI*280*t)*(0.5+0.5*sin(2*PI*2*t))+0.1*sin(2*PI*331*t)':s=48000:d=60" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=1" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=2" \ - -filter_complex "[1:a][2:a]amerge=inputs=2,aformat=channel_layouts=stereo[n];[0:a][n]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]" \ - -map "[o]" -c:a pcm_s16le src_stereo.wav - fi - if [ ! -f src_stereo.f32 ]; then "${FF[@]}" -i src_stereo.wav -f f32le -acodec pcm_f32le src_stereo.f32; fi - if [ ! -f src_51.thd ]; then - # 60 s 5.1 for TrueHD: six tones plus six independent pink-noise channels. - "${FF[@]}" -f lavfi -i "aevalsrc='0.25*sin(2*PI*220*t)|0.25*sin(2*PI*222*t)|0.2*sin(2*PI*110*t)|0.1*sin(2*PI*440*t)|0.15*sin(2*PI*330*t)|0.15*sin(2*PI*150*t)':s=48000:d=60" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=3" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=4" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=5" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=6" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=7" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=8" \ - -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]amerge=inputs=6,aformat=channel_layouts=5.1[n];[0:a][n]amix=inputs=2:normalize=0,aformat=sample_fmts=s32:channel_layouts=5.1[o]" \ - -map "[o]" -c:a truehd -strict -2 -f truehd src_51.thd - fi - # AAC-LC 128k stereo (libfdk_aac) and Opus 96k, Vorbis q5 (libvorbis), MP3 192k reference. - [ -f aac_lc_128k.adts ] || "${FF[@]}" -i src_stereo.wav -c:a libfdk_aac -profile:a aac_low -b:a 128k -f adts aac_lc_128k.adts - [ -f opus_96k.ogg ] || "${FF[@]}" -i src_stereo.wav -c:a libopus -b:a 96k -f ogg opus_96k.ogg - [ -f vorbis_q5.ogg ] || "${FF[@]}" -i src_stereo.wav -c:a libvorbis -q:a 5 -f ogg vorbis_q5.ogg - # HE-AAC v1: the local libfdk_aac cannot encode SBR (it fails "Unable to set the AOT 5" at every - # rate and bitrate tried), so the stream is the 2.1 s HE-AAC v1 fixture of the repo - # (ec-aac tests/data/heaac_44100_48k_implicit_2s.aac, implicit SBR), repeated 28 times to 60 s. - if [ ! -f aac_he_v1_60s.adts ]; then - fx="$REPO/crates/ec-aac/tests/data/heaac_44100_48k_implicit_2s.aac" - : > aac_he_v1_60s.adts - for _ in $(seq 28); do cat "$fx" >> aac_he_v1_60s.adts; done - fi - # H.264 1080p30 + AAC stereo, 60 s synthetic (testsrc2 video, the tones+noise audio). - [ -f h264_aac_1080p30.mp4 ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=30:duration=60" -i src_stereo.wav \ - -c:v libx264 -preset veryfast -b:v 4M -pix_fmt yuv420p -c:a aac -b:a 128k -shortest h264_aac_1080p30.mp4 - # References for the output checks (ffmpeg's own decoders and remux). - [ -f ref_aac_lc.f32le ] || "${FF[@]}" -i aac_lc_128k.adts -f f32le -acodec pcm_f32le ref_aac_lc.f32le - [ -f ref_aac_he.f32le ] || "${FF[@]}" -i aac_he_v1_60s.adts -f f32le -acodec pcm_f32le ref_aac_he.f32le - [ -f ref_opus.f32le ] || "${FF[@]}" -i opus_96k.ogg -f f32le -acodec pcm_f32le ref_opus.f32le - [ -f ref_vorbis.f32le ] || "${FF[@]}" -i vorbis_q5.ogg -f f32le -acodec pcm_f32le ref_vorbis.f32le - [ -f ref_truehd.s32le ] || "${FF[@]}" -i src_51.thd -f s32le -acodec pcm_s32le ref_truehd.s32le - [ -f ref_mp4.v.bin ] || "${FF[@]}" -i h264_aac_1080p30.mp4 -map 0:v:0 -c copy -f data ref_mp4.v.bin - [ -f ref_mp4.a.bin ] || "${FF[@]}" -i h264_aac_1080p30.mp4 -map 0:a:0 -c copy -f data ref_mp4.a.bin - cd "$REPO" -fi - -# ---- 2. build the six examples (one binary per crate, copied before the next build) -------- -crates=(ec-aac ec-opus ec-vorbis ec-mp3 ec-truehd ec-mp4) -if [ "$DO_BUILD" = 1 ]; then - for c in "${crates[@]}"; do - cargo build --release -j6 -p "$c" --example bench - cp "$CARGO_TARGET_DIR/release/examples/bench" "$BIN/$c-bench" - done -fi - -# ---- 3. helpers -------------------------------------------------------------------------- -wait_load() { - # Start a row only when the 1-minute load is below 3. - while :; do - l=$(cut -d' ' -f1 /proc/loadavg) - if awk -v l="$l" 'BEGIN{exit !(l < 3)}'; then echo "$l"; return; fi - sleep 5 - done -} -field() { echo "$1" | tr ' ' '\n' | sed -n "s/^$2=//p"; } -ratio() { awk -v a="$1" -v b="$2" 'BEGIN{ if (b > 0) printf "%.2f", a / b; else print "nan" }'; } -# corr CHECK: min per-channel Pearson correlation at the best lag (+-4096 samples), ref vs test. -corr() { - python3 -I - "$1" "$2" "$3" "$4" "$5" <<'PY' -import sys -import numpy as np -ref_p, test_p, ch, rate, fmt = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]), sys.argv[5] -def load(p): - a = np.fromfile(p, ' t.shape[0]: - continue - x = t[s:s + L, 0] - x = x - x.mean() - c = float(np.dot(seg, x) / (seg_n * np.linalg.norm(x) + 1e-30)) - if c > best_c: - best_c, best_lag = c, lag -i0, i1 = max(0, -best_lag), min(r.shape[0], t.shape[0] - best_lag) -cs = [] -for k in range(ch): - a = r[i0:i1, k] - r[i0:i1, k].mean() - b = t[i0 + best_lag:i1 + best_lag, k] - t[i0 + best_lag:i1 + best_lag, k].mean() - cs.append(float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30))) -print(f"corr_min={min(cs):.6f} corr_max={max(cs):.6f} lag={best_lag} ref_frames={r.shape[0]} test_frames={t.shape[0]} overlap_frames={i1 - i0}") -PY -} -md5_of() { md5sum "$1" | cut -c1-8; } - -# ---- 4. rows ----------------------------------------------------------------------------- -cd "$CLIPS" -B="$BIN" - -# AAC decode, LC and HE-AAC v1 (ADTS), 2 ch. -for spec in "ec-aac|aac_lc_128k.adts|AAC-LC stereo 128 kb/s 60 s (libfdk_aac)|ref_aac_lc.f32le" \ - "ec-aac|aac_he_v1_60s.adts|HE-AAC v1 stereo 64 kb/s 2.1 s fixture x28 (implicit SBR)|ref_aac_he.f32le"; do - IFS='|' read -r crate in content ref <<<"$spec" - l=$(wait_load) - res=$("$B/$crate-bench" dec "$in" "$OUT/aacdec-$in.f32le" 5) - best=$(field "$res" best_decode_s); samples=$(field "$res" samples); fails=$(field "$res" frames_failed) - audio=$(awk -v s="$samples" 'BEGIN{printf "%.3f", s/2/48000}') - echo "ROW|$crate|decode|$content|$best|$(ratio "$audio" "$best")x|load1=$l frames_failed=$fails" - c=$(corr "$ref" "$OUT/aacdec-$in.f32le" 2 48000 f32) - echo "CHECK|$crate decode $in|vs ffmpeg $(ffmpeg -version | head -1 | awk '{print $3}') native aac: $c" -done - -# AAC-LC encode, stereo 128k: encode the source, then decode the result with ffmpeg and compare. -l=$(wait_load) -res=$("$B/ec-aac-bench" enc src_stereo.f32 2 48000 128 "$OUT/aacenc.adts" 5) -best=$(field "$res" best_encode_s); audio=$(field "$res" audio_s); bytes=$(field "$res" bytes) -echo "ROW|ec-aac|encode|AAC-LC stereo 128 kb/s from 60 s PCM|$best|$(ratio "$audio" "$best")x|load1=$l kbps=$(awk -v b="$bytes" -v a="$audio" 'BEGIN{printf "%.1f", b*8/a/1000}')" -"${FF[@]}" -i "$OUT/aacenc.adts" -f f32le -acodec pcm_f32le "$OUT/aacenc-ffdec.f32le" -echo "CHECK|ec-aac encode|ffmpeg decode of our ADTS vs source: $(corr src_stereo.f32 "$OUT/aacenc-ffdec.f32le" 2 48000 f32)" -# Calibration: ffmpeg's own AAC encoders at the same 128k, through the same decode and check. -"${FF[@]}" -i src_stereo.wav -c:a aac -b:a 128k -f adts "$OUT/cal-native.adts" -"${FF[@]}" -i "$OUT/cal-native.adts" -f f32le -acodec pcm_f32le "$OUT/cal-native.f32le" -echo "CHECK|ec-aac encode calibration|ffmpeg native aac 128k, same check: $(corr src_stereo.f32 "$OUT/cal-native.f32le" 2 48000 f32)" -"${FF[@]}" -i src_stereo.wav -c:a libfdk_aac -profile:a aac_low -b:a 128k -f adts "$OUT/cal-fdk.adts" -"${FF[@]}" -i "$OUT/cal-fdk.adts" -f f32le -acodec pcm_f32le "$OUT/cal-fdk.f32le" -echo "CHECK|ec-aac encode calibration|ffmpeg libfdk_aac 128k, same check: $(corr src_stereo.f32 "$OUT/cal-fdk.f32le" 2 48000 f32)" - -# Opus decode 48k stereo 96k, and encode. -l=$(wait_load) -res=$("$B/ec-opus-bench" dec opus_96k.ogg "$OUT/opusdec.f32le" 5) -best=$(field "$res" best_decode_s); samples=$(field "$res" samples) -audio=$(awk -v s="$samples" 'BEGIN{printf "%.3f", s/48000}') -echo "ROW|ec-opus|decode|Opus 48k stereo 96 kb/s 60 s (libopus)|$best|$(ratio "$audio" "$best")x|load1=$l packets_failed=$(field "$res" failed)" -echo "CHECK|ec-opus decode|vs ffmpeg Opus decode: $(corr ref_opus.f32le "$OUT/opusdec.f32le" 2 48000 f32)" - -l=$(wait_load) -res=$("$B/ec-opus-bench" enc src_stereo.f32 2 96 "$OUT/opusenc.ogg" 5) -best=$(field "$res" best_encode_s); audio=$(field "$res" audio_s); bytes=$(field "$res" bytes) -echo "ROW|ec-opus|encode|Opus 48k stereo 96 kb/s 60 s (vbr off, 20 ms frames)|$best|$(ratio "$audio" "$best")x|load1=$l kbps=$(awk -v b="$bytes" -v a="$audio" 'BEGIN{printf "%.1f", b*8/a/1000}')" -"${FF[@]}" -i "$OUT/opusenc.ogg" -f f32le -acodec pcm_f32le "$OUT/opusenc-ffdec.f32le" -echo "CHECK|ec-opus encode|ffmpeg decode of our Ogg Opus vs source: $(corr src_stereo.f32 "$OUT/opusenc-ffdec.f32le" 2 48000 f32)" - -# Vorbis decode, q5 stereo. -l=$(wait_load) -res=$("$B/ec-vorbis-bench" dec vorbis_q5.ogg "$OUT/vorbisdec.f32le" 5) -best=$(field "$res" best_decode_s); samples=$(field "$res" samples) -audio=$(awk -v s="$samples" 'BEGIN{printf "%.3f", s/48000}') -echo "ROW|ec-vorbis|decode|Vorbis q5 stereo 60 s (libvorbis)|$best|$(ratio "$audio" "$best")x|load1=$l" -echo "CHECK|ec-vorbis decode|vs ffmpeg Vorbis decode: $(corr ref_vorbis.f32le "$OUT/vorbisdec.f32le" 2 48000 f32)" - -# MP3 encode, 192k CBR stereo (Layer III); the output is decoded with ffmpeg and compared. -l=$(wait_load) -res=$("$B/ec-mp3-bench" enc src_stereo.f32 2 48000 192 "$OUT/mp3enc.mp3" 5) -best=$(field "$res" best_encode_s); audio=$(field "$res" audio_s); bytes=$(field "$res" bytes) -echo "ROW|ec-mp3|encode|MP3 192 kb/s CBR stereo 48k 60 s|$best|$(ratio "$audio" "$best")x|load1=$l kbps=$(awk -v b="$bytes" -v a="$audio" 'BEGIN{printf "%.1f", b*8/a/1000}')" -"${FF[@]}" -i "$OUT/mp3enc.mp3" -f f32le -acodec pcm_f32le "$OUT/mp3enc-ffdec.f32le" -echo "CHECK|ec-mp3 encode|ffmpeg decode of our MP3 vs source: $(corr src_stereo.f32 "$OUT/mp3enc-ffdec.f32le" 2 48000 f32)" - -# TrueHD decode, 5.1 24-bit (S32 container). Lossless: the output must equal ffmpeg's bytes. -l=$(wait_load) -res=$("$B/ec-truehd-bench" dec src_51.thd "$OUT/truehd-dec.s32le" 5) -best=$(field "$res" best_decode_s); audio=$(field "$res" audio_s); fails=$(field "$res" check_failures) -echo "ROW|ec-truehd|decode|TrueHD 5.1 24-bit 48k 60 s|$best|$(ratio "$audio" "$best")x|load1=$l self_check_failures=$fails" -if cmp -s ref_truehd.s32le "$OUT/truehd-dec.s32le"; then - echo "CHECK|ec-truehd decode|md5 $(md5_of ref_truehd.s32le) = ffmpeg (bit-exact, $(stat -c%s ref_truehd.s32le) bytes)" -else - echo "CHECK|ec-truehd decode|md5 MISMATCH vs ffmpeg: ours $(md5_of "$OUT/truehd-dec.s32le") ffmpeg $(md5_of ref_truehd.s32le)" -fi - -# MP4 demux and mux, H.264 1080p30 + AAC, 60 s. -file_bytes=$(stat -c%s h264_aac_1080p30.mp4) -l=$(wait_load) -res=$("$B/ec-mp4-bench" demux h264_aac_1080p30.mp4 "$OUT/mp4" 5) -pps=$(field "$res" packets_per_s); mbs=$(field "$res" mb_per_s); pk=$(field "$res" packets) -echo "ROW|ec-mp4|demux|H.264 1080p30 + AAC 128k stereo, 60 s (${file_bytes} bytes)|$(field "$res" best_demux_s)|$pps packets/s, $mbs MB/s (payload)|load1=$l packets=$pk" -v_ok=$([ "$(md5_of "$OUT/mp4.s0.bin")" = "$(md5_of ref_mp4.v.bin)" ] && echo match || echo MISMATCH) -a_ok=$([ "$(md5_of "$OUT/mp4.s1.bin")" = "$(md5_of ref_mp4.a.bin)" ] && echo match || echo MISMATCH) -echo "CHECK|ec-mp4 demux|payload md5 vs ffmpeg -c copy -f data: video $v_ok, audio $a_ok; packets ours=$pk ffprobe=$(( $(ffprobe -v error -count_packets -select_streams v:0 -show_entries stream=nb_read_packets -of csv=p=0 h264_aac_1080p30.mp4) + $(ffprobe -v error -count_packets -select_streams a:0 -show_entries stream=nb_read_packets -of csv=p=0 h264_aac_1080p30.mp4) ))" - -l=$(wait_load) -res=$("$B/ec-mp4-bench" mux h264_aac_1080p30.mp4 "$OUT/mux.mp4" 5) -echo "ROW|ec-mp4|mux|H.264 1080p30 + AAC 128k stereo, 60 s (remux of the same packets)|$(field "$res" best_mux_s)|$(field "$res" packets_per_s) packets/s, $(field "$res" mb_per_s) MB/s (payload)|load1=$l" -"${FF[@]}" -i "$OUT/mux.mp4" -map 0:v:0 -c copy -f data "$OUT/mux.v.bin" -"${FF[@]}" -i "$OUT/mux.mp4" -map 0:a:0 -c copy -f data "$OUT/mux.a.bin" -v_ok=$([ "$(md5_of "$OUT/mux.v.bin")" = "$(md5_of ref_mp4.v.bin)" ] && echo match || echo MISMATCH) -a_ok=$([ "$(md5_of "$OUT/mux.a.bin")" = "$(md5_of ref_mp4.a.bin)" ] && echo match || echo MISMATCH) -echo "CHECK|ec-mp4 mux|ffmpeg -c copy -f data of our output vs source payload: video $v_ok, audio $a_ok" diff --git a/scripts/bench-benchhw.sh b/scripts/bench-benchhw.sh deleted file mode 100755 index 13f2e3ad..00000000 --- a/scripts/bench-benchhw.sh +++ /dev/null @@ -1,173 +0,0 @@ -#!/usr/bin/env bash -# bench-benchhw.sh: the VA-API rows of lanes/bench.md ("lane benchhw", DONE.md gate G6). -# -# Local machine only, with the GPU (radeonsi VA-API; `vainfo` lists the profiles). Clips are -# synthetic, generated here with the local ffmpeg (testsrc2 + noise, 1080p30, 60 s), and live in -# $BENCH_CLIPS (default ~/.cache/benchhw-clips), outside the repo. -# -# Rows: -# decode ec-hw Decoder, H.264 High, HEVC Main, HEVC Main10, VP9 profile 0, AV1 8-bit. -# Each row: best of 5 timed runs (GPU waited per picture), then one readback pass whose -# frames are compared md5-per-frame with ffmpeg's software decode of the same file. -# encode ec-hw Encoder, H.264 High and HEVC Main, 1080p30 CBR 8 Mb/s, GOP 30, 1800 pictures. -# Best of 5; the stream is decoded by ffmpeg (exit status, frame count, PSNR vs source). -# -# Output: one "ROW|..." line per row, then "CHECK|..." lines with the comparison details. -# The lanes/bench.md "lane benchhw" table is written from these lines. -# -# usage: scripts/bench-benchhw.sh [--no-clips] [--no-build] -set -euo pipefail - -cd "$(dirname "$0")/.." -REPO="$(pwd)" -CLIPS="${BENCH_CLIPS:-$HOME/.cache/benchhw-clips}" -BIN="${BENCH_BIN:-$HOME/.cache/benchhw-bin}" -OUT="$CLIPS/out" -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchhw}" -export RUSTC_WRAPPER= -export TMPDIR="${TMPDIR:-$HOME/.cache/tmp-benchhw}" -FF=(ffmpeg -hide_banner -loglevel error -y) -DO_CLIPS=1 -DO_BUILD=1 -for a in "$@"; do - case "$a" in - --no-clips) DO_CLIPS=0 ;; - --no-build) DO_BUILD=0 ;; - *) echo "unknown option: $a" >&2; exit 2 ;; - esac -done -mkdir -p "$CLIPS" "$BIN" "$OUT" "$TMPDIR" -COMMIT="$(git -C "$REPO" rev-parse --short HEAD)" -echo "# host=local cores=$(nproc) commit=$COMMIT ffmpeg=$(ffmpeg -version | head -1 | awk '{print $3}') gpu=$(vainfo 2>/dev/null | sed -n 's/.*Driver version: //p' | head -1)" - -SRC="testsrc2=size=1920x1080:rate=30:duration=60" -W=1920 -H=1080 - -# ---- 1. synthetic clips ------------------------------------------------------------------- -if [ "$DO_CLIPS" = 1 ]; then - cd "$CLIPS" - # Raw 8-bit 4:2:0 source for the encode rows (1800 pictures, about 5.6 GB). - [ -f src_1080p30_8bit.yuv ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \ - -f rawvideo -pix_fmt yuv420p src_1080p30_8bit.yuv - # Decode inputs. Short GOP (30 pictures = 1 s). Annex B for H.264/HEVC, IVF for VP9/AV1. - [ -f h264_high_1080p30.264 ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \ - -c:v libx264 -preset veryfast -profile:v high -crf 23 -g 30 -keyint_min 30 \ - -f h264 h264_high_1080p30.264 - [ -f hevc_main_1080p30.265 ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \ - -c:v libx265 -preset veryfast -crf 23 -x265-params "keyint=30:min-keyint=30:log-level=error" \ - -profile:v main -f hevc hevc_main_1080p30.265 - [ -f hevc_main10_1080p30.265 ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p10le,noise=alls=20:allf=t" \ - -c:v libx265 -preset veryfast -crf 23 -x265-params "keyint=30:min-keyint=30:log-level=error" \ - -profile:v main10 -pix_fmt yuv420p10le -f hevc hevc_main10_1080p30.265 - [ -f vp9_profile0_1080p30.ivf ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \ - -c:v libvpx-vp9 -deadline realtime -cpu-used 5 -row-mt 1 -b:v 0 -crf 31 -g 30 \ - -pix_fmt yuv420p -f ivf vp9_profile0_1080p30.ivf - [ -f av1_8bit_1080p30.ivf ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \ - -c:v libsvtav1 -preset 8 -crf 35 -g 30 -pix_fmt yuv420p -f ivf av1_8bit_1080p30.ivf - # References: ffmpeg's software decoders, native pixel format, every picture. - [ -f ref_h264.yuv ] || "${FF[@]}" -i h264_high_1080p30.264 -map 0:v:0 -fps_mode passthrough -f rawvideo -pix_fmt yuv420p ref_h264.yuv - [ -f ref_hevc.yuv ] || "${FF[@]}" -i hevc_main_1080p30.265 -map 0:v:0 -fps_mode passthrough -f rawvideo -pix_fmt yuv420p ref_hevc.yuv - [ -f ref_hevc10.yuv ] || "${FF[@]}" -i hevc_main10_1080p30.265 -map 0:v:0 -fps_mode passthrough -f rawvideo -pix_fmt yuv420p10le ref_hevc10.yuv - [ -f ref_vp9.yuv ] || "${FF[@]}" -i vp9_profile0_1080p30.ivf -map 0:v:0 -fps_mode passthrough -f rawvideo -pix_fmt yuv420p ref_vp9.yuv - [ -f ref_av1.yuv ] || "${FF[@]}" -i av1_8bit_1080p30.ivf -map 0:v:0 -fps_mode passthrough -f rawvideo -pix_fmt yuv420p ref_av1.yuv - cd "$REPO" -fi - -# ---- 2. build the bench example ----------------------------------------------------------- -if [ "$DO_BUILD" = 1 ]; then - cargo build --release -j6 -p ec-hw --example bench - cp "$CARGO_TARGET_DIR/release/examples/bench" "$BIN/ec-hw-bench" -fi -B="$BIN/ec-hw-bench" - -# ---- 3. helpers -------------------------------------------------------------------------- -wait_load() { - # Start a row only when the 1-minute load is below 3. - while :; do - l=$(cut -d' ' -f1 /proc/loadavg) - if awk -v l="$l" 'BEGIN{exit !(l < 3)}'; then echo "$l"; return; fi - sleep 5 - done -} -field() { echo "$1" | tr ' ' '\n' | sed -n "s/^$2=//p"; } -# framecmp REF TEST FRAME_BYTES: per-frame md5 comparison; prints frames, equal count, first diff. -framecmp() { - python3 -I - "$1" "$2" "$3" <<'PY' -import hashlib, sys -ref, test, fb = sys.argv[1], sys.argv[2], int(sys.argv[3]) -def md5s(p): - out = [] - with open(p, 'rb') as f: - while True: - b = f.read(fb) - if not b: - break - out.append(hashlib.md5(b).hexdigest()[:12]) - return out -r, t = md5s(ref), md5s(test) -same = sum(1 for a, b in zip(r, t) if a == b) -first = next((i for i, (a, b) in enumerate(zip(r, t)) if a != b), None) -print(f"frames_ref={len(r)} frames_test={len(t)} frames_md5_equal={same} first_diff={first if first is not None else 'none'}") -PY -} - -# ---- 4. decode rows ---------------------------------------------------------------------- -cd "$CLIPS" -dec_row() { # label codec stream ref frame_bytes - local label=$1 codec=$2 stream=$3 ref=$4 fb=$5 - local l res best fps x pics - l=$(wait_load) - res=$("$B" dec "$codec" "$stream" --out "$OUT/dump-$label.yuv" --runs 5) - best=$(echo "$res" | sed -n 's/^BEST|.*best_s=\([^ ]*\).*/\1/p') - fps=$(echo "$res" | sed -n 's/^BEST|.*fps=\([^ ]*\).*/\1/p') - x=$(echo "$res" | sed -n 's/^BEST|.*x_realtime=\([^ ]*\).*/\1/p') - pics=$(echo "$res" | sed -n 's/^BEST|.*pictures=\([^ ]*\).*/\1/p') - echo "ROW|ec-hw|decode $label|VA-API $label 1080p30 60 s, $pics pictures|best ${best} s|${fps} fps, ${x}x realtime|load1=$l runs=5 best" - echo "CHECK|ec-hw decode $label|$(framecmp "$ref" "$OUT/dump-$label.yuv" "$fb")" - rm -f "$OUT/dump-$label.yuv" -} -FB8=$((W * H * 3 / 2)) -FB10=$((W * H * 3)) -dec_row h264-high h264 h264_high_1080p30.264 ref_h264.yuv "$FB8" -dec_row hevc-main hevc hevc_main_1080p30.265 ref_hevc.yuv "$FB8" -dec_row hevc-main10 hevc hevc_main10_1080p30.265 ref_hevc10.yuv "$FB10" -dec_row vp9-profile0 vp9 vp9_profile0_1080p30.ivf ref_vp9.yuv "$FB8" -dec_row av1-8bit av1 av1_8bit_1080p30.ivf ref_av1.yuv "$FB8" - -# ---- 5. encode rows ---------------------------------------------------------------------- -enc_row() { # label codec ffmt - local label=$1 codec=$2 ffmt=$3 - local l res best fps x kbps - l=$(wait_load) - res=$("$B" enc "$codec" src_1080p30_8bit.yuv "$W" "$H" 1800 8000000 --out "$OUT/enc-$label.bin" --runs 5) - best=$(echo "$res" | sed -n 's/^BEST|.*best_s=\([^ ]*\).*/\1/p') - fps=$(echo "$res" | sed -n 's/^BEST|.*fps=\([^ ]*\).*/\1/p') - x=$(echo "$res" | sed -n 's/^BEST|.*x_realtime=\([^ ]*\).*/\1/p') - kbps=$(echo "$res" | sed -n 's/^BEST|.*kbps=\([^ ]*\).*/\1/p') - echo "ROW|ec-hw|encode $label|VA-API $label 1080p30 CBR 8 Mb/s GOP 30, 60 s|best ${best} s|${fps} fps, ${x}x realtime, ${kbps} kb/s|load1=$l runs=5 best" - # ffmpeg decodes our stream: exit status, picture count, and PSNR against the source. - local ff_out nb psnr - ff_out=$("${FF[@]}" -f "$ffmt" -i "$OUT/enc-$label.bin" -f rawvideo -pix_fmt yuv420p "$OUT/enc-$label.ref.yuv" 2>&1 && echo ok || echo FAIL) - nb=$(stat -c%s "$OUT/enc-$label.ref.yuv") - nb=$((nb / FB8)) - psnr=$(ffmpeg -hide_banner -nostats -f "$ffmt" -i "$OUT/enc-$label.bin" -f rawvideo -s ${W}x${H} -pix_fmt yuv420p -i src_1080p30_8bit.yuv -lavfi "[0:v][1:v]psnr" -f null - 2>&1 | sed -n 's/.*average:\([0-9.inf]*\).*/\1/p' | tail -1) - echo "CHECK|ec-hw encode $label|ffmpeg decode: $ff_out, pictures=$nb of 1800, PSNR vs source avg ${psnr} dB" - rm -f "$OUT/enc-$label.ref.yuv" -} -enc_row h264-high h264 h264 -enc_row hevc-main hevc hevc - -# Calibration for the PSNR above: ffmpeg's libx264 and libx265 at the same 8 Mb/s, GOP 30, the -# same source, decoded and measured the same way. Not a bench row; it says how much of the PSNR -# is the bitrate and the noisy source, not the hardware encoder. -for spec in "h264|libx264|h264" "hevc|libx265|hevc"; do - IFS='|' read -r lbl enc ffmt <<<"$spec" - "${FF[@]}" -f rawvideo -pix_fmt yuv420p -s ${W}x${H} -r 30 -i src_1080p30_8bit.yuv -c:v "$enc" \ - -preset veryfast -b:v 8M -maxrate 8M -bufsize 1M -g 30 -f "$ffmt" "$OUT/cal-$lbl.bin" - psnr=$(ffmpeg -hide_banner -nostats -f "$ffmt" -i "$OUT/cal-$lbl.bin" -f rawvideo -s ${W}x${H} -pix_fmt yuv420p -i src_1080p30_8bit.yuv -lavfi "[0:v][1:v]psnr" -f null - 2>&1 | sed -n 's/.*average:\([0-9.inf]*\).*/\1/p' | tail -1) - echo "CHECK|calibration $enc 8 Mb/s GOP 30|PSNR vs source avg ${psnr} dB (same source, ffmpeg software encoder)" -done - -cd "$REPO" -echo "# done" diff --git a/scripts/bench-benchp1-clips.sh b/scripts/bench-benchp1-clips.sh deleted file mode 100755 index d5f73180..00000000 --- a/scripts/bench-benchp1-clips.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env bash -# bench-benchp1-clips.sh: generate the inputs for the subtitle, Ogg and RIFF bench rows of -# lanes/bench.md ("lane benchp1"). Clips go to $BENCH_CLIPS (default ~/.cache/benchp1-clips), -# never into the repo. The .sup input is written by `ec-pgs --example benchp1 gen` (ffmpeg has no -# PGS encoder), so it is not made here. -set -euo pipefail -d=${BENCH_CLIPS:-$HOME/.cache/benchp1-clips} -mkdir -p "$d" -ff() { ffmpeg -nostdin -v error -y "$@"; } - -# ASS with many styled events: 20 styles, one event every 0.5 s for 2 h (14400 events). -# awk writes the script; ffmpeg converts it to SRT and WebVTT (14400 cues each) for ec-subs. -if [ ! -s "$d/styled-2h.ass" ]; then - awk 'BEGIN { - print "[Script Info]\nTitle: benchp1\nScriptType: v4.00+\nPlayResX: 1920\nPlayResY: 1080\nWrapStyle: 0\n" - print "[V4+ Styles]" - print "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding" - for (s = 0; s < 20; s++) { - printf "Style: S%02d,Arial,%d,&H00%02X%02X%02X,&H000000FF,&H00000000,&H64000000,%d,0,0,0,100,100,0,0,1,2,1,%d,10,10,40,1\n", s, 36 + s, (s * 37) % 256, (s * 91) % 256, (s * 53) % 256, s % 2, 1 + (s % 9) - } - print "\n[Events]" - print "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text" - for (i = 0; i < 14400; i++) { - t0 = i * 50; t1 = t0 + 120 - s = i % 20 - printf "Dialogue: %d,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,S%02d,,0,0,0,,{\\an%d\\pos(%d,%d)\\fad(200,200)\\c&H%02X%02X%02X&\\b%d}Event %d {\\i1}styled{\\i0} text \\N line two of %d {\\fscx%d\\frz%d}\n", - i % 3, int(t0 / 360000), int(t0 / 6000) % 60, int(t0 / 100) % 60, t0 % 100, - int(t1 / 360000), int(t1 / 6000) % 60, int(t1 / 100) % 60, t1 % 100, - s, 1 + (i % 9), 100 + (i * 7) % 1700, 80 + (i * 13) % 900, - (i * 31) % 256, (i * 17) % 256, (i * 5) % 256, i % 2, i, i, 90 + i % 30, (i % 60) - 30 - } - }' > "$d/styled-2h.ass" -fi -[ -s "$d/styled-2h.srt" ] || ff -i "$d/styled-2h.ass" -c:s srt "$d/styled-2h.srt" -[ -s "$d/styled-2h.vtt" ] || ff -i "$d/styled-2h.ass" -c:s webvtt "$d/styled-2h.vtt" - -# Vorbis and Opus in Ogg, 10 min, stereo pink noise. -[ -s "$d/vorbis-10m.ogg" ] || ff -f lavfi -i "anoisesrc=d=600:c=pink:r=48000:a=0.2:seed=7" \ - -ac 2 -c:a libvorbis -q:a 4 "$d/vorbis-10m.ogg" -[ -s "$d/opus-10m.ogg" ] || ff -f lavfi -i "anoisesrc=d=600:c=pink:r=48000:a=0.2:seed=7" \ - -ac 2 -c:a libopus -b:a 128k "$d/opus-10m.ogg" - -# 24-bit 5.1 WAV, 10 min at 48 kHz: six independent pink-noise channels joined as 5.1. -inputs=() -for seed in 1 2 3 4 5 6; do - inputs+=(-f lavfi -i "anoisesrc=d=600:c=pink:r=48000:a=0.2:seed=$seed") -done -[ -s "$d/wav-51-24b-10m.wav" ] || ff "${inputs[@]}" -filter_complex \ - "[0:a][1:a][2:a][3:a][4:a][5:a]amerge=inputs=6,pan=5.1(side)|c0=c0|c1=c1|c2=c2|c3=c3|c4=c4|c5=c5[a]" \ - -map "[a]" -ar 48000 -c:a pcm_s24le -f wav "$d/wav-51-24b-10m.wav" -[ -s "$d/wav-51-24b-10m.s24le.md5" ] || ffmpeg -nostdin -v error -i "$d/wav-51-24b-10m.wav" -f s24le - \ - | md5sum | cut -d' ' -f1 > "$d/wav-51-24b-10m.s24le.md5" -echo "clips in $d" diff --git a/scripts/bench-benchrest.sh b/scripts/bench-benchrest.sh deleted file mode 100755 index b9c3297f..00000000 --- a/scripts/bench-benchrest.sh +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/env bash -# bench-benchrest.sh: the still-image, Matroska, FLAC and zlib rows of lanes/bench.md -# ("lane benchrest", DONE.md gate G6). -# -# Local machine only (DONE.md D7 exception): build with -j6 into CARGO_TARGET_DIR and run each row -# as the best of 5 inside the bench binary. Before each row, wait up to 40 minutes for the 1-minute -# load to be at most 2; the load at the start of the row is printed. Inputs are generated here with -# the local ffmpeg and python (never personal media) into $BENCH_INPUTS, which lives in the tmp dir -# $TMPDIR (default ~/.cache/tmp-benchrest), outside the repo. -# -# Output: one "ROW|..." line per bench row, then "CHECK|..." lines with the self-check. The -# lanes/bench.md "lane benchrest" table is written from these lines. -# -# usage: scripts/bench-benchrest.sh [--no-inputs] [--no-build] -set -euo pipefail - -cd "$(dirname "$0")/.." -REPO="$(pwd)" -export RUSTC_WRAPPER= -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchrest}" -export TMPDIR="${TMPDIR:-$HOME/.cache/tmp-benchrest}" -IN="${BENCH_INPUTS:-$TMPDIR/inputs}" -BIN="$TMPDIR/bin" -OUT="$IN/out" -FF=(ffmpeg -hide_banner -loglevel error -y) -DO_INPUTS=1 -DO_BUILD=1 -for a in "$@"; do - case "$a" in - --no-inputs) DO_INPUTS=0 ;; - --no-build) DO_BUILD=0 ;; - *) echo "unknown option: $a" >&2; exit 2 ;; - esac -done -mkdir -p "$IN" "$BIN" "$OUT" "$TMPDIR" -COMMIT="$(git -C "$REPO" rev-parse --short HEAD)" -echo "# host=local cores=$(nproc) commit=$COMMIT ffmpeg=$(ffmpeg -version | head -1 | awk '{print $3}') python=$(python3 -c 'import numpy; print("numpy " + numpy.__version__)')" - -# ---- 1. inputs ---------------------------------------------------------------------------------- -if [ "$DO_INPUTS" = 1 ]; then - cd "$IN" - # Still images: one testsrc2 frame at 1920x1080. - [ -f png_rgb.png ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=1" -frames:v 1 -pix_fmt rgb24 png_rgb.png - [ -f ref_png_rgb.rgb ] || "${FF[@]}" -i png_rgb.png -f rawvideo -pix_fmt rgb24 ref_png_rgb.rgb - [ -f jpg_420_q2.jpg ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=1" -frames:v 1 -c:v mjpeg -q:v 2 -pix_fmt yuvj420p jpg_420_q2.jpg - [ -f ref_jpg.rgb ] || "${FF[@]}" -i jpg_420_q2.jpg -f rawvideo -pix_fmt rgb24 ref_jpg.rgb - [ -f src_rgba.raw ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=1" -frames:v 1 -pix_fmt rgba -f rawvideo src_rgba.raw - # Matroska: H.264 1080p30 + AAC 128k stereo, 60 s. - [ -f h264_aac_1080p30.mkv ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=30:duration=60" \ - -f lavfi -i "sine=frequency=220:sample_rate=48000:duration=60" -ac 2 \ - -c:v libx264 -preset veryfast -b:v 4M -pix_fmt yuv420p -c:a aac -b:a 128k -f matroska h264_aac_1080p30.mkv - [ -f ref_mkv.v.bin ] || "${FF[@]}" -i h264_aac_1080p30.mkv -map 0:v:0 -c copy -f data ref_mkv.v.bin - [ -f ref_mkv.a.bin ] || "${FF[@]}" -i h264_aac_1080p30.mkv -map 0:a:0 -c copy -f data ref_mkv.a.bin - # FLAC: 60 s stereo 16-bit 44.1 kHz (tones plus pink noise, as benchaudio) and 60 s 5.1 24-bit 48 kHz. - [ -f st16_44k.flac ] || "${FF[@]}" \ - -f lavfi -i "aevalsrc='0.25*sin(2*PI*220*t)+0.12*sin(2*PI*277.18*t)*(0.5+0.5*sin(2*PI*2*t))|0.25*sin(2*PI*222*t)+0.12*sin(2*PI*280*t)*(0.5+0.5*sin(2*PI*2*t))':s=44100:d=60" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=44100:r=44100:seed=1" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=44100:r=44100:seed=2" \ - -filter_complex "[1:a][2:a]amerge=inputs=2,aformat=channel_layouts=stereo[n];[0:a][n]amix=inputs=2:normalize=0,aformat=channel_layouts=stereo[o]" \ - -map "[o]" -c:a flac -sample_fmt s16 st16_44k.flac - [ -f ref_st16.pcm ] || "${FF[@]}" -i st16_44k.flac -f s16le ref_st16.pcm - [ -f m51_48k_24.flac ] || "${FF[@]}" \ - -f lavfi -i "aevalsrc='0.25*sin(2*PI*220*t)|0.25*sin(2*PI*222*t)|0.2*sin(2*PI*110*t)|0.1*sin(2*PI*440*t)|0.15*sin(2*PI*330*t)|0.15*sin(2*PI*150*t)':s=48000:d=60" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=3" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=4" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=5" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=6" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=7" \ - -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=8" \ - -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]amerge=inputs=6,aformat=channel_layouts=5.1[n];[0:a][n]amix=inputs=2:normalize=0,aformat=channel_layouts=5.1[o]" \ - -map "[o]" -c:a flac -sample_fmt s32 -bits_per_raw_sample 24 m51_48k_24.flac - [ -f ref_m51.s32 ] || "${FF[@]}" -i m51_48k_24.flac -f s32le ref_m51.s32 - [ -f ref_m51.s24 ] || "${FF[@]}" -i m51_48k_24.flac -f s24le ref_m51.s24 - # zlib: 64 MiB of mixed text and PCM (python zlib level 6), and 20k blocks of 3 KiB (python zlib - # level 6 each, length-prefixed). The refs are python's md5 of zlib.decompress. - [ -f big_mixed.zlib ] || python3 -I - "$IN" <<'PY' -import hashlib, random, string, struct, sys, zlib -import numpy as np -d = sys.argv[1] -rng = random.Random(1) -words = [''.join(rng.choices(string.ascii_lowercase, k=rng.randint(2, 9))) for _ in range(4000)] -def text(n): - return ' '.join(rng.choices(words, k=n // 5)).encode()[:n] -def pcm(n): - gen = np.random.default_rng(7) - t = np.arange(n // 4) - x = 6000 * np.sin(2 * np.pi * 440 * t / 44100) + 2500 * np.sin(2 * np.pi * 659.3 * t / 44100) \ - + gen.normal(0, 300, t.size) - return np.clip(x, -32768, 32767).astype(' 0 else float("inf") -print(f"max_abs_diff={d.max()} mean_abs_diff={d.mean():.4f} psnr={psnr:.2f}dB exact_samples={np.mean(d == 0) * 100:.2f}%") -PY -} - -# ---- 4. rows ------------------------------------------------------------------------------------- -cd "$IN" -B="$BIN" -FFV="$(ffmpeg -version | head -1 | awk '{print $3}')" - -# ec-image: PNG decode, 1920x1080 RGB8. -l=$(wait_load) -res=$("$B/ec-image-bench" png-dec png_rgb.png "$OUT/png_rgb.rgb" 5) -best=$(field "$res" best_decode_s) -echo "ROW|ec-image|png decode|PNG RGB8 1920x1080 (ffmpeg testsrc2 frame)|$best|$(field "$res" mpix_per_s) Mpix/s, $(field "$res" mb_per_s) MB/s (RGB out)|load1=$l" -if [ "$(md5_of ref_png_rgb.rgb)" = "$(md5_of "$OUT/png_rgb.rgb")" ]; then - echo "CHECK|ec-image png decode|md5 $(md5_of ref_png_rgb.rgb | cut -c1-8) = ffmpeg rawvideo rgb24 (bit-exact, $(stat -c%s ref_png_rgb.rgb) bytes)" -else - echo "CHECK|ec-image png decode|md5 MISMATCH vs ffmpeg: ours $(md5_of "$OUT/png_rgb.rgb") ffmpeg $(md5_of ref_png_rgb.rgb)" -fi - -# ec-image: JPEG decode, 1920x1080 4:2:0 q2. -l=$(wait_load) -res=$("$B/ec-image-bench" jpeg-dec jpg_420_q2.jpg "$OUT/jpg.rgb" 5) -best=$(field "$res" best_decode_s) -echo "ROW|ec-image|jpeg decode|JPEG 4:2:0 q2 1920x1080 (ffmpeg mjpeg -q:v 2)|$best|$(field "$res" mpix_per_s) Mpix/s, $(field "$res" mb_per_s) MB/s (RGB out)|load1=$l" -echo "CHECK|ec-image jpeg decode|vs ffmpeg rawvideo rgb24 decode: $(psnr "$OUT/jpg.rgb" ref_jpg.rgb 1920 1080) (not bit-exact by design; see report)" - -# ec-image: PNG encode of the 1920x1080 RGBA frame, decoded back by ffmpeg. -l=$(wait_load) -res=$("$B/ec-image-bench" png-enc src_rgba.raw 1920 1080 "$OUT/enc.png" 5) -best=$(field "$res" best_encode_s) -echo "ROW|ec-image|png encode|PNG RGBA8 1920x1080 (raw input from ffmpeg testsrc2)|$best|$(field "$res" mpix_per_s) Mpix/s, $(field "$res" mb_per_s) MB/s (raw in), out $(field "$res" out_bytes) bytes|load1=$l" -"${FF[@]}" -i "$OUT/enc.png" -f rawvideo -pix_fmt rgba "$OUT/enc-ffdec.rgba" -if [ "$(md5_of src_rgba.raw)" = "$(md5_of "$OUT/enc-ffdec.rgba")" ]; then - echo "CHECK|ec-image png encode|ffmpeg decode of our PNG md5 $(md5_of src_rgba.raw | cut -c1-8) = source RGBA (bit-exact)" -else - echo "CHECK|ec-image png encode|ffmpeg decode of our PNG md5 MISMATCH: ours $(md5_of "$OUT/enc-ffdec.rgba") source $(md5_of src_rgba.raw)" -fi - -# ec-matroska: demux, H.264 1080p30 + AAC 128k stereo, 60 s. -file_bytes=$(stat -c%s h264_aac_1080p30.mkv) -l=$(wait_load) -res=$("$B/ec-matroska-bench" demux h264_aac_1080p30.mkv "$OUT/mkv" 5) -pk=$(field "$res" packets) -echo "ROW|ec-matroska|demux|H.264 1080p30 + AAC 128k stereo, 60 s (${file_bytes} bytes)|$(field "$res" best_demux_s)|$(field "$res" packets_per_s) packets/s, $(field "$res" mb_per_s) MB/s (payload)|load1=$l packets=$pk" -v_ok=$([ "$(md5_of "$OUT/mkv.s0.bin")" = "$(md5_of ref_mkv.v.bin)" ] && echo match || echo MISMATCH) -a_ok=$([ "$(md5_of "$OUT/mkv.s1.bin")" = "$(md5_of ref_mkv.a.bin)" ] && echo match || echo MISMATCH) -ff_pk=$(( $(ffprobe -v error -count_packets -select_streams v:0 -show_entries stream=nb_read_packets -of csv=p=0 h264_aac_1080p30.mkv) + $(ffprobe -v error -count_packets -select_streams a:0 -show_entries stream=nb_read_packets -of csv=p=0 h264_aac_1080p30.mkv) )) -echo "CHECK|ec-matroska demux|payload md5 vs ffmpeg -c copy -f data: video $v_ok, audio $a_ok; packets ours=$pk ffprobe=$ff_pk" - -# ec-flac: decode, 16-bit stereo 44.1k 60 s and 24-bit 5.1 48k 60 s. -for spec in "st16_44k.flac|ref_st16.pcm|FLAC 16-bit stereo 44.1 kHz 60 s (ffmpeg)|2|16|44100" \ - "m51_48k_24.flac|ref_m51.s32|FLAC 24-bit 5.1 48 kHz 60 s (ffmpeg, s32 container)|6|24|48000"; do - IFS='|' read -r in ref content _ _ _ <<<"$spec" - l=$(wait_load) - res=$("$B/ec-flac-bench" dec "$in" "$OUT/flac-$in.pcm" 5) - best=$(field "$res" best_decode_s); xrt=$(field "$res" x_realtime) - echo "ROW|ec-flac|decode|$content|$best|${xrt}x realtime|load1=$l" - if [ "$(md5_of "$ref")" = "$(md5_of "$OUT/flac-$in.pcm")" ]; then - echo "CHECK|ec-flac decode $in|md5 $(md5_of "$ref" | cut -c1-8) = ffmpeg PCM ($(stat -c%s "$ref") bytes, bit-exact)" - else - echo "CHECK|ec-flac decode $in|md5 MISMATCH vs ffmpeg: ours $(md5_of "$OUT/flac-$in.pcm") ffmpeg $(md5_of "$ref")" - fi -done - -# ec-flac: encode at the export level (EncoderConfig::default()), then ffmpeg decode of our output. -for spec in "ref_st16.pcm|2|16|44100|s16le|FLAC encode 16-bit stereo 44.1 kHz 60 s (default level)" \ - "ref_m51.s24|6|24|48000|s24le|FLAC encode 24-bit 5.1 48 kHz 60 s (default level)"; do - IFS='|' read -r src ch bits rate fmt content <<<"$spec" - l=$(wait_load) - res=$("$B/ec-flac-bench" enc "$src" "$ch" "$bits" "$rate" "$OUT/enc-$bits.flac" 5) - best=$(field "$res" best_encode_s); xrt=$(field "$res" x_realtime) - echo "ROW|ec-flac|encode|$content|$best|${xrt}x realtime, $(field "$res" kbps) kb/s|load1=$l" - "${FF[@]}" -i "$OUT/enc-$bits.flac" -f "$fmt" "$OUT/enc-$bits-ffdec.pcm" - if [ "$(md5_of "$src")" = "$(md5_of "$OUT/enc-$bits-ffdec.pcm")" ]; then - echo "CHECK|ec-flac encode $bits-bit|ffmpeg decode of our FLAC md5 $(md5_of "$src" | cut -c1-8) = source PCM (bit-exact)" - else - echo "CHECK|ec-flac encode $bits-bit|ffmpeg decode of our FLAC md5 MISMATCH: ours $(md5_of "$OUT/enc-$bits-ffdec.pcm") source $(md5_of "$src")" - fi -done - -# ec-inflate: one zlib stream, 64 MiB mixed text and PCM. -l=$(wait_load) -res=$("$B/ec-inflate-bench" zlib big_mixed.zlib "$OUT/big.bin" 5) -best=$(field "$res" best_inflate_s) -echo "ROW|ec-inflate|zlib inflate|zlib, 64 MiB mixed text (32 MiB) and 16-bit PCM (32 MiB), python level 6|$best|$(field "$res" mb_per_s) MB/s out|load1=$l in_bytes=$(field "$res" in_bytes)" -if [ "$(md5_of "$OUT/big.bin")" = "$(cut -d' ' -f1 ref_big.md5)" ]; then - echo "CHECK|ec-inflate zlib|md5 $(cut -c1-8 ref_big.md5) = python zlib.decompress ($(field "$res" out_bytes) bytes)" -else - echo "CHECK|ec-inflate zlib|md5 MISMATCH vs python: ours $(md5_of "$OUT/big.bin") python $(cut -d' ' -f1 ref_big.md5)" -fi -rm -f "$OUT/big.bin" - -# ec-inflate: 20k length-prefixed zlib streams of 3 KiB text each (subtitle-sized packets). -l=$(wait_load) -res=$("$B/ec-inflate-bench" blocks blocks_3k.bin "$OUT/blocks.bin" 5) -best=$(field "$res" best_inflate_s) -echo "ROW|ec-inflate|zlib inflate, many blocks|20000 zlib streams of 3 KiB text (python level 6, subtitle-sized)|$best|$(field "$res" mb_per_s) MB/s out, $(field "$res" streams) streams|load1=$l" -if [ "$(md5_of "$OUT/blocks.bin")" = "$(cut -d' ' -f1 ref_blocks.md5)" ]; then - echo "CHECK|ec-inflate blocks|md5 $(cut -c1-8 ref_blocks.md5) = python zlib.decompress per block ($(field "$res" out_bytes) bytes)" -else - echo "CHECK|ec-inflate blocks|md5 MISMATCH vs python: ours $(md5_of "$OUT/blocks.bin") python $(cut -d' ' -f1 ref_blocks.md5)" -fi -rm -f "$OUT/blocks.bin" -echo "# ffmpeg $FFV" diff --git a/scripts/bench-rows-clips.sh b/scripts/bench-rows-clips.sh deleted file mode 100755 index f7cfc913..00000000 --- a/scripts/bench-rows-clips.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash -# bench-rows-clips.sh: generate the ffmpeg clips used by scripts/bench-rows.sh. -# Clips go to $BENCH_CLIPS (default ~/.cache/benchrows-clips), never into the repo. -# The h264 input is the personal 1080p30 clip that ec-bench's real_video() picks first -# (first h264 mp4 in ~/Videos or ~/Downloads, sorted by path); it is only read, never copied. -set -euo pipefail -d=${BENCH_CLIPS:-$HOME/.cache/benchrows-clips} -h264_src=${H264_SRC:-$HOME/Downloads/reelk.mp4} -mkdir -p "$d" -ff() { ffmpeg -nostdin -v error -y "$@"; } - -# VP8 1080p30, libvpx, 10 s, 4 Mb/s, realtime deadline. -[ -s "$d/vp8-1080p30.ivf" ] || ff -f lavfi -i testsrc2=size=1920x1080:rate=30 -t 10 \ - -c:v libvpx -b:v 4M -deadline realtime -cpu-used 8 -pix_fmt yuv420p "$d/vp8-1080p30.ivf" - -# VP9 profile 0 1080p30, libvpx-vp9, 10 s, 4 tile columns (threads have work to split). -[ -s "$d/vp9-1080p30-tile4.ivf" ] || ff -f lavfi -i testsrc2=size=1920x1080:rate=30 -t 10 \ - -c:v libvpx-vp9 -tile-columns 2 -row-mt 1 -b:v 4M -deadline realtime -cpu-used 8 \ - -pix_fmt yuv420p "$d/vp9-1080p30-tile4.ivf" - -# AC-3 5.1 at 448 kb/s, 60 s: six independent pink-noise channels, one per 5.1 speaker -# (a mono source upmixed would fill only the centre channel and make the parity test vacuous). -ac3_in=() -for seed in 1 2 3 4 5 6; do - ac3_in+=(-f lavfi -i "anoisesrc=d=60:c=pink:r=48000:a=0.2:seed=$seed") -done -[ -s "$d/ac3-5.1-448k.ac3" ] || ff "${ac3_in[@]}" -filter_complex \ - "[0:a][1:a][2:a][3:a][4:a][5:a]amerge=inputs=6,pan=5.1(side)|c0=c0|c1=c1|c2=c2|c3=c3|c4=c4|c5=c5[a]" \ - -map "[a]" -ar 48000 -c:a ac3 -b:a 448k -f ac3 "$d/ac3-5.1-448k.ac3" - -# H264 Annex-B, first 10 s of the h264 input, stream copy (same extraction as ec-bench). -[ -s "$d/h264-1080p30-10s.264" ] || ff -t 10 -i "$h264_src" -an -c:v copy \ - -bsf:v h264_mp4toannexb -f h264 "$d/h264-1080p30-10s.264" - -# ffmpeg reference outputs (raw, the decoded samples the crates must match). -[ -s "$d/vp8-1080p30.yuv.md5" ] || ffmpeg -nostdin -v error -i "$d/vp8-1080p30.ivf" \ - -f rawvideo -pix_fmt yuv420p - | md5sum | cut -d' ' -f1 > "$d/vp8-1080p30.yuv.md5" -[ -s "$d/vp9-1080p30-tile4.yuv.md5" ] || ffmpeg -nostdin -v error -i "$d/vp9-1080p30-tile4.ivf" \ - -f rawvideo -pix_fmt yuv420p - | md5sum | cut -d' ' -f1 > "$d/vp9-1080p30-tile4.yuv.md5" -[ -s "$d/ac3-5.1-448k.ref.f32" ] || ffmpeg -nostdin -v error -i "$d/ac3-5.1-448k.ac3" \ - -f f32le -acodec pcm_f32le -ac 6 "$d/ac3-5.1-448k.ref.f32" -ls -l "$d" diff --git a/scripts/bench-rows-parity.py b/scripts/bench-rows-parity.py deleted file mode 100644 index 3e6161b1..00000000 --- a/scripts/bench-rows-parity.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python3 -"""bench-rows-parity.py REF.f32 OUT.f32 CHANNELS: per-channel correlation of two -interleaved float32 streams (ffmpeg reference vs the crate's output). -Prints one line per channel and the sample counts. Run as: python3 -I ...""" -import sys -import numpy as np - -ref = np.fromfile(sys.argv[1], dtype=" 0 and b.std() > 0 else float("nan") - err = np.max(np.abs(a - b)) - worst = min(worst, corr) - print(f"ch{c} corr={corr:.6f} max_abs_err={err:.6f}") -print(f"min_corr={worst:.6f} tolerance=0.999 {'PASS' if worst >= 0.999 else 'FAIL'}") diff --git a/scripts/bench-rows-vp8.rs b/scripts/bench-rows-vp8.rs deleted file mode 100644 index 8c93b1b2..00000000 --- a/scripts/bench-rows-vp8.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! VP8 decode bench harness for scripts/bench-rows.sh. The script copies this file into -//! crates/ec-vp8/examples/ for the run and deletes the copy afterwards. -//! -//! usage: vp8_ivf [reps] [raw-out|-] -//! Times `reps` full decodes with a fresh decoder each (best wall time, output not -//! written). With a third argument, one more untimed pass writes the visible planes as -//! raw yuv420p to that path (`/dev/stdout` for a pipe into md5sum). -use ec_vp8::decode::Decoder; -use std::time::Instant; - -fn main() { - let args: Vec = std::env::args().collect(); - let bytes = std::fs::read(&args[1]).expect("read ivf"); - let reps: usize = args.get(2).map_or(5, |s| s.parse().expect("reps")); - let mut frames: Vec<&[u8]> = Vec::new(); - let mut pos = 32; - while pos + 12 <= bytes.len() { - let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize; - frames.push(&bytes[pos + 12..pos + 12 + sz]); - pos += 12 + sz; - } - let mut best = f64::MAX; - let mut shown = 0usize; - for _ in 0..reps { - let mut dec = Decoder::new(); - let t = Instant::now(); - shown = 0; - for f in &frames { - if dec.decode(f).expect("vp8 decode").is_some() { - shown += 1; - } - } - best = best.min(t.elapsed().as_secs_f64()); - } - println!( - "frames={} shown={} best_secs={best:.3} fps={:.2}", - frames.len(), - shown, - shown as f64 / best - ); - if let Some(path) = args.get(3) { - let mut out = Vec::new(); - let mut dec = Decoder::new(); - for f in &frames { - if let Some(pic) = dec.decode(f).expect("vp8 decode") { - let (w, h) = (usize::from(pic.width), usize::from(pic.height)); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - for r in 0..h { - out.extend_from_slice(&pic.y[r * pic.stride..r * pic.stride + w]); - } - for plane in [&pic.u, &pic.v] { - for r in 0..ch { - out.extend_from_slice(&plane[r * pic.uv_stride..r * pic.uv_stride + cw]); - } - } - } - } - std::fs::write(path, out).expect("write raw"); - } -} diff --git a/scripts/bench-rows.sh b/scripts/bench-rows.sh deleted file mode 100755 index d60a8a91..00000000 --- a/scripts/bench-rows.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env bash -# bench-rows.sh: local best-of-5 decode rows (DONE.md D7: speed is measured on the local -# 12-core machine). Rows: ec-vp8 decode, ec-vp9 decode at 1/2/4/6 tile threads, ec-ac3 5.1 -# 448k decode with parity, ec-h264 decode at 1/2/4/6 cores (the decoder runs 1 thread). -# Every row starts only when the 1-minute load is below 3; otherwise it waits in 290 s -# steps for at most 1 h (12 steps). Clips come from scripts/bench-rows-clips.sh. -# Usage: scripts/bench-rows.sh (prints markdown rows; also saved under $BENCH_CLIPS) -set -euo pipefail -root=$(cd "$(dirname "$0")/.." && pwd) -clips=${BENCH_CLIPS:-$HOME/.cache/benchrows-clips} -export CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchrows} -export TMPDIR=${TMPDIR:-$HOME/.cache/tmp-benchrows} -mkdir -p "$TMPDIR" -rel=$CARGO_TARGET_DIR/release -today=$(date +%F) -res="$clips/bench-rows-$today.md" -: > "$res" - -# Prints the 1-minute load once it is below 3. Returns 1 after 1 h of waiting. -gate() { - local steps=0 l - while :; do - l=$(cut -d' ' -f1 /proc/loadavg) - if awk -v l="$l" 'BEGIN { exit !(l < 3) }'; then echo "$l"; return 0; fi - if [ "$steps" -ge 12 ]; then echo "$l"; return 1; fi - sleep 290 - steps=$((steps + 1)) - done -} - -# emit -emit() { - printf '| %s | %s | %s | local 12-core | %s | %s | %s | %s | %s |\n' \ - "$today" "$1" "$2" "$3" "$4" "$5" "$6" "$7" | tee -a "$res" -} - -# ---- build (outside the gate; nothing is timed here) ---- -cd "$root" -cargo build --release -q -p ec-vp9 --example decode_ivf -cargo build --release -q -p ec-ac3 --example ac3dec -cargo build --release -q --manifest-path tools/ec-bench/Cargo.toml -cp scripts/bench-rows-vp8.rs crates/ec-vp8/examples/vp8_ivf.rs -trap 'rm -f "$root/crates/ec-vp8/examples/vp8_ivf.rs"' EXIT -cargo build --release -q -p ec-vp8 --example vp8_ivf - -echo "| date | crate | clip | host | threads | load 1m at start | fps (best of 5) | realtime x | check |" -echo "|---|---|---|---|---|---|---|---|---|" - -# ---- ec-vp8 decode, 1080p30 libvpx clip, 1 thread (the decoder has no thread knob) ---- -vp8=$clips/vp8-1080p30.ivf -if load=$(gate); then - line=$("$rel/examples/vp8_ivf" "$vp8" 5) - fps=$(sed -n 's/.*fps=\([0-9.]*\).*/\1/p' <<<"$line") - raw=$TMPDIR/vp8.yuv - "$rel/examples/vp8_ivf" "$vp8" 1 "$raw" >/dev/null - got=$(md5sum "$raw" | cut -d' ' -f1); rm -f "$raw" - want=$(cat "$clips/vp8-1080p30.yuv.md5") - check="md5 $([ "$got" = "$want" ] && echo "= ffmpeg" || echo "!= ffmpeg ($got)")" - emit ec-vp8 "1080p30 libvpx 10 s, 4 Mb/s" 1 "$load" "$fps" "$(awk -v f="$fps" 'BEGIN{printf "%.2fx", f/30}')" "$check" -else - emit ec-vp8 "1080p30 libvpx 10 s" 1 "$load" - - "load gate timed out" -fi - -# ---- ec-vp9 decode, 1080p30 profile 0, 4 tile columns, threads 1/2/4/6 ---- -vp9=$clips/vp9-1080p30-tile4.ivf -want=$(cat "$clips/vp9-1080p30-tile4.yuv.md5") -for t in 1 2 4 6; do - if load=$(gate); then - best=0 - for _ in 1 2 3 4 5; do - f=$("$rel/examples/decode_ivf" "$vp9" "$t" | sed -n 's/.*decode_fps=\([0-9.]*\).*/\1/p') - best=$(awk -v a="$best" -v b="$f" 'BEGIN{print (b > a ? b : a)}') - done - raw=$TMPDIR/vp9.yuv - EC_RAW_OUT=$raw "$rel/examples/decode_ivf" "$vp9" "$t" >/dev/null - got=$(md5sum "$raw" | cut -d' ' -f1); rm -f "$raw" - check="md5 $([ "$got" = "$want" ] && echo "= ffmpeg" || echo "!= ffmpeg ($got)")" - emit ec-vp9 "1080p30 profile 0 libvpx-vp9 10 s, 4 tile cols" "$t" "$load" "$best" \ - "$(awk -v f="$best" 'BEGIN{printf "%.2fx", f/30}')" "$check" - else - emit ec-vp9 "1080p30 profile 0 tile4" "$t" "$load" - - "load gate timed out" - fi -done - -# ---- ec-ac3 decode, AC-3 5.1 448 kb/s, 60 s; speed to /dev/null, parity to a file ---- -ac3=$clips/ac3-5.1-448k.ac3 -if load=$(gate); then - best=0 - for _ in 1 2 3 4 5; do - rt=$("$rel/examples/ac3dec" "$ac3" /dev/null | awk -F'\t' '/^realtime/{print $2}') - best=$(awk -v a="$best" -v b="$rt" 'BEGIN{print (b > a ? b : a)}') - done - out=$TMPDIR/ac3.f32 - errs=$("$rel/examples/ac3dec" "$ac3" "$out" | awk -F'\t' '/^errors/{print $2}') - par=$(python3 -I "$root/scripts/bench-rows-parity.py" "$clips/ac3-5.1-448k.ref.f32" "$out" 6 | tail -1) - rm -f "$out" - emit ec-ac3 "AC-3 5.1 448 kb/s 60 s (5.1 layout)" 1 "$load" "-" "${best}x" \ - "decode errors $errs; parity: $par" -else - emit ec-ac3 "AC-3 5.1 448 kb/s" 1 "$load" - - "load gate timed out" -fi - -# ---- ec-h264 decode: the bench.log:145 row, from tools/ec-bench itself, pinned to 1/2/4/6 -# cores. The decoder has no thread knob (ec-h264 spawns threads only in enc/), so the -# core count is the only parallelism available; 5 full ec-bench runs per core count. ---- -bench=$CARGO_TARGET_DIR/release/ec-bench -for n in 1 2 4 6; do - best="" - loads="" - for _ in 1 2 3 4 5; do - if load=$(gate); then - line=$(taskset -c "0-$((n - 1))" "$bench" | grep '^| ec-h264 | decode') - ms=$(awk -F'|' '{gsub(/ /,"",$6); print $6}' <<<"$line") - frames=$(awk -F'|' '{print $4}' <<<"$line" | sed -n 's/.*, \([0-9]*\) frames.*/\1/p') - loads="$loads $load" - if [ -z "$best" ] || awk -v a="$ms" -v b="$best" 'BEGIN{exit !(a < b)}'; then - best=$ms; bestframes=$frames - fi - else - loads="$loads gate-timeout" - fi - done - fps=$(awk -v f="$bestframes" -v m="$best" 'BEGIN{printf "%.2f", f / (m / 1000)}') - emit ec-h264 "1080p30 film 10 s, ec-bench row (wall best $best ms, $bestframes frames)" 1 \ - "$(awk '{print $1}' <<<"${loads# }")" "$fps" "$(awk -v f="$fps" 'BEGIN{printf "%.2fx", f/30}')" \ - "cores pinned $n, decoder threads 1; loads of 5 runs:$loads" -done -echo "saved: $res" >&2 diff --git a/scripts/bench_hevc_enc.sh b/scripts/bench_hevc_enc.sh deleted file mode 100755 index 093df1fc..00000000 --- a/scripts/bench_hevc_enc.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -# bench_hevc_enc.sh: 1080p30 synthetic encode bench for ec-h265 (8 and 10 bit), prints fps and sha1. -# Run on a server via scripts/remote-run.sh. Env: N (frames, 30), RUNS (3), THREADS (4). -set -e -N=${N:-30}; RUNS=${RUNS:-3}; T=${THREADS:-4} -D=$HOME/.cache/hevc10simd2-bench; mkdir -p "$D" -[ -s $D/c8.yuv ] || ffmpeg -loglevel error -y -f lavfi -i "testsrc2=size=1920x1080:rate=30:duration=1,scroll=v=0.02" -frames:v $N -pix_fmt yuv420p -f rawvideo $D/c8.yuv -[ -s $D/c10.yuv ] || ffmpeg -loglevel error -y -f lavfi -i "testsrc2=size=1920x1080:rate=30:duration=1,scroll=v=0.02" -frames:v $N -pix_fmt yuv420p10le -f rawvideo $D/c10.yuv -cargo build --release -p ec-h265 --example hevc_gop 2>&1 | tail -1 -BIN=${CARGO_TARGET_DIR:-target}/release/examples/hevc_gop -echo "load: $(cat /proc/loadavg)" -for bd in 8 10; do - for r in $(seq $RUNS); do - s=$(date +%s.%N) - EC_H265_BITDEPTH=$bd EC_H265_THREADS=$T EC_H265_TIMING=1 $BIN encode $D/c$bd.yuv 1920 1080 8 30 $D/o$bd.hevc $D/r$bd.yuv >/dev/null 2>$D/t.log - e=$(date +%s.%N) - echo "bd=$bd run=$r enc=$(cut -d" " -f2 $D/t.log) fps=$(awk "BEGIN{printf \"%.2f\", $N/($e-$s)}") sha=$(sha1sum $D/o$bd.hevc | cut -c1-12) rec=$(sha1sum $D/r$bd.yuv | cut -c1-12)" - done -done -echo "load after: $(cat /proc/loadavg)" diff --git a/scripts/changed-crates.sh b/scripts/changed-crates.sh deleted file mode 100755 index 95e148ea..00000000 --- a/scripts/changed-crates.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash -# Print `-p ` lines for the workspace crates affected by a change, for use as -# cargo test $(scripts/changed-crates.sh) -# -# Changed files = `git diff ...HEAD` + uncommitted (staged/unstaged) + untracked. -# Each changed file maps to the workspace package whose directory contains it. Those -# packages are then expanded to all their reverse dependencies inside the workspace -# (path dependencies only). A change to a root file (Cargo.toml, Cargo.lock, .config/, -# .cargo/, rust-toolchain*) selects every workspace crate. -# ec-hw and ec-va are dropped unless they changed themselves (GPU; no hardware encode). -# -# Usage: scripts/changed-crates.sh [BASE_REF] (BASE_REF defaults to main) -set -euo pipefail - -base="${1:-main}" -root="$(git rev-parse --show-toplevel)" -cd "$root" - -meta_file="$(mktemp)" -trap 'rm -f "$meta_file"' EXIT -cargo metadata --format-version 1 --no-deps > "$meta_file" - -changed="$({ - git diff --name-only "$base...HEAD" - git diff --name-only HEAD - git ls-files --others --exclude-standard -} | sort -u | jq -R -s 'split("\n") | map(select(length > 0))')" - -jq -r --argjson files "$changed" ' - .workspace_root as $wr - | [ .packages[] | select(.source == null) - | { name, - dir: (.manifest_path | sub("/Cargo.toml$"; "") | ltrimstr($wr + "/")), - deps: [ .dependencies[] | select(.path != null) | .name ] } ] as $pk - | ($files | any(test("^(Cargo\\.toml|Cargo\\.lock|rust-toolchain[^/]*|\\.config/.*|\\.cargo/.*)$"))) as $rootChanged - | [ $pk[] | select(.dir != "") as $p - | select([$files[] | select(startswith($p.dir + "/"))] | length > 0) - | .name ] | unique as $changedPkgs - | (if $rootChanged then [$pk[].name] else $changedPkgs end) as $seeds - | def closure($cur): - ([ $pk[] | select(any(.deps[]; . as $x | any($cur[]; . == $x))) | .name ] + $cur | unique) as $next - | if ($next | length) == ($cur | length) then $cur else closure($next) end; - closure($seeds) - | map(. as $n - | select((["ec-hw", "ec-va"] | any(. == $n) | not) or ($changedPkgs | any(. == $n)))) - | sort[] - | "-p " + . -' "$meta_file" diff --git a/scripts/cmp422-ffmpeg.py b/scripts/cmp422-ffmpeg.py deleted file mode 100755 index 9ddb144f..00000000 --- a/scripts/cmp422-ffmpeg.py +++ /dev/null @@ -1,313 +0,0 @@ -#!/usr/bin/env python3 -"""ffmpeg pixel-oracle comparator for ec-av1 4:2:2 (and 4:2:0 / 4:4:4 controls). - -Discipline (oracle-comparator-liveness-control): - -1. Geometry is an EXPLICIT argument read from the SEQUENCE HEADER via ffprobe - (coded_width / coded_height / pix_fmt of the AV1 stream), never derived - from a file size. A raw frame whose byte length disagrees with the geometry - is a hard error. -2. Plane attribution is per FRAME, from that frame's own plane lengths, with a - monotone cursor -- never absolute thresholds from frame 0. -3. A wrong SAMPLE is one bps-wide unit. At 10 bit the comparator walks - 16-bit LE samples, so the top bits cannot hide. -4. A count over zero frames is a hard error (vacuous 0/0/0). -5. Decode-order (ours, EC_AV1_FINAL_DUMP) -> display-order (ffmpeg rawvideo) - mapping is derived by LUMA-IDENTITY content match under a strictly - increasing assignment, then re-verified per frame. Exactly one decode frame - must have no display partner: the hidden alt-ref picture. -""" -import json -import os -import re -import subprocess -import sys - -SS = {"420": (1, 1), "422": (1, 0), "444": (0, 0), "440": (0, 1)} -DEPTH_RE = re.compile(r"^yuv(\d{3})p(\d*)(?:le)?$") - - -def probe_geometry(obu): - """ffprobe reads the AV1 SEQUENCE HEADER: coded_width/coded_height and the - chroma format/depth it implies. Never the raw output's byte length.""" - r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v", - "-show_entries", "stream=coded_width,coded_height,pix_fmt", - "-of", "csv=p=0", obu], capture_output=True, check=True) - parts = r.stdout.decode().strip().split(",") - mw, h, pix = parts[0], parts[1], parts[2] - m = DEPTH_RE.match(pix) - if not m: - raise SystemExit(f"{obu}: unsupported pix_fmt {pix!r} (need a planar yuv*p[le])") - ss = SS.get(m.group(1)) - if ss is None: - raise SystemExit(f"{obu}: unknown chroma tag C{m.group(1)} in pix_fmt {pix!r}") - depth = int(m.group(2)) if m.group(2) else 8 - return int(mw), int(h), ss[0], ss[1], depth, pix - - -def plane_spans(w, h, ss_x, ss_y, bps): - cw = -(-w // (1 << ss_x)) - ch = -(-h // (1 << ss_y)) - sizes = (w * h, cw * ch, cw * ch) - return sizes, sum(sizes) * bps - - -def frame_files(prefix): - out, i = [], 0 - while os.path.isfile(f"{prefix}.f{i}"): - out.append(f"{prefix}.f{i}") - i += 1 - return out - - -def ffmpeg_frames(obu, pix): - r = subprocess.run(["ffmpeg", "-v", "error", "-i", obu, "-f", "rawvideo", - "-pix_fmt", pix, "-"], capture_output=True) - if r.returncode != 0: - raise SystemExit(f"{obu}: ffmpeg refused: {r.stderr.decode()[-300:]}") - return r.stdout - - -def split(raw, sizes, fsz, cell): - if not raw: - raise SystemExit(f"{cell}: ffmpeg produced ZERO bytes -- a 0/0/0 here is vacuous") - if len(raw) % fsz: - raise SystemExit(f"{cell}: ffmpeg rawvideo is {len(raw)} B, not a whole " - f"multiple of the {fsz} B frame the geometry implies") - return [raw[i * fsz:(i + 1) * fsz] for i in range(len(raw) // fsz)] - - -def _matchings(cands, disp_n, cap=64, node_cap=4_000_000): - """Every way to assign each decode frame either a distinct display partner - or the hidden role, covering the display side exactly. Enumerated, not - guessed: a duplicated picture can make the assignment genuinely ambiguous, - and the caller then has to show the ambiguity does not change the answer. - - Two bounds, both learned the hard way: without the feasibility prune, an - instance whose candidate lists cannot cover the display side explores the - whole 2**frames tree before returning empty (that is what made three - 43-frame cells burn a 300 s cap with 15 minutes of user CPU and never - finish), and without a node cap a pathological instance would hang the - comparator instead of reporting.""" - sols = [] - nodes = 0 - - def dfs(i, used, acc, hid): - nonlocal nodes - nodes += 1 - if nodes > node_cap: - raise SystemExit(f"the decode->display assignment search exceeded {node_cap} nodes " - f"at frame {i} of {len(cands)} ({disp_n} display frames) -- this " - f"instance is not enumerable; report it rather than hang") - if len(sols) >= cap: - return - if disp_n - len(used) > len(cands) - i: - return # not enough decode frames left to cover the display side - if i == len(cands): - if len(used) == disp_n: - sols.append((dict(acc), list(hid))) - return - for di in cands[i]: - if di not in used: - used.add(di) - acc[i] = di - dfs(i + 1, used, acc, hid) - del acc[i] - used.discard(di) - hid.append(i) - dfs(i + 1, used, acc, hid) - hid.pop() - - dfs(0, set(), {}, []) - return sols - - -def map_decode_to_display(ours, disp, sizes, bps, cell): - """Identity of each decode-order frame is carried by its LUMA plane; full-frame - identity is preferred when it exists. Every assignment that covers the - display side is enumerated, so a duplicated picture shows up as an - explicit solution COUNT rather than a silent pick. Real altref streams - REORDER display against decode (measured: decode f2..f8 -> display - 7,3,1,2,5,4,6), so no monotonicity prior is applied -- an unjustified one - is exactly the class of silent mismatch this instrument exists to catch.""" - luma = sizes[0] * bps - for use_full in (True, False): - cands = [[di for di, d in enumerate(disp) - if o[:luma] == d[:luma] and (o == d or not use_full)] for o in ours] - sols = _matchings(cands, len(disp)) - if sols: - if min(len(h) for _, h in sols) > 4: - raise SystemExit(f"{cell}: {min(len(h) for _, h in sols)} decode frames have " - f"no luma-identical display partner -- LUMA itself " - f"diverges, so this is not a hidden-alt-ref count " - f"(class av1-frame-count-vs-pixel-divergence)") - return sols - raise SystemExit(f"{cell}: luma identity never covers the display side " - f"({len(ours)} decode frames, {len(disp)} display frames) " - f"-- the frame-count or per-frame identity claim is wrong") - - - -def compare(cell, ours_prefix, disp, w, h, ss_x, ss_y, depth, want_hidden=None): - bps = 1 if depth <= 8 else 2 - sizes, fsz = plane_spans(w, h, ss_x, ss_y, bps) - ours = [open(p, "rb").read() for p in frame_files(ours_prefix)] - if not ours: - raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames from us -- vacuous 0/0/0") - for i, o in enumerate(ours): - if len(o) != fsz: - raise SystemExit(f"{cell}: our decode frame {i} is {len(o)} B, geometry " - f"{w}x{h} ss={ss_x}{ss_y} depth={depth} implies {fsz} B") - sols = map_decode_to_display(ours, disp, sizes, bps, cell) - - def measure(mapping, hidden): - tot = [0, 0, 0] - per_disp = [[0, 0, 0] for _ in disp] - per_dec, first = [], None - bb_all = [[None, None, None, None] for _ in range(3)] - for oi, a in enumerate(ours): - if oi in hidden: - per_dec.append(None) - continue - b = disp[mapping[oi]] - fcount, off = [0, 0, 0], 0 - for pi, sz in enumerate(sizes): - pw = w if pi == 0 else -(-w // (1 << ss_x)) - for i in range(sz): - s = i * bps - if a[off + s:off + s + bps] != b[off + s:off + s + bps]: - fcount[pi] += 1 - tot[pi] += 1 - per_disp[mapping[oi]][pi] += 1 - r, c = divmod(i, pw) - bb = bb_all[pi] - if bb[0] is None or r < bb[0]: - bb[0] = r - if bb[1] is None or r > bb[1]: - bb[1] = r - if bb[2] is None or c < bb[2]: - bb[2] = c - if bb[3] is None or c > bb[3]: - bb[3] = c - if first is None: - first = (mapping[oi], oi, "YUV"[pi], r, c, - int.from_bytes(a[off + s:off + s + bps], "little"), - int.from_bytes(b[off + s:off + s + bps], "little")) - off += sz * bps - per_dec.append(fcount) - return tot, per_disp, per_dec, first, bb_all - - def xor_plane_counts(a, b): - """Per-plane differing-SAMPLE counts at 8-bit, at C speed: XOR the two - planes as big ints, then count non-zero bytes per plane. Equivalent to - the per-sample loop above, and the only reason a 43-frame cell with 64 - candidate assignments used to cost half an hour.""" - z = int.from_bytes(a, "big") ^ int.from_bytes(b, "big") - zb = z.to_bytes(len(a), "big") - out, off = [], 0 - for sz in sizes: - seg = zb[off:off + sz] - off += sz - out.append(len(seg) - seg.count(0)) - return out - - if bps == 1: - pair_cache = {} - - def pair_total(oi, di): - v = pair_cache.get((oi, di)) - if v is None: - v = xor_plane_counts(ours[oi], disp[di]) - pair_cache[(oi, di)] = v - return v - - sol_totals = [] - for m, _h in sols: - t = [0, 0, 0] - for oi, di in m.items(): - p = pair_total(oi, di) - t[0] += p[0] - t[1] += p[1] - t[2] += p[2] - sol_totals.append(tuple(t)) - if len(set(sol_totals)) > 1: - raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS " - f"({len(sols)} solutions) and they DISAGREE on the counts " - f"{sorted(set(sol_totals))} -- pick the identity source explicitly, " - f"this instrument will not choose for you") - tot = list(sol_totals[0]) - mapping, hidden = sols[0] - if tot == [0, 0, 0]: - per_disp = [[0, 0, 0] for _ in disp] - per_dec = [None if oi in hidden else [0, 0, 0] for oi in range(len(ours))] - first, bbox = None, [[None, None, None, None] for _ in range(3)] - else: - tot, per_disp, per_dec, first, bbox = measure(mapping, hidden) - else: - # 16-bit planes: the sample loop below is the only path today. - if all(all(ours[oi] == disp[di] for oi, di in m.items()) for m, h in sols): - hidden0 = sols[0][1] - measured = [([0, 0, 0], [[0, 0, 0] for _ in disp], - [None if oi in hidden0 else [0, 0, 0] for oi in range(len(ours))], - None, [[None, None, None, None] for _ in range(3)])] - measured *= len(sols) - else: - measured = [measure(m, h) for m, h in sols] - totals = {tuple(t[0]) for t in measured} - if len(totals) > 1: - raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS " - f"({len(sols)} solutions) and they DISAGREE on the counts " - f"{sorted(totals)} -- pick the identity source explicitly, " - f"this instrument will not choose for you") - tot, per_disp, per_dec, first, bbox = measured[0] - mapping, hidden = sols[0] - if want_hidden is not None and len(hidden) != want_hidden: - raise SystemExit(f"{cell}: {len(hidden)} hidden decode frame(s) {hidden}, " - f"expected {want_hidden} -- the frame-count claim changed") - return {"cell": cell, "status": "BYTE-EXACT" if tot == [0, 0, 0] else "DIVERGES", - "w": w, "h": h, "ss": f"{ss_x}{ss_y}", "depth": depth, "pix": pix_of(ss_x, ss_y, depth), - "decode_frames": len(ours), "display_frames": len(disp), - "hidden_decode": hidden, "mapping_solutions": len(sols), - "Y": tot[0], "U": tot[1], "V": tot[2], - "first": first, "bbox": bbox, - "per_decode_frame": per_dec, "per_display_frame": per_disp} - - -def pix_of(ss_x, ss_y, depth): - tag = next(k for k, v in SS.items() if v == (ss_x, ss_y)) - return f"yuv{tag}p" + ("" if depth <= 8 else f"{depth}le") - - -def flip(disp, sizes, bps, disp_index, plane, sample_index): - """Flip bit 0 of one oracle SAMPLE's low byte: exactly +1 wrong sample in - both depths (2**bitdepth < 2**16, so nothing carries out of the container). - Returns a new list; the caller drops it to restore.""" - new = list(disp) - buf = bytearray(new[disp_index]) - buf[sum(sizes[:plane]) * bps + sample_index * bps] ^= 1 - new[disp_index] = bytes(buf) - return new - - -def run(cell, obu, ours_prefix, want_hidden=None, json_out=False): - w, h, ssx, ssy, depth, pix = probe_geometry(obu) - bps = 1 if depth <= 8 else 2 - sizes, fsz = plane_spans(w, h, ssx, ssy, bps) - disp = split(ffmpeg_frames(obu, pix), sizes, fsz, cell) - res = compare(cell, ours_prefix, disp, w, h, ssx, ssy, depth, want_hidden) - if json_out: - print(json.dumps(res)) - else: - f = res["first"] - fs = "none" if f is None else \ - f"disp f{f[0]} (decode f{f[1]}) {f[2]} (r{f[3]},c{f[4]}) ours={f[5]} ffmpeg={f[6]}" - print(f"{cell}: {res['status']} {res['decode_frames']}df/" - f"{res['display_frames']}shown hidden={res['hidden_decode']} " - f"Y={res['Y']} U={res['U']} V={res['V']} first: {fs}") - return res, disp, sizes, fsz, bps - - -if __name__ == "__main__": - cell, obu, prefix = sys.argv[1:4] - wh = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4].isdigit() else None - run(cell, obu, prefix, wh, "--json" in sys.argv) diff --git a/scripts/cmpff.py b/scripts/cmpff.py deleted file mode 120000 index 33d64e4b..00000000 --- a/scripts/cmpff.py +++ /dev/null @@ -1 +0,0 @@ -cmp422-ffmpeg.py \ No newline at end of file diff --git a/scripts/flipctl-422.py b/scripts/flipctl-422.py deleted file mode 100755 index 901b4176..00000000 --- a/scripts/flipctl-422.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python3 -"""Flip control: prove the ffmpeg comparator BITES, before any verdict. - -[`cmp422-ffmpeg`][c] re-derives the decode->display assignment from LUMA -identity on every call, so a flipped oracle sample can never be re-mapped -- -the identity it keys on is exactly what the flip breaks. This control -therefore maps ONCE from the untouched streams and then flips one SAMPLE per -arm with the mapping PINNED, which is the only way to ask "does one wrong -sample move the count by exactly one?". - -Two independent directions, both required to pass: - -* **oracle arm** -- flip one ffmpeg sample. The plane that owns it must move by - EXACTLY +1, every other plane by exactly 0. On a byte-exact cell this is the - only thing that can move, so a `0/0/0` that survives a flip is a comparator - that is not reading the oracle. -* **ours arm** -- flip one of OUR samples with the oracle untouched. Same - delta. This is the direction the whole corpus verdict rests on, and on a - `0/0/0` cell it is what separates "we agree" from "we never looked". - -Every decode->display SOLUTION is exercised, so an ambiguous mapping cannot -hide a failure behind the one that was picked. - -Usage: - python3 scripts/flipctl-422.py cells.json - -`cells.json` entries: `{"name", "path", "prefix"}`, `prefix` being our -`EC_AV1_FINAL_DUMP` prefix. Exit status 0 only if every arm passes. -""" -import importlib.util -import json -import os -import sys - -_HERE = os.path.dirname(os.path.abspath(__file__)) -_spec = importlib.util.spec_from_file_location( - "cmp422_ffmpeg", os.path.join(_HERE, "cmp422-ffmpeg.py")) -C = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(C) - - -def plane_counts(ours, disp, mapping, hidden, sizes, bps): - """The comparator's own accounting (`cmp422-ffmpeg.compare`'s `measure`), - with the decode->display assignment PINNED so a flipped sample cannot - re-map.""" - tot = [0, 0, 0] - for oi, a in enumerate(ours): - if oi in hidden: - continue - b = disp[mapping[oi]] - off = 0 - for pi, sz in enumerate(sizes): - for i in range(sz): - s = off + i * bps - if a[s:s + bps] != b[s:s + bps]: - tot[pi] += 1 - off += sz * bps - return tot - - -def flip_sample(buf, sample_index, bps): - """Flip bit 0 of one SAMPLE's low byte: exactly +1 wrong sample at both - depths (2**bitdepth < 2**16, so nothing carries out of the container).""" - out = bytearray(buf) - out[sample_index * bps] ^= 1 - return bytes(out) - - -def arms_for(sizes): - """(plane, sample_index) per plane: the first, the middle and the last.""" - out = [] - for pi, sz in enumerate(sizes): - out += [(pi, 0), (pi, sz // 2), (pi, sz - 1)] - return out - - -def one_cell(cell, path, prefix): - w, h, ssx, ssy, depth, pix = C.probe_geometry(path) - bps = 1 if depth <= 8 else 2 - sizes, fsz = C.plane_spans(w, h, ssx, ssy, bps) - disp = C.split(C.ffmpeg_frames(path, pix), sizes, fsz, cell) - ours = [open(p, "rb").read() for p in C.frame_files(prefix)] - if not ours: - raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames -- vacuous") - for i, o in enumerate(ours): - if len(o) != fsz: - raise SystemExit(f"{cell}: our frame {i} is {len(o)} B, " - f"geometry {w}x{h} ss={ssx}{ssy} depth={depth} implies {fsz} B") - sols = C.map_decode_to_display(ours, disp, sizes, bps, cell) - shown = set() - for mapping, hidden in sols: - shown |= {d for oi, d in enumerate(mapping) if oi not in hidden} - shown = sorted(shown) - # Two shown display frames per cell -- the first and one in the middle -- - # so the arm is not confined to frame 0. - ks = sorted({shown[0], shown[len(shown) // 2]}) - results, arms = [], 0 - base0 = plane_counts(ours, disp, sols[0][0], sols[0][1], sizes, bps) - for k in ks: - for sol_i, (mapping, hidden) in enumerate(sols): - dmap = {d: oi for oi, d in enumerate(mapping) if oi not in hidden} - if k not in dmap: - continue - oi = dmap[k] - base = plane_counts(ours, disp, mapping, hidden, sizes, bps) - for pi, si in arms_for(sizes): - off = sum(sizes[:pi]) + si # sample index inside the frame - want = [0, 0, 0] - want[pi] = 1 - for side in ("oracle", "ours"): - if side == "oracle": - f = list(disp) - f[k] = flip_sample(disp[k], off, bps) - got = plane_counts(ours, f, mapping, hidden, sizes, bps) - else: - f = list(ours) - f[oi] = flip_sample(ours[oi], off, bps) - got = plane_counts(f, disp, mapping, hidden, sizes, bps) - delta = [got[i] - base[i] for i in range(3)] - ok = delta == want - results.append(ok) - arms += 1 - if not ok: - print(f" FAIL {side:6s} disp f{k} plane {'YUV'[pi]} " - f"sample {si} sol{sol_i}: {base} -> {got} " - f"delta {delta} want {want}") - print(f"{cell}: baseline {base0} {len(ours)} decode / {len(disp)} shown, " - f"hidden {sols[0][1]}, {len(sols)} mapping solution(s), {arms} arms") - return results - - -def main(spec_path): - rows = [] - for c in json.load(open(spec_path)): - rows += one_cell(c["name"], c["path"], c["prefix"]) - print(f"\n{sum(rows)} PASS, {len(rows) - sum(rows)} FAIL of {len(rows)} flip arms") - return 0 if all(rows) else 1 - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1])) \ No newline at end of file diff --git a/scripts/gen-aac-layouts.sh b/scripts/gen-aac-layouts.sh deleted file mode 100755 index 14096b17..00000000 --- a/scripts/gen-aac-layouts.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash -# Usage: scripts/gen-aac-layouts.sh -# Generates the 3.0, 4.0, 5.0 and 7.1 48 kHz FLAC fixtures, same construction as gen-fixtures.sh's 5.1. -set -euo pipefail -OUT=$1 -FREQS=(220 440 660 55 880 1320 1760 2200) -gen() { # name nch layout - local name=$1 nch=$2 layout=$3 ain=() lbl="" i - for ((i = 0; i < nch; i++)); do - ain+=(-f lavfi -i "sine=frequency=${FREQS[i]}:sample_rate=48000:duration=3") - lbl="${lbl}[${i}:a]" - done - ffmpeg -v error -y "${ain[@]}" -filter_complex "${lbl}join=inputs=${nch}:channel_layout=${layout}[a]" \ - -map "[a]" -c:a flac -compression_level 5 -ar 48000 "$OUT/flac-${name}-48000.flac" -} -gen 3.0 3 3.0 -gen 4.0 4 4.0 -gen 5.0 5 5.0 -gen 7.1 8 7.1 diff --git a/scripts/gen-bitmap-sub-fixtures.py b/scripts/gen-bitmap-sub-fixtures.py deleted file mode 100644 index 8bf72c6a..00000000 --- a/scripts/gen-bitmap-sub-fixtures.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python3 -"""Writes a small synthetic PGS .sup (720x576, four cues with known times) to argv[1]. - -It is the *source* the DVD/DVB subtitle fixtures are encoded from with ffmpeg -(scripts/gen-bitmap-sub-fixtures.sh): ffmpeg's dvdsub and dvbsub encoders take bitmaps only. -No third-party media is involved; the text is rendered with PIL's default font. -""" -import struct, sys -from PIL import Image, ImageDraw, ImageFilter, ImageFont - -W, H = 720, 576 -CUES = [ # start s, end s, text lines, y - (0.5, 1.5, ["Hello DVD"], 480), - (2.0, 3.2, ["Second cue", "line two"], 440), - (3.5, 4.5, ["Third — éèü"], 60), - (5.0, 6.0, ["End"], 500), -] -try: - FONT = ImageFont.load_default(size=36) -except TypeError: - FONT = ImageFont.load_default() - - -def seg(kind, pts, body): - return b"PG" + struct.pack(">IIBH", int(pts * 90000), 0, kind, len(body)) + body - - -def rle(rows): - out = bytearray() - for row in rows: - x = 0 - while x < len(row): - c = row[x] - n = 1 - while x + n < len(row) and row[x + n] == c and n < 16383: - n += 1 - if c != 0 and n < 3: - out += bytes([c]) * n - elif c == 0: - out += bytes([0, 0x40 | (n >> 8), n & 255]) if n > 63 else bytes([0, n]) - else: - out += bytes([0, 0xC0 | (n >> 8), n & 255, c]) if n > 63 else bytes([0, 0x80 | n, c]) - x += n - out += b"\0\0" - return bytes(out) - - -def render(lines): - d = ImageDraw.Draw(Image.new("L", (1, 1))) - ws = [d.textbbox((0, 0), t, font=FONT)[2] for t in lines] - w, h = max(ws) + 12, 44 * len(lines) + 8 - fg = Image.new("L", (w, h), 0) - dr = ImageDraw.Draw(fg) - for i, t in enumerate(lines): - dr.text(((w - ws[i]) // 2, 4 + 44 * i), t, fill=255, font=FONT) - ol = fg.filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(0.7)) - px = [] - for y in range(h): - row = [] - for x in range(w): - f, o = fg.getpixel((x, y)) // 32, ol.getpixel((x, y)) // 32 # 0..7 - row.append(1 + f if f >= 4 else (9 + o if o else 0)) if False else row.append( - (1 + f) if f >= 3 else ((9 + o) if o else 0)) - px.append(row) - return w, h, px - - -def palette(): - ents = [(0, 16, 128, 128, 0)] - for i in range(1, 9): # white ramp, indices 1..8 - ents.append((i, 235, 128, 128, 255 if i > 4 else 128)) - for i in range(9, 17): # black outline, indices 9..16 - ents.append((i, 16, 128, 128, min(255, 40 * (i - 8)))) - return b"".join(struct.pack("BBBBB", i, y, cr, cb, a) for i, y, cr, cb, a in ents) - - -out = bytearray() -num = 0 -for start, end, lines, y in CUES: - w, h, px = render(lines) - x = (W - w) // 2 - data = rle(px) - pcs = struct.pack(">HHBHBBBB", W, H, 0x10, num, 0x80, 0, 0, 1) + struct.pack(">HBBHH", 0, 0, 0, x, y) - wds = struct.pack(">BBHHHH", 1, 0, x, y, w, h) - pds = bytes([0, 0]) + palette() - ods = struct.pack(">HBB", 0, 0, 0xC0) + (len(data) + 4).to_bytes(3, "big") + struct.pack(">HH", w, h) + data - for k, b in ((0x16, pcs), (0x17, wds), (0x14, pds), (0x15, ods), (0x80, b"")): - out += seg(k, start, b) - num += 1 - pcs = struct.pack(">HHBHBBBB", W, H, 0x10, num, 0x00, 0, 0, 0) - out += seg(0x16, end, pcs) + seg(0x17, end, struct.pack(">BBHHHH", 1, 0, x, y, w, h)) + seg(0x80, end, b"") - num += 1 -open(sys.argv[1], "wb").write(out) diff --git a/scripts/gen-bitmap-sub-fixtures.sh b/scripts/gen-bitmap-sub-fixtures.sh deleted file mode 100755 index d677d35d..00000000 --- a/scripts/gen-bitmap-sub-fixtures.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# gen-bitmap-sub-fixtures.sh: regenerate the DVD/DVB subtitle fixtures of ec-dvdsub and ec-dvbsub. -# -# A synthetic 720x576 PGS source (scripts/gen-bitmap-sub-fixtures.py, PIL text, four cues at -# 0.5-1.5, 2.0-3.2, 3.5-4.5, 5.0-6.0 s) is encoded by ffmpeg's dvdsub and dvbsub encoders (they -# take bitmaps only). Needs ffmpeg and python3 with PIL. dvd.idx is written by hand from dvd.sub. -set -euo pipefail -ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) -T=$(mktemp -d "${TMPDIR:-/tmp}/bitmapsub.XXXXXX") -trap 'rm -rf "$T"' EXIT -python3 "$ROOT/scripts/gen-bitmap-sub-fixtures.py" "$T/src.sup" -S=(-fix_sub_duration -f sup -i "$T/src.sup") -DVD="$ROOT/crates/ec-dvdsub/tests/data"; DVB="$ROOT/crates/ec-dvbsub/tests/data" -mkdir -p "$DVD" "$DVB" -ffmpeg -v error -y "${S[@]}" -c:s dvdsub -map 0 "$DVD/dvd.mkv" -ffmpeg -v error -y -f lavfi -i color=c=black:s=720x576:r=25:d=7 "${S[@]}" -c:v mpeg2video -b:v 200k \ - -maxrate 9000k -bufsize 1835k -c:s dvdsub -map 0 -map 1 -target pal-dvd -an "$DVD/dvd.vob" -ffmpeg -v error -y -f lavfi -i color=c=black:s=64x64:r=5:d=7 "${S[@]}" -c:v mpeg4 -c:s dvdsub -map 0 -map 1 "$DVD/dvd.mp4" -ffmpeg -v error -y "${S[@]}" -c:s dvdsub -map 0 -f vob "$DVD/dvd.sub" -ffmpeg -v error -y -f lavfi -i color=c=black:s=64x64:r=5:d=7 "${S[@]}" -c:v mpeg2video -b:v 50k -c:s dvbsub -map 0 -map 1 "$DVB/dvb.ts" -ffmpeg -v error -y "${S[@]}" -c:s dvbsub -map 0 "$DVB/dvb.mkv" -echo "fixtures written (dvd.idx is hand-made; see the test)" diff --git a/scripts/gen-mp4-parity-corpus.sh b/scripts/gen-mp4-parity-corpus.sh deleted file mode 100755 index dd6019da..00000000 --- a/scripts/gen-mp4-parity-corpus.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash -# gen-mp4-parity-corpus.sh: write the generated mp4/mov cases that the ec-mp4 parity -# test (crates/ec-mp4/tests/it/edith_parity.rs) compares against ffprobe. -# -# Usage: scripts/gen-mp4-parity-corpus.sh -# -# Each case isolates one thing the demuxer must read the way edith does: -# bframes.mp4 B-frames: ctts v0 offsets, a sample order that differs from display order -# negcts.mp4 negative composition offsets (ctts v1), -movflags negative_cts_offsets -# rot90.mp4 tkhd display matrix of a quarter turn (copied from tests/data) -# rot270.mp4 the other quarter turn (copied from tests/data) -# qt.mov QuickTime container (-f mov): mp4a in a sound description -# emptyedit.mp4 an audio track delayed by 0.5 s: an empty edit ahead of the media -# aac-prime.mp4 AAC audio alone: the encoder delay is an edit list (elst) of its own -# mp3.mp4 an mp4a entry carrying MP3 -# -# Needs ffmpeg with libx264. Output is deterministic for a given ffmpeg build. -set -euo pipefail -out=${1:?usage: gen-mp4-parity-corpus.sh } -here=$(cd -- "$(dirname -- "$0")" && pwd) -mkdir -p "$out" -cd "$out" -ff() { ffmpeg -hide_banner -v error -y "$@"; } -ff -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \ - -f lavfi -i sine=frequency=440:duration=2 \ - -c:v libx264 -bf 2 -g 24 -pix_fmt yuv420p -c:a aac -b:a 128k bframes.mp4 -ff -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \ - -c:v libx264 -bf 2 -pix_fmt yuv420p -movflags negative_cts_offsets negcts.mp4 -# The display matrices: stream copies of the committed rotation clips, whose tkhd -# matrix ffmpeg wrote with -display_rotation (crates/ec-mp4/tests/data/gen.sh). -ff -i "$here/../crates/ec-mp4/tests/data/rot90.mp4" -c copy rot90.mp4 -ff -i "$here/../crates/ec-mp4/tests/data/rot270.mp4" -c copy rot270.mp4 -ff -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \ - -f lavfi -i sine=frequency=440:duration=2 \ - -c:v libx264 -bf 2 -pix_fmt yuv420p -c:a aac -f mov qt.mov -ff -f lavfi -i sine=frequency=440:duration=2 -itsoffset 0.5 \ - -f lavfi -i testsrc2=size=64x64:rate=24:duration=2 \ - -map 0:a -map 1:v -c:v libx264 -c:a aac -shortest emptyedit.mp4 -ff -f lavfi -i sine=frequency=440:duration=2 -c:a aac -b:a 96k aac-prime.mp4 -ff -f lavfi -i sine=frequency=440:duration=2 -c:a libmp3lame -b:a 96k -f mp4 mp3.mp4 diff --git a/scripts/h264-bd.sh b/scripts/h264-bd.sh deleted file mode 100755 index 4525f6dc..00000000 --- a/scripts/h264-bd.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -# h264-bd.sh: BD-rate of the Fast preset vs x264 veryfast on the 1080p library clip -# (the h264encbd method). Run through scripts/remote-run.sh. Prints bd_rate_pct and bd_psnr_db. -set -euo pipefail -d=${TMPDIR:-/tmp}/h264bd.$$; mkdir -p "$d" -EC_REQUIRE_FIXTURES=1 EC_H264_X264_PRESET=veryfast \ -EC_H264_CLIP=$HOME/fixtures/video/h264-1080p-23.976-8bit.mp4 \ - cargo test --release -p ec-h264 --test it encode::bd_psnr_vs_x264 -- --nocapture 2>&1 | tee "$d/log" | grep -E "^(test |BD-)" || true -python3 -I - "$d" <<'PY' -import re,sys -d=sys.argv[1] -o=open(d+"/ours.tsv","w"); x=open(d+"/x264.tsv","w") -for l in open(d+"/log"): - m=re.match(r"qp \d+: ours (\d+) bits ([\d.]+) dB \(([\d.]+) yuv\) \| x264 (\d+) bits ([\d.]+) dB \(([\d.]+) yuv\)",l) - if m: - o.write(f"{int(m[1])//8}\t{m[2]}\t{m[3]}\n"); x.write(f"{int(m[4])//8}\t{m[5]}\t{m[6]}\n") -PY -python3 -I scripts/bdrate.py --metric yuv "$d/x264.tsv" "$d/ours.tsv" diff --git a/scripts/h264-speed.sh b/scripts/h264-speed.sh deleted file mode 100755 index 3de4662a..00000000 --- a/scripts/h264-speed.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -# h264-speed.sh [features]: 1080p30 encode speed, noisy and clean testsrc2. -# Run it through scripts/remote-run.sh. Clips are cached in $HOME/.cache/h264speed. -set -euo pipefail -frames=${1:-60}; threads=${2:-1}; feat=${3:-} -d=$HOME/.cache/h264speed; mkdir -p "$d" -for kind in noisy clean; do - f=$d/$kind-$frames.yuv - if [ ! -s "$f" ]; then - g="testsrc2=size=1920x1080:rate=30:duration=$(awk -v n="$frames" 'BEGIN{print n/30}')" - [ $kind = noisy ] && g="$g,noise=alls=24:allf=t" - ffmpeg -nostdin -v error -y -f lavfi -i "$g" -pix_fmt yuv420p -f rawvideo "$f" - fi -done -cargo build --release -p ec-h264 --example h264_clip_encode ${feat:+--features $feat} 2>&1 | tail -2 -bin=${CARGO_TARGET_DIR:-target}/release/examples/h264_clip_encode -for kind in noisy clean; do - echo "== $kind threads=$threads" - bash -c "time \"\$0\" \"\$@\"" "$bin" "$d/$kind-$frames.yuv" 1920 1080 30 4000000 26 "$threads" none -done diff --git a/scripts/h264-sweep.sh b/scripts/h264-sweep.sh deleted file mode 100755 index 28499c59..00000000 --- a/scripts/h264-sweep.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -# h264-sweep.sh "" : speed (60 frames, 1 thread) and BD-rate for one knob setting. -# Run on one host: scripts/remote-run.sh h264encspeed2 --host a -- bash scripts/h264-sweep.sh "EC_H264_ME_SUB=1" -set -uo pipefail -for kv in $1; do export "$kv"; done -echo "### $1" -bash scripts/h264-speed.sh 60 1 2>&1 | grep -E "^(==|frames)" -bash scripts/h264-bd.sh 2>&1 | grep -E "bd_rate|BD-PSNR-YUV" diff --git a/scripts/hevc-intra-bd.sh b/scripts/hevc-intra-bd.sh deleted file mode 100755 index ed14ac5d..00000000 --- a/scripts/hevc-intra-bd.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# hevc-intra-bd.sh: intra-only (keyint=1) BD-rate of ec-h265 against x265 intra on the three -# clips the ec-h265 encode gate names. Thin wrapper over scripts/hevc-bdrate.sh with GOP 1. -# Clips are generated with ffmpeg lavfi (no copyrighted media) into $DATA. -# -# The x265 anchor uses -tune psnr by default (see hevc-bdrate.sh). Set X265_TUNE= for x265's -# default tuning. Each tuning writes its own point files under $DATA/tune-/. -# -# Usage: scripts/hevc-intra-bd.sh [QPS] -# clip-name: testsrc2-352x288 | testsrc2-1280x720 | natural-1280x720 | all -# Environment: DATA (default $HOME/.cache/hevcintra-data). -set -euo pipefail -here=$(cd "$(dirname "$0")/.." && pwd) -which=${1:-all} -qps=${2:-"22 27 32 37"} -data=${DATA:-$HOME/.cache/hevcintra-data} -mkdir -p "$data" -frames=30 -gen() { # gen - [ -f "$1" ] || ffmpeg -v error -y -f lavfi -i "$2" -frames:v $frames -pix_fmt yuv420p -f rawvideo "$1" -} -gen "$data/testsrc2-352x288.yuv" "testsrc2=size=352x288:rate=30" -gen "$data/testsrc2-1280x720.yuv" "testsrc2=size=1280x720:rate=30" -# "natural": a moving mandelbrot zoom blended with testsrc2 and film-like noise (the -# gen-hevcperf-fixtures.sh moving clip), so it has texture rather than flat synthetic edges. -[ -f "$data/natural-1280x720.yuv" ] || ffmpeg -v error -y \ - -f lavfi -i "mandelbrot=size=1280x720:rate=30" \ - -f lavfi -i "testsrc2=size=1280x720:rate=30" \ - -filter_complex "[0:v][1:v]blend=all_mode=average,noise=alls=8:allf=t,format=yuv420p[v]" \ - -map "[v]" -frames:v $frames -f rawvideo "$data/natural-1280x720.yuv" -for spec in "testsrc2-352x288 352 288" "testsrc2-1280x720 1280 720" "natural-1280x720 1280 720"; do - set -- $spec - [ "$which" = all ] || [ "$which" = "$1" ] || continue - DATA="$data/tune-${X265_TUNE-psnr}" "$here/scripts/hevc-bdrate.sh" "$data/$1.yuv" "$2" "$3" 1 "$qps" - echo "----" -done diff --git a/scripts/hevc-preset-quick.sh b/scripts/hevc-preset-quick.sh deleted file mode 100644 index 37d074fd..00000000 --- a/scripts/hevc-preset-quick.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash -# hevc-preset-quick.sh: single-thread encode time and size of the 1080p 10-bit bench clip per preset. -set -e -cargo build --release -q -p ec-h265 --example hevc_gop 2>&1 | grep -E '^error' -A8 || true -B=${CARGO_TARGET_DIR:-target}/release/examples/hevc_gop; D=$HOME/.cache/hevc10simd2-bench -echo load $(cut -d' ' -f1-3 /proc/loadavg) -for p in ${PRESETS:-default fast faster}; do - echo -n "$p: "; EC_H265_PRESET=$p EC_H265_BITDEPTH=10 EC_H265_THREADS=1 EC_H265_TIMING=1 $B encode $D/c10.yuv 1920 1080 8 30 $D/o.hevc $D/r.yuv 2>&1 | grep -v PROF | tr "\n" " "; echo -done diff --git a/scripts/hevc-rc-bdrate.sh b/scripts/hevc-rc-bdrate.sh deleted file mode 100755 index aabbb4ea..00000000 --- a/scripts/hevc-rc-bdrate.sh +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env bash -# hevc-rc-bdrate.sh: BD-rate of ec-h265's bitrate-controlled sequence encoder against libx265 -# at the same bitrates, with x265 at bframes=0 and the same keyframe interval. -# -# The bitrate counterpart of hevc-bdrate.sh (which sweeps constant QP). Each side is encoded at -# the KBPS targets (ec-h265 through the hevc_rc example, x265 with -b:v at veryfast); the points -# are (bytes, Y and YUV PSNR against the source, from scripts/ffmpeg-psnr.sh). Positive -# bd_rate_pct means ec-h265 needs more bytes at the same quality. -# -# Usage: scripts/hevc-rc-bdrate.sh [GOP] [KBPS list] -# Environment: DATA (default $HOME/.cache/hevcencrc-data), FPS (default 30). -set -euo pipefail - -here=$(cd "$(dirname "$0")/.." && pwd) -clip=$1 -w=$2 -h=$3 -gop=${4:-30} -kbpss=${5:-"1000 2000 4000 8000"} -fps=${FPS:-30} -data=${DATA:-$HOME/.cache/hevcencrc-data} -mkdir -p "$data" -[ -f "$clip" ] || clip="$data/$clip" -tag=$(basename "$clip" .yuv)-${w}x${h}-k$gop-rc - -cargo build --release -q -p ec-h265 --example hevc_rc --manifest-path "$here/Cargo.toml" -target=$(cargo metadata --format-version 1 --no-deps --manifest-path "$here/Cargo.toml" \ - | python3 -I -c 'import json,sys; print(json.load(sys.stdin)["target_directory"])') -rcbin="$target/release/examples/hevc_rc" - -anchor="$data/$tag.x265.tsv" -test_="$data/$tag.ec.tsv" -: > "$anchor" -: > "$test_" -for kbps in $kbpss; do - x265="$data/$tag-$kbps.x265.hevc" - ffmpeg -v error -y -f rawvideo -pix_fmt yuv420p -s "${w}x${h}" -r "$fps" -i "$clip" \ - -c:v libx265 -preset veryfast -b:v "${kbps}k" \ - -x265-params "bframes=0:keyint=$gop:min-keyint=$gop:scenecut=0:log-level=error" \ - -f hevc "$x265" - xdec="$data/$tag-$kbps.x265.yuv" - ffmpeg -v error -y -i "$x265" -f rawvideo -pix_fmt yuv420p "$xdec" - xline=$("$here/scripts/ffmpeg-psnr.sh" "$clip" "$xdec" "$w" "$h") - xpy=$(echo "$xline" | sed -n 's/.*psnr_y=\([^ ]*\).*/\1/p') - xpsnr=$(echo "$xline" | sed -n 's/.*psnr_yuv=\([^ ]*\).*/\1/p') - rm -f "$xdec" - printf '%s\t%s\t%s\n' "$(stat -c %s "$x265")" "$xpy" "$xpsnr" >> "$anchor" - - ours="$data/$tag-$kbps.ec.hevc" - recon="$data/$tag-$kbps.ec.recon.yuv" - "$rcbin" encode "$clip" "$w" "$h" "$gop" "$kbps" "$fps" "$ours" "$recon" >/dev/null - oline=$("$here/scripts/ffmpeg-psnr.sh" "$clip" "$recon" "$w" "$h") - rm -f "$recon" - opy=$(echo "$oline" | sed -n 's/.*psnr_y=\([^ ]*\).*/\1/p') - opsnr=$(echo "$oline" | sed -n 's/.*psnr_yuv=\([^ ]*\).*/\1/p') - printf '%s\t%s\t%s\n' "$(stat -c %s "$ours")" "$opy" "$opsnr" >> "$test_" - echo "kbps=$kbps x265: bytes=$(stat -c %s "$x265") psnr_y=$xpy | ec-h265: bytes=$(stat -c %s "$ours") psnr_y=$opy" >&2 -done -echo "clip=$(basename "$clip") size=${w}x${h} gop=$gop kbps=[$kbpss]" -echo "points (bytes, psnr_y, psnr_yuv):" -echo " anchor x265:"; sed 's/^/ /' "$anchor" -echo " test ec-h265:"; sed 's/^/ /' "$test_" -echo "metric=yuv (6:1:1):" -python3 -I "$here/scripts/bdrate.py" --metric yuv "$anchor" "$test_" -echo "metric=y:" -python3 -I "$here/scripts/bdrate.py" --metric y "$anchor" "$test_" diff --git a/scripts/hevc-speed-sweep.sh b/scripts/hevc-speed-sweep.sh deleted file mode 100755 index ba1bddd0..00000000 --- a/scripts/hevc-speed-sweep.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# hevc-speed-sweep.sh: speed and rate-distortion of ec-h265 sequence encodes under env overrides. -# Usage: scripts/hevc-speed-sweep.sh