forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/u2' into simplify/w1b

Browse files at this commit

be2d31f20667a69ec964f749b024256a7227cdadAhmet Kaan GümüşParent: d8990c1c9e7d91
.gitignoremodified+0 -1
@@ -11,7 +11,6 @@ fixtures
11 !crates/*/fixtures/11 !crates/*/fixtures/
12 !crates/*/fixtures/**12 !crates/*/fixtures/**
13 __pycache__/13 __pycache__/
14-scripts/aac-tables/sbr-cache.json
15 .cache/14 .cache/
16 lanes/wedge_dump15 lanes/wedge_dump
17 /graphify-out16 /graphify-out
scripts/aac-tables/aacprobe.pydeleted+0 -132
@@ -1,132 +0,0 @@
1-#!/usr/bin/env python3
2-"""Black-box derivation of the ISO/IEC 14496-3 AAC-LC Huffman codebooks.
3-
4-Clean-room: no AAC implementation source is read. The only oracle is ffmpeg's
5-`aac` decoder driven as a black box. We synthesise ADTS frames whose spectral
6-payload is a bit string we choose, decode them, invert the (windowed) MDCT to
7-recover the quantised spectrum, and learn the prefix code from bits -> tuple.
8-
9-Frame shape (mono, 48 kHz, ONLY_LONG, sine window):
10- SCE(3)=0 tag(4)=0 global_gain(8) ics_info section_data sf_data flags spectral
11-max_sfb=2 gives one section of 8 coefficients, so the spectral field always
12-outlives the probe prefix and the trailing all-ones run lands on an END element
13-(id 7 = 0b111). The ones run is bounded -- a long 0xFF tail makes ffmpeg's ADTS
14-parser resync on a false 0xFFF sync word.
15-"""
16-
17-import numpy as np
18-import subprocess
19-import os
20-
21-SR = 48000
22-N = 1024
23-ONES_RUN = 96 # bits of `1` filler after the probe, then zero padding
24-
25-
26-class BitW:
27- def __init__(self):
28- self.bits = []
29-
30- def w(self, val, n):
31- for i in range(n - 1, -1, -1):
32- self.bits.append((val >> i) & 1)
33- return self
34-
35- def wbits(self, seq):
36- self.bits.extend(seq)
37- return self
38-
39- def __len__(self):
40- return len(self.bits)
41-
42- def pack(self, total_bytes=None, pad=0):
43- if total_bytes is None:
44- total_bytes = (len(self.bits) + 7) // 8
45- b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8]
46- out = bytearray()
47- for i in range(0, len(b), 8):
48- v = 0
49- for bit in b[i : i + 8]:
50- v = (v << 1) | bit
51- out.append(v)
52- return bytes(out)
53-
54-
55-def adts(payload: bytes, sf_index=3, chan_cfg=1) -> bytes:
56- h = BitW()
57- h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1) # sync, MPEG-4, layer, no CRC
58- h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3) # AAC-LC
59- h.w(0, 1).w(0, 1).w(0, 1).w(0, 1) # original, home, copyright id/start
60- h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2)
61- return h.pack(7) + payload
62-
63-
64-def probe_frame(cb, sf_bits, probe_bits, gg=200, max_sfb=2):
65- w = BitW()
66- w.w(0, 3).w(0, 4) # SCE, instance tag
67- w.w(gg, 8)
68- w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine window
69- w.w(cb, 4).w(max_sfb, 5) # one section covering every band
70- w.wbits(sf_bits)
71- w.w(0, 3) # pulse / tns / gain-control absent
72- w.wbits(probe_bits).wbits([1] * ONES_RUN)
73- return adts(w.pack(pad=0))
74-
75-
76-def silent_frame():
77- w = BitW()
78- w.w(0, 3).w(0, 4).w(128, 8)
79- w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1) # max_sfb = 0: nothing coded
80- w.w(0, 3).w(7, 3) # flags, END
81- return adts(w.pack(4))
82-
83-
84-# --- MDCT read-back ---------------------------------------------------------
85-
86-_PINV = None
87-
88-
89-def recover(block, ncoef=12):
90- """Quantised-spectrum-proportional coefficients from 2048 output samples."""
91- global _PINV
92- if _PINV is None:
93- cache = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pinv.npy")
94- if os.path.exists(cache):
95- _PINV = np.load(cache)
96- else:
97- n = np.arange(2 * N)
98- k = np.arange(N)
99- m = np.cos(2 * np.pi / N * np.outer(n + 0.5 + N / 2, k + 0.5))
100- win = np.sin(np.pi / (2 * N) * (n + 0.5))
101- _PINV = np.linalg.pinv(m * win[:, None])[:32].astype(np.float64)
102- np.save(cache, _PINV)
103- return _PINV[:ncoef] @ block
104-
105-
106-def decode_probes(frames, tag="p"):
107- """One 2048-sample block per probe frame, or None when ffmpeg refused it."""
108- d = os.path.dirname(os.path.abspath(__file__))
109- src = os.path.join(d, f"probe-{tag}.aac")
110- sil = silent_frame()
111- with open(src, "wb") as f:
112- f.write(sil + b"".join(fr + sil + sil for fr in frames))
113- raw = subprocess.run(
114- ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"],
115- capture_output=True,
116- )
117- pcm = np.frombuffer(raw.stdout, dtype="<f4")
118- nblk = len(pcm) // N
119- pcm = pcm[: nblk * N].reshape(nblk, N).astype(np.float64)
120- os.remove(src)
121- if nblk != 3 * len(frames) + 1:
122- return None, raw.stderr.decode()
123- return [np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]) for i in range(len(frames))], ""
124-
125-
126-if __name__ == "__main__":
127- frs = [probe_frame(3, [0] * 2, [1] * 40)]
128- blocks, err = decode_probes(frs, "smoke")
129- if blocks is None:
130- print("MISALIGNED", err[:400])
131- else:
132- print("coefs", np.round(recover(blocks[0], 12), 6))
scripts/aac-tables/sbrnoise.pydeleted+0 -111
@@ -1,111 +0,0 @@
1-#!/usr/bin/env python3
2-"""Black-box measurement of the reference decoder's SBR noise-floor
3-dequantization law (round-21 Task 1).
4-
5-Method: reuse `sbrchirp.py`'s repaired probe shape (SCE, FIXFIX num_env=2,
6-amp_res=1, broadband comb core so the HF-signal envelope target is fixed
7-and non-zero), fix the envelope raw value, and sweep only the noise-floor
8-raw value `q_q` (`noise0`) across its 5-bit range. Noise is spec-additive
9-on top of the gain-adjusted HF signal (module doc in sbr_env.rs), so the
10-total power measured in the target band at each `q_q` is
11-`signal_energy(fixed) + noise_energy(q_q)`; subtracting the high-`q_q`
12-(minimal-noise) baseline isolates `noise_energy(q_q)` and its shape can be
13-fit against `q_q` directly, independent of our own decoder.
14-"""
15-import os
16-import sys
17-
18-import numpy as np
19-
20-HERE = os.path.dirname(os.path.abspath(__file__))
21-sys.path.insert(0, HERE)
22-
23-import sbrchirp as C
24-import sbrpayload_fixtures as F
25-
26-RATE = C.RATE
27-
28-
29-def noise_stream(cfg, tables, n_frames, q, env=40):
30- """Like `sbrchirp.stream()` but `bs_invf_mode` held at NONE (0, so the
31- injected noise is not reshaped by the inverse filter) and `noise0`
32- swept to `[q, q]` instead of `bs_invf_mode`; `env` is the fixed
33- envelope raw value."""
34- grid = dict(frame_class=0, num_env=2, freq_res=0)
35- frames = [C.P.silent(C.SF_INDEX)]
36- for _ in range(n_frames):
37- c = dict(cfg, invf=0, header=1, amp_res=1, element="sce", coupling=0,
38- df_env=[0] * 8, df_noise=[0, 0], env0=[env] * 8, noise0=[q, q])
39- w = C.P.BitW()
40- C.broadband_core_bits(w)
41- body = F.sbr_bits_full(c, tables, grid, [])
42- w.w(6, 3)
43- cnt = (len(body.bits) + 4 + 7) // 8
44- if cnt >= 15:
45- w.w(15, 4)
46- w.w(cnt - 15 + 1, 8)
47- else:
48- w.w(cnt, 4)
49- start = len(w)
50- w.w(13, 4)
51- w.wbits(body.bits)
52- while len(w) - start < cnt * 8:
53- w.w(0, 1)
54- w.w(7, 3)
55- frames.append(C.P.adts(w.pack(pad=0), C.SF_INDEX))
56- frames.append(C.P.silent(C.SF_INDEX))
57- return frames
58-
59-
60-def band_power(pcm, lo_hz, hi_hz, skip=6, n_fft=8192):
61- start = skip * 1024
62- seg = pcm[start : start + n_fft]
63- if len(seg) < n_fft:
64- seg = np.pad(seg, (0, n_fft - len(seg)))
65- spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2
66- freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
67- mask = (freqs >= lo_hz) & (freqs < hi_hz)
68- return float(np.sum(spec[mask]))
69-
70-
71-if __name__ == "__main__":
72- cfg0, tables0 = F.one_band_header()
73- lo, hi = 19 * RATE / 128, 23 * RATE / 128
74- 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})")
75-
76- print("\n== value-engagement check: envelope raw sweep (fixed q_q) must move power by orders ==")
77- for e in (10, 40, 60):
78- cfg = dict(cfg0)
79- frames = noise_stream(cfg, tables0, 20, 30, env=e)
80- pcm, err = C.decode(frames, f"env_check{e}")
81- pwr = band_power(pcm, lo, hi)
82- print(f" env0={e} (q_q=30, minimal noise) pwr={pwr:.4e} err={err.strip()[:60]!r}")
83-
84- print("\n== Task 1: noise-floor raw (q_q) sweep, fixed envelope ==")
85- qs = list(range(0, 31, 3))
86- pwrs = {}
87- for q in qs:
88- cfg = dict(cfg0)
89- frames = noise_stream(cfg, tables0, 20, q)
90- pcm, err = C.decode(frames, f"q{q}")
91- pwr = band_power(pcm, lo, hi)
92- pwrs[q] = pwr
93- print(f" q_q={q:2d} pwr={pwr:.6e} err={err.strip()[:80]!r}")
94-
95- baseline = pwrs[qs[-1]]
96- print(f"\nbaseline (q_q={qs[-1]}, minimal noise) pwr={baseline:.6e}")
97- print("q_q, noise_energy=pwr-baseline, log2(noise_energy)")
98- fit_x, fit_y = [], []
99- for q in qs[:-1]:
100- n = pwrs[q] - baseline
101- if n > 0:
102- l2 = np.log2(n)
103- print(f" {q:2d} {n:.6e} {l2:.4f}")
104- fit_x.append(q)
105- fit_y.append(l2)
106- else:
107- print(f" {q:2d} {n:.6e} (non-positive, skipped)")
108- if len(fit_x) >= 2:
109- slope, intercept = np.polyfit(fit_x, fit_y, 1)
110- print(f"\nfit: log2(noise_energy) = {slope:.4f} * q_q + {intercept:.4f}")
111- print(f"(spec/ours form: log2(noise_energy) = -1*q_q + 6 => slope~-1, intercept~6 expected if law matches)")
scripts/aac-tables/sbrprobe.pydeleted+0 -231
@@ -1,231 +0,0 @@
1-#!/usr/bin/env python3
2-"""Black-box probing rig for the SBR (HE-AAC v1) tool. WORK IN PROGRESS.
3-
4-Same method as the AAC tables: the vehicle is an ADTS access unit whose core is
5-an AAC-LC frame of exactly known bit length -- so the FIL element carrying the
6-SBR payload starts at a position we control -- followed by a FIL element holding
7-an sbr_extension_data built field by field. A reference decoder is the only
8-oracle.
9-
10-State, so a successor does not repeat the ground already covered:
11-
12-* The core writer is correct: `sce_core` frames decode clean at every max_sfb,
13- and the FIL length accounting is right (the reference decoder reads the
14- element without complaint about its framing).
15-* `sbr_header` is parsed by the reference decoder -- `start_freq=14` comes back
16- as "Invalid n_master: 0", which is a semantic complaint about a field it read,
17- not a framing one.
18-* `sbr_data` is NOT yet accepted: the decoder consumes 16 bits more than this
19- writer emits ("Expected to read 7 SBR bytes actually read 9"), constant across
20- start_freq, stop_freq and freq_res. The gap is most likely the envelope
21- Huffman reads for bands beyond the first, whose codebooks are still unknown --
22- which is the bootstrap problem: only the first envelope value of a
23- frequency-delta frame is raw (6 or 7 bits), every later one is coded.
24-* The decoder reports the exact byte count its parser consumed, which is a
25- precise, cheap observable: that is the instrument to bootstrap the ten SBR
26- codebooks by the same prefix walk the AAC tables came from.
27-"""
28-
29-import os
30-import re
31-import subprocess
32-import sys
33-
34-import numpy as np
35-
36-TABLES = "/home/user/Documents/Code/Rust/edith_codecs/crates/ec-aac/src/tables.rs"
37-SR_TABLE = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]
38-
39-
40-def load_table(name):
41- src = open(TABLES).read()
42- body = re.search(rf"static {name}: \[\(u8, u32\); \d+\] = \[(.*?)\n\];", src, re.S).group(1)
43- return [tuple(int(x) for x in m) for m in re.findall(r"\((\d+),\s*(\d+)\)", body)]
44-
45-
46-def load_swb(kind):
47- src = open(TABLES).read()
48- body = re.search(rf"pub static SWB_{kind}: \[&\[u16\]; 12\] = \[(.*?)\n\];", src, re.S).group(1)
49- return [[int(x) for x in re.findall(r"\d+", row)] for row in re.findall(r"&\[([^\]]*?)\]", body, re.S)]
50-
51-
52-HCB3 = load_table("HCB3")
53-HCB_SF = load_table("HCB_SF")
54-SWB_LONG = load_swb("LONG")
55-
56-
57-class BitW:
58- def __init__(self):
59- self.bits = []
60-
61- def w(self, val, n):
62- for i in range(n - 1, -1, -1):
63- self.bits.append((val >> i) & 1)
64- return self
65-
66- def wbits(self, seq):
67- self.bits.extend(seq)
68- return self
69-
70- def __len__(self):
71- return len(self.bits)
72-
73- def pack(self, total_bytes=None, pad=0):
74- if total_bytes is None:
75- total_bytes = (len(self.bits) + 7) // 8
76- b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8]
77- out = bytearray()
78- for i in range(0, len(b), 8):
79- v = 0
80- for bit in b[i : i + 8]:
81- v = (v << 1) | bit
82- out.append(v)
83- return bytes(out)
84-
85-
86-def adts(payload, sf_index, chan_cfg=1):
87- h = BitW()
88- h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1)
89- h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3)
90- h.w(0, 1).w(0, 1).w(0, 1).w(0, 1)
91- h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2)
92- return h.pack(7) + payload
93-
94-
95-def tuple_index_u(vals, lav, dim):
96- span = lav + 1
97- idx = 0
98- for i in range(dim):
99- idx = idx * span + min(abs(vals[i]), lav)
100- return idx
101-
102-
103-def sce_core(w, sf_index, max_sfb, gain=200, quad=(2, 0, 2, 2)):
104- """A single_channel_element of exactly known length: codebook 3 throughout,
105- the same tuple in every position, so the bit cost is arithmetic."""
106- swb = SWB_LONG[sf_index]
107- max_sfb = min(max_sfb, len(swb) - 1)
108- w.w(0, 3).w(0, 4) # SCE, instance tag
109- w.w(gain, 8)
110- w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine
111- w.w(3, 4) # one section, codebook 3
112- left = max_sfb
113- while left >= 31:
114- w.w(31, 5)
115- left -= 31
116- w.w(left, 5)
117- for _ in range(max_sfb):
118- w.w(HCB_SF[60][1], HCB_SF[60][0]) # delta 0
119- w.w(0, 3) # pulse / tns / gain-control absent
120- length, code = HCB3[tuple_index_u(quad, 2, 4)]
121- signs = [1 for v in quad if v != 0]
122- for _ in range(swb[max_sfb] // 4):
123- w.w(code, length)
124- for _ in signs:
125- w.w(0, 1) # positive
126- return w
127-
128-
129-def sbr_payload(cfg):
130- """sbr_extension_data for one single channel element, from `cfg`."""
131- s = BitW()
132- s.w(1, 1) # bs_header_flag
133- s.w(cfg["amp_res"], 1)
134- s.w(cfg["start_freq"], 4)
135- s.w(cfg["stop_freq"], 4)
136- s.w(cfg["xover_band"], 3)
137- s.w(0, 2) # bs_reserved
138- s.w(1, 1) # bs_header_extra_1
139- s.w(1, 1) # bs_header_extra_2
140- s.w(cfg["freq_scale"], 2)
141- s.w(cfg["alter_scale"], 1)
142- s.w(cfg["noise_bands"], 2)
143- s.w(cfg["limiter_bands"], 2)
144- s.w(cfg["limiter_gains"], 2)
145- s.w(cfg["interpol_freq"], 1)
146- s.w(cfg["smoothing_mode"], 1)
147- # sbr_single_channel_element
148- s.w(0, 1) # bs_data_extra
149- # sbr_grid: FIXFIX with one envelope
150- s.w(0, 2) # bs_frame_class = FIXFIX
151- s.w(0, 2) # bs_num_env_raw -> num_env = 1
152- s.w(cfg["freq_res"], 1)
153- # sbr_dtdf
154- s.w(0, 1) # bs_df_env[0] = frequency direction
155- s.w(0, 1) # bs_df_noise[0]
156- # sbr_invf: one mode per noise band
157- for _ in range(cfg["n_q"]):
158- s.w(cfg["invf"], 2)
159- # sbr_envelope: first value raw, the rest would need Huffman
160- s.w(cfg["env0"], 6 if cfg["amp_res"] else 7)
161- for value, (length, code) in cfg.get("env_deltas", []):
162- s.w(code, length)
163- # sbr_noise: first value raw, the rest Huffman
164- s.w(cfg["noise0"], 5)
165- for value, (length, code) in cfg.get("noise_deltas", []):
166- s.w(code, length)
167- # bs_add_harmonic_flag
168- if cfg.get("harmonics") is None:
169- s.w(0, 1)
170- else:
171- s.w(1, 1)
172- for bit in cfg["harmonics"]:
173- s.w(bit, 1)
174- s.w(0, 1) # bs_extended_data
175- return s
176-
177-
178-def frame(cfg, sf_index=7, max_sfb=20):
179- w = BitW()
180- sce_core(w, sf_index, max_sfb, gain=cfg.get("gain", 200))
181- body = sbr_payload(cfg)
182- # extension_type nibble plus the payload, padded to whole bytes
183- payload_bits = 4 + len(body)
184- count = (payload_bits + 7) // 8
185- w.w(6, 3) # FIL
186- if count >= 15:
187- w.w(15, 4)
188- w.w(count - 15 + 1, 8)
189- else:
190- w.w(count, 4)
191- start = len(w)
192- w.w(13, 4) # EXT_SBR_DATA
193- w.wbits(body.bits)
194- while len(w) - start < count * 8:
195- w.w(0, 1)
196- w.w(7, 3) # END
197- return adts(w.pack(pad=0), sf_index)
198-
199-
200-def silent(sf_index):
201- w = BitW()
202- w.w(0, 3).w(0, 4).w(128, 8)
203- w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1)
204- w.w(0, 3).w(7, 3)
205- return adts(w.pack(4), sf_index)
206-
207-
208-def decode(frames, sf_index, tag=None):
209- """(samples, stderr) from ffmpeg for a stream of frames."""
210- src = f"/tmp/sbrprobe-{tag or os.getpid()}.aac"
211- with open(src, "wb") as f:
212- f.write(b"".join(frames))
213- r = subprocess.run(
214- ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"],
215- capture_output=True,
216- )
217- os.remove(src)
218- return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode()
219-
220-
221-DEFAULT = dict(
222- amp_res=1, start_freq=5, stop_freq=3, xover_band=0, freq_scale=0, alter_scale=0,
223- noise_bands=0, limiter_bands=0, limiter_gains=2, interpol_freq=1, smoothing_mode=1,
224- freq_res=1, invf=1, env0=40, noise0=15, n_q=1,
225-)
226-
227-if __name__ == "__main__":
228- cfg = dict(DEFAULT)
229- frames = [silent(7)] + [frame(cfg) for _ in range(6)] + [silent(7)]
230- pcm, err = decode(frames, 7, "smoke")
231- print("samples", len(pcm), "err", err.strip()[:300])
scripts/aac-tables/swb.pydeleted+0 -119
@@ -1,119 +0,0 @@
1-#!/usr/bin/env python3
2-"""Derive the scalefactor-band offset tables (ISO 14496-3 tbl 4.140) by probing.
3-
4-For a frame coded with max_sfb = k, the highest non-zero spectral coefficient is
5-swb_offset[k] - 1. Long windows are read back through the exact MDCT inverse;
6-short windows through the FFT of the 2048-sample frame, whose bin spacing
7-(fs/2048) is eight times finer than one short-block coefficient (fs/256).
8-"""
9-
10-import json
11-import os
12-import subprocess
13-import sys
14-
15-import numpy as np
16-
17-import aacprobe as A
18-import learn as L
19-
20-BASIS = np.cos(np.pi / 1024 * np.outer(np.arange(2048) + 512.5, np.arange(1024) + 0.5))
21-
22-
23-def sect_len(w, k, bits):
24- esc = (1 << bits) - 1
25- left = k
26- while left >= esc:
27- w.w(esc, bits)
28- left -= esc
29- w.w(left, bits)
30-
31-
32-def frame_long(k, sf_index):
33- w = A.BitW()
34- w.w(0, 3).w(0, 4).w(200, 8)
35- w.w(0, 1).w(0, 2).w(0, 1).w(k, 6).w(0, 1)
36- w.w(3, 4)
37- sect_len(w, k, 5)
38- w.wbits([0] * k) # the one-bit delta-zero scalefactor codeword per band
39- w.w(0, 3)
40- w.wbits([1] * 6000)
41- return A.adts(w.pack(pad=0), sf_index=sf_index)
42-
43-
44-def frame_short(k, sf_index):
45- w = A.BitW()
46- w.w(0, 3).w(0, 4).w(200, 8)
47- w.w(0, 1).w(2, 2).w(0, 1).w(k, 4).w(0x7F, 7) # EIGHT_SHORT, one group of 8
48- w.w(3, 4)
49- sect_len(w, k, 3)
50- w.wbits([0] * k)
51- w.w(0, 3)
52- w.wbits([1] * 6000)
53- return A.adts(w.pack(pad=0), sf_index=sf_index)
54-
55-
56-def silent(sf_index):
57- w = A.BitW()
58- w.w(0, 3).w(0, 4).w(128, 8)
59- w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1)
60- w.w(0, 3).w(7, 3)
61- return A.adts(w.pack(4), sf_index=sf_index)
62-
63-
64-def blocks(frames, sf_index):
65- src = f"swb-{os.getpid()}.aac"
66- sil = silent(sf_index)
67- with open(src, "wb") as f:
68- f.write(sil + b"".join(fr + sil + sil for fr in frames))
69- raw = subprocess.run(
70- ["ffmpeg", "-v", "quiet", "-i", src, "-f", "f32le", "-ac", "1", "-"],
71- capture_output=True,
72- )
73- pcm = np.frombuffer(raw.stdout, dtype="<f4").astype(np.float64)
74- os.remove(src)
75- nb = len(pcm) // 1024
76- if nb != 3 * len(frames) + 1:
77- if len(frames) == 1:
78- return [None]
79- h = len(frames) // 2
80- return blocks(frames[:h], sf_index) + blocks(frames[h:], sf_index)
81- pcm = pcm[: nb * 1024].reshape(nb, 1024)
82- return [np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]) for i in range(len(frames))]
83-
84-
85-def long_offsets(sf_index):
86- out = []
87- got = blocks([frame_long(k, sf_index) for k in range(1, 52)], sf_index)
88- for blk in got:
89- if blk is None:
90- break
91- spec = (BASIS.T @ (blk / L.WIN)) / 1024
92- nz = np.where(np.abs(spec) > 1e-3)[0]
93- if len(nz) == 0:
94- break
95- out.append(int(nz.max()) + 1)
96- return out
97-
98-
99-def short_offsets(sf_index):
100- out = []
101- got = blocks([frame_short(k, sf_index) for k in range(1, 17)], sf_index)
102- for blk in got:
103- if blk is None:
104- break
105- mag = np.abs(np.fft.rfft(blk * np.hanning(2048)))
106- top = np.where(mag > mag.max() * 3e-4)[0].max()
107- out.append(top / 8.0)
108- return out
109-
110-
111-if __name__ == "__main__":
112- out = {}
113- for idx in range(0, 12):
114- lo = long_offsets(idx)
115- sh = short_offsets(idx)
116- out[idx] = {"long": lo, "short": sh}
117- print(idx, "long", len(lo), lo, file=sys.stderr)
118- print(idx, "short", [round(v, 1) for v in sh], file=sys.stderr)
119- json.dump(out, open("swb.json", "w"))
scripts/aac-tables/tns.pydeleted+0 -34
@@ -1,34 +0,0 @@
1-import swb, aacprobe as A, sys
2-def frame_tns(max_sfb, n_filt, coef_res, length, order, direction, compress, coefs, sf_index=3):
3- w=A.BitW()
4- w.w(0,3).w(0,4).w(200,8)
5- w.w(0,1).w(0,2).w(0,1).w(max_sfb,6).w(0,1)
6- w.w(3,4); swb.sect_len(w,max_sfb,5)
7- w.wbits([0]*max_sfb)
8- w.w(0,1) # pulse_data_present
9- w.w(1,1) # tns_data_present
10- w.w(n_filt,2)
11- if n_filt:
12- w.w(coef_res,1)
13- for f in range(n_filt):
14- w.w(length,6); w.w(order,5)
15- if order:
16- w.w(direction,1); w.w(compress,1)
17- bits = coef_res + 3 - compress
18- for c in coefs[:order]:
19- w.w(c & ((1<<bits)-1), bits)
20- w.w(0,1) # gain_control
21- w.wbits([1]*6000)
22- return A.adts(w.pack(pad=0), sf_index=sf_index)
23-sil=swb.silent(3)
24-cases=[
25- (20,1,0,8,4,0,0,[1,2,-1,0]),
26- (20,1,0,8,4,1,0,[1,2,-1,0]),
27- (20,1,1,10,6,0,0,[3,-2,1,0,2,-1]),
28- (20,1,1,10,6,0,1,[1,-1,1,0,1,-1]),
29- (30,1,0,40,3,0,0,[2,-2,1]),
30- (20,2,0,6,3,0,0,[1,1,-1]),
31-]
32-frames=[frame_tns(*c) for c in cases]
33-open('/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/6410b1a2-7cdb-42c3-ac18-2bbfd6cd1284/scratchpad/short/tns.aac','wb').write(sil+b''.join(f+sil+sil for f in frames))
34-print('cases', len(cases))
scripts/av1-stage-suite.shdeleted+0 -124
@@ -1,124 +0,0 @@
1-#!/usr/bin/env bash
2-# av1-stage-suite.sh — stage an ec-av1 suite on a server host, behind the preflight
3-# gate. A staging whose pin audit or rung check FAILED, or whose checkers never
4-# ran, MUST NOT reach `=== SUITE`.
5-#
6-# WHY THIS EXISTS (lane-av1stagegaps, 2026-09-30). The hand-written staging
7-# driver logged the checker outcome and continued regardless:
8-#
9-# === ORACLE RUNG CHECKER
10-# rungs_exit=1 ok_count=0
11-# === SUITE
12-#
13-# so a green suite on a host meant nothing about its preflight. Three states —
14-# passed, failed, never ran — all looked the same. This driver runs
15-# scripts/av1-suite-preflight.sh under `set -e` and stops there.
16-#
17-# Usage:
18-# scripts/av1-stage-suite.sh --name <suite> --tree <dir> [--tarball <tgz>]
19-# [--skip <cargo-test-arg>]... [-- command...]
20-#
21-# Defaults: no cargo-test-arg means
22-# cargo test -p ec-av1 --lib -- --test-threads=1
23-#
24-# Env (all passed to the unit):
25-# CARGO_TARGET_DIR, TMPDIR defaulted under $HOME/gates/<name>-*
26-# EC_AV1_REQUIRE_AOMENC=1, EC_AV1_REQUIRE_FFMPEG=1, EC_REQUIRE_FIXTURES=1
27-# SUITE_RUNG_WAIVER=<reason> required to accept rung_check=not-run
28-#
29-# Exit: 0 the unit was started; non-zero the preflight BLOCKED and no unit
30-# exists. `systemctl --user is-active <name>-suite` is the only thing that
31-# starts a suite, so a blocked staging leaves the host idle on purpose.
32-
33-set -uo pipefail
34-
35-NAME=""
36-TREE=""
37-TARBALL=""
38-declare -a SKIPS=()
39-declare -a CMD=()
40-DRY_RUN=0
41-while [ $# -gt 0 ]; do
42- case "$1" in
43- --name) NAME=$2; shift 2 ;;
44- --tree) TREE=$2; shift 2 ;;
45- --tarball) TARBALL=$2; shift 2 ;;
46- --skip) SKIPS+=(--skip "$2"); shift 2 ;;
47- --dry-run) DRY_RUN=1; shift ;;
48- --) shift; CMD=("$@"); break ;;
49- -h|--help) sed -n '2,28p' "$0"; exit 0 ;;
50- *) echo "unknown argument: $1" >&2; exit 2 ;;
51- esac
52-done
53-[ -n "$NAME" ] && [ -n "$TREE" ] || { echo "usage: --name <suite> --tree <dir> [--tarball <tgz>] [--skip <arg>]... [-- cmd...]" >&2; exit 2; }
54-[ -d "$TREE" ] || { echo "no such tree: $TREE" >&2; exit 2; }
55-
56-# 1. The staged tree needs a real git checkout with a POPULATED index. A bare
57-# `git init` leaves the index empty and pin-gate-audit.py's
58-# `git ls-files --error-unmatch` then reports every pin as uncommitted — a
59-# staging artefact indistinguishable from the defect invariant 4 exists to
60-# catch (wave-3c-b correction). Test rev-parse, not `[ -d .git ]`: a worktree
61-# copy and a `git archive` untar both leave a `.git` FILE.
62-git -C "$TREE" rev-parse --git-dir >/dev/null 2>&1 || {
63- echo "staging defect: $TREE is not a git checkout; memguard-runner.sh dies with exit 128" >&2
64- exit 2
65-}
66-if [ -z "$(git -C "$TREE" ls-files | head -1)" ]; then
67- echo "staging defect: $TREE has an empty index; run git add -A after the untar" >&2
68- exit 2
69-fi
70-
71-# 2. Both gitignored lanes dumps: missing them fails exactly 2 tests that are
72-# not a decoder regression.
73-for f in intrarect_dump.expected.txt wedge_libaom.expected.txt; do
74- [ -f "$TREE/lanes/$f" ] || { echo "staging defect: $TREE/lanes/$f missing" >&2; exit 2; }
75-done
76-
77-TARGET=${CARGO_TARGET_DIR:-$HOME/gates/target-$NAME}
78-TMP=${TMPDIR:-$HOME/gates/tmp-$NAME}
79-mkdir -p "$TARGET" "$TMP"
80-
81-echo "=== host=$(hostname) commit=$(git -C "$TREE" rev-parse HEAD) date=$(date -Is)"
82-echo "=== cargo=$(command -v cargo || echo MISSING) aomenc=${EC_AV1_AOMENC:-unset} aomdec=${EC_AV1_AOMDEC:-unset} ffmpeg=$(command -v ffmpeg || echo MISSING)"
83-if [ -n "$TARBALL" ]; then
84- echo "=== tarball=$(sha256sum "$TARBALL" | cut -c1-16) -> $TREE"
85-fi
86-
87-# 3. THE GATE. `set -e` is the whole mechanism: a non-zero verdict aborts this
88-# script before systemd-run is ever reached, so no unit exists and no suite
89-# runs. There is no path from a blocked verdict to `=== SUITE`.
90-set -e
91-echo "=== PIN-GATE PREFLIGHT + ORACLE RUNG CHECKER"
92-EC_REQUIRE_FIXTURES=${EC_REQUIRE_FIXTURES:-1} \
93-EC_FIXTURE_SHAPE_STRICT=${EC_FIXTURE_SHAPE_STRICT:-1} \
94- bash "$TREE/scripts/av1-suite-preflight.sh" --tree "$TREE"
95-set +e
96-
97-echo "=== SUITE"
98-if [ "$DRY_RUN" = 1 ]; then
99- echo "dry-run: would start unit $NAME-suite in $TREE (target $TARGET, tmp $TMP)"
100- exit 0
101-fi
102-
103-if [ ${#CMD[@]} -eq 0 ]; then
104- CMD=(cargo test -p ec-av1 --lib -- --test-threads=1)
105-fi
106-declare -a quoted=()
107-for a in "${SKIPS[@]}"; do quoted+=("$a"); done
108-
109-LOG=$HOME/gates/$NAME-suite.log
110-mkdir -p "$HOME/gates"
111-systemd-run --user --unit="$NAME-suite" -p MemoryMax=5G \
112- -p WorkingDirectory="$TREE" \
113- --setenv="CARGO_TARGET_DIR=$TARGET" \
114- --setenv="TMPDIR=$TMP" \
115- --setenv=EC_NOMEMGUARD=1 \
116- --setenv=EC_AV1_REQUIRE_AOMENC=1 \
117- --setenv=EC_AV1_REQUIRE_FFMPEG=1 \
118- --setenv=EC_REQUIRE_FIXTURES=1 \
119- --setenv="EC_FIXTURES=${EC_FIXTURES:-$TREE/fixtures}" \
120- ${EC_AV1_AOMENC:+--setenv=EC_AV1_AOMENC=$EC_AV1_AOMENC} \
121- ${EC_AV1_AOMDEC:+--setenv=EC_AV1_AOMDEC=$EC_AV1_AOMDEC} \
122- --setenv="PATH=$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin" \
123- /usr/bin/bash -lc "cd '$TREE' && ${CMD[*]} ${quoted[*]-} > '$LOG' 2>&1"
124-echo "started $NAME-suite; real test output: $LOG"
scripts/av1-suite-preflight.shdeleted+0 -248
@@ -1,248 +0,0 @@
1-#!/usr/bin/env bash
2-# av1-suite-preflight.sh — the gate a server staging must pass BEFORE `=== SUITE`.
3-#
4-# WHY (lane-av1stagegaps, measured 2026-09-30). Three hosts, three different
5-# preflight realities, one identical green suite:
6-#
7-# host C host-d the driver printed
8-# === ORACLE RUNG CHECKER
9-# rungs_exit=1 ok_count=0
10-# === SUITE
11-# and the suite ran. The real cause, with stderr
12-# visible, was a MISSING PREREQUISITE: the host has
13-# `~/.cache/aom-oracle/build` (aomdec/aomenc binaries)
14-# and no `src/` tree, so the checker asserted nothing.
15-# host A host-a staged with a bare `cargo test -p ec-av1 --lib`. No
16-# pin-gate audit, no rung checker, no self-test: not a
17-# failure, an ABSENT check.
18-# so "green suite" meant checker-passed, checker-failed and no-checker-ran
19-# with equal confidence.
20-#
21-# WHAT THIS DOES. Runs both preflight pieces, prints one machine-readable state
22-# per piece, then a single VERDICT. Exit 0 only when every piece is GREEN or an
23-# explicitly waived NOT-RUN, so a `set -e` staging driver CANNOT reach
24-# `=== SUITE` on a failed or missing check.
25-#
26-# pin_audit = GREEN | FAIL | ABSENT (verify-fixture-library.sh: shape,
27-# resolve, drift, invariants 1-4 +
28-# census self-test)
29-# rung_check = GREEN | FAIL | NOT-RUN | ABSENT
30-# VERDICT = GREEN | WAIVED | BLOCKED
31-#
32-# NOT-RUN vs ABSENT is the distinction that matters. NOT-RUN means the checker
33-# RAN and reported a missing prerequisite (exit 3 from check-aom-oracle-rungs.sh)
34-# — a provisioning fact, not a code defect. ABSENT means the checker is not in
35-# this tree at all, which is exactly the host-A defect and is never waivable.
36-#
37-# WAIVER. not-run can be waived, but only with an explicit non-empty reason that
38-# is recorded in the verdict line, so a later reader can tell a deliberate
39-# waiver from a check that silently vanished:
40-# SUITE_RUNG_WAIVER="host host-d carries oracle binaries only; rung
41-# coverage verified on the build host, see report"
42-# An empty waiver counts as absent, so a unit's Environment= carrying a bare
43-# SUITE_RUNG_WAIVER= cannot accidentally authorise a run.
44-#
45-# Usage:
46-# scripts/av1-suite-preflight.sh [--tree DIR] [--self-test]
47-#
48-# Env:
49-# EC_FIXTURES=<dir> fixture root (default <tree>/fixtures)
50-# EC_REQUIRE_FIXTURES=1 make an absent/empty fixture path fatal
51-# SUITE_RUNG_WAIVER=<reason> waive rung_check=not-run (see above)
52-# SUITE_RUNG_CHECKER=<path> override the rung checker (self-test stubs)
53-# SUITE_PIN_CHECKER=<path> override the pin preflight (self-test stubs)
54-
55-set -uo pipefail
56-
57-ROOT_DEFAULT=$(cd -- "$(dirname -- "$0")/.." && pwd)
58-TREE=$ROOT_DEFAULT
59-SELF_TEST=0
60-while [ $# -gt 0 ]; do
61- case "$1" in
62- --tree) TREE=$2; shift 2 ;;
63- --self-test) SELF_TEST=1; shift ;;
64- -h|--help) sed -n '2,40p' "$0"; exit 0 ;;
65- *) echo "unknown argument: $1" >&2; exit 2 ;;
66- esac
67-done
68-PIN_CHECKER=${SUITE_PIN_CHECKER:-$TREE/scripts/verify-fixture-library.sh}
69-RUNG_CHECKER=${SUITE_RUNG_CHECKER:-$TREE/scripts/check-aom-oracle-rungs.sh}
70-
71-pin_state=ABSENT
72-rung_state=ABSENT
73-
74-run_pin() { # sets pin_state, prints every detail line
75- pin_state=ABSENT
76- if [ ! -f "$PIN_CHECKER" ]; then
77- echo "pin_audit_state=ABSENT reason=pin preflight not in tree ($PIN_CHECKER)" >&2
78- return
79- fi
80- local out rc
81- out=$("$PIN_CHECKER" 2>&1)
82- rc=$?
83- printf '%s\n' "$out" | sed 's/^/ /'
84- if [ $rc -eq 0 ]; then pin_state=GREEN; else pin_state=FAIL; fi
85- echo "pin_audit_exit=$rc state=$pin_state"
86-}
87-
88-run_rungs() { # sets rung_state, prints every detail line
89- rung_state=ABSENT
90- if [ ! -f "$RUNG_CHECKER" ]; then
91- echo "rung_check_state=ABSENT reason=checker not in tree ($RUNG_CHECKER)" >&2
92- return
93- fi
94- local out rc ok_count
95- out=$("$RUNG_CHECKER" 2>&1)
96- rc=$?
97- ok_count=$(printf '%s\n' "$out" | grep -c '^ok ' || true)
98- # The detail lines are the whole point: the 2026-09-30 driver logged
99- # `rungs_exit=1 ok_count=0` and no reason at all. Every outcome here prints
100- # the checker's own stdout and stderr together, indented.
101- printf '%s\n' "$out" | sed 's/^/ /'
102- case $rc in
103- 0) rung_state=GREEN ;;
104- 3) rung_state=NOT-RUN ;;
105- *) rung_state=FAIL ;;
106- esac
107- echo "rungs_exit=$rc ok_count=$ok_count state=$rung_state"
108-}
109-
110-verdict() { # echoes VERDICT; returns 0 iff GREEN or WAIVED
111- # A pin audit that did not run or failed, and a rung check that is absent
112- # or failed, are all fatal: no waiver exists for any of them. Only
113- # rung_check=not-run (a missing prerequisite) is waivable, and only with a
114- # non-empty reason.
115- local v=BLOCKED
116- local waived=""
117- if [ "$pin_state" = GREEN ] && [ "$rung_state" = GREEN ]; then
118- v=GREEN
119- elif [ "$pin_state" = GREEN ] && [ "$rung_state" = NOT-RUN ]; then
120- if [ -n "${SUITE_RUNG_WAIVER:-}" ]; then
121- v=WAIVED
122- waived=" (rung_check=not-run waived: ${SUITE_RUNG_WAIVER})"
123- fi
124- fi
125- echo "VERDICT=$v$waived"
126- if [ "$v" = BLOCKED ]; then
127- {
128- echo "PREFLIGHT BLOCKED: pin_audit=$pin_state rung_check=$rung_state."
129- echo " A staging with a failed or missing check must NOT reach === SUITE."
130- echo " rung_check=not-run (missing oracle source) is waivable only via"
131- echo " SUITE_RUNG_WAIVER='<host and reason>'; an absent checker never is."
132- } >&2
133- return 1
134- fi
135- return 0
136-}
137-
138-self_test() {
139- local d rc=0 out
140- d=$(mktemp -d "${TMPDIR:-/tmp}/av1-preflight-selftest.XXXXXX")
141- # shellcheck disable=SC2064
142- trap "rm -rf '$d'" RETURN
143-
144- stub() { # name, exit-code, body
145- printf '#!/usr/bin/env bash\n%s\nexit %s\n' "$3" "$2" >"$d/$1"
146- chmod +x "$d/$1"
147- }
148- # `set -o pipefail` is on, so `verdict | grep -q ...` returns verdict's own
149- # non-zero status even when grep matched, and every BLOCKED case would read
150- # as a self-test failure. Capture first, then compare.
151- v_of() { verdict 2>/dev/null; }
152- expect() { # expected-verdict, label
153- out=$("${@:3}" 2>/dev/null || true)
154- :
155- }
156-
157- # 1. all green -> GREEN
158- stub pin-ok 0 'echo "verify-fixture-library: GREEN"'
159- stub rungs-ok 0 'echo "ok derives the rungs"'
160- PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1
161- RUNG_CHECKER=$d/rungs-ok run_rungs >/dev/null 2>&1
162- if [ "$(v_of)" = "VERDICT=GREEN" ]; then
163- echo "ok 1 an all-green staging is GREEN"
164- else
165- echo "FAIL 1 an all-green staging is GREEN"; rc=1
166- fi
167-
168- # 2. rung checker FAILS (exit 1) -> BLOCKED. The mutation: red the checker
169- # and the gate must stop.
170- stub rungs-bad 1 'echo "FAIL derived file violates the rung contract"'
171- PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1
172- RUNG_CHECKER=$d/rungs-bad run_rungs >/dev/null 2>&1
173- if [ "$(v_of)" = "VERDICT=BLOCKED" ]; then
174- echo "ok 2 a FAILING rung checker blocks the suite"
175- else
176- echo "FAIL 2 a FAILING rung checker blocks the suite"; rc=1
177- fi
178-
179- # 3. rung checker NOT-RUN (exit 3), no waiver -> BLOCKED.
180- stub rungs-notrun 3 'echo "PREREQ-ABSENT: no oracle source at ..."'
181- PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1
182- RUNG_CHECKER=$d/rungs-notrun run_rungs >/dev/null 2>&1
183- if [ "$(v_of)" = "VERDICT=BLOCKED" ]; then
184- echo "ok 3 not-run without a waiver blocks the suite"
185- else
186- echo "FAIL 3 not-run without a waiver blocks the suite"; rc=1
187- fi
188-
189- # 4. not-run WITH a waiver -> WAIVED, and the reason lands in the verdict.
190- if [ "$(SUITE_RUNG_WAIVER='host C carries oracle binaries only' v_of)" \
191- = "VERDICT=WAIVED (rung_check=not-run waived: host C carries oracle binaries only)" ]
192- then
193- echo "ok 4 not-run with a named waiver is WAIVED, reason recorded"
194- else
195- echo "FAIL 4 not-run with a named waiver is WAIVED, reason recorded"; rc=1
196- fi
197-
198- # 5. an EMPTY waiver authorises nothing: a unit Environment= carrying a bare
199- # SUITE_RUNG_WAIVER= is a real staging shape.
200- if [ "$(SUITE_RUNG_WAIVER='' v_of)" = "VERDICT=BLOCKED" ]; then
201- echo "ok 5 an empty waiver does not authorise a run"
202- else
203- echo "FAIL 5 an empty waiver does not authorise a run"; rc=1
204- fi
205-
206- # 6. an ABSENT checker is never waivable: the host-A defect.
207- PIN_CHECKER=$d/pin-ok run_pin >/dev/null 2>&1
208- RUNG_CHECKER=$d/does-not-exist run_rungs >/dev/null 2>&1
209- if [ "$(SUITE_RUNG_WAIVER='a waiver' v_of)" = "VERDICT=BLOCKED" ]; then
210- echo "ok 6 a tree with NO rung checker is blocked even with a waiver"
211- else
212- echo "FAIL 6 a tree with NO rung checker is blocked even with a waiver"; rc=1
213- fi
214-
215- # 6b. an ABSENT pin audit is fatal too, and not waivable by the same knob.
216- PIN_CHECKER=$d/does-not-exist run_pin >/dev/null 2>&1
217- RUNG_CHECKER=$d/rungs-ok run_rungs >/dev/null 2>&1
218- if [ "$(SUITE_RUNG_WAIVER='a waiver' v_of)" = "VERDICT=BLOCKED" ]; then
219- echo "ok 7 a tree with NO pin audit is blocked even with a waiver"
220- else
221- echo "FAIL 7 a tree with NO pin audit is blocked even with a waiver"; rc=1
222- fi
223-
224- # 8. pin audit FAILING -> BLOCKED even when the rungs are green.
225- stub pin-bad 1 'echo "FAIL [invariant 4]: census self-test did not pass"'
226- PIN_CHECKER=$d/pin-bad run_pin >/dev/null 2>&1
227- RUNG_CHECKER=$d/rungs-ok run_rungs >/dev/null 2>&1
228- if [ "$(v_of)" = "VERDICT=BLOCKED" ]; then
229- echo "ok 8 a FAILING pin audit blocks the suite"
230- else
231- echo "FAIL 8 a FAILING pin audit blocks the suite"; rc=1
232- fi
233-
234- return $rc
235-}
236-
237-if [ "$SELF_TEST" = 1 ]; then
238- self_test
239- exit $?
240-fi
241-
242-echo "=== PIN-GATE PREFLIGHT (EC_REQUIRE_FIXTURES=${EC_REQUIRE_FIXTURES:-0})"
243-run_pin
244-echo "=== ORACLE RUNG CHECKER"
245-run_rungs
246-echo "=== VERDICT"
247-verdict
248-exit $?
scripts/bench-benchaudio.shdeleted+0 -237
@@ -1,237 +0,0 @@
1-#!/usr/bin/env bash
2-# bench-benchaudio.sh: the audio rows of lanes/bench.md ("lane benchaudio", DONE.md gate G6).
3-#
4-# Local machine only (DONE.md D7 exception): build with -j6 into CARGO_TARGET_DIR and run each
5-# row as the best of 5 inside the bench binary. Before each row, wait until the 1-minute load is
6-# below 3. Clips are synthetic and generated here with the local ffmpeg (never personal media);
7-# they live in $BENCH_CLIPS (default ~/.cache/benchaudio-clips), outside the repo.
8-#
9-# Output: one "ROW|..." line per bench row (crate, op, content, best time, x realtime or rates,
10-# and the output check), then "CHECK|..." lines with the comparison details. The lanes/bench.md
11-# "lane benchaudio" table is written from these lines.
12-#
13-# usage: scripts/bench-benchaudio.sh [--no-clips] [--no-build]
14-set -euo pipefail
15-
16-cd "$(dirname "$0")/.."
17-REPO="$(pwd)"
18-CLIPS="${BENCH_CLIPS:-$HOME/.cache/benchaudio-clips}"
19-BIN="${BENCH_BIN:-$HOME/.cache/benchaudio-bin}"
20-OUT="$CLIPS/out"
21-export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchaudio}"
22-export RUSTC_WRAPPER=
23-export TMPDIR="${TMPDIR:-$HOME/.cache/tmp-benchaudio}"
24-FF=(ffmpeg -hide_banner -loglevel error -y)
25-DO_CLIPS=1
26-DO_BUILD=1
27-for a in "$@"; do
28- case "$a" in
29- --no-clips) DO_CLIPS=0 ;;
30- --no-build) DO_BUILD=0 ;;
31- *) echo "unknown option: $a" >&2; exit 2 ;;
32- esac
33-done
34-mkdir -p "$CLIPS" "$BIN" "$OUT" "$TMPDIR"
35-COMMIT="$(git -C "$REPO" rev-parse --short HEAD)"
36-echo "# host=local cores=$(nproc) commit=$COMMIT ffmpeg=$(ffmpeg -version | head -1 | awk '{print $3}')"
37-
38-# ---- 1. synthetic clips -------------------------------------------------------------------
39-if [ "$DO_CLIPS" = 1 ]; then
40- cd "$CLIPS"
41- if [ ! -f src_stereo.wav ]; then
42- # 60 s stereo: tones with a slow AM, plus two independent pink-noise channels.
43- "${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" \
44- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=1" \
45- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=2" \
46- -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]" \
47- -map "[o]" -c:a pcm_s16le src_stereo.wav
48- fi
49- if [ ! -f src_stereo.f32 ]; then "${FF[@]}" -i src_stereo.wav -f f32le -acodec pcm_f32le src_stereo.f32; fi
50- if [ ! -f src_51.thd ]; then
51- # 60 s 5.1 for TrueHD: six tones plus six independent pink-noise channels.
52- "${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" \
53- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=3" \
54- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=4" \
55- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=5" \
56- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=6" \
57- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=7" \
58- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=8" \
59- -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]" \
60- -map "[o]" -c:a truehd -strict -2 -f truehd src_51.thd
61- fi
62- # AAC-LC 128k stereo (libfdk_aac) and Opus 96k, Vorbis q5 (libvorbis), MP3 192k reference.
63- [ -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
64- [ -f opus_96k.ogg ] || "${FF[@]}" -i src_stereo.wav -c:a libopus -b:a 96k -f ogg opus_96k.ogg
65- [ -f vorbis_q5.ogg ] || "${FF[@]}" -i src_stereo.wav -c:a libvorbis -q:a 5 -f ogg vorbis_q5.ogg
66- # HE-AAC v1: the local libfdk_aac cannot encode SBR (it fails "Unable to set the AOT 5" at every
67- # rate and bitrate tried), so the stream is the 2.1 s HE-AAC v1 fixture of the repo
68- # (ec-aac tests/data/heaac_44100_48k_implicit_2s.aac, implicit SBR), repeated 28 times to 60 s.
69- if [ ! -f aac_he_v1_60s.adts ]; then
70- fx="$REPO/crates/ec-aac/tests/data/heaac_44100_48k_implicit_2s.aac"
71- : > aac_he_v1_60s.adts
72- for _ in $(seq 28); do cat "$fx" >> aac_he_v1_60s.adts; done
73- fi
74- # H.264 1080p30 + AAC stereo, 60 s synthetic (testsrc2 video, the tones+noise audio).
75- [ -f h264_aac_1080p30.mp4 ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=30:duration=60" -i src_stereo.wav \
76- -c:v libx264 -preset veryfast -b:v 4M -pix_fmt yuv420p -c:a aac -b:a 128k -shortest h264_aac_1080p30.mp4
77- # References for the output checks (ffmpeg's own decoders and remux).
78- [ -f ref_aac_lc.f32le ] || "${FF[@]}" -i aac_lc_128k.adts -f f32le -acodec pcm_f32le ref_aac_lc.f32le
79- [ -f ref_aac_he.f32le ] || "${FF[@]}" -i aac_he_v1_60s.adts -f f32le -acodec pcm_f32le ref_aac_he.f32le
80- [ -f ref_opus.f32le ] || "${FF[@]}" -i opus_96k.ogg -f f32le -acodec pcm_f32le ref_opus.f32le
81- [ -f ref_vorbis.f32le ] || "${FF[@]}" -i vorbis_q5.ogg -f f32le -acodec pcm_f32le ref_vorbis.f32le
82- [ -f ref_truehd.s32le ] || "${FF[@]}" -i src_51.thd -f s32le -acodec pcm_s32le ref_truehd.s32le
83- [ -f ref_mp4.v.bin ] || "${FF[@]}" -i h264_aac_1080p30.mp4 -map 0:v:0 -c copy -f data ref_mp4.v.bin
84- [ -f ref_mp4.a.bin ] || "${FF[@]}" -i h264_aac_1080p30.mp4 -map 0:a:0 -c copy -f data ref_mp4.a.bin
85- cd "$REPO"
86-fi
87-
88-# ---- 2. build the six examples (one binary per crate, copied before the next build) --------
89-crates=(ec-aac ec-opus ec-vorbis ec-mp3 ec-truehd ec-mp4)
90-if [ "$DO_BUILD" = 1 ]; then
91- for c in "${crates[@]}"; do
92- cargo build --release -j6 -p "$c" --example bench
93- cp "$CARGO_TARGET_DIR/release/examples/bench" "$BIN/$c-bench"
94- done
95-fi
96-
97-# ---- 3. helpers --------------------------------------------------------------------------
98-wait_load() {
99- # Start a row only when the 1-minute load is below 3.
100- while :; do
101- l=$(cut -d' ' -f1 /proc/loadavg)
102- if awk -v l="$l" 'BEGIN{exit !(l < 3)}'; then echo "$l"; return; fi
103- sleep 5
104- done
105-}
106-field() { echo "$1" | tr ' ' '\n' | sed -n "s/^$2=//p"; }
107-ratio() { awk -v a="$1" -v b="$2" 'BEGIN{ if (b > 0) printf "%.2f", a / b; else print "nan" }'; }
108-# corr CHECK: min per-channel Pearson correlation at the best lag (+-4096 samples), ref vs test.
109-corr() {
110- python3 -I - "$1" "$2" "$3" "$4" "$5" <<'PY'
111-import sys
112-import numpy as np
113-ref_p, test_p, ch, rate, fmt = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]), sys.argv[5]
114-def load(p):
115- a = np.fromfile(p, '<f4' if fmt == 'f32' else '<i4').astype(np.float64)
116- if fmt == 's32':
117- a /= 2147483648.0
118- n = (a.size // ch) * ch
119- return a[:n].reshape(-1, ch)
120-r, t = load(ref_p), load(test_p)
121-L = min(2 * rate, r.shape[0] // 2)
122-s0 = min(10 * rate, r.shape[0] - L)
123-seg = r[s0:s0 + L, 0] - r[s0:s0 + L, 0].mean()
124-seg_n = np.linalg.norm(seg)
125-best_c, best_lag = -2.0, 0
126-for lag in range(-4096, 4097):
127- s = s0 + lag
128- if s < 0 or s + L > t.shape[0]:
129- continue
130- x = t[s:s + L, 0]
131- x = x - x.mean()
132- c = float(np.dot(seg, x) / (seg_n * np.linalg.norm(x) + 1e-30))
133- if c > best_c:
134- best_c, best_lag = c, lag
135-i0, i1 = max(0, -best_lag), min(r.shape[0], t.shape[0] - best_lag)
136-cs = []
137-for k in range(ch):
138- a = r[i0:i1, k] - r[i0:i1, k].mean()
139- b = t[i0 + best_lag:i1 + best_lag, k] - t[i0 + best_lag:i1 + best_lag, k].mean()
140- cs.append(float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30)))
141-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}")
142-PY
143-}
144-md5_of() { md5sum "$1" | cut -c1-8; }
145-
146-# ---- 4. rows -----------------------------------------------------------------------------
147-cd "$CLIPS"
148-B="$BIN"
149-
150-# AAC decode, LC and HE-AAC v1 (ADTS), 2 ch.
151-for spec in "ec-aac|aac_lc_128k.adts|AAC-LC stereo 128 kb/s 60 s (libfdk_aac)|ref_aac_lc.f32le" \
152- "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
153- IFS='|' read -r crate in content ref <<<"$spec"
154- l=$(wait_load)
155- res=$("$B/$crate-bench" dec "$in" "$OUT/aacdec-$in.f32le" 5)
156- best=$(field "$res" best_decode_s); samples=$(field "$res" samples); fails=$(field "$res" frames_failed)
157- audio=$(awk -v s="$samples" 'BEGIN{printf "%.3f", s/2/48000}')
158- echo "ROW|$crate|decode|$content|$best|$(ratio "$audio" "$best")x|load1=$l frames_failed=$fails"
159- c=$(corr "$ref" "$OUT/aacdec-$in.f32le" 2 48000 f32)
160- echo "CHECK|$crate decode $in|vs ffmpeg $(ffmpeg -version | head -1 | awk '{print $3}') native aac: $c"
161-done
162-
163-# AAC-LC encode, stereo 128k: encode the source, then decode the result with ffmpeg and compare.
164-l=$(wait_load)
165-res=$("$B/ec-aac-bench" enc src_stereo.f32 2 48000 128 "$OUT/aacenc.adts" 5)
166-best=$(field "$res" best_encode_s); audio=$(field "$res" audio_s); bytes=$(field "$res" bytes)
167-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}')"
168-"${FF[@]}" -i "$OUT/aacenc.adts" -f f32le -acodec pcm_f32le "$OUT/aacenc-ffdec.f32le"
169-echo "CHECK|ec-aac encode|ffmpeg decode of our ADTS vs source: $(corr src_stereo.f32 "$OUT/aacenc-ffdec.f32le" 2 48000 f32)"
170-# Calibration: ffmpeg's own AAC encoders at the same 128k, through the same decode and check.
171-"${FF[@]}" -i src_stereo.wav -c:a aac -b:a 128k -f adts "$OUT/cal-native.adts"
172-"${FF[@]}" -i "$OUT/cal-native.adts" -f f32le -acodec pcm_f32le "$OUT/cal-native.f32le"
173-echo "CHECK|ec-aac encode calibration|ffmpeg native aac 128k, same check: $(corr src_stereo.f32 "$OUT/cal-native.f32le" 2 48000 f32)"
174-"${FF[@]}" -i src_stereo.wav -c:a libfdk_aac -profile:a aac_low -b:a 128k -f adts "$OUT/cal-fdk.adts"
175-"${FF[@]}" -i "$OUT/cal-fdk.adts" -f f32le -acodec pcm_f32le "$OUT/cal-fdk.f32le"
176-echo "CHECK|ec-aac encode calibration|ffmpeg libfdk_aac 128k, same check: $(corr src_stereo.f32 "$OUT/cal-fdk.f32le" 2 48000 f32)"
177-
178-# Opus decode 48k stereo 96k, and encode.
179-l=$(wait_load)
180-res=$("$B/ec-opus-bench" dec opus_96k.ogg "$OUT/opusdec.f32le" 5)
181-best=$(field "$res" best_decode_s); samples=$(field "$res" samples)
182-audio=$(awk -v s="$samples" 'BEGIN{printf "%.3f", s/48000}')
183-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)"
184-echo "CHECK|ec-opus decode|vs ffmpeg Opus decode: $(corr ref_opus.f32le "$OUT/opusdec.f32le" 2 48000 f32)"
185-
186-l=$(wait_load)
187-res=$("$B/ec-opus-bench" enc src_stereo.f32 2 96 "$OUT/opusenc.ogg" 5)
188-best=$(field "$res" best_encode_s); audio=$(field "$res" audio_s); bytes=$(field "$res" bytes)
189-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}')"
190-"${FF[@]}" -i "$OUT/opusenc.ogg" -f f32le -acodec pcm_f32le "$OUT/opusenc-ffdec.f32le"
191-echo "CHECK|ec-opus encode|ffmpeg decode of our Ogg Opus vs source: $(corr src_stereo.f32 "$OUT/opusenc-ffdec.f32le" 2 48000 f32)"
192-
193-# Vorbis decode, q5 stereo.
194-l=$(wait_load)
195-res=$("$B/ec-vorbis-bench" dec vorbis_q5.ogg "$OUT/vorbisdec.f32le" 5)
196-best=$(field "$res" best_decode_s); samples=$(field "$res" samples)
197-audio=$(awk -v s="$samples" 'BEGIN{printf "%.3f", s/48000}')
198-echo "ROW|ec-vorbis|decode|Vorbis q5 stereo 60 s (libvorbis)|$best|$(ratio "$audio" "$best")x|load1=$l"
199-echo "CHECK|ec-vorbis decode|vs ffmpeg Vorbis decode: $(corr ref_vorbis.f32le "$OUT/vorbisdec.f32le" 2 48000 f32)"
200-
201-# MP3 encode, 192k CBR stereo (Layer III); the output is decoded with ffmpeg and compared.
202-l=$(wait_load)
203-res=$("$B/ec-mp3-bench" enc src_stereo.f32 2 48000 192 "$OUT/mp3enc.mp3" 5)
204-best=$(field "$res" best_encode_s); audio=$(field "$res" audio_s); bytes=$(field "$res" bytes)
205-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}')"
206-"${FF[@]}" -i "$OUT/mp3enc.mp3" -f f32le -acodec pcm_f32le "$OUT/mp3enc-ffdec.f32le"
207-echo "CHECK|ec-mp3 encode|ffmpeg decode of our MP3 vs source: $(corr src_stereo.f32 "$OUT/mp3enc-ffdec.f32le" 2 48000 f32)"
208-
209-# TrueHD decode, 5.1 24-bit (S32 container). Lossless: the output must equal ffmpeg's bytes.
210-l=$(wait_load)
211-res=$("$B/ec-truehd-bench" dec src_51.thd "$OUT/truehd-dec.s32le" 5)
212-best=$(field "$res" best_decode_s); audio=$(field "$res" audio_s); fails=$(field "$res" check_failures)
213-echo "ROW|ec-truehd|decode|TrueHD 5.1 24-bit 48k 60 s|$best|$(ratio "$audio" "$best")x|load1=$l self_check_failures=$fails"
214-if cmp -s ref_truehd.s32le "$OUT/truehd-dec.s32le"; then
215- echo "CHECK|ec-truehd decode|md5 $(md5_of ref_truehd.s32le) = ffmpeg (bit-exact, $(stat -c%s ref_truehd.s32le) bytes)"
216-else
217- echo "CHECK|ec-truehd decode|md5 MISMATCH vs ffmpeg: ours $(md5_of "$OUT/truehd-dec.s32le") ffmpeg $(md5_of ref_truehd.s32le)"
218-fi
219-
220-# MP4 demux and mux, H.264 1080p30 + AAC, 60 s.
221-file_bytes=$(stat -c%s h264_aac_1080p30.mp4)
222-l=$(wait_load)
223-res=$("$B/ec-mp4-bench" demux h264_aac_1080p30.mp4 "$OUT/mp4" 5)
224-pps=$(field "$res" packets_per_s); mbs=$(field "$res" mb_per_s); pk=$(field "$res" packets)
225-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"
226-v_ok=$([ "$(md5_of "$OUT/mp4.s0.bin")" = "$(md5_of ref_mp4.v.bin)" ] && echo match || echo MISMATCH)
227-a_ok=$([ "$(md5_of "$OUT/mp4.s1.bin")" = "$(md5_of ref_mp4.a.bin)" ] && echo match || echo MISMATCH)
228-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) ))"
229-
230-l=$(wait_load)
231-res=$("$B/ec-mp4-bench" mux h264_aac_1080p30.mp4 "$OUT/mux.mp4" 5)
232-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"
233-"${FF[@]}" -i "$OUT/mux.mp4" -map 0:v:0 -c copy -f data "$OUT/mux.v.bin"
234-"${FF[@]}" -i "$OUT/mux.mp4" -map 0:a:0 -c copy -f data "$OUT/mux.a.bin"
235-v_ok=$([ "$(md5_of "$OUT/mux.v.bin")" = "$(md5_of ref_mp4.v.bin)" ] && echo match || echo MISMATCH)
236-a_ok=$([ "$(md5_of "$OUT/mux.a.bin")" = "$(md5_of ref_mp4.a.bin)" ] && echo match || echo MISMATCH)
237-echo "CHECK|ec-mp4 mux|ffmpeg -c copy -f data of our output vs source payload: video $v_ok, audio $a_ok"
scripts/bench-benchhw.shdeleted+0 -173
@@ -1,173 +0,0 @@
1-#!/usr/bin/env bash
2-# bench-benchhw.sh: the VA-API rows of lanes/bench.md ("lane benchhw", DONE.md gate G6).
3-#
4-# Local machine only, with the GPU (radeonsi VA-API; `vainfo` lists the profiles). Clips are
5-# synthetic, generated here with the local ffmpeg (testsrc2 + noise, 1080p30, 60 s), and live in
6-# $BENCH_CLIPS (default ~/.cache/benchhw-clips), outside the repo.
7-#
8-# Rows:
9-# decode ec-hw Decoder, H.264 High, HEVC Main, HEVC Main10, VP9 profile 0, AV1 8-bit.
10-# Each row: best of 5 timed runs (GPU waited per picture), then one readback pass whose
11-# frames are compared md5-per-frame with ffmpeg's software decode of the same file.
12-# encode ec-hw Encoder, H.264 High and HEVC Main, 1080p30 CBR 8 Mb/s, GOP 30, 1800 pictures.
13-# Best of 5; the stream is decoded by ffmpeg (exit status, frame count, PSNR vs source).
14-#
15-# Output: one "ROW|..." line per row, then "CHECK|..." lines with the comparison details.
16-# The lanes/bench.md "lane benchhw" table is written from these lines.
17-#
18-# usage: scripts/bench-benchhw.sh [--no-clips] [--no-build]
19-set -euo pipefail
20-
21-cd "$(dirname "$0")/.."
22-REPO="$(pwd)"
23-CLIPS="${BENCH_CLIPS:-$HOME/.cache/benchhw-clips}"
24-BIN="${BENCH_BIN:-$HOME/.cache/benchhw-bin}"
25-OUT="$CLIPS/out"
26-export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchhw}"
27-export RUSTC_WRAPPER=
28-export TMPDIR="${TMPDIR:-$HOME/.cache/tmp-benchhw}"
29-FF=(ffmpeg -hide_banner -loglevel error -y)
30-DO_CLIPS=1
31-DO_BUILD=1
32-for a in "$@"; do
33- case "$a" in
34- --no-clips) DO_CLIPS=0 ;;
35- --no-build) DO_BUILD=0 ;;
36- *) echo "unknown option: $a" >&2; exit 2 ;;
37- esac
38-done
39-mkdir -p "$CLIPS" "$BIN" "$OUT" "$TMPDIR"
40-COMMIT="$(git -C "$REPO" rev-parse --short HEAD)"
41-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)"
42-
43-SRC="testsrc2=size=1920x1080:rate=30:duration=60"
44-W=1920
45-H=1080
46-
47-# ---- 1. synthetic clips -------------------------------------------------------------------
48-if [ "$DO_CLIPS" = 1 ]; then
49- cd "$CLIPS"
50- # Raw 8-bit 4:2:0 source for the encode rows (1800 pictures, about 5.6 GB).
51- [ -f src_1080p30_8bit.yuv ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \
52- -f rawvideo -pix_fmt yuv420p src_1080p30_8bit.yuv
53- # Decode inputs. Short GOP (30 pictures = 1 s). Annex B for H.264/HEVC, IVF for VP9/AV1.
54- [ -f h264_high_1080p30.264 ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \
55- -c:v libx264 -preset veryfast -profile:v high -crf 23 -g 30 -keyint_min 30 \
56- -f h264 h264_high_1080p30.264
57- [ -f hevc_main_1080p30.265 ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \
58- -c:v libx265 -preset veryfast -crf 23 -x265-params "keyint=30:min-keyint=30:log-level=error" \
59- -profile:v main -f hevc hevc_main_1080p30.265
60- [ -f hevc_main10_1080p30.265 ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p10le,noise=alls=20:allf=t" \
61- -c:v libx265 -preset veryfast -crf 23 -x265-params "keyint=30:min-keyint=30:log-level=error" \
62- -profile:v main10 -pix_fmt yuv420p10le -f hevc hevc_main10_1080p30.265
63- [ -f vp9_profile0_1080p30.ivf ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \
64- -c:v libvpx-vp9 -deadline realtime -cpu-used 5 -row-mt 1 -b:v 0 -crf 31 -g 30 \
65- -pix_fmt yuv420p -f ivf vp9_profile0_1080p30.ivf
66- [ -f av1_8bit_1080p30.ivf ] || "${FF[@]}" -f lavfi -i "$SRC,format=yuv420p,noise=alls=10:allf=t" \
67- -c:v libsvtav1 -preset 8 -crf 35 -g 30 -pix_fmt yuv420p -f ivf av1_8bit_1080p30.ivf
68- # References: ffmpeg's software decoders, native pixel format, every picture.
69- [ -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
70- [ -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
71- [ -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
72- [ -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
73- [ -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
74- cd "$REPO"
75-fi
76-
77-# ---- 2. build the bench example -----------------------------------------------------------
78-if [ "$DO_BUILD" = 1 ]; then
79- cargo build --release -j6 -p ec-hw --example bench
80- cp "$CARGO_TARGET_DIR/release/examples/bench" "$BIN/ec-hw-bench"
81-fi
82-B="$BIN/ec-hw-bench"
83-
84-# ---- 3. helpers --------------------------------------------------------------------------
85-wait_load() {
86- # Start a row only when the 1-minute load is below 3.
87- while :; do
88- l=$(cut -d' ' -f1 /proc/loadavg)
89- if awk -v l="$l" 'BEGIN{exit !(l < 3)}'; then echo "$l"; return; fi
90- sleep 5
91- done
92-}
93-field() { echo "$1" | tr ' ' '\n' | sed -n "s/^$2=//p"; }
94-# framecmp REF TEST FRAME_BYTES: per-frame md5 comparison; prints frames, equal count, first diff.
95-framecmp() {
96- python3 -I - "$1" "$2" "$3" <<'PY'
97-import hashlib, sys
98-ref, test, fb = sys.argv[1], sys.argv[2], int(sys.argv[3])
99-def md5s(p):
100- out = []
101- with open(p, 'rb') as f:
102- while True:
103- b = f.read(fb)
104- if not b:
105- break
106- out.append(hashlib.md5(b).hexdigest()[:12])
107- return out
108-r, t = md5s(ref), md5s(test)
109-same = sum(1 for a, b in zip(r, t) if a == b)
110-first = next((i for i, (a, b) in enumerate(zip(r, t)) if a != b), None)
111-print(f"frames_ref={len(r)} frames_test={len(t)} frames_md5_equal={same} first_diff={first if first is not None else 'none'}")
112-PY
113-}
114-
115-# ---- 4. decode rows ----------------------------------------------------------------------
116-cd "$CLIPS"
117-dec_row() { # label codec stream ref frame_bytes
118- local label=$1 codec=$2 stream=$3 ref=$4 fb=$5
119- local l res best fps x pics
120- l=$(wait_load)
121- res=$("$B" dec "$codec" "$stream" --out "$OUT/dump-$label.yuv" --runs 5)
122- best=$(echo "$res" | sed -n 's/^BEST|.*best_s=\([^ ]*\).*/\1/p')
123- fps=$(echo "$res" | sed -n 's/^BEST|.*fps=\([^ ]*\).*/\1/p')
124- x=$(echo "$res" | sed -n 's/^BEST|.*x_realtime=\([^ ]*\).*/\1/p')
125- pics=$(echo "$res" | sed -n 's/^BEST|.*pictures=\([^ ]*\).*/\1/p')
126- 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"
127- echo "CHECK|ec-hw decode $label|$(framecmp "$ref" "$OUT/dump-$label.yuv" "$fb")"
128- rm -f "$OUT/dump-$label.yuv"
129-}
130-FB8=$((W * H * 3 / 2))
131-FB10=$((W * H * 3))
132-dec_row h264-high h264 h264_high_1080p30.264 ref_h264.yuv "$FB8"
133-dec_row hevc-main hevc hevc_main_1080p30.265 ref_hevc.yuv "$FB8"
134-dec_row hevc-main10 hevc hevc_main10_1080p30.265 ref_hevc10.yuv "$FB10"
135-dec_row vp9-profile0 vp9 vp9_profile0_1080p30.ivf ref_vp9.yuv "$FB8"
136-dec_row av1-8bit av1 av1_8bit_1080p30.ivf ref_av1.yuv "$FB8"
137-
138-# ---- 5. encode rows ----------------------------------------------------------------------
139-enc_row() { # label codec ffmt
140- local label=$1 codec=$2 ffmt=$3
141- local l res best fps x kbps
142- l=$(wait_load)
143- res=$("$B" enc "$codec" src_1080p30_8bit.yuv "$W" "$H" 1800 8000000 --out "$OUT/enc-$label.bin" --runs 5)
144- best=$(echo "$res" | sed -n 's/^BEST|.*best_s=\([^ ]*\).*/\1/p')
145- fps=$(echo "$res" | sed -n 's/^BEST|.*fps=\([^ ]*\).*/\1/p')
146- x=$(echo "$res" | sed -n 's/^BEST|.*x_realtime=\([^ ]*\).*/\1/p')
147- kbps=$(echo "$res" | sed -n 's/^BEST|.*kbps=\([^ ]*\).*/\1/p')
148- 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"
149- # ffmpeg decodes our stream: exit status, picture count, and PSNR against the source.
150- local ff_out nb psnr
151- 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)
152- nb=$(stat -c%s "$OUT/enc-$label.ref.yuv")
153- nb=$((nb / FB8))
154- 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)
155- echo "CHECK|ec-hw encode $label|ffmpeg decode: $ff_out, pictures=$nb of 1800, PSNR vs source avg ${psnr} dB"
156- rm -f "$OUT/enc-$label.ref.yuv"
157-}
158-enc_row h264-high h264 h264
159-enc_row hevc-main hevc hevc
160-
161-# Calibration for the PSNR above: ffmpeg's libx264 and libx265 at the same 8 Mb/s, GOP 30, the
162-# same source, decoded and measured the same way. Not a bench row; it says how much of the PSNR
163-# is the bitrate and the noisy source, not the hardware encoder.
164-for spec in "h264|libx264|h264" "hevc|libx265|hevc"; do
165- IFS='|' read -r lbl enc ffmt <<<"$spec"
166- "${FF[@]}" -f rawvideo -pix_fmt yuv420p -s ${W}x${H} -r 30 -i src_1080p30_8bit.yuv -c:v "$enc" \
167- -preset veryfast -b:v 8M -maxrate 8M -bufsize 1M -g 30 -f "$ffmt" "$OUT/cal-$lbl.bin"
168- 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)
169- echo "CHECK|calibration $enc 8 Mb/s GOP 30|PSNR vs source avg ${psnr} dB (same source, ffmpeg software encoder)"
170-done
171-
172-cd "$REPO"
173-echo "# done"
scripts/bench-benchp1-clips.shdeleted+0 -53
@@ -1,53 +0,0 @@
1-#!/usr/bin/env bash
2-# bench-benchp1-clips.sh: generate the inputs for the subtitle, Ogg and RIFF bench rows of
3-# lanes/bench.md ("lane benchp1"). Clips go to $BENCH_CLIPS (default ~/.cache/benchp1-clips),
4-# never into the repo. The .sup input is written by `ec-pgs --example benchp1 gen` (ffmpeg has no
5-# PGS encoder), so it is not made here.
6-set -euo pipefail
7-d=${BENCH_CLIPS:-$HOME/.cache/benchp1-clips}
8-mkdir -p "$d"
9-ff() { ffmpeg -nostdin -v error -y "$@"; }
10-
11-# ASS with many styled events: 20 styles, one event every 0.5 s for 2 h (14400 events).
12-# awk writes the script; ffmpeg converts it to SRT and WebVTT (14400 cues each) for ec-subs.
13-if [ ! -s "$d/styled-2h.ass" ]; then
14- awk 'BEGIN {
15- print "[Script Info]\nTitle: benchp1\nScriptType: v4.00+\nPlayResX: 1920\nPlayResY: 1080\nWrapStyle: 0\n"
16- print "[V4+ Styles]"
17- 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"
18- for (s = 0; s < 20; s++) {
19- 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)
20- }
21- print "\n[Events]"
22- print "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
23- for (i = 0; i < 14400; i++) {
24- t0 = i * 50; t1 = t0 + 120
25- s = i % 20
26- 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",
27- i % 3, int(t0 / 360000), int(t0 / 6000) % 60, int(t0 / 100) % 60, t0 % 100,
28- int(t1 / 360000), int(t1 / 6000) % 60, int(t1 / 100) % 60, t1 % 100,
29- s, 1 + (i % 9), 100 + (i * 7) % 1700, 80 + (i * 13) % 900,
30- (i * 31) % 256, (i * 17) % 256, (i * 5) % 256, i % 2, i, i, 90 + i % 30, (i % 60) - 30
31- }
32- }' > "$d/styled-2h.ass"
33-fi
34-[ -s "$d/styled-2h.srt" ] || ff -i "$d/styled-2h.ass" -c:s srt "$d/styled-2h.srt"
35-[ -s "$d/styled-2h.vtt" ] || ff -i "$d/styled-2h.ass" -c:s webvtt "$d/styled-2h.vtt"
36-
37-# Vorbis and Opus in Ogg, 10 min, stereo pink noise.
38-[ -s "$d/vorbis-10m.ogg" ] || ff -f lavfi -i "anoisesrc=d=600:c=pink:r=48000:a=0.2:seed=7" \
39- -ac 2 -c:a libvorbis -q:a 4 "$d/vorbis-10m.ogg"
40-[ -s "$d/opus-10m.ogg" ] || ff -f lavfi -i "anoisesrc=d=600:c=pink:r=48000:a=0.2:seed=7" \
41- -ac 2 -c:a libopus -b:a 128k "$d/opus-10m.ogg"
42-
43-# 24-bit 5.1 WAV, 10 min at 48 kHz: six independent pink-noise channels joined as 5.1.
44-inputs=()
45-for seed in 1 2 3 4 5 6; do
46- inputs+=(-f lavfi -i "anoisesrc=d=600:c=pink:r=48000:a=0.2:seed=$seed")
47-done
48-[ -s "$d/wav-51-24b-10m.wav" ] || ff "${inputs[@]}" -filter_complex \
49- "[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]" \
50- -map "[a]" -ar 48000 -c:a pcm_s24le -f wav "$d/wav-51-24b-10m.wav"
51-[ -s "$d/wav-51-24b-10m.s24le.md5" ] || ffmpeg -nostdin -v error -i "$d/wav-51-24b-10m.wav" -f s24le - \
52- | md5sum | cut -d' ' -f1 > "$d/wav-51-24b-10m.s24le.md5"
53-echo "clips in $d"
scripts/bench-benchrest.shdeleted+0 -246
@@ -1,246 +0,0 @@
1-#!/usr/bin/env bash
2-# bench-benchrest.sh: the still-image, Matroska, FLAC and zlib rows of lanes/bench.md
3-# ("lane benchrest", DONE.md gate G6).
4-#
5-# Local machine only (DONE.md D7 exception): build with -j6 into CARGO_TARGET_DIR and run each row
6-# as the best of 5 inside the bench binary. Before each row, wait up to 40 minutes for the 1-minute
7-# load to be at most 2; the load at the start of the row is printed. Inputs are generated here with
8-# the local ffmpeg and python (never personal media) into $BENCH_INPUTS, which lives in the tmp dir
9-# $TMPDIR (default ~/.cache/tmp-benchrest), outside the repo.
10-#
11-# Output: one "ROW|..." line per bench row, then "CHECK|..." lines with the self-check. The
12-# lanes/bench.md "lane benchrest" table is written from these lines.
13-#
14-# usage: scripts/bench-benchrest.sh [--no-inputs] [--no-build]
15-set -euo pipefail
16-
17-cd "$(dirname "$0")/.."
18-REPO="$(pwd)"
19-export RUSTC_WRAPPER=
20-export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchrest}"
21-export TMPDIR="${TMPDIR:-$HOME/.cache/tmp-benchrest}"
22-IN="${BENCH_INPUTS:-$TMPDIR/inputs}"
23-BIN="$TMPDIR/bin"
24-OUT="$IN/out"
25-FF=(ffmpeg -hide_banner -loglevel error -y)
26-DO_INPUTS=1
27-DO_BUILD=1
28-for a in "$@"; do
29- case "$a" in
30- --no-inputs) DO_INPUTS=0 ;;
31- --no-build) DO_BUILD=0 ;;
32- *) echo "unknown option: $a" >&2; exit 2 ;;
33- esac
34-done
35-mkdir -p "$IN" "$BIN" "$OUT" "$TMPDIR"
36-COMMIT="$(git -C "$REPO" rev-parse --short HEAD)"
37-echo "# host=local cores=$(nproc) commit=$COMMIT ffmpeg=$(ffmpeg -version | head -1 | awk '{print $3}') python=$(python3 -c 'import numpy; print("numpy " + numpy.__version__)')"
38-
39-# ---- 1. inputs ----------------------------------------------------------------------------------
40-if [ "$DO_INPUTS" = 1 ]; then
41- cd "$IN"
42- # Still images: one testsrc2 frame at 1920x1080.
43- [ -f png_rgb.png ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=1" -frames:v 1 -pix_fmt rgb24 png_rgb.png
44- [ -f ref_png_rgb.rgb ] || "${FF[@]}" -i png_rgb.png -f rawvideo -pix_fmt rgb24 ref_png_rgb.rgb
45- [ -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
46- [ -f ref_jpg.rgb ] || "${FF[@]}" -i jpg_420_q2.jpg -f rawvideo -pix_fmt rgb24 ref_jpg.rgb
47- [ -f src_rgba.raw ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=1" -frames:v 1 -pix_fmt rgba -f rawvideo src_rgba.raw
48- # Matroska: H.264 1080p30 + AAC 128k stereo, 60 s.
49- [ -f h264_aac_1080p30.mkv ] || "${FF[@]}" -f lavfi -i "testsrc2=size=1920x1080:rate=30:duration=60" \
50- -f lavfi -i "sine=frequency=220:sample_rate=48000:duration=60" -ac 2 \
51- -c:v libx264 -preset veryfast -b:v 4M -pix_fmt yuv420p -c:a aac -b:a 128k -f matroska h264_aac_1080p30.mkv
52- [ -f ref_mkv.v.bin ] || "${FF[@]}" -i h264_aac_1080p30.mkv -map 0:v:0 -c copy -f data ref_mkv.v.bin
53- [ -f ref_mkv.a.bin ] || "${FF[@]}" -i h264_aac_1080p30.mkv -map 0:a:0 -c copy -f data ref_mkv.a.bin
54- # FLAC: 60 s stereo 16-bit 44.1 kHz (tones plus pink noise, as benchaudio) and 60 s 5.1 24-bit 48 kHz.
55- [ -f st16_44k.flac ] || "${FF[@]}" \
56- -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" \
57- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=44100:r=44100:seed=1" \
58- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=44100:r=44100:seed=2" \
59- -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]" \
60- -map "[o]" -c:a flac -sample_fmt s16 st16_44k.flac
61- [ -f ref_st16.pcm ] || "${FF[@]}" -i st16_44k.flac -f s16le ref_st16.pcm
62- [ -f m51_48k_24.flac ] || "${FF[@]}" \
63- -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" \
64- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=3" \
65- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=4" \
66- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=5" \
67- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=6" \
68- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=7" \
69- -f lavfi -i "anoisesrc=d=60:c=pink:a=0.03:s=48000:r=48000:seed=8" \
70- -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]" \
71- -map "[o]" -c:a flac -sample_fmt s32 -bits_per_raw_sample 24 m51_48k_24.flac
72- [ -f ref_m51.s32 ] || "${FF[@]}" -i m51_48k_24.flac -f s32le ref_m51.s32
73- [ -f ref_m51.s24 ] || "${FF[@]}" -i m51_48k_24.flac -f s24le ref_m51.s24
74- # zlib: 64 MiB of mixed text and PCM (python zlib level 6), and 20k blocks of 3 KiB (python zlib
75- # level 6 each, length-prefixed). The refs are python's md5 of zlib.decompress.
76- [ -f big_mixed.zlib ] || python3 -I - "$IN" <<'PY'
77-import hashlib, random, string, struct, sys, zlib
78-import numpy as np
79-d = sys.argv[1]
80-rng = random.Random(1)
81-words = [''.join(rng.choices(string.ascii_lowercase, k=rng.randint(2, 9))) for _ in range(4000)]
82-def text(n):
83- return ' '.join(rng.choices(words, k=n // 5)).encode()[:n]
84-def pcm(n):
85- gen = np.random.default_rng(7)
86- t = np.arange(n // 4)
87- x = 6000 * np.sin(2 * np.pi * 440 * t / 44100) + 2500 * np.sin(2 * np.pi * 659.3 * t / 44100) \
88- + gen.normal(0, 300, t.size)
89- return np.clip(x, -32768, 32767).astype('<i2').repeat(2).tobytes()[:n]
90-big = text(32 << 20) + pcm(32 << 20)
91-comp = zlib.compress(big, 6)
92-open(f"{d}/big_mixed.zlib", "wb").write(comp)
93-open(f"{d}/ref_big.md5", "w").write(hashlib.md5(zlib.decompress(comp)).hexdigest() + "\n")
94-del big
95-blocks = open(f"{d}/blocks_3k.bin", "wb")
96-digest = hashlib.md5()
97-for _ in range(20000):
98- c = zlib.compress(text(3072), 6)
99- blocks.write(struct.pack('<I', len(c)) + c)
100- digest.update(zlib.decompress(c))
101-blocks.close()
102-open(f"{d}/ref_blocks.md5", "w").write(digest.hexdigest() + "\n")
103-PY
104- cd "$REPO"
105-fi
106-
107-# ---- 2. build the four examples (one binary per crate, copied before the next build) ------------
108-crates=(ec-image ec-matroska ec-flac ec-inflate)
109-if [ "$DO_BUILD" = 1 ]; then
110- for c in "${crates[@]}"; do
111- cargo build --release -j6 -p "$c" --example bench
112- cp "$CARGO_TARGET_DIR/release/examples/bench" "$BIN/$c-bench"
113- done
114-fi
115-
116-# ---- 3. helpers ----------------------------------------------------------------------------------
117-wait_load() {
118- # Start a row when the 1-minute load is at most 2, or after 40 minutes at most (the row then
119- # records the load it actually ran at).
120- local waited=0 l
121- while :; do
122- l=$(cut -d' ' -f1 /proc/loadavg)
123- if awk -v l="$l" 'BEGIN{exit !(l <= 2)}' || [ "$waited" -ge 2400 ]; then echo "$l"; return; fi
124- sleep 5
125- waited=$((waited + 5))
126- done
127-}
128-field() { echo "$1" | tr ' ' '\n' | sed -n "s/^$2=//p"; }
129-md5_of() { md5sum "$1" | cut -c1-32; }
130-# psnr CHECK: max abs diff, mean abs diff and PSNR of two 8-bit RGB raw files of the same size.
131-psnr() {
132- python3 -I - "$1" "$2" "$3" "$4" <<'PY'
133-import sys
134-import numpy as np
135-a = np.fromfile(sys.argv[1], np.uint8).astype(np.int32)
136-b = np.fromfile(sys.argv[2], np.uint8).astype(np.int32)
137-w, h = int(sys.argv[3]), int(sys.argv[4])
138-assert a.size == b.size == w * h * 3, (a.size, b.size)
139-d = np.abs(a - b)
140-mse = float(np.mean((a - b) ** 2))
141-psnr = 10 * np.log10(255 * 255 / mse) if mse > 0 else float("inf")
142-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}%")
143-PY
144-}
145-
146-# ---- 4. rows -------------------------------------------------------------------------------------
147-cd "$IN"
148-B="$BIN"
149-FFV="$(ffmpeg -version | head -1 | awk '{print $3}')"
150-
151-# ec-image: PNG decode, 1920x1080 RGB8.
152-l=$(wait_load)
153-res=$("$B/ec-image-bench" png-dec png_rgb.png "$OUT/png_rgb.rgb" 5)
154-best=$(field "$res" best_decode_s)
155-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"
156-if [ "$(md5_of ref_png_rgb.rgb)" = "$(md5_of "$OUT/png_rgb.rgb")" ]; then
157- 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)"
158-else
159- echo "CHECK|ec-image png decode|md5 MISMATCH vs ffmpeg: ours $(md5_of "$OUT/png_rgb.rgb") ffmpeg $(md5_of ref_png_rgb.rgb)"
160-fi
161-
162-# ec-image: JPEG decode, 1920x1080 4:2:0 q2.
163-l=$(wait_load)
164-res=$("$B/ec-image-bench" jpeg-dec jpg_420_q2.jpg "$OUT/jpg.rgb" 5)
165-best=$(field "$res" best_decode_s)
166-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"
167-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)"
168-
169-# ec-image: PNG encode of the 1920x1080 RGBA frame, decoded back by ffmpeg.
170-l=$(wait_load)
171-res=$("$B/ec-image-bench" png-enc src_rgba.raw 1920 1080 "$OUT/enc.png" 5)
172-best=$(field "$res" best_encode_s)
173-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"
174-"${FF[@]}" -i "$OUT/enc.png" -f rawvideo -pix_fmt rgba "$OUT/enc-ffdec.rgba"
175-if [ "$(md5_of src_rgba.raw)" = "$(md5_of "$OUT/enc-ffdec.rgba")" ]; then
176- echo "CHECK|ec-image png encode|ffmpeg decode of our PNG md5 $(md5_of src_rgba.raw | cut -c1-8) = source RGBA (bit-exact)"
177-else
178- 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)"
179-fi
180-
181-# ec-matroska: demux, H.264 1080p30 + AAC 128k stereo, 60 s.
182-file_bytes=$(stat -c%s h264_aac_1080p30.mkv)
183-l=$(wait_load)
184-res=$("$B/ec-matroska-bench" demux h264_aac_1080p30.mkv "$OUT/mkv" 5)
185-pk=$(field "$res" packets)
186-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"
187-v_ok=$([ "$(md5_of "$OUT/mkv.s0.bin")" = "$(md5_of ref_mkv.v.bin)" ] && echo match || echo MISMATCH)
188-a_ok=$([ "$(md5_of "$OUT/mkv.s1.bin")" = "$(md5_of ref_mkv.a.bin)" ] && echo match || echo MISMATCH)
189-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) ))
190-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"
191-
192-# ec-flac: decode, 16-bit stereo 44.1k 60 s and 24-bit 5.1 48k 60 s.
193-for spec in "st16_44k.flac|ref_st16.pcm|FLAC 16-bit stereo 44.1 kHz 60 s (ffmpeg)|2|16|44100" \
194- "m51_48k_24.flac|ref_m51.s32|FLAC 24-bit 5.1 48 kHz 60 s (ffmpeg, s32 container)|6|24|48000"; do
195- IFS='|' read -r in ref content _ _ _ <<<"$spec"
196- l=$(wait_load)
197- res=$("$B/ec-flac-bench" dec "$in" "$OUT/flac-$in.pcm" 5)
198- best=$(field "$res" best_decode_s); xrt=$(field "$res" x_realtime)
199- echo "ROW|ec-flac|decode|$content|$best|${xrt}x realtime|load1=$l"
200- if [ "$(md5_of "$ref")" = "$(md5_of "$OUT/flac-$in.pcm")" ]; then
201- echo "CHECK|ec-flac decode $in|md5 $(md5_of "$ref" | cut -c1-8) = ffmpeg PCM ($(stat -c%s "$ref") bytes, bit-exact)"
202- else
203- echo "CHECK|ec-flac decode $in|md5 MISMATCH vs ffmpeg: ours $(md5_of "$OUT/flac-$in.pcm") ffmpeg $(md5_of "$ref")"
204- fi
205-done
206-
207-# ec-flac: encode at the export level (EncoderConfig::default()), then ffmpeg decode of our output.
208-for spec in "ref_st16.pcm|2|16|44100|s16le|FLAC encode 16-bit stereo 44.1 kHz 60 s (default level)" \
209- "ref_m51.s24|6|24|48000|s24le|FLAC encode 24-bit 5.1 48 kHz 60 s (default level)"; do
210- IFS='|' read -r src ch bits rate fmt content <<<"$spec"
211- l=$(wait_load)
212- res=$("$B/ec-flac-bench" enc "$src" "$ch" "$bits" "$rate" "$OUT/enc-$bits.flac" 5)
213- best=$(field "$res" best_encode_s); xrt=$(field "$res" x_realtime)
214- echo "ROW|ec-flac|encode|$content|$best|${xrt}x realtime, $(field "$res" kbps) kb/s|load1=$l"
215- "${FF[@]}" -i "$OUT/enc-$bits.flac" -f "$fmt" "$OUT/enc-$bits-ffdec.pcm"
216- if [ "$(md5_of "$src")" = "$(md5_of "$OUT/enc-$bits-ffdec.pcm")" ]; then
217- echo "CHECK|ec-flac encode $bits-bit|ffmpeg decode of our FLAC md5 $(md5_of "$src" | cut -c1-8) = source PCM (bit-exact)"
218- else
219- 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")"
220- fi
221-done
222-
223-# ec-inflate: one zlib stream, 64 MiB mixed text and PCM.
224-l=$(wait_load)
225-res=$("$B/ec-inflate-bench" zlib big_mixed.zlib "$OUT/big.bin" 5)
226-best=$(field "$res" best_inflate_s)
227-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)"
228-if [ "$(md5_of "$OUT/big.bin")" = "$(cut -d' ' -f1 ref_big.md5)" ]; then
229- echo "CHECK|ec-inflate zlib|md5 $(cut -c1-8 ref_big.md5) = python zlib.decompress ($(field "$res" out_bytes) bytes)"
230-else
231- echo "CHECK|ec-inflate zlib|md5 MISMATCH vs python: ours $(md5_of "$OUT/big.bin") python $(cut -d' ' -f1 ref_big.md5)"
232-fi
233-rm -f "$OUT/big.bin"
234-
235-# ec-inflate: 20k length-prefixed zlib streams of 3 KiB text each (subtitle-sized packets).
236-l=$(wait_load)
237-res=$("$B/ec-inflate-bench" blocks blocks_3k.bin "$OUT/blocks.bin" 5)
238-best=$(field "$res" best_inflate_s)
239-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"
240-if [ "$(md5_of "$OUT/blocks.bin")" = "$(cut -d' ' -f1 ref_blocks.md5)" ]; then
241- echo "CHECK|ec-inflate blocks|md5 $(cut -c1-8 ref_blocks.md5) = python zlib.decompress per block ($(field "$res" out_bytes) bytes)"
242-else
243- echo "CHECK|ec-inflate blocks|md5 MISMATCH vs python: ours $(md5_of "$OUT/blocks.bin") python $(cut -d' ' -f1 ref_blocks.md5)"
244-fi
245-rm -f "$OUT/blocks.bin"
246-echo "# ffmpeg $FFV"
scripts/bench-rows-clips.shdeleted+0 -42
@@ -1,42 +0,0 @@
1-#!/usr/bin/env bash
2-# bench-rows-clips.sh: generate the ffmpeg clips used by scripts/bench-rows.sh.
3-# Clips go to $BENCH_CLIPS (default ~/.cache/benchrows-clips), never into the repo.
4-# The h264 input is the personal 1080p30 clip that ec-bench's real_video() picks first
5-# (first h264 mp4 in ~/Videos or ~/Downloads, sorted by path); it is only read, never copied.
6-set -euo pipefail
7-d=${BENCH_CLIPS:-$HOME/.cache/benchrows-clips}
8-h264_src=${H264_SRC:-$HOME/Downloads/reelk.mp4}
9-mkdir -p "$d"
10-ff() { ffmpeg -nostdin -v error -y "$@"; }
11-
12-# VP8 1080p30, libvpx, 10 s, 4 Mb/s, realtime deadline.
13-[ -s "$d/vp8-1080p30.ivf" ] || ff -f lavfi -i testsrc2=size=1920x1080:rate=30 -t 10 \
14- -c:v libvpx -b:v 4M -deadline realtime -cpu-used 8 -pix_fmt yuv420p "$d/vp8-1080p30.ivf"
15-
16-# VP9 profile 0 1080p30, libvpx-vp9, 10 s, 4 tile columns (threads have work to split).
17-[ -s "$d/vp9-1080p30-tile4.ivf" ] || ff -f lavfi -i testsrc2=size=1920x1080:rate=30 -t 10 \
18- -c:v libvpx-vp9 -tile-columns 2 -row-mt 1 -b:v 4M -deadline realtime -cpu-used 8 \
19- -pix_fmt yuv420p "$d/vp9-1080p30-tile4.ivf"
20-
21-# AC-3 5.1 at 448 kb/s, 60 s: six independent pink-noise channels, one per 5.1 speaker
22-# (a mono source upmixed would fill only the centre channel and make the parity test vacuous).
23-ac3_in=()
24-for seed in 1 2 3 4 5 6; do
25- ac3_in+=(-f lavfi -i "anoisesrc=d=60:c=pink:r=48000:a=0.2:seed=$seed")
26-done
27-[ -s "$d/ac3-5.1-448k.ac3" ] || ff "${ac3_in[@]}" -filter_complex \
28- "[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]" \
29- -map "[a]" -ar 48000 -c:a ac3 -b:a 448k -f ac3 "$d/ac3-5.1-448k.ac3"
30-
31-# H264 Annex-B, first 10 s of the h264 input, stream copy (same extraction as ec-bench).
32-[ -s "$d/h264-1080p30-10s.264" ] || ff -t 10 -i "$h264_src" -an -c:v copy \
33- -bsf:v h264_mp4toannexb -f h264 "$d/h264-1080p30-10s.264"
34-
35-# ffmpeg reference outputs (raw, the decoded samples the crates must match).
36-[ -s "$d/vp8-1080p30.yuv.md5" ] || ffmpeg -nostdin -v error -i "$d/vp8-1080p30.ivf" \
37- -f rawvideo -pix_fmt yuv420p - | md5sum | cut -d' ' -f1 > "$d/vp8-1080p30.yuv.md5"
38-[ -s "$d/vp9-1080p30-tile4.yuv.md5" ] || ffmpeg -nostdin -v error -i "$d/vp9-1080p30-tile4.ivf" \
39- -f rawvideo -pix_fmt yuv420p - | md5sum | cut -d' ' -f1 > "$d/vp9-1080p30-tile4.yuv.md5"
40-[ -s "$d/ac3-5.1-448k.ref.f32" ] || ffmpeg -nostdin -v error -i "$d/ac3-5.1-448k.ac3" \
41- -f f32le -acodec pcm_f32le -ac 6 "$d/ac3-5.1-448k.ref.f32"
42-ls -l "$d"
scripts/bench-rows-parity.pydeleted+0 -22
@@ -1,22 +0,0 @@
1-#!/usr/bin/env python3
2-"""bench-rows-parity.py REF.f32 OUT.f32 CHANNELS: per-channel correlation of two
3-interleaved float32 streams (ffmpeg reference vs the crate's output).
4-Prints one line per channel and the sample counts. Run as: python3 -I <this file> ..."""
5-import sys
6-import numpy as np
7-
8-ref = np.fromfile(sys.argv[1], dtype="<f4")
9-out = np.fromfile(sys.argv[2], dtype="<f4")
10-ch = int(sys.argv[3])
11-n = min(len(ref), len(out)) // ch * ch
12-print(f"ref_samples={len(ref) // ch} out_samples={len(out) // ch} compared={n // ch}")
13-r = ref[:n].reshape(-1, ch)
14-o = out[:n].reshape(-1, ch)
15-worst = 1.0
16-for c in range(ch):
17- a, b = r[:, c].astype(np.float64), o[:, c].astype(np.float64)
18- corr = np.corrcoef(a, b)[0, 1] if a.std() > 0 and b.std() > 0 else float("nan")
19- err = np.max(np.abs(a - b))
20- worst = min(worst, corr)
21- print(f"ch{c} corr={corr:.6f} max_abs_err={err:.6f}")
22-print(f"min_corr={worst:.6f} tolerance=0.999 {'PASS' if worst >= 0.999 else 'FAIL'}")
scripts/bench-rows-vp8.rsdeleted+0 -60
@@ -1,60 +0,0 @@
1-//! VP8 decode bench harness for scripts/bench-rows.sh. The script copies this file into
2-//! crates/ec-vp8/examples/ for the run and deletes the copy afterwards.
3-//!
4-//! usage: vp8_ivf <file.ivf> [reps] [raw-out|-]
5-//! Times `reps` full decodes with a fresh decoder each (best wall time, output not
6-//! written). With a third argument, one more untimed pass writes the visible planes as
7-//! raw yuv420p to that path (`/dev/stdout` for a pipe into md5sum).
8-use ec_vp8::decode::Decoder;
9-use std::time::Instant;
10-
11-fn main() {
12- let args: Vec<String> = std::env::args().collect();
13- let bytes = std::fs::read(&args[1]).expect("read ivf");
14- let reps: usize = args.get(2).map_or(5, |s| s.parse().expect("reps"));
15- let mut frames: Vec<&[u8]> = Vec::new();
16- let mut pos = 32;
17- while pos + 12 <= bytes.len() {
18- let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
19- frames.push(&bytes[pos + 12..pos + 12 + sz]);
20- pos += 12 + sz;
21- }
22- let mut best = f64::MAX;
23- let mut shown = 0usize;
24- for _ in 0..reps {
25- let mut dec = Decoder::new();
26- let t = Instant::now();
27- shown = 0;
28- for f in &frames {
29- if dec.decode(f).expect("vp8 decode").is_some() {
30- shown += 1;
31- }
32- }
33- best = best.min(t.elapsed().as_secs_f64());
34- }
35- println!(
36- "frames={} shown={} best_secs={best:.3} fps={:.2}",
37- frames.len(),
38- shown,
39- shown as f64 / best
40- );
41- if let Some(path) = args.get(3) {
42- let mut out = Vec::new();
43- let mut dec = Decoder::new();
44- for f in &frames {
45- if let Some(pic) = dec.decode(f).expect("vp8 decode") {
46- let (w, h) = (usize::from(pic.width), usize::from(pic.height));
47- let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
48- for r in 0..h {
49- out.extend_from_slice(&pic.y[r * pic.stride..r * pic.stride + w]);
50- }
51- for plane in [&pic.u, &pic.v] {
52- for r in 0..ch {
53- out.extend_from_slice(&plane[r * pic.uv_stride..r * pic.uv_stride + cw]);
54- }
55- }
56- }
57- }
58- std::fs::write(path, out).expect("write raw");
59- }
60-}
scripts/bench-rows.shdeleted+0 -128
@@ -1,128 +0,0 @@
1-#!/usr/bin/env bash
2-# bench-rows.sh: local best-of-5 decode rows (DONE.md D7: speed is measured on the local
3-# 12-core machine). Rows: ec-vp8 decode, ec-vp9 decode at 1/2/4/6 tile threads, ec-ac3 5.1
4-# 448k decode with parity, ec-h264 decode at 1/2/4/6 cores (the decoder runs 1 thread).
5-# Every row starts only when the 1-minute load is below 3; otherwise it waits in 290 s
6-# steps for at most 1 h (12 steps). Clips come from scripts/bench-rows-clips.sh.
7-# Usage: scripts/bench-rows.sh (prints markdown rows; also saved under $BENCH_CLIPS)
8-set -euo pipefail
9-root=$(cd "$(dirname "$0")/.." && pwd)
10-clips=${BENCH_CLIPS:-$HOME/.cache/benchrows-clips}
11-export CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-$HOME/.cache/tgt-benchrows}
12-export TMPDIR=${TMPDIR:-$HOME/.cache/tmp-benchrows}
13-mkdir -p "$TMPDIR"
14-rel=$CARGO_TARGET_DIR/release
15-today=$(date +%F)
16-res="$clips/bench-rows-$today.md"
17-: > "$res"
18-
19-# Prints the 1-minute load once it is below 3. Returns 1 after 1 h of waiting.
20-gate() {
21- local steps=0 l
22- while :; do
23- l=$(cut -d' ' -f1 /proc/loadavg)
24- if awk -v l="$l" 'BEGIN { exit !(l < 3) }'; then echo "$l"; return 0; fi
25- if [ "$steps" -ge 12 ]; then echo "$l"; return 1; fi
26- sleep 290
27- steps=$((steps + 1))
28- done
29-}
30-
31-# emit <crate> <clip> <threads> <load> <fps> <realtime> <check>
32-emit() {
33- printf '| %s | %s | %s | local 12-core | %s | %s | %s | %s | %s |\n' \
34- "$today" "$1" "$2" "$3" "$4" "$5" "$6" "$7" | tee -a "$res"
35-}
36-
37-# ---- build (outside the gate; nothing is timed here) ----
38-cd "$root"
39-cargo build --release -q -p ec-vp9 --example decode_ivf
40-cargo build --release -q -p ec-ac3 --example ac3dec
41-cargo build --release -q --manifest-path tools/ec-bench/Cargo.toml
42-cp scripts/bench-rows-vp8.rs crates/ec-vp8/examples/vp8_ivf.rs
43-trap 'rm -f "$root/crates/ec-vp8/examples/vp8_ivf.rs"' EXIT
44-cargo build --release -q -p ec-vp8 --example vp8_ivf
45-
46-echo "| date | crate | clip | host | threads | load 1m at start | fps (best of 5) | realtime x | check |"
47-echo "|---|---|---|---|---|---|---|---|---|"
48-
49-# ---- ec-vp8 decode, 1080p30 libvpx clip, 1 thread (the decoder has no thread knob) ----
50-vp8=$clips/vp8-1080p30.ivf
51-if load=$(gate); then
52- line=$("$rel/examples/vp8_ivf" "$vp8" 5)
53- fps=$(sed -n 's/.*fps=\([0-9.]*\).*/\1/p' <<<"$line")
54- raw=$TMPDIR/vp8.yuv
55- "$rel/examples/vp8_ivf" "$vp8" 1 "$raw" >/dev/null
56- got=$(md5sum "$raw" | cut -d' ' -f1); rm -f "$raw"
57- want=$(cat "$clips/vp8-1080p30.yuv.md5")
58- check="md5 $([ "$got" = "$want" ] && echo "= ffmpeg" || echo "!= ffmpeg ($got)")"
59- emit ec-vp8 "1080p30 libvpx 10 s, 4 Mb/s" 1 "$load" "$fps" "$(awk -v f="$fps" 'BEGIN{printf "%.2fx", f/30}')" "$check"
60-else
61- emit ec-vp8 "1080p30 libvpx 10 s" 1 "$load" - - "load gate timed out"
62-fi
63-
64-# ---- ec-vp9 decode, 1080p30 profile 0, 4 tile columns, threads 1/2/4/6 ----
65-vp9=$clips/vp9-1080p30-tile4.ivf
66-want=$(cat "$clips/vp9-1080p30-tile4.yuv.md5")
67-for t in 1 2 4 6; do
68- if load=$(gate); then
69- best=0
70- for _ in 1 2 3 4 5; do
71- f=$("$rel/examples/decode_ivf" "$vp9" "$t" | sed -n 's/.*decode_fps=\([0-9.]*\).*/\1/p')
72- best=$(awk -v a="$best" -v b="$f" 'BEGIN{print (b > a ? b : a)}')
73- done
74- raw=$TMPDIR/vp9.yuv
75- EC_RAW_OUT=$raw "$rel/examples/decode_ivf" "$vp9" "$t" >/dev/null
76- got=$(md5sum "$raw" | cut -d' ' -f1); rm -f "$raw"
77- check="md5 $([ "$got" = "$want" ] && echo "= ffmpeg" || echo "!= ffmpeg ($got)")"
78- emit ec-vp9 "1080p30 profile 0 libvpx-vp9 10 s, 4 tile cols" "$t" "$load" "$best" \
79- "$(awk -v f="$best" 'BEGIN{printf "%.2fx", f/30}')" "$check"
80- else
81- emit ec-vp9 "1080p30 profile 0 tile4" "$t" "$load" - - "load gate timed out"
82- fi
83-done
84-
85-# ---- ec-ac3 decode, AC-3 5.1 448 kb/s, 60 s; speed to /dev/null, parity to a file ----
86-ac3=$clips/ac3-5.1-448k.ac3
87-if load=$(gate); then
88- best=0
89- for _ in 1 2 3 4 5; do
90- rt=$("$rel/examples/ac3dec" "$ac3" /dev/null | awk -F'\t' '/^realtime/{print $2}')
91- best=$(awk -v a="$best" -v b="$rt" 'BEGIN{print (b > a ? b : a)}')
92- done
93- out=$TMPDIR/ac3.f32
94- errs=$("$rel/examples/ac3dec" "$ac3" "$out" | awk -F'\t' '/^errors/{print $2}')
95- par=$(python3 -I "$root/scripts/bench-rows-parity.py" "$clips/ac3-5.1-448k.ref.f32" "$out" 6 | tail -1)
96- rm -f "$out"
97- emit ec-ac3 "AC-3 5.1 448 kb/s 60 s (5.1 layout)" 1 "$load" "-" "${best}x" \
98- "decode errors $errs; parity: $par"
99-else
100- emit ec-ac3 "AC-3 5.1 448 kb/s" 1 "$load" - - "load gate timed out"
101-fi
102-
103-# ---- ec-h264 decode: the bench.log:145 row, from tools/ec-bench itself, pinned to 1/2/4/6
104-# cores. The decoder has no thread knob (ec-h264 spawns threads only in enc/), so the
105-# core count is the only parallelism available; 5 full ec-bench runs per core count. ----
106-bench=$CARGO_TARGET_DIR/release/ec-bench
107-for n in 1 2 4 6; do
108- best=""
109- loads=""
110- for _ in 1 2 3 4 5; do
111- if load=$(gate); then
112- line=$(taskset -c "0-$((n - 1))" "$bench" | grep '^| ec-h264 | decode')
113- ms=$(awk -F'|' '{gsub(/ /,"",$6); print $6}' <<<"$line")
114- frames=$(awk -F'|' '{print $4}' <<<"$line" | sed -n 's/.*, \([0-9]*\) frames.*/\1/p')
115- loads="$loads $load"
116- if [ -z "$best" ] || awk -v a="$ms" -v b="$best" 'BEGIN{exit !(a < b)}'; then
117- best=$ms; bestframes=$frames
118- fi
119- else
120- loads="$loads gate-timeout"
121- fi
122- done
123- fps=$(awk -v f="$bestframes" -v m="$best" 'BEGIN{printf "%.2f", f / (m / 1000)}')
124- emit ec-h264 "1080p30 film 10 s, ec-bench row (wall best $best ms, $bestframes frames)" 1 \
125- "$(awk '{print $1}' <<<"${loads# }")" "$fps" "$(awk -v f="$fps" 'BEGIN{printf "%.2fx", f/30}')" \
126- "cores pinned $n, decoder threads 1; loads of 5 runs:$loads"
127-done
128-echo "saved: $res" >&2
scripts/bench_hevc_enc.shdeleted+0 -20
@@ -1,20 +0,0 @@
1-#!/usr/bin/env bash
2-# bench_hevc_enc.sh: 1080p30 synthetic encode bench for ec-h265 (8 and 10 bit), prints fps and sha1.
3-# Run on a server via scripts/remote-run.sh. Env: N (frames, 30), RUNS (3), THREADS (4).
4-set -e
5-N=${N:-30}; RUNS=${RUNS:-3}; T=${THREADS:-4}
6-D=$HOME/.cache/hevc10simd2-bench; mkdir -p "$D"
7-[ -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
8-[ -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
9-cargo build --release -p ec-h265 --example hevc_gop 2>&1 | tail -1
10-BIN=${CARGO_TARGET_DIR:-target}/release/examples/hevc_gop
11-echo "load: $(cat /proc/loadavg)"
12-for bd in 8 10; do
13- for r in $(seq $RUNS); do
14- s=$(date +%s.%N)
15- 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
16- e=$(date +%s.%N)
17- 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)"
18- done
19-done
20-echo "load after: $(cat /proc/loadavg)"
scripts/changed-crates.shdeleted+0 -48
@@ -1,48 +0,0 @@
1-#!/usr/bin/env bash
2-# Print `-p <crate>` lines for the workspace crates affected by a change, for use as
3-# cargo test $(scripts/changed-crates.sh)
4-#
5-# Changed files = `git diff <base>...HEAD` + uncommitted (staged/unstaged) + untracked.
6-# Each changed file maps to the workspace package whose directory contains it. Those
7-# packages are then expanded to all their reverse dependencies inside the workspace
8-# (path dependencies only). A change to a root file (Cargo.toml, Cargo.lock, .config/,
9-# .cargo/, rust-toolchain*) selects every workspace crate.
10-# ec-hw and ec-va are dropped unless they changed themselves (GPU; no hardware encode).
11-#
12-# Usage: scripts/changed-crates.sh [BASE_REF] (BASE_REF defaults to main)
13-set -euo pipefail
14-
15-base="${1:-main}"
16-root="$(git rev-parse --show-toplevel)"
17-cd "$root"
18-
19-meta_file="$(mktemp)"
20-trap 'rm -f "$meta_file"' EXIT
21-cargo metadata --format-version 1 --no-deps > "$meta_file"
22-
23-changed="$({
24- git diff --name-only "$base...HEAD"
25- git diff --name-only HEAD
26- git ls-files --others --exclude-standard
27-} | sort -u | jq -R -s 'split("\n") | map(select(length > 0))')"
28-
29-jq -r --argjson files "$changed" '
30- .workspace_root as $wr
31- | [ .packages[] | select(.source == null)
32- | { name,
33- dir: (.manifest_path | sub("/Cargo.toml$"; "") | ltrimstr($wr + "/")),
34- deps: [ .dependencies[] | select(.path != null) | .name ] } ] as $pk
35- | ($files | any(test("^(Cargo\\.toml|Cargo\\.lock|rust-toolchain[^/]*|\\.config/.*|\\.cargo/.*)$"))) as $rootChanged
36- | [ $pk[] | select(.dir != "") as $p
37- | select([$files[] | select(startswith($p.dir + "/"))] | length > 0)
38- | .name ] | unique as $changedPkgs
39- | (if $rootChanged then [$pk[].name] else $changedPkgs end) as $seeds
40- | def closure($cur):
41- ([ $pk[] | select(any(.deps[]; . as $x | any($cur[]; . == $x))) | .name ] + $cur | unique) as $next
42- | if ($next | length) == ($cur | length) then $cur else closure($next) end;
43- closure($seeds)
44- | map(. as $n
45- | select((["ec-hw", "ec-va"] | any(. == $n) | not) or ($changedPkgs | any(. == $n))))
46- | sort[]
47- | "-p " + .
48-' "$meta_file"
scripts/cmp422-ffmpeg.pydeleted+0 -313
@@ -1,313 +0,0 @@
1-#!/usr/bin/env python3
2-"""ffmpeg pixel-oracle comparator for ec-av1 4:2:2 (and 4:2:0 / 4:4:4 controls).
3-
4-Discipline (oracle-comparator-liveness-control):
5-
6-1. Geometry is an EXPLICIT argument read from the SEQUENCE HEADER via ffprobe
7- (coded_width / coded_height / pix_fmt of the AV1 stream), never derived
8- from a file size. A raw frame whose byte length disagrees with the geometry
9- is a hard error.
10-2. Plane attribution is per FRAME, from that frame's own plane lengths, with a
11- monotone cursor -- never absolute thresholds from frame 0.
12-3. A wrong SAMPLE is one bps-wide unit. At 10 bit the comparator walks
13- 16-bit LE samples, so the top bits cannot hide.
14-4. A count over zero frames is a hard error (vacuous 0/0/0).
15-5. Decode-order (ours, EC_AV1_FINAL_DUMP) -> display-order (ffmpeg rawvideo)
16- mapping is derived by LUMA-IDENTITY content match under a strictly
17- increasing assignment, then re-verified per frame. Exactly one decode frame
18- must have no display partner: the hidden alt-ref picture.
19-"""
20-import json
21-import os
22-import re
23-import subprocess
24-import sys
25-
26-SS = {"420": (1, 1), "422": (1, 0), "444": (0, 0), "440": (0, 1)}
27-DEPTH_RE = re.compile(r"^yuv(\d{3})p(\d*)(?:le)?$")
28-
29-
30-def probe_geometry(obu):
31- """ffprobe reads the AV1 SEQUENCE HEADER: coded_width/coded_height and the
32- chroma format/depth it implies. Never the raw output's byte length."""
33- r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v",
34- "-show_entries", "stream=coded_width,coded_height,pix_fmt",
35- "-of", "csv=p=0", obu], capture_output=True, check=True)
36- parts = r.stdout.decode().strip().split(",")
37- mw, h, pix = parts[0], parts[1], parts[2]
38- m = DEPTH_RE.match(pix)
39- if not m:
40- raise SystemExit(f"{obu}: unsupported pix_fmt {pix!r} (need a planar yuv*p[le])")
41- ss = SS.get(m.group(1))
42- if ss is None:
43- raise SystemExit(f"{obu}: unknown chroma tag C{m.group(1)} in pix_fmt {pix!r}")
44- depth = int(m.group(2)) if m.group(2) else 8
45- return int(mw), int(h), ss[0], ss[1], depth, pix
46-
47-
48-def plane_spans(w, h, ss_x, ss_y, bps):
49- cw = -(-w // (1 << ss_x))
50- ch = -(-h // (1 << ss_y))
51- sizes = (w * h, cw * ch, cw * ch)
52- return sizes, sum(sizes) * bps
53-
54-
55-def frame_files(prefix):
56- out, i = [], 0
57- while os.path.isfile(f"{prefix}.f{i}"):
58- out.append(f"{prefix}.f{i}")
59- i += 1
60- return out
61-
62-
63-def ffmpeg_frames(obu, pix):
64- r = subprocess.run(["ffmpeg", "-v", "error", "-i", obu, "-f", "rawvideo",
65- "-pix_fmt", pix, "-"], capture_output=True)
66- if r.returncode != 0:
67- raise SystemExit(f"{obu}: ffmpeg refused: {r.stderr.decode()[-300:]}")
68- return r.stdout
69-
70-
71-def split(raw, sizes, fsz, cell):
72- if not raw:
73- raise SystemExit(f"{cell}: ffmpeg produced ZERO bytes -- a 0/0/0 here is vacuous")
74- if len(raw) % fsz:
75- raise SystemExit(f"{cell}: ffmpeg rawvideo is {len(raw)} B, not a whole "
76- f"multiple of the {fsz} B frame the geometry implies")
77- return [raw[i * fsz:(i + 1) * fsz] for i in range(len(raw) // fsz)]
78-
79-
80-def _matchings(cands, disp_n, cap=64, node_cap=4_000_000):
81- """Every way to assign each decode frame either a distinct display partner
82- or the hidden role, covering the display side exactly. Enumerated, not
83- guessed: a duplicated picture can make the assignment genuinely ambiguous,
84- and the caller then has to show the ambiguity does not change the answer.
85-
86- Two bounds, both learned the hard way: without the feasibility prune, an
87- instance whose candidate lists cannot cover the display side explores the
88- whole 2**frames tree before returning empty (that is what made three
89- 43-frame cells burn a 300 s cap with 15 minutes of user CPU and never
90- finish), and without a node cap a pathological instance would hang the
91- comparator instead of reporting."""
92- sols = []
93- nodes = 0
94-
95- def dfs(i, used, acc, hid):
96- nonlocal nodes
97- nodes += 1
98- if nodes > node_cap:
99- raise SystemExit(f"the decode->display assignment search exceeded {node_cap} nodes "
100- f"at frame {i} of {len(cands)} ({disp_n} display frames) -- this "
101- f"instance is not enumerable; report it rather than hang")
102- if len(sols) >= cap:
103- return
104- if disp_n - len(used) > len(cands) - i:
105- return # not enough decode frames left to cover the display side
106- if i == len(cands):
107- if len(used) == disp_n:
108- sols.append((dict(acc), list(hid)))
109- return
110- for di in cands[i]:
111- if di not in used:
112- used.add(di)
113- acc[i] = di
114- dfs(i + 1, used, acc, hid)
115- del acc[i]
116- used.discard(di)
117- hid.append(i)
118- dfs(i + 1, used, acc, hid)
119- hid.pop()
120-
121- dfs(0, set(), {}, [])
122- return sols
123-
124-
125-def map_decode_to_display(ours, disp, sizes, bps, cell):
126- """Identity of each decode-order frame is carried by its LUMA plane; full-frame
127- identity is preferred when it exists. Every assignment that covers the
128- display side is enumerated, so a duplicated picture shows up as an
129- explicit solution COUNT rather than a silent pick. Real altref streams
130- REORDER display against decode (measured: decode f2..f8 -> display
131- 7,3,1,2,5,4,6), so no monotonicity prior is applied -- an unjustified one
132- is exactly the class of silent mismatch this instrument exists to catch."""
133- luma = sizes[0] * bps
134- for use_full in (True, False):
135- cands = [[di for di, d in enumerate(disp)
136- if o[:luma] == d[:luma] and (o == d or not use_full)] for o in ours]
137- sols = _matchings(cands, len(disp))
138- if sols:
139- if min(len(h) for _, h in sols) > 4:
140- raise SystemExit(f"{cell}: {min(len(h) for _, h in sols)} decode frames have "
141- f"no luma-identical display partner -- LUMA itself "
142- f"diverges, so this is not a hidden-alt-ref count "
143- f"(class av1-frame-count-vs-pixel-divergence)")
144- return sols
145- raise SystemExit(f"{cell}: luma identity never covers the display side "
146- f"({len(ours)} decode frames, {len(disp)} display frames) "
147- f"-- the frame-count or per-frame identity claim is wrong")
148-
149-
150-
151-def compare(cell, ours_prefix, disp, w, h, ss_x, ss_y, depth, want_hidden=None):
152- bps = 1 if depth <= 8 else 2
153- sizes, fsz = plane_spans(w, h, ss_x, ss_y, bps)
154- ours = [open(p, "rb").read() for p in frame_files(ours_prefix)]
155- if not ours:
156- raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames from us -- vacuous 0/0/0")
157- for i, o in enumerate(ours):
158- if len(o) != fsz:
159- raise SystemExit(f"{cell}: our decode frame {i} is {len(o)} B, geometry "
160- f"{w}x{h} ss={ss_x}{ss_y} depth={depth} implies {fsz} B")
161- sols = map_decode_to_display(ours, disp, sizes, bps, cell)
162-
163- def measure(mapping, hidden):
164- tot = [0, 0, 0]
165- per_disp = [[0, 0, 0] for _ in disp]
166- per_dec, first = [], None
167- bb_all = [[None, None, None, None] for _ in range(3)]
168- for oi, a in enumerate(ours):
169- if oi in hidden:
170- per_dec.append(None)
171- continue
172- b = disp[mapping[oi]]
173- fcount, off = [0, 0, 0], 0
174- for pi, sz in enumerate(sizes):
175- pw = w if pi == 0 else -(-w // (1 << ss_x))
176- for i in range(sz):
177- s = i * bps
178- if a[off + s:off + s + bps] != b[off + s:off + s + bps]:
179- fcount[pi] += 1
180- tot[pi] += 1
181- per_disp[mapping[oi]][pi] += 1
182- r, c = divmod(i, pw)
183- bb = bb_all[pi]
184- if bb[0] is None or r < bb[0]:
185- bb[0] = r
186- if bb[1] is None or r > bb[1]:
187- bb[1] = r
188- if bb[2] is None or c < bb[2]:
189- bb[2] = c
190- if bb[3] is None or c > bb[3]:
191- bb[3] = c
192- if first is None:
193- first = (mapping[oi], oi, "YUV"[pi], r, c,
194- int.from_bytes(a[off + s:off + s + bps], "little"),
195- int.from_bytes(b[off + s:off + s + bps], "little"))
196- off += sz * bps
197- per_dec.append(fcount)
198- return tot, per_disp, per_dec, first, bb_all
199-
200- def xor_plane_counts(a, b):
201- """Per-plane differing-SAMPLE counts at 8-bit, at C speed: XOR the two
202- planes as big ints, then count non-zero bytes per plane. Equivalent to
203- the per-sample loop above, and the only reason a 43-frame cell with 64
204- candidate assignments used to cost half an hour."""
205- z = int.from_bytes(a, "big") ^ int.from_bytes(b, "big")
206- zb = z.to_bytes(len(a), "big")
207- out, off = [], 0
208- for sz in sizes:
209- seg = zb[off:off + sz]
210- off += sz
211- out.append(len(seg) - seg.count(0))
212- return out
213-
214- if bps == 1:
215- pair_cache = {}
216-
217- def pair_total(oi, di):
218- v = pair_cache.get((oi, di))
219- if v is None:
220- v = xor_plane_counts(ours[oi], disp[di])
221- pair_cache[(oi, di)] = v
222- return v
223-
224- sol_totals = []
225- for m, _h in sols:
226- t = [0, 0, 0]
227- for oi, di in m.items():
228- p = pair_total(oi, di)
229- t[0] += p[0]
230- t[1] += p[1]
231- t[2] += p[2]
232- sol_totals.append(tuple(t))
233- if len(set(sol_totals)) > 1:
234- raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS "
235- f"({len(sols)} solutions) and they DISAGREE on the counts "
236- f"{sorted(set(sol_totals))} -- pick the identity source explicitly, "
237- f"this instrument will not choose for you")
238- tot = list(sol_totals[0])
239- mapping, hidden = sols[0]
240- if tot == [0, 0, 0]:
241- per_disp = [[0, 0, 0] for _ in disp]
242- per_dec = [None if oi in hidden else [0, 0, 0] for oi in range(len(ours))]
243- first, bbox = None, [[None, None, None, None] for _ in range(3)]
244- else:
245- tot, per_disp, per_dec, first, bbox = measure(mapping, hidden)
246- else:
247- # 16-bit planes: the sample loop below is the only path today.
248- if all(all(ours[oi] == disp[di] for oi, di in m.items()) for m, h in sols):
249- hidden0 = sols[0][1]
250- measured = [([0, 0, 0], [[0, 0, 0] for _ in disp],
251- [None if oi in hidden0 else [0, 0, 0] for oi in range(len(ours))],
252- None, [[None, None, None, None] for _ in range(3)])]
253- measured *= len(sols)
254- else:
255- measured = [measure(m, h) for m, h in sols]
256- totals = {tuple(t[0]) for t in measured}
257- if len(totals) > 1:
258- raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS "
259- f"({len(sols)} solutions) and they DISAGREE on the counts "
260- f"{sorted(totals)} -- pick the identity source explicitly, "
261- f"this instrument will not choose for you")
262- tot, per_disp, per_dec, first, bbox = measured[0]
263- mapping, hidden = sols[0]
264- if want_hidden is not None and len(hidden) != want_hidden:
265- raise SystemExit(f"{cell}: {len(hidden)} hidden decode frame(s) {hidden}, "
266- f"expected {want_hidden} -- the frame-count claim changed")
267- return {"cell": cell, "status": "BYTE-EXACT" if tot == [0, 0, 0] else "DIVERGES",
268- "w": w, "h": h, "ss": f"{ss_x}{ss_y}", "depth": depth, "pix": pix_of(ss_x, ss_y, depth),
269- "decode_frames": len(ours), "display_frames": len(disp),
270- "hidden_decode": hidden, "mapping_solutions": len(sols),
271- "Y": tot[0], "U": tot[1], "V": tot[2],
272- "first": first, "bbox": bbox,
273- "per_decode_frame": per_dec, "per_display_frame": per_disp}
274-
275-
276-def pix_of(ss_x, ss_y, depth):
277- tag = next(k for k, v in SS.items() if v == (ss_x, ss_y))
278- return f"yuv{tag}p" + ("" if depth <= 8 else f"{depth}le")
279-
280-
281-def flip(disp, sizes, bps, disp_index, plane, sample_index):
282- """Flip bit 0 of one oracle SAMPLE's low byte: exactly +1 wrong sample in
283- both depths (2**bitdepth < 2**16, so nothing carries out of the container).
284- Returns a new list; the caller drops it to restore."""
285- new = list(disp)
286- buf = bytearray(new[disp_index])
287- buf[sum(sizes[:plane]) * bps + sample_index * bps] ^= 1
288- new[disp_index] = bytes(buf)
289- return new
290-
291-
292-def run(cell, obu, ours_prefix, want_hidden=None, json_out=False):
293- w, h, ssx, ssy, depth, pix = probe_geometry(obu)
294- bps = 1 if depth <= 8 else 2
295- sizes, fsz = plane_spans(w, h, ssx, ssy, bps)
296- disp = split(ffmpeg_frames(obu, pix), sizes, fsz, cell)
297- res = compare(cell, ours_prefix, disp, w, h, ssx, ssy, depth, want_hidden)
298- if json_out:
299- print(json.dumps(res))
300- else:
301- f = res["first"]
302- fs = "none" if f is None else \
303- f"disp f{f[0]} (decode f{f[1]}) {f[2]} (r{f[3]},c{f[4]}) ours={f[5]} ffmpeg={f[6]}"
304- print(f"{cell}: {res['status']} {res['decode_frames']}df/"
305- f"{res['display_frames']}shown hidden={res['hidden_decode']} "
306- f"Y={res['Y']} U={res['U']} V={res['V']} first: {fs}")
307- return res, disp, sizes, fsz, bps
308-
309-
310-if __name__ == "__main__":
311- cell, obu, prefix = sys.argv[1:4]
312- wh = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4].isdigit() else None
313- run(cell, obu, prefix, wh, "--json" in sys.argv)
scripts/cmpff.pydeleted+0 -1
@@ -1 +0,0 @@
1-cmp422-ffmpeg.py
\ No newline at end of file\ No newline at end of file
scripts/flipctl-422.pydeleted+0 -141
@@ -1,141 +0,0 @@
1-#!/usr/bin/env python3
2-"""Flip control: prove the ffmpeg comparator BITES, before any verdict.
3-
4-[`cmp422-ffmpeg`][c] re-derives the decode->display assignment from LUMA
5-identity on every call, so a flipped oracle sample can never be re-mapped --
6-the identity it keys on is exactly what the flip breaks. This control
7-therefore maps ONCE from the untouched streams and then flips one SAMPLE per
8-arm with the mapping PINNED, which is the only way to ask "does one wrong
9-sample move the count by exactly one?".
10-
11-Two independent directions, both required to pass:
12-
13-* **oracle arm** -- flip one ffmpeg sample. The plane that owns it must move by
14- EXACTLY +1, every other plane by exactly 0. On a byte-exact cell this is the
15- only thing that can move, so a `0/0/0` that survives a flip is a comparator
16- that is not reading the oracle.
17-* **ours arm** -- flip one of OUR samples with the oracle untouched. Same
18- delta. This is the direction the whole corpus verdict rests on, and on a
19- `0/0/0` cell it is what separates "we agree" from "we never looked".
20-
21-Every decode->display SOLUTION is exercised, so an ambiguous mapping cannot
22-hide a failure behind the one that was picked.
23-
24-Usage:
25- python3 scripts/flipctl-422.py cells.json
26-
27-`cells.json` entries: `{"name", "path", "prefix"}`, `prefix` being our
28-`EC_AV1_FINAL_DUMP` prefix. Exit status 0 only if every arm passes.
29-"""
30-import importlib.util
31-import json
32-import os
33-import sys
34-
35-_HERE = os.path.dirname(os.path.abspath(__file__))
36-_spec = importlib.util.spec_from_file_location(
37- "cmp422_ffmpeg", os.path.join(_HERE, "cmp422-ffmpeg.py"))
38-C = importlib.util.module_from_spec(_spec)
39-_spec.loader.exec_module(C)
40-
41-
42-def plane_counts(ours, disp, mapping, hidden, sizes, bps):
43- """The comparator's own accounting (`cmp422-ffmpeg.compare`'s `measure`),
44- with the decode->display assignment PINNED so a flipped sample cannot
45- re-map."""
46- tot = [0, 0, 0]
47- for oi, a in enumerate(ours):
48- if oi in hidden:
49- continue
50- b = disp[mapping[oi]]
51- off = 0
52- for pi, sz in enumerate(sizes):
53- for i in range(sz):
54- s = off + i * bps
55- if a[s:s + bps] != b[s:s + bps]:
56- tot[pi] += 1
57- off += sz * bps
58- return tot
59-
60-
61-def flip_sample(buf, sample_index, bps):
62- """Flip bit 0 of one SAMPLE's low byte: exactly +1 wrong sample at both
63- depths (2**bitdepth < 2**16, so nothing carries out of the container)."""
64- out = bytearray(buf)
65- out[sample_index * bps] ^= 1
66- return bytes(out)
67-
68-
69-def arms_for(sizes):
70- """(plane, sample_index) per plane: the first, the middle and the last."""
71- out = []
72- for pi, sz in enumerate(sizes):
73- out += [(pi, 0), (pi, sz // 2), (pi, sz - 1)]
74- return out
75-
76-
77-def one_cell(cell, path, prefix):
78- w, h, ssx, ssy, depth, pix = C.probe_geometry(path)
79- bps = 1 if depth <= 8 else 2
80- sizes, fsz = C.plane_spans(w, h, ssx, ssy, bps)
81- disp = C.split(C.ffmpeg_frames(path, pix), sizes, fsz, cell)
82- ours = [open(p, "rb").read() for p in C.frame_files(prefix)]
83- if not ours:
84- raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames -- vacuous")
85- for i, o in enumerate(ours):
86- if len(o) != fsz:
87- raise SystemExit(f"{cell}: our frame {i} is {len(o)} B, "
88- f"geometry {w}x{h} ss={ssx}{ssy} depth={depth} implies {fsz} B")
89- sols = C.map_decode_to_display(ours, disp, sizes, bps, cell)
90- shown = set()
91- for mapping, hidden in sols:
92- shown |= {d for oi, d in enumerate(mapping) if oi not in hidden}
93- shown = sorted(shown)
94- # Two shown display frames per cell -- the first and one in the middle --
95- # so the arm is not confined to frame 0.
96- ks = sorted({shown[0], shown[len(shown) // 2]})
97- results, arms = [], 0
98- base0 = plane_counts(ours, disp, sols[0][0], sols[0][1], sizes, bps)
99- for k in ks:
100- for sol_i, (mapping, hidden) in enumerate(sols):
101- dmap = {d: oi for oi, d in enumerate(mapping) if oi not in hidden}
102- if k not in dmap:
103- continue
104- oi = dmap[k]
105- base = plane_counts(ours, disp, mapping, hidden, sizes, bps)
106- for pi, si in arms_for(sizes):
107- off = sum(sizes[:pi]) + si # sample index inside the frame
108- want = [0, 0, 0]
109- want[pi] = 1
110- for side in ("oracle", "ours"):
111- if side == "oracle":
112- f = list(disp)
113- f[k] = flip_sample(disp[k], off, bps)
114- got = plane_counts(ours, f, mapping, hidden, sizes, bps)
115- else:
116- f = list(ours)
117- f[oi] = flip_sample(ours[oi], off, bps)
118- got = plane_counts(f, disp, mapping, hidden, sizes, bps)
119- delta = [got[i] - base[i] for i in range(3)]
120- ok = delta == want
121- results.append(ok)
122- arms += 1
123- if not ok:
124- print(f" FAIL {side:6s} disp f{k} plane {'YUV'[pi]} "
125- f"sample {si} sol{sol_i}: {base} -> {got} "
126- f"delta {delta} want {want}")
127- print(f"{cell}: baseline {base0} {len(ours)} decode / {len(disp)} shown, "
128- f"hidden {sols[0][1]}, {len(sols)} mapping solution(s), {arms} arms")
129- return results
130-
131-
132-def main(spec_path):
133- rows = []
134- for c in json.load(open(spec_path)):
135- rows += one_cell(c["name"], c["path"], c["prefix"])
136- print(f"\n{sum(rows)} PASS, {len(rows) - sum(rows)} FAIL of {len(rows)} flip arms")
137- return 0 if all(rows) else 1
138-
139-
140-if __name__ == "__main__":
141- sys.exit(main(sys.argv[1]))
\ No newline at end of file\ No newline at end of file
scripts/gen-aac-layouts.shdeleted+0 -19
@@ -1,19 +0,0 @@
1-#!/usr/bin/env bash
2-# Usage: scripts/gen-aac-layouts.sh <fixtures/audio dir>
3-# Generates the 3.0, 4.0, 5.0 and 7.1 48 kHz FLAC fixtures, same construction as gen-fixtures.sh's 5.1.
4-set -euo pipefail
5-OUT=$1
6-FREQS=(220 440 660 55 880 1320 1760 2200)
7-gen() { # name nch layout
8- local name=$1 nch=$2 layout=$3 ain=() lbl="" i
9- for ((i = 0; i < nch; i++)); do
10- ain+=(-f lavfi -i "sine=frequency=${FREQS[i]}:sample_rate=48000:duration=3")
11- lbl="${lbl}[${i}:a]"
12- done
13- ffmpeg -v error -y "${ain[@]}" -filter_complex "${lbl}join=inputs=${nch}:channel_layout=${layout}[a]" \
14- -map "[a]" -c:a flac -compression_level 5 -ar 48000 "$OUT/flac-${name}-48000.flac"
15-}
16-gen 3.0 3 3.0
17-gen 4.0 4 4.0
18-gen 5.0 5 5.0
19-gen 7.1 8 7.1
scripts/gen-bitmap-sub-fixtures.pydeleted+0 -93
@@ -1,93 +0,0 @@
1-#!/usr/bin/env python3
2-"""Writes a small synthetic PGS .sup (720x576, four cues with known times) to argv[1].
3-
4-It is the *source* the DVD/DVB subtitle fixtures are encoded from with ffmpeg
5-(scripts/gen-bitmap-sub-fixtures.sh): ffmpeg's dvdsub and dvbsub encoders take bitmaps only.
6-No third-party media is involved; the text is rendered with PIL's default font.
7-"""
8-import struct, sys
9-from PIL import Image, ImageDraw, ImageFilter, ImageFont
10-
11-W, H = 720, 576
12-CUES = [ # start s, end s, text lines, y
13- (0.5, 1.5, ["Hello DVD"], 480),
14- (2.0, 3.2, ["Second cue", "line two"], 440),
15- (3.5, 4.5, ["Third — éèü"], 60),
16- (5.0, 6.0, ["End"], 500),
17-]
18-try:
19- FONT = ImageFont.load_default(size=36)
20-except TypeError:
21- FONT = ImageFont.load_default()
22-
23-
24-def seg(kind, pts, body):
25- return b"PG" + struct.pack(">IIBH", int(pts * 90000), 0, kind, len(body)) + body
26-
27-
28-def rle(rows):
29- out = bytearray()
30- for row in rows:
31- x = 0
32- while x < len(row):
33- c = row[x]
34- n = 1
35- while x + n < len(row) and row[x + n] == c and n < 16383:
36- n += 1
37- if c != 0 and n < 3:
38- out += bytes([c]) * n
39- elif c == 0:
40- out += bytes([0, 0x40 | (n >> 8), n & 255]) if n > 63 else bytes([0, n])
41- else:
42- out += bytes([0, 0xC0 | (n >> 8), n & 255, c]) if n > 63 else bytes([0, 0x80 | n, c])
43- x += n
44- out += b"\0\0"
45- return bytes(out)
46-
47-
48-def render(lines):
49- d = ImageDraw.Draw(Image.new("L", (1, 1)))
50- ws = [d.textbbox((0, 0), t, font=FONT)[2] for t in lines]
51- w, h = max(ws) + 12, 44 * len(lines) + 8
52- fg = Image.new("L", (w, h), 0)
53- dr = ImageDraw.Draw(fg)
54- for i, t in enumerate(lines):
55- dr.text(((w - ws[i]) // 2, 4 + 44 * i), t, fill=255, font=FONT)
56- ol = fg.filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(0.7))
57- px = []
58- for y in range(h):
59- row = []
60- for x in range(w):
61- f, o = fg.getpixel((x, y)) // 32, ol.getpixel((x, y)) // 32 # 0..7
62- row.append(1 + f if f >= 4 else (9 + o if o else 0)) if False else row.append(
63- (1 + f) if f >= 3 else ((9 + o) if o else 0))
64- px.append(row)
65- return w, h, px
66-
67-
68-def palette():
69- ents = [(0, 16, 128, 128, 0)]
70- for i in range(1, 9): # white ramp, indices 1..8
71- ents.append((i, 235, 128, 128, 255 if i > 4 else 128))
72- for i in range(9, 17): # black outline, indices 9..16
73- ents.append((i, 16, 128, 128, min(255, 40 * (i - 8))))
74- return b"".join(struct.pack("BBBBB", i, y, cr, cb, a) for i, y, cr, cb, a in ents)
75-
76-
77-out = bytearray()
78-num = 0
79-for start, end, lines, y in CUES:
80- w, h, px = render(lines)
81- x = (W - w) // 2
82- data = rle(px)
83- pcs = struct.pack(">HHBHBBBB", W, H, 0x10, num, 0x80, 0, 0, 1) + struct.pack(">HBBHH", 0, 0, 0, x, y)
84- wds = struct.pack(">BBHHHH", 1, 0, x, y, w, h)
85- pds = bytes([0, 0]) + palette()
86- ods = struct.pack(">HBB", 0, 0, 0xC0) + (len(data) + 4).to_bytes(3, "big") + struct.pack(">HH", w, h) + data
87- for k, b in ((0x16, pcs), (0x17, wds), (0x14, pds), (0x15, ods), (0x80, b"")):
88- out += seg(k, start, b)
89- num += 1
90- pcs = struct.pack(">HHBHBBBB", W, H, 0x10, num, 0x00, 0, 0, 0)
91- out += seg(0x16, end, pcs) + seg(0x17, end, struct.pack(">BBHHHH", 1, 0, x, y, w, h)) + seg(0x80, end, b"")
92- num += 1
93-open(sys.argv[1], "wb").write(out)
scripts/gen-bitmap-sub-fixtures.shdeleted+0 -22
@@ -1,22 +0,0 @@
1-#!/usr/bin/env bash
2-# gen-bitmap-sub-fixtures.sh: regenerate the DVD/DVB subtitle fixtures of ec-dvdsub and ec-dvbsub.
3-#
4-# A synthetic 720x576 PGS source (scripts/gen-bitmap-sub-fixtures.py, PIL text, four cues at
5-# 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
6-# take bitmaps only). Needs ffmpeg and python3 with PIL. dvd.idx is written by hand from dvd.sub.
7-set -euo pipefail
8-ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd)
9-T=$(mktemp -d "${TMPDIR:-/tmp}/bitmapsub.XXXXXX")
10-trap 'rm -rf "$T"' EXIT
11-python3 "$ROOT/scripts/gen-bitmap-sub-fixtures.py" "$T/src.sup"
12-S=(-fix_sub_duration -f sup -i "$T/src.sup")
13-DVD="$ROOT/crates/ec-dvdsub/tests/data"; DVB="$ROOT/crates/ec-dvbsub/tests/data"
14-mkdir -p "$DVD" "$DVB"
15-ffmpeg -v error -y "${S[@]}" -c:s dvdsub -map 0 "$DVD/dvd.mkv"
16-ffmpeg -v error -y -f lavfi -i color=c=black:s=720x576:r=25:d=7 "${S[@]}" -c:v mpeg2video -b:v 200k \
17- -maxrate 9000k -bufsize 1835k -c:s dvdsub -map 0 -map 1 -target pal-dvd -an "$DVD/dvd.vob"
18-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"
19-ffmpeg -v error -y "${S[@]}" -c:s dvdsub -map 0 -f vob "$DVD/dvd.sub"
20-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"
21-ffmpeg -v error -y "${S[@]}" -c:s dvbsub -map 0 "$DVB/dvb.mkv"
22-echo "fixtures written (dvd.idx is hand-made; see the test)"
scripts/gen-mp4-parity-corpus.shdeleted+0 -40
@@ -1,40 +0,0 @@
1-#!/usr/bin/env bash
2-# gen-mp4-parity-corpus.sh: write the generated mp4/mov cases that the ec-mp4 parity
3-# test (crates/ec-mp4/tests/it/edith_parity.rs) compares against ffprobe.
4-#
5-# Usage: scripts/gen-mp4-parity-corpus.sh <out-dir>
6-#
7-# Each case isolates one thing the demuxer must read the way edith does:
8-# bframes.mp4 B-frames: ctts v0 offsets, a sample order that differs from display order
9-# negcts.mp4 negative composition offsets (ctts v1), -movflags negative_cts_offsets
10-# rot90.mp4 tkhd display matrix of a quarter turn (copied from tests/data)
11-# rot270.mp4 the other quarter turn (copied from tests/data)
12-# qt.mov QuickTime container (-f mov): mp4a in a sound description
13-# emptyedit.mp4 an audio track delayed by 0.5 s: an empty edit ahead of the media
14-# aac-prime.mp4 AAC audio alone: the encoder delay is an edit list (elst) of its own
15-# mp3.mp4 an mp4a entry carrying MP3
16-#
17-# Needs ffmpeg with libx264. Output is deterministic for a given ffmpeg build.
18-set -euo pipefail
19-out=${1:?usage: gen-mp4-parity-corpus.sh <out-dir>}
20-here=$(cd -- "$(dirname -- "$0")" && pwd)
21-mkdir -p "$out"
22-cd "$out"
23-ff() { ffmpeg -hide_banner -v error -y "$@"; }
24-ff -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \
25- -f lavfi -i sine=frequency=440:duration=2 \
26- -c:v libx264 -bf 2 -g 24 -pix_fmt yuv420p -c:a aac -b:a 128k bframes.mp4
27-ff -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \
28- -c:v libx264 -bf 2 -pix_fmt yuv420p -movflags negative_cts_offsets negcts.mp4
29-# The display matrices: stream copies of the committed rotation clips, whose tkhd
30-# matrix ffmpeg wrote with -display_rotation (crates/ec-mp4/tests/data/gen.sh).
31-ff -i "$here/../crates/ec-mp4/tests/data/rot90.mp4" -c copy rot90.mp4
32-ff -i "$here/../crates/ec-mp4/tests/data/rot270.mp4" -c copy rot270.mp4
33-ff -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \
34- -f lavfi -i sine=frequency=440:duration=2 \
35- -c:v libx264 -bf 2 -pix_fmt yuv420p -c:a aac -f mov qt.mov
36-ff -f lavfi -i sine=frequency=440:duration=2 -itsoffset 0.5 \
37- -f lavfi -i testsrc2=size=64x64:rate=24:duration=2 \
38- -map 0:a -map 1:v -c:v libx264 -c:a aac -shortest emptyedit.mp4
39-ff -f lavfi -i sine=frequency=440:duration=2 -c:a aac -b:a 96k aac-prime.mp4
40-ff -f lavfi -i sine=frequency=440:duration=2 -c:a libmp3lame -b:a 96k -f mp4 mp3.mp4
scripts/h264-bd.shdeleted+0 -18
@@ -1,18 +0,0 @@
1-#!/usr/bin/env bash
2-# h264-bd.sh: BD-rate of the Fast preset vs x264 veryfast on the 1080p library clip
3-# (the h264encbd method). Run through scripts/remote-run.sh. Prints bd_rate_pct and bd_psnr_db.
4-set -euo pipefail
5-d=${TMPDIR:-/tmp}/h264bd.$$; mkdir -p "$d"
6-EC_REQUIRE_FIXTURES=1 EC_H264_X264_PRESET=veryfast \
7-EC_H264_CLIP=$HOME/fixtures/video/h264-1080p-23.976-8bit.mp4 \
8- cargo test --release -p ec-h264 --test it encode::bd_psnr_vs_x264 -- --nocapture 2>&1 | tee "$d/log" | grep -E "^(test |BD-)" || true
9-python3 -I - "$d" <<'PY'
10-import re,sys
11-d=sys.argv[1]
12-o=open(d+"/ours.tsv","w"); x=open(d+"/x264.tsv","w")
13-for l in open(d+"/log"):
14- m=re.match(r"qp \d+: ours (\d+) bits ([\d.]+) dB \(([\d.]+) yuv\) \| x264 (\d+) bits ([\d.]+) dB \(([\d.]+) yuv\)",l)
15- if m:
16- 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")
17-PY
18-python3 -I scripts/bdrate.py --metric yuv "$d/x264.tsv" "$d/ours.tsv"
scripts/h264-speed.shdeleted+0 -20
@@ -1,20 +0,0 @@
1-#!/usr/bin/env bash
2-# h264-speed.sh <frames> <threads> [features]: 1080p30 encode speed, noisy and clean testsrc2.
3-# Run it through scripts/remote-run.sh. Clips are cached in $HOME/.cache/h264speed.
4-set -euo pipefail
5-frames=${1:-60}; threads=${2:-1}; feat=${3:-}
6-d=$HOME/.cache/h264speed; mkdir -p "$d"
7-for kind in noisy clean; do
8- f=$d/$kind-$frames.yuv
9- if [ ! -s "$f" ]; then
10- g="testsrc2=size=1920x1080:rate=30:duration=$(awk -v n="$frames" 'BEGIN{print n/30}')"
11- [ $kind = noisy ] && g="$g,noise=alls=24:allf=t"
12- ffmpeg -nostdin -v error -y -f lavfi -i "$g" -pix_fmt yuv420p -f rawvideo "$f"
13- fi
14-done
15-cargo build --release -p ec-h264 --example h264_clip_encode ${feat:+--features $feat} 2>&1 | tail -2
16-bin=${CARGO_TARGET_DIR:-target}/release/examples/h264_clip_encode
17-for kind in noisy clean; do
18- echo "== $kind threads=$threads"
19- bash -c "time \"\$0\" \"\$@\"" "$bin" "$d/$kind-$frames.yuv" 1920 1080 30 4000000 26 "$threads" none
20-done
scripts/h264-sweep.shdeleted+0 -8
@@ -1,8 +0,0 @@
1-#!/usr/bin/env bash
2-# h264-sweep.sh "<ENV=.. ENV=..>" : speed (60 frames, 1 thread) and BD-rate for one knob setting.
3-# Run on one host: scripts/remote-run.sh h264encspeed2 --host a -- bash scripts/h264-sweep.sh "EC_H264_ME_SUB=1"
4-set -uo pipefail
5-for kv in $1; do export "$kv"; done
6-echo "### $1"
7-bash scripts/h264-speed.sh 60 1 2>&1 | grep -E "^(==|frames)"
8-bash scripts/h264-bd.sh 2>&1 | grep -E "bd_rate|BD-PSNR-YUV"
scripts/hevc-intra-bd.shdeleted+0 -36
@@ -1,36 +0,0 @@
1-#!/usr/bin/env bash
2-# hevc-intra-bd.sh: intra-only (keyint=1) BD-rate of ec-h265 against x265 intra on the three
3-# clips the ec-h265 encode gate names. Thin wrapper over scripts/hevc-bdrate.sh with GOP 1.
4-# Clips are generated with ffmpeg lavfi (no copyrighted media) into $DATA.
5-#
6-# The x265 anchor uses -tune psnr by default (see hevc-bdrate.sh). Set X265_TUNE= for x265's
7-# default tuning. Each tuning writes its own point files under $DATA/tune-<name>/.
8-#
9-# Usage: scripts/hevc-intra-bd.sh <clip-name|all> [QPS]
10-# clip-name: testsrc2-352x288 | testsrc2-1280x720 | natural-1280x720 | all
11-# Environment: DATA (default $HOME/.cache/hevcintra-data).
12-set -euo pipefail
13-here=$(cd "$(dirname "$0")/.." && pwd)
14-which=${1:-all}
15-qps=${2:-"22 27 32 37"}
16-data=${DATA:-$HOME/.cache/hevcintra-data}
17-mkdir -p "$data"
18-frames=30
19-gen() { # gen <out.yuv> <lavfi graph>
20- [ -f "$1" ] || ffmpeg -v error -y -f lavfi -i "$2" -frames:v $frames -pix_fmt yuv420p -f rawvideo "$1"
21-}
22-gen "$data/testsrc2-352x288.yuv" "testsrc2=size=352x288:rate=30"
23-gen "$data/testsrc2-1280x720.yuv" "testsrc2=size=1280x720:rate=30"
24-# "natural": a moving mandelbrot zoom blended with testsrc2 and film-like noise (the
25-# gen-hevcperf-fixtures.sh moving clip), so it has texture rather than flat synthetic edges.
26-[ -f "$data/natural-1280x720.yuv" ] || ffmpeg -v error -y \
27- -f lavfi -i "mandelbrot=size=1280x720:rate=30" \
28- -f lavfi -i "testsrc2=size=1280x720:rate=30" \
29- -filter_complex "[0:v][1:v]blend=all_mode=average,noise=alls=8:allf=t,format=yuv420p[v]" \
30- -map "[v]" -frames:v $frames -f rawvideo "$data/natural-1280x720.yuv"
31-for spec in "testsrc2-352x288 352 288" "testsrc2-1280x720 1280 720" "natural-1280x720 1280 720"; do
32- set -- $spec
33- [ "$which" = all ] || [ "$which" = "$1" ] || continue
34- DATA="$data/tune-${X265_TUNE-psnr}" "$here/scripts/hevc-bdrate.sh" "$data/$1.yuv" "$2" "$3" 1 "$qps"
35- echo "----"
36-done
scripts/hevc-preset-quick.shdeleted+0 -9
@@ -1,9 +0,0 @@
1-#!/usr/bin/env bash
2-# hevc-preset-quick.sh: single-thread encode time and size of the 1080p 10-bit bench clip per preset.
3-set -e
4-cargo build --release -q -p ec-h265 --example hevc_gop 2>&1 | grep -E '^error' -A8 || true
5-B=${CARGO_TARGET_DIR:-target}/release/examples/hevc_gop; D=$HOME/.cache/hevc10simd2-bench
6-echo load $(cut -d' ' -f1-3 /proc/loadavg)
7-for p in ${PRESETS:-default fast faster}; do
8- 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
9-done
scripts/hevc-rc-bdrate.shdeleted+0 -66
@@ -1,66 +0,0 @@
1-#!/usr/bin/env bash
2-# hevc-rc-bdrate.sh: BD-rate of ec-h265's bitrate-controlled sequence encoder against libx265
3-# at the same bitrates, with x265 at bframes=0 and the same keyframe interval.
4-#
5-# The bitrate counterpart of hevc-bdrate.sh (which sweeps constant QP). Each side is encoded at
6-# the KBPS targets (ec-h265 through the hevc_rc example, x265 with -b:v at veryfast); the points
7-# are (bytes, Y and YUV PSNR against the source, from scripts/ffmpeg-psnr.sh). Positive
8-# bd_rate_pct means ec-h265 needs more bytes at the same quality.
9-#
10-# Usage: scripts/hevc-rc-bdrate.sh <clip.yuv> <width> <height> [GOP] [KBPS list]
11-# Environment: DATA (default $HOME/.cache/hevcencrc-data), FPS (default 30).
12-set -euo pipefail
13-
14-here=$(cd "$(dirname "$0")/.." && pwd)
15-clip=$1
16-w=$2
17-h=$3
18-gop=${4:-30}
19-kbpss=${5:-"1000 2000 4000 8000"}
20-fps=${FPS:-30}
21-data=${DATA:-$HOME/.cache/hevcencrc-data}
22-mkdir -p "$data"
23-[ -f "$clip" ] || clip="$data/$clip"
24-tag=$(basename "$clip" .yuv)-${w}x${h}-k$gop-rc
25-
26-cargo build --release -q -p ec-h265 --example hevc_rc --manifest-path "$here/Cargo.toml"
27-target=$(cargo metadata --format-version 1 --no-deps --manifest-path "$here/Cargo.toml" \
28- | python3 -I -c 'import json,sys; print(json.load(sys.stdin)["target_directory"])')
29-rcbin="$target/release/examples/hevc_rc"
30-
31-anchor="$data/$tag.x265.tsv"
32-test_="$data/$tag.ec.tsv"
33-: > "$anchor"
34-: > "$test_"
35-for kbps in $kbpss; do
36- x265="$data/$tag-$kbps.x265.hevc"
37- ffmpeg -v error -y -f rawvideo -pix_fmt yuv420p -s "${w}x${h}" -r "$fps" -i "$clip" \
38- -c:v libx265 -preset veryfast -b:v "${kbps}k" \
39- -x265-params "bframes=0:keyint=$gop:min-keyint=$gop:scenecut=0:log-level=error" \
40- -f hevc "$x265"
41- xdec="$data/$tag-$kbps.x265.yuv"
42- ffmpeg -v error -y -i "$x265" -f rawvideo -pix_fmt yuv420p "$xdec"
43- xline=$("$here/scripts/ffmpeg-psnr.sh" "$clip" "$xdec" "$w" "$h")
44- xpy=$(echo "$xline" | sed -n 's/.*psnr_y=\([^ ]*\).*/\1/p')
45- xpsnr=$(echo "$xline" | sed -n 's/.*psnr_yuv=\([^ ]*\).*/\1/p')
46- rm -f "$xdec"
47- printf '%s\t%s\t%s\n' "$(stat -c %s "$x265")" "$xpy" "$xpsnr" >> "$anchor"
48-
49- ours="$data/$tag-$kbps.ec.hevc"
50- recon="$data/$tag-$kbps.ec.recon.yuv"
51- "$rcbin" encode "$clip" "$w" "$h" "$gop" "$kbps" "$fps" "$ours" "$recon" >/dev/null
52- oline=$("$here/scripts/ffmpeg-psnr.sh" "$clip" "$recon" "$w" "$h")
53- rm -f "$recon"
54- opy=$(echo "$oline" | sed -n 's/.*psnr_y=\([^ ]*\).*/\1/p')
55- opsnr=$(echo "$oline" | sed -n 's/.*psnr_yuv=\([^ ]*\).*/\1/p')
56- printf '%s\t%s\t%s\n' "$(stat -c %s "$ours")" "$opy" "$opsnr" >> "$test_"
57- echo "kbps=$kbps x265: bytes=$(stat -c %s "$x265") psnr_y=$xpy | ec-h265: bytes=$(stat -c %s "$ours") psnr_y=$opy" >&2
58-done
59-echo "clip=$(basename "$clip") size=${w}x${h} gop=$gop kbps=[$kbpss]"
60-echo "points (bytes, psnr_y, psnr_yuv):"
61-echo " anchor x265:"; sed 's/^/ /' "$anchor"
62-echo " test ec-h265:"; sed 's/^/ /' "$test_"
63-echo "metric=yuv (6:1:1):"
64-python3 -I "$here/scripts/bdrate.py" --metric yuv "$anchor" "$test_"
65-echo "metric=y:"
66-python3 -I "$here/scripts/bdrate.py" --metric y "$anchor" "$test_"
scripts/hevc-speed-sweep.shdeleted+0 -36
@@ -1,36 +0,0 @@
1-#!/usr/bin/env bash
2-# hevc-speed-sweep.sh: speed and rate-distortion of ec-h265 sequence encodes under env overrides.
3-# Usage: scripts/hevc-speed-sweep.sh <label> [VAR=val ...]
4-# Encodes 3 synthetic 720p 10-bit clips at QP 22/27/32/37 (keyint 8, 4 threads), writes
5-# $D/<label>.<clip>.tsv (bytes, psnr_y, psnr_yuv) and prints fps. Compare labels with bdrate.py.
6-# Env: BITDEPTH (10), CLIPS (a b c), N (32).
7-set -e
8-here=$(cd "$(dirname "$0")/.." && pwd)
9-label=$1; shift
10-D=${D:-$HOME/.cache/hevcfast-data2}; mkdir -p "$D"
11-N=${N:-32}; BD=${BITDEPTH:-10}; W=1280; H=720
12-pix=yuv420p; [ $BD = 10 ] && pix=yuv420p10le
13-src_a="testsrc2=size=${W}x${H}:rate=30,scroll=h=0.003:v=0.004,noise=alls=4:allf=t"
14-src_b="mandelbrot=size=${W}x${H}:rate=30"
15-src_c="gradients=size=${W}x${H}:rate=30:speed=0.02:n=4,noise=alls=5:allf=t"
16-for c in ${CLIPS:-a b c}; do
17- f=$D/$c$BD.yuv
18- [ -s $f ] || { eval s=\$src_$c; ffmpeg -loglevel error -y -f lavfi -i "$s" -frames:v $N -pix_fmt $pix -f rawvideo $f; }
19-done
20-(cd "$here" && cargo build --release -q -p ec-h265 --example hevc_gop)
21-BIN=${CARGO_TARGET_DIR:-$here/target}/release/examples/hevc_gop
22-echo "host=$(hostname) load=$(cut -d' ' -f1-3 /proc/loadavg)"
23-for c in ${CLIPS:-a b c}; do
24- f=$D/$c$BD.yuv; out=$D/$label.$c.tsv; : > $out; tt=0; tc=0
25- for qp in 22 27 32 37; do
26- TIMEFORMAT='%U %S'; { time env "$@" EC_H265_BITDEPTH=$BD EC_H265_THREADS=4 EC_H265_TIMING=1 $BIN encode $f $W $H 8 $qp $D/o.hevc $D/r.yuv >/dev/null 2>$D/t.log; } 2>$D/cpu.log
27- cpu=$(awk '{print $1+$2}' $D/cpu.log); tc=$(awk "BEGIN{print ${tc:-0}+$cpu}")
28- t=$(cut -d' ' -f2 $D/t.log | tr -d s); tt=$(awk "BEGIN{print $tt+$t}")
29- l=$(PIX=$pix $here/scripts/ffmpeg-psnr.sh $f $D/r.yuv $W $H)
30- py=$(echo "$l" | sed -n 's/.*psnr_y=\([^ ]*\).*/\1/p'); pyuv=$(echo "$l" | sed -n 's/.*psnr_yuv=\([^ ]*\).*/\1/p')
31- printf '%s\t%s\t%s\n' $(stat -c %s $D/o.hevc) $py $pyuv >> $out
32- done
33- fps=$(awk "BEGIN{printf \"%.2f\", 4*$N/$tt}")
34- bd=""; [ "$label" != default ] && [ -s $D/default.$c.tsv ] && bd=$(python3 -I $here/scripts/bdrate.py --metric yuv $D/default.$c.tsv $out | tr '\n' ' ')
35- echo "$label clip=$c fps=$fps cpu_ms_per_frame=$(awk "BEGIN{printf \"%.0f\", 1000*$tc/(4*$N)}") $bd"
36-done
scripts/hevc-thread-bench.shdeleted+0 -72
@@ -1,72 +0,0 @@
1-#!/usr/bin/env bash
2-# hevc-thread-bench.sh: encode lavfi clips with ec-h265 at 1, 2, 4 and 6 worker threads,
3-# report fps per thread count, and check that every thread count writes the same bytes.
4-#
5-# Usage: scripts/remote-run.sh hevcencthreads --host b -- scripts/hevc-thread-bench.sh
6-#
7-# Environment: DATA (default $HOME/.cache/hevcencthreads-data), GOP (keyframe interval,
8-# default 8), QP (default 30), FRAMES (default 12), CLIPS (default "1280x720 1920x1080"),
9-# THREADS (default "1 2 4 6"), RUNS (timed runs per point, default 1, best time kept).
10-# RC_KBPS: when set (e.g. 4000), encode with bitrate control at that rate and FPS (default 30)
11-# through the hevc_rc example instead of constant QP through hevc_gop.
12-set -euo pipefail
13-
14-here=$(cd "$(dirname "$0")/.." && pwd)
15-data=${DATA:-$HOME/.cache/hevcencthreads-data}
16-gop=${GOP:-8}
17-qp=${QP:-30}
18-frames=${FRAMES:-12}
19-clips=${CLIPS:-"1280x720 1920x1080"}
20-threads_list=${THREADS:-"1 2 4 6"}
21-runs=${RUNS:-1}
22-mkdir -p "$data"
23-
24-rc_kbps=${RC_KBPS:-}
25-rc_fps=${FPS:-30}
26-if [ -n "$rc_kbps" ]; then
27- cargo build --release -q -p ec-h265 --example hevc_rc --manifest-path "$here/Cargo.toml"
28-else
29- cargo build --release -q -p ec-h265 --example hevc_gop --manifest-path "$here/Cargo.toml"
30-fi
31-target=$(cargo metadata --format-version 1 --no-deps --manifest-path "$here/Cargo.toml" \
32- | python3 -I -c 'import json,sys; print(json.load(sys.stdin)["target_directory"])')
33-gopbin="$target/release/examples/hevc_gop"
34-[ -n "$rc_kbps" ] && gopbin="$target/release/examples/hevc_rc"
35-
36-printf '%-10s %-8s %-10s %-10s %-10s %-s\n' clip threads secs fps bytes identical
37-for size in $clips; do
38- w=${size%x*}
39- h=${size#*x}
40- src="$data/src-$size-$frames.yuv"
41- if [ ! -s "$src" ]; then
42- ffmpeg -v error -y -f lavfi -i "testsrc2=size=${size}:rate=30" \
43- -vf "scroll=v=0.02,format=yuv420p" -frames:v "$frames" -f rawvideo "$src"
44- fi
45- ref_md5=""
46- for t in $threads_list; do
47- out="$data/out-$size-t$t.hevc"
48- recon="$data/recon-$size-t$t.yuv"
49- best=""
50- for _ in $(seq "$runs"); do
51- start=$(date +%s.%N)
52- if [ -n "$rc_kbps" ]; then
53- EC_H265_THREADS="$t" "$gopbin" encode "$src" "$w" "$h" "$gop" "$rc_kbps" "$rc_fps" "$out" "$recon" >/dev/null
54- else
55- EC_H265_THREADS="$t" "$gopbin" encode "$src" "$w" "$h" "$gop" "$qp" "$out" "$recon" >/dev/null
56- fi
57- end=$(date +%s.%N)
58- secs=$(python3 -I -c "print(f'{$end - $start:.3f}')")
59- if [ -z "$best" ] || python3 -I -c "import sys; sys.exit(0 if $secs < $best else 1)"; then
60- best=$secs
61- fi
62- done
63- bytes=$(stat -c %s "$out")
64- md5=$(md5sum "$out" | cut -d' ' -f1)
65- if [ -z "$ref_md5" ]; then ref_md5=$md5; fi
66- same=yes
67- [ "$md5" = "$ref_md5" ] || same=NO
68- [ "$same" = yes ] || { echo "FAIL: $size threads $t bytes differ from the first thread count" >&2; exit 1; }
69- fps=$(python3 -I -c "print(f'{$frames / $best:.2f}')")
70- printf '%-10s %-8s %-10s %-10s %-10s %-s\n' "$size" "$t" "$best" "$fps" "$bytes" "$same"
71- done
72-done
scripts/lr-sgr-pin-harness.cdeleted+0 -113
@@ -1,113 +0,0 @@
1-#include <stdio.h>
2-#include <stdint.h>
3-#include <stdlib.h>
4-
5-extern int av1_apply_selfguided_restoration_c(
6- const uint8_t *dat8, int width, int height, int stride, int eps,
7- const int *xqd, uint8_t *dst8, int dst_stride, int32_t *tmpbuf,
8- int bit_depth, int highbd);
9-extern int av1_selfguided_restoration_c(const uint8_t *dgd8, int width,
10- int height, int dgd_stride,
11- int32_t *flt0, int32_t *flt1,
12- int flt_stride, int sgr_params_idx,
13- int bit_depth, int highbd);
14-// Exported by scripts/instrument-aom-oracle.sh's rung 6 (normally `static`
15-// in restoration.c) so this harness can get real per-tap A[]/B[] instead of
16-// only the combined flt0/flt1 -- the missing half of r6's 9-tap cross-check.
17-extern void calculate_intermediate_result(int32_t *dgd, int width, int height,
18- int dgd_stride, int bit_depth,
19- int sgr_params_idx, int radius_idx,
20- int pass, int32_t *A, int32_t *B);
21-
22-#define SGRPROJ_BORDER_VERT 3
23-#define SGRPROJ_BORDER_HORZ 3
24-
25-int main(void) {
26- const int bw = 102, bh = 10;
27- // real libaom splits stripe_width into RESTORATION_PROC_UNIT_SIZE=64
28- // chunks (sgrproj_filter_stripe's `for j += procunit_width` loop) --
29- // av1_apply_selfguided_restoration_c's internal fixed-size arrays are
30- // sized for that max, so replicate the chunking (target col=6 is in
31- // the first 64-wide chunk).
32- const int w = 64, h = 4;
33- // The depth of `/tmp/lr_full.bin` is NOT in the file: the capture is a raw
34- // plane dump written by an env-gated `std::fs::write` inside
35- // `apply_sgrproj_stripe`, and whoever re-captures it from a 10/12-bit pin
36- // gets 2 bytes per sample, i.e. a file TWICE this size whose first half
37- // still looks like plausible plane data. Reading it at 1 byte per sample
38- // would then print self-guided-restoration A/B taps for the wrong pixels
39- // and nothing would fail -- so the size is the assertion: a 2x capture
40- // must not pass as an 8-bit one.
41- const size_t expect = (size_t)bw * bh;
42- uint8_t *buf = malloc(expect);
43- FILE *f = fopen("/tmp/lr_full.bin", "rb");
44- if (!f) { perror("open"); return 1; }
45- fseek(f, 0, SEEK_END);
46- const long size = ftell(f);
47- fseek(f, 0, SEEK_SET);
48- if (size != (long)expect) {
49- fprintf(stderr,
50- "/tmp/lr_full.bin is %ld bytes, this harness reads it as %d-bit (%zu bytes: "
51- "%dx%d at 1 byte per sample). %s\n",
52- size, 8, expect, bw, bh,
53- size == 2 * (long)expect
54- ? "That is exactly a 2x-size high-bit-depth capture: re-capture it as 8-bit, "
55- "or port the harness to the uint16 arm (bit_depth=10, highbd=1) before "
56- "trusting a single printed tap."
57- : "Recapture it, or fix bw/bh to the plane the capture came from.");
58- return 1;
59- }
60- if (fread(buf, 1, expect, f) != expect) { fprintf(stderr, "short read\n"); return 1; }
61- fclose(f);
62-
63- const uint8_t *dgd8 = buf + 3 * bw + 3; // logical (0,0)
64- int xqd[2] = { -16, -32 };
65- uint8_t dst[w * h];
66- // flt1 = tmpbuf + RESTORATION_UNITPELS_MAX (~152100); undersizing this
67- // segfaults inside av1_apply_selfguided_restoration_c.
68- static int32_t tmpbuf[2 * 400 * 400];
69-
70- int ret = av1_apply_selfguided_restoration_c(dgd8, w, h, bw, /*eps=*/6, xqd,
71- dst, w, tmpbuf, 8, 0);
72- printf("ret=%d\n", ret);
73- // target pixel: row i=1, col j=6
74- printf("out[1][6] = %d\n", dst[1 * w + 6]);
75- printf("dgd[1][6] = %d\n", dgd8[1 * bw + 6]);
76-
77- static int32_t flt0[400 * 400], flt1[400 * 400];
78- int r2 = av1_selfguided_restoration_c(dgd8, w, h, bw, flt0, flt1, w, 6, 8, 0);
79- printf("selfguided ret=%d flt0[1][6]=%d flt1[1][6]=%d\n", r2, flt0[1 * w + 6],
80- flt1[1 * w + 6]);
81-
82- // --- rung 6: real per-tap A[]/B[] ground truth for the dense (r1) arm ---
83- // Replicate av1_selfguided_restoration_c's own uint8->int32 border-extend
84- // copy (that function's `dgd32` setup, restoration.c) so
85- // calculate_intermediate_result sees exactly the same input it would from
86- // the real call path above.
87- const int dgd32_stride = w + 2 * SGRPROJ_BORDER_HORZ;
88- static int32_t dgd32_buf[(64 + 6) * (4 + 6)];
89- int32_t *dgd32 = dgd32_buf + dgd32_stride * SGRPROJ_BORDER_VERT + SGRPROJ_BORDER_HORZ;
90- for (int i = -SGRPROJ_BORDER_VERT; i < h + SGRPROJ_BORDER_VERT; ++i)
91- for (int j = -SGRPROJ_BORDER_HORZ; j < w + SGRPROJ_BORDER_HORZ; ++j)
92- dgd32[i * dgd32_stride + j] = dgd8[i * bw + j];
93-
94- const int width_ext = w + 2 * SGRPROJ_BORDER_HORZ;
95- const int buf_stride = ((width_ext + 3) & ~3) + 16;
96- static int32_t A_[2 * 400 * 400], B_[2 * 400 * 400];
97- // radius_idx=1 (dense/r1 arm), pass=0 (every row, matches
98- // selfguided_restoration_internal's own call).
99- calculate_intermediate_result(dgd32, w, h, dgd32_stride, /*bit_depth=*/8,
100- /*sgr_params_idx=*/6, /*radius_idx=*/1,
101- /*pass=*/0, A_, B_);
102- int32_t *A = A_ + SGRPROJ_BORDER_VERT * buf_stride + SGRPROJ_BORDER_HORZ;
103- int32_t *B = B_ + SGRPROJ_BORDER_VERT * buf_stride + SGRPROJ_BORDER_HORZ;
104- const int ti = 1, tj = 6;
105- const char *names[9] = { "c", "u", "d", "l", "r", "ul", "ur", "dl", "dr" };
106- const int di[9] = { 0, -1, 1, 0, 0, -1, -1, 1, 1 };
107- const int dj[9] = { 0, 0, 0, -1, 1, -1, 1, -1, 1 };
108- for (int t = 0; t < 9; ++t) {
109- int k = (ti + di[t]) * buf_stride + (tj + dj[t]);
110- printf("real_ab %s = (%d,%d)\n", names[t], A[k], B[k]);
111- }
112- return 0;
113-}
scripts/mp3-tables/mp3probe.pydeleted+0 -211
@@ -1,211 +0,0 @@
1-"""Black-box probe rig for MPEG-1 Layer III.
2-
3-Builds legal Layer III frames whose main data we control bit for bit, decodes
4-them with ffmpeg, and models the decode chain analytically so the spec's
5-constant tables (synthesis window, Huffman codes, scalefactor bands) can be
6-*measured* rather than copied from an implementation.
7-"""
8-
9-import math
10-import subprocess
11-import tempfile
12-import os
13-import numpy as np
14-
15-SRATES = [44100, 48000, 32000]
16-BITRATES = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]
17-
18-
19-class BitWriter:
20- def __init__(self):
21- self.bits = []
22-
23- def w(self, value, n):
24- for i in range(n - 1, -1, -1):
25- self.bits.append((value >> i) & 1)
26-
27- def __len__(self):
28- return len(self.bits)
29-
30- def bytes(self, pad_to=None):
31- bits = list(self.bits)
32- if pad_to is not None:
33- bits += [0] * (pad_to * 8 - len(bits))
34- while len(bits) % 8:
35- bits.append(0)
36- out = bytearray()
37- for i in range(0, len(bits), 8):
38- b = 0
39- for j in range(8):
40- b = (b << 1) | bits[i + j]
41- out.append(b)
42- return bytes(out)
43-
44-
45-class Granule:
46- """One granule of side info; long blocks only (all the probes need)."""
47-
48- def __init__(self, part2_3_length=0, big_values=0, global_gain=210,
49- scalefac_compress=0, table_select=(0, 0, 0), region0_count=15,
50- region1_count=1, preflag=0, scalefac_scale=0, count1table_select=0,
51- block_type=0, mixed_block=0, subblock_gain=(0, 0, 0)):
52- self.block_type = block_type
53- self.mixed_block = mixed_block
54- self.subblock_gain = subblock_gain
55- self.part2_3_length = part2_3_length
56- self.big_values = big_values
57- self.global_gain = global_gain
58- self.scalefac_compress = scalefac_compress
59- self.table_select = table_select
60- self.region0_count = region0_count
61- self.region1_count = region1_count
62- self.preflag = preflag
63- self.scalefac_scale = scalefac_scale
64- self.count1table_select = count1table_select
65-
66- def write(self, bw):
67- bw.w(self.part2_3_length, 12)
68- bw.w(self.big_values, 9)
69- bw.w(self.global_gain, 8)
70- bw.w(self.scalefac_compress, 4)
71- bw.w(1 if self.block_type else 0, 1) # window_switching_flag
72- if self.block_type:
73- bw.w(self.block_type, 2)
74- bw.w(self.mixed_block, 1)
75- for t in self.table_select[:2]:
76- bw.w(t, 5)
77- for g in self.subblock_gain:
78- bw.w(g, 3)
79- else:
80- for t in self.table_select:
81- bw.w(t, 5)
82- bw.w(self.region0_count, 4)
83- bw.w(self.region1_count, 3)
84- bw.w(self.preflag, 1)
85- bw.w(self.scalefac_scale, 1)
86- bw.w(self.count1table_select, 1)
87-
88-
89-def frame_bytes(granules, main_data, srate_idx=0, bitrate_idx=14, padding=0):
90- """One mono MPEG-1 Layer III frame. `main_data` is a list of bit lists."""
91- srate = SRATES[srate_idx]
92- frame_len = 144 * BITRATES[bitrate_idx] * 1000 // srate + padding
93- bw = BitWriter()
94- bw.w(0x7FF, 11)
95- bw.w(0b11, 2) # MPEG-1
96- bw.w(0b01, 2) # Layer III
97- bw.w(1, 1) # no CRC
98- bw.w(bitrate_idx, 4)
99- bw.w(srate_idx, 2)
100- bw.w(padding, 1)
101- bw.w(0, 1)
102- bw.w(0b11, 2) # mono
103- bw.w(0, 2)
104- bw.w(0, 1)
105- bw.w(1, 1)
106- bw.w(0, 2)
107- # side info, mono: 17 bytes
108- bw.w(0, 9) # main_data_begin
109- bw.w(0, 5) # private_bits
110- bw.w(0, 4) # scfsi
111- for g in granules:
112- g.write(bw)
113- assert len(bw) == 32 + 17 * 8, len(bw)
114- for bits in main_data:
115- bw.bits.extend(bits)
116- assert len(bw) <= frame_len * 8, (len(bw), frame_len * 8)
117- return bw.bytes(pad_to=frame_len)
118-
119-
120-def ffmpeg_decode(mp3: bytes, channels=1):
121- """Decode with ffmpeg, returning float32 samples (no resampling)."""
122- with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
123- f.write(mp3)
124- path = f.name
125- try:
126- p = subprocess.run(
127- ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(channels), "-"],
128- capture_output=True, check=True)
129- return np.frombuffer(p.stdout, dtype=np.float32).astype(np.float64), p.stderr.decode()
130- finally:
131- os.unlink(path)
132-
133-
134-# ---------------------------------------------------------------- model side
135-
136-def imdct36(X):
137- """ISO Layer III IMDCT, n = 36."""
138- n = 36
139- out = np.zeros(n)
140- for i in range(n):
141- s = 0.0
142- for k in range(n // 2):
143- s += X[k] * math.cos(math.pi / (2 * n) * (2 * i + 1 + n // 2) * (2 * k + 1))
144- out[i] = s
145- return out
146-
147-
148-WIN_NORMAL = np.array([math.sin(math.pi / 36 * (i + 0.5)) for i in range(36)])
149-
150-ALIAS_CI = [-0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037]
151-ALIAS_CS = np.array([1.0 / math.sqrt(1.0 + c * c) for c in ALIAS_CI])
152-ALIAS_CA = np.array([c / math.sqrt(1.0 + c * c) for c in ALIAS_CI])
153-
154-
155-def alias_reduce(xr):
156- """In-place butterflies across the 31 long-block subband boundaries."""
157- xr = xr.copy()
158- for sb in range(1, 32):
159- for i in range(8):
160- lo = sb * 18 - 1 - i
161- hi = sb * 18 + i
162- a, b = xr[lo], xr[hi]
163- xr[lo] = a * ALIAS_CS[i] - b * ALIAS_CA[i]
164- xr[hi] = b * ALIAS_CS[i] + a * ALIAS_CA[i]
165- return xr
166-
167-
168-def granules_to_subband(granule_spectra):
169- """Requantised spectra (long blocks) -> subband samples [slot][32]."""
170- overlap = np.zeros((32, 18))
171- slots = []
172- for xr in granule_spectra:
173- xr = alias_reduce(xr)
174- block = np.zeros((18, 32))
175- for sb in range(32):
176- y = imdct36(xr[sb * 18: sb * 18 + 18]) * WIN_NORMAL
177- block[:, sb] = y[:18] + overlap[sb]
178- overlap[sb] = y[18:]
179- for t in range(18):
180- for sb in range(1, 32, 2):
181- if t % 2 == 1:
182- block[t, sb] = -block[t, sb]
183- slots.extend(block)
184- return np.array(slots)
185-
186-
187-def synthesis_basis(slots):
188- """Per output sample, the 512 coefficients multiplying D (the window).
189-
190- Returns an (nsamples, 512) matrix A with pcm = A @ D.
191- """
192- nslots = len(slots)
193- N = np.array([[math.cos((16 + i) * (2 * k + 1) * math.pi / 64) for k in range(32)]
194- for i in range(64)])
195- blocks = slots @ N.T # [slot][64] V blocks
196- A = np.zeros((nslots * 32, 512))
197- for t in range(nslots):
198- for j in range(32):
199- row = A[t * 32 + j]
200- for i in range(16):
201- p = j + 32 * i
202- a, b = divmod(p, 64)
203- m = 2 * a + (1 if b >= 32 else 0)
204- s = t - m
205- if s >= 0:
206- row[p] = blocks[s][b]
207- return A
208-
209-
210-def synthesise(slots, D):
211- return synthesis_basis(slots) @ D
scripts/mp3-tables/probe_engine.pydeleted+0 -54
@@ -1,54 +0,0 @@
1-"""Batch probe runner: many one-pair probes per ffmpeg invocation."""
2-
3-import numpy as np
4-from mp3probe import Granule, frame_bytes, ffmpeg_decode
5-
6-GLOBAL_GAIN = 150
7-SCALE = 2.0 ** ((GLOBAL_GAIN - 210) / 4.0)
8-PART2_3 = 48
9-
10-
11-class Engine:
12- def __init__(self, Minv):
13- self.Minv = Minv
14-
15- def run(self, probes):
16- """probes: list of (bits, table_select, big_values, count1table_select).
17-
18- Returns one array of 576 requantised coefficients per probe.
19- """
20- stream = b""
21- for i in range(0, len(probes), 2):
22- pair = probes[i:i + 2]
23- grans, mains = [], []
24- for bits, tsel, bigv, c1 in pair:
25- bits = list(bits) + [0] * (PART2_3 - len(bits))
26- grans.append(Granule(part2_3_length=PART2_3, big_values=bigv,
27- global_gain=GLOBAL_GAIN,
28- table_select=(tsel, tsel, tsel),
29- count1table_select=c1))
30- mains.append(bits[:PART2_3])
31- while len(grans) < 2:
32- grans.append(Granule())
33- mains.append([])
34- stream += frame_bytes(grans, mains)
35- stream += frame_bytes([Granule(), Granule()], [[], []])
36- pcm, err = ffmpeg_decode(stream)
37- nframes = (len(probes) + 1) // 2
38- assert len(pcm) >= nframes * 2304, (len(pcm), nframes * 2304, err)
39- windows = np.stack([pcm[i * 2304:(i + 1) * 2304] for i in range(nframes)])
40- coeffs = windows @ self.Minv # (nframes, 1152)
41- out = []
42- for i in range(len(probes)):
43- out.append(coeffs[i // 2][(i % 2) * 576:((i % 2) + 1) * 576])
44- return out
45-
46-
47-def values(xr, n):
48- """First n integer magnitudes of a recovered granule."""
49- mag = np.abs(xr[:n]) / SCALE
50- return np.round(np.power(np.maximum(mag, 0.0), 0.75)).astype(np.int64)
51-
52-
53-def signs(xr, n):
54- return np.sign(xr[:n]).astype(np.int64)
scripts/raw_to_y4m.pydeleted+0 -63
@@ -1,63 +0,0 @@
1-#!/usr/bin/env python3
2-"""Wrap raw planar yuv420p frames into a minimal y4m (for vpxenc).
3-
4- ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m DEPTH
5-
6-DEPTH (8, 10 or 12) is REQUIRED and is the number of BYTES per sample in the
7-raw stream on stdin, not the stream's bit depth: ffmpeg's rawvideo muxer
8-never packs to the bit depth, it uses 1 byte for `yuv420p` and 2 bytes for
9-`yuv420p10le` / `yuv420p12le`. This script has no parser and no way to learn
10-it, so the depth is an ASSERTED argument: it is checked against the stdin
11-length, and a mismatch is a hard error naming the depth, the byte count it
12-implied, and the misframed y4m it would have produced. The old version
13-computed `w*h*3//2` unconditionally, so a 10-bit stream (2 bytes per sample)
14-was cut into frames at half length, the chroma planes of frame N+1 were read
15-as the tail of frame N, and the last partial frame was dropped silently --
16-a y4m that vpxenc accepts and encodes, with no error anywhere.
17-
18-The y4m header's `C` tag follows the same argument, so the wrapped stream
19-carries the depth it actually has.
20-
21-LIMIT, stated because it cannot be fixed here: raw planar video carries NO
22-depth of its own, so the length check below can only catch a stream whose
23-byte count is not a whole number of frames at the claimed depth. A 10-bit
24-stream of N frames is exactly 2N 8-bit frames, and no length test can tell
25-those apart -- that case is caught only by the caller asserting the right
26-DEPTH, which is why DEPTH is required and not defaulted.
27-"""
28-
29-import sys
30-
31-
32-if len(sys.argv) != 6:
33- sys.exit(
34- "usage: raw_to_y4m.py W H FPS out.y4m DEPTH "
35- "(DEPTH = 8|10|12, the BYTES per sample on stdin)"
36- )
37-w, h, fps, out, depth = sys.argv[1:6]
38-try:
39- depth = int(depth)
40-except ValueError:
41- sys.exit(f"raw_to_y4m.py: DEPTH {depth!r} is not a number (8, 10 or 12)")
42-if depth not in (8, 10, 12):
43- sys.exit(
44- f"raw_to_y4m.py: DEPTH {depth} is not 8, 10 or 12 -- the frame size below would be "
45- "wrong and every frame after the first would be misframed"
46- )
47-bpp = 1 if depth == 8 else 2
48-frame = int(w) * int(h) * 3 // 2 * bpp
49-raw = sys.stdin.buffer.read()
50-if len(raw) % frame:
51- sys.exit(
52- f"raw_to_y4m.py: stdin is {len(raw)} bytes, not a whole number of "
53- f"{int(w)}x{int(h)} 4:2:0 frames at {depth}-bit ({bpp} bytes per sample, "
54- f"{frame} bytes each): {len(raw) % frame} trailing bytes. At the other depth a "
55- f"frame would be {int(w) * int(h) * 3 // 2 * (3 - bpp)} bytes and each frame would "
56- "carry half a frame of the next one's planes. Refusing to write a misframed y4m."
57- )
58-ctag = {8: "C420jpeg", 10: "C420p10", 12: "C420p12"}[depth]
59-with open(out, "wb") as f:
60- f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 {ctag}\n".encode())
61- for i in range(len(raw) // frame):
62- f.write(b"FRAME\n")
63- f.write(raw[i * frame : (i + 1) * frame])
scripts/run422-ffmpeg.pydeleted+0 -54
@@ -1,54 +0,0 @@
1-#!/usr/bin/env python3
2-"""Driver: decode a cell with our decode_probe (EC_AV1_FINAL_DUMP) and compare
3-against ffmpeg, per plane, per frame. Geometry from the sequence header."""
4-import json
5-import os
6-import subprocess
7-import sys
8-
9-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10-import cmpff # noqa: E402
11-
12-PROBE = "/home/user/.cache/probes/decode_probe-main-8aedb701"
13-WORK = "/home/user/.cache/seed422"
14-
15-
16-def decode_ours(name, path, extra_env=None):
17- d = os.path.join(WORK, name)
18- os.makedirs(d, exist_ok=True)
19- for f in os.listdir(d):
20- os.remove(os.path.join(d, f))
21- prefix = os.path.join(d, "ours")
22- env = dict(os.environ, EC_AV1_FINAL_DUMP=prefix)
23- env.update(extra_env or {})
24- r = subprocess.run([PROBE, path], stdout=subprocess.PIPE,
25- stderr=subprocess.STDOUT, timeout=3600, env=env)
26- out = r.stdout.decode("utf-8", "replace")
27- if "REFUSED:" in out:
28- return None, out.split("REFUSED:", 1)[1].strip().splitlines()[0]
29- return prefix, out
30-
31-
32-def one(name, path, want_hidden=None, keep=True):
33- prefix, out = decode_ours(name, path)
34- if prefix is None:
35- print(f"{name}: REFUSES: {out}")
36- return {"cell": name, "status": "REFUSES", "msg": out}
37- res, *_ = cmpff.run(name, path, prefix, want_hidden, json_out=False)
38- res["probe"] = out.strip().splitlines()[-1] if out.strip() else ""
39- return res
40-
41-
42-if __name__ == "__main__":
43- cells = json.load(open(sys.argv[1]))
44- out = []
45- for c in cells:
46- try:
47- res = one(c["name"], c["path"], c.get("hidden"))
48- except SystemExit as e:
49- res = {"cell": c["name"], "status": "COMPARATOR-ERROR", "msg": str(e)}
50- print(json.dumps({k: v for k, v in res.items()
51- if k not in ("per_decode_frame", "per_display_frame", "bbox")}),
52- flush=True)
53- out.append(res)
54- json.dump(out, open(sys.argv[2], "w"), indent=1)
scripts/shape422-diff.pydeleted+0 -28
@@ -1,28 +0,0 @@
1-import sys
2-import cmpff
3-def shape(cell, obu, frame_d=0, frame_s=0, planes=(1,2)):
4- w,h,ssx,ssy,depth,pix=cmpff.probe_geometry(obu)
5- bps=1 if depth<=8 else 2
6- sizes,fsz=cmpff.plane_spans(w,h,ssx,ssy,bps)
7- disp=cmpff.split(cmpff.ffmpeg_frames(obu,pix),sizes,fsz,cell)
8- a=open(f"/home/user/.cache/seed422/{cell}/ours.f{frame_d}",'rb').read()
9- b=disp[frame_s]
10- cw=-(-w>>ssx); ch=-(-h>>ssy)
11- print(f"== {cell} {w}x{h} d{depth} chroma {cw}x{ch} decode f{frame_d} vs display f{frame_s}")
12- for pi in planes:
13- name="YUV"[pi]
14- off=sum(sizes[:pi])*bps
15- blocks={}
16- for r in range(ch):
17- base=off+(r*cw)*bps
18- for c in range(cw):
19- if a[base+c*bps:base+(c+1)*bps]!=b[base+c*bps:base+(c+1)*bps]:
20- blocks.setdefault((r//8,c//8),[]).append((r%8,c%8))
21- print(f" {name}: {len(blocks)} 8x8 blocks wrong")
22- for k in sorted(blocks):
23- v=blocks[k]
24- rows=sorted({p[0] for p in v}); cols=sorted({p[1] for p in v})
25- print(f" blk(r{k[0]},c{k[1]}) abs rows {k[0]*8}..{k[0]*8+7} cols {k[1]*8}..{k[1]*8+7}"
26- f": {len(v)}/64 wrong, subrows {rows[0]}..{rows[-1]} subcols {cols[0]}..{cols[-1]}")
27-if __name__=="__main__":
28- shape(sys.argv[1], sys.argv[2], int(sys.argv[3]) if len(sys.argv)>3 else 0)
scripts/stress-mp4-fixtures.shdeleted+0 -33
@@ -1,33 +0,0 @@
1-#!/usr/bin/env bash
2-# stress-mp4-fixtures.sh: the multi-crate test command that once flaked on
3-# ec-mp4's fragmented-file test, run three times plus once at --test-threads=16.
4-# Every run starts from a cold fixture work directory (the derived mp4/mkv
5-# fixtures are made on first use), because the race only exists while those
6-# files are being written. Run it through scripts/remote-run.sh, which sets TMPDIR.
7-#
8-# scripts/remote-run.sh mp4fixturerace --host auto -- scripts/stress-mp4-fixtures.sh
9-#
10-# Exit 0 only if every run passes. Logs go to $TMPDIR/stress-mp4-<n>.log.
11-
12-set -uo pipefail
13-: "${TMPDIR:=/tmp}"
14-CRATES=(-p ec-h265 -p ec-vorbis -p ec-probe -p ec-ac3 -p oxideav-ac3 -p ec-mp4 -p ec-image -p ec-alac -p ec-mp3 -p ec-ogg)
15-
16-fail=0
17-run() {
18- local n=$1; shift
19- rm -rf "$TMPDIR/ec-mp4-tests" "$TMPDIR/ec-matroska-tests"
20- if cargo test --release "${CRATES[@]}" "$@" >"$TMPDIR/stress-mp4-$n.log" 2>&1; then
21- echo "run $n ($*): PASS"
22- else
23- echo "run $n ($*): FAIL, see $TMPDIR/stress-mp4-$n.log"
24- grep -E "panicked|packet [0-9]+|FAILED|failures:" "$TMPDIR/stress-mp4-$n.log" | head -10
25- fail=1
26- fi
27-}
28-
29-run 1
30-run 2
31-run 3
32-run 4 -- --test-threads=16
33-exit $fail
scripts/vp9-bench.shdeleted+0 -31
@@ -1,31 +0,0 @@
1-#!/usr/bin/env bash
2-# vp9-bench.sh: ec-vp9 decode throughput sweep. Run on a server through remote-run.sh.
3-#
4-# Usage: scripts/vp9-bench.sh [clip.ivf ...]
5-# Builds the decode_ivf example in release, then decodes each clip at 1, 2 and 4 tile
6-# threads. With no arguments it uses tile1080.ivf (fixtures/vp9-bench) and a libvpx-encoded
7-# 1080p30 testsrc2 clip with 4 tile columns, encoded here with ffmpeg.
8-# Prints one line per run: clip threads fps digest.
9-set -euo pipefail
10-cd "$(dirname "$0")/../crates/ec-vp9"
11-cargo build --release --example decode_ivf 2>&1 | tail -1
12-bin=$(cd ../.. && pwd)/target/release/examples/decode_ivf
13-[ -x "$bin" ] || bin=${CARGO_TARGET_DIR:-../../target}/release/examples/decode_ivf
14-tmp=${TMPDIR:-/tmp}/vp9bench
15-mkdir -p "$tmp"
16-clips=("$@")
17-if [ ${#clips[@]} -eq 0 ]; then
18- clips=("$HOME/fixtures/vp9-bench/tile1080.ivf")
19- if [ ! -s "$tmp/tile4-1080p30.ivf" ]; then
20- ffmpeg -v error -y -f lavfi -i testsrc2=size=1920x1080:rate=30 -t 10 \
21- -c:v libvpx-vp9 -tile-columns 2 -row-mt 1 -b:v 4M -deadline realtime -cpu-used 8 \
22- "$tmp/tile4-1080p30.ivf"
23- fi
24- clips+=("$tmp/tile4-1080p30.ivf")
25-fi
26-for clip in "${clips[@]}"; do
27- for t in 1 2 4; do
28- line=$("$bin" "$clip" "$t")
29- echo "$(basename "$clip") threads=$t $line"
30- done
31-done