diff --git a/Cargo.lock b/Cargo.lock index eeffe8cd..5a6ac0d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,3 +5,7 @@ version = 4 [[package]] name = "ec-core" version = "0.1.0" + +[[package]] +name = "oracle" +version = "0.1.0" diff --git a/scripts/fetch-vectors.sh b/scripts/fetch-vectors.sh new file mode 100755 index 00000000..2503dde8 --- /dev/null +++ b/scripts/fetch-vectors.sh @@ -0,0 +1,216 @@ +#!/usr/bin/env bash +# fetch-vectors.sh — download third-party conformance vectors into fixtures/vectors/. +# +# Vectors are NOT redistributed from this repo (fixtures/ is gitignored); only this +# script and scripts/vectors.sha256 are committed. Idempotent, checksum-verified, +# and graceful: a dead URL or offline network reports the set as FAILED and the +# script continues with the remaining sets. +# +# Usage: scripts/fetch-vectors.sh [set ...] (default: all sets) +# sets: h264-jvt hevc-jctvc opus-rfc6716 flac-xiph vorbis-xiph +# Env: EC_FIXTURES= (default /fixtures) + +set -uo pipefail + +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) +VEC=${EC_FIXTURES:-$ROOT/fixtures}/vectors +SUMS=$ROOT/scripts/vectors.sha256 +CURL=(curl -fsSL --retry 2 --retry-delay 2 --connect-timeout 20 --max-time 900) + +command -v curl >/dev/null || { echo "fetch-vectors: curl not found" >&2; exit 2; } +mkdir -p -- "$VEC" +touch -- "$SUMS" + +ok_sets=() +fail_sets=() +n_new=0 +n_have=0 +n_bad=0 + +# verify_or_record — checksum against scripts/vectors.sha256, or record it. +verify_or_record() { + local f=$1 rel=${1#"$VEC"/} want have + have=$(sha256sum -- "$f" | cut -d' ' -f1) + want=$(awk -v k="$rel" '$2 == k { print $1 }' "$SUMS") + if [ -z "$want" ]; then + printf '%s %s\n' "$have" "$rel" >>"$SUMS" + return 0 + fi + [ "$want" = "$have" ] && return 0 + echo "CHECKSUM MISMATCH $rel (want $want got $have)" >&2 + rm -f -- "$f" + n_bad=$((n_bad + 1)) + return 1 +} + +# fetch_list — parallel download of missing names. +fetch_list() { + local dest=$1 base=$2 + shift 2 + local name missing=() args=() rc=0 + mkdir -p -- "$dest" + for name in "$@"; do + if [ -s "$dest/$name" ]; then + verify_or_record "$dest/$name" && { n_have=$((n_have + 1)); continue; } + fi + missing+=("$name") + done + if [ "${#missing[@]}" -gt 0 ]; then + for name in "${missing[@]}"; do args+=(-O "$base/$name"); done + "${CURL[@]}" --parallel --parallel-max 4 --output-dir "$dest" "${args[@]}" || rc=1 + for name in "${missing[@]}"; do + if [ -s "$dest/$name" ] && verify_or_record "$dest/$name"; then + n_new=$((n_new + 1)) + else + rm -f -- "$dest/$name" + rc=1 + fi + done + fi + return "$rc" +} + +# fetch_archive — download + extract once. +fetch_archive() { + local dest=$1 url=$2 arc=$3 + mkdir -p -- "$dest" + if [ -s "$dest/$arc" ]; then + verify_or_record "$dest/$arc" || return 1 + n_have=$((n_have + 1)) + else + "${CURL[@]}" -o "$dest/$arc" "$url" || { rm -f -- "$dest/$arc"; return 1; } + verify_or_record "$dest/$arc" || return 1 + n_new=$((n_new + 1)) + fi + [ -e "$dest/.extracted" ] && return 0 + case $arc in + *.tar.gz | *.tgz) tar -xzf "$dest/$arc" -C "$dest" || return 1 ;; + *.zip) unzip -qo "$dest/$arc" -d "$dest" || return 1 ;; + *) return 0 ;; + esac + touch -- "$dest/.extracted" +} + +# extract_zips — unpack each .zip into / once (bitstream + ref yuv). +extract_zips() { + local dir=$1 z base + command -v unzip >/dev/null || { + echo "fetch-vectors: unzip not found — zips left packed in $dir" >&2 + return 0 + } + for z in "$dir"/*.zip; do + [ -e "$z" ] || continue + base=${z%.zip} + [ -d "$base" ] && continue + mkdir -p -- "$base" + unzip -qo "$z" -d "$base" || { + echo "fetch-vectors: unzip failed: $z" >&2 + rm -rf -- "$base" + } + done +} + +run_set() { + local name=$1 + shift + if "$@"; then ok_sets+=("$name"); else fail_sets+=("$name"); fi +} + +# ------------------------------------------------------------- h264-jvt ----- +# JVT/ITU-T H.264.1 conformance bitstreams (the set openh264 & ffmpeg are checked +# against). 35-stream feature-covering subset: CAVLC/CABAC, MBAFF/PAFF, I_PCM, +# weighted pred, long-term refs, multiple slice groups, redundant slices. +JVT_BASE=https://www.itu.int/wftp3/av-arch/jvt-site/draft_conformance/AVCv1 +JVT_STREAMS=( + AUD_MW_E.zip BA1_Sony_D.zip BA3_SVA_C.zip BA_MW_D.zip BANM_MW_D.zip + BASQP1_Sony_C.zip CABA1_SVA_B.zip CABA2_SVA_B.zip CABA3_SVA_B.zip + CACQP3_Sony_D.zip CAMACI3_Sony_C.zip CAMASL3_Sony_B.zip CANL1_SVA_B.zip + CANL2_SVA_B.zip CANL3_SVA_B.zip CANL4_SVA_B.zip CI_MW_D.zip CVFI1_SVA_C.zip + CVFI2_SVA_C.zip CVMAQP2_Sony_G.zip CVMAQP3_Sony_D.zip CVPCMNL2_SVA_C.zip + FI1_Sony_E.zip FM2_SVA_C.zip MIDR_MW_D.zip MR1_BT_A.zip MR9_BT_B.zip + NL1_Sony_D.zip NL3_SVA_E.zip NRF_MW_E.zip SL1_SVA_B.zip SVA_BA2_D.zip + SVA_CL1_E.zip SVA_FM1_E.zip SVA_NL2_E.zip +) + +# ----------------------------------------------------------- hevc-jctvc ----- +# JCT-VC HEVC_v1 conformance suite. NOTE: "class A/B" names the CTC *test +# sequences* (Traffic/Kimono/...), not conformance bitstreams — the redistributable +# conformance set is feature-named, so this is a feature-covering subset incl. the +# Main10 streams needed for the 10-bit/P010 HW path. +HEVC_BASE=https://www.itu.int/wftp3/av-arch/jctvc-site/bitstream_exchange/draft_conformance/HEVC_v1 +HEVC_STREAMS=( + AMP_A_Samsung_7.zip AMVP_A_MTK_4.zip BUMPING_A_ericsson_1.zip + CAINIT_A_SHARP_4.zip CIP_A_Panasonic_3.zip CONFWIN_A_Sony_1.zip + DBLK_A_SONY_3.zip DBLK_A_MAIN10_VIXS_4.zip DELTAQP_A_BRCM_4.zip + DSLICE_A_HHI_5.zip ENTP_A_QUALCOMM_1.zip FILLER_A_Sony_1.zip + INITQP_A_Sony_1.zip INITQP_B_Main10_Sony_1.zip ipcm_A_NEC_3.zip + IPRED_A_docomo_2.zip MAXBINS_A_TI_5.zip MERGE_A_TI_3.zip + PICSIZE_A_Bossen_1.zip POC_A_Bossen_3.zip RAP_A_docomo_6.zip + RPS_A_docomo_5.zip RQT_A_HHI_4.zip SAO_A_MediaTek_4.zip SDH_A_Orange_4.zip + SLICES_A_Rovi_3.zip TILES_A_Cisco_2.zip TSKIP_A_MS_3.zip + TSUNEQBD_A_MAIN10_Technicolor_2.zip WPP_A_ericsson_MAIN_2.zip + WPP_A_ericsson_MAIN10_2.zip WP_A_MAIN10_Toshiba_3.zip +) + +# ---------------------------------------------------------- vorbis-xiph ----- +# Xiph's own Vorbis I decoder test vectors (chained streams, LSP edge cases, +# 48k mono, sample-rate oddities). +VORBIS_BASE=https://people.xiph.org/~xiphmont/test-vectors/vorbis +VORBIS_FILES=( + 1.0-test.ogg 1.0.1-test.ogg 48k-mono.ogg beta3-test.ogg beta4-test.ogg + bimS-silence.ogg chain-test1.ogg chain-test2.ogg chain-test3.ogg + highrate-test.ogg lsp-test.ogg lsp-test2.ogg lsp-test3.ogg lsp-test4.ogg + moog.ogg one-entry-codebook-test.ogg out-of-spec-blocksize.ogg + rc1-test.ogg rc2-test.ogg rc3-test.ogg singlemap-test.ogg sleepzor.ogg + test-short.ogg test-short2.ogg unused-mode-test.ogg +) + +SETS=("$@") +[ "${#SETS[@]}" -eq 0 ] && SETS=(h264-jvt hevc-jctvc opus-rfc6716 flac-xiph vorbis-xiph) + +for s in "${SETS[@]}"; do + case $s in + h264-jvt) + run_set "$s" fetch_list "$VEC/h264-jvt" "$JVT_BASE" "${JVT_STREAMS[@]}" + extract_zips "$VEC/h264-jvt" + ;; + hevc-jctvc) + run_set "$s" fetch_list "$VEC/hevc-jctvc" "$HEVC_BASE" "${HEVC_STREAMS[@]}" + extract_zips "$VEC/hevc-jctvc" + ;; + opus-rfc6716) + # RFC 6716 / 8251 decoder test vectors (opus_compare reference set). + run_set "$s" fetch_archive "$VEC/opus-rfc6716" \ + https://opus-codec.org/testvectors/opus_testvectors.tar.gz \ + opus_testvectors.tar.gz + ;; + flac-xiph) + # IETF cellar WG FLAC test files (supersedes the old svn.xiph.org set; + # carries the RFC 9639 subset + uncommon-but-legal stream shapes). + run_set "$s" fetch_archive "$VEC/flac-xiph" \ + https://codeload.github.com/ietf-wg-cellar/flac-test-files/tar.gz/refs/heads/main \ + flac-test-files.tar.gz + ;; + vorbis-xiph) + run_set "$s" fetch_list "$VEC/vorbis-xiph" "$VORBIS_BASE" "${VORBIS_FILES[@]}" + ;; + *) + echo "unknown set: $s" >&2 + fail_sets+=("$s") + ;; + esac +done + +printf '\n%s\n' "== vectors: $VEC ==" +for s in "${ok_sets[@]:-}"; do + [ -n "$s" ] || continue + printf 'OK %-14s files=%s bytes=%s\n' "$s" \ + "$(find "$VEC/$s" -type f ! -name .extracted 2>/dev/null | wc -l)" \ + "$(du -sb "$VEC/$s" 2>/dev/null | cut -f1)" +done +for s in "${fail_sets[@]:-}"; do + [ -n "$s" ] && printf 'FAILED %-14s (network or dead URL — rerun to resume)\n' "$s" +done +printf 'downloaded=%s already-present=%s checksum-mismatch=%s sets-ok=%s sets-failed=%s\n' \ + "$n_new" "$n_have" "$n_bad" "${#ok_sets[@]}" "${#fail_sets[@]}" +[ "${#fail_sets[@]}" -eq 0 ] && [ "$n_bad" -eq 0 ] diff --git a/scripts/gen-fixtures.sh b/scripts/gen-fixtures.sh new file mode 100755 index 00000000..3090ca4f --- /dev/null +++ b/scripts/gen-fixtures.sh @@ -0,0 +1,167 @@ +#!/usr/bin/env bash +# gen-fixtures.sh — deterministic ffmpeg-generated media fixtures for edith_codecs. +# +# ffmpeg is ORACLE/test-input tooling only; no ec-* crate depends on it at runtime. +# Idempotent: non-empty outputs are skipped, partial outputs are deleted on failure. +# Content is deterministic (sine tones per channel, testsrc2) so regenerating on +# another machine with the same ffmpeg yields the same bytes. +# +# Usage: scripts/gen-fixtures.sh [-f] (-f: regenerate everything) +# Env: EC_FIXTURES= (default /fixtures) + +set -uo pipefail + +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} +DUR_A=3 +DUR_V=2 +FORCE=0 +[ "${1:-}" = "-f" ] && FORCE=1 + +command -v ffmpeg >/dev/null || { echo "gen-fixtures: ffmpeg not found" >&2; exit 2; } + +TMPLOG=$(mktemp) || exit 2 +trap 'rm -f "$TMPLOG"' EXIT + +n_made=0 +n_skip=0 +failed=() +unsupported=() + +# gen +gen() { + local out=$1 + shift + if [ "$FORCE" -eq 0 ] && [ -s "$out" ]; then + n_skip=$((n_skip + 1)) + return 0 + fi + mkdir -p -- "$(dirname -- "$out")" + if ffmpeg -nostdin -y -v error "$@" "$out" 2>"$TMPLOG"; then + n_made=$((n_made + 1)) + + return 0 + fi + rm -f -- "$out" + failed+=("${out#"$FIXTURES"/}: $(tr '\n' ' ' <"$TMPLOG" | cut -c1-140)") + return 1 +} + +# ---------------------------------------------------------------- audio ----- +# Per-channel distinct frequencies: lets the oracle catch channel-order bugs +# (5.1 order FL,FR,FC,LFE,BL,BR) that identical-tone fixtures hide. +FREQS=(220 440 660 55 880 1320) + +# build_audio_in -> sets AIN[] and AMAP[] +build_audio_in() { + local nch=$1 rate=$2 i lbl="" layout + AIN=() + for ((i = 0; i < nch; i++)); do + AIN+=(-f lavfi -i "sine=frequency=${FREQS[i]}:sample_rate=${rate}:duration=${DUR_A}") + done + if [ "$nch" -eq 1 ]; then + AMAP=(-map 0:a) + return + fi + for ((i = 0; i < nch; i++)); do lbl="${lbl}[${i}:a]"; done + case $nch in + 2) layout=stereo ;; + 6) layout=5.1 ;; + *) layout=$nch ;; + esac + AMAP=(-filter_complex "${lbl}join=inputs=${nch}:channel_layout=${layout}[a]" -map "[a]") +} + +# name|ext|encoder args +AUDIO_CODECS=( + "wav16|wav|-c:a pcm_s16le" + "flac|flac|-c:a flac -compression_level 5" + "mp3|mp3|-c:a libmp3lame -b:a 192k" + "aac-adts|aac|-c:a aac -b:a 160k" + "aac-mp4|mp4|-c:a aac -b:a 160k" + "ac3|ac3|-c:a ac3 -b:a 448k" + "eac3|eac3|-c:a eac3 -b:a 448k" + "vorbis-ogg|ogg|-c:a libvorbis -q:a 5" + "opus-ogg|opus|-c:a libopus -b:a 160k -vbr on" + "alac-mp4|m4a|-c:a alac" +) +LAYOUTS=("mono|1" "stereo|2" "5.1|6") +RATES=(44100 48000) + +for spec in "${AUDIO_CODECS[@]}"; do + IFS='|' read -r cname cext cargs <<<"$spec" + read -r -a CARGS <<<"$cargs" + for lspec in "${LAYOUTS[@]}"; do + IFS='|' read -r lname nch <<<"$lspec" + for rate in "${RATES[@]}"; do + # Encoder capability gates — a skipped combo is reported, never silent. + if [ "$cname" = "mp3" ] && [ "$nch" -gt 2 ]; then + unsupported+=("audio/${cname}-${lname}-${rate}: libmp3lame is mono/stereo only") + continue + fi + if [ "$cname" = "opus-ogg" ] && [ "$rate" != 48000 ]; then + unsupported+=("audio/${cname}-${lname}-${rate}: libopus encodes at 48 kHz only") + continue + fi + build_audio_in "$nch" "$rate" + gen "$FIXTURES/audio/${cname}-${lname}-${rate}.${cext}" \ + "${AIN[@]}" "${AMAP[@]}" "${CARGS[@]}" -ar "$rate" + done + done +done + +# ---------------------------------------------------------------- video ----- +# name|encoder|extra args|pix_fmts (comma-separated) +VIDEO_CODECS=( + "h264|libx264|-preset ultrafast -crf 23|yuv420p" + "hevc|libx265|-preset ultrafast -crf 28 -x265-params log-level=error|yuv420p,yuv420p10le" + "vp9|libvpx-vp9|-deadline realtime -cpu-used 8 -row-mt 1 -b:v 0 -crf 32|yuv420p,yuv420p10le" + "av1|librav1e|-speed 10 -qp 100|yuv420p,yuv420p10le" +) +FPS=("23.976|24000/1001" "60|60") +CONTAINERS=(mp4 mkv) + +# gen_video +gen_video() { + local codec=$1 enc=$2 extra=$3 pix=$4 fpstag=$5 fpsval=$6 size=$7 restag=$8 cont=$9 + local depth=8 tag=() + case $pix in *10le) depth=10 ;; esac + [ "$codec" = hevc ] && [ "$cont" = mp4 ] && tag=(-tag:v hvc1) + local ex=() + read -r -a ex <<<"$extra" + gen "$FIXTURES/video/${codec}-${restag}-${fpstag}-${depth}bit.${cont}" \ + -f lavfi -i "testsrc2=size=${size}:rate=${fpsval}:duration=${DUR_V}" \ + -pix_fmt "$pix" -c:v "$enc" "${ex[@]}" "${tag[@]}" +} + +for spec in "${VIDEO_CODECS[@]}"; do + IFS='|' read -r vname venc vextra vpixs <<<"$spec" + IFS=',' read -r -a PIXS <<<"$vpixs" + for pix in "${PIXS[@]}"; do + for fspec in "${FPS[@]}"; do + IFS='|' read -r ftag fval <<<"$fspec" + for cont in "${CONTAINERS[@]}"; do + gen_video "$vname" "$venc" "$vextra" "$pix" "$ftag" "$fval" 1920x1080 1080p "$cont" + done + done + done + # One 4K sample per codec (8-bit, mp4, 23.976) — size/stride edge cases. + gen_video "$vname" "$venc" "$vextra" yuv420p 23.976 24000/1001 3840x2160 2160p mp4 +done + +# -------------------------------------------------------------- summary ----- +printf '\n%s\n' "== fixtures: $FIXTURES ==" +printf '%-42s %10s %s\n' FILE SIZE PROBE +total=0 +while IFS= read -r f; do + total=$((total + 1)) + sz=$(stat -c %s -- "$f") + p=$(ffprobe -v error -show_entries stream=codec_name,channels,sample_rate,width,height,pix_fmt \ + -of default=nw=1:nk=1 "$f" 2>/dev/null | tr '\n' ' ') + printf '%-42s %10s %s\n' "${f#"$FIXTURES"/}" "$sz" "$p" +done < <(find "$FIXTURES/audio" "$FIXTURES/video" -type f 2>/dev/null | sort) + +printf '\n%s\n' "total=$total generated=$n_made skipped-existing=$n_skip unsupported=${#unsupported[@]} failed=${#failed[@]}" +for u in "${unsupported[@]:-}"; do [ -n "$u" ] && printf 'UNSUPPORTED %s\n' "$u"; done +for e in "${failed[@]:-}"; do [ -n "$e" ] && printf 'FAILED %s\n' "$e"; done +[ "${#failed[@]}" -eq 0 ] || exit 1 diff --git a/scripts/scan-real-library.sh b/scripts/scan-real-library.sh new file mode 100755 index 00000000..2e3deed8 --- /dev/null +++ b/scripts/scan-real-library.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# scan-real-library.sh — ffprobe sweep of the user's real media library. +# +# READ-ONLY on the scanned directories; the only thing written is the manifest +# under fixtures/ (gitignored — regenerable). The manifest is the T3 gate input: +# every codec/container claim in this repo is checked against these files, not +# only against synthetic fixtures. +# +# Usage: scripts/scan-real-library.sh [dir ...] (default: ~/Videos ~/Downloads) +# Env: EC_FIXTURES= (default /fixtures) +# Out: fixtures/real-library-manifest.tsv +# columns: path container vcodec width height pix_fmt bit_depth acodecs duration size + +set -uo pipefail + +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} +OUT=$FIXTURES/real-library-manifest.tsv + +command -v ffprobe >/dev/null || { echo "scan-real-library: ffprobe not found" >&2; exit 2; } + +DIRS=("$@") +[ "${#DIRS[@]}" -eq 0 ] && DIRS=("$HOME/Videos" "$HOME/Downloads") + +EXTS=(mp4 m4v mov mkv webm avi flv ts m2ts mts wmv ogv + mp3 m4a aac flac wav ogg oga opus wma ac3 eac3 alac aif aiff) + +mkdir -p -- "$FIXTURES" +tmp=$(mktemp) || exit 2 +trap 'rm -f "$tmp"' EXIT + +# Build the -iname predicate list once. +find_args=() +for e in "${EXTS[@]}"; do find_args+=(-iname "*.$e" -o); done +unset 'find_args[${#find_args[@]}-1]' + +# field — "" when absent or N/A. +field() { + local v + v=$(printf '%s\n' "$2" | sed -n "s/^$1=//p" | head -n1) + [ "$v" = "N/A" ] && v="" + printf '%s' "$v" +} + +n=0 +nerr=0 +{ + printf 'path\tcontainer\tvcodec\twidth\theight\tpix_fmt\tbit_depth\tacodecs\tduration\tsize\n' + while IFS= read -r -d '' f; do + # Key=value form (not nk=1): a field ffprobe omits must not shift the others. + fmt=$(ffprobe -v error -show_entries format=format_name,duration \ + -of default=nw=1 "$f" 2>/dev/null) + if [ -z "$fmt" ]; then + nerr=$((nerr + 1)) + printf '%s\tUNREADABLE\t-\t-\t-\t-\t-\t-\t-\t%s\n' "$f" "$(stat -c %s -- "$f")" + continue + fi + container=$(field format_name "$fmt") + duration=$(field duration "$fmt") + v=$(ffprobe -v error -select_streams v:0 \ + -show_entries stream=codec_name,width,height,pix_fmt,bits_per_raw_sample \ + -of default=nw=1 "$f" 2>/dev/null) + vcodec=$(field codec_name "$v") + vw=$(field width "$v") + vh=$(field height "$v") + vpix=$(field pix_fmt "$v") + vbits=$(field bits_per_raw_sample "$v") + # bits_per_raw_sample is often absent/0 — fall back to the pix_fmt suffix. + if [ -z "$vbits" ] || [ "$vbits" = "N/A" ] || [ "$vbits" = 0 ]; then + case $vpix in + *12le | *12be) vbits=12 ;; + *10le | *10be) vbits=10 ;; + "") vbits="" ;; + *) vbits=8 ;; + esac + fi + acodecs=$(ffprobe -v error -select_streams a -show_entries stream=codec_name \ + -of default=nw=1:nk=1 "$f" 2>/dev/null | paste -sd, -) + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "$f" "${container:--}" "${vcodec:--}" "${vw:--}" "${vh:--}" \ + "${vpix:--}" "${vbits:--}" "${acodecs:--}" "${duration:--}" \ + "$(stat -c %s -- "$f")" + n=$((n + 1)) + done < <(find "${DIRS[@]}" -type f \( "${find_args[@]}" \) -print0 2>/dev/null) +} >"$tmp" + +mv -- "$tmp" "$OUT" +trap - EXIT + +printf '%s\n' "== $OUT ==" +printf 'scanned=%s unreadable=%s\n\n' "$((n + nerr))" "$nerr" +printf 'containers:\n' +tail -n +2 "$OUT" | cut -f2 | sort | uniq -c | sort -rn +printf '\nvideo codecs:\n' +tail -n +2 "$OUT" | cut -f3 | sort | uniq -c | sort -rn +printf '\naudio codecs (per file, comma-joined):\n' +tail -n +2 "$OUT" | cut -f8 | tr ',' '\n' | sort | uniq -c | sort -rn +printf '\nbit depths:\n' +tail -n +2 "$OUT" | cut -f7 | sort | uniq -c | sort -rn diff --git a/scripts/vectors.sha256 b/scripts/vectors.sha256 new file mode 100644 index 00000000..3108e142 --- /dev/null +++ b/scripts/vectors.sha256 @@ -0,0 +1,94 @@ +ecaed4a05d02c8ffc0ec7dd02a640f87ba9d9f8c2dab3273ef1d6da3d7f8568e h264-jvt/AUD_MW_E.zip +399eae2eb03f82fc291bdc4fe9cedd110b40a96368ffe1e1bcf9ff6436fa9df7 h264-jvt/BA1_Sony_D.zip +1c7003ff7b4507204f50e0b279149fd183c0890ee2a12c4c2d008db387299b82 h264-jvt/BA3_SVA_C.zip +f85d0c1e6a8317ecff19bf11d1496b327ee11e391de27453031062ea62241843 h264-jvt/BA_MW_D.zip +b50e2e7ca2a355087e9d993174626a027cea2da5f84f704cc0b2c6cb9145dfbd h264-jvt/BANM_MW_D.zip +f7cdbfaee43ff2e88b78d0b41ddcde83ac5148867e7b7df1759d97e0294f6c19 h264-jvt/BASQP1_Sony_C.zip +d0cf94006df2319a6c98683a6013f85ea5a1c0d382c796523b751c263e8c8989 h264-jvt/CABA1_SVA_B.zip +68c700914c0926b5dcb75ef3fe601a3434c1de3af6c4906a3573baf9998752db h264-jvt/CABA2_SVA_B.zip +375996d3de61bf6f7a58f48c46a477804636d118fe743501eef48c04fb3993cf h264-jvt/CABA3_SVA_B.zip +c8efdbc5d0af62b99d1e357717c26eb34ed13f3cf8bacb04a60bf87a0bd2a054 h264-jvt/CACQP3_Sony_D.zip +da020750950a89277ff10b53d5983ab525d61ba9b180562fc4fc1da9af721227 h264-jvt/CAMACI3_Sony_C.zip +4e675b3701e5ed42c7f94c8d04ec755111a2bb595a759e512dc1361fb2f59ccd h264-jvt/CAMASL3_Sony_B.zip +2f364e4ff117f9fce0b55ae417f2f5ee992d6e4042e207eed0a212b71580ae27 h264-jvt/CANL1_SVA_B.zip +0936f0816c5b44e0115c5dcea65717c678f3de8cf858308283f1328358733186 h264-jvt/CANL2_SVA_B.zip +2398eca7b8da95820ccb025b37c1103d8abd9f9a06eb45ccc3b9704ab1f2ff2e h264-jvt/CANL3_SVA_B.zip +a19e259438917a68f026de4045eff25d2dfe416c081d215bca40901214617cab h264-jvt/CANL4_SVA_B.zip +6e41825983037e3af50a3e4add6ac9dbde3ea6f41ab6f77cc432de22a2920d49 h264-jvt/CI_MW_D.zip +3f3da0c2ae0400e9549af1bea567ee0833db3141d39b2d10e7612f8c246029de h264-jvt/CVFI1_SVA_C.zip +0c46afd124d9931ad349e9355e405f9f61b2f168223618691d023ab8e04a2877 h264-jvt/CVFI2_SVA_C.zip +7ba8640b584bcf5d96e942800b9f2e6a70d4fefa4c70768913c7cb559ddcd379 h264-jvt/CVMAQP2_Sony_G.zip +867360dcec6f9da7572be6717e20182ed5ff7fb574ba665b0d22fce4fb106822 h264-jvt/CVMAQP3_Sony_D.zip +90b0574aa7d02f8b250c4997b78fd4f112983fd3eb9eb7c12df6d5b7560ceb1d h264-jvt/CVPCMNL2_SVA_C.zip +9ce036bcd91bf89aa6256b4d5461231e74f8482dcf76bed075abddbcf4108f9f h264-jvt/FI1_Sony_E.zip +7e27a8776c70e47e4b4441809a6ec23c8a62e1a06eea364a6407839fc8650d4f h264-jvt/FM2_SVA_C.zip +69e7d04bd4b782f93401b12b79d58a96b39319d932743af8bc7134c752d6b577 h264-jvt/MIDR_MW_D.zip +a76d4e199e6ffb27292d1a07c516e5adea251e63e3f756de490c153b23d4684d h264-jvt/MR1_BT_A.zip +fd10a0be32f6fbe5d35e4a4b73707af97b3d8c1999bc5680c53d7068c20bf72e h264-jvt/MR9_BT_B.zip +1b26bfe8d05cf54b95e410779e48f90cc55305186e0c6184b5ea28ce9dc1b02d h264-jvt/NL1_Sony_D.zip +09d7a3fcf430e0635b55bc4308c56842863cdc1d52cc3e3ec6014487d13c1977 h264-jvt/NL3_SVA_E.zip +c48f067fe8ac1309b99292d024324a0a7561bf28312a133995a42d7a98ae9835 h264-jvt/NRF_MW_E.zip +60d61046c3aee6b9aa6b3dd4fad4081be9c959affec2bd641808632edffed1b2 h264-jvt/SL1_SVA_B.zip +e0cefee7e9206d06cad7bbdbe1441b6566208d693bcebc4396fa896be3a2c8d4 h264-jvt/SVA_BA2_D.zip +636098f10f2cdc80e31451b198c688bcc868fe536707c46ce2e0eaf54a33fa98 h264-jvt/SVA_CL1_E.zip +9db49088a67d960d1363605c40a603d38c87361f3b83e730e6541c5a1db4c10f h264-jvt/SVA_FM1_E.zip +f21e06d253b205aa65e796158daecfbcfc4ea2b5c41af1412f6bdd54a0a59977 h264-jvt/SVA_NL2_E.zip +3b8c7e4f77759351893470d87cd5c8252146ae19523786510914a9e8d5c7e340 hevc-jctvc/AMP_A_Samsung_7.zip +b89aa3d113bdff9aff61d4c190b9035155db44a9c9b08b5a40df89fde2e6a2c7 hevc-jctvc/AMVP_A_MTK_4.zip +3fef73e8e6263fd0f9f1bc6095e2a2cfba3451132e24f7ad08fa7c6510fafe5c hevc-jctvc/BUMPING_A_ericsson_1.zip +58d66213064bac9444cf13cc2f62d6f044bdb4d8ec9488640fb86090de976b43 hevc-jctvc/CAINIT_A_SHARP_4.zip +5c55b3594e5c951c9f5312913961750283eb2dadd15844fe35f9beb94a9a548c hevc-jctvc/CIP_A_Panasonic_3.zip +c3c823ffb9e526f5d9506ba2f1239b1f0323572850789230d762f4e4678fc298 hevc-jctvc/CONFWIN_A_Sony_1.zip +ce18cd42375359b9ff293d12a95793cc6b56eb75d899ad012c68e25dfa54dfbf hevc-jctvc/DBLK_A_SONY_3.zip +d86ec87f98fccbcec3758954a7cf430e8af8cf021d347dfbbed2f1d5dbb00f25 hevc-jctvc/DBLK_A_MAIN10_VIXS_4.zip +63abbbaf43d334d7952eab7bbc5b3e34b4ad0259eddcd63cdb164dbcf9a36ca6 hevc-jctvc/DELTAQP_A_BRCM_4.zip +c41c1a1e1e700af201eaf4cb0d11d4361b41ba0828e80c78d1835d1de187f80c hevc-jctvc/DSLICE_A_HHI_5.zip +66abdf60455ece468acf160274316c51dca3858d93a8ffce93646cbb5568fe43 hevc-jctvc/ENTP_A_QUALCOMM_1.zip +abf6cd7525378d2e1c8f32b67af01c594553c342c21dcd36ab677c3c77b528db hevc-jctvc/FILLER_A_Sony_1.zip +38b1d9396bab068fa701b08db73c3a900e893ef4cd00c82fc7b4d2b150a2f749 hevc-jctvc/INITQP_A_Sony_1.zip +c3f87037640953691dee02d4c9f28cd6a3b99de43e30bdcfdf583888191fa23e hevc-jctvc/INITQP_B_Main10_Sony_1.zip +89a71f4b9b7e22c481378f83bacc5aac6c8f204999691d3fa21f2804337e84c9 hevc-jctvc/ipcm_A_NEC_3.zip +5ee6e90cbcbf0547e43e72536ab39af1d831363f95c368c175267d6e48d264da hevc-jctvc/IPRED_A_docomo_2.zip +a6d1ed217b232aec8faff836c180a3368e5dd8ed3f8bf912c3527297ee89d498 hevc-jctvc/MAXBINS_A_TI_5.zip +b38d58301c0a8bd41ce982e40552850eabe9f140d2ff6ceca3375f9f5abc8a65 hevc-jctvc/MERGE_A_TI_3.zip +ffdffecff6ba03ce0220eb89e83bc3043af5953ab6864ad6acefee382e49ee7c hevc-jctvc/PICSIZE_A_Bossen_1.zip +aec93a088b81d68d87eda99e4a0e64bed7012b571158c8a2242223d1f9db8ccd hevc-jctvc/POC_A_Bossen_3.zip +5031bac0b1520ed826bf3112d000e59c76677c01dee706738af0d206cde031be hevc-jctvc/RAP_A_docomo_6.zip +45427f66400a033e7a47cc6ca9b21d456e9e06450db6ca8d8fa92c438125324b hevc-jctvc/RPS_A_docomo_5.zip +958d958baedbe4f2c864f5d9b3b87e69884170db403b4e190d1d33a0490ec3c6 hevc-jctvc/RQT_A_HHI_4.zip +e0b5c8f4ab4fb592971f06469db630d9e7ef72b4d37d729604e2fdaa9df706c9 hevc-jctvc/SAO_A_MediaTek_4.zip +ddf41877f10b47bad946712954e4a4b35cae435bac187d8c404c6bcfcb4acad0 hevc-jctvc/SDH_A_Orange_4.zip +d0141e111c1c854930eb16430cc5d3e5b82ccfa1458805fce20dd410b08c61ad hevc-jctvc/SLICES_A_Rovi_3.zip +bd63079966105a3bdac764979cb82b708f586cc7c34859a1d466e18cc6a5c345 hevc-jctvc/TILES_A_Cisco_2.zip +7f09bd323228975260b14c1b8e92cb15341771b29addd71cc0c2471d5e070a80 hevc-jctvc/TSKIP_A_MS_3.zip +615696a911a824988da0d883ab573fb673fd72bf45275d75549abc763602f814 hevc-jctvc/TSUNEQBD_A_MAIN10_Technicolor_2.zip +81c601e9301ba5f562ebf9918e73d1c7153e0a6fe8fa4509f61035a212188216 hevc-jctvc/WPP_A_ericsson_MAIN_2.zip +1827b7111a9ce76f6c04332b61cd24d9daf818fd203aa1d0b7d1087b9b83a6aa hevc-jctvc/WPP_A_ericsson_MAIN10_2.zip +26b3bc442265222032c1960cc02fe2bd55121fe933e70e5039521785073d33b2 hevc-jctvc/WP_A_MAIN10_Toshiba_3.zip +94ac78ca4f74c4e43bc9fe4ec1ad0aa36f38ab90f45b0727c40dd1e96096e767 opus-rfc6716/opus_testvectors.tar.gz +dae450db1ddd9d7773bc596bbca5d6cfd26e936eec48da9e1c2222f53e16526d flac-xiph/flac-test-files.tar.gz +9a882710314bcc1d2b4cdefb7f89911f4375acd1feb9e64a12eca9f7202377d3 vorbis-xiph/1.0-test.ogg +8c9423e00826d6d2457d78c09d6e2a94bcdf9216af796bb22a4c4f450c2e72bb vorbis-xiph/1.0.1-test.ogg +f51459d9bdd04ca3ec6f6732b8a01efcdc83e5c6fc79c7d5347527bfd4948e9e vorbis-xiph/48k-mono.ogg +7fc791a4d5a0d3b7cef2448093ccf2ae54600acc81667be90c6b209c366c32ea vorbis-xiph/beta3-test.ogg +bc367c0d4dcdbf1f0a2f81abf74cc52c8f0ab8366d150a75830782ca2dba080a vorbis-xiph/beta4-test.ogg +e2a38871d390ed651faf0fec5253a6873530da4f2503d85021c99325dfd23813 vorbis-xiph/bimS-silence.ogg +d9c37533a1f456d2a996755a43d112ef46b6ef953319913907bc79f1c014d79e vorbis-xiph/chain-test1.ogg +5b5bf834e93e9a93b7114be084161e972f33d2031963518492ba2c91dc4418a7 vorbis-xiph/chain-test2.ogg +ed039ba775d1b31e805d26d6413a3ef2c6663bf4c5ea47ce1462f8f23c84d8dc vorbis-xiph/chain-test3.ogg +0942c88369f84b125388cc8437575b66d67bc97baaeeb997b6602144821509df vorbis-xiph/highrate-test.ogg +ad1b07b68576ae2c85178475ef3607e1a96c09e96296cae83ee7a9726f8311eb vorbis-xiph/lsp-test.ogg +7b00f893a93071bdf243b8a22c1758a6ab09c1ab8eee89ca21659d98ec0f53ea vorbis-xiph/lsp-test2.ogg +7a5c4064fc31285f6fea0b2424a0d415a8b18ef13d1aa1ef931a429ab9a593d1 vorbis-xiph/lsp-test3.ogg +cb0b28931dfc8ef8b2d320f3028fab548171e7c6e94006f0c23532478a8d3596 vorbis-xiph/lsp-test4.ogg +bd5b51bb1d6855e0e990e3ebdd230fc16265407809bd6db44aea691ada498943 vorbis-xiph/moog.ogg +789b5146f2a7c0864a228ee4a870606a32c4169e22097be65129623705c54749 vorbis-xiph/one-entry-codebook-test.ogg +0970e66291744815f2ca0dec7523f5bbc112907c5c75978a0f91d3b0ed6f03b2 vorbis-xiph/out-of-spec-blocksize.ogg +ccfac6ac7c75615bec0632b94bcf088c027c0b112cd136c997d04f037252cd3d vorbis-xiph/rc1-test.ogg +4adcda786dfeea4188d7b1df35571dbe29c687f2d1cac680ed115353abfe1637 vorbis-xiph/rc2-test.ogg +edd984e84c7c2a59af7801f3e8d2db11a6619134fd8d0274d1289e70bf60cde7 vorbis-xiph/rc3-test.ogg +50d8077608a4192b8f8505aec0217be8b6c25def4068899afc19c17f30e1d521 vorbis-xiph/singlemap-test.ogg +01c67ecaf7a58b5ac5f1fe3bd060b5d61536595e97927a1b1cf0129a62b5cfcf vorbis-xiph/sleepzor.ogg +183510552403021fb90ce43796fcc88e16c8bb4ae5d0d72a316b8e51afc395fa vorbis-xiph/test-short.ogg +6bd3f59e0fa77904edd35c73dadd6558e2a36d78c9d7bc5db223862bf092fcc2 vorbis-xiph/test-short2.ogg +e27ae6fc2f7c0037c28328801c46d966abcee3050e3ebd40bf097f7986f50f94 vorbis-xiph/unused-mode-test.ogg diff --git a/tools/oracle/Cargo.toml b/tools/oracle/Cargo.toml new file mode 100644 index 00000000..483a9646 --- /dev/null +++ b/tools/oracle/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "oracle" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[[bin]] +name = "oracle" +path = "src/main.rs" + +# No dependencies on purpose: the oracle drives ffmpeg/ffprobe through std process +# pipes so that comparison tooling can never leak into any ec-* crate's dep graph. +[dependencies] diff --git a/tools/oracle/src/main.rs b/tools/oracle/src/main.rs new file mode 100644 index 00000000..62cb63cb --- /dev/null +++ b/tools/oracle/src/main.rs @@ -0,0 +1,577 @@ +//! `oracle` — ffmpeg-backed comparison harness for the edith_codecs family. +//! +//! ffmpeg/ffprobe are ORACLE tooling: they are driven here through `std::process` +//! pipes so no `ec-*` crate ever gains a media dependency, sync or async. +//! +//! Subcommands: +//! `bit-exact ` byte-identical check +//! `audio-compare ` per-channel correlation + RMS delta +//! `video-compare ` per-frame PSNR, min/mean +//! +//! `` is our decoder's raw output: interleaved f32 LE for audio, raw +//! planar/packed frames in `--pix-fmt` order for video. The reference is any file +//! ffmpeg can decode; it is decoded to the same raw layout and compared. +//! +//! stdout is TSV (every line `type...`), stderr is the human summary. +//! Exit code: 0 = PASS, 1 = FAIL, 2 = usage/IO error. + +use std::collections::HashMap; +use std::process::{Command, Stdio}; + +const USAGE: &str = "\ +oracle — comparison harness (ffmpeg is test tooling only) + + oracle bit-exact + oracle audio-compare [--channels N] [--min-corr F] [--max-rms F] + oracle video-compare [--pix-fmt FMT] [--size WxH] [--min-psnr DB] + +Defaults: --min-corr 0.999 --max-rms 1e-3 --min-psnr 40 +Missing --channels/--pix-fmt/--size are probed from with ffprobe. +"; + +fn main() { + let argv: Vec = std::env::args().skip(1).collect(); + let rc = match argv.first().map(String::as_str) { + Some("bit-exact") => run(cmd_bit_exact(&argv[1..])), + Some("audio-compare") => run(cmd_audio_compare(&argv[1..])), + Some("video-compare") => run(cmd_video_compare(&argv[1..])), + Some("-h") | Some("--help") => { + print!("{USAGE}"); + 0 + } + _ => { + eprint!("{USAGE}"); + 2 + } + }; + std::process::exit(rc); +} + +fn run(r: Result) -> i32 { + match r { + Ok(true) => 0, + Ok(false) => 1, + Err(e) => { + eprintln!("oracle: {e}"); + 2 + } + } +} + +// ------------------------------------------------------------------ args --- + +struct Args { + pos: Vec, + flags: HashMap, +} + +impl Args { + fn parse(argv: &[String]) -> Result { + let mut pos = Vec::new(); + let mut flags = HashMap::new(); + let mut it = argv.iter(); + while let Some(a) = it.next() { + if let Some(key) = a.strip_prefix("--") { + let v = it + .next() + .ok_or_else(|| format!("flag --{key} needs a value"))?; + flags.insert(key.to_string(), v.clone()); + } else { + pos.push(a.clone()); + } + } + Ok(Self { pos, flags }) + } + + fn num(&self, key: &str, default: T) -> Result { + match self.flags.get(key) { + None => Ok(default), + Some(v) => v.parse().map_err(|_| format!("bad --{key} value: {v}")), + } + } +} + +// --------------------------------------------------------------- ffmpeg ---- + +/// Decode `input` with ffmpeg and return the raw bytes it writes to stdout. +/// stderr is inherited so a large error log can never deadlock the pipe. +fn ffmpeg_raw(input: &str, extra: &[&str]) -> Result, String> { + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i", input]) + .args(extra) + .arg("-") + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .output() + .map_err(|e| format!("spawning ffmpeg: {e}"))?; + if !out.status.success() { + return Err(format!("ffmpeg failed on {input} ({})", out.status)); + } + if out.stdout.is_empty() { + return Err(format!("ffmpeg produced no data for {input}")); + } + Ok(out.stdout) +} + +/// `ffprobe -show_entries stream=` as a key -> value map (first stream wins). +fn ffprobe(input: &str, select: &str, entries: &str) -> Result, String> { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", select, "-show_entries"]) + .arg(format!("stream={entries}")) + .args(["-of", "default=nw=1"]) + .arg(input) + .stderr(Stdio::inherit()) + .output() + .map_err(|e| format!("spawning ffprobe: {e}"))?; + if !out.status.success() { + return Err(format!("ffprobe failed on {input} ({})", out.status)); + } + let mut map = HashMap::new(); + for line in String::from_utf8_lossy(&out.stdout).lines() { + if let Some((k, v)) = line.split_once('=') + && v != "N/A" + { + map.entry(k.to_string()).or_insert_with(|| v.to_string()); + } + } + Ok(map) +} + +fn read_file(path: &str) -> Result, String> { + std::fs::read(path).map_err(|e| format!("reading {path}: {e}")) +} + +// ------------------------------------------------------------ bit-exact ---- + +fn cmd_bit_exact(argv: &[String]) -> Result { + let a = Args::parse(argv)?; + if a.pos.len() != 2 { + return Err("bit-exact needs exactly two files".into()); + } + let (x, y) = (read_file(&a.pos[0])?, read_file(&a.pos[1])?); + let first_diff = x.iter().zip(&y).position(|(p, q)| p != q); + let pass = x.len() == y.len() && first_diff.is_none(); + + println!("meta\ta\t{}", a.pos[0]); + println!("meta\tb\t{}", a.pos[1]); + println!("meta\tlen_a\t{}", x.len()); + println!("meta\tlen_b\t{}", y.len()); + match first_diff { + Some(off) => println!("diff\tfirst_offset\t{off}"), + None => println!("diff\tfirst_offset\t-"), + } + println!("verdict\t{}", if pass { "PASS" } else { "FAIL" }); + eprintln!( + "bit-exact: {} ({} vs {} bytes, first diff {})", + if pass { "PASS" } else { "FAIL" }, + x.len(), + y.len(), + first_diff.map_or("-".into(), |o| o.to_string()) + ); + Ok(pass) +} + +// -------------------------------------------------------------- audio ------ + +fn deinterleave_f32(buf: &[u8], channels: usize) -> Vec> { + let frames = buf.len() / 4 / channels; + let mut out = vec![Vec::with_capacity(frames); channels]; + for f in 0..frames { + for (c, ch) in out.iter_mut().enumerate() { + let i = (f * channels + c) * 4; + ch.push(f32::from_le_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as f64); + } + } + out +} + +/// Pearson correlation. Two constant signals correlate perfectly iff equal. +fn corr(a: &[f64], b: &[f64]) -> f64 { + let n = a.len().min(b.len()); + if n == 0 { + return 0.0; + } + let (ma, mb) = ( + a[..n].iter().sum::() / n as f64, + b[..n].iter().sum::() / n as f64, + ); + let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); + for i in 0..n { + let (x, y) = (a[i] - ma, b[i] - mb); + num += x * y; + da += x * x; + db += y * y; + } + if da == 0.0 || db == 0.0 { + return if da == db && (ma - mb).abs() < 1e-12 { + 1.0 + } else { + 0.0 + }; + } + num / (da * db).sqrt() +} + +fn rms_delta(a: &[f64], b: &[f64]) -> (f64, f64) { + let n = a.len().min(b.len()); + if n == 0 { + return (f64::INFINITY, f64::INFINITY); + } + let mut sum = 0.0; + let mut peak: f64 = 0.0; + for i in 0..n { + let d = a[i] - b[i]; + sum += d * d; + peak = peak.max(d.abs()); + } + ((sum / n as f64).sqrt(), peak) +} + +fn cmd_audio_compare(argv: &[String]) -> Result { + let a = Args::parse(argv)?; + if a.pos.len() != 2 { + return Err("audio-compare needs ".into()); + } + let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]); + let min_corr: f64 = a.num("min-corr", 0.999)?; + let max_rms: f64 = a.num("max-rms", 1e-3)?; + + let probe = ffprobe(ref_path, "a:0", "channels,sample_rate")?; + let channels: usize = match a.flags.get("channels") { + Some(v) => v.parse().map_err(|_| "bad --channels".to_string())?, + None => probe + .get("channels") + .ok_or("could not probe channel count; pass --channels")? + .parse() + .map_err(|_| "bad probed channel count".to_string())?, + }; + if channels == 0 { + return Err("channel count is zero".into()); + } + let rate = probe + .get("sample_rate") + .cloned() + .unwrap_or_else(|| "-".into()); + + let ours = read_file(ours_path)?; + let reference = ffmpeg_raw( + ref_path, + &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"], + )?; + let (na, nb) = (ours.len() / 4 / channels, reference.len() / 4 / channels); + let (ca, cb) = ( + deinterleave_f32(&ours, channels), + deinterleave_f32(&reference, channels), + ); + + println!("meta\tours\t{ours_path}"); + println!("meta\tref\t{ref_path}"); + println!("meta\tchannels\t{channels}"); + println!("meta\tsample_rate\t{rate}"); + println!("meta\tframes_ours\t{na}"); + println!("meta\tframes_ref\t{nb}"); + + // A length gap beyond one percent is a decoder bug (dropped/duplicated + // packets), not a comparison detail — it fails on its own. + let len_ok = na.abs_diff(nb) as f64 <= 0.01 * na.max(nb) as f64; + let mut min_c = f64::INFINITY; + let mut max_r: f64 = 0.0; + for c in 0..channels { + let k = corr(&ca[c], &cb[c]); + let (r, p) = rms_delta(&ca[c], &cb[c]); + min_c = min_c.min(k); + max_r = max_r.max(r); + println!("ch\t{c}\tcorr\t{k:.6}\trms\t{r:.8}\tpeak\t{p:.8}"); + } + let pass = len_ok && min_c >= min_corr && max_r <= max_rms; + println!( + "verdict\t{}\tmin_corr={min_c:.6}\tmax_rms={max_r:.8}\tlen_ok={len_ok}", + if pass { "PASS" } else { "FAIL" } + ); + eprintln!( + "audio-compare: {} — {channels}ch @{rate}, min corr {min_c:.6} (>= {min_corr}), \ + max RMS delta {max_r:.8} (<= {max_rms}), lengths {na}/{nb}", + if pass { "PASS" } else { "FAIL" } + ); + Ok(pass) +} + +// -------------------------------------------------------------- video ------ + +/// Raw-frame geometry for a pixel format: total samples, luma samples (0 when the +/// format is packed and has no contiguous luma plane), bytes per sample, max value. +struct PixGeom { + samples: usize, + luma: usize, + bps: usize, + max: f64, +} + +fn pix_geom(pix_fmt: &str, w: usize, h: usize) -> Result { + let wh = w * h; + let g = |samples: usize, luma: usize, bps: usize, max: f64| PixGeom { + samples, + luma, + bps, + max, + }; + // Semi-planar formats carry their depth inside the name, so match them first. + match pix_fmt { + "nv12" | "nv21" => return Ok(g(wh * 3 / 2, wh, 1, 255.0)), + "p010le" | "p010be" => return Ok(g(wh * 3 / 2, wh, 2, 1023.0)), + "p016le" | "p016be" => return Ok(g(wh * 3 / 2, wh, 2, 65535.0)), + _ => {} + } + let mut base = pix_fmt; + let mut bps = 1; + let mut max = 255.0; + for (suffix, depth) in [("9", 9u32), ("10", 10), ("12", 12), ("14", 14), ("16", 16)] { + for endian in ["le", "be"] { + let s = format!("{suffix}{endian}"); + if let Some(b) = pix_fmt.strip_suffix(&s) { + base = b; + bps = 2; + max = ((1u32 << depth) - 1) as f64; + } + } + } + let geom = match base { + "yuv420p" | "yuvj420p" => g(wh * 3 / 2, wh, bps, max), + "yuv422p" | "yuvj422p" => g(wh * 2, wh, bps, max), + "yuv444p" | "yuvj444p" | "gbrp" => g(wh * 3, wh, bps, max), + "gray" => g(wh, wh, bps, max), + // Packed: no contiguous luma plane, so luma PSNR falls back to all-plane. + "yuyv422" | "uyvy422" => g(wh * 2, 0, bps, max), + "rgb24" | "bgr24" => g(wh * 3, 0, bps, max), + "rgba" | "bgra" | "argb" | "abgr" => g(wh * 4, 0, bps, max), + _ => return Err(format!("unsupported pix_fmt for raw compare: {pix_fmt}")), + }; + Ok(geom) +} + +fn sample(buf: &[u8], i: usize, bps: usize) -> f64 { + if bps == 1 { + buf[i] as f64 + } else { + u16::from_le_bytes([buf[2 * i], buf[2 * i + 1]]) as f64 + } +} + +/// PSNR over `n` samples starting at sample index `off` in both buffers. +fn psnr(a: &[u8], b: &[u8], off: usize, n: usize, bps: usize, max: f64) -> f64 { + let mut sum = 0.0; + for i in off..off + n { + let d = sample(a, i, bps) - sample(b, i, bps); + sum += d * d; + } + let mse = sum / n as f64; + if mse == 0.0 { + f64::INFINITY + } else { + 10.0 * (max * max / mse).log10() + } +} + +fn cmd_video_compare(argv: &[String]) -> Result { + let a = Args::parse(argv)?; + if a.pos.len() != 2 { + return Err("video-compare needs ".into()); + } + let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]); + let min_psnr: f64 = a.num("min-psnr", 40.0)?; + + let probe = ffprobe(ref_path, "v:0", "width,height,pix_fmt")?; + let pix = match a.flags.get("pix-fmt") { + Some(v) => v.clone(), + None => probe + .get("pix_fmt") + .cloned() + .ok_or("could not probe pix_fmt; pass --pix-fmt")?, + }; + let (w, h) = match a.flags.get("size") { + Some(s) => { + let (ws, hs) = s.split_once('x').ok_or("--size must look like 1920x1080")?; + ( + ws.parse::().map_err(|_| "bad --size width")?, + hs.parse::().map_err(|_| "bad --size height")?, + ) + } + None => ( + probe + .get("width") + .ok_or("could not probe width; pass --size")? + .parse() + .map_err(|_| "bad probed width".to_string())?, + probe + .get("height") + .ok_or("could not probe height; pass --size")? + .parse() + .map_err(|_| "bad probed height".to_string())?, + ), + }; + + let geom = pix_geom(&pix, w, h)?; + let frame_bytes = geom.samples * geom.bps; + if frame_bytes == 0 { + return Err("frame size computed as zero".into()); + } + + let ours = read_file(ours_path)?; + let reference = ffmpeg_raw( + ref_path, + &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", &pix], + )?; + let (fa, fb) = (ours.len() / frame_bytes, reference.len() / frame_bytes); + let frames = fa.min(fb); + + println!("meta\tours\t{ours_path}"); + println!("meta\tref\t{ref_path}"); + println!("meta\tpix_fmt\t{pix}"); + println!("meta\tdims\t{w}x{h}"); + println!("meta\tframe_bytes\t{frame_bytes}"); + println!("meta\tframes_ours\t{fa}"); + println!("meta\tframes_ref\t{fb}"); + if frames == 0 { + println!("verdict\tFAIL\tno complete frame in common"); + eprintln!("video-compare: FAIL — no complete frame in common ({fa} vs {fb})"); + return Ok(false); + } + + let luma_n = if geom.luma == 0 { + geom.samples + } else { + geom.luma + }; + let mut min_y = f64::INFINITY; + let mut sum_y = 0.0; + let mut min_all = f64::INFINITY; + let mut sum_all = 0.0; + let mut finite_y = 0usize; + let mut finite_all = 0usize; + for f in 0..frames { + let off = f * geom.samples; + let py = psnr(&ours, &reference, off, luma_n, geom.bps, geom.max); + let pa = psnr(&ours, &reference, off, geom.samples, geom.bps, geom.max); + min_y = min_y.min(py); + min_all = min_all.min(pa); + if py.is_finite() { + sum_y += py; + finite_y += 1; + } + if pa.is_finite() { + sum_all += pa; + finite_all += 1; + } + println!("frame\t{f}\tpsnr_y\t{py:.4}\tpsnr_all\t{pa:.4}"); + } + // Mean over finite frames only: identical frames give +inf and would otherwise + // poison the average of a run that also contains real differences. + let mean_y = if finite_y == 0 { + f64::INFINITY + } else { + sum_y / finite_y as f64 + }; + let mean_all = if finite_all == 0 { + f64::INFINITY + } else { + sum_all / finite_all as f64 + }; + let len_ok = fa == fb; + let pass = len_ok && min_y >= min_psnr; + println!("stats\tpsnr_y\tmin\t{min_y:.4}\tmean\t{mean_y:.4}"); + println!("stats\tpsnr_all\tmin\t{min_all:.4}\tmean\t{mean_all:.4}"); + println!( + "verdict\t{}\tmin_psnr_y={min_y:.4}\tframes={frames}\tlen_ok={len_ok}", + if pass { "PASS" } else { "FAIL" } + ); + eprintln!( + "video-compare: {} — {frames} frames {w}x{h} {pix}, min luma PSNR {min_y:.4} dB \ + (>= {min_psnr}), mean {mean_y:.4} dB, frame counts {fa}/{fb}", + if pass { "PASS" } else { "FAIL" } + ); + Ok(pass) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corr_identical_and_inverted() { + let a = [0.0, 1.0, -1.0, 0.5, -0.25]; + let inv: Vec = a.iter().map(|x| -x).collect(); + assert!((corr(&a, &a) - 1.0).abs() < 1e-12); + assert!((corr(&a, &inv) + 1.0).abs() < 1e-12); + // Silence vs silence correlates; silence vs DC offset does not. + assert_eq!(corr(&[0.0; 4], &[0.0; 4]), 1.0); + assert_eq!(corr(&[0.0; 4], &[1.0; 4]), 0.0); + } + + #[test] + fn rms_and_peak_delta() { + let (r, p) = rms_delta(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]); + assert_eq!((r, p), (0.0, 0.0)); + let (r, p) = rms_delta(&[1.0, -1.0], &[0.0, 0.0]); + assert!((r - 1.0).abs() < 1e-12 && (p - 1.0).abs() < 1e-12); + } + + #[test] + fn psnr_identical_is_infinite_and_differing_is_finite() { + let a = vec![10u8, 20, 30, 40]; + assert!(psnr(&a, &a, 0, 4, 1, 255.0).is_infinite()); + let b = vec![11u8, 21, 31, 41]; + let p = psnr(&a, &b, 0, 4, 1, 255.0); + // MSE 1 over 8-bit range: 10*log10(255^2) = 48.13 dB. + assert!((p - 48.1308).abs() < 1e-3, "psnr={p}"); + // 10-bit path reads little-endian u16 pairs. + let x = [0u8, 1, 0, 1]; + let y = [1u8, 1, 0, 1]; + assert!(psnr(&x, &y, 0, 2, 2, 1023.0).is_finite()); + } + + #[test] + fn pix_geom_covers_the_generated_fixture_formats() { + let (w, h) = (1920, 1080); + let g = pix_geom("yuv420p", w, h).unwrap(); + assert_eq!( + (g.samples, g.luma, g.bps, g.max), + (w * h * 3 / 2, w * h, 1, 255.0) + ); + let g = pix_geom("yuv420p10le", w, h).unwrap(); + assert_eq!( + (g.samples, g.luma, g.bps, g.max), + (w * h * 3 / 2, w * h, 2, 1023.0) + ); + let g = pix_geom("p010le", w, h).unwrap(); + assert_eq!((g.samples, g.bps, g.max), (w * h * 3 / 2, 2, 1023.0)); + assert_eq!(pix_geom("yuv444p", w, h).unwrap().samples, w * h * 3); + assert_eq!(pix_geom("yuyv422", w, h).unwrap().luma, 0); + assert!(pix_geom("no_such_fmt", w, h).is_err()); + } + + #[test] + fn deinterleave_splits_channels() { + let mut buf = Vec::new(); + for f in 0..3u32 { + for c in 0..2u32 { + buf.extend_from_slice(&((f * 10 + c) as f32).to_le_bytes()); + } + } + let ch = deinterleave_f32(&buf, 2); + assert_eq!(ch[0], vec![0.0, 10.0, 20.0]); + assert_eq!(ch[1], vec![1.0, 11.0, 21.0]); + } + + #[test] + fn args_parse_flags_and_positionals() { + let argv: Vec = ["a.raw", "b.mp4", "--min-corr", "0.5"] + .iter() + .map(|s| s.to_string()) + .collect(); + let a = Args::parse(&argv).unwrap(); + assert_eq!(a.pos, ["a.raw", "b.mp4"]); + assert_eq!(a.num::("min-corr", 0.999).unwrap(), 0.5); + assert_eq!(a.num::("max-rms", 1e-3).unwrap(), 1e-3); + assert!(Args::parse(&["--dangling".to_string()]).is_err()); + } +} diff --git a/tools/oracle/tests/cli.rs b/tools/oracle/tests/cli.rs new file mode 100644 index 00000000..c11e7599 --- /dev/null +++ b/tools/oracle/tests/cli.rs @@ -0,0 +1,163 @@ +//! Self-test of the `oracle` CLI itself: drives the built binary the way a codec +//! crate's test will, using ffmpeg as both the "our decoder" stand-in and the +//! reference. Exercises the PASS and the FAIL path of every subcommand. +//! +//! Fixture-gated: fixtures/ is gitignored, so a checkout without +//! `scripts/gen-fixtures.sh` run skips loudly instead of failing. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures") + .canonicalize() + .unwrap_or_else(|_| PathBuf::from("/nonexistent")) +} + +// Per-test directory: the test binary runs its cases as threads of one process, +// so a pid-only name would let one case delete another's raw files. +fn workdir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("oracle-selftest-{}-{name}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Decode `input` to a raw file with ffmpeg — stands in for "our decoder's output". +fn decode_raw(input: &Path, out: &Path, extra: &[&str]) { + let f = std::fs::File::create(out).unwrap(); + let st = Command::new("ffmpeg") + .args(["-nostdin", "-y", "-v", "error", "-i"]) + .arg(input) + .args(extra) + .arg("-") + .stdout(Stdio::from(f)) + .status() + .expect("ffmpeg must be installed to run the oracle self-test"); + assert!(st.success(), "ffmpeg failed decoding {}", input.display()); +} + +fn oracle(args: &[&str]) -> i32 { + Command::new(env!("CARGO_BIN_EXE_oracle")) + .args(args) + .status() + .expect("oracle binary") + .code() + .expect("oracle exited by signal") +} + +fn require(paths: &[PathBuf]) -> bool { + for p in paths { + if !p.is_file() { + eprintln!( + "SKIP: missing fixture {} — run scripts/gen-fixtures.sh", + p.display() + ); + return false; + } + } + true +} + +const F32: &[&str] = &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"]; + +#[test] +fn bit_exact_passes_on_same_decode_and_fails_on_a_different_one() { + let fx = fixtures(); + let a = fx.join("audio/flac-stereo-48000.flac"); + let b = fx.join("audio/flac-mono-48000.flac"); + if !require(&[a.clone(), b.clone()]) { + return; + } + let w = workdir("bitexact"); + let (r1, r2, r3) = (w.join("a1.raw"), w.join("a2.raw"), w.join("b.raw")); + decode_raw(&a, &r1, F32); + decode_raw(&a, &r2, F32); + decode_raw(&b, &r3, F32); + + assert_eq!( + oracle(&["bit-exact", r1.to_str().unwrap(), r2.to_str().unwrap()]), + 0, + "same file decoded twice must be bit-exact" + ); + assert_eq!( + oracle(&["bit-exact", r1.to_str().unwrap(), r3.to_str().unwrap()]), + 1, + "different fixtures must not be bit-exact" + ); + let _ = std::fs::remove_dir_all(&w); +} + +#[test] +fn audio_compare_passes_against_its_own_source_and_fails_across_rates() { + let fx = fixtures(); + let a = fx.join("audio/flac-stereo-48000.flac"); + let b = fx.join("audio/flac-stereo-44100.flac"); + if !require(&[a.clone(), b.clone()]) { + return; + } + let w = workdir("audio"); + let (ra, rb) = (w.join("a.raw"), w.join("b.raw")); + decode_raw(&a, &ra, F32); + decode_raw(&b, &rb, F32); + + assert_eq!( + oracle(&["audio-compare", ra.to_str().unwrap(), a.to_str().unwrap()]), + 0, + "lossless decode vs its own source must correlate at 1.0" + ); + // 44.1 kHz samples against a 48 kHz reference: wrong length and wrong phase. + assert_eq!( + oracle(&["audio-compare", rb.to_str().unwrap(), a.to_str().unwrap()]), + 1, + "a different-rate decode must be rejected" + ); + let _ = std::fs::remove_dir_all(&w); +} + +#[test] +fn video_compare_passes_against_its_own_source_and_fails_on_frame_count() { + let fx = fixtures(); + let a = fx.join("video/h264-1080p-23.976-8bit.mp4"); + let b = fx.join("video/h264-1080p-60-8bit.mp4"); + if !require(&[a.clone(), b.clone()]) { + return; + } + let w = workdir("video"); + let raw = w.join("a.raw"); + decode_raw( + &a, + &raw, + &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "yuv420p"], + ); + + assert_eq!( + oracle(&[ + "video-compare", + raw.to_str().unwrap(), + a.to_str().unwrap(), + "--pix-fmt", + "yuv420p", + ]), + 0, + "decode vs its own source must be lossless (infinite PSNR)" + ); + assert_eq!( + oracle(&[ + "video-compare", + raw.to_str().unwrap(), + b.to_str().unwrap(), + "--pix-fmt", + "yuv420p", + ]), + 1, + "48 frames against a 120-frame reference must fail" + ); + let _ = std::fs::remove_dir_all(&w); +} + +#[test] +fn bad_usage_exits_two() { + assert_eq!(oracle(&["no-such-subcommand"]), 2); + assert_eq!(oracle(&["bit-exact", "only-one-arg"]), 2); +}