Include xombe source directly in repository instead of submodule

This commit is contained in:
2026-11-28 13:00:55 +01:00
parent 0206e69108
commit d53662bff2
303 changed files with 29260 additions and 4 deletions
+137
View File
@@ -0,0 +1,137 @@
#!/bin/sh
set -u
BUILD=${1:-build}
PY=${2:-python3}
ROOT=$(cd "$(dirname "$0")/.." && pwd)
case $BUILD in /*) ;; *) BUILD=$ROOT/$BUILD ;; esac
VEC=$ROOT/vectors
OUT=$BUILD/conformance
IN=$BUILD/e3in # dithered E3 inputs, from gen_inputs.py
JOBS=4
export XOMBE_BUILD=$BUILD
mkdir -p "$OUT/t3" "$OUT/e3" "$OUT/e5" "$OUT/e6in" "$OUT/e6" "$OUT/e7"
status=0
summary=""
record() {
if [ "$2" -eq 0 ]; then summary="$summary
$1: PASS"; else summary="$summary
$1: FAIL"; status=1; fi
}
# runs a command, reports it on stderr and returns 1 if it fails
run() {
"$@" || { echo "FAILED ($?): $*" >&2; return 1; }
}
echo "== inputs"
run "$PY" "$ROOT/scripts/gen_inputs.py" --out "$IN"
record inputs $?
echo "== T3"
t3=0
for s in es1_nsdtx_off es1_nsdtx_on es2 es3 es4; do
run "$BUILD/xombe-dec" --conformance-noise "$VEC/perceptual/$s.amb" "$OUT/t3/$s.raw" || t3=1
done
# each scorer's stderr goes to its own log, printed if that scorer fails
for s in es1_nsdtx_off es1_nsdtx_on es2 es3 es4; do
echo "$s"
done | xargs -P $JOBS -I{} sh -c "\"$PY\" \"$ROOT/tools/score.py\" \"$VEC/perceptual/{}_ref.raw\" \"$OUT/t3/{}.raw\" --json > \"$OUT/t3/{}.json\" 2> \"$OUT/t3/{}.log\" || { echo 'score.py failed for {}:' >&2; cat \"$OUT/t3/{}.log\" >&2; exit 1; }" || t3=1
"$PY" - "$OUT/t3" <<'EOF' || t3=1
import json, sys, os
d = sys.argv[1]
sets = ['es1_nsdtx_off', 'es1_nsdtx_on', 'es2', 'es3', 'es4']
keys = ['pesq_nb', 'visqol_speech', 'stoi', 'lsd_db']
ok = True
rows = []
print('%-14s %7s %7s %7s %7s' % ('set', 'PESQ', 'ViSQOL', 'STOI', 'LSD'))
for s in sets:
try:
r = json.load(open(os.path.join(d, s + '.json')))
bad = [k for k in keys if not isinstance(r.get(k), (int, float))]
except (OSError, ValueError) as e:
r, bad = {}, ['unreadable scores (%s)' % e]
if bad:
print('%-14s missing or failed: %s FAIL' % (s, ', '.join(bad)))
ok = False
continue
good = r['pesq_nb'] >= 4.05 and r['visqol_speech'] >= 4.15 and r['stoi'] >= 0.98 and r['lsd_db'] <= 1.30
ok &= good
rows.append(r)
print('%-14s %7.3f %7.3f %7.3f %7.3f %s' % (s, r['pesq_nb'], r['visqol_speech'], r['stoi'], r['lsd_db'],
'ok' if good else 'FAIL'))
if len(rows) == len(sets):
mp = sum(r['pesq_nb'] for r in rows) / len(rows)
ml = sum(r['lsd_db'] for r in rows) / len(rows)
mv = sum(r['visqol_speech'] for r in rows) / len(rows)
ms = sum(r['stoi'] for r in rows) / len(rows)
print('%-14s %7.3f %7.3f %7.3f %7.3f' % ('mean (5 sets)', mp, mv, ms, ml))
ok &= mp >= 4.25 and ml <= 1.00
print('limits: each PESQ >= 4.05, ViSQOL >= 4.15, STOI >= 0.98, LSD <= 1.30; mean PESQ >= 4.25, mean LSD <= 1.00')
print('T3: ' + ('PASS' if ok else 'FAIL'))
sys.exit(0 if ok else 1)
EOF
record T3 $t3
echo "== T4"
run "$BUILD/test_stream" --metrics "$VEC"/stream/mixed_stream_0.jsonl.gz "$VEC"/stream/mixed_stream_1.jsonl.gz \
"$VEC"/stream/mixed_stream_2.jsonl.gz "$VEC"/stream/mixed_stream_3.jsonl.gz
record T4 $?
echo "== T5"
run "$BUILD/test_tones" "$VEC/tones"
record T5 $?
echo "== encodes"
enc=0
for c in es1 es2 es3 sn10 ttsf ttsc ttsl; do
for k in 0 1 2 3 4; do echo "$c.d$k"; done
done | xargs -P $JOBS -I{} sh -c "\"$BUILD/xombe-enc\" \"$IN/{}.raw\" \"$OUT/e3/{}.amb\" || { echo 'xombe-enc failed for {}' >&2; exit 1; }" || enc=1
for n in low5 hp5; do run "$BUILD/xombe-enc" "$VEC/e5/$n.raw" "$OUT/e5/$n.amb" || enc=1; done
for n in glide mix saw150 tones; do run "$BUILD/xombe-enc" "$VEC/e7/$n.raw" "$OUT/e7/$n.amb" || enc=1; done
record encodes $enc
echo "== E1"
e1=0
for f in "$OUT"/e3/*.amb; do
b=$(basename "$f" .amb)
"$PY" "$ROOT/tools/e1.py" "$f" --input "$IN/$b.raw" --quiet > /dev/null || { echo "E1 fail: $f"; e1=1; }
done
for d in e5 e7; do
for f in "$OUT"/$d/*.amb; do
b=$(basename "$f" .amb)
"$PY" "$ROOT/tools/e1.py" "$f" --input "$VEC/$d/$b.raw" --quiet > /dev/null || { echo "E1 fail: $f"; e1=1; }
done
done
echo "E1 (e1.py): $(ls "$OUT"/e3/*.amb "$OUT"/e5/*.amb "$OUT"/e7/*.amb | wc -l) streams checked"
record "E1 (streams)" $e1
echo "== E1/E2/E7"
run "$BUILD/test_mirror" "$VEC" --e7 --inputs "$IN" --stress 600
record "E1/E2/E7" $?
echo "== E3"
run "$PY" "$ROOT/tools/e3.py" "$OUT/e3" --jobs $JOBS --quiet --json "$OUT/e3.json"
record E3 $?
echo "== E4"
run "$PY" "$ROOT/tools/e4.py" "$OUT/e3" --json "$OUT/e4.json"
record E4 $?
echo "== E5"
run "$PY" "$ROOT/tools/e5.py" "$OUT/e3" --e5-cand "$OUT/e5" --inputs "$IN" --json "$OUT/e5.json"
record E5 $?
echo "== E6"
e6=0
run "$PY" "$ROOT/tools/e6.py" gen "$OUT/e6in" > /dev/null || e6=1
for f in "$OUT"/e6in/*.raw; do run "$BUILD/xombe-enc" "$f" "$OUT/e6/$(basename "$f" .raw).amb" || e6=1; done
run "$PY" "$ROOT/tools/e6.py" check "$OUT/e6in/cases.json" "$OUT/e6" > "$OUT/e6.txt" || e6=1
tail -2 "$OUT/e6.txt"
run "$PY" "$ROOT/tools/e6.py" check pkg "$OUT/e7" > "$OUT/e6pkg.txt" || e6=1
tail -2 "$OUT/e6pkg.txt"
run "$PY" "$ROOT/tools/e6.py" speech "$OUT/e3" "$OUT/e5" "$OUT/e7" || e6=1
record E6 $e6
echo "== summary$summary"
exit $status
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
# conformance_dstar.sh [BUILD [PYTHON]]: D-STAR gates from the repository's own vectors (tools/dstar_conf.py)
set -u
BUILD=${1:-build}
PY=${2:-python3}
ROOT=$(cd "$(dirname "$0")/.." && pwd)
case $BUILD in /*) ;; *) BUILD=$ROOT/$BUILD ;; esac
OUT=$BUILD/conformance-dstar
export XOMBE_BUILD=$BUILD
mkdir -p "$OUT"
status=0
summary=""
record() {
if [ "$2" -eq 0 ]; then summary="$summary
$1: PASS"; else summary="$summary
$1: FAIL"; status=1; fi
}
for t in xombe-enc xombe-dec xombe-xc dstar_dump_fec; do
if [ ! -x "$BUILD/$t" ]; then
echo "$BUILD/$t missing: conformance-dstar needs XOMBE_DSTAR, XOMBE_ENCODER and the tests" >&2
exit 1
fi
done
echo "== inputs"
"$PY" "$ROOT/scripts/gen_inputs.py" --out "$BUILD/e3in" > /dev/null
record inputs $?
echo "== refs"
"$PY" "$ROOT/tools/dstar_conf.py" refs "$BUILD" --json "$OUT/refs.json"
record refs $?
echo "== speech"
"$PY" "$ROOT/tools/dstar_conf.py" speech "$BUILD" "$OUT/speech" --inputs "$BUILD/e3in" --json "$OUT/speech.json"
record speech $?
echo "== tones"
"$PY" "$ROOT/tools/dstar_conf.py" tones "$BUILD" "$OUT/tones" --inputs "$BUILD/e3in" --json "$OUT/tones.json"
record tones $?
echo "== summary$summary"
exit $status
+220
View File
@@ -0,0 +1,220 @@
# D-STAR (AMBE 2400) reference harness, record format in test/dstar_ref.h
set(XOMBE_DSTAR_REFS ${CMAKE_CURRENT_SOURCE_DIR}/vectors/dstar)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/dstar_out) # outputs, also of the tool tests that need no Python
find_package(Python3 COMPONENTS Interpreter QUIET)
add_library(xombe_dstar_ref STATIC test/dstar_ref.c)
xombe_target_options(xombe_dstar_ref)
xombe_executable(test_dstar_refs test/test_dstar_refs.c)
target_link_libraries(test_dstar_refs xombe_dstar_ref)
add_test(NAME dstar_refs COMMAND test_dstar_refs ${XOMBE_DSTAR_REFS})
# xombe_dstar_test(<name> [DIR <set>] [CLIPS <clip>...] INPUT <file-or-suffix> REF <file-or-suffix>
# RUN <program> [<args>...] [CMP <dstar_cmp.py options>...])
#
# Adds one ctest per clip (or one test without CLIPS), named dstar_<name>[_<clip>], that runs
# <program> <args> <set>/<clip><INPUT> <out>
# and then compares <out> with <set>/<clip><REF> using test/dstar_cmp.py <CMP options>; a REF ending
# in .raw is compared as PCM (--pcm). <set> is vectors/dstar unless DIR gives another. <program> may be a
# target name. The program reads the input (a stream, or a reference file it takes its inputs from) and writes
# its dump with test/dstar_ref.h's writer, using the reference file's column names. Needs Python 3 (standard
# library only): without it each test is a placeholder that ctest reports as skipped (label no_python).
function(xombe_dstar_test name)
cmake_parse_arguments(A "" "DIR;INPUT;REF" "CLIPS;RUN;CMP" ${ARGN})
if(A_DIR)
set(dir ${A_DIR})
else()
set(dir ${XOMBE_DSTAR_REFS})
endif()
list(GET A_RUN 0 prog)
list(REMOVE_AT A_RUN 0)
if(TARGET ${prog})
set(prog $<TARGET_FILE:${prog}>)
endif()
set(pcm "")
if(A_REF MATCHES "\\.raw$")
set(pcm --pcm)
endif()
if(NOT A_CLIPS)
set(A_CLIPS "-")
endif()
foreach(clip ${A_CLIPS})
if(clip STREQUAL "-")
set(clip "")
set(tname dstar_${name})
else()
set(tname dstar_${name}_${clip})
endif()
if(NOT Python3_Interpreter_FOUND)
add_test(NAME ${tname} COMMAND sh -c "exit 77")
set_tests_properties(${tname} PROPERTIES SKIP_RETURN_CODE 77 LABELS no_python)
set_property(GLOBAL APPEND PROPERTY XOMBE_SKIPPED_TESTS ${tname})
continue()
endif()
set(out ${CMAKE_CURRENT_BINARY_DIR}/dstar_out/${tname}.out)
add_test(NAME ${tname} COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/dstar_cmp.py
${pcm} ${A_CMP} ${dir}/${clip}${A_REF} ${out} --run ${prog} ${A_RUN} ${dir}/${clip}${A_INPUT} ${out})
endforeach()
endfunction()
# In-repo clips: sp (speech), nz (speech in noise), tn (tones), kx (Knox tones, near silence) and
# sper (sp with special frames and bit errors; D-Star input only); rate-33 inputs: sp, tn, kx, sper, tx.
set(XOMBE_DSTAR_CLIPS sp nz tn kx sper)
set(XOMBE_DSTAR_R33_CLIPS sp tn kx sper tx)
# The comparison machinery itself: each reference against a copy of itself.
xombe_dstar_test(selfcheck CLIPS sp sper INPUT .fec.txt.gz REF .fec.txt.gz RUN ${CMAKE_COMMAND} -E copy)
xombe_dstar_test(selfcheck_pcm CLIPS sper INPUT .dec.raw REF .dec.raw RUN ${CMAKE_COMMAND} -E copy)
xombe_dstar_test(selfcheck_quant INPUT quant_closed.txt.gz REF quant_closed.txt.gz RUN ${CMAKE_COMMAND} -E copy
CMP --key tset,parent,pass)
# deq floats: float32 against the model's float64, measured max |error|:
# a 3.2e-6 (log2; float32 ulp is 9.5e-7 for |a| in [8, 16)), Tv 1.0e-6, G 4.4e-7, f0 1.8e-9.
set(XOMBE_DSTAR_DEQ_TOL --tol *=1e-5:0)
if(XOMBE_DSTAR)
# P1: FEC, fields, the error rule and the encoder's packer (exact), and dequantization against the mirror.
xombe_internal_executable(test_dstar_tables test/test_dstar_tables.c)
target_link_libraries(test_dstar_tables xombe_dstar_ref)
add_test(NAME dstar_tables COMMAND test_dstar_tables ${XOMBE_DSTAR_REFS})
xombe_internal_executable(dstar_dump_fec test/dstar_dump_fec.c)
target_link_libraries(dstar_dump_fec xombe_dstar_ref)
xombe_internal_executable(dstar_dump_deq test/dstar_dump_deq.c)
target_link_libraries(dstar_dump_deq xombe_dstar_ref)
xombe_dstar_test(fec CLIPS ${XOMBE_DSTAR_CLIPS} INPUT .dstar REF .fec.txt.gz RUN dstar_dump_fec)
xombe_dstar_test(fec_enc INPUT fec_enc.txt.gz REF fec_enc.txt.gz RUN dstar_dump_fec --enc
CMP --tol level=0:0)
xombe_dstar_test(deq CLIPS ${XOMBE_DSTAR_CLIPS} INPUT .dstar REF .deq.txt.gz RUN dstar_dump_deq
CMP ${XOMBE_DSTAR_DEQ_TOL})
# P2: the decoder (dstar_dump_dec).
xombe_internal_executable(dstar_dump_dec test/dstar_dump_dec.c)
target_link_libraries(dstar_dump_dec xombe_dstar_ref)
# tolerances, measured:
# dec: float32 against the model's float64: Pia 7.2e-6, PiG 3.5e-6, lam 4.6e-6 (log2 units), Pif0 3.9e-7
# (the initial memory's f0); fbar 0.0033 Hz (AMBE+2's initial average pitch, 111.63 Hz against 111.6333).
# half: a 5.2e-5 at |a| ~ 12 (6 printed digits), M 3e-5 relative (2^a), rms 0.5 + 0.2%.
# PCM: the AMBE+2 synthesis' own C-vs-Python difference (relative ~1e-3, max 5 LSB on AMBE+2's es2). tn and sper
# meet the gate up to their first dual tone (frames 25 and 31), then drift in phase: xombe's tone table f0
# (US 7,970,606 B2) and the model's fitted one differ by up to 0.007 Hz. pcm_all bounds the whole clip
set(XOMBE_DSTAR_DEC_TOL --tol *=1e-5:0 --tol fbar=0.01:0)
set(XOMBE_DSTAR_HALF_TOL --tol *=1e-5:1e-5 --tol M=1e-5:3e-5 --tol rms=0.5:2e-3)
set(XOMBE_DSTAR_PCM_GATE --lsb 4 --max-rms 3 --min-within 0.995)
xombe_dstar_test(dec CLIPS ${XOMBE_DSTAR_CLIPS} INPUT .dstar REF .dec.txt.gz RUN dstar_dump_dec
CMP ${XOMBE_DSTAR_DEC_TOL})
xombe_dstar_test(half CLIPS sp nz tn kx sper INPUT .dstar REF .half.txt.gz RUN dstar_dump_dec --half
CMP ${XOMBE_DSTAR_HALF_TOL})
xombe_dstar_test(pcm CLIPS sp nz kx INPUT .dstar REF .dec.raw RUN dstar_dump_dec --pcm
CMP ${XOMBE_DSTAR_PCM_GATE})
xombe_dstar_test(pcm CLIPS tn INPUT .dstar REF .dec.raw RUN dstar_dump_dec --pcm
CMP ${XOMBE_DSTAR_PCM_GATE} --samples 0:4000)
xombe_dstar_test(pcm CLIPS sper INPUT .dstar REF .dec.raw RUN dstar_dump_dec --pcm
CMP ${XOMBE_DSTAR_PCM_GATE} --samples 0:4960)
xombe_dstar_test(pcm_all CLIPS tn INPUT .dstar REF .dec.raw RUN dstar_dump_dec --pcm
CMP --lsb 4 --max-rms 110 --min-within 0.55)
xombe_dstar_test(pcm_all CLIPS sper INPUT .dstar REF .dec.raw RUN dstar_dump_dec --pcm
CMP --lsb 4 --max-rms 4 --min-within 0.94)
endif()
# P3: the closed-loop amplitude quantizer (src/common/cquant.c) on the quantizer cases.
if(XOMBE_DSTAR AND XOMBE_ENCODER)
xombe_internal_executable(dstar_dump_quant test/dstar_dump_quant.c)
target_link_libraries(dstar_dump_quant xombe_dstar_ref)
set(XOMBE_DSTAR_QUANT_CMP --tol *=1e-5:1e-4)
xombe_dstar_test(quant_closed INPUT quant_closed.txt.gz REF quant_closed.txt.gz RUN dstar_dump_quant closed
CMP --key tset,parent,pass ${XOMBE_DSTAR_QUANT_CMP})
xombe_dstar_test(quant_dstar INPUT quant_dstar.txt.gz REF quant_dstar.txt.gz RUN dstar_dump_quant dstar
CMP --key id ${XOMBE_DSTAR_QUANT_CMP})
xombe_dstar_test(quant_ambe2 INPUT quant_ambe2.txt.gz REF quant_ambe2.txt.gz RUN dstar_dump_quant ambe2
CMP --key id ${XOMBE_DSTAR_QUANT_CMP})
# capped at 100 units (the encoders use XOMBE_CQ_CAP): the bound per search, the summed error within 1e-3
# of the exact search's (checked by dstar_dump_quant), and 99% of the calls as the reference
set(cmin_closed --min b=0.99 --min err=0.99)
set(cmin_dstar --min b=0.99 --min ahat=0.99 --min err=0.99)
set(cmin_ambe2 --min bclosed=0.99 --min pick=0.99 --min b=0.99 --min ahat=0.99 --min err=0.99)
set(ckey_closed tset,parent,pass)
set(ckey_dstar id)
set(ckey_ambe2 id)
foreach(k closed dstar ambe2)
xombe_dstar_test(quant_${k}_cap INPUT quant_${k}.txt.gz REF quant_${k}.txt.gz RUN dstar_dump_quant --cap 100 ${k}
CMP --key ${ckey_${k}} ${XOMBE_DSTAR_QUANT_CMP} ${cmin_${k}})
endforeach()
endif()
# P4b: the encoder back end (src/dstar/dstar_enc.c) on the model's recorded inputs (test/dstar_dump_enc_be.c).
# Exact: b0 from the refined period, b1 from the recorded a and w, the fields and bytes of the recorded targets
# quantized against the mirror over the stream. m_noise is the generated table (16 bits, relative error < 3e-5).
# --spec: the voicing on the C spectrum of the input (C high-pass, float), against the model's.
if(XOMBE_DSTAR AND XOMBE_ENCODER)
xombe_internal_executable(dstar_dump_enc_be test/dstar_dump_enc_be.c)
target_link_libraries(dstar_dump_enc_be xombe_dstar_ref)
set(XOMBE_DSTAR_ENC_CLIPS sp nz tn kx)
xombe_dstar_test(enc_be CLIPS ${XOMBE_DSTAR_ENC_CLIPS} INPUT .enc.txt.gz REF .enc.txt.gz RUN dstar_dump_enc_be
CMP --tol mn=0:1e-4)
# measured: a within 0.01 on 99.84-100% of frames (worst 0.073), b1 equal on all but one frame, mv and w differ
# by the input high-pass (4-digit coefficients against scipy's Butterworth)
set(XOMBE_DSTAR_ENC_SPEC_CMP --tol mv=0:0.01 --tol w=0:0.01 --tol a=0.01:0 --min mv=0.9 --min w=0.95 --min a=0.995
--min b1=0.999)
# The q15 kernels' block-floating-point FFT (~60-65 dB) moves the metric further: measured minimums over the
# same clips w 76.7%, mv 79.2%, a 94.8%, b1 99.77%
if(XOMBE_KERNELS STREQUAL "q15")
set(XOMBE_DSTAR_ENC_SPEC_CMP --tol mv=0:0.01 --tol w=0:0.01 --tol a=0.01:0 --min mv=0.78 --min w=0.75
--min a=0.94 --min b1=0.997)
endif()
xombe_dstar_test(enc_be_spec CLIPS ${XOMBE_DSTAR_ENC_CLIPS} INPUT .enc.txt.gz REF .enc.txt.gz
RUN dstar_dump_enc_be --spec CMP ${XOMBE_DSTAR_ENC_SPEC_CMP})
# P4c: the whole encoder with the D-Star output on the clip's PCM (test/dstar_dump_enc.c): the tone pipeline's
# detection, run rule and final tone, and the frame class, exact against the model; levels within 0.02.
xombe_internal_executable(dstar_dump_enc test/dstar_dump_enc.c)
target_link_libraries(dstar_dump_enc xombe_dstar_ref)
set(XOMBE_DSTAR_ENC_TONE_CMP --tol det=0.02:0 --tol trk=0.02:0 --tol tone=0.02:0 --skip b0,b1,out)
# kx's Knox frames take their pairs from xombe's tone table (US 7,970,606 B2's f0 and harmonics); the model's
# are fitted, and every kx frame still matches, bytes included.
xombe_dstar_test(enc CLIPS sp nz tn kx INPUT .in.raw REF .enc.txt.gz RUN dstar_dump_enc CMP ${XOMBE_DSTAR_ENC_TONE_CMP})
xombe_dstar_test(enc_dual CLIPS tn INPUT .in.raw REF .enc.txt.gz RUN dstar_dump_enc --dual
CMP ${XOMBE_DSTAR_ENC_TONE_CMP})
endif()
# P5: the rate-33 -> D-STAR transcoder (src/dstar/xcode.c) on the rate-33 streams (test/dstar_dump_xc.c).
# Floats: f0, a, G, soft and tgt within 1e-5 (float32 against the model's float64). Knox frames (kx, tx) take f0
# and harmonics from xombe's tone table (US 7,970,606 B2), the model its fitted one: b0 differs for IDs 145, 150,
# 151, 153, 154 and 157, and the mirror carries the difference on
if(XOMBE_DSTAR)
xombe_internal_executable(dstar_dump_xc test/dstar_dump_xc.c)
target_link_libraries(dstar_dump_xc xombe_dstar_ref)
set(XOMBE_DSTAR_XC_CMP --tol *=1e-5:1e-5)
set(XOMBE_DSTAR_XC_KNOX --min tgt=0.4 --min tb0=0.44 --min b=0.17 --min out=0.17)
xombe_dstar_test(xc CLIPS sp tn sper INPUT .r33 REF .xc.txt.gz RUN dstar_dump_xc CMP ${XOMBE_DSTAR_XC_CMP})
xombe_dstar_test(xc CLIPS kx tx INPUT .r33 REF .xc.txt.gz RUN dstar_dump_xc CMP ${XOMBE_DSTAR_XC_CMP}
${XOMBE_DSTAR_XC_KNOX})
# the tool's stream equals the model's output
if(XOMBE_BUILD_TOOLS)
foreach(clip sp tn sper)
add_test(NAME dstar_xc_tool_${clip} COMMAND sh -c "\"$1\" \"$2\" \"$3\" && \"$4\" -E compare_files \"$3\" \"$5\""
xc $<TARGET_FILE:xombe-xc> ${XOMBE_DSTAR_REFS}/${clip}.r33
${CMAKE_CURRENT_BINARY_DIR}/dstar_out/xc_tool_${clip}.dstar ${CMAKE_COMMAND}
${XOMBE_DSTAR_REFS}/${clip}.xc.dstar)
endforeach()
endif()
endif()
# the D-STAR -> rate-33 transcoder (src/dstar/xrev.c) on the D-STAR streams (test/dstar_dump_xrev.c).
# floats: f0, a and tgt within 1e-5 (float32 against the model's float64)
if(XOMBE_DSTAR AND XOMBE_ENCODER)
xombe_internal_executable(dstar_dump_xrev test/dstar_dump_xrev.c)
target_link_libraries(dstar_dump_xrev xombe_dstar_ref)
set(XOMBE_DSTAR_XREV_CMP --tol *=1e-5:1e-5)
xombe_dstar_test(xrev CLIPS sp tn kx sper INPUT .dstar REF .xrev.txt.gz RUN dstar_dump_xrev
CMP ${XOMBE_DSTAR_XREV_CMP})
# with the transcoder's XOMBE_CQ_CAP (the tool's search): the same records
xombe_dstar_test(xrev_capped CLIPS sp tn kx sper INPUT .dstar REF .xrev.txt.gz RUN dstar_dump_xrev --capped
CMP ${XOMBE_DSTAR_XREV_CMP})
if(XOMBE_BUILD_TOOLS)
foreach(clip sp tn kx sper)
add_test(NAME dstar_xrev_tool_${clip}
COMMAND sh -c "\"$1\" --reverse \"$2\" \"$3\" && \"$4\" -E compare_files \"$3\" \"$5\""
xrev $<TARGET_FILE:xombe-xc> ${XOMBE_DSTAR_REFS}/${clip}.dstar
${CMAKE_CURRENT_BINARY_DIR}/dstar_out/xrev_tool_${clip}.r33 ${CMAKE_COMMAND}
${XOMBE_DSTAR_REFS}/${clip}.xrev.r33)
endforeach()
endif()
endif()
+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env python3
"""compares a C stage dump against a D-STAR reference file, standard library only
records:
dstar_cmp.py REF TEST [--key n,h] [--cols a,b,...] [--skip c,...] [--tol COL=ABS[:REL]]... [--min COL=RATE]...
[--rows N] [--run CMD ARGS...]
rows are matched on the key columns (default n, plus h when both files have it, else row order)
compared columns are those in both files (or --cols), minus --skip. integers, tokens, hex and bit strings,
and integer vectors must be equal, floats and float vectors agree when |test - ref| <= ABS + REL*|ref| for
every element (default 1e-6:1e-6, --tol '*=ABS:REL' changes the default), nan only matches nan
a column passes when its agreement rate is >= its --min (default 1)
PCM:
dstar_cmp.py --pcm REF.raw TEST.raw [--lsb N] [--max-rms R] [--min-within RATE] [--samples A:B]
[--run CMD ARGS...]
int16 little endian (--samples: only samples A..B-1 of both, B empty for the end), reports the maximum and
rms difference in LSB and the fraction of samples within --lsb (default 1), fails when the rms difference
exceeds --max-rms (default 0) or the fraction is below --min-within (default 1)
--run (must come last) runs the producer first, e.g. the C dump program that writes TEST
exit status: 0 agree, 1 disagree, 2 usage or I/O error
"""
import gzip
import math
import os
import struct
import subprocess
import sys
def read(path):
"""-> (meta, [(name, type)], [row dict])"""
with open(path, 'rb') as fh:
gz = fh.read(2) == b'\x1f\x8b'
op = gzip.open if gz else open
meta, cols, rows = {}, None, []
with op(path, 'rt') as fh:
for ln, line in enumerate(fh, 1):
line = line.rstrip('\n')
if line.startswith('#'):
if '=' in line:
k, v = line[1:].strip().split('=', 1)
meta[k] = v
continue
tok = line.split()
if not tok:
continue
if cols is None:
cols = [tuple(t.rsplit(':', 1)) for t in tok]
continue
r, i = {}, 0
try:
for name, t in cols:
if t == 'i':
r[name] = int(tok[i]); i += 1
elif t == 'f':
r[name] = float(tok[i]); i += 1
elif t in ('s', 'x', 'b'):
r[name] = '' if tok[i] == '-' else tok[i]; i += 1
elif t in ('i*', 'f*'):
n = int(tok[i]); i += 1
conv = int if t == 'i*' else float
r[name] = [conv(x) for x in tok[i:i + n]]
if len(r[name]) != n:
raise ValueError('short vector ' + name)
i += n
else:
raise ValueError('bad type ' + t)
except (IndexError, ValueError) as e:
raise ValueError('%s:%d: %s' % (path, ln, e))
if i != len(tok):
raise ValueError('%s:%d: %d values, %d used' % (path, ln, len(tok), i))
rows.append(r)
if cols is None:
raise ValueError('%s: no column line' % path)
return meta, cols, rows
def fclose(a, b, ab, rel):
if math.isnan(a) or math.isnan(b):
return math.isnan(a) and math.isnan(b), 0.0
d = abs(a - b)
return d <= ab + rel * abs(a), d
def cmp_records(ref, test, opt):
_, rc, rr = read(ref)
_, tc, tr = read(test)
rtypes, ttypes = dict(rc), dict(tc)
key = opt['key'] or (['n', 'h'] if 'h' in rtypes and 'h' in ttypes else ['n'])
key = [k for k in key if k in rtypes and k in ttypes]
cols = opt['cols'] or [c for c, _ in rc if c in ttypes]
cols = [c for c in cols if c not in opt['skip'] and c not in key]
for c in cols:
if c not in rtypes or c not in ttypes:
print('column %s missing from %s' % (c, 'REF' if c not in rtypes else 'TEST'))
return 2
if rtypes[c] != ttypes[c]:
print('column %s: type %s in REF, %s in TEST' % (c, rtypes[c], ttypes[c]))
return 2
if key:
tindex = {tuple(r[k] for k in key): r for r in tr}
pairs = [(r, tindex.get(tuple(r[k] for k in key))) for r in rr]
else:
pairs = list(zip(rr, tr)) + [(r, None) for r in rr[len(tr):]]
if opt['rows'] is not None:
pairs = pairs[:opt['rows']]
missing = sum(1 for _, t in pairs if t is None)
print('%s vs %s: %d reference rows, %d test rows, %d unmatched; key %s' % (
os.path.basename(ref), os.path.basename(test), len(rr), len(tr), missing, ','.join(key) or 'row order'))
status = 0 if pairs else 1
for c in cols:
t = rtypes[c]
ab, rel = opt['tol'].get(c, opt['tol'].get('*', (1e-6, 1e-6)))
agree, total, worst, wrow = 0, 0, 0.0, None
for r, s in pairs:
total += 1
if s is None:
continue
a, b = r[c], s[c]
if t == 'f':
ok, d = fclose(a, b, ab, rel)
elif t == 'f*':
ok, d = len(a) == len(b), (math.inf if len(a) != len(b) else 0.0)
if ok:
for x, y in zip(a, b):
o, e = fclose(x, y, ab, rel)
ok, d = ok and o, max(d, e)
else:
ok, d = a == b, 0.0 if a == b else math.inf
agree += ok
if d > worst or (not ok and wrow is None):
worst, wrow = max(d, worst), tuple(r[k] for k in key) if key else None
rate = agree / total if total else 0.0
need = opt['min'].get(c, opt['min'].get('*', 1.0))
flag = 'ok' if rate >= need else 'FAIL'
if flag == 'FAIL':
status = 1
tol = (' tol %g:%g' % (ab, rel)) if t in ('f', 'f*') else ''
wtxt = ''
if worst:
wtxt = ' worst %s at %s' % ('mismatch' if worst == math.inf else '%.3g' % worst, wrow)
print(' %-10s %-2s %6d/%-6d %7.3f%%%s%s %s' % (c, t, agree, total, 100.0 * rate, tol, wtxt, flag))
return status
def read_pcm(path):
b = open(path, 'rb').read()
if len(b) % 2:
raise ValueError('%s: odd size' % path)
return struct.unpack('<%dh' % (len(b) // 2), b)
def cmp_pcm(ref, test, opt):
x, y = read_pcm(ref), read_pcm(test)
if opt['samples']:
a, b = opt['samples']
x, y = x[a:b], y[a:b]
n = min(len(x), len(y))
if len(x) != len(y):
print('length: REF %d samples, TEST %d' % (len(x), len(y)))
d = [abs(a - b) for a, b in zip(x[:n], y[:n])]
rms = math.sqrt(sum(v * v for v in d) / n) if n else 0.0
sig = math.sqrt(sum(v * v for v in x[:n]) / n) if n else 0.0
within = sum(1 for v in d if v <= opt['lsb']) / n if n else 0.0
snr = 20 * math.log10(sig / rms) if rms > 0 and sig > 0 else math.inf
print('%s vs %s: %d samples, max diff %d LSB, rms diff %.3f LSB, %.3f%% within %d LSB, SNR %.1f dB' % (
os.path.basename(ref), os.path.basename(test), n, max(d) if d else 0, rms, 100 * within, opt['lsb'], snr))
ok = len(x) == len(y) and rms <= opt['max_rms'] and within >= opt['min_within']
print(' %s' % ('ok' if ok else 'FAIL'))
return 0 if ok else 1
def parse(argv):
opt = dict(key=None, cols=None, skip=set(), tol={}, min={}, rows=None, pcm=False, lsb=1, max_rms=0.0,
min_within=1.0, run=None, samples=None)
pos, i = [], 0
while i < len(argv):
a = argv[i]
if a == '--run':
opt['run'] = argv[i + 1:]
break
if a == '--pcm':
opt['pcm'] = True
elif a in ('--key', '--cols', '--skip', '--tol', '--min', '--rows', '--lsb', '--max-rms', '--min-within',
'--samples'):
i += 1
v = argv[i]
if a == '--key':
opt['key'] = [s for s in v.split(',') if s]
elif a == '--cols':
opt['cols'] = [s for s in v.split(',') if s]
elif a == '--skip':
opt['skip'] |= set(v.split(','))
elif a == '--tol':
c, t = v.split('=')
ab, _, rel = t.partition(':')
opt['tol'][c] = (float(ab), float(rel or 0.0))
elif a == '--min':
c, t = v.split('=')
opt['min'][c] = float(t)
elif a == '--rows':
opt['rows'] = int(v)
elif a == '--samples':
a0, b0 = v.split(':')
opt['samples'] = (int(a0), int(b0) if b0 else None)
elif a == '--lsb':
opt['lsb'] = int(v)
elif a == '--max-rms':
opt['max_rms'] = float(v)
else:
opt['min_within'] = float(v)
elif a.startswith('--'):
raise SystemExit('unknown option %s' % a)
else:
pos.append(a)
i += 1
if len(pos) != 2:
raise SystemExit(__doc__)
return pos, opt
def main(argv):
try:
(ref, test), opt = parse(argv)
except SystemExit as e:
print(e, file=sys.stderr)
return 2
if opt['run']:
r = subprocess.run(opt['run'])
if r.returncode:
print('producer failed (%d): %s' % (r.returncode, ' '.join(opt['run'])))
return 2
try:
return cmp_pcm(ref, test, opt) if opt['pcm'] else cmp_records(ref, test, opt)
except (OSError, ValueError) as e:
print(e)
return 2
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
+132
View File
@@ -0,0 +1,132 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "../src/dstar/dsd_state.h"
#include "dstar_ref.h"
/* D-STAR decoder records: --dec (default) frame level (stage 'dec'), --half half-frame sets (stage 'half'),
--pcm the PCM */
static const char *const LOG[] = {"voice", "tone", "null", "repeat", "mute"};
static const char *cls_name(int c)
{
return c == XOMBE_CLASS_VOICE ? "voice" : c == XOMBE_CLASS_SILENCE ? "silence" : c == XOMBE_CLASS_TONE ? "tone" : "?";
}
static void write_half(dsref_writer *w, long n, int h, const xombe_set *s, const int16_t *pcm, int N)
{
char V[9], vl[XOMBE_LMAX + 2];
uint8_t vh[XOMBE_LMAX + 1];
float a[XOMBE_LMAX + 1], M[XOMBE_LMAX + 1];
double e2 = 0.0;
int l, tone = s->cls == XOMBE_CLASS_TONE;
for (l = 0; l < 8; l++)
V[l] = tone || s->vb[l] ? 'V' : 'U';
V[8] = 0;
memset(vh, 0, sizeof(vh));
if (!tone)
xombe__ds_harm_voicing(s->vb, s->f0, s->L, vh);
for (l = 1; l <= s->L; l++) {
if (tone) {
int on = s->e[l] > XOMBE_AMP_OFF;
M[l] = on ? exp2f(s->e[l]) : 0.0f;
a[l] = on ? s->e[l] : (float)log2(1e-30);
vh[l] = (uint8_t)on;
} else {
M[l] = exp2f(s->e[l]);
a[l] = s->a[l];
}
vl[l - 1] = vh[l] ? 'V' : 'U';
}
vl[s->L] = 0;
for (l = 0; l < N; l++)
e2 += (double)pcm[l] * pcm[l];
dsref_wi(w, n);
dsref_wi(w, h);
dsref_ws(w, cls_name(s->cls));
dsref_wi(w, s->repeat);
dsref_wf(w, s->f0);
dsref_wi(w, s->L);
dsref_ws(w, V);
dsref_ws(w, vl);
dsref_wfv_float(w, a + 1, s->L);
dsref_wfv_float(w, M + 1, s->L);
dsref_wf(w, sqrt(e2 / N));
dsref_wend(w);
}
int main(int argc, char **argv)
{
long n, nf;
uint8_t *fr;
dsref_writer w;
xombe_dec_mem mem;
xombe_dec *s;
FILE *pcm_out = NULL;
int mode = 0, ok = 1, a = 1;
if (argc == 4 && !strcmp(argv[1], "--half"))
mode = 1, a = 2;
else if (argc == 4 && !strcmp(argv[1], "--pcm"))
mode = 2, a = 2;
else if (argc == 4 && !strcmp(argv[1], "--dec"))
a = 2;
if (argc != a + 2) {
fprintf(stderr, "usage: dstar_dump_dec [--dec | --half | --pcm] IN.dstar OUT\n");
return 2;
}
if (!(fr = dsref_read_frames(argv[a], 9, &nf)))
return 1;
if (mode == 2)
ok = (pcm_out = fopen(argv[a + 1], "wb")) != NULL;
else if (mode == 1)
ok = dsref_wopen(&w, argv[a + 1], "half", "n:i h:i cls:s rep:i f0:f L:i V:s vl:s a:f* M:f* rms:f", 0);
else
ok = dsref_wopen(&w, argv[a + 1], "dec",
"n:i log:s ea:i eb:i bf:i hb:i eT:i e1:i Picls:s PiL:i Pif0:f PiG:f lam:f fbar:f Pia:f*", 0);
if (!ok) {
free(fr);
return 1;
}
s = xombe_dec_init(&mem, XOMBE_DSTAR);
xombe_dec_set_noise(s, XOMBE_NOISE_CONFORMANCE, 0);
for (n = 0; n < nf && ok; n++) {
int16_t pcm[160];
float fbar = s->c.avg_f0 * XOMBE_FS; /* the model records it before the frame's halves */
xombe_dec_half(s, fr + 9 * n, 0, 0, 80, pcm);
if (mode == 0) {
const xombe_pred *pi = &s->c.pi;
dsref_wi(&w, n);
dsref_ws(&w, LOG[s->ds.log]);
dsref_wi(&w, s->c.decision.e0);
dsref_wi(&w, s->c.decision.e1);
dsref_wi(&w, s->c.decision.bf);
dsref_wi(&w, s->c.decision.hb);
dsref_wi(&w, s->ds.eT);
dsref_wi(&w, s->ds.e1);
dsref_ws(&w, cls_name(pi->cls));
dsref_wi(&w, pi->L);
dsref_wf(&w, pi->f0);
dsref_wf(&w, pi->gamma);
dsref_wf(&w, s->c.lambda);
dsref_wf(&w, fbar);
dsref_wfv_float(&w, pi->a + 1, pi->L);
dsref_wend(&w);
} else if (mode == 1) {
write_half(&w, n, 1, &s->c.p1, pcm, 80);
}
xombe_dec_half(s, fr + 9 * n, 0, 1, 80, pcm + 80);
if (mode == 1)
write_half(&w, n, 2, &s->c.p2, pcm + 80, 80);
if (mode == 2)
ok = fwrite(pcm, 2, 160, pcm_out) == 160;
}
free(fr);
if (mode == 2)
ok &= fclose(pcm_out) == 0;
else
ok &= dsref_wclose(&w);
return ok ? 0 : 1;
}
+60
View File
@@ -0,0 +1,60 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "../src/dstar/dstar_internal.h"
#include "dstar_ref.h"
/* D-STAR dequantization against the mirror (stage 'deq') */
int main(int argc, char **argv)
{
long n, nf;
uint8_t *fr;
dsref_writer w;
xombe_ds_mirror m;
int k, ok;
if (argc != 3) {
fprintf(stderr, "usage: dstar_dump_deq IN.dstar OUT\n");
return 2;
}
if (!(fr = dsref_read_frames(argv[1], 9, &nf)))
return 1;
if (!dsref_wopen(&w, argv[2], "deq",
"n:i voice:i b0:i b1:i b2:i b3:i b4:i b5:i b6:i b7:i b8:i f0:f L:i vl:b Tv:f* G:f stL:i "
"stG:f sta:f*", 0)) {
free(fr);
return 1;
}
xombe__ds_mirror_init(&m);
for (n = 0; n < nf; n++) {
xombe_ds_frame f;
xombe_ds_params p;
int voice;
xombe__ds_fec_decode(fr + 9 * n, &f);
voice = xombe__ds_params_from_frame(&m, &f, &p);
dsref_wi(&w, n);
dsref_wi(&w, voice);
for (k = 0; k < 9; k++)
dsref_wi(&w, f.b[k]);
if (voice) {
dsref_wf(&w, p.f0);
dsref_wi(&w, p.L);
dsref_wb(&w, p.vl + 1, p.L);
dsref_wfv_float(&w, p.Tv + 1, p.L);
dsref_wf(&w, p.G);
} else {
dsref_wf(&w, NAN);
dsref_wi(&w, 0);
dsref_wb(&w, NULL, 0);
dsref_wfv_float(&w, NULL, 0);
dsref_wf(&w, NAN);
}
dsref_wi(&w, m.L);
dsref_wf(&w, m.G);
dsref_wfv_float(&w, m.a + 1, m.L);
dsref_wend(&w);
}
free(fr);
ok = dsref_wclose(&w);
return ok ? 0 : 1;
}
+76
View File
@@ -0,0 +1,76 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/state.h"
#include "../src/dstar/dstar_enc.h"
#include "dstar_ref.h"
/* whole encoder with the D-STAR output on PCM, against the model's records (enc stage)
columns n cls det trk tone b0 b1 out:
cls voice, tone, knox, or silence (a NULL frame)
det, trk, tone tone pipeline on the frame (T and level, empty when none): detection, after the
run rule, and the final tone after the tone-in-noise pass
b0, b1 the frame's first two fields (126 and -1 on tone frames, 124 and -1 on NULL frames)
--dual: both outputs enabled (the D-STAR output does not depend on it) */
static void wtone(dsref_writer *w, const xombe_ds_tone *t)
{
float v[2];
v[0] = (float)t->T;
v[1] = t->level;
dsref_wfv_float(w, v, t->on ? 2 : 0);
}
int main(int argc, char **argv)
{
static const char *cls_name[4] = {"voice", "silence", "tone", "knox"};
static xombe_enc_mem mem;
xombe_enc_cfg cfg;
xombe_enc *e;
dsref_writer w;
int16_t pcm[XOMBE_FRAME];
uint8_t d[9];
long frames = 0, n = 0;
int dual = argc > 1 && !strcmp(argv[1], "--dual");
FILE *in;
if (argc != 3 + dual) {
fprintf(stderr, "usage: dstar_dump_enc [--dual] IN.raw OUT\n");
return 2;
}
in = fopen(argv[1 + dual], "rb");
if (!in) {
perror(argv[1 + dual]);
return 1;
}
xombe_enc_cfg_default(&cfg);
cfg.outputs = XOMBE_ENC_DSTAR | (dual ? XOMBE_ENC_DMR : 0);
e = xombe_enc_init(&mem, &cfg);
if (!e || !dsref_wopen(&w, argv[2 + dual], "enc", "n:i cls:s det:f* trk:f* tone:f* b0:i b1:i out:x", 7))
return 1;
for (;;) {
const xombe_ds_enc_frame *fr = &XOMBE_DS_ENC(e)->fr;
size_t k = fread(pcm, sizeof(pcm[0]), XOMBE_FRAME, in);
int got;
if (k > 0) { /* a partial last frame is zero-padded, as the model counts frames */
memset(pcm + k, 0, (XOMBE_FRAME - k) * sizeof(pcm[0]));
frames++;
got = xombe_enc_frame(e, pcm, NULL, NULL, d);
} else if (n < frames)
got = xombe_enc_frame(e, NULL, NULL, NULL, d);
else
break;
if (!got)
continue;
dsref_wi(&w, n++);
dsref_ws(&w, cls_name[fr->cls]);
wtone(&w, &fr->det);
wtone(&w, &fr->trk);
wtone(&w, &fr->tone);
dsref_wi(&w, fr->cls == XOMBE_DS_CLS_TONE ? 126 : fr->cls == XOMBE_DS_CLS_NULL ? 124 : fr->b0);
dsref_wi(&w, fr->cls == XOMBE_DS_CLS_VOICE ? fr->b1 : fr->cls == XOMBE_DS_CLS_KNOX ? 15 : -1);
dsref_wx(&w, d, 9);
dsref_wend(&w);
}
fclose(in);
return dsref_wclose(&w) ? 0 : 1;
}
+246
View File
@@ -0,0 +1,246 @@
#define _POSIX_C_SOURCE 200112L
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../src/state.h"
#include "../src/dstar/dstar_enc.h"
#include "dstar_ref.h"
#if defined(XOMBE_CALLGRIND)
#include <valgrind/callgrind.h>
#endif
/* D-STAR encoder back end (src/dstar/dstar_enc.c) on the model's recorded inputs (enc stage):
dstar_dump_enc_be C.enc.txt.gz OUT n cls b0t mn b1 b out
b0t xombe__ds_b0_from_f0(1/Pr) of the recorded refined period
mn xombe__ds_m_noise(N, b0t) of the recorded window and pitch
b1 xombe__ds_b1_search of the recorded a and w
b the recorded targets at, b0 and b1 quantized against the mirror run over the stream (xombe__ds_enc_amps;
the mirror commits these fields, Knox frames commit their recorded fields, tone and NULL frames skip)
out the 9 bytes of b
dstar_dump_enc_be --spec C.enc.txt.gz OUT n cls mv w a b1
the voicing on the C front end's spectrum: C.in.raw through the input high-pass, spectrum at window N centred
on 160n + 120, the metric and weights at the recorded b0t's f0, a with the recorded second-half VAD
decision (the VAD gate), b1 from those
non-voice frames are written with the reference's values, so rows stay matched
--bench REPS: (default mode) time xombe__ds_enc_amps over the stream REPS times, best to stderr, with
-DXOMBE_CALLGRIND the voice frames run between CALLGRIND_START/STOP_INSTRUMENTATION */
#define MAXF 20000
#define HPF_GAIN 0.9427f /* must match INPUT_HPF_GAIN in enc/encoder.c */
#define PAD 400
typedef struct {
int n, voice, knox, N, b0t, b0, b1, L, vad2;
char cls[8];
float Pr, a[8], w[8], mn[8], at[XOMBE_LMAX + 1];
int b[9];
uint8_t out[9];
} rec;
static rec R[MAXF];
static int nrec;
static int load(const char *path)
{
dsref r;
int st;
if (!dsref_open(&r, path))
return 0;
int c_n = dsref_need(&r, "n", DSREF_INT), c_cls = dsref_need(&r, "cls", DSREF_STR),
c_N = dsref_need(&r, "N", DSREF_INT), c_Pr = dsref_need(&r, "Pr", DSREF_FLOAT),
c_b0t = dsref_need(&r, "b0t", DSREF_INT), c_b0 = dsref_need(&r, "b0", DSREF_INT),
c_L = dsref_need(&r, "L", DSREF_INT), c_w = dsref_need(&r, "w", DSREF_FVEC),
c_mn = dsref_need(&r, "mn", DSREF_FVEC), c_a = dsref_need(&r, "a", DSREF_FVEC),
c_b1 = dsref_need(&r, "b1", DSREF_INT), c_at = dsref_need(&r, "at", DSREF_FVEC),
c_b = dsref_need(&r, "b", DSREF_IVEC), c_out = dsref_need(&r, "out", DSREF_HEX),
c_vad2 = dsref_need(&r, "vad2", DSREF_INT);
while ((st = dsref_next(&r)) > 0 && nrec < MAXF) {
rec *q = &R[nrec++];
int j;
memset(q, 0, sizeof(*q));
q->n = (int)dsref_i(&r, c_n);
snprintf(q->cls, sizeof(q->cls), "%s", dsref_s(&r, c_cls));
q->voice = !strcmp(q->cls, "voice");
q->knox = !strcmp(q->cls, "knox");
q->N = (int)dsref_i(&r, c_N);
q->Pr = (float)dsref_f(&r, c_Pr);
q->b0t = (int)dsref_i(&r, c_b0t);
q->b0 = (int)dsref_i(&r, c_b0);
q->b1 = (int)dsref_i(&r, c_b1);
q->L = (int)dsref_i(&r, c_L);
q->vad2 = (int)dsref_i(&r, c_vad2);
if (q->voice) {
if (dsref_len(&r, c_a) != 8 || dsref_len(&r, c_w) != 8 || dsref_len(&r, c_mn) != 8 ||
dsref_len(&r, c_at) != q->L) {
fprintf(stderr, "%s: frame %d: bad vector lengths\n", path, q->n);
return 0;
}
for (j = 0; j < 8; j++) {
q->a[j] = (float)dsref_fv(&r, c_a)[j];
q->w[j] = (float)dsref_fv(&r, c_w)[j];
q->mn[j] = (float)dsref_fv(&r, c_mn)[j];
}
for (j = 0; j < q->L; j++)
q->at[j + 1] = (float)dsref_fv(&r, c_at)[j];
}
for (j = 0; j < dsref_len(&r, c_b) && j < 9; j++)
q->b[j] = (int)dsref_iv(&r, c_b)[j];
if (dsref_len(&r, c_out) == 9)
memcpy(q->out, dsref_bytes(&r, c_out), 9);
}
return dsref_close(&r) && st == 0;
}
static xombe_ds_enc ds;
static void run_amps(int b[][9])
{
int i;
xombe__ds_enc_reset(&ds);
#if defined(XOMBE_CALLGRIND)
CALLGRIND_START_INSTRUMENTATION;
#endif
for (i = 0; i < nrec; i++) {
rec *q = &R[i];
if (q->voice)
xombe__ds_enc_amps(&ds, q->b0, q->b1, q->at, b[i]);
else if (q->knox)
xombe__ds_mirror_commit(&ds.mirror, q->b, NULL);
}
#if defined(XOMBE_CALLGRIND)
CALLGRIND_STOP_INSTRUMENTATION;
#endif
}
static int dump_exact(const char *out, int bench)
{
static int b[MAXF][9];
dsref_writer w;
int i, j;
run_amps(b);
if (!dsref_wopen(&w, out, "enc", "n:i cls:s b0t:i mn:f* b1:i b:i* out:x", 7))
return 1;
for (i = 0; i < nrec; i++) {
rec *q = &R[i];
dsref_wi(&w, q->n);
dsref_ws(&w, q->cls);
if (q->voice) {
float mn[8];
uint8_t o[9];
xombe__ds_m_noise(q->N, q->b0t, mn);
dsref_wi(&w, xombe__ds_b0_from_f0(1.0f / q->Pr));
dsref_wfv_float(&w, mn, 8);
dsref_wi(&w, xombe__ds_b1_search(q->a, q->w));
dsref_wiv_int(&w, b[i], 9);
xombe__ds_encode_fields(b[i], o);
dsref_wx(&w, o, 9);
} else {
long bl[9];
int nb = q->b[0] >= 124 && !q->knox ? 1 : 9;
for (j = 0; j < nb; j++)
bl[j] = q->b[j];
dsref_wi(&w, q->b0t);
dsref_wfv_float(&w, q->mn, 0);
dsref_wi(&w, q->b1);
dsref_wiv(&w, bl, nb);
dsref_wx(&w, q->out, 9);
}
dsref_wend(&w);
}
if (bench > 0) {
double best = 1e30;
int k, nv = 0;
for (i = 0; i < nrec; i++)
nv += R[i].voice;
for (k = 0; k < bench; k++) {
struct timespec t0, t1;
double dt;
clock_gettime(CLOCK_MONOTONIC, &t0);
run_amps(b);
clock_gettime(CLOCK_MONOTONIC, &t1);
dt = (double)(t1.tv_sec - t0.tv_sec) + 1e-9 * (double)(t1.tv_nsec - t0.tv_nsec);
if (dt < best)
best = dt;
}
fprintf(stderr, "amps: %d voice frames, %.1f us per frame\n", nv, 1e6 * best / (nv ? nv : 1));
}
return dsref_wclose(&w) ? 0 : 1;
}
static int dump_spec(const char *encpath, const char *out)
{
static unsigned char mem[XOMBE_ENC_SIZE];
static xombe_spec S;
char pcmpath[1024];
size_t n = strlen(encpath);
long ns, i;
int16_t *x;
float *xh;
xombe_hpf hpf;
xombe_enc *e = xombe_enc_init(mem, NULL);
dsref_writer w;
if (n < 11 || strcmp(encpath + n - 11, ".enc.txt.gz") || n > sizeof(pcmpath) - 8) {
fprintf(stderr, "%s: expected C.enc.txt.gz\n", encpath);
return 1;
}
memcpy(pcmpath, encpath, n - 11);
strcpy(pcmpath + n - 11, ".in.raw");
if (!(x = dsref_read_pcm(pcmpath, &ns)))
return 1;
xh = calloc((size_t)(ns + 2 * PAD + 160), sizeof(float));
xombe__hpf_init(&hpf, HPF_GAIN);
for (i = 0; i < ns; i++)
xh[PAD + i] = xombe__hpf_step(&hpf, (float)x[i]);
for (; i < ns + PAD + 160; i++)
xh[PAD + i] = xombe__hpf_step(&hpf, 0.0f);
if (!dsref_wopen(&w, out, "enc", "n:i cls:s mv:f* w:f* a:f* b1:i", 7))
return 1;
for (i = 0; i < nrec; i++) {
rec *q = &R[i];
dsref_wi(&w, q->n);
dsref_ws(&w, q->cls);
if (q->voice) {
float m[8], wv[8], mn[8], a[8], f0 = xombe__ds_f0(q->b0t);
xombe__enc_set_window(e, q->N);
xombe__kern_spectrum(xh + PAD + 160 * q->n + 120, e->win, q->N, &S);
xombe__voicing_metric(e, &S, f0, m, wv);
xombe__ds_m_noise(q->N, q->b0t, mn);
xombe__ds_soft(m, mn, XOMBE_DS_S_VN, q->vad2, a);
dsref_wfv_float(&w, m, 8);
dsref_wfv_float(&w, wv, 8);
dsref_wfv_float(&w, a, 8);
dsref_wi(&w, xombe__ds_b1_search(a, wv));
} else {
dsref_wfv_float(&w, NULL, 0);
dsref_wfv_float(&w, NULL, 0);
dsref_wfv_float(&w, NULL, 0);
dsref_wi(&w, q->b1);
}
dsref_wend(&w);
}
free(x);
free(xh);
return dsref_wclose(&w) ? 0 : 1;
}
int main(int argc, char **argv)
{
int spec = 0, bench = 0, i = 1;
for (; i < argc && !strncmp(argv[i], "--", 2); i++) {
if (!strcmp(argv[i], "--spec"))
spec = 1;
else if (!strcmp(argv[i], "--bench") && i + 1 < argc)
bench = atoi(argv[++i]);
else
break;
}
if (argc - i != 2) {
fprintf(stderr, "usage: dstar_dump_enc_be [--spec] [--bench REPS] C.enc.txt.gz OUT\n");
return 2;
}
if (!load(argv[i]))
return 1;
return spec ? dump_spec(argv[i], argv[i + 1]) : dump_exact(argv[i + 1], bench);
}
+147
View File
@@ -0,0 +1,147 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/dstar/dstar_internal.h"
#include "dstar_ref.h"
/* D-STAR FEC and fields (stage 'fec'): every frame of a stream with the error rule 'ds', --enc re-encodes the
fields and tone cases of a fec_enc file, --ids prints "n class toneid" per frame, toneid -1 if none (conformance) */
static const char *class_name(const xombe_ds_frame *f)
{
switch (f->cls) {
case XOMBE_DS_VOICE: return "voice";
case XOMBE_DS_TONE: return "tone";
default: return f->b[0] == 124 ? "null124" : f->b[0] == 125 ? "null125" : "null127";
}
}
static int dump_stream(const char *in, const char *out)
{
long n, nf;
uint8_t *fr = dsref_read_frames(in, 9, &nf), enc[9];
dsref_writer w;
xombe_ds_err er;
int k, ok;
if (!fr)
return 1;
if (!dsref_wopen(&w, out, "fec",
"n:i in:x A:i B:i C:i pn:i da:i ea:i db:i eb:i d48:b b0:i b1:i b2:i b3:i b4:i b5:i b6:i b7:i "
"b8:i cls:s T:i AD:i bf:i hb:i eT:i e1:i enc:x", 0)) {
free(fr);
return 1;
}
xombe__ds_err_init(&er);
for (n = 0; n < nf; n++) {
xombe_ds_frame f;
xombe_ds_flags fl;
xombe__ds_fec_decode(fr + 9 * n, &f);
xombe__ds_err_update(&er, f.ea, f.eb, &fl);
xombe__ds_encode_fields(f.b, enc);
dsref_wi(&w, n);
dsref_wx(&w, fr + 9 * n, 9);
dsref_wi(&w, (long)f.A);
dsref_wi(&w, (long)f.B);
dsref_wi(&w, (long)f.C);
dsref_wi(&w, (long)f.pn);
dsref_wi(&w, f.da);
dsref_wi(&w, f.ea);
dsref_wi(&w, f.db);
dsref_wi(&w, f.eb);
dsref_wb(&w, f.d, 48);
for (k = 0; k < 9; k++)
dsref_wi(&w, f.b[k]);
dsref_ws(&w, class_name(&f));
dsref_wi(&w, f.T);
dsref_wi(&w, f.AD);
dsref_wi(&w, fl.bf);
dsref_wi(&w, fl.hb);
dsref_wi(&w, fl.eT);
dsref_wi(&w, fl.e1);
dsref_wx(&w, enc, 9);
dsref_wend(&w);
}
free(fr);
ok = dsref_wclose(&w);
return ok ? 0 : 1;
}
static int dump_enc(const char *in, const char *out)
{
dsref r;
dsref_writer w;
int c_kind, c_b, c_T, c_level, st, k, ok;
if (!dsref_open(&r, in))
return 1;
c_kind = dsref_need(&r, "kind", DSREF_STR);
c_b = dsref_need(&r, "b", DSREF_IVEC);
c_T = dsref_need(&r, "T", DSREF_INT);
c_level = dsref_need(&r, "level", DSREF_FLOAT);
if (c_kind < 0 || c_b < 0 || c_T < 0 || c_level < 0 ||
!dsref_wopen(&w, out, "fec_enc", "kind:s b:i* T:i level:f d48:b out:x", 0)) {
dsref_close(&r);
return 1;
}
while ((st = dsref_next(&r)) > 0) {
uint8_t d[48], o[9];
int b[9];
if (!strcmp(dsref_s(&r, c_kind), "tone")) {
int T = (int)dsref_i(&r, c_T);
xombe__ds_tone_bits(T, xombe__ds_tone_q((float)dsref_f(&r, c_level)), d);
xombe__ds_tone_frame(T, xombe__ds_tone_q((float)dsref_f(&r, c_level)), o);
xombe__ds_get_fields(d, b);
} else {
if (dsref_len(&r, c_b) != 9) {
fprintf(stderr, "%s: b needs 9 fields\n", in);
st = -1;
break;
}
for (k = 0; k < 9; k++)
b[k] = (int)dsref_iv(&r, c_b)[k];
xombe__ds_put_fields(b, d);
if (xombe__ds_encode_fields(b, o) != 0) {
fprintf(stderr, "%s: field out of range\n", in);
st = -1;
break;
}
}
dsref_ws(&w, dsref_s(&r, c_kind));
dsref_wiv_int(&w, b, 9);
dsref_wi(&w, dsref_i(&r, c_T));
dsref_wf(&w, dsref_f(&r, c_level));
dsref_wb(&w, d, 48);
dsref_wx(&w, o, 9);
dsref_wend(&w);
}
ok = dsref_close(&r) && st == 0;
ok &= dsref_wclose(&w);
return ok ? 0 : 1;
}
static int dump_ids(const char *in)
{
long n, nf;
uint8_t *fr = dsref_read_frames(in, 9, &nf);
if (!fr)
return 1;
for (n = 0; n < nf; n++) {
xombe_ds_frame f;
xombe__ds_fec_decode(fr + 9 * n, &f);
printf("%ld %s %d\n", n, class_name(&f), f.tid);
}
free(fr);
return 0;
}
int main(int argc, char **argv)
{
if (argc == 3 && !strcmp(argv[1], "--ids"))
return dump_ids(argv[2]);
if (argc == 4 && !strcmp(argv[1], "--enc"))
return dump_enc(argv[2], argv[3]);
if (argc == 3)
return dump_stream(argv[1], argv[2]);
fprintf(stderr, "usage: dstar_dump_fec IN.dstar OUT | --enc fec_enc.txt.gz OUT | --ids IN.dstar\n");
return 2;
}
+397
View File
@@ -0,0 +1,397 @@
#define _POSIX_C_SOURCE 200112L
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../src/common/cquant.h"
#include "../src/dstar/dstar_internal.h"
#include "dstar_ref.h"
#if defined(XOMBE_CALLGRIND)
#include <valgrind/callgrind.h>
#endif
/* closed-loop quantizer against the reference quantizer cases:
dstar_dump_quant [options] closed quant_closed.txt.gz OUT (tset parent pass b err)
dstar_dump_quant [options] dstar quant_dstar.txt.gz OUT (id b ahat err)
dstar_dump_quant [options] ambe2 quant_ambe2.txt.gz OUT (id bopen bclosed pick b ahat err)
extra columns: errpy, the C error of the reference's fields (closed, dstar), for mismatch analysis, and w
(dstar, ambe2), recomputed with xombe__cq_amp_weights from the target and checked against the record
options:
--brute no pruning in the pair search
--bench REPS time the quantizer over every call after the dump, best of REPS, to stderr
--top N with --bench, the N slowest calls' ids
--ids a,b,... only these calls, with -DXOMBE_CALLGRIND a callgrind dump after each
--cap N dump the search capped at N, fail if a pair search exceeds max(N + 4, 132) units or the
summed error grows by more than --cap-tol REL (default 1e-3) against the exact search */
typedef struct {
int kind; /* 0 closed, 1 dstar, 2 ambe2 */
int tset; /* closed: 0 dstar, 1 ambe2 */
long id, pass;
int L, n_pairs, n_gain, iters, clip_passes, has_w, mode_closed;
float Gprev;
float r[XOMBE_LMAX + 1], target[XOMBE_LMAX + 1], base[XOMBE_LMAX + 1], w[XOMBE_LMAX + 1];
int Lp;
float ap[XOMBE_LMAX + 1];
int bref[9];
} qcall;
typedef struct {
xombe_cq_result res;
int pick, bopen[9], bclosed[9];
float ahat[XOMBE_LMAX + 1], err, errpy;
} qout;
static xombe_cq_ws ws;
static int brute, qcap;
static void fill(float *dst, const double *src, int n)
{
int i;
dst[0] = 0.0f;
for (i = 0; i < n; i++)
dst[i + 1] = (float)src[i];
}
static const xombe_amp_tables *set_of(const qcall *c)
{
return c->kind == 1 || (c->kind == 0 && c->tset == 0) ? &xombe__amp_dstar : &xombe__amp_ambe2;
}
/* decoder's reconstruction of fields b against the memory */
static void recon(const qcall *c, const int b[9], float *a)
{
const xombe_amp_tables *ts = set_of(c);
float t[XOMBE_LMAX + 1], pt[XOMBE_LMAX + 1];
xombe__predict_from(c->Lp, c->ap, c->L, pt);
xombe__spectral_shape_ts(ts, b, c->L, t);
xombe__assemble_ts(ts, t, pt, c->L, xombe__gain_ts(ts, b[2], c->Gprev), a);
}
static float werr(const qcall *c, const float *a, float amax)
{
float e = 0.0f;
int l;
for (l = 1; l <= c->L; l++) {
float t = c->target[l] < -15.0f ? -15.0f : c->target[l] > amax ? amax : c->target[l];
float d = a[l] - t;
e += (c->has_w ? c->w[l] : 1.0f) * d * d;
}
return e;
}
/* search's clipped error of fields b on a prepared workspace */
static float closed_err(const qcall *c, const int b[9])
{
const xombe_amp_tables *ts = set_of(c);
float t[XOMBE_LMAX + 1], mt = 0.0f, G = xombe__gain_ts(ts, b[2], c->Gprev), e = 0.0f;
int l;
xombe__spectral_shape_ts(ts, b, c->L, t);
for (l = 1; l <= c->L; l++)
mt += t[l];
mt /= (float)c->L;
for (l = 1; l <= c->L; l++) {
float a = t[l] - mt + c->base[l] + G, d;
a = a < -15.0f ? -15.0f : a > XOMBE_CQ_AMAX ? XOMBE_CQ_AMAX : a;
d = a - c->target[l];
e += (c->has_w ? c->w[l] : 1.0f) * d * d;
}
return e;
}
static void run(const qcall *c, qout *o)
{
const float *w = c->has_w ? c->w : NULL;
ws.brute = brute;
ws.cap = qcap;
if (c->kind == 0) {
xombe__cq_prepare(&ws, set_of(c), c->L, w);
xombe__cq_closed(&ws, c->r, c->target, c->base, c->Gprev, c->n_pairs, c->n_gain, c->iters, &o->res);
} else if (c->kind == 1) {
float pt[XOMBE_LMAX + 1];
xombe__predict_from(c->Lp, c->ap, c->L, pt);
xombe__cq_quantize(&ws, &xombe__amp_dstar, c->target, c->L, pt, c->Gprev, w, c->mode_closed, c->n_pairs,
c->n_gain, c->iters, c->clip_passes, &o->res);
} else {
xombe_pred pi;
xombe__pred_init(&pi);
pi.L = c->Lp;
pi.gamma = c->Gprev;
memcpy(pi.a, c->ap, sizeof(pi.a));
o->pick = xombe__cq_search_ambe2(&ws, &pi, c->target, c->L, w, c->n_pairs, c->n_gain, &o->res, o->bclosed,
o->bopen);
}
}
static int cmp_double(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return x < y ? -1 : x > y;
}
static double now(void)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + 1e-9 * t.tv_nsec;
}
static int in_ids(const char *ids, long id)
{
const char *p = ids;
while (p && *p) {
char *e;
long v = strtol(p, &e, 10);
if (e == p)
break;
if (v == id)
return 1;
p = *e == ',' ? e + 1 : e;
}
return 0;
}
int main(int argc, char **argv)
{
static const char *cols[3] = {
"tset:s parent:i pass:i b:i* err:f errpy:f",
"id:i w:f* b:i* ahat:f* err:f errpy:f",
"id:i w:f* bopen:i* bclosed:i* pick:s b:i* ahat:f* err:f"};
const char *ids = NULL;
int kind, reps = 0, ntop = 0, ai = 1, st, ok = 1, worst = 0, nchg = 0;
long n = 0, cap = 0, i;
double e_exact = 0.0, e_cap = 0.0, cap_tol = 1e-3;
qcall *calls = NULL;
dsref r;
dsref_writer wr;
while (ai < argc && argv[ai][0] == '-') {
if (!strcmp(argv[ai], "--brute"))
brute = 1;
else if (!strcmp(argv[ai], "--bench") && ai + 1 < argc)
reps = atoi(argv[++ai]);
else if (!strcmp(argv[ai], "--top") && ai + 1 < argc)
ntop = atoi(argv[++ai]);
else if (!strcmp(argv[ai], "--ids") && ai + 1 < argc)
ids = argv[++ai];
else if (!strcmp(argv[ai], "--cap") && ai + 1 < argc)
qcap = atoi(argv[++ai]);
else if (!strcmp(argv[ai], "--cap-tol") && ai + 1 < argc)
cap_tol = atof(argv[++ai]);
else
break;
ai++;
}
if (argc - ai != 3) {
fprintf(stderr, "usage: dstar_dump_quant [--brute] [--bench REPS [--top N]] [--ids a,b] [--cap N [--cap-tol REL]] "
"closed|dstar|ambe2 IN OUT\n");
return 2;
}
kind = !strcmp(argv[ai], "closed") ? 0 : !strcmp(argv[ai], "dstar") ? 1 : !strcmp(argv[ai], "ambe2") ? 2 : -1;
if (kind < 0 || !dsref_open(&r, argv[ai + 1]))
return 2;
{
int c_L = dsref_need(&r, "L", DSREF_INT), c_np = dsref_need(&r, "n_pairs", DSREF_INT);
int c_ng = dsref_need(&r, "n_gain", DSREF_INT), c_t = dsref_need(&r, "target", DSREF_FVEC);
int c_w = dsref_need(&r, "w", DSREF_FVEC), c_b = dsref_need(&r, "b", DSREF_IVEC);
int c_id = dsref_need(&r, kind == 0 ? "parent" : "id", DSREF_INT);
int c_ts = -1, c_pass = -1, c_it = -1, c_G = -1, c_r = -1, c_base = -1, c_cp = -1, c_mode = -1;
int c_Lp = -1, c_ap = -1;
if (kind == 0) {
c_ts = dsref_need(&r, "tset", DSREF_STR);
c_pass = dsref_need(&r, "pass", DSREF_INT);
c_it = dsref_need(&r, "iters", DSREF_INT);
c_G = dsref_need(&r, "Gprev", DSREF_FLOAT);
c_r = dsref_need(&r, "r", DSREF_FVEC);
c_base = dsref_need(&r, "base", DSREF_FVEC);
} else if (kind == 1) {
c_it = dsref_need(&r, "iters", DSREF_INT);
c_cp = dsref_need(&r, "clip_passes", DSREF_INT);
c_mode = dsref_need(&r, "mode", DSREF_STR);
c_G = dsref_need(&r, "stG", DSREF_FLOAT);
c_Lp = dsref_need(&r, "stL", DSREF_INT);
c_ap = dsref_need(&r, "sta", DSREF_FVEC);
} else {
c_mode = dsref_need(&r, "mode", DSREF_STR);
c_G = dsref_need(&r, "piG", DSREF_FLOAT);
c_Lp = dsref_need(&r, "piL", DSREF_INT);
c_ap = dsref_need(&r, "pia", DSREF_FVEC);
}
while ((st = dsref_next(&r)) > 0) {
qcall *c;
int k, L;
if (ids && !in_ids(ids, dsref_i(&r, c_id)))
continue;
if (n == cap) {
cap = cap ? 2 * cap : 1024;
calls = realloc(calls, cap * sizeof(*calls));
if (!calls)
return 2;
}
c = &calls[n++];
memset(c, 0, sizeof(*c));
c->kind = kind;
c->id = dsref_i(&r, c_id);
c->L = L = (int)dsref_i(&r, c_L);
c->n_pairs = (int)dsref_i(&r, c_np);
c->n_gain = (int)dsref_i(&r, c_ng);
c->iters = c_it >= 0 ? (int)dsref_i(&r, c_it) : 2;
c->clip_passes = c_cp >= 0 ? (int)dsref_i(&r, c_cp) : 0;
c->mode_closed = c_mode < 0 || !strcmp(dsref_s(&r, c_mode), "closed");
c->Gprev = (float)dsref_f(&r, c_G);
fill(c->target, dsref_fv(&r, c_t), L);
c->has_w = dsref_len(&r, c_w) > 0;
if (c->has_w)
fill(c->w, dsref_fv(&r, c_w), L);
for (k = 0; k < 7; k++)
c->bref[2 + k] = (int)dsref_iv(&r, c_b)[k];
if (kind == 0) {
c->tset = strcmp(dsref_s(&r, c_ts), "dstar") ? 1 : 0;
c->pass = dsref_i(&r, c_pass);
fill(c->r, dsref_fv(&r, c_r), L);
fill(c->base, dsref_fv(&r, c_base), L);
} else {
int la = dsref_len(&r, c_ap), l;
c->Lp = (int)dsref_i(&r, c_Lp);
fill(c->ap, dsref_fv(&r, c_ap), la);
for (l = la + 1; l <= XOMBE_LMAX; l++)
c->ap[l] = c->ap[la];
}
if (c->L < 1 || c->L > XOMBE_LMAX || c->n_pairs > XOMBE_CQ_MAX_PAIRS || c->n_gain > XOMBE_CQ_MAX_GAIN) {
fprintf(stderr, "dstar_dump_quant: bad call %ld\n", c->id);
return 2;
}
}
}
if (!dsref_close(&r) || st < 0)
return 2;
if (!dsref_wopen(&wr, argv[ai + 2], argv[ai], cols[kind], 9))
return 2;
for (i = 0; i < n; i++) {
const qcall *c = &calls[i];
qout o;
float a[XOMBE_LMAX + 1];
#if defined(XOMBE_CALLGRIND)
CALLGRIND_TOGGLE_COLLECT;
#endif
run(c, &o);
#if defined(XOMBE_CALLGRIND)
CALLGRIND_TOGGLE_COLLECT;
if (ids)
CALLGRIND_DUMP_STATS;
#endif
if (qcap > 0) {
qout x;
int k, d = 0, cq;
if (ws.work > worst)
worst = ws.work;
cq = qcap;
qcap = 0;
run(c, &x);
qcap = cq;
for (k = 2; k < 9; k++)
d |= x.res.b[k] != o.res.b[k];
nchg += d;
e_exact += x.res.err;
e_cap += o.res.err;
}
if (kind == 0) {
dsref_ws(&wr, c->tset ? "ambe2" : "dstar");
dsref_wi(&wr, c->id);
dsref_wi(&wr, c->pass);
dsref_wiv_int(&wr, o.res.b + 2, 7);
dsref_wf(&wr, o.res.err);
dsref_wf(&wr, closed_err(c, c->bref));
} else {
recon(c, o.res.b, a);
dsref_wi(&wr, c->id);
if (c->has_w) { /* amp_weights(target, 0.5) against the recorded weights */
float wc[XOMBE_LMAX + 1];
xombe__cq_amp_weights(c->target, c->L, XOMBE_CQ_QWEIGHT, XOMBE_CQ_WEIGHT_FLOOR, wc);
dsref_wfv_float(&wr, wc + 1, c->L);
} else
dsref_wfv_float(&wr, NULL, 0);
if (kind == 2) {
dsref_wiv_int(&wr, o.bopen + 2, 7);
dsref_wiv_int(&wr, o.bclosed + 2, 7);
dsref_ws(&wr, o.pick ? "open" : "closed");
}
dsref_wiv_int(&wr, o.res.b + 2, 7);
dsref_wfv_float(&wr, a + 1, c->L);
dsref_wf(&wr, werr(c, a, kind == 1 ? XOMBE_DS_AMP_MAX : XOMBE_AMP_MAX));
if (kind == 1) {
recon(c, c->bref, a);
dsref_wf(&wr, werr(c, a, XOMBE_DS_AMP_MAX));
}
}
dsref_wend(&wr);
}
ok = dsref_wclose(&wr);
if (qcap > 0) {
int bound = qcap + 4 > 132 ? qcap + 4 : 132;
fprintf(stderr, "cap %d: %d of %ld calls changed, error %+.4f%%, most units in a search %d (bound %d)\n", qcap,
nchg, n, 100.0 * (e_cap / e_exact - 1.0), worst, bound);
if (worst > bound || e_cap > (1.0 + cap_tol) * e_exact)
ok = 0;
}
if (reps > 0 && n > 0) {
double best = 1e30, *ct = malloc(n * sizeof(double));
int rep;
for (i = 0; i < n; i++)
ct[i] = 1e30;
for (rep = 0; rep < reps; rep++) {
double t0 = now(), t1;
for (i = 0; i < n; i++) {
qout o;
double s = ntop ? now() : 0.0;
run(&calls[i], &o);
if (ntop) {
double d = now() - s;
if (d < ct[i])
ct[i] = d;
}
}
t1 = now() - t0;
if (t1 < best)
best = t1;
}
fprintf(stderr, "bench %s: %ld calls, best of %d: %.3f us/call\n", argv[ai], n, reps, 1e6 * best / n);
if (ntop) {
/* per-call distribution (each call's best time) */
double *sorted = malloc(n * sizeof(double));
static const double pc[5] = {0.5, 0.9, 0.99, 0.999, 1.0};
int p;
memcpy(sorted, ct, n * sizeof(double));
qsort(sorted, n, sizeof(double), cmp_double);
fprintf(stderr, " per call (us):");
for (p = 0; p < 5; p++) {
long k = (long)(pc[p] * (n - 1) + 0.5);
fprintf(stderr, " p%g %.2f", 100.0 * pc[p], 1e6 * sorted[k]);
}
fprintf(stderr, "\n");
free(sorted);
}
for (rep = 0; rep < ntop; rep++) {
long m = -1;
for (i = 0; i < n; i++)
if (ct[i] >= 0 && (m < 0 || ct[i] > ct[m]))
m = i;
if (m < 0)
break;
fprintf(stderr, " slow: id %ld pass %ld L %d %.2f us\n", calls[m].id, calls[m].pass, calls[m].L,
1e6 * ct[m]);
ct[m] = -1.0;
}
free(ct);
}
free(calls);
#ifdef XOMBE_CQ_STATS
{
extern long xombe__cq_stat[4];
double n = (double)xombe__cq_stat[0];
fprintf(stderr, "stats: %ld pair searches, %.1f rows, %.1f pairs, and %.1f columns per search\n",
xombe__cq_stat[0], xombe__cq_stat[1] / n, xombe__cq_stat[2] / n, xombe__cq_stat[3] / n);
}
#endif
return ok ? 0 : 1;
}
+78
View File
@@ -0,0 +1,78 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "../src/dstar/xc_state.h"
#include "../src/dstar/trace.h"
#include "dstar_ref.h"
/* the rate-33 -> D-STAR transcoder's records (stage 'xc') */
static const char *cls_name(int c)
{
return c == XOMBE_CLASS_VOICE ? "voice" : c == XOMBE_CLASS_SILENCE ? "silence" : c == XOMBE_CLASS_TONE ? "tone" : "?";
}
static void bits8(dsref_writer *w, const uint8_t *v, int on)
{
dsref_wb(w, v, on ? 8 : 0);
}
int main(int argc, char **argv)
{
long n, nf;
uint8_t *fr;
dsref_writer w;
xombe_xc_mem mem;
xombe_xc_trace tr;
xombe_xc *x;
int ok;
if (argc != 3) {
fprintf(stderr, "usage: dstar_dump_xc IN.r33 OUT\n");
return 2;
}
if (!(fr = dsref_read_frames(argv[1], 9, &nf)))
return 1;
ok = dsref_wopen(&w, argv[2], "xc",
"n:i in:x e0:i e1:i cls:s cls_out:s rb:i* f0:f L:i a:f* V2:b V1:b G:f pulse:i tid:i AD:i "
"soft:f* tgt:f* tb0:i b:i* out:x", 7);
if (!ok) {
free(fr);
return 1;
}
x = xombe_xc_init(&mem, XOMBE_DMR);
x->u.f.trace = &tr;
for (n = 0; n < nf && ok; n++) {
uint8_t out[9];
xombe_xc_decision dc;
xombe_xc_frame(x, fr + 9 * n, 0, out);
xombe_xc_decision_get(x, &dc);
dsref_wi(&w, n);
dsref_wx(&w, fr + 9 * n, 9);
dsref_wi(&w, dc.in.e0);
dsref_wi(&w, dc.in.e1);
dsref_ws(&w, tr.conceal == XOMBE_CONCEAL_REPEAT ? "repeat"
: tr.conceal == XOMBE_CONCEAL_MUTE ? "mute" : cls_name(tr.cls));
dsref_ws(&w, cls_name(tr.cls_out));
dsref_wiv_int(&w, tr.rb, tr.has_rb ? 9 : 0);
dsref_wf(&w, tr.has_par ? tr.f0 : NAN);
dsref_wi(&w, tr.has_par ? tr.L : 0);
dsref_wfv_float(&w, tr.a + 1, tr.has_par ? tr.L : 0);
bits8(&w, tr.V2, tr.has_par);
bits8(&w, tr.V1, tr.has_v1);
dsref_wf(&w, tr.has_v1 ? tr.G : NAN);
dsref_wi(&w, tr.pulse);
dsref_wi(&w, tr.tid);
dsref_wi(&w, tr.AD);
dsref_wfv_float(&w, tr.soft, tr.has_soft ? 4 : 0);
dsref_wfv_float(&w, tr.tgt + 1, tr.tb0 >= 0 ? tr.tL : 0);
dsref_wi(&w, tr.tb0);
dsref_wiv_int(&w, tr.b, tr.has_b ? 9 : 0);
dsref_wx(&w, out, 9);
dsref_wend(&w);
}
free(fr);
ok &= dsref_wclose(&w);
return ok ? 0 : 1;
}
+74
View File
@@ -0,0 +1,74 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "../src/dstar/xc_state.h"
#include "../src/dstar/trace.h"
#include "dstar_ref.h"
/* the D-STAR -> rate-33 transcoder's records (stage 'xrev'), exact quantizer search (ws->cap 0) unless --capped
keeps the transcoder's XOMBE_CQ_CAP */
static const char *cls_name(int c)
{
return c == XOMBE_CLASS_VOICE ? "voice" : c == XOMBE_CLASS_SILENCE ? "silence" : c == XOMBE_CLASS_TONE ? "tone" : "?";
}
int main(int argc, char **argv)
{
static const char *const in_cls[] = {"voice", "tone", "null", "repeat", "mute"};
static const char *const ocls[] = {"voice", "pulse", "tone", "knox", "silence", "resend"}; /* enum xombe_xc_out */
static xombe_xc_mem mem;
long n, nf;
uint8_t *fr;
dsref_writer w;
xombe_xr_trace tr;
xombe_xc *x;
int ok, capped = argc == 4 && !strcmp(argv[1], "--capped");
if (argc != 3 + capped) {
fprintf(stderr, "usage: dstar_dump_xrev [--capped] IN.dstar OUT\n");
return 2;
}
argv += capped;
if (!(fr = dsref_read_frames(argv[1], 9, &nf)))
return 1;
ok = dsref_wopen(&w, argv[2], "xrev",
"n:i in:x ea:i eb:i cls:s scls:s db:i* f0:f L:i a:f* ocls:s tid:i AD:i tgt:f* b:i* d49:b out:x",
7);
if (!ok) {
free(fr);
return 1;
}
x = xombe_xc_init(&mem, XOMBE_DSTAR);
x->u.r.trace = &tr;
if (!capped)
x->u.r.ws->cap = 0;
for (n = 0; n < nf && ok; n++) {
uint8_t out[9];
xombe_xc_decision dc;
xombe_xc_frame(x, fr + 9 * n, 0, out);
xombe_xc_decision_get(x, &dc);
dsref_wi(&w, n);
dsref_wx(&w, fr + 9 * n, 9);
dsref_wi(&w, dc.in.e0);
dsref_wi(&w, dc.in.e1);
dsref_ws(&w, in_cls[tr.in_cls]);
dsref_ws(&w, cls_name(tr.scls));
dsref_wiv_int(&w, tr.db, tr.has_db ? 9 : 0);
dsref_wf(&w, tr.has_par ? tr.f0 : NAN);
dsref_wi(&w, tr.has_par ? tr.L : 0);
dsref_wfv_float(&w, tr.a + 1, tr.has_par ? tr.L : 0);
dsref_ws(&w, ocls[dc.out]);
dsref_wi(&w, tr.tid);
dsref_wi(&w, tr.AD);
dsref_wfv_float(&w, tr.tgt + 1, tr.tL);
dsref_wiv_int(&w, tr.b, tr.has_b ? 9 : 0);
dsref_wb(&w, tr.d49, 49);
dsref_wx(&w, out, 9);
dsref_wend(&w);
}
free(fr);
ok &= dsref_wclose(&w);
return ok ? 0 : 1;
}
+559
View File
@@ -0,0 +1,559 @@
#define _POSIX_C_SOURCE 200809L
#include "dstar_ref.h"
#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
static void fail(dsref *r, const char *what)
{
fprintf(stderr, "%s:%ld: %s\n", r->path, r->lineno, what);
r->failed = 1;
}
static FILE *open_gzip(const char *path, long *pid_out)
{
int fd[2];
pid_t pid;
FILE *f;
if (pipe(fd))
return NULL;
pid = fork();
if (pid < 0) {
close(fd[0]);
close(fd[1]);
return NULL;
}
if (pid == 0) {
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
execlp("gzip", "gzip", "-dc", "--", path, (char *)NULL);
_exit(127);
}
close(fd[1]);
f = fdopen(fd[0], "r");
if (!f) {
close(fd[0]);
waitpid(pid, NULL, 0);
return NULL;
}
*pid_out = (long)pid;
return f;
}
static int read_line(dsref *r)
{
ssize_t n = getline(&r->line, &r->line_cap, r->f);
if (n < 0)
return 0;
r->lineno++;
while (n > 0 && (r->line[n - 1] == '\n' || r->line[n - 1] == '\r'))
r->line[--n] = 0;
return 1;
}
static int parse_type(const char *s, dsref_type *t)
{
static const char *names[] = {"i", "f", "s", "x", "b", "i*", "f*"};
int k;
for (k = 0; k < 7; k++)
if (!strcmp(s, names[k])) {
*t = (dsref_type)k;
return 1;
}
return 0;
}
const char *dsref_type_name(dsref_type t)
{
static const char *names[] = {"i", "f", "s", "x", "b", "i*", "f*"};
return (unsigned)t < 7 ? names[t] : "?";
}
int dsref_open(dsref *r, const char *path)
{
size_t n = strlen(path);
memset(r, 0, sizeof(*r));
r->path = path;
r->pid = -1;
if (n > 3 && !strcmp(path + n - 3, ".gz"))
r->f = open_gzip(path, &r->pid);
else
r->f = fopen(path, "r");
if (!r->f) {
fprintf(stderr, "%s: cannot open: %s\n", path, strerror(errno));
r->failed = 1;
return 0;
}
for (;;) {
char *tok, *save = NULL;
if (!read_line(r)) {
fail(r, "no column line");
return 0;
}
if (r->line[0] == '#') {
char *eq = strchr(r->line, '=');
if (eq && r->nmeta < DSREF_MAX_META) {
char *k = r->line + 1;
while (*k == ' ')
k++;
*eq = 0;
snprintf(r->meta_key[r->nmeta], DSREF_NAME_LEN, "%s", k);
snprintf(r->meta_val[r->nmeta], sizeof(r->meta_val[0]), "%s", eq + 1);
r->nmeta++;
}
continue;
}
for (tok = strtok_r(r->line, " \t", &save); tok; tok = strtok_r(NULL, " \t", &save)) {
char *colon = strrchr(tok, ':');
dsref_column *c;
if (r->ncol == DSREF_MAX_COLS || !colon || colon == tok || colon - tok >= DSREF_NAME_LEN) {
fail(r, "bad column spec");
return 0;
}
c = &r->col[r->ncol];
memcpy(c->name, tok, (size_t)(colon - tok));
c->name[colon - tok] = 0;
if (!parse_type(colon + 1, &c->type)) {
fail(r, "bad column type");
return 0;
}
if (dsref_col(r, c->name) >= 0) {
fail(r, "duplicate column");
return 0;
}
r->ncol++;
}
if (!r->ncol) {
fail(r, "empty column line");
return 0;
}
return 1;
}
}
int dsref_col(const dsref *r, const char *name)
{
int k;
for (k = 0; k < r->ncol; k++)
if (!strcmp(r->col[k].name, name))
return k;
return -1;
}
int dsref_need(dsref *r, const char *name, dsref_type type)
{
int c = dsref_col(r, name);
if (c < 0 || r->col[c].type != type) {
char msg[96];
snprintf(msg, sizeof(msg), "column %s:%s %s", name, dsref_type_name(type), c < 0 ? "missing" : "has another type");
fail(r, msg);
return -1;
}
return c;
}
const char *dsref_meta(const dsref *r, const char *key)
{
int k;
for (k = 0; k < r->nmeta; k++)
if (!strcmp(r->meta_key[k], key))
return r->meta_val[k];
return NULL;
}
static int grow(dsref_column *c, size_t n, size_t elem)
{
void *p;
if (n <= c->cap)
return 1;
if (c->type == DSREF_IVEC)
p = realloc(c->iv, n * elem);
else if (c->type == DSREF_FVEC)
p = realloc(c->fv, n * elem);
else
p = realloc(c->bytes, n * elem);
if (!p)
return 0;
if (c->type == DSREF_IVEC)
c->iv = p;
else if (c->type == DSREF_FVEC)
c->fv = p;
else
c->bytes = p;
c->cap = n;
return 1;
}
static int to_long(const char *s, long *v)
{
char *end;
errno = 0;
*v = strtol(s, &end, 10);
return end != s && !*end && !errno;
}
static int to_double(const char *s, double *v)
{
char *end;
*v = strtod(s, &end);
return end != s && !*end;
}
static int hexval(int ch)
{
if (ch >= '0' && ch <= '9')
return ch - '0';
ch = tolower(ch);
return ch >= 'a' && ch <= 'f' ? ch - 'a' + 10 : -1;
}
int dsref_next(dsref *r)
{
char *save = NULL, *tok;
int k;
if (r->failed || !r->f)
return -1;
do {
if (!read_line(r))
return 0;
} while (r->line[0] == '#' || r->line[0] == 0);
tok = strtok_r(r->line, " \t", &save);
for (k = 0; k < r->ncol; k++) {
dsref_column *c = &r->col[k];
long n, j;
if (!tok) {
fail(r, "too few values");
return -1;
}
switch (c->type) {
case DSREF_INT:
if (!to_long(tok, &c->i)) {
fail(r, "bad integer");
return -1;
}
c->len = 1;
break;
case DSREF_FLOAT:
if (!to_double(tok, &c->f)) {
fail(r, "bad float");
return -1;
}
c->len = 1;
break;
case DSREF_STR:
case DSREF_HEX:
case DSREF_BITS:
c->s = strcmp(tok, "-") ? tok : "";
c->len = (int)strlen(c->s);
if (c->type == DSREF_HEX) {
if (c->len % 2 || !grow(c, (size_t)c->len / 2 + 1, 1)) {
fail(r, "bad hex");
return -1;
}
for (j = 0; j < c->len / 2; j++) {
int hi = hexval(c->s[2 * j]), lo = hexval(c->s[2 * j + 1]);
if (hi < 0 || lo < 0) {
fail(r, "bad hex digit");
return -1;
}
c->bytes[j] = (uint8_t)(hi << 4 | lo);
}
c->len /= 2;
} else if (c->type == DSREF_BITS) {
if (!grow(c, (size_t)c->len + 1, 1)) {
fail(r, "out of memory");
return -1;
}
for (j = 0; j < c->len; j++) {
if (c->s[j] != '0' && c->s[j] != '1') {
fail(r, "bad bit string");
return -1;
}
c->bytes[j] = (uint8_t)(c->s[j] - '0');
}
}
break;
case DSREF_IVEC:
case DSREF_FVEC:
if (!to_long(tok, &n) || n < 0 || n > 100000 ||
!grow(c, (size_t)n + 1, c->type == DSREF_IVEC ? sizeof(long) : sizeof(double))) {
fail(r, "bad vector count");
return -1;
}
for (j = 0; j < n; j++) {
tok = strtok_r(NULL, " \t", &save);
if (!tok || (c->type == DSREF_IVEC ? !to_long(tok, &c->iv[j]) : !to_double(tok, &c->fv[j]))) {
fail(r, tok ? "bad vector value" : "short vector");
return -1;
}
}
c->len = (int)n;
break;
}
tok = strtok_r(NULL, " \t", &save);
}
if (tok) {
fail(r, "too many values");
return -1;
}
r->nrec++;
return 1;
}
int dsref_close(dsref *r)
{
int k, ok = !r->failed;
if (r->f) {
if (ferror(r->f))
ok = 0;
fclose(r->f);
}
if (r->pid >= 0) {
int status = 0;
if (waitpid((pid_t)r->pid, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status)) {
fprintf(stderr, "%s: gzip failed\n", r->path);
ok = 0;
}
}
for (k = 0; k < r->ncol; k++) {
free(r->col[k].iv);
free(r->col[k].fv);
free(r->col[k].bytes);
}
free(r->line);
memset(r, 0, sizeof(*r));
r->pid = -1;
return ok;
}
static void *read_all(const char *path, long *size)
{
FILE *f = fopen(path, "rb");
char *buf = NULL;
long n = 0, cap = 0;
size_t k;
if (!f) {
fprintf(stderr, "%s: cannot open: %s\n", path, strerror(errno));
return NULL;
}
for (;;) {
if (n + 65536 > cap) {
char *p = realloc(buf, (size_t)(cap = 2 * cap + 65536));
if (!p) {
free(buf);
fclose(f);
return NULL;
}
buf = p;
}
k = fread(buf + n, 1, (size_t)(cap - n), f);
n += (long)k;
if (k == 0)
break;
}
if (ferror(f)) {
fprintf(stderr, "%s: read error\n", path);
free(buf);
buf = NULL;
}
fclose(f);
*size = n;
return buf;
}
int16_t *dsref_read_pcm(const char *path, long *nsamples)
{
long n, i;
uint8_t *b = read_all(path, &n);
int16_t *x;
if (!b)
return NULL;
if (n % 2) {
fprintf(stderr, "%s: odd size %ld for int16 PCM\n", path, n);
free(b);
return NULL;
}
x = malloc((size_t)(n / 2 + 1) * sizeof(int16_t));
if (x)
for (i = 0; i < n / 2; i++)
x[i] = (int16_t)(uint16_t)(b[2 * i] | b[2 * i + 1] << 8);
free(b);
*nsamples = n / 2;
return x;
}
uint8_t *dsref_read_frames(const char *path, int frame_bytes, long *nframes)
{
long n;
uint8_t *b = read_all(path, &n);
if (!b)
return NULL;
if (n % frame_bytes) {
fprintf(stderr, "%s: size %ld is not a multiple of %d\n", path, n, frame_bytes);
free(b);
return NULL;
}
*nframes = n / frame_bytes;
return b;
}
int dsref_wopen(dsref_writer *w, const char *path, const char *stage, const char *cols, int prec)
{
char buf[1024], *tok, *save = NULL;
memset(w, 0, sizeof(*w));
w->prec = prec > 0 ? prec : 9;
snprintf(buf, sizeof(buf), "%s", cols);
for (tok = strtok_r(buf, " \t", &save); tok; tok = strtok_r(NULL, " \t", &save)) {
char *colon = strrchr(tok, ':');
if (w->ncol == DSREF_MAX_COLS || !colon || !parse_type(colon + 1, &w->type[w->ncol])) {
fprintf(stderr, "%s: bad column spec '%s'\n", path, tok);
return 0;
}
w->ncol++;
}
w->f = fopen(path, "w");
if (!w->f) {
fprintf(stderr, "%s: cannot create: %s\n", path, strerror(errno));
return 0;
}
fprintf(w->f, "# xombe-dstar-ref 1\n# stage=%s\n# prec=%d\n# src=xombe\n%s\n", stage, w->prec, cols);
return 1;
}
static int wcol(dsref_writer *w, dsref_type t)
{
if (w->failed || !w->f)
return 0;
if (w->cur >= w->ncol || w->type[w->cur] != t) {
fprintf(stderr, "dsref writer: value %d is not of type %s\n", w->cur, dsref_type_name(t));
w->failed = 1;
return 0;
}
if (w->cur++)
fputc(' ', w->f);
return 1;
}
static void put_f(dsref_writer *w, double v)
{
if (v == 0.0)
fputs("0", w->f);
else if (isnan(v))
fputs("nan", w->f);
else
fprintf(w->f, "%.*g", w->prec, v);
}
void dsref_wi(dsref_writer *w, long v)
{
if (wcol(w, DSREF_INT))
fprintf(w->f, "%ld", v);
}
void dsref_wf(dsref_writer *w, double v)
{
if (wcol(w, DSREF_FLOAT))
put_f(w, v);
}
void dsref_ws(dsref_writer *w, const char *s)
{
if (wcol(w, DSREF_STR))
fputs(*s ? s : "-", w->f);
}
void dsref_wx(dsref_writer *w, const uint8_t *bytes, int n)
{
int k;
if (!wcol(w, DSREF_HEX))
return;
if (!n)
fputc('-', w->f);
for (k = 0; k < n; k++)
fprintf(w->f, "%02x", bytes[k]);
}
void dsref_wb(dsref_writer *w, const uint8_t *bits, int n)
{
int k;
if (!wcol(w, DSREF_BITS))
return;
if (!n)
fputc('-', w->f);
for (k = 0; k < n; k++)
fputc(bits[k] ? '1' : '0', w->f);
}
void dsref_wiv(dsref_writer *w, const long *v, int n)
{
int k;
if (!wcol(w, DSREF_IVEC))
return;
fprintf(w->f, "%d", n);
for (k = 0; k < n; k++)
fprintf(w->f, " %ld", v[k]);
}
void dsref_wiv_int(dsref_writer *w, const int *v, int n)
{
int k;
if (!wcol(w, DSREF_IVEC))
return;
fprintf(w->f, "%d", n);
for (k = 0; k < n; k++)
fprintf(w->f, " %d", v[k]);
}
void dsref_wfv(dsref_writer *w, const double *v, int n)
{
int k;
if (!wcol(w, DSREF_FVEC))
return;
fprintf(w->f, "%d", n);
for (k = 0; k < n; k++) {
fputc(' ', w->f);
put_f(w, v[k]);
}
}
void dsref_wfv_float(dsref_writer *w, const float *v, int n)
{
int k;
if (!wcol(w, DSREF_FVEC))
return;
fprintf(w->f, "%d", n);
for (k = 0; k < n; k++) {
fputc(' ', w->f);
put_f(w, v[k]);
}
}
void dsref_wend(dsref_writer *w)
{
if (!w->f || w->failed)
return;
if (w->cur != w->ncol) {
fprintf(stderr, "dsref writer: record has %d values, %d columns\n", w->cur, w->ncol);
w->failed = 1;
return;
}
fputc('\n', w->f);
w->cur = 0;
}
int dsref_wclose(dsref_writer *w)
{
int ok = w->f && !w->failed && w->cur == 0;
if (w->f) {
if (ferror(w->f) || fclose(w->f))
ok = 0;
}
w->f = NULL;
return ok;
}
+104
View File
@@ -0,0 +1,104 @@
#ifndef XOMBE_TEST_DSTAR_REF_H
#define XOMBE_TEST_DSTAR_REF_H
/* reader and writer for the D-STAR reference records, the writer for stage dumps test/dstar_cmp.py compares
a record file is text, gzip-compressed if the path ends in .gz (read through gzip -dc):
# xombe-dstar-ref 1 meta lines start with '#', "# key=value" lines are kept
# stage=fec
n:i in:x ea:i ... a:f* column line, name:type, types i f s x b i* f*
0 9e8d32... 0 ... 3 0.5 1 2 one record per line, whitespace separated
i integer, f float (nan allowed), s token, x hex bytes, b string of 0/1, '-' is an empty s/x/b
i* and f*: a count followed by that many values */
#include <stdint.h>
#include <stdio.h>
#define DSREF_MAX_COLS 64
#define DSREF_NAME_LEN 32
#define DSREF_MAX_META 16
typedef enum { DSREF_INT, DSREF_FLOAT, DSREF_STR, DSREF_HEX, DSREF_BITS, DSREF_IVEC, DSREF_FVEC } dsref_type;
typedef struct {
char name[DSREF_NAME_LEN];
dsref_type type;
/* the current record's value */
long i;
double f;
int len; /* vector or token length, byte or bit count, 1 for i and f */
const char *s; /* s, x, and b: the token ("" for '-') */
long *iv;
double *fv;
uint8_t *bytes; /* x: decoded bytes, b: one 0/1 per bit */
size_t cap;
} dsref_column;
typedef struct {
const char *path;
FILE *f;
long pid;
char *line;
size_t line_cap;
long lineno;
long nrec;
int failed;
int ncol;
dsref_column col[DSREF_MAX_COLS];
int nmeta;
char meta_key[DSREF_MAX_META][DSREF_NAME_LEN];
char meta_val[DSREF_MAX_META][128];
} dsref;
/* opens path and reads the meta and column lines, returns 0 (reported) on failure */
int dsref_open(dsref *r, const char *path);
/* reads the next record: 1, 0 at the end, -1 on a malformed record (reported) */
int dsref_next(dsref *r);
/* returns 1 if the file was opened and read without error */
int dsref_close(dsref *r);
/* column index of name, or -1 */
int dsref_col(const dsref *r, const char *name);
/* column index of name with the given type, a missing column or another type is reported and fails the file (-1) */
int dsref_need(dsref *r, const char *name, dsref_type type);
/* "# key=value" meta value, or NULL */
const char *dsref_meta(const dsref *r, const char *key);
static inline long dsref_i(const dsref *r, int c) { return r->col[c].i; }
static inline double dsref_f(const dsref *r, int c) { return r->col[c].f; }
static inline int dsref_len(const dsref *r, int c) { return r->col[c].len; }
static inline const char *dsref_s(const dsref *r, int c) { return r->col[c].s; }
static inline const long *dsref_iv(const dsref *r, int c) { return r->col[c].iv; }
static inline const double *dsref_fv(const dsref *r, int c) { return r->col[c].fv; }
static inline const uint8_t *dsref_bytes(const dsref *r, int c) { return r->col[c].bytes; }
const char *dsref_type_name(dsref_type t);
/* whole binary files, PCM (int16 little endian) and 9-byte frame streams
return malloc'd data (free() it) and the count, or NULL (reported) */
int16_t *dsref_read_pcm(const char *path, long *nsamples);
uint8_t *dsref_read_frames(const char *path, int frame_bytes, long *nframes);
typedef struct {
FILE *f;
int ncol, cur, prec;
dsref_type type[DSREF_MAX_COLS];
int failed;
} dsref_writer;
/* writes the meta and column lines, prec = significant digits of floats (9 if 0) */
int dsref_wopen(dsref_writer *w, const char *path, const char *stage, const char *cols, int prec);
void dsref_wi(dsref_writer *w, long v);
void dsref_wf(dsref_writer *w, double v);
void dsref_ws(dsref_writer *w, const char *s);
void dsref_wx(dsref_writer *w, const uint8_t *bytes, int n);
void dsref_wb(dsref_writer *w, const uint8_t *bits, int n);
void dsref_wiv(dsref_writer *w, const long *v, int n);
void dsref_wiv_int(dsref_writer *w, const int *v, int n);
void dsref_wfv(dsref_writer *w, const double *v, int n);
void dsref_wfv_float(dsref_writer *w, const float *v, int n);
/* ends the record, a wrong number of values or a type mismatch fails the writer */
void dsref_wend(dsref_writer *w);
/* returns 1 if every record was written correctly */
int dsref_wclose(dsref_writer *w);
#endif
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# q15ops_arm.sh CC QEMU SRC OUT: test_q15ops built for a Cortex-M33 (DSP extension) and run under qemu-arm
# with semihosting, checking q15ops.h's intrinsics as the host run checks the fallback
set -e
"$1" -mcpu=cortex-m33 -mthumb -O2 -std=c99 -Wall -Wextra -Werror --specs=rdimon.specs \
-Wl,-Ttext-segment=0x100000 "$3/test/test_q15ops.c" -o "$4/test_q15ops_m33.elf" -lm
"$2" -cpu cortex-m33 "$4/test_q15ops_m33.elf"
+66
View File
@@ -0,0 +1,66 @@
#ifndef XOMBE_TEST_REF_H
#define XOMBE_TEST_REF_H
/* double-precision references for the generated tables (scripts/gen_dsp_tables.py) and the tests */
#include <math.h>
#include "../src/internal.h"
#include "../src/dsp/biquad.h"
static inline double ref_hamming(int i, int n)
{
return 0.54 - 0.46 * cos(2.0 * XOMBE_PI * i / (n - 1));
}
/* solves a*x = b (n x n, row-major) in place by Gaussian elimination with partial pivoting, x replaces b
returns 0 if a is singular */
static inline int ref_solve(double *a, double *b, int n)
{
int i, j, k;
for (i = 0; i < n; i++) {
int piv = i;
for (j = i + 1; j < n; j++)
if (fabs(a[j * n + i]) > fabs(a[piv * n + i]))
piv = j;
if (fabs(a[piv * n + i]) < 1e-12)
return 0;
for (k = 0; k < n; k++) {
double t = a[i * n + k];
a[i * n + k] = a[piv * n + k];
a[piv * n + k] = t;
}
{
double t = b[i];
b[i] = b[piv];
b[piv] = t;
}
for (j = i + 1; j < n; j++) {
double m = a[j * n + i] / a[i * n + i];
for (k = i; k < n; k++)
a[j * n + k] -= m * a[i * n + k];
b[j] -= m * b[i];
}
}
for (i = n - 1; i >= 0; i--) {
for (k = i + 1; k < n; k++)
b[i] -= a[i * n + k] * b[k];
b[i] /= a[i * n + i];
}
return 1;
}
/* codec high-pass power gain at f_hz, dB */
static inline double ref_hpf_gain_db(double f_hz)
{
double w = 2.0 * XOMBE_PI * f_hz / XOMBE_FS;
double cr = cos(w), ci = -sin(w), c2r = cos(2 * w), c2i = -sin(2 * w);
double zr = 1.0 - cr, zi = -ci;
double nr = zr * zr - zi * zi, ni = 2.0 * zr * zi, n3r = nr * zr - ni * zi, n3i = nr * zi + ni * zr;
double d1r = 1.0 - HPF_POLE1 * cr, d1i = -HPF_POLE1 * ci;
double d2r = 1.0 - HPF_A1 * cr + HPF_A2 * c2r, d2i = -HPF_A1 * ci + HPF_A2 * c2i;
double num = n3r * n3r + n3i * n3i;
double den = (d1r * d1r + d1i * d1i) * (d2r * d2r + d2i * d2i);
return 10.0 * log10(num / den);
}
#endif
+115
View File
@@ -0,0 +1,115 @@
#include <stdio.h>
#include <string.h>
#include "xombe.h"
/* prints this build's row of the size table (scripts/size_table.sh) and checks every *_size() <= its *_SIZE.
usage: sizes [--header] */
static int failures;
static void check(size_t got, size_t max, const char *what)
{
if (got > max) {
failures++;
fprintf(stderr, "FAIL %s: %zu > %zu\n", what, got, max);
}
}
#if XOMBE_HAVE_DSTAR
/* state and workspace bytes xombe_xc_init_shared writes for one input codec (it zeroes both in full): the last
byte off its fill, over two fills */
static void shared_bytes(enum xombe_codec from, size_t *state, size_t *ws)
{
static unsigned char mem[2][XOMBE_XC_SIZE]; /* larger than any shared state */
static unsigned char qws[2][XOMBE_QWS_SIZE];
static const unsigned char pat[2] = {0xA5, 0x5A};
size_t s[2], w[2];
int i;
for (i = 0; i < 2; i++) {
memset(mem[i], pat[i], sizeof(mem[i]));
memset(qws[i], pat[i], sizeof(qws[i]));
xombe_xc_init_shared(mem[i], from, qws[i]);
}
for (i = 0; i < 2; i++) {
size_t k = sizeof(mem[i]);
while (k > 0 && mem[i][k - 1] == pat[i])
k--;
s[i] = k;
k = sizeof(qws[i]);
while (k > 0 && qws[i][k - 1] == pat[i])
k--;
w[i] = k;
}
*state = s[0] > s[1] ? s[0] : s[1];
*ws = w[0] > w[1] ? w[0] : w[1];
}
#endif
int main(int argc, char **argv)
{
char row[1024];
size_t n = 0;
if (argc > 1 && !strcmp(argv[1], "--header")) {
printf("| kernels | D-STAR | enc | enc delay DMR / D-STAR / both | dec | xc | xc shared DMR / D-STAR | QWS |\n");
printf("|---|---|---|---|---|---|---|---|\n");
return 0;
}
n += (size_t)snprintf(row + n, sizeof(row) - n, "| %s | %s |", XOMBE_KERNELS_Q15 ? "q15" : "float",
XOMBE_HAVE_DSTAR ? "on" : "off");
#if XOMBE_HAVE_ENCODER
{
static xombe_enc_mem mem;
static const unsigned outs[3] = {XOMBE_ENC_DMR, XOMBE_ENC_DSTAR, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR};
xombe_enc_cfg cfg;
int i;
check(xombe_enc_size(), XOMBE_ENC_SIZE, "xombe_enc_size");
n += (size_t)snprintf(row + n, sizeof(row) - n, " %zu |", xombe_enc_size());
for (i = 0; i < 3; i++) {
xombe_enc *e;
xombe_enc_cfg_default(&cfg);
cfg.outputs = outs[i];
e = xombe_enc_init(&mem, &cfg);
if (e)
n += (size_t)snprintf(row + n, sizeof(row) - n, "%s%d", i ? " / " : " ", xombe_enc_delay(e));
else
n += (size_t)snprintf(row + n, sizeof(row) - n, "%s-", i ? " / " : " ");
if (!e && !(outs[i] & XOMBE_ENC_DSTAR)) {
failures++;
fprintf(stderr, "FAIL encoder init, outputs %u\n", outs[i]);
}
}
n += (size_t)snprintf(row + n, sizeof(row) - n, " |");
}
#else
n += (size_t)snprintf(row + n, sizeof(row) - n, " - | - |");
#endif
check(xombe_dec_size(), XOMBE_DEC_SIZE, "xombe_dec_size");
n += (size_t)snprintf(row + n, sizeof(row) - n, " %zu |", xombe_dec_size());
#if XOMBE_HAVE_DSTAR
{
size_t st, ws, qws;
check(xombe_xc_size(), XOMBE_XC_SIZE, "xombe_xc_size");
shared_bytes(XOMBE_DMR, &st, &ws);
check(st, XOMBE_XC_SHARED_SIZE, "xc shared state from DMR");
check(ws, XOMBE_QWS_SIZE, "xc workspace from DMR");
qws = ws;
n += (size_t)snprintf(row + n, sizeof(row) - n, " %zu | %zu", xombe_xc_size(), st);
#if XOMBE_HAVE_ENCODER
shared_bytes(XOMBE_DSTAR, &st, &ws);
check(st, XOMBE_XC_SHARED_SIZE, "xc shared state from D-STAR");
check(ws, XOMBE_QWS_SIZE, "xc workspace from D-STAR");
qws = ws > qws ? ws : qws;
n += (size_t)snprintf(row + n, sizeof(row) - n, " / %zu |", st);
#else
n += (size_t)snprintf(row + n, sizeof(row) - n, " / - |");
#endif
n += (size_t)snprintf(row + n, sizeof(row) - n, " %zu |", qws);
}
#else
n += (size_t)snprintf(row + n, sizeof(row) - n, " - | - | - |");
#endif
puts(row);
if (failures)
fprintf(stderr, "sizes: %d failures\n", failures);
return failures != 0;
}
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""usage: snapcmp.py [-v] A B, compares two test/snapshot.sh outputs, exit 0 when identical
per output: frames changed for each bitstream (AMBE+2 .amb, air, D-STAR, dual, xc, xr) and samples changed with the
largest difference for each decoder output, then totals per output kind. -v also lists unchanged files"""
import os
import sys
from array import array
AMB_HEADER = b".amb"
AMB_RECORD = 8
AIR_RECORD = 9 # air frames, D-STAR frames, and rate-33 frames are all 72 bits
def kind(path):
"""output kind and frame size (0: 16-bit PCM, None: compared as text) of a snapshot file"""
top, name = path.split("/", 1)
if name.endswith(".err"):
return "stderr", None
if top == "dec":
return "decoder", 0
if top == "xc":
return ("xc", AIR_RECORD) if name.endswith(".dstar") else ("xr", AIR_RECORD)
for suffix, k, n in ((".dual.amb", "dual AMBE+2", AMB_RECORD), (".dual.dstar", "dual D-STAR", AIR_RECORD),
(".dsdtx.dstar", "D-STAR dtx", AIR_RECORD), (".dstar", "D-STAR", AIR_RECORD),
(".air", "AMBE+2 air", AIR_RECORD), (".amb", "AMBE+2", AMB_RECORD)):
if name.endswith(suffix):
return k, n
return "other", None
def frames(data, n):
if n == AMB_RECORD and data.startswith(AMB_HEADER):
data = data[len(AMB_HEADER):]
return [data[i:i + n] for i in range(0, len(data), n)]
def pcm(data):
a = array("h")
a.frombytes(data[:len(data) & ~1])
if sys.byteorder != "little":
a.byteswap()
return a
def compare(a, b, n):
"""(changed, total, detail) for one file pair"""
if n is None:
la, lb = a.decode(errors="replace").splitlines(), b.decode(errors="replace").splitlines()
changed = sum(x != y for x, y in zip(la, lb)) + abs(len(la) - len(lb))
return changed, max(len(la), len(lb)), "lines"
if n == 0:
sa, sb = pcm(a), pcm(b)
diffs = [abs(x - y) for x, y in zip(sa, sb) if x != y]
extra = abs(len(sa) - len(sb))
detail = "samples, max diff %d" % max(diffs) if diffs else "samples"
if extra:
detail += ", length %d vs %d" % (len(sa), len(sb))
return len(diffs) + extra, max(len(sa), len(sb)), detail
fa, fb = frames(a, n), frames(b, n)
changed = sum(x != y for x, y in zip(fa, fb)) + abs(len(fa) - len(fb))
detail = "frames" if len(fa) == len(fb) else "frames, length %d vs %d" % (len(fa), len(fb))
return changed, max(len(fa), len(fb)), detail
def files(root):
out = set()
for d in ("dec", "enc", "xc"):
top = os.path.join(root, d)
if os.path.isdir(top):
out.update(d + "/" + f for f in os.listdir(top))
return out
def read(path):
with open(path, "rb") as f:
return f.read()
def main(argv):
verbose = "-v" in argv
args = [a for a in argv if a != "-v"]
if len(args) != 2:
sys.exit(__doc__)
ra, rb = args
totals = {}
differ = 0
for path in sorted(files(ra) | files(rb)):
k, n = kind(path)
pa, pb = os.path.join(ra, path), os.path.join(rb, path)
if not os.path.exists(pa) or not os.path.exists(pb):
print("%s: only in %s" % (path, ra if os.path.exists(pa) else rb))
differ = 1
continue
a, b = read(pa), read(pb)
t = totals.setdefault(k, [0, 0, 0, 0, 0]) # files, files changed, units changed, units, max diff
t[0] += 1
if a == b:
if verbose:
print("%s: same" % path)
continue
changed, total, detail = compare(a, b, n)
t[1] += 1
t[2] += changed
t[3] += total
if n == 0 and "max diff" in detail:
t[4] = max(t[4], int(detail.split("max diff ")[1].split(",")[0]))
print("%s: %d of %d %s" % (path, changed, total, detail))
differ = 1
sa, sb = read(os.path.join(ra, "status")), read(os.path.join(rb, "status"))
if sa != sb:
print("status differs")
differ = 1
print("summary:")
for k in sorted(totals):
f, fc, uc, u, md = totals[k]
line = " %-12s %3d files, %3d changed" % (k, f, fc)
if fc:
unit = "lines" if kind_unit(k) is None else ("samples" if kind_unit(k) == 0 else "frames")
line += ", %d of %d %s in those" % (uc, u, unit)
if kind_unit(k) == 0:
line += ", max diff %d" % md
print(line)
print("identical" if not differ else "DIFFERENT")
return differ
def kind_unit(k):
return {"decoder": 0, "stderr": None, "other": None}.get(k, AIR_RECORD)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+106
View File
@@ -0,0 +1,106 @@
#!/bin/sh
# bit-exactness snapshot of a xombe source tree, compare two with test/snapcmp.py
#
# usage: snapshot.sh [-q] [-j N] [-D CMAKE_DEF]... SRC OUT
# SRC xombe source tree (a worktree or an exported `git archive`)
# OUT output dir, removed first if it exists, the build goes to OUT.build (reused, reconfigured each run)
# -q build with -DXOMBE_KERNELS=q15
# -j N build parallelism (default nproc)
# -D X extra cmake definition, e.g. -D XOMBE_DSTAR=OFF (repeatable)
#
# OUT holds one file per run, named <mode>/<vector path, / -> _>[.ext]:
# dec/ xombe-dec PCM for every .amb (default, --lost 3,10-12, --conformance-noise), .bits, .r33 (--air), .dstar
# (--dstar, and --lost 3,10-12), stream .jsonl.gz (--stream)
# enc/ xombe-enc for every .raw: .amb, --air, --dstar, --dual (amb + dstar), and --dstar-dtx on, each with
# default settings (def) and with --ns off --dtx off (quiet)
# xc/ xombe-xc forward on every .r33, --reverse on every .dstar
# status exit status of every run, a mode the build lacks shows as a nonzero status
# stderr of each run is kept as .err next to its output (it holds --decisions where used)
set -u
kern=
jobs=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
defs=
while getopts qj:D: o; do
case $o in
q) kern=-DXOMBE_KERNELS=q15 ;;
j) jobs=$OPTARG ;;
D) defs="$defs -D$OPTARG" ;;
*) sed -n '4,9p' "$0"; exit 2 ;;
esac
done
shift $((OPTIND - 1))
[ $# -eq 2 ] || { sed -n '4,9p' "$0"; exit 2; }
src=$(cd "$1" && pwd) || exit 2
out=$2
case $out in /*) ;; *) out=$(pwd)/$out ;; esac
bld=$out.build
# shellcheck disable=SC2086
cmake -S "$src" -B "$bld" -DCMAKE_BUILD_TYPE=Release -DXOMBE_BUILD_TOOLS=ON -DXOMBE_BUILD_TESTS=OFF $kern $defs \
>"$bld.log" 2>&1 &&
cmake --build "$bld" -j "$jobs" >>"$bld.log" 2>&1 || { echo "snapshot.sh: build failed, see $bld.log" >&2; exit 1; }
tdir=$(dirname "$(find "$bld" -name xombe-dec -type f -perm -u+x | head -1)")
[ -x "$tdir/xombe-dec" ] || { echo "snapshot.sh: no xombe-dec in $bld" >&2; exit 1; }
DEC=$tdir/xombe-dec ENC=$tdir/xombe-enc XC=$tdir/xombe-xc
rm -rf "$out"
mkdir -p "$out/dec" "$out/enc" "$out/xc"
st=$out/status
: >"$st"
# run NAME CMD...: CMD with stderr to NAME.err, its status recorded
run() {
n=$1; shift
"$@" 2>"$n.err"
echo "$? ${n#"$out"/}" >>"$st"
}
cd "$src" || exit 2
key() { echo "$1" | sed 's|^vectors/||; s|/|_|g'; }
for f in $(find vectors -name '*.amb' | sort); do
k=$out/dec/$(key "$f")
run "$k.raw" "$DEC" --decisions "$f" "$k.raw"
run "$k.lost.raw" "$DEC" --lost 3,10-12 "$f" "$k.lost.raw"
run "$k.conf.raw" "$DEC" --conformance-noise "$f" "$k.conf.raw"
done
for f in $(find vectors -name '*.bits' | sort); do
k=$out/dec/$(key "$f")
run "$k.raw" "$DEC" --bits --decisions "$f" "$k.raw"
done
for f in $(find vectors -name '*.r33' | sort); do
k=$out/dec/$(key "$f")
run "$k.raw" "$DEC" --air --decisions "$f" "$k.raw"
k=$out/xc/$(key "$f")
run "$k.dstar" "$XC" --decisions "$f" "$k.dstar"
done
for f in $(find vectors -name '*.dstar' | sort); do
k=$out/dec/$(key "$f")
run "$k.raw" "$DEC" --dstar --decisions "$f" "$k.raw"
run "$k.lost.raw" "$DEC" --dstar --lost 3,10-12 "$f" "$k.lost.raw"
k=$out/xc/$(key "$f")
run "$k.r33" "$XC" --reverse --decisions "$f" "$k.r33"
done
for f in $(find vectors -name '*.jsonl.gz' | sort); do
k=$out/dec/$(key "$f")
run "$k.raw" "$DEC" --stream "$f" "$k.raw"
done
for f in $(find vectors -name '*.raw' | sort); do
for set in def quiet; do
if [ $set = quiet ]; then o="--ns off --dtx off"; else o=; fi
k=$out/enc/$(key "$f").$set
# shellcheck disable=SC2086
{
run "$k.amb" "$ENC" $o "$f" "$k.amb"
run "$k.air" "$ENC" $o --air "$f" "$k.air"
run "$k.dstar" "$ENC" $o --dstar "$f" "$k.dstar"
run "$k.dual.amb" "$ENC" $o --dual "$k.dual.dstar" "$f" "$k.dual.amb"
run "$k.dsdtx.dstar" "$ENC" $o --dstar --dstar-dtx on "$f" "$k.dsdtx.dstar"
}
done
done
n=$(wc -l <"$st")
bad=$(awk '$1 != 0' "$st" | wc -l)
echo "snapshot.sh: $n runs into $out ($bad nonzero exits, see status)"
+786
View File
@@ -0,0 +1,786 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "xombe.h"
/* public API contracts: handles, sizes, argument checks, call order, and delays, public headers only. every
codec test runs for each codec built */
static int failures, checks;
static void check(int ok, const char *what)
{
checks++;
if (!ok) {
failures++;
fprintf(stderr, "FAIL %s\n", what);
}
}
static const char *codec_name(enum xombe_codec c)
{
return c == XOMBE_DSTAR ? "D-STAR" : "DMR";
}
static void checkc(int ok, enum xombe_codec c, const char *what)
{
char msg[256];
snprintf(msg, sizeof(msg), "%s: %s", codec_name(c), what);
check(ok, msg);
}
static const enum xombe_codec codecs[] = {
XOMBE_DMR,
#if XOMBE_HAVE_DSTAR
XOMBE_DSTAR,
#endif
};
#define NCODECS ((int)(sizeof(codecs) / sizeof(codecs[0])))
static const uint8_t dmr_silence_bits[XOMBE_BITS_BYTES] = {0xF8, 0x01, 0xA9, 0x9F, 0x8C, 0xE0, 0x80};
static const uint8_t dstar_null_frame[XOMBE_FRAME_BYTES] = {0x9E, 0x8D, 0x32, 0x88, 0x26, 0x1A, 0x3F, 0x61, 0xE8};
static const uint8_t dstar_null_bits[XOMBE_BITS_BYTES] = {0xF8, 0x54, 0xAA, 0x9D, 0xE8, 0x0A, 0x00};
static const uint8_t fill[XOMBE_FRAME_BYTES] = {0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5};
/* each codec's silence frame (DMR silence, D-STAR null frame) and its voice bits */
static uint8_t silence_frame[2][XOMBE_FRAME_BYTES];
static const uint8_t *const silence_bits[2] = {dmr_silence_bits, dstar_null_bits};
static void setup_frames(void)
{
uint8_t f[XOMBE_FRAME_BYTES];
xombe_fec_encode(XOMBE_DMR, dmr_silence_bits, silence_frame[XOMBE_DMR]);
memcpy(silence_frame[XOMBE_DSTAR], dstar_null_frame, XOMBE_FRAME_BYTES);
memcpy(f, fill, sizeof(f));
check(xombe_fec_encode(XOMBE_DSTAR, dstar_null_bits, f) == (XOMBE_HAVE_DSTAR ? 0 : -1) &&
!memcmp(f, XOMBE_HAVE_DSTAR ? dstar_null_frame : fill, sizeof(f)),
"D-STAR null frame from its voice bits, refused without D-STAR");
}
/* pseudo-random frame n: every tenth the silence frame, every third a clean one from random voice bits */
static void stream_frame(enum xombe_codec c, int n, uint8_t fr[XOMBE_FRAME_BYTES])
{
int i;
for (i = 0; i < XOMBE_FRAME_BYTES; i++)
fr[i] = (uint8_t)((n * 131 + i * 71 + (n * i) % 13) & 0xff);
if (n % 10 == 3) {
memcpy(fr, silence_frame[c], XOMBE_FRAME_BYTES);
} else if (n % 3 == 0) {
uint8_t bits[XOMBE_BITS_BYTES];
for (i = 0; i < XOMBE_BITS_BYTES; i++)
bits[i] = (uint8_t)(n * 37 + i * 101);
bits[0] &= 0x7f;
bits[6] &= c == XOMBE_DMR ? 0x80 : 0x00;
xombe_fec_encode(c, bits, fr);
}
}
static int popcount_bytes(const uint8_t *a, const uint8_t *b, int n)
{
int i, k = 0;
for (i = 0; i < n; i++) {
unsigned v = (unsigned)(a[i] ^ b[i]);
while (v) {
k += v & 1;
v >>= 1;
}
}
return k;
}
static void test_fec(enum xombe_codec c)
{
xombe_fec f;
xombe_fec_stats st;
uint8_t bits[XOMBE_BITS_BYTES], back[XOMBE_BITS_BYTES], fr[XOMBE_FRAME_BYTES];
int n, i, round = 1, flipped = 1, rate = 1;
checkc(xombe_fec_init(&f, c) == 0, c, "fec init");
for (n = 0; n < 72; n++) {
int diff;
for (i = 0; i < XOMBE_BITS_BYTES; i++)
bits[i] = (uint8_t)(n * 53 + i * 29 + n * i);
bits[6] &= c == XOMBE_DMR ? 0x80 : 0x00;
checkc(xombe_fec_encode(c, bits, fr) == 0, c, "fec encode");
round &= xombe_fec_decode(&f, fr, back, n % 2 ? NULL : &st) == 0 && !memcmp(bits, back, sizeof(bits));
if (n % 2 == 0)
round &= st.eps0 == 0 && st.eps1 == 0 && st.eps_t == 0 && !st.bf && !st.hb;
fr[n / 8] ^= (uint8_t)(0x80 >> (n % 8));
xombe_fec_decode(&f, fr, back, &st);
diff = popcount_bytes(bits, back, XOMBE_BITS_BYTES);
flipped &= diff <= 1 && st.eps_t <= 1 && (diff == 0 || st.eps_t == 0) && st.eps_t == st.eps0 + st.eps1;
rate &= st.eps_r > 0;
}
checkc(round, c, "fec round trip of clean frames, no corrections, NULL stats accepted");
checkc(flipped, c, "any single flipped bit is corrected, or reaches the voice bits as one bit");
checkc(rate, c, "the running error rate counts the corrections");
}
static void test_decoder(enum xombe_codec c)
{
const uint8_t *silence = silence_frame[c];
static xombe_dec_mem mem;
int16_t pcm[XOMBE_HALF_MAX];
xombe_dec *d, *h;
void *heap;
checkc(xombe_dec_init(NULL, c) == NULL, c, "decoder init rejects NULL");
checkc(xombe_dec_size() <= XOMBE_DEC_SIZE, c, "decoder size within XOMBE_DEC_SIZE");
d = xombe_dec_init(&mem, c);
checkc(d == (xombe_dec *)&mem, c, "decoder handle is the caller's memory");
{
xombe_decision r;
xombe_dec_decision_get(d, &r);
checkc(r.mute_src == -1 && r.e0 == -1 && r.e1 == -1 && r.run == 0, c, "decision before the first frame");
}
checkc(xombe_dec_set_noise(d, (enum xombe_noise_mode)7, 1) == -1, c, "set_noise rejects an unknown mode");
checkc(xombe_dec_set_noise(d, XOMBE_NOISE_PRODUCTION, 1) == 0, c, "set_noise accepts production");
checkc(xombe_dec_set_noise(d, XOMBE_NOISE_CONFORMANCE, 0) == 0, c, "set_noise accepts conformance");
{
static xombe_dec_mem m[3];
xombe_dec *def = xombe_dec_init(&m[0], c), *prod = xombe_dec_init(&m[1], c);
xombe_dec *conf = xombe_dec_init(&m[2], c);
int16_t a[160], b[160], cc[160];
int f, same_prod = 1, same_conf = 1;
xombe_dec_set_noise(prod, XOMBE_NOISE_PRODUCTION, 0);
xombe_dec_set_noise(conf, XOMBE_NOISE_CONFORMANCE, 0);
for (f = 0; f < 4; f++) {
xombe_dec_frame(def, silence, 0, a);
xombe_dec_frame(prod, silence, 0, b);
xombe_dec_frame(conf, silence, 0, cc);
same_prod &= !memcmp(a, b, sizeof(a));
same_conf &= !memcmp(a, cc, sizeof(a));
}
checkc(same_prod && !same_conf, c, "default noise source is production, seed 0");
}
d = xombe_dec_init(&mem, c);
checkc(xombe_dec_half(d, silence, 0, 1, 80, pcm) == -1, c, "second half before a first half is refused");
checkc(xombe_dec_half(d, silence, 0, 0, 200, pcm) == XOMBE_HALF_MAX, c, "first half, length clamped up to 84");
checkc(xombe_dec_half(d, silence, 0, 0, 80, pcm) == -1, c, "two first halves in a row are refused");
checkc(xombe_dec_half(d, silence, 0, 1, 10, pcm) == XOMBE_HALF_MIN, c, "second half, length clamped to 76");
checkc(xombe_dec_half(d, silence, 0, 1, 80, pcm) == -1, c, "two second halves in a row are refused");
checkc(xombe_dec_half(d, silence, 0, 0, 80, pcm) == 80 && xombe_dec_half(d, NULL, 0, 1, 80, pcm) == 80, c,
"second half reads no frame");
checkc(xombe_dec_half_bits(d, NULL, 0, 1, 80, pcm) == -1, c, "bits second half before a first half is refused");
checkc(xombe_dec_half_bits(d, silence_bits[c], 0, 0, 80, pcm) == 80 &&
xombe_dec_half_bits(d, NULL, 0, 1, 80, pcm) == 80,
c, "bits second half reads no bits");
{
static xombe_dec_mem lone_mem, twin_mem;
xombe_dec *lone = xombe_dec_init(&lone_mem, c), *twin = xombe_dec_init(&twin_mem, c);
int16_t full[160], want[160];
int i, zeros = 1;
xombe_dec_half(lone, silence, 0, 0, 80, pcm);
xombe_dec_half(twin, silence, 0, 0, 80, want);
xombe_dec_half(twin, NULL, 0, 1, 80, want + 80);
for (i = 0; i < 160; i++)
full[i] = 0x5555;
checkc(xombe_dec_frame(lone, silence, 0, full) == 0, c, "frame after an unpaired first half returns 0");
for (i = 0; i < 80; i++)
zeros &= full[i] == 0;
checkc(zeros && !memcmp(full + 80, want + 80, 80 * sizeof(*full)), c,
"frame after an unpaired first half: zeros, then the pending second half");
checkc(xombe_dec_frame(lone, silence, 0, full) == 1, c, "the next frame returns 1");
xombe_dec_frame(twin, silence, 0, want);
checkc(!memcmp(full, want, sizeof(full)), c, "the next frame decodes normally");
xombe_dec_half_bits(lone, silence_bits[c], 0, 0, 80, pcm);
checkc(xombe_dec_frame_bits(lone, silence_bits[c], 0, full) == 0, c,
"bits frame after an unpaired first half returns 0");
}
{
xombe_decision r;
int16_t f[160];
xombe_dec_frame(d, silence, 0, f);
xombe_dec_decision_get(d, &r);
checkc(r.cls == XOMBE_CLASS_SILENCE && r.conceal == XOMBE_CONCEAL_NONE && r.e0 == 0 && r.e1 == 0, c,
"decision of a silence frame");
}
{
/* a lost frame plays as a bad frame, without reading bits. D-STAR's bad voice frames never mute, so its
run stays short of the mute */
static xombe_dec_mem lm, bm;
xombe_dec *l = xombe_dec_init(&lm, c), *b = xombe_dec_init(&bm, c);
static const uint8_t zero[XOMBE_BITS_BYTES];
int16_t pl[160], pb[160];
int i, same = 1, erasure = 1, last_lost = c == XOMBE_DMR ? 6 : 3;
for (i = 0; i < 8; i++) {
xombe_decision r;
unsigned lost = i >= 2 && i <= last_lost;
xombe_dec_frame_bits(l, lost ? NULL : silence_bits[c], lost ? XOMBE_FLAG_LOST : 0, pl);
xombe_dec_frame_bits(b, lost ? zero : silence_bits[c], lost ? XOMBE_FLAG_BF : 0, pb);
same &= !memcmp(pl, pb, sizeof(pl));
xombe_dec_decision_get(l, &r);
if (lost)
erasure &= r.cls == XOMBE_CLASS_ERASURE && r.conceal != XOMBE_CONCEAL_NONE && r.run == i - 1 &&
r.e0 == -1 && r.e1 == -1 && !r.bf && !r.hb;
}
checkc(same, c, "XOMBE_FLAG_LOST plays as XOMBE_FLAG_BF");
checkc(erasure, c, "decision of a lost frame: erasure, concealed, run counts it");
}
heap = malloc(xombe_dec_size());
h = xombe_dec_init(heap, c);
if (h) {
int16_t a[160], b[160];
int i;
d = xombe_dec_init(&mem, c);
for (i = 0; i < 20; i++) {
xombe_dec_frame(d, silence, 0, a);
xombe_dec_frame(h, silence, 0, b);
}
checkc(!memcmp(a, b, sizeof(a)), c, "malloc'd and static decoders agree");
}
checkc(h != NULL, c, "decoder in malloc'd memory");
free(heap);
}
/* frame calls equal the caller's own FEC into the *_bits calls, and two half calls */
static void test_decoder_bits(enum xombe_codec c)
{
static xombe_dec_mem am, bm, hm;
xombe_dec *a = xombe_dec_init(&am, c), *b = xombe_dec_init(&bm, c), *h = xombe_dec_init(&hm, c);
xombe_fec fec;
int n, same = 1, halves = 1, decided = 1, seen = 0;
xombe_fec_init(&fec, c);
for (n = 0; n < 300; n++) {
uint8_t fr[XOMBE_FRAME_BYTES], bits[XOMBE_BITS_BYTES];
int16_t pa[160], pb[160], ph[160];
unsigned lost = n % 41 >= 7 && n % 41 < 11 ? XOMBE_FLAG_LOST : 0, flags = XOMBE_FLAG_LOST;
xombe_fec_stats st;
xombe_decision ra, rb;
stream_frame(c, n, fr);
same &= xombe_dec_frame(a, lost ? NULL : fr, lost, pa) == 1;
if (!lost) {
flags = xombe_fec_decode(&fec, fr, bits, &st);
xombe_dec_set_errors(b, st.eps_t, st.eps1);
}
same &= xombe_dec_frame_bits(b, lost ? NULL : bits, flags, pb) == 1;
halves &= xombe_dec_half(h, lost ? NULL : fr, lost, 0, 80, ph) == 80 &&
xombe_dec_half(h, NULL, 0, 1, 80, ph + 80) == 80 && !memcmp(pa, ph, sizeof(pa));
same &= !memcmp(pa, pb, sizeof(pa));
xombe_dec_decision_get(a, &ra);
xombe_dec_decision_get(b, &rb);
decided &= ra.cls == rb.cls && ra.conceal == rb.conceal && ra.run == rb.run && ra.mute_src == rb.mute_src &&
ra.bf == rb.bf && ra.hb == rb.hb && rb.e0 == -1 && rb.e1 == -1;
decided &= lost ? ra.e0 == -1 && ra.e1 == -1 && !ra.bf && !ra.hb
: ra.e0 == st.eps0 && ra.e1 == st.eps1 && ra.bf == st.bf && ra.hb == st.hb;
if (ra.conceal == XOMBE_CONCEAL_NONE)
seen |= 1 << ra.cls;
else
seen |= 1 << (4 + ra.conceal);
}
checkc(same, c, "xombe_dec_frame equals xombe_fec_decode, xombe_dec_set_errors, and xombe_dec_frame_bits");
checkc(halves, c, "xombe_dec_frame equals two xombe_dec_half calls");
checkc(decided, c, "frame decisions: the bits one with the Golay corrections");
checkc((seen & 0x65) == 0x65, c, "the stream plays voice, silence, repeats, and mutes");
}
/* tone frames: same ID and level rules as forced tones, refused calls write nothing, decoded as tones */
static void test_tone_frames(enum xombe_codec c)
{
static const int bad[][2] = {{0, 90}, {4, 90}, {123, 90}, {127, 90}, {164, 90}, {-1, 90}, {255, 90},
{5, -1}, {5, 128}, {129, 1000}};
static const int good[][2] = {{5, 0}, {122, 127}, {128, 64}, {163, 1}};
static xombe_dec_mem dm;
xombe_dec *d = xombe_dec_init(&dm, c);
uint8_t f[XOMBE_FRAME_BYTES];
int16_t pcm[160];
unsigned i;
int refused = 1, accepted = 1, knox = 1;
for (i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
memcpy(f, fill, sizeof(f));
refused &= xombe_tone_frame(c, bad[i][0], bad[i][1], f) == -1 && !memcmp(f, fill, sizeof(f));
}
for (i = 0; i < sizeof(good) / sizeof(good[0]); i++) {
xombe_decision r;
accepted &= xombe_tone_frame(c, good[i][0], good[i][1], f) == 0;
xombe_dec_frame(d, f, 0, pcm);
xombe_dec_decision_get(d, &r);
accepted &= r.cls == XOMBE_CLASS_TONE && r.conceal == XOMBE_CONCEAL_NONE && r.e0 == 0 && r.e1 == 0;
}
for (i = 144; i <= 159; i++) {
int r;
memcpy(f, fill, sizeof(f));
r = xombe_tone_frame(c, (int)i, 90, f);
knox &= c == XOMBE_DMR ? r == 0 : r == -1 && !memcmp(f, fill, sizeof(f));
}
checkc(refused, c, "xombe_tone_frame refuses IDs outside 5..122, 128..163 and levels outside 0..127");
checkc(accepted, c, "xombe_tone_frame takes range ends, its frames decode as clean tones");
checkc(knox, c, "Knox tone frames: DMR has them, D-STAR refuses them and writes nothing");
}
/* calls naming a codec the build lacks, or none at all */
static void test_codecs(void)
{
static xombe_dec_mem dm;
xombe_fec f, g;
uint8_t fr[XOMBE_FRAME_BYTES];
memset(&f, 0x5A, sizeof(f));
g = f;
check(xombe_dec_init(&dm, (enum xombe_codec)7) == NULL, "decoder init refuses an unknown codec");
check(xombe_fec_init(&f, (enum xombe_codec)7) == -1 && !memcmp(&f, &g, sizeof(f)),
"fec init refuses an unknown codec, f unchanged");
memcpy(fr, fill, sizeof(fr));
check(xombe_fec_encode((enum xombe_codec)7, dmr_silence_bits, fr) == -1 && !memcmp(fr, fill, sizeof(fr)),
"fec encode refuses an unknown codec, writes nothing");
check(xombe_tone_frame((enum xombe_codec)7, 128, 64, fr) == -1 && !memcmp(fr, fill, sizeof(fr)),
"tone frame refuses an unknown codec, writes nothing");
check((xombe_dec_init(&dm, XOMBE_DSTAR) != NULL) == XOMBE_HAVE_DSTAR, "D-STAR decoder only in a D-STAR build");
check((xombe_fec_init(&f, XOMBE_DSTAR) == 0) == XOMBE_HAVE_DSTAR, "D-STAR FEC only in a D-STAR build");
check((xombe_tone_frame(XOMBE_DSTAR, 128, 64, fr) == 0) == XOMBE_HAVE_DSTAR,
"D-STAR tone frames only in a D-STAR build");
#if XOMBE_HAVE_DSTAR
{
xombe_fec_stats st;
uint8_t bits[XOMBE_BITS_BYTES];
xombe_fec_init(&f, XOMBE_DSTAR);
check(xombe_fec_decode(&f, dstar_null_frame, bits, &st) == 0 && !memcmp(bits, dstar_null_bits, 7),
"D-STAR null frame's voice bits");
}
#endif
}
#if XOMBE_HAVE_ENCODER
/* harmonic signal that comes and goes */
static void test_signal(int n, int16_t pcm[160])
{
int i;
for (i = 0; i < 160; i++) {
float t = (float)(n * 160 + i), x = 0.0f;
int h;
if ((n / 20) % 2 == 0)
for (h = 1; h <= 8; h++)
x += 1500.0f / (float)h * sinf(0.0393f * (float)h * t + 0.3f * (float)h);
pcm[i] = (int16_t)(x + (float)((n * 160 + i) * 7919 % 61) - 30.0f);
}
}
#if XOMBE_HAVE_DSTAR
#define ALL_OUTPUTS (XOMBE_ENC_DMR | XOMBE_ENC_DSTAR)
#else
#define ALL_OUTPUTS XOMBE_ENC_DMR
#endif
static void test_encoder(void)
{
static xombe_enc_mem mem;
xombe_enc_cfg cfg;
int16_t pcm[160];
uint8_t f[XOMBE_FRAME_BYTES];
int i, got = 0;
check(xombe_enc_size() <= XOMBE_ENC_SIZE, "encoder size within XOMBE_ENC_SIZE");
check(xombe_enc_init(NULL, NULL) == NULL, "encoder init rejects NULL");
check(xombe_enc_init(&mem, NULL) != NULL, "encoder init with default settings");
xombe_enc_cfg_default(&cfg);
cfg.ns_strength_permille = -1;
check(xombe_enc_init(&mem, &cfg) == NULL, "ns_strength_permille below 0 is refused");
cfg.ns_strength_permille = 1001;
check(xombe_enc_init(&mem, &cfg) == NULL, "ns_strength_permille above 1000 is refused");
cfg.ns_strength_permille = 0;
check(xombe_enc_init(&mem, &cfg) != NULL, "ns_strength_permille 0 is accepted");
cfg.ns_strength_permille = 1000;
check(xombe_enc_init(&mem, &cfg) != NULL, "ns_strength_permille 1000 is accepted");
xombe_enc_cfg_default(&cfg);
cfg.voicing_scale_permille = 0;
check(xombe_enc_init(&mem, &cfg) == NULL, "voicing_scale_permille 0 is refused");
cfg.voicing_scale_permille = -350;
check(xombe_enc_init(&mem, &cfg) == NULL, "voicing_scale_permille below 0 is refused");
xombe_enc_cfg_default(&cfg);
cfg.dmr_dtx = 5;
cfg.dstar_dtx = 5;
check(xombe_enc_init(&mem, &cfg) != NULL, "nonzero dtx means on");
memset(pcm, 0, sizeof(pcm));
xombe_enc_init(&mem, NULL);
for (i = 0; i < XOMBE_ENC_DELAY + 2; i++)
got += xombe_enc_frame((xombe_enc *)&mem, pcm, NULL, f, NULL);
check(got == 2, "encoder output starts after XOMBE_ENC_DELAY frames");
xombe_enc_cfg_default(&cfg);
cfg.outputs = 0x80u;
check(xombe_enc_init(&mem, &cfg) == NULL, "an unknown output is refused");
cfg.outputs = 0;
check(xombe_enc_init(&mem, &cfg) != NULL, "outputs 0 means DMR");
check(xombe_enc_delay((xombe_enc *)&mem) == XOMBE_ENC_DELAY, "DMR-only delay");
cfg.outputs = XOMBE_ENC_DSTAR;
check((xombe_enc_init(&mem, &cfg) != NULL) == XOMBE_HAVE_DSTAR, "D-STAR output only in a D-STAR build");
xombe_enc_cfg_default(&cfg);
check(cfg.outputs == XOMBE_ENC_DMR && cfg.dmr_dtx && !cfg.dstar_dtx && cfg.dmr_quant == XOMBE_ENC_QUANT_CLOSED,
"defaults: DMR output, DMR DTX on, D-STAR DTX off, closed loop");
{
/* pcm NULL is a frame of zeros, for both outputs and both forms */
static xombe_enc_mem m2, m3, m4;
xombe_enc *a, *b, *c2, *d2;
uint8_t fa[2][XOMBE_FRAME_BYTES], fb[2][XOMBE_FRAME_BYTES], ba[2][XOMBE_BITS_BYTES];
uint8_t bb[2][XOMBE_BITS_BYTES];
int same = 1;
xombe_enc_cfg_default(&cfg);
cfg.outputs = ALL_OUTPUTS;
a = xombe_enc_init(&mem, &cfg);
b = xombe_enc_init(&m2, &cfg);
c2 = xombe_enc_init(&m3, &cfg);
d2 = xombe_enc_init(&m4, &cfg);
for (i = 0; i < 8; i++) {
int ra = xombe_enc_frame(a, NULL, NULL, fa[0], fa[1]), rb = xombe_enc_frame(b, pcm, NULL, fb[0], fb[1]);
int rc = xombe_enc_frame_bits(c2, NULL, NULL, ba[0], ba[1]);
int rd = xombe_enc_frame_bits(d2, pcm, NULL, bb[0], bb[1]);
same &= ra == rb && rc == rd && !memcmp(fa, fb, sizeof(fa)) && !memcmp(ba, bb, sizeof(ba));
}
check(same, "pcm NULL encodes zeros");
}
}
/* an output the encoder does not produce gets its codec's silence frame, in either form */
static void test_encoder_absent(void)
{
static xombe_enc_mem mem;
int16_t pcm[160];
uint8_t f[XOMBE_FRAME_BYTES], b[XOMBE_BITS_BYTES];
int n, ok = 1;
xombe_enc_init(&mem, NULL);
for (n = 0; n < 10; n++) {
test_signal(n, pcm);
xombe_enc_frame((xombe_enc *)&mem, pcm, NULL, NULL, f);
xombe_enc_frame_bits((xombe_enc *)&mem, pcm, NULL, NULL, b);
ok &= !memcmp(f, dstar_null_frame, sizeof(f)) && !memcmp(b, dstar_null_bits, sizeof(b));
}
check(ok, "a DMR-only encoder writes D-STAR null frames and their bits");
#if XOMBE_HAVE_DSTAR
{
xombe_enc_cfg cfg;
xombe_enc_cfg_default(&cfg);
cfg.outputs = XOMBE_ENC_DSTAR;
xombe_enc_init(&mem, &cfg);
for (n = 0, ok = 1; n < 10; n++) {
test_signal(n, pcm);
xombe_enc_frame((xombe_enc *)&mem, pcm, NULL, f, NULL);
xombe_enc_frame_bits((xombe_enc *)&mem, pcm, NULL, b, NULL);
ok &= !memcmp(f, silence_frame[XOMBE_DMR], sizeof(f)) && !memcmp(b, dmr_silence_bits, sizeof(b));
}
check(ok, "a D-STAR-only encoder writes DMR silence frames and their bits");
}
#endif
}
/* frames are the voice bits through the FEC, for both codecs, through the delay fill, tones, and voice */
static void test_encoder_bits(void)
{
static const xombe_enc_tone tones[] = {{128, 64}, {150, 90}, {40, 100}};
static xombe_enc_mem ma, mb;
xombe_enc_cfg cfg;
xombe_enc *a, *b;
int16_t pcm[160];
int n, k, same = 1;
xombe_enc_cfg_default(&cfg);
cfg.outputs = ALL_OUTPUTS;
a = xombe_enc_init(&ma, &cfg);
b = xombe_enc_init(&mb, &cfg);
for (n = 0; n < 100; n++) {
uint8_t f[2][XOMBE_FRAME_BYTES], bits[2][XOMBE_BITS_BYTES], g[XOMBE_FRAME_BYTES];
const xombe_enc_tone *t = n % 17 == 5 ? &tones[(n / 17) % 3] : NULL;
test_signal(n, pcm);
same &= xombe_enc_frame(a, pcm, t, f[0], f[1]) == xombe_enc_frame_bits(b, pcm, t, bits[0], bits[1]);
for (k = 0; k < NCODECS; k++) {
xombe_fec_encode(codecs[k], bits[codecs[k]], g);
same &= !memcmp(g, f[codecs[k]], sizeof(g));
}
}
check(same, "xombe_enc_frame equals xombe_fec_encode of xombe_enc_frame_bits, both codecs");
}
/* forced tone requests: ID and level ranges, refused calls write and consume nothing */
static void test_encoder_tone(void)
{
static const xombe_enc_tone bad[] = {{0, 90}, {4, 90}, {123, 90}, {127, 90}, {164, 90}, {-1, 90},
{255, 90}, {5, -1}, {5, 128}, {129, 1000}};
static const xombe_enc_tone good[] = {{5, 0}, {122, 127}, {128, 64}, {163, 1}, {144, 90}, {159, 90}};
static xombe_enc_mem ma, mb;
xombe_enc_cfg cfg;
xombe_enc *a, *b;
int16_t pcm[160];
uint8_t fa[2][XOMBE_FRAME_BYTES], fb[2][XOMBE_FRAME_BYTES], ba[2][XOMBE_BITS_BYTES];
unsigned i, n;
int refused = 1, untouched = 1, same = 1, accepted = 1;
xombe_enc_cfg_default(&cfg);
cfg.outputs = ALL_OUTPUTS;
a = xombe_enc_init(&ma, &cfg);
b = xombe_enc_init(&mb, &cfg);
for (n = 0; n < 40; n++) {
for (i = 0; i < 160; i++)
pcm[i] = (int16_t)(3000.0f * sinf(0.05f * (float)(n * 160 + i)) + (float)((n * 160 + i) * 7919 % 61));
if (n % 4 == 0) {
for (i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
memset(fa, 0xA5, sizeof(fa));
memset(ba, 0xA5, sizeof(ba));
refused &= xombe_enc_frame(a, pcm, &bad[i], fa[0], fa[1]) == -1 &&
xombe_enc_frame_bits(a, pcm, &bad[i], ba[0], ba[1]) == -1;
untouched &= !memcmp(fa[0], fill, 9) && !memcmp(fa[1], fill, 9) && !memcmp(ba[0], fill, 7) &&
!memcmp(ba[1], fill, 7);
}
}
same &= xombe_enc_frame(a, pcm, NULL, fa[0], fa[1]) == xombe_enc_frame(b, pcm, NULL, fb[0], fb[1]) &&
!memcmp(fa, fb, sizeof(fa));
}
check(refused, "xombe_enc_frame refuses IDs outside 5..122, 128..163 and levels outside 0..127");
check(untouched, "a refused request writes nothing");
check(same, "refused requests consume nothing");
for (i = 0; i < sizeof(good) / sizeof(good[0]); i++)
accepted &= xombe_enc_frame(a, pcm, &good[i], fa[0], fa[1]) == 1;
check(accepted, "range ends and Knox IDs are accepted");
check(xombe_enc_frame(a, pcm, &good[1], NULL, NULL) == 1 &&
xombe_enc_frame_bits(a, pcm, &good[1], NULL, NULL) == 1,
"NULL outputs are accepted");
}
/* FNV-1a 32 of the DMR voice bits of 100 test_signal frames, open loop, per kernel backend */
#if XOMBE_KERNELS_Q15
#define OPEN_LOOP_HASH 0xb7487b6du
#else
#define OPEN_LOOP_HASH 0x99dd5352u
#endif
static uint32_t fnv1a(uint32_t h, const uint8_t *p, size_t n)
{
while (n--)
h = (h ^ *p++) * 16777619u;
return h;
}
/* quantizer setting: range, open loop unchanged, D-STAR output independent of it */
static void test_encoder_quant(void)
{
static xombe_enc_mem m1, m2;
xombe_enc_cfg cfg;
xombe_enc *e1, *e2;
int16_t pcm[160];
uint8_t a1[7], a2[7];
uint32_t h = 2166136261u;
int n, differ = 0;
xombe_enc_cfg_default(&cfg);
cfg.dmr_quant = 2;
check(xombe_enc_init(&m1, &cfg) == NULL, "an unknown quantizer is refused");
cfg.dmr_quant = -1;
check(xombe_enc_init(&m1, &cfg) == NULL, "a negative quantizer is refused");
cfg.dmr_quant = XOMBE_ENC_QUANT_OPEN;
e1 = xombe_enc_init(&m1, &cfg);
e2 = xombe_enc_init(&m2, NULL);
check(e1 && e2, "encoder init with each quantizer");
if (!e1 || !e2)
return;
for (n = 0; n < 100; n++) {
test_signal(n, pcm);
if (xombe_enc_frame_bits(e1, pcm, NULL, a1, NULL) == 1)
h = fnv1a(h, a1, 7);
xombe_enc_frame_bits(e2, pcm, NULL, a2, NULL);
differ += memcmp(a1, a2, 7) != 0;
}
if (h != OPEN_LOOP_HASH)
fprintf(stderr, "open-loop hash 0x%08lx\n", (unsigned long)h);
check(h == OPEN_LOOP_HASH, "open-loop output unchanged");
check(differ > 0, "closed-loop output differs from open loop");
#if XOMBE_HAVE_DSTAR
{
uint8_t d1[XOMBE_FRAME_BYTES], d2[XOMBE_FRAME_BYTES], f1[XOMBE_FRAME_BYTES], f2[XOMBE_FRAME_BYTES];
int same = 1;
cfg.outputs = XOMBE_ENC_DMR | XOMBE_ENC_DSTAR;
e1 = xombe_enc_init(&m1, &cfg);
cfg.dmr_quant = XOMBE_ENC_QUANT_CLOSED;
e2 = xombe_enc_init(&m2, &cfg);
for (n = 0, differ = 0; n < 100; n++) {
test_signal(n, pcm);
xombe_enc_frame(e1, pcm, NULL, f1, d1);
xombe_enc_frame(e2, pcm, NULL, f2, d2);
same &= !memcmp(d1, d2, sizeof(d1));
differ += memcmp(f1, f2, sizeof(f1)) != 0;
}
check(same && differ > 0, "D-STAR output of a dual encoder independent of the quantizer");
}
#endif
}
#if XOMBE_HAVE_DSTAR
static void test_encoder_dstar(void)
{
const uint8_t *silence = silence_frame[XOMBE_DMR];
static xombe_enc_mem m1, m2, m3, m4;
static uint8_t a1[100][XOMBE_FRAME_BYTES];
xombe_enc_cfg cfg;
xombe_enc *e1, *e2, *e3, *e4;
int16_t pcm[160];
uint8_t a2[XOMBE_FRAME_BYTES], a3[XOMBE_FRAME_BYTES], d2[XOMBE_FRAME_BYTES], d3[XOMBE_FRAME_BYTES];
uint8_t d4[XOMBE_FRAME_BYTES];
int n, same = 1, nulls = 0, dtx_nulls = 0, silent = 1, r1 = 0, r2 = 0, r3 = 0;
int lag = XOMBE_ENC_DSTAR_DELAY - XOMBE_ENC_DELAY;
xombe_enc_cfg_default(&cfg);
e1 = xombe_enc_init(&m1, &cfg);
cfg.outputs = XOMBE_ENC_DMR | XOMBE_ENC_DSTAR;
e2 = xombe_enc_init(&m2, &cfg);
cfg.outputs = XOMBE_ENC_DSTAR;
e3 = xombe_enc_init(&m3, &cfg);
cfg.dstar_dtx = 1;
e4 = xombe_enc_init(&m4, &cfg);
check(e1 && e2 && e3 && e4, "encoder init with each output set");
if (!e1 || !e2 || !e3 || !e4)
return;
check(xombe_enc_delay(e1) == XOMBE_ENC_DELAY && xombe_enc_delay(e2) == XOMBE_ENC_DSTAR_DELAY &&
xombe_enc_delay(e3) == XOMBE_ENC_DSTAR_DELAY && lag > 0,
"the D-STAR output adds look-ahead to both outputs");
for (n = 0; n < 100; n++) {
test_signal(n, pcm);
r1 += xombe_enc_frame(e1, pcm, NULL, a1[n], NULL);
r2 += xombe_enc_frame(e2, pcm, NULL, a2, d2);
r3 += xombe_enc_frame(e3, pcm, NULL, a3, d3);
same &= !memcmp(n >= lag ? a1[n - lag] : silence, a2, XOMBE_FRAME_BYTES);
silent &= !memcmp(a3, silence, XOMBE_FRAME_BYTES);
if (n >= XOMBE_ENC_DSTAR_DELAY)
nulls += !memcmp(d2, dstar_null_frame, sizeof(d2)) + !memcmp(d3, dstar_null_frame, sizeof(d3));
if (xombe_enc_frame(e4, pcm, NULL, NULL, d4))
dtx_nulls += !memcmp(d4, dstar_null_frame, sizeof(d4));
}
check(r1 == 100 - XOMBE_ENC_DELAY && r2 == 100 - XOMBE_ENC_DSTAR_DELAY && r3 == r2,
"both outputs share XOMBE_ENC_DSTAR_DELAY");
check(same, "with D-STAR, the DMR output is the DMR-only one, delayed");
check(silent, "an encoder without DMR writes DMR silence frames");
check(nulls == 0, "with D-STAR DTX off, every D-STAR frame is a voice frame");
check(dtx_nulls > 0, "with D-STAR DTX on, inactive frames are null frames");
}
#endif
#endif
#if XOMBE_HAVE_DSTAR
/* transcoder from codec c: init, lost frames, clean output, two instances agree, and the decision of the input is
the source decoder's */
static void test_xc(enum xombe_codec c)
{
enum xombe_codec to = c == XOMBE_DMR ? XOMBE_DSTAR : XOMBE_DMR;
static xombe_xc_mem x1, x2;
static xombe_dec_mem dm;
xombe_xc *x, *y;
xombe_xc_decision d;
xombe_dec *dd;
xombe_fec fs;
uint8_t fr[XOMBE_FRAME_BYTES], o1[XOMBE_FRAME_BYTES], o2[XOMBE_FRAME_BYTES], bits[XOMBE_BITS_BYTES];
int16_t pcm[160];
int n, agree = 1, clean = 1, decided = 1, lost_ok = 1, outs = 1;
x = xombe_xc_init(&x1, c);
if (c == XOMBE_DSTAR && !XOMBE_HAVE_ENCODER) {
checkc(x == NULL, c, "transcoder from D-STAR needs the encoder");
return;
}
y = xombe_xc_init(&x2, c);
dd = xombe_dec_init(&dm, c);
checkc(x == (xombe_xc *)&x1 && y != NULL, c, "transcoder handle is the caller's memory");
checkc(xombe_xc_size() <= XOMBE_XC_SIZE, c, "transcoder size within XOMBE_XC_SIZE");
checkc(xombe_xc_init(NULL, c) == NULL, c, "transcoder init rejects NULL");
xombe_xc_decision_get(x, &d);
checkc(d.in.e0 == -1 && d.in.e1 == -1 && d.in.mute_src == -1, c, "transcoder decision before the first frame");
checkc(xombe_xc_frame(x, silence_frame[c], 0, o1) == 1 && xombe_xc_frame(y, silence_frame[c], 0, o2) == 1, c,
"transcoder takes a silence frame");
xombe_dec_frame(dd, silence_frame[c], 0, pcm);
xombe_xc_decision_get(x, &d);
checkc(d.in.cls == XOMBE_CLASS_SILENCE && d.out == (c == XOMBE_DMR ? XOMBE_XC_OUT_VOICE : XOMBE_XC_OUT_SILENCE),
c, "a silence frame transcodes as a D-STAR all-unvoiced voice frame or a DMR silence frame");
xombe_fec_init(&fs, to);
for (n = 0; n < 300; n++) {
unsigned flags = n % 37 == 5 ? XOMBE_FLAG_LOST : 0;
xombe_fec_stats st;
xombe_decision r;
stream_frame(c, n, fr);
agree &= xombe_xc_frame(x, flags ? NULL : fr, flags, o1) == 1;
agree &= xombe_xc_frame(y, fr, flags, o2) == 1 && !memcmp(o1, o2, sizeof(o1));
xombe_fec_decode(&fs, o1, bits, &st);
clean &= st.eps0 == 0 && st.eps1 == 0;
xombe_xc_decision_get(x, &d);
if (flags)
lost_ok &= d.in.cls == XOMBE_CLASS_ERASURE && d.in.conceal != XOMBE_CONCEAL_NONE && d.in.e0 == -1 &&
!d.in.bf && !d.in.hb;
xombe_dec_frame(dd, fr, flags, pcm);
xombe_dec_decision_get(dd, &r);
decided &= d.in.cls == r.cls && d.in.conceal == r.conceal && d.in.run == r.run &&
d.in.mute_src == r.mute_src && d.in.e0 == r.e0 && d.in.e1 == r.e1 && d.in.bf == r.bf &&
d.in.hb == r.hb;
if (c == XOMBE_DMR)
outs &= d.out == XOMBE_XC_OUT_VOICE || d.out == XOMBE_XC_OUT_TONE || d.out == XOMBE_XC_OUT_KNOX ||
d.out == XOMBE_XC_OUT_RESEND;
else
outs &= d.out == XOMBE_XC_OUT_VOICE || d.out == XOMBE_XC_OUT_PULSE || d.out == XOMBE_XC_OUT_TONE ||
d.out == XOMBE_XC_OUT_SILENCE;
}
checkc(agree, c, "two transcoders agree, a lost frame's input is not read");
checkc(clean, c, "transcoder output frames are clean codewords of the other codec");
checkc(lost_ok, c, "decision of a lost frame: erasure, concealed, no error counts");
checkc(decided, c, "the transcoder's input decision is the source decoder's");
checkc(outs, c, "output classes are those of its direction");
checkc(xombe_xc_init_shared(NULL, c, &x2) == NULL && xombe_xc_init_shared(&x2, c, NULL) == NULL, c,
"shared init rejects NULL memory or workspace");
}
static void test_xc_codecs(void)
{
static xombe_xc_mem m;
check(xombe_xc_init(&m, (enum xombe_codec)7) == NULL, "transcoder init refuses an unknown codec");
#if XOMBE_HAVE_ENCODER
{
/* two transcoders on one workspace, interleaved, equal two with their own */
static xombe_xc_mem c1, r1;
static xombe_qws_mem ws;
static xombe_xc_shared_mem c2, r2;
xombe_xc *ca = xombe_xc_init(&c1, XOMBE_DMR), *ra = xombe_xc_init(&r1, XOMBE_DSTAR), *cb, *rb;
uint8_t fr[XOMBE_FRAME_BYTES], o1[XOMBE_FRAME_BYTES], o2[XOMBE_FRAME_BYTES], q1[XOMBE_FRAME_BYTES];
uint8_t q2[XOMBE_FRAME_BYTES];
int n, same = 1;
cb = xombe_xc_init_shared(&c2, XOMBE_DMR, &ws);
rb = xombe_xc_init_shared(&r2, XOMBE_DSTAR, &ws);
check(cb != NULL && rb != NULL, "shared init in XOMBE_XC_SHARED_SIZE");
for (n = 0; cb && rb && n < 200; n++) {
stream_frame(XOMBE_DMR, n, fr);
xombe_xc_frame(ca, fr, 0, o1);
xombe_xc_frame(cb, fr, 0, o2);
xombe_xc_frame(ra, o1, 0, q1);
xombe_xc_frame(rb, o2, 0, q2);
same &= !memcmp(o1, o2, sizeof(o1)) && !memcmp(q1, q2, sizeof(q1));
}
check(same, "transcoders sharing a workspace equal transcoders with their own");
}
#endif
}
#endif
int main(void)
{
int k;
check(xombe_version() == XOMBE_VERSION, "library version matches the header");
setup_frames();
test_codecs();
for (k = 0; k < NCODECS; k++) {
test_fec(codecs[k]);
test_decoder(codecs[k]);
test_decoder_bits(codecs[k]);
test_tone_frames(codecs[k]);
#if XOMBE_HAVE_DSTAR
test_xc(codecs[k]);
#endif
}
#if XOMBE_HAVE_DSTAR
test_xc_codecs();
#endif
#if XOMBE_HAVE_ENCODER
test_encoder();
test_encoder_absent();
test_encoder_bits();
test_encoder_tone();
test_encoder_quant();
#if XOMBE_HAVE_DSTAR
test_encoder_dstar();
#endif
#endif
printf("API: %d/%d checks passed\n", checks - failures, checks);
return failures ? 1 : 0;
}
+223
View File
@@ -0,0 +1,223 @@
/* checks a D-STAR reference set is complete and well formed: every file in MANIFEST
exists with its size, every record file parses, and the per-clip files agree on the frame counts
tests the harness and the references, not the codec
test_dstar_refs DIR */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dstar_ref.h"
#define MAX_FILES 512
static char names[MAX_FILES][128];
static int nfiles;
static int failures;
static void bad(const char *what, const char *name)
{
fprintf(stderr, "FAIL %s: %s\n", name, what);
failures++;
}
static int has(const char *name)
{
int k;
for (k = 0; k < nfiles; k++)
if (!strcmp(names[k], name))
return 1;
return 0;
}
static int ends(const char *s, const char *suffix)
{
size_t n = strlen(s), m = strlen(suffix);
return n >= m && !strcmp(s + n - m, suffix);
}
static long file_size(const char *dir, const char *name)
{
char path[1024];
FILE *f;
long n;
if (snprintf(path, sizeof(path), "%s/%s", dir, name) >= (int)sizeof(path))
return -1;
f = fopen(path, "rb");
if (!f)
return -1;
fseek(f, 0, SEEK_END);
n = ftell(f);
fclose(f);
return n;
}
/* parses every record, returns the record count, or -1 */
static long records(const char *dir, const char *name)
{
char path[1024];
dsref r;
long n = 0;
int st;
if (snprintf(path, sizeof(path), "%s/%s", dir, name) >= (int)sizeof(path) || !dsref_open(&r, path))
return -1;
if (!dsref_meta(&r, "stage"))
fprintf(stderr, "%s: no stage meta line\n", path), r.failed = 1;
while ((st = dsref_next(&r)) > 0)
n++;
if (!dsref_close(&r) || st < 0)
return -1;
return n;
}
static long count_of(const char *dir, const char *clip, const char *suffix, long unit)
{
char name[160];
long n;
if (snprintf(name, sizeof(name), "%s%s", clip, suffix) >= (int)sizeof(name) || !has(name))
return -2;
if (ends(name, ".txt.gz"))
return records(dir, name);
n = file_size(dir, name);
if (n < 0 || n % unit) {
bad("size is not a multiple of the unit", name);
return -1;
}
return n / unit;
}
static void expect(const char *dir, const char *clip, const char *suffix, long unit, long want)
{
long n = count_of(dir, clip, suffix, unit);
if (n == -2)
return;
if (n != want) {
char msg[96], name[160];
if (snprintf(name, sizeof(name), "%s%s", clip, suffix) >= (int)sizeof(name))
name[0] = 0;
snprintf(msg, sizeof(msg), "%ld units, expected %ld", n, want);
bad(msg, name);
}
}
/* writes a record of every type with the C writer and reads it back */
static void selftest(void)
{
const char *path = "dstar_ref_selftest.txt";
static const uint8_t bytes[3] = {0x9e, 0x8d, 0xff}, bits[5] = {1, 0, 1, 1, 0};
static const double fv[3] = {-15.0, 0.125, 1e-7};
static const long iv[2] = {-3, 123456};
dsref_writer w;
dsref r;
int ok = dsref_wopen(&w, path, "selftest", "n:i x:f s:s h:x b:b iv:i* fv:f* e:f*", 0);
dsref_wi(&w, 7);
dsref_wf(&w, 0.1);
dsref_ws(&w, "voice");
dsref_wx(&w, bytes, 3);
dsref_wb(&w, bits, 5);
dsref_wiv(&w, iv, 2);
dsref_wfv(&w, fv, 3);
dsref_wfv(&w, fv, 0);
dsref_wend(&w);
ok = dsref_wclose(&w) && ok;
if (ok && dsref_open(&r, path)) {
int cn = dsref_need(&r, "n", DSREF_INT), cx = dsref_need(&r, "x", DSREF_FLOAT);
int cs = dsref_need(&r, "s", DSREF_STR), ch = dsref_need(&r, "h", DSREF_HEX);
int cb = dsref_need(&r, "b", DSREF_BITS), ci = dsref_need(&r, "iv", DSREF_IVEC);
int cf = dsref_need(&r, "fv", DSREF_FVEC), ce = dsref_need(&r, "e", DSREF_FVEC);
ok = cn >= 0 && cx >= 0 && cs >= 0 && ch >= 0 && cb >= 0 && ci >= 0 && cf >= 0 && ce >= 0 &&
dsref_next(&r) == 1 && dsref_i(&r, cn) == 7 && dsref_f(&r, cx) == 0.1 &&
!strcmp(dsref_s(&r, cs), "voice") && dsref_len(&r, ch) == 3 && !memcmp(dsref_bytes(&r, ch), bytes, 3) &&
dsref_len(&r, cb) == 5 && !memcmp(dsref_bytes(&r, cb), bits, 5) && dsref_len(&r, ci) == 2 &&
dsref_iv(&r, ci)[1] == 123456 && dsref_len(&r, cf) == 3 && dsref_fv(&r, cf)[0] == -15.0 &&
dsref_fv(&r, cf)[2] == 1e-7 && dsref_len(&r, ce) == 0 && dsref_next(&r) == 0 &&
!strcmp(dsref_meta(&r, "stage"), "selftest");
ok = dsref_close(&r) && ok;
} else {
ok = 0;
}
if (!ok)
bad("writer/reader round trip", path);
remove(path);
}
int main(int argc, char **argv)
{
const char *dir;
char path[1024], line[512];
FILE *mf;
int k, nrecfiles = 0, nclips = 0;
if (argc != 2) {
fprintf(stderr, "usage: test_dstar_refs DIR\n");
return 2;
}
dir = argv[1];
selftest();
if (snprintf(path, sizeof(path), "%s/MANIFEST", dir) >= (int)sizeof(path))
return 2;
mf = fopen(path, "r");
if (!mf) {
fprintf(stderr, "%s: cannot open\n", path);
return 1;
}
while (fgets(line, sizeof(line), mf)) {
char sha[80], name[128];
long size;
if (line[0] == '#')
continue;
if (sscanf(line, "%79s %ld %127s", sha, &size, name) != 3 || nfiles == MAX_FILES) {
bad("malformed MANIFEST line", line);
continue;
}
snprintf(names[nfiles++], sizeof(names[0]), "%s", name);
if (file_size(dir, name) != size)
bad("missing or size differs from MANIFEST", name);
if (ends(name, ".txt.gz")) {
nrecfiles++;
if (records(dir, name) <= 0)
bad("unreadable or empty record file", name);
}
}
fclose(mf);
/* per-clip consistency, keyed by the stream files */
for (k = 0; k < nfiles; k++) {
char clip[128];
size_t n = strlen(names[k]);
if (ends(names[k], ".dstar") && !ends(names[k], ".xc.dstar")) {
long nf;
memcpy(clip, names[k], n - 6);
clip[n - 6] = 0;
nf = count_of(dir, clip, ".dstar", 9);
if (nf <= 0) {
bad("empty D-Star stream", names[k]);
continue;
}
nclips++;
expect(dir, clip, ".fec.txt.gz", 1, nf);
expect(dir, clip, ".deq.txt.gz", 1, nf);
expect(dir, clip, ".dec.txt.gz", 1, nf);
expect(dir, clip, ".half.txt.gz", 1, 2 * nf);
expect(dir, clip, ".dec.raw", 2 * 160, nf);
expect(dir, clip, ".xrev.txt.gz", 1, nf);
expect(dir, clip, ".xrev.r33", 9, nf);
expect(dir, clip, ".enc.txt.gz", 1, nf);
if (has(strcat(strcpy(path, clip), ".in.raw"))) {
long ns = file_size(dir, path) / 2;
if ((ns + 159) / 160 != nf)
bad("encoder frame count is not ceil(samples / 160)", path);
}
} else if (ends(names[k], ".r33") && !ends(names[k], ".xrev.r33")) {
long nf;
memcpy(clip, names[k], n - 4);
clip[n - 4] = 0;
nf = count_of(dir, clip, ".r33", 9);
nclips++;
expect(dir, clip, ".xc.txt.gz", 1, nf);
expect(dir, clip, ".xc.dstar", 9, nf);
}
}
printf("%d files, %d record files, %d streams checked, %d failures\n", nfiles, nrecfiles, nclips, failures);
if (!nrecfiles || !nclips)
return 1;
return failures ? 1 : 0;
}
+144
View File
@@ -0,0 +1,144 @@
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "../src/dstar/dstar_internal.h"
#include "dstar_ref.h"
/* generated D-STAR tables (scripts/gen_dstar_tables.py) against the model's tables_dstar record (vectors/dstar):
every float within a float rounding of the double, the masks, VUV0, and LMPRBL exact, the pitch grid against
its closed form, and the table sets' shapes */
static int failures, checks;
static void check(int ok, const char *what, long i)
{
checks++;
if (!ok) {
failures++;
fprintf(stderr, "FAIL %s (item %ld)\n", what, i);
}
}
static int close_to(float t, double v)
{
return fabs((double)t - v) <= 6e-8 * (fabs(v) > 1.0 ? fabs(v) : 1.0);
}
static void floats(const char *what, long row, const float *t, int n, const double *v, int nv)
{
int i;
check(n == nv, what, row);
for (i = 0; i < n && i < nv; i++)
check(close_to(t[i], v[i]), what, row * 100 + i);
}
static void bytes(const char *what, long row, const unsigned char *t, int n, const double *v, int nv)
{
int i;
check(n == nv, what, row);
for (i = 0; i < n && i < nv; i++)
check((double)t[i] == v[i], what, row * 1000 + i);
}
int main(int argc, char **argv)
{
static const char *const hoc_name[4] = {"HOC1", "HOC2", "HOC3", "HOC4"};
static const char *const ok_hoc_name[4] = {"ok_HOC1", "ok_HOC2", "ok_HOC3", "ok_HOC4"};
const xombe_amp_tables *ts = &xombe__amp_dstar;
double p0 = 0, p1 = 0;
int seen[32], st, k, c_tab, c_row, c_v;
char path[1024];
dsref r;
if (argc != 2) {
fprintf(stderr, "usage: test_dstar_tables VECTORS/dstar\n");
return 2;
}
snprintf(path, sizeof(path), "%s/tables_dstar.txt.gz", argv[1]);
if (!dsref_open(&r, path))
return 1;
c_tab = dsref_need(&r, "tab", DSREF_STR);
c_row = dsref_need(&r, "row", DSREF_INT);
c_v = dsref_need(&r, "v", DSREF_FVEC);
memset(seen, 0, sizeof(seen));
while (c_v >= 0 && (st = dsref_next(&r)) > 0) {
const char *t = dsref_s(&r, c_tab);
long row = dsref_i(&r, c_row);
const double *v = dsref_fv(&r, c_v);
int n = dsref_len(&r, c_v);
if (!strcmp(t, "p0"))
p0 = v[0], seen[0]++;
else if (!strcmp(t, "p1"))
p1 = v[0], seen[1]++;
else if (!strcmp(t, "rho"))
check(close_to(XOMBE_DS_RHO, v[0]) && ts->rho == XOMBE_DS_RHO, "rho", 0), seen[2]++;
else if (!strcmp(t, "grho"))
check(close_to(XOMBE_DS_GRHO, v[0]) && ts->grho == XOMBE_DS_GRHO, "grho", 0), seen[3]++;
else if (!strcmp(t, "DG") && row < 64)
floats("DG", row, &xombe__ds_dg[row], 1, v, n), seen[4]++;
else if (!strcmp(t, "PRBA24") && row < 512)
floats("PRBA24", row, xombe__ds_prba24[row], 3, v, n), seen[5]++;
else if (!strcmp(t, "PRBA58") && row < 128)
floats("PRBA58", row, xombe__ds_prba58[row], 4, v, n), seen[6]++;
else if (!strcmp(t, "VUV0") && row < 16)
bytes("VUV0", row, xombe__ds_vuv[row], 8, v, n), seen[7]++;
else if (!strcmp(t, "LMPRBL") && row < 57)
bytes("LMPRBL", row, ts->blk[row], 4, v, n), seen[8]++;
else if (!strcmp(t, "ok_DG"))
bytes("ok_DG", row, ts->ok_dg, ts->n_dg, v, n), seen[9]++;
else if (!strcmp(t, "ok_PRBA24"))
bytes("ok_PRBA24", row, ts->ok_prba24, ts->n_prba24, v, n), seen[10]++;
else if (!strcmp(t, "ok_PRBA58"))
bytes("ok_PRBA58", row, ts->ok_prba58, ts->n_prba58, v, n), seen[11]++;
else {
for (k = 0; k < 4; k++) {
if (!strcmp(t, hoc_name[k]) && row < ts->n_hoc[k]) {
floats(hoc_name[k], row, ts->hoc[k] + 4 * row, 4, v, n), seen[12 + k]++;
break;
}
if (!strcmp(t, ok_hoc_name[k])) {
bytes(ok_hoc_name[k], row, ts->ok_hoc[k], ts->n_hoc[k], v, n), seen[16 + k]++;
break;
}
}
check(k < 4, t, row);
}
}
if (!dsref_close(&r))
failures++;
{
static const int want[20] = {1, 1, 1, 1, 64, 512, 128, 16, 57, 1, 1, 1, 16, 16, 16, 8, 1, 1, 1, 1};
for (k = 0; k < 20; k++)
check(seen[k] == want[k], "row count", k);
}
check(close_to(XOMBE_DS_P0, p0) && close_to(XOMBE_DS_P1, p1), "p0 p1", 0);
for (k = 0; k < XOMBE_DS_B0_COUNT; k++) {
double f0 = pow(2.0, p0 + p1 * (k + 0.5));
int L = (int)floor(0.4627 / f0);
L = L < 9 ? 9 : L > XOMBE_LMAX ? XOMBE_LMAX : L;
check(close_to(xombe__ds_w0[k], f0), "W0", k);
check(xombe__ds_lt[k] == L, "LTAB", k);
}
check(ts->n_dg == 64 && ts->n_prba24 == 512 && ts->n_prba58 == 128, "table set sizes", 0);
check(xombe__ds_tone_id[0] == 129 && xombe__ds_tone_id[16] == 160 && xombe__ds_tone_id[37] == 5 &&
xombe__ds_tone_id[154] == 122 && xombe__ds_tone_id[20] == XOMBE_DS_TONE_NONE &&
xombe__ds_tone_id[155] == XOMBE_DS_TONE_NONE, "tone map", 0);
{ /* the silence frame decodes cleanly to b0 124 and re-encodes to itself */
static const uint8_t nf[9] = XOMBE_DS_NULL_FRAME;
xombe_ds_frame f;
uint8_t o[9];
xombe__ds_fec_decode(nf, &f);
check(f.ea == 0 && f.eb == 0 && f.b[0] == XOMBE_DS_B0_SILENCE && f.cls == XOMBE_DS_NULL, "null frame", 0);
check(xombe__ds_encode_fields(f.b, o) == 0 && !memcmp(o, nf, 9), "null frame encode", 0);
}
{ /* out-of-range fields are clamped to their widths and still written */
int lo[9] = {-1, -1, -1, -1, -1, -1, -1, -1, -1}, hi[9] = {999, 99, 99, 999, 999, 99, 99, 99, 99};
int zero[9] = {0}, top[9] = {127, 15, 63, 511, 127, 15, 15, 15, 7};
uint8_t o[9], want[9];
xombe__ds_encode_fields(zero, want);
check(xombe__ds_encode_fields(lo, o) == -1 && !memcmp(o, want, 9), "fields clamped up to 0", 0);
xombe__ds_encode_fields(top, want);
check(xombe__ds_encode_fields(hi, o) == -1 && !memcmp(o, want, 9), "fields clamped down to their widths", 0);
}
printf("%d checks, %d failures\n", checks, failures);
return failures ? 1 : 0;
}
+570
View File
@@ -0,0 +1,570 @@
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tone_fit.h"
#if XOMBE_HAVE_DSTAR
#include "../src/dstar/dstar_enc.h"
#endif
/* forced tones (xombe_enc_frame): position, decoded tone, unchanged analysis
state, no leak into later frames, and the D-STAR mirror */
#define MAXF 4000
#define RUN 30 /* forced frames in a row for the decode measurements */
#define FIT_AT 12
static int failures, checks;
static void check(int ok, const char *what)
{
checks++;
if (!ok) {
failures++;
printf("FAIL: %s\n", what);
}
}
static int16_t *load_raw(const char *dir, const char *name, int *frames)
{
char path[4096];
FILE *f;
long size;
int16_t *x;
snprintf(path, sizeof(path), "%s/%s", dir, name);
f = fopen(path, "rb");
if (!f) {
perror(path);
exit(2);
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
x = malloc((size_t)size + 2);
*frames = (int)(fread(x, sizeof(int16_t), (size_t)size / 2, f) / 160);
fclose(f);
if (*frames > MAXF)
*frames = MAXF;
return x;
}
/* per input frame: requested tone (id 0: none) and the outputs that belong to it */
typedef struct {
int frames;
xombe_enc_tone req[MAXF];
uint8_t a2[MAXF][7];
uint8_t ds[MAXF][9];
} run;
static xombe_enc_mem mem_a, mem_b;
/* xombe_enc_frame with DMR voice bits and a D-STAR frame (ds NULL: none) */
static int enc_frame(xombe_enc *e, const int16_t *pcm, const xombe_enc_tone *t, uint8_t a2[7], uint8_t *ds)
{
uint8_t dsb[7];
int got = xombe_enc_frame_bits(e, pcm, t, a2, ds ? dsb : NULL);
if (ds)
xombe_fec_encode(XOMBE_DSTAR, dsb, ds);
return got;
}
/* encodes r->frames of x with r->req, flushing so every input frame has its output */
static void encode(const xombe_enc_cfg *cfg, const int16_t *x, run *r)
{
static const int16_t zeros[160];
xombe_enc *e = xombe_enc_init(&mem_a, cfg);
int dual = (cfg->outputs & ~XOMBE_ENC_DMR) != 0, delay = xombe_enc_delay(e), c;
memset(r->a2, 0, sizeof(r->a2));
memset(r->ds, 0, sizeof(r->ds));
for (c = 0; c < r->frames + delay; c++) {
const int16_t *pcm = c < r->frames ? x + 160 * c : zeros;
const xombe_enc_tone *t = c < r->frames && r->req[c].id ? &r->req[c] : NULL;
uint8_t a[7], d[9] = {0};
int got;
got = enc_frame(e, pcm, t, a, dual ? d : NULL);
if (got == 1) {
memcpy(r->a2[c - delay], a, 7);
memcpy(r->ds[c - delay], d, 9);
}
}
}
static void tone_bytes(int id, int ad, uint8_t bytes[7])
{
uint8_t d[49];
xombe__tone_frame_bits(id, ad, d);
xombe__pack49(d, bytes);
}
static int is_tone(const uint8_t bytes[7])
{
uint8_t d[49];
xombe__unpack49(bytes, d);
return xombe__frame_class(d) == XOMBE_CLASS_TONE;
}
#if XOMBE_HAVE_DSTAR
static int ds_code(int id)
{
int T;
for (T = 0; T < 256; T++)
if (xombe__ds_tone_id[T] == id)
return T;
return -1;
}
static int ds_is_tone(const uint8_t f[9])
{
xombe_ds_frame fr;
xombe__ds_fec_decode(f, &fr);
return fr.cls == XOMBE_DS_TONE;
}
#endif
static xombe_enc_cfg cfg_of(unsigned outputs, int tones)
{
xombe_enc_cfg c;
xombe_enc_cfg_default(&c);
c.outputs = outputs;
c.tones = tones;
return c;
}
static void label(char what[160], unsigned outputs, int tones, const char *s)
{
const char *o = outputs == XOMBE_ENC_DMR ? "AMBE+2" : outputs == XOMBE_ENC_DSTAR ? "D-STAR" : "dual";
snprintf(what, 160, "%s, tones %s: %s", o, tones ? "on" : "off", s);
}
/* forced frames land at their own input's output, in both outputs, and nothing else turns into a tone */
static void test_position(const int16_t *x, int frames, unsigned outputs, int tones)
{
static run plain, forced;
static const int at[][3] = {{40, 20, 90}, {41, 129, 70}, {77, 150, 100}, {120, 5, 0},
{121, 122, 127}, {122, 163, 3}, {200, 144, 60}, {201, 160, 110}};
xombe_enc_cfg cfg = cfg_of(outputs, tones);
int i, n = (int)(sizeof(at) / sizeof(at[0])), first = at[0][0], pos_ok = 1, before_ok = 1, leak = 0;
int plain_tones = 0;
char what[160];
memset(&plain, 0, sizeof(plain));
plain.frames = frames;
encode(&cfg, x, &plain);
forced = plain;
for (i = 0; i < n; i++) {
forced.req[at[i][0]].id = at[i][1];
forced.req[at[i][0]].ad = at[i][2];
}
encode(&cfg, x, &forced);
for (i = 0; i < frames; i++) {
plain_tones += is_tone(plain.a2[i]);
if (forced.req[i].id) {
uint8_t want[7];
tone_bytes(forced.req[i].id, forced.req[i].ad, want);
if (outputs & XOMBE_ENC_DMR)
pos_ok &= !memcmp(forced.a2[i], want, 7);
#if XOMBE_HAVE_DSTAR
if (outputs & XOMBE_ENC_DSTAR) {
int T = ds_code(forced.req[i].id);
int ad = forced.req[i].ad;
xombe_ds_frame fr;
xombe__ds_fec_decode(forced.ds[i], &fr);
if (T >= 0)
pos_ok &= fr.cls == XOMBE_DS_TONE && fr.tid == forced.req[i].id && fr.AD == (ad < 8 ? 8 : ad);
else
pos_ok &= fr.cls == XOMBE_DS_VOICE;
}
#endif
} else {
leak += is_tone(forced.a2[i]);
#if XOMBE_HAVE_DSTAR
if (outputs & XOMBE_ENC_DSTAR)
leak += ds_is_tone(forced.ds[i]);
#endif
}
if (i < first)
before_ok &= !memcmp(plain.a2[i], forced.a2[i], 7) && !memcmp(plain.ds[i], forced.ds[i], 9);
}
label(what, outputs, tones, "speech input without detected tones");
check(plain_tones == 0, what);
label(what, outputs, tones, "each forced tone is its input frame's output");
check(pos_ok, what);
label(what, outputs, tones, "frames before the first request are unchanged");
check(before_ok, what);
label(what, outputs, tones, "no tone frame without a request");
check(leak == 0, what);
}
/* a forced tone inside a detected tone run changes nothing but its own frame: tone frames leave the AMBE+2
predictor at class tone and the D-STAR mirror alone, so the rest of the stream is bit-identical unless the
request leaked into the detector's confirmation and hold */
static void test_in_tone_run(const int16_t *x, int frames, unsigned outputs)
{
static run plain, forced;
xombe_enc_cfg cfg = cfg_of(outputs, 1);
int i, len = 0, placed = 0, same = 1, j;
memset(&plain, 0, sizeof(plain));
plain.frames = frames;
encode(&cfg, x, &plain);
forced = plain;
for (i = 0; i < frames && placed < 6; i++) {
int both = is_tone(plain.a2[i]);
#if XOMBE_HAVE_DSTAR
if (outputs & XOMBE_ENC_DSTAR)
both &= ds_is_tone(plain.ds[i]);
#endif
len = both ? len + 1 : 0;
if (len == 5) {
/* last frame of a natural run's first five, also the frame after its end when the run is short */
forced.req[i - 2].id = 130 + placed;
forced.req[i - 2].ad = 80;
placed++;
}
}
check(placed >= 3, "tone input has detected tone runs");
encode(&cfg, x, &forced);
for (i = 0; i < frames; i++) {
if (forced.req[i].id)
continue;
same &= !memcmp(plain.a2[i], forced.a2[i], 7);
for (j = 0; j < 9; j++)
same &= plain.ds[i][j] == forced.ds[i][j];
}
check(same, outputs & XOMBE_ENC_DSTAR ? "dual: a forced tone in a tone run leaves every other frame unchanged"
: "AMBE+2: a forced tone in a tone run leaves every other frame unchanged");
}
#define SAME_FIELD(a, b, f) (!memcmp(&(a)->f, &(b)->f, sizeof((a)->f)))
/* VAD, hangover, noise and comfort-noise tracking, and the tone detector's state */
static int same_analysis(const struct xombe_enc *a, const struct xombe_enc *b)
{
size_t lo = offsetof(struct xombe_enc, vad_nl), hi = offsetof(struct xombe_enc, tone_spec);
int same = !memcmp((const char *)a + lo, (const char *)b + lo, hi - lo) && a->tone_prev_id == b->tone_prev_id &&
a->tone_confirmed == b->tone_confirmed && a->tone_hold_used == b->tone_hold_used &&
a->tone_last_id == b->tone_last_id && a->tone_last_ad == b->tone_last_ad && a->p_prev == b->p_prev;
#if XOMBE_HAVE_DSTAR
if (a->cfg.outputs & XOMBE_ENC_DSTAR) {
const xombe_ds_enc *da = XOMBE_DS_ENC(a), *db = XOMBE_DS_ENC(b);
same &= SAME_FIELD(da, db, ns_mem) && SAME_FIELD(&da->tones, &db->tones, detected) &&
SAME_FIELD(&da->tones, &db->tones, run) && SAME_FIELD(&da->tones, &db->tones, confirmed) &&
SAME_FIELD(&da->tones, &db->tones, held) && da->tones.hold_left == db->tones.hold_left &&
SAME_FIELD(&da->tones, &db->tones, level_db);
}
#endif
return same;
}
/* lockstep with an unforced encoder: up to and including the call that emits the forced frame, the analysis
state is the same, a request changes only the output and the prediction memory */
static void test_state(const int16_t *x, unsigned outputs, int tones, int dtx, int start)
{
char what[160];
xombe_enc_cfg cfg = cfg_of(outputs, tones);
xombe_enc *a, *b;
xombe_enc_tone t = {150, 90};
int c, same = 1, delay;
cfg.dmr_dtx = dtx;
a = xombe_enc_init(&mem_a, &cfg);
b = xombe_enc_init(&mem_b, &cfg);
delay = xombe_enc_delay(a);
for (c = 0; c <= start + delay + 3; c++) {
const xombe_enc_tone *r = c >= start && c < start + 4 ? &t : NULL;
uint8_t a2[9], ds[9];
xombe_enc_frame(a, x + 160 * c, r, a2, ds);
xombe_enc_frame(b, x + 160 * c, NULL, a2, ds);
same &= same_analysis(a, b);
}
label(what, outputs, tones, "a request leaves VAD, noise, comfort-noise, and tone detector state as without it");
check(same, what);
}
static void fit(const double *x, int id, double *freq, double *amp, int *nf)
{
float lo, hi;
*nf = xombe__tone_freqs(id, &lo, &hi);
freq[0] = lo;
freq[1] = hi;
search_freqs(x, freq, *nf, *nf == 1 ? 0.005 : 0.05);
sinusoid_fit(x, FIT_LEN, freq, *nf, amp);
}
/* frequency and level errors of a fitted tone, the T5 limits */
static int tone_ok(int id, int ad, const double *freq, const double *amp, int nf, double *worst_df, double *worst_dl)
{
float lo, hi;
double nominal[2];
int c, ok = 1;
xombe__tone_freqs(id, &lo, &hi);
nominal[0] = lo;
nominal[1] = hi;
for (c = 0; c < nf; c++) {
double df = nf == 1 ? fabs(freq[c] - nominal[c]) : fabs(freq[c] - nominal[c]) / nominal[c];
double dl = 20.0 * log10(amp[c] / 32768.0 + 1e-30) - expected_db(ad, freq[c]);
ok &= nf == 1 ? df <= 0.1 : df <= (id >= 160 ? 0.04 : 0.01);
ok &= fabs(dl) <= 0.5;
if (nf == 2 && df > *worst_df)
*worst_df = df;
if (fabs(dl) > fabs(*worst_dl))
*worst_dl = dl;
}
return ok;
}
/* RUN forced frames in speech, decoded through xombe_dec (and xombe_dsd), measured FIT_AT frames into the run */
static void test_decode(const int16_t *x, int frames, unsigned outputs)
{
static run r;
static double y[MAXF * 160];
static const int ids[] = {5, 20, 64, 122, 128, 129, 143, 144, 150, 156, 159, 160, 161, 163};
static const int ads[] = {40, 90, 115};
const int start = 60;
xombe_enc_cfg cfg = cfg_of(outputs, 1);
double wdf = 0.0, wdl = 0.0;
int ii, ai, i, ok = 1, cases = 0;
#if XOMBE_HAVE_DSTAR
double wdf_ds = 0.0, wdl_ds = 0.0, knox_df = 0.0, knox_res = 0.0;
int ok_ds = 1, knox_voice = 1;
#endif
for (ii = 0; ii < (int)(sizeof(ids) / sizeof(ids[0])); ii++) {
for (ai = 0; ai < 3; ai++) {
int id = ids[ii], ad = ads[ai], nf;
double freq[2], amp[2];
xombe_dec dec;
memset(&r, 0, sizeof(r));
r.frames = start + RUN + 1 < frames ? start + RUN + 1 : frames;
for (i = start; i < start + RUN; i++) {
r.req[i].id = id;
r.req[i].ad = ad;
}
encode(&cfg, x, &r);
xombe_dec_set_noise(xombe_dec_init(&dec, XOMBE_DMR), XOMBE_NOISE_CONFORMANCE, 0);
for (i = 0; i < start + RUN; i++) {
int16_t pcm[160];
int k;
xombe_dec_frame_bits(&dec, r.a2[i], 0, pcm);
for (k = 0; k < 160; k++)
y[i * 160 + k] = pcm[k];
}
fit(y + (start + FIT_AT) * 160, id, freq, amp, &nf);
if (!tone_ok(id, ad, freq, amp, nf, &wdf, &wdl)) {
ok = 0;
printf(" AMBE+2 id %d AD %d: %.2f/%.2f Hz\n", id, ad, freq[0], freq[1]);
}
cases++;
#if XOMBE_HAVE_DSTAR
if (outputs & XOMBE_ENC_DSTAR) {
static xombe_dec_mem dm;
xombe_dec *dsd = xombe_dec_init(&dm, XOMBE_DSTAR);
int voice = 1;
xombe_dec_set_noise(dsd, XOMBE_NOISE_CONFORMANCE, 0);
for (i = 0; i < start + RUN; i++) {
int16_t pcm[160];
xombe_decision dc;
int k;
xombe_dec_frame(dsd, r.ds[i], 0, pcm);
xombe_dec_decision_get(dsd, &dc);
if (i >= start)
voice &= dc.cls == XOMBE_CLASS_VOICE;
for (k = 0; k < 160; k++)
y[i * 160 + k] = pcm[k];
}
if (ds_code(id) < 0) {
/* Knox: voice frames with the two tones on the nearest D-STAR harmonics */
const double *seg = y + (start + FIT_AT) * 160;
double e = 0.0, res, df = 0.0;
float lo, hi;
int c2;
xombe__tone_freqs(id, &lo, &hi);
fit(seg, id, freq, amp, &nf);
for (i = 0; i < FIT_LEN; i++)
e += seg[i] * seg[i];
res = sinusoid_fit(seg, FIT_LEN, freq, nf, amp) / e;
for (c2 = 0; c2 < 2; c2++) {
double d = fabs(freq[c2] - (c2 ? hi : lo)) / (c2 ? hi : lo);
df = d > df ? d : df;
}
knox_df = df > knox_df ? df : knox_df;
knox_res = res > knox_res ? res : knox_res;
if (!voice || df > 0.03 || res > 0.6) {
knox_voice = 0;
printf(" D-STAR Knox id %d AD %d: voice %d, frequency error %.2f%%, residual %.2f\n", id, ad,
voice, 100.0 * df, res);
}
} else {
fit(y + (start + FIT_AT) * 160, id, freq, amp, &nf);
if (!tone_ok(id, ad, freq, amp, nf, &wdf_ds, &wdl_ds)) {
ok_ds = 0;
printf(" D-STAR id %d AD %d: %.2f/%.2f Hz, %.1f/%.1f\n", id, ad, freq[0], freq[1],
20.0 * log10(amp[0] / 32768.0), expected_db(ad, freq[0]));
}
}
}
#endif
}
}
printf("forced tones (%s): %d cases, AMBE+2 worst dual frequency error %.2f%%, worst level error %+.3f dB\n",
outputs & XOMBE_ENC_DSTAR ? "dual" : "AMBE+2", cases, 100.0 * wdf, wdl);
check(ok, "forced tones decode at their frequency and level (T5 limits)");
#if XOMBE_HAVE_DSTAR
if (outputs & XOMBE_ENC_DSTAR) {
printf("forced tones, D-STAR: worst dual frequency error %.2f%%, worst level error %+.3f dB\n", 100.0 * wdf_ds,
wdl_ds);
check(ok_ds, "forced D-STAR tones decode at their frequency and level (T5 limits)");
printf("forced Knox tones, D-STAR: worst frequency error %.2f%%, worst residual %.2f of the energy\n",
100.0 * knox_df, knox_res);
check(knox_voice, "forced Knox tones are D-STAR voice frames carrying the tone");
}
#endif
}
/* the packers' frames are the forced encoder's, for every ID at levels 0..127 in steps of 7 and 127, and decode
as tone frames of that ID and level */
static void test_packers(const int16_t *x, int frames, unsigned outputs)
{
static run r;
static int16_t loop[MAXF * 160];
xombe_enc_cfg cfg = cfg_of(outputs, 1);
int id, ad, i, n = 0, same = 1, decoded = 1;
memset(&r, 0, sizeof(r));
for (i = 0; i < MAXF; i++)
memcpy(loop + 160 * i, x + 160 * (i % frames), sizeof(int16_t) * 160);
for (id = 5; id <= 163; id++)
for (ad = 0; ad <= 127 + 6; ad += 7)
if (xombe__tone_id_accepted(id) && n < MAXF) {
r.req[n].id = id;
r.req[n].ad = ad > 127 ? 127 : ad;
n++;
}
r.frames = n;
encode(&cfg, loop, &r);
for (i = 0; i < n; i++) {
static xombe_dec dec;
uint8_t a2[7], f[9], d[9], d49[49];
int16_t pcm[160];
xombe_decision dc;
xombe_fec fec;
int ok = xombe_tone_frame(XOMBE_DMR, r.req[i].id, r.req[i].ad, f) == 0, pid, pad;
xombe_fec_init(&fec, XOMBE_DMR);
xombe_fec_decode(&fec, f, a2, NULL);
if (outputs & XOMBE_ENC_DMR)
same &= ok && !memcmp(a2, r.a2[i], 7);
xombe_dec_set_noise(xombe_dec_init(&dec, XOMBE_DMR), XOMBE_NOISE_CONFORMANCE, 0);
xombe_dec_frame(&dec, f, 0, pcm);
xombe_dec_decision_get(&dec, &dc);
xombe__unpack49(a2, d49);
decoded &= dc.cls == XOMBE_CLASS_TONE && xombe__tone_frame_parse(d49, &pid, &pad) && pid == r.req[i].id &&
pad == r.req[i].ad;
#if XOMBE_HAVE_DSTAR
if (outputs & XOMBE_ENC_DSTAR) {
int T = ds_code(r.req[i].id);
ok = xombe_tone_frame(XOMBE_DSTAR, r.req[i].id, r.req[i].ad, d);
same &= T >= 0 ? ok == 0 && !memcmp(d, r.ds[i], 9) : ok == -1;
if (T >= 0) {
static xombe_dec_mem dm;
xombe_dec *dsd = xombe_dec_init(&dm, XOMBE_DSTAR);
xombe_decision dd;
xombe_ds_frame fr;
xombe_dec_set_noise(dsd, XOMBE_NOISE_CONFORMANCE, 0);
xombe_dec_frame(dsd, d, 0, pcm);
xombe_dec_decision_get(dsd, &dd);
xombe__ds_fec_decode(d, &fr);
decoded &= dd.cls == XOMBE_CLASS_TONE && fr.tid == r.req[i].id &&
fr.AD == (r.req[i].ad < 8 ? 8 : r.req[i].ad);
}
}
#else
(void)d;
#endif
}
check(n < MAXF, "every ID in the packer sweep");
check(same, outputs & XOMBE_ENC_DSTAR ? "packers equal the forced dual encoder's frames"
: "xombe_tone_frame equals the forced DMR encoder's frames");
check(decoded, "packer frames decode as tone frames of their ID and level");
}
#if XOMBE_HAVE_DSTAR
/* the D-STAR encoder's mirror equals the decoder's, replayed from the emitted frames, after every frame, with
forced tones in speech */
static void test_ds_mirror(const int16_t *x, int frames)
{
static run r;
xombe_enc_cfg cfg = cfg_of(XOMBE_ENC_DMR | XOMBE_ENC_DSTAR, 1);
xombe_enc *e = xombe_enc_init(&mem_a, &cfg);
xombe_ds_mirror dm;
int c, bad = 0, n = 0, knox = 0, tone = 0, knox_bad = 0, delay = xombe_enc_delay(e);
uint32_t s = 12345u;
xombe__ds_mirror_init(&dm);
memset(&r, 0, sizeof(r));
for (c = 30; c < frames; c += 7 + (int)(s % 23)) {
int k, len = 1 + (int)((s >> 8) % 3), id = (int)((s >> 12) % 154) + 5;
if (id > 122)
id += 5;
for (k = 0; k < len && c + k < frames; k++) {
r.req[c + k].id = id;
r.req[c + k].ad = (int)((s >> 16) % 128);
}
knox += id >= 144 && id <= 159;
tone += id < 144 || id > 159;
s = s * 1664525u + 1013904223u;
}
for (c = 0; c < frames; c++) {
static xombe_ds_enc before;
uint8_t a2[7], ds[9], want[9];
const xombe_enc_tone *t = c >= delay ? &r.req[c - delay] : NULL;
int is_knox = t && t->id >= 144 && t->id <= 159;
if (is_knox) {
/* the encoder's own Knox frame at the requested level */
int k = 0, b[9];
before = *XOMBE_DS_ENC(e);
while (before.tones.knox[k].id != t->id)
k++;
xombe__ds_knox_amps(&before, k, (float)t->ad, b);
xombe__ds_encode_fields(b, want);
}
if (enc_frame(e, x + 160 * c, r.req[c].id ? &r.req[c] : NULL, a2, ds) == 1) {
const xombe_ds_mirror *m = &XOMBE_DS_ENC(e)->mirror;
xombe_ds_frame fr;
xombe_ds_params p;
xombe__ds_fec_decode(ds, &fr);
xombe__ds_params_from_frame(&dm, &fr, &p);
bad += m->L != dm.L || m->G != dm.G || memcmp(m->a, dm.a, sizeof(m->a));
knox_bad += is_knox && memcmp(ds, want, 9);
n++;
}
}
printf("D-STAR mirror with %d forced tone and %d Knox requests: %d/%d frames equal\n", tone, knox, n - bad, n);
check(knox > 0 && tone > 0, "mirror test forces both kinds");
check(bad == 0, "the D-STAR mirror stays equal to the decoder's across forced tones");
check(knox_bad == 0, "a forced Knox tone is the D-STAR encoder's Knox voice frame");
}
#endif
int main(int argc, char **argv)
{
const char *vec = argc > 1 ? argv[1] : "vectors";
int fs, ft;
int16_t *speech = load_raw(vec, "e3/es1_orig.raw", &fs), *tones = load_raw(vec, "e7/tones.raw", &ft);
test_position(speech, fs, XOMBE_ENC_DMR, 1);
test_position(speech, fs, XOMBE_ENC_DMR, 0);
test_in_tone_run(tones, ft, XOMBE_ENC_DMR);
test_state(speech, XOMBE_ENC_DMR, 1, 1, 50);
test_state(tones, XOMBE_ENC_DMR, 1, 1, 50);
test_state(speech, XOMBE_ENC_DMR, 0, 0, 80);
test_decode(speech, fs, XOMBE_ENC_DMR);
test_packers(speech, fs, XOMBE_ENC_DMR);
#if XOMBE_HAVE_DSTAR
test_position(speech, fs, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR, 1);
test_position(speech, fs, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR, 0);
test_position(speech, fs, XOMBE_ENC_DSTAR, 1);
test_in_tone_run(tones, ft, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR);
test_state(speech, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR, 1, 1, 50);
test_state(tones, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR, 1, 0, 50);
test_decode(speech, fs, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR);
test_ds_mirror(speech, fs);
test_packers(speech, fs, XOMBE_ENC_DMR | XOMBE_ENC_DSTAR);
#endif
free(speech);
free(tones);
printf("forced tones: %d/%d checks passed\n", checks - failures, checks);
return failures ? 1 : 0;
}
+321
View File
@@ -0,0 +1,321 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
static int failures, checks;
static void check(int ok, const char *what, int index)
{
checks++;
if (!ok) {
failures++;
if (failures <= 20)
fprintf(stderr, "FAIL %s (item %d)\n", what, index);
}
}
static int hex_bytes(const char *s, uint8_t *out, int n)
{
int i;
for (i = 0; i < n; i++) {
unsigned v;
if (sscanf(s + 2 * i, "%2x", &v) != 1)
return 0;
out[i] = (uint8_t)v;
}
return 1;
}
static FILE *open_vec(const char *dir, const char *name)
{
char path[4096];
FILE *f;
snprintf(path, sizeof(path), "%s/%s", dir, name);
f = fopen(path, "r");
if (!f) {
perror(path);
exit(2);
}
return f;
}
static void test_encode_vectors(const char *dir)
{
char line[512], h49[64], h72[64];
FILE *f = open_vec(dir, "fec_encode_vectors.txt");
int n = 0;
while (fgets(line, sizeof(line), f)) {
uint8_t b[7], air[9], mine[9], back[7];
xombe_fec fec;
xombe_fec_stats st;
unsigned flags;
if (line[0] == '#' || sscanf(line, "%63s %63s", h49, h72) != 2)
continue;
hex_bytes(h49, b, 7);
hex_bytes(h72, air, 9);
xombe_fec_encode(XOMBE_DMR, b, mine);
check(!memcmp(mine, air, 9), "encode vector", n);
xombe_fec_init(&fec, XOMBE_DMR);
flags = xombe_fec_decode(&fec, air, back, &st);
check(!memcmp(back, b, 7) && st.eps0 == 0 && st.eps1 == 0 && flags == 0, "decode vector", n);
n++;
}
fclose(f);
check(n == 80, "80 encode vectors", n);
printf("fec_encode_vectors: %d pairs\n", n);
}
static void test_air_map(const char *dir)
{
char line[512], cw[16], label[32];
FILE *f = open_vec(dir, "air72_map.txt");
static const int offset[4] = {0, 24, 47, 58};
static const int data_base[4] = {0, 12, 24, 35};
static const int data_len[4] = {12, 12, 11, 14};
uint8_t w[72], a[72];
int n = 0, i;
for (i = 0; i < 72; i++)
w[i] = (uint8_t)i;
xombe__interleave(w, a);
while (fgets(line, sizeof(line), f)) {
int air_bit, k, bit;
char *p;
if (line[0] == '#')
continue;
if (sscanf(line, "%d %15s", &air_bit, cw) != 2)
continue;
p = strchr(line, '[');
if (!p || sscanf(p + 1, "%d] %31s", &bit, label) != 2)
continue;
k = cw[1] - '0';
check(a[air_bit] == offset[k] + bit, "air map position", air_bit);
if (bit < data_len[k]) {
char want[16];
snprintf(want, sizeof(want), "d%d", data_base[k] + bit);
check(!strcmp(label, want), "air map data index", air_bit);
} else {
check(!strcmp(label, "parity"), "air map parity", air_bit);
}
n++;
}
fclose(f);
check(n == 72, "72 air map entries", n);
printf("air72_map: %d entries\n", n);
}
static uint32_t rng_state = 12345u;
static uint32_t rnd(void)
{
rng_state = rng_state * 1103515245u + 12345u;
return rng_state >> 8;
}
static void flip_codeword_bit(uint8_t air[9], int w_index)
{
uint8_t w[72], a[72];
int i;
for (i = 0; i < 72; i++)
w[i] = (uint8_t)(i == w_index);
xombe__interleave(w, a);
for (i = 0; i < 72; i++)
if (a[i])
air[i >> 3] ^= (uint8_t)(0x80 >> (i & 7));
}
static void test_injection(void)
{
int trial, e0, e1, n = 0;
for (trial = 0; trial < 400; trial++) {
for (e0 = 0; e0 <= 3; e0++) {
for (e1 = 0; e1 <= 3; e1++) {
uint8_t b[7], air[9], back[7];
int used[24] = {0}, used1[23] = {0}, i;
xombe_fec fec;
xombe_fec_stats st;
for (i = 0; i < 7; i++)
b[i] = (uint8_t)rnd();
b[6] &= 0x80;
xombe_fec_encode(XOMBE_DMR, b, air);
for (i = 0; i < e0;) {
int pos = (int)(rnd() % 24);
if (used[pos])
continue;
used[pos] = 1;
flip_codeword_bit(air, pos);
i++;
}
for (i = 0; i < e1;) {
int pos = (int)(rnd() % 23);
if (used1[pos])
continue;
used1[pos] = 1;
flip_codeword_bit(air, 24 + pos);
i++;
}
xombe_fec_init(&fec, XOMBE_DMR);
xombe_fec_decode(&fec, air, back, &st);
check(!memcmp(back, b, 7), "corrected data", trial);
check(st.eps0 == e0 && st.eps1 == e1, "error counts", trial);
check(st.bf == (e0 >= 2 && e0 + e1 >= 6), "bad-frame flag", trial);
n++;
}
}
{
uint8_t b[7], air[9], back[7];
int i;
xombe_fec fec;
xombe_fec_stats st;
for (i = 0; i < 7; i++)
b[i] = (uint8_t)rnd();
b[6] &= 0x80;
xombe_fec_encode(XOMBE_DMR, b, air);
flip_codeword_bit(air, 23);
xombe_fec_init(&fec, XOMBE_DMR);
xombe_fec_decode(&fec, air, back, &st);
check(!memcmp(back, b, 7) && st.eps0 == 1 && st.eps1 == 0, "parity-only error", trial);
n++;
}
}
printf("error injection: %d frames\n", n);
}
static void test_c0x4(const char *dir)
{
char line[512], s49[64], a72[64], o49[64];
FILE *f = open_vec(dir, "fec_decode_c0x4.txt");
int n = 0;
while (fgets(line, sizeof(line), f)) {
uint8_t air[9], want[7], got[7];
int e0, e1, bf;
xombe_fec fec;
xombe_fec_stats st;
if (line[0] == '#' || sscanf(line, "%63s %63s %63s %d %d %d", s49, a72, o49, &e0, &e1, &bf) != 6)
continue;
hex_bytes(a72, air, 9);
hex_bytes(o49, want, 7);
xombe_fec_init(&fec, XOMBE_DMR);
xombe_fec_decode(&fec, air, got, &st);
check(!memcmp(got, want, 7), "c0x4 output bits", n);
check(st.eps0 == e0 && st.eps1 == e1 && st.bf == bf, "c0x4 counts and BF", n);
n++;
}
fclose(f);
check(n == 200, "200 c0x4 frames", n);
printf("fec_decode_c0x4: %d frames\n", n);
}
static void test_hb_onset(const char *dir)
{
char line[512], a72[64], o49[64];
FILE *f = open_vec(dir, "fec_hb_onset.txt");
int n = 0, cur_seq = -1;
xombe_fec fec;
xombe_fec_init(&fec, XOMBE_DMR);
while (fgets(line, sizeof(line), f)) {
uint8_t air[9], want[7], got[7];
int seq, fr, e0, e1, bf, hb;
xombe_fec_stats st;
if (line[0] == '#' ||
sscanf(line, "%d %d %63s %63s %d %d %d %d", &seq, &fr, a72, o49, &e0, &e1, &bf, &hb) != 8)
continue;
if (seq != cur_seq) {
xombe_fec_init(&fec, XOMBE_DMR);
cur_seq = seq;
}
hex_bytes(a72, air, 9);
hex_bytes(o49, want, 7);
xombe_fec_decode(&fec, air, got, &st);
check(!memcmp(got, want, 7), "hb_onset output bits", n);
check(st.eps0 == e0 && st.eps1 == e1 && st.bf == bf && st.hb == hb, "hb_onset flags", n);
n++;
}
fclose(f);
printf("fec_hb_onset: %d frames\n", n);
}
static void test_fields(void)
{
uint8_t d[49];
int b[9], c, i, f;
for (c = 0; c < 64; c++) {
memset(d, 0, sizeof(d));
xombe__put_bits(d, 0, 6, c);
i = xombe__frame_class(d);
check(i == (c < 60 ? XOMBE_CLASS_VOICE : c < 62 ? XOMBE_CLASS_ERASURE
: c == 62 ? XOMBE_CLASS_SILENCE : XOMBE_CLASS_TONE), "frame class", c);
}
for (f = 0; f < 9; f++) {
static const int lsb[9] = {39, 35, 36, 43, 42, 44, 45, 46, 48};
static const int msb[9] = {0, 4, 8, 12, 20, 24, 28, 31, 34};
static const int width[9] = {7, 5, 5, 9, 7, 5, 4, 4, 3};
memset(b, 0, sizeof(b));
b[f] = 1;
memset(d, 0, sizeof(d));
xombe__put_fields(b, d);
check(d[lsb[f]] == 1, "field LSB position", f);
b[f] = 1 << (width[f] - 1);
memset(d, 0, sizeof(d));
xombe__put_fields(b, d);
check(d[msb[f]] == 1, "field MSB position", f);
}
for (i = 0; i < 2000; i++) {
int back[9];
uint8_t packed[7], again[49];
for (c = 0; c < 49; c++)
d[c] = (uint8_t)(rnd() & 1);
xombe__get_fields(d, b);
memset(again, 0, sizeof(again));
xombe__put_fields(b, again);
check(!memcmp(again, d, 49), "field round trip", i);
xombe__pack49(d, packed);
xombe__unpack49(packed, again);
check(!memcmp(again, d, 49), "pack round trip", i);
xombe__get_fields(again, back);
check(!memcmp(back, b, sizeof(b)), "field values", i);
}
printf("class and field map: ok\n");
}
/* Q24 running error rate against 0.95*eps_r + 0.05*eps_t/47 in double, over runs of error counts hovering
around the HB threshold (eps_t = 4 or 5 in steady state gives eps_r 0.085 or 0.106) */
static void test_eps_r(void)
{
xombe_fec f;
double r = 0.0, worst = 0.0;
int i, hb_diff = 0;
xombe_fec_init(&f, XOMBE_DMR);
for (i = 0; i < 200000; i++) {
xombe_fec_stats st;
int burst = (i / 1000) % 3;
memset(&st, 0, sizeof(st));
st.eps0 = (int)(rnd() % (burst == 0 ? 3u : burst == 1 ? 5u : 8u));
st.eps1 = (int)(rnd() % 4u);
if (st.eps0 > 4)
st.eps0 = 4;
xombe__fec_stats_update(&f, &st);
r = 0.95 * r + 0.05 * st.eps_t / 47.0;
if (fabs(st.eps_r / 16777216.0 - r) > worst)
worst = fabs(st.eps_r / 16777216.0 - r);
if (st.hb != (r > 0.096) && fabs(r - 0.096) > 1e-6)
hb_diff++;
}
check(worst < 1e-6, "eps_r within 1e-6 of the double recursion", 0);
check(hb_diff == 0, "HB as in the double recursion away from the threshold", hb_diff);
printf("eps_r: worst %.2g against double\n", worst);
}
int main(int argc, char **argv)
{
const char *dir = argc > 1 ? argv[1] : "vectors/fec";
test_encode_vectors(dir);
test_air_map(dir);
test_injection();
test_c0x4(dir);
test_hb_onset(dir);
test_fields();
test_eps_r();
printf("T1: %d/%d checks passed\n", checks - failures, checks);
return failures ? 1 : 0;
}
+109
View File
@@ -0,0 +1,109 @@
/* closed-loop quantizer (src/common/cquant.c): the pruned pair search against the exhaustive one on random
shaped targets for both table sets, and with the q15 kernels the codebook images against the codebooks */
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "../src/common/cquant.h"
#include "../src/dstar/dstar_internal.h"
#include "../src/tables/dsp_tables.h"
#define CASES 300
static unsigned rng = 12345u;
static float urand(void) /* [0, 1) */
{
rng = rng * 1664525u + 1013904223u;
return (float)(rng >> 8) / 16777216.0f;
}
static int irand(int n)
{
return (int)(urand() * (float)n) % n;
}
static xombe_cq_ws ws;
/* random fields' shape plus noise, quantized with and without pruning, uncapped */
static int brute_cases(const xombe_amp_tables *ts, const char *name)
{
int c, bad = 0;
for (c = 0; c < CASES; c++) {
float t[XOMBE_LMAX + 1], target[XOMBE_LMAX + 1], base[XOMBE_LMAX + 1], w[XOMBE_LMAX + 1], G;
float noise = 0.05f + 0.6f * urand();
int b[9] = {0}, L = 9 + irand(48), l, k, pass;
xombe_cq_result res[2];
b[3] = irand(ts->n_prba24);
b[4] = irand(ts->n_prba58);
for (k = 0; k < 4; k++)
b[5 + k] = irand(ts->n_hoc[k]);
xombe__spectral_shape_ts(ts, b, L, t);
G = 2.0f * urand() - 1.0f;
target[0] = base[0] = 0.0f;
for (l = 1; l <= L; l++) {
target[l] = t[l] + 3.0f * G + noise * (2.0f * urand() - 1.0f);
base[l] = -xombe__half_log2[L];
}
xombe__cq_amp_weights(target, L, XOMBE_CQ_QWEIGHT, XOMBE_CQ_WEIGHT_FLOOR, w);
for (pass = 0; pass < 2; pass++) {
memset(&ws, 0, sizeof(ws));
ws.brute = pass;
xombe__cq_prepare(&ws, ts, L, c & 1 ? w : NULL);
xombe__cq_closed(&ws, target, target, base, 0.0f, XOMBE_CQ_N_PAIRS, XOMBE_CQ_N_GAIN, XOMBE_CQ_ITERS,
&res[pass]);
}
for (k = 2; k < 9 && res[0].b[k] == res[1].b[k]; k++)
;
if (k < 9 && bad++ < 5)
fprintf(stderr, "%s case %d (L %d): pruned b%d %d, exhaustive %d\n", name, c, L, k, res[0].b[k],
res[1].b[k]);
}
printf("kern_cq: %s %d/%d cases pruned = exhaustive\n", name, CASES - bad, CASES);
return bad;
}
#if XOMBE_KERNELS_Q15
/* every image entry within 1/2 unit of its exact value and within its column's maximum */
static int image_check(const xombe_amp_tables *ts, const xombe_cq_q15_tab *qt, const char *name)
{
static const int p24[6][2] = {{0, 0}, {1, 1}, {2, 2}, {0, 1}, {0, 2}, {1, 2}};
static const int p58[10][2] = {{0, 0}, {1, 1}, {2, 2}, {3, 3}, {0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
int i, k, bad = 0;
for (i = 0; i < ts->n_prba24; i++) {
const float *x = ts->prba24[i];
for (k = 0; k < 9; k++) {
uint32_t v = qt->r24[i][k / 2];
int q = (int16_t)(k & 1 ? v >> 16 : v & 0xffff), t = k < 6 ? qt->tm24 : qt->tx24;
double e = k < 6 ? (p24[k][0] == p24[k][1] ? 1.0 : 2.0) * x[p24[k][0]] * x[p24[k][1]] : x[k - 6];
double m = k < 6 ? qt->m24[k] : qt->x24[k - 6];
bad += fabs(q - ldexp(e, t)) > 0.5 || fabs(ldexp(q, -t)) > m;
}
}
for (i = 0; i < ts->n_prba58; i++) {
const float *x = ts->prba58[i];
for (k = 0; k < 14; k++) {
uint32_t v = qt->r58[i][k / 2];
int q = (int16_t)(k & 1 ? v >> 16 : v & 0xffff), t = k < 10 ? qt->tm58 : qt->tx58;
double e = k < 10 ? (p58[k][0] == p58[k][1] ? 1.0 : 2.0) * x[p58[k][0]] * x[p58[k][1]] : x[k - 10];
double m = k < 10 ? qt->m58[k] : qt->x58[k - 10];
bad += fabs(q - ldexp(e, t)) > 0.5 || fabs(ldexp(q, -t)) > m;
}
}
printf("kern_cq: %s images %s\n", name, bad ? "WRONG, rerun scripts/gen_cq_tables.py" : "match the codebooks");
return bad;
}
#endif
int main(int argc, char **argv)
{
int bad = 0;
(void)argc;
(void)argv;
#if XOMBE_KERNELS_Q15
bad += image_check(&xombe__amp_ambe2, &xombe__cq_q15_ambe2, "AMBE+2");
bad += image_check(&xombe__amp_dstar, &xombe__cq_q15_dstar, "D-STAR");
#endif
bad += brute_cases(&xombe__amp_ambe2, "AMBE+2");
bad += brute_cases(&xombe__amp_dstar, "D-STAR");
return bad != 0;
}
+162
View File
@@ -0,0 +1,162 @@
/* decoder kernels (src/dec/dkernels.h) and src/dsp/fmath.h against float, argv[1] the vectors directory */
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "../src/internal.h"
#include "../src/dec/dkernels.h"
#include "../src/dsp/fmath.h"
#if XOMBE_KERNELS_Q15
/* the float kernels as the reference, renamed */
#define xombe__dk_wavetable ref_wavetable
#define xombe__dk_add_grain ref_add_grain
#define xombe__dk_unvoiced ref_unvoiced
void ref_wavetable(const xombe_set *s, const float *M, const uint8_t *vh, float tab[XOMBE_WT_SIZE]);
void ref_add_grain(float *buf, int N, float P, float fhat, float period, const float *tab);
void ref_unvoiced(const int16_t *seg, int N, const xombe_set *cur, const float *M, const uint8_t *vh,
float avg_f0, float y[XOMBE_UV_FFT]);
#include "../src/dec/dkern_float.c"
#undef xombe__dk_wavetable
#undef xombe__dk_add_grain
#undef xombe__dk_unvoiced
#endif
/* fmath.h against libm: exact in float builds, in q15 builds exp2 within EXP2_TOL relative, log2 and sincos
within LOG2_TOL (absolute, relative above 1) and SINCOS_TOL absolute, sincos over |x| <= 520 (wavetable
phases reach about 360) */
#define EXP2_TOL 2e-7
#define LOG2_TOL 1.5e-7
#define SINCOS_TOL 2e-7
static double rel_err(double v, double ref)
{
return fabs(v - ref) / fabs(ref);
}
static double log_err(double v, double ref)
{
return fabs(v - ref) / fmax(1.0, fabs(ref));
}
static int test_fmath(void)
{
double e_exp = 0.0, e_log = 0.0, e_sc = 0.0, d;
int i, fails = 0;
for (i = -1300000; i <= 1300000; i++) {
float x = (float)i * 9e-5f, y = exp2f((float)i * 9.6e-5f), z = (float)(i + 1300001) * 1e-6f, s, c;
xombe__sincosf(4.4f * x, &s, &c);
d = fmax(fabs(s - sin(4.4f * x)), fabs(c - cos(4.4f * x)));
e_sc = fmax(e_sc, d);
e_exp = fmax(e_exp, rel_err(xombe__exp2f(x), exp2(x)));
e_log = fmax(e_log, fmax(log_err(xombe__log2f(y), log2(y)), log_err(xombe__log2f(z), log2(z))));
if (!XOMBE_KERNELS_Q15) {
xombe__sincosf(x, &s, &c);
if (xombe__exp2f(x) != exp2f(x) || s != sinf(x) || c != cosf(x) || xombe__log2f(y) != log2f(y))
fails++;
}
}
/* libm's results at the edges */
if (xombe__exp2f(-200.0f) != exp2f(-200.0f) || !isinf(xombe__exp2f(200.0f)) || isinf(xombe__exp2f(127.9f)) ||
!isinf(xombe__log2f(0.0f)) || xombe__log2f(1e-40f) != log2f(1e-40f))
fails++;
if (XOMBE_KERNELS_Q15 && (e_exp > EXP2_TOL || e_log > LOG2_TOL || e_sc > SINCOS_TOL))
fails++;
printf("kern_dec: fmath max error exp2 %.2e (relative), log2 %.2e, sincos %.2e: %s\n", e_exp, e_log, e_sc,
fails ? "FAIL" : "ok");
return fails;
}
#if XOMBE_KERNELS_Q15
/* q15 kernels against float on random sets, SNR limits in dB over each output: the wavetable differs only by
fmath.h, the unvoiced transforms carry the Q15 FFT's 60-70 dB, down to ~52 dB when a few strong unvoiced
bands hold nearly all the power, the block exponent then set by bins the error spreads over all */
#define WT_SNR 100.0
#define GRAIN_SNR 95.0
#define UV_SNR 50.0
#define CN_SNR 55.0
#define SETS 400
static uint32_t rng = 1;
static float urand(void)
{
rng = rng * 1664525u + 1013904223u;
return (float)(rng >> 8) * (1.0f / 16777216.0f);
}
static void snr_add(const float *a, const float *b, int n, double *worst)
{
double e = 0.0, p = 0.0, r;
int i;
for (i = 0; i < n; i++) {
e += (double)(a[i] - b[i]) * (a[i] - b[i]);
p += (double)b[i] * b[i];
}
r = e > 0.0 ? 10.0 * log10(p / e) : 200.0;
if (p > 0.0 && r < *worst)
*worst = r;
}
/* f0 80..400 Hz, log2 amplitudes falling about 0.1 per harmonic plus up to 6 of noise, random phases and
voicing, every class but tone */
static void random_set(xombe_set *s, float *M, uint8_t *vh)
{
int l;
memset(s, 0, sizeof(*s));
s->f0 = XOMBE_HZ(80.0f + 320.0f * urand());
s->L = xombe__L_from_f0(s->f0);
s->cls = urand() < 0.2f ? XOMBE_CLASS_SILENCE : XOMBE_CLASS_VOICE;
for (l = 0; l <= XOMBE_LMAX; l++) {
M[l] = l ? exp2f(12.0f - 0.1f * (float)l - 6.0f * urand()) : 0.0f;
vh[l] = (uint8_t)(urand() < 0.5f);
s->phi[l] = 400.0f * (urand() - 0.5f);
}
}
static int test_kernels(void)
{
double wt = 200.0, uv = 200.0, cn = 200.0, gr = 200.0;
int i, n, fails;
for (i = 0; i < SETS; i++) {
xombe_set s;
float M[XOMBE_LMAX + 1], a[XOMBE_UV_FFT], b[XOMBE_UV_FFT];
int16_t seg[2 * XOMBE_HALF_MAX];
uint8_t vh[XOMBE_LMAX + 1];
int N = XOMBE_HALF_MIN + (int)(urand() * (XOMBE_HALF_MAX - XOMBE_HALF_MIN + 1));
random_set(&s, M, vh);
xombe__dk_wavetable(&s, M, vh, a);
ref_wavetable(&s, M, vh, b);
snr_add(a, b, XOMBE_WT_SIZE, &wt);
{
float ga[XOMBE_HALF_MAX + XOMBE_TAIL], gb[XOMBE_HALF_MAX + XOMBE_TAIL], fh = s.f0 * (0.9f + 0.2f * urand());
float P = 1.5f * (float)N * urand() - 0.5f * (float)N;
memset(ga, 0, sizeof(ga));
memset(gb, 0, sizeof(gb));
xombe__dk_add_grain(ga, N, P, fh, 1.0f / s.f0, b);
ref_add_grain(gb, N, P, fh, 1.0f / s.f0, b);
snr_add(ga, gb, N + XOMBE_TAIL, &gr);
}
for (n = 0; n < 2 * N; n++)
seg[n] = (int16_t)(urand() * 65535.0f - 32768.0f);
xombe__dk_unvoiced(seg, N, &s, M, vh, XOMBE_HZ(100.0f), a);
ref_unvoiced(seg, N, &s, M, vh, XOMBE_HZ(100.0f), b);
snr_add(a, b, 2 * N, s.cls == XOMBE_CLASS_SILENCE ? &cn : &uv);
}
fails = (wt < WT_SNR) + (gr < GRAIN_SNR) + (uv < UV_SNR) + (cn < CN_SNR);
printf("kern_dec: worst SNR vs float over %d sets, wavetable %.1f dB, grain %.1f dB, unvoiced %.1f dB, comfort "
"noise %.1f dB: %s\n", SETS, wt, gr, uv, cn, fails ? "FAIL" : "ok");
return fails;
}
#endif
int main(int argc, char **argv)
{
int fails = 0;
(void)argc;
(void)argv;
fails += test_fmath();
#if XOMBE_KERNELS_Q15
fails += test_kernels();
#endif
return fails != 0;
}
+219
View File
@@ -0,0 +1,219 @@
/* analysis spectrum kernels (src/enc/kernels.h) against a double-precision DFT, argv[1] the vectors directory */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "../src/enc/kernels.h"
#include "../src/tables/dsp_tables.h"
#define PI 3.14159265358979323846
#define HMAX (XOMBE_MAX_WINDOW / 2)
/* worst bin amplitude error relative to the peak bin, and least SNR over all bins. q15: the block-floating-point
FFT sets both (61 dB, 0.0032 on these frames with a float split), prepared bins against their range's peak */
#if XOMBE_KERNELS_Q15
#define AMP_TOL 5e-3
#define SNR_MIN 58.0
#define LF_TOL 0.05
#else
#define AMP_TOL 1e-5
#define SNR_MIN 100.0
#endif
static int fails;
static double worst_snr = 1e9, worst_amp, sum_snr;
#if XOMBE_KERNELS_Q15
static double worst_lf;
#endif
static int nsnr;
static double urand(uint32_t *s)
{
*s = *s * 1664525u + 1013904223u;
return (double)(*s >> 8) / 8388608.0 - 1.0;
}
static void fail(const char *what, const char *msg, double v)
{
if (fails++ < 10)
printf("%s: %s %g\n", what, msg, v);
}
#if XOMBE_KERNELS_Q15
/* block layout, then lf_prepare on the whole band and on a high band: prepared peak at least 16384, exact prefix
sums, and bins / g against the reference relative to the range's peak */
static void check_q15(const char *what, const xombe_spec *S, const double *rr, const double *ri)
{
static xombe_enc e;
const int16_t *re = S->v, *im = re + XOMBE_LF_IM;
int k, j, big = 0, kmax = XOMBE_SPEC_BINS - 2;
if (im[0] != 0 || im[XOMBE_SPEC_BINS - 1] != 0)
fail(what, "imaginary DC or Nyquist", 0);
for (k = 0; k < XOMBE_SPEC_BINS; k++) {
if (abs(re[k]) > big)
big = abs(re[k]);
if (abs(im[k]) > big)
big = abs(im[k]);
}
if (big < 32735 || big > 32767)
fail(what, "largest component", big);
for (j = 0; j < 2; j++) {
xombe_lf_spec sp;
uint64_t acc = 0;
double lpeak = 0.0, lf = 0.0;
const int16_t *pr, *pi;
int kmin = j ? 300 : 1, top = 0;
xombe__kern_lf_prepare(&e, S, kmin, kmax, &sp);
if (sp.g == 0.0f || (sp.S != S && sp.S != &e.kq.spec)) {
fail(what, "prepared g 0 or a foreign spectrum, from kmin", kmin);
continue;
}
pr = sp.S->v;
pi = pr + XOMBE_LF_IM;
if (e.kq.ep[kmin] != 0)
fail(what, "prefix sum start", (double)e.kq.ep[kmin]);
for (k = kmin; k <= kmax; k++) {
acc += (uint64_t)((int32_t)pr[k] * pr[k]) + (uint64_t)((int32_t)pi[k] * pi[k]);
if (e.kq.ep[k + 1] != acc)
fail(what, "prefix sum at", k);
if (abs(pr[k]) > top)
top = abs(pr[k]);
if (abs(pi[k]) > top)
top = abs(pi[k]);
if (hypot(rr[k], ri[k]) > lpeak)
lpeak = hypot(rr[k], ri[k]);
}
if (top < 16384)
fail(what, "prepared peak", top);
for (k = kmin; k <= kmax; k++) {
double d = hypot(pr[k] / sp.g - rr[k], pi[k] / sp.g - ri[k]) / lpeak;
if (d > lf)
lf = d;
}
if (lf > worst_lf)
worst_lf = lf;
if (lf > LF_TOL)
fail(what, "prepared bins off, of the range peak, by", lf);
}
}
#endif
static void check_frame(const char *what, const float *centre, const float *w, int n, double sum_w2)
{
static double rr[XOMBE_SPEC_BINS], ri[XOMBE_SPEC_BINS];
static float P[XOMBE_SPEC_BINS];
static xombe_spec S;
double peak = 0.0, sig = 0.0, err = 0.0, amp = 0.0, scale = 1.0 / (XOMBE_FFT * sum_w2), snr;
int half = (n - 1) / 2, j, k;
for (k = 0; k < XOMBE_SPEC_BINS; k++) {
double xr = 0.0, xi = 0.0;
for (j = -half; j <= half; j++) {
double a = -2.0 * PI * (double)(((j + XOMBE_FFT) * k) % XOMBE_FFT) / XOMBE_FFT;
double v = (double)centre[j] * w[half + j];
xr += v * cos(a);
xi += v * sin(a);
}
rr[k] = xr;
ri[k] = xi;
if (hypot(xr, xi) > peak)
peak = hypot(xr, xi);
}
xombe__kern_spectrum(centre, w, n, &S);
xombe__kern_bin_power(&S, (float)sum_w2, P);
if (peak == 0.0) {
for (k = 0; k < XOMBE_SPEC_BINS; k++)
if (P[k] != 0.0f)
fail(what, "power of a zero frame at bin", k);
return;
}
for (k = 0; k < XOMBE_SPEC_BINS; k++) {
double d = sqrt(P[k] / scale) - hypot(rr[k], ri[k]);
sig += rr[k] * rr[k] + ri[k] * ri[k];
err += d * d;
if (fabs(d) / peak > amp)
amp = fabs(d) / peak;
}
snr = err > 0.0 ? 10.0 * log10(sig / err) : 999.0;
if (amp > worst_amp)
worst_amp = amp;
sum_snr += snr;
nsnr++;
if (snr < worst_snr)
worst_snr = snr;
if (amp > AMP_TOL)
fail(what, "bin amplitude error, of the peak", amp);
if (snr < SNR_MIN)
fail(what, "SNR dB", snr);
#if XOMBE_KERNELS_Q15
check_q15(what, &S, rr, ri);
#endif
}
int main(int argc, char **argv)
{
static float buf[2 * HMAX + 1], wl[XOMBE_MAX_WINDOW];
static int16_t pcm[100000];
float *centre = buf + HMAX;
const float *ws[2];
int ns[2] = {XOMBE_BASE_WINDOW, XOMBE_MAX_WINDOW}, i, j, k, frames = 0, len = 0;
double s2[2] = {0.0, 0.0};
uint32_t seed = 1;
char path[1024], what[64];
FILE *f;
for (j = 0; j < XOMBE_MAX_WINDOW; j++)
wl[j] = (float)(0.54 - 0.46 * cos(2.0 * PI * j / (XOMBE_MAX_WINDOW - 1)));
ws[0] = xombe__base_win;
ws[1] = wl;
for (i = 0; i < 2; i++)
for (j = 0; j < ns[i]; j++)
s2[i] += (double)ws[i][j] * ws[i][j];
snprintf(path, sizeof path, "%s/e3/es1_orig.raw", argc > 1 ? argv[1] : "vectors");
f = fopen(path, "rb");
if (f) {
len = (int)fread(pcm, sizeof(pcm[0]), sizeof(pcm) / sizeof(pcm[0]), f);
fclose(f);
} else {
fail(path, "can't read", 0);
}
/* speech every 37 ms through es1 (16-bit little-endian), both windows */
for (k = HMAX; k + HMAX < len; k += 296) {
for (i = 0; i < 2; i++) {
int h = (ns[i] - 1) / 2;
for (j = -h; j <= h; j++) {
const uint8_t *b = (const uint8_t *)&pcm[k + j];
centre[j] = (float)(int16_t)(b[0] | b[1] << 8);
}
snprintf(what, sizeof what, "es1 at %d, window %d", k, ns[i]);
check_frame(what, centre, ws[i], ns[i], s2[i]);
frames++;
}
}
/* harmonics with a falling envelope and noise 70 dB down, loud and quiet, an impulse, and silence */
for (i = 0; i < 3; i++) {
double f0 = 0.0125 + 0.02 * i;
int l;
for (j = -HMAX; j <= HMAX; j++) {
double v = 3e-4 * urand(&seed);
for (l = 1; l * f0 < 0.5; l++)
v += cos(2.0 * PI * l * f0 * j + l) / l;
centre[j] = (float)(v * (i == 2 ? 1e-6 : 3000.0));
}
snprintf(what, sizeof what, "harmonics f0 %.4f", f0);
check_frame(what, centre, wl, XOMBE_MAX_WINDOW, s2[1]);
frames++;
}
memset(buf, 0, sizeof buf);
centre[0] = 1000.0f;
check_frame("impulse", centre, wl, XOMBE_MAX_WINDOW, s2[1]);
centre[0] = 0.0f;
check_frame("silence", centre, wl, XOMBE_MAX_WINDOW, s2[1]);
frames += 2;
printf("kern_spec: %d frames, SNR mean %.2f dB least %.1f dB, worst bin amplitude error %.2g of peak", frames,
sum_snr / nsnr, worst_snr, worst_amp);
#if XOMBE_KERNELS_Q15
printf(", prepared bins %.2g of the range peak", worst_lf);
#endif
printf(", %d failures\n", fails);
return fails != 0;
}
+168
View File
@@ -0,0 +1,168 @@
/* tone detector kernels against float, argv[1] the vectors directory: q15 bin powers against a double DFT, gate
shares, sincos_turn, and the tone twiddles */
#include "../src/enc/tone_detect.c" /* its spectrum and trig are static */
#include <stdio.h>
#include <stdlib.h>
#if XOMBE_KERNELS_Q15
static int failures, checks;
static void check(int ok, const char *what)
{
checks++;
if (!ok) {
failures++;
printf("FAIL: %s\n", what);
}
}
#define PEAK_TOL 2.5e-3 /* largest bin power error, relative to the peak bin (amplitude error near -64 dB) */
#define SHARE_TOL 3e-4 /* gate share error, against DUAL_GATE_SHARE 0.7 */
static struct xombe_enc enc;
static double worst_bin, worst_share;
/* bin powers of x under win, double DFT */
static void ref_power(const float *x, int len, const float *win, double *pw)
{
int k, n;
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++) {
double re = 0.0, im = 0.0;
for (n = 0; n < len; n++) {
double v = (double)x[n] * win[n], a = 2.0 * XOMBE_PI * k * n / XOMBE_TONE_FFT;
re += v * cos(a);
im -= v * sin(a);
}
pw[k] = re * re + im * im;
}
}
/* q15 powers of one segment against ref_power, scaled by their ratio of sums, and the gate share of each
AMBE+2 dual against the reference share */
static void one_segment(const int16_t *seg, int len, const float *win, const char *what)
{
xombe_tone_seg sg;
double ref[XOMBE_TONE_FFT / 2 + 1], peak = 0.0, num = 0.0, den = 0.0, sc, err = 0.0, rtot = 0.0, serr = 0.0;
double qtot;
int k, id;
char msg[160];
sg.energy = prepare(&enc, seg, len, win, sg.x, sg.pw);
if (sg.energy == 0.0f)
return;
ref_power(sg.x, len, win, ref);
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++) {
peak = ref[k] > peak ? ref[k] : peak;
num += (double)sg.pw[k];
den += ref[k];
}
sc = num / den;
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++) {
double d = fabs((double)sg.pw[k] - sc * ref[k]) / (sc * peak);
err = d > err ? d : err;
}
worst_bin = err > worst_bin ? err : worst_bin;
snprintf(msg, sizeof(msg), "%s, %d samples: bin power error %.2e of peak", what, len, err);
check(err <= PEAK_TOL, msg);
for (k = (int)ceilf(GATE_LO_HZ / BIN_HZ); k <= (int)floorf(GATE_HI_HZ / BIN_HZ); k++)
rtot += ref[k];
qtot = (double)band_total(sg.pw);
for (id = XOMBE_TONE_DUAL_FIRST; id < XOMBE_TONE_DUAL_FIRST + XOMBE_TONE_DUALS; id++) {
float nominal[2];
int r0lo, r0hi, r1lo, r1hi;
double near = 0.0, qnear = 0.0;
xombe__tone_freqs(id, &nominal[0], &nominal[1]);
gate_run(nominal[0], &r0lo, &r0hi);
gate_run(nominal[1], &r1lo, &r1hi);
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++)
if ((k >= r0lo && k <= r0hi) || (k >= r1lo && k <= r1hi)) {
near += ref[k];
qnear += (double)sg.pw[k];
}
if (rtot > 0.0 && qtot > 0.0) {
double d = fabs(qnear / qtot - near / rtot);
serr = d > serr ? d : serr;
}
}
worst_share = serr > worst_share ? serr : worst_share;
snprintf(msg, sizeof(msg), "%s, %d samples: gate share error %.2e", what, len, serr);
check(serr <= SHARE_TOL, msg);
}
static void spectra(const char *vec)
{
static int16_t seg[XOMBE_TONE_SEG];
static const double hz[] = {300.0, 697.0, 1209.0, 1633.0, 2000.0, 3000.0, 3800.0};
static const double dbfs[] = {-3.0, -20.0, -45.0};
char path[4096], what[64];
unsigned lcg = 1u;
int i, j, n, segs = 0;
FILE *f;
for (i = 0; i < (int)(sizeof(hz) / sizeof(hz[0])); i++)
for (j = 0; j < 3; j++) {
double a = 32768.0 * pow(10.0, dbfs[j] / 20.0) / 1.5;
for (n = 0; n < XOMBE_TONE_SEG; n++) {
lcg = lcg * 1664525u + 1013904223u;
seg[n] = (int16_t)floor(a * cos(2.0 * XOMBE_PI * hz[i] * n / XOMBE_FS + 0.3) +
0.5 * a * cos(2.0 * XOMBE_PI * 1.37 * hz[i] * n / XOMBE_FS) +
(double)(lcg >> 28) - 7.5 + 0.5);
}
snprintf(what, sizeof(what), "%.0f Hz %.0f dBFS", hz[i], dbfs[j]);
one_segment(seg, XOMBE_TONE_SEG, xombe__tone_win, what);
one_segment(seg, 160, xombe__tone_win + 40, what); /* shorter segment, any window */
}
snprintf(path, sizeof(path), "%s/e3/es1_orig.raw", vec);
f = fopen(path, "rb");
if (!f) {
perror(path);
exit(2);
}
while (segs < 120 && fread(seg, sizeof(int16_t), XOMBE_TONE_SEG, f) == XOMBE_TONE_SEG) {
snprintf(what, sizeof(what), "es1 segment %d", segs++);
one_segment(seg, XOMBE_TONE_SEG, xombe__tone_win, what);
}
fclose(f);
printf("kern_tone: worst bin power error %.2e of peak, gate share error %.2e\n", worst_bin, worst_share);
}
static void trig(void)
{
double worst = 0.0;
int i;
for (i = -400000; i <= 400000; i++) {
float t = (float)i * 3.0e-4f, s, c; /* to 120 turns, as far as (2*len - 1)*w/2 reaches */
double ds = sin(2.0 * XOMBE_PI * (double)t), dc = cos(2.0 * XOMBE_PI * (double)t), e;
sincos_turn(t, &s, &c);
e = fmax(fabs(s - ds), fabs(c - dc));
worst = e > worst ? e : worst;
}
printf("kern_tone: sincos_turn worst error %.2e\n", worst);
check(worst < 3e-7, "sincos_turn within 3e-7");
}
static void twiddles(void)
{
int j, ok = 1;
for (j = 0; j < XOMBE_TONE_FFT / 4; j++)
ok &= xombe__tone_tw_q15[j] == xombe__fft_tw_q15[2 * j];
check(ok, "xombe__tone_tw_q15 is every second xombe__fft_tw_q15");
}
#endif
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: test_kern_tone VEC\n");
return 2;
}
#if XOMBE_KERNELS_Q15
twiddles();
trig();
spectra(argv[1]);
printf("kern_tone: %d/%d checks passed\n", checks - failures, checks);
return failures != 0;
#else
(void)argv;
printf("kern_tone: float build, no checks\n");
return 0;
#endif
}
+627
View File
@@ -0,0 +1,627 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "../src/tables/tables.h"
#define FS 8000
static long e1_frames, e1_bad, mirror_frames, mirror_bad, e7_fail;
static const xombe_enc_tone *forced; /* per input frame, id 0: none, NULL: no requests */
static long forced_frames;
static double mirror_max_err;
static uint32_t rng = 20261019u;
static uint32_t rnd(void)
{
rng = rng * 1664525u + 1013904223u;
return rng >> 8;
}
static double urand(void)
{
return (rnd() & 0xFFFFFF) / 16777216.0;
}
static int16_t *load_raw(const char *dir, const char *name, long *n)
{
char path[4096];
FILE *f;
long size;
int16_t *x;
snprintf(path, sizeof(path), "%s/%s", dir, name);
f = fopen(path, "rb");
if (!f) {
perror(path);
exit(2);
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
x = malloc((size_t)size + 2);
*n = (long)fread(x, sizeof(int16_t), (size_t)size / 2, f);
fclose(f);
return x;
}
static int e1_frame_ok(const uint8_t d[49])
{
int c = xombe__get_bits(d, 0, 6), b[9], i;
if (c == 60 || c == 61)
return 0;
if (c == 63) {
int id = xombe__get_bits(d, 12, 8);
for (i = 1; i < 4; i++)
if (xombe__get_bits(d, 12 + 8 * i, 8) != id)
return 0;
return xombe__tone_id_accepted(id) && !d[45] && !d[46] && !d[47] && !d[48];
}
xombe__get_fields(d, b);
if (c == 62)
return b[0] == XOMBE_SILENCE_B0 && b[1] == XOMBE_SILENCE_B1;
return b[0] <= 119 && (b[1] < 18 || b[1] > 31);
}
static int same_pred(const xombe_pred *a, const xombe_pred *b)
{
int l;
if (a->cls != b->cls || a->L != b->L || a->f0 != b->f0 || a->gamma != b->gamma || memcmp(a->v2, b->v2, 8))
return 0;
for (l = 0; l <= XOMBE_LMAX; l++)
if (a->a[l] != b->a[l])
return 0;
return 1;
}
/* E2(a): decoder's dequantized f0, L, and amplitudes equal the encoder's reconstruction, the dequantization of
the emitted fields from the encoder's predictor before the frame. the encoder keeps that reconstruction as its
predictor after a voice frame, so the two predictors must also agree */
static int mirror_ok(const xombe_pred *before, const xombe_enc *enc, const xombe_dec *dec, const uint8_t d[49],
int cls)
{
const xombe_set *p2 = &dec->c.p2;
xombe_params rec;
int b[9], l;
if (enc->pi.cls != cls || !same_pred(&enc->pi, &dec->c.pi))
return 0;
if (cls == XOMBE_CLASS_TONE)
return 1;
xombe__get_fields(d, b);
xombe__dequant(b, before, cls == XOMBE_CLASS_SILENCE, &rec);
if (p2->L != rec.L || p2->f0 != rec.f0)
return 0;
for (l = 1; l <= p2->L; l++) {
double err = fabs((double)p2->a[l] - rec.a[l]);
if (err > mirror_max_err)
mirror_max_err = err;
if (err > 1e-6)
return 0;
}
return 1;
}
typedef struct {
long frames;
int16_t *pcm;
int *cls;
int *b0;
int *voiced_bands;
int state_finite; /* encoder and decoder state free of NaN and infinity after the run */
} encode_result;
static int all_finite(const float *v, int n)
{
int i;
for (i = 0; i < n; i++)
if (!isfinite(v[i]))
return 0;
return 1;
}
static int pred_finite(const xombe_pred *p)
{
return isfinite(p->f0) && isfinite(p->gamma) && all_finite(p->a, XOMBE_LMAX + 1);
}
static int state_finite(const xombe_enc *e, const xombe_dec *d)
{
return pred_finite(&e->pi) && pred_finite(&d->c.pi) && isfinite(d->c.lambda) && isfinite(d->c.avg_f0) &&
isfinite(d->hpf.y1) && isfinite(d->hpf.y2) && isfinite(e->hpf.y1) && isfinite(e->hpf.y2) &&
isfinite(d->pitch_phase) && isfinite(d->epoch) && all_finite(d->tail, XOMBE_TAIL) &&
all_finite(d->uv_overlap, XOMBE_TAIL) && isfinite(e->ns_floor) &&
all_finite(e->ns_noise, XOMBE_NS_BINS) && all_finite(e->cn_power, XOMBE_SPEC_BINS) &&
all_finite(e->vad_nl, 8) && isfinite(e->p_prev);
}
static void e7_check(int ok, const char *what)
{
if (!ok) {
e7_fail++;
printf("E7 FAIL: %s\n", what);
}
}
static void run_case(const char *name, const int16_t *x, long n, const xombe_enc_cfg *cfg, encode_result *res)
{
static xombe_enc enc;
static xombe_dec dec;
long frames = n / 160, f, out = 0, bad = 0;
xombe_enc_init(&enc, cfg);
xombe_dec_set_noise(xombe_dec_init(&dec, XOMBE_DMR), XOMBE_NOISE_CONFORMANCE, 0);
if (res) {
res->frames = frames;
res->pcm = malloc(sizeof(int16_t) * 160 * (size_t)(frames + 1));
res->cls = malloc(sizeof(int) * (size_t)(frames + 1));
res->b0 = malloc(sizeof(int) * (size_t)(frames + 1));
res->voiced_bands = malloc(sizeof(int) * (size_t)(frames + 1));
}
for (f = 0; out < frames; f++) {
uint8_t bits[7], d[49];
int16_t pcm[160];
xombe_pred before = enc.pi;
const xombe_enc_tone *t = forced && f < frames && forced[f].id ? &forced[f] : NULL;
int got = xombe_enc_frame_bits(&enc, f < frames ? x + 160 * f : NULL, t, bits, NULL);
forced_frames += t != NULL;
int cls, b[9];
if (!got)
continue;
xombe__unpack49(bits, d);
e1_frames++;
if (!e1_frame_ok(d)) {
bad++;
e1_bad++;
}
xombe_dec_frame_bits(&dec, bits, 0, pcm);
cls = xombe__frame_class(d);
mirror_bad += !mirror_ok(&before, &enc, &dec, d, cls);
mirror_frames++;
if (res) {
xombe__get_fields(d, b);
memcpy(res->pcm + 160 * out, pcm, sizeof(pcm));
res->cls[out] = cls;
res->b0[out] = b[0];
res->voiced_bands[out] = cls == XOMBE_CLASS_VOICE ? xombe__count_voiced(xombe__vuv[b[1]]) : 0;
}
out++;
}
if (bad)
printf(" %s: %ld E1 violations\n", name, bad);
if (res)
res->state_finite = state_finite(&enc, &dec);
}
static void free_result(encode_result *r)
{
free(r->pcm);
free(r->cls);
free(r->b0);
free(r->voiced_bands);
}
static void test_files(const char *vec)
{
static const char *const files[] = {
"e3/es1_orig.raw", "e3/es2_orig.raw", "e3/es3_orig.raw", "e3/sn10_orig.raw", "e3/ttsf_orig.raw",
"e3/ttsc_orig.raw", "e3/ttsl_orig.raw", "e5/low5.raw", "e5/hp5.raw", "e5/es1_lead0.5s.raw",
"e7/glide.raw", "e7/mix.raw", "e7/saw150.raw", "e7/tones.raw"};
xombe_enc_cfg cfg[4];
unsigned i, v;
for (v = 0; v < 4; v++)
xombe_enc_cfg_default(&cfg[v]);
cfg[1].dmr_dtx = 0;
cfg[2].ns = 0;
cfg[2].tones = 0;
cfg[3].voicing_scale_permille = 600;
for (i = 0; i < sizeof(files) / sizeof(files[0]); i++) {
long n;
int16_t *x = load_raw(vec, files[i], &n);
for (v = 0; v < 4; v++)
if (v == 0 || i % 3 == v - 1)
run_case(files[i], x, n, &cfg[v], NULL);
free(x);
}
}
static uint32_t lcg(uint32_t *s)
{
*s = *s * 1664525u + 1013904223u;
return *s >> 8;
}
/* E2 across forced tones: bursts of one to three tone frames at random IDs and levels in speech and noise */
static void test_forced(const char *vec)
{
static const char *const files[] = {"e3/es1_orig.raw", "e3/sn10_orig.raw", "e3/ttsl_orig.raw", "e5/low5.raw"};
xombe_enc_cfg cfg;
uint32_t r = 7u;
unsigned i;
for (i = 0; i < sizeof(files) / sizeof(files[0]); i++) {
long n, f, frames;
int16_t *x = load_raw(vec, files[i], &n);
xombe_enc_tone *req;
frames = n / 160;
req = calloc((size_t)frames + 1, sizeof(*req));
for (f = 20; f < frames; f += 5 + (long)(lcg(&r) % 30)) {
int k, len = 1 + (int)(lcg(&r) % 3), id = 5 + (int)(lcg(&r) % 154);
if (id > 122)
id += 5;
for (k = 0; k < len && f + k < frames; k++) {
req[f + k].id = id;
req[f + k].ad = (int)(lcg(&r) % 128);
}
}
forced = req;
xombe_enc_cfg_default(&cfg);
cfg.tones = (int)(i & 1);
cfg.dmr_dtx = i != 2;
run_case(files[i], x, n, &cfg, NULL);
forced = NULL;
free(req);
free(x);
}
}
static void random_frame(int b[9], int silence)
{
b[0] = silence ? XOMBE_SILENCE_B0 : (int)(rnd() % 120);
b[1] = silence ? XOMBE_SILENCE_B1 : (int)(rnd() % 18);
b[2] = (int)(rnd() % 32);
b[3] = (int)(rnd() % 512);
b[4] = (int)(rnd() % 128);
b[5] = (int)(rnd() % 32);
b[6] = (int)(rnd() % 16);
b[7] = (int)(rnd() % 16);
b[8] = (int)(rnd() % 8);
}
static int same_recon(const xombe_params *a, const xombe_params *b)
{
int l;
if (a->L != b->L || fabsf(a->gamma - b->gamma) > 1e-6f)
return 0;
for (l = 1; l <= a->L; l++)
if (fabsf(a->a[l] - b->a[l]) > 1e-5f)
return 0;
return 1;
}
static int clamp_hit(const xombe_params *p)
{
int l;
if (p->gamma >= XOMBE_GAIN_MAX)
return 1;
for (l = 1; l <= p->L; l++)
if (p->a[l] <= XOMBE_AMP_MIN || p->a[l] >= XOMBE_AMP_MAX)
return 1;
return 0;
}
static long idem_frames, idem_exact, idem_equivalent, idem_clamped, idem_bad;
static void test_idempotence(int count)
{
xombe_pred pi;
int i;
xombe__pred_init(&pi);
for (i = 0; i < count; i++) {
int b[9], q[9], silence = (rnd() % 5) == 0, k, same = 1;
xombe_params p, back;
uint8_t v2[8];
random_frame(b, silence);
xombe__dequant(b, &pi, silence, &p);
memcpy(q, b, sizeof(q));
xombe__quantize(&pi, silence, p.L, p.a, q);
for (k = 2; k < 9; k++)
same &= q[k] == b[k];
idem_frames++;
if (same) {
idem_exact++;
} else {
xombe__dequant(q, &pi, silence, &back);
if (same_recon(&p, &back))
idem_equivalent++;
else if (clamp_hit(&p))
idem_clamped++;
else {
idem_bad++;
if (idem_bad <= 10)
printf(" idempotence: frame %d b=%d,%d,%d,%d,%d,%d,%d got %d,%d,%d,%d,%d,%d,%d\n", i, b[2], b[3],
b[4], b[5], b[6], b[7], b[8], q[2], q[3], q[4], q[5], q[6], q[7], q[8]);
}
}
if (silence) {
xombe__pred_store_other(&pi, XOMBE_CLASS_SILENCE);
} else {
xombe__v2_from_b1(b[1], v2);
xombe__pred_store_voice(&pi, &p, v2);
}
}
}
static double level_dbfs(const int16_t *x, long n)
{
double s = 0.0;
long i;
for (i = 0; i < n; i++)
s += (double)x[i] * x[i];
return s > 0.0 ? 10.0 * log10(s / n / (32768.0 * 32768.0)) : -200.0;
}
static int16_t clip16(double v)
{
return (int16_t)(v > 32767.0 ? 32767 : v < -32768.0 ? -32768 : floor(v + 0.5));
}
static void am_sweep(int16_t *x, long n, long lead, double f_start, double f_end, double *f_at)
{
double phase = 0.0;
long i;
for (i = 0; i < n; i++) {
double t = (double)(i - lead) / FS, dur = (double)(n - lead) / FS, f, v = 0.0, env;
int k;
if (i < lead) {
x[i] = 0;
if (f_at)
f_at[i] = 0.0;
continue;
}
f = f_start * pow(f_end / f_start, t / dur);
if (f_at)
f_at[i] = f;
phase += 2.0 * XOMBE_PI * f / FS;
for (k = 1; k * f < 3900.0; k++)
v += cos(k * phase);
env = 1.0 + 0.5 * sin(2.0 * XOMBE_PI * 3.5 * t);
x[i] = clip16(600.0 * env * v / sqrt((double)(3900.0 / f)));
}
}
static void sweep_report(const char *name, double f_start, double f_end, int16_t *x, long n)
{
double *f_at = malloc(sizeof(double) * (size_t)n);
encode_result r;
xombe_enc_cfg cfg;
long f, in_range = 0, good = 0, octave_low = 0;
am_sweep(x, n, FS / 2, f_start, f_end, f_at);
xombe_enc_cfg_default(&cfg);
run_case(name, x, n, &cfg, &r);
for (f = 0; f < r.frames; f++) {
double truth = f_at[160 * f + 120 < n ? 160 * f + 120 : n - 1], coded;
if (truth < 66.0 || truth > 398.0 || r.cls[f] != XOMBE_CLASS_VOICE)
continue;
in_range++;
coded = xombe__w0[r.b0[f]] * FS;
if (fabs(coded - truth) <= 0.05 * truth)
good++;
else if (fabs(coded - truth / 2.0) <= 0.05 * truth / 2.0)
octave_low++;
}
printf("E7 %s (informative): coded pitch within 5%% on %ld of %ld voice frames in 66..398 Hz (%ld an octave "
"low)\n", name, good, in_range, octave_low);
free_result(&r);
free(f_at);
}
/* decoded over input power in dB on the pause frames of x from frame from on, frames whose clean source and two
neighbours on each side are below 20 dB (16-bit units), which also absorbs the decoder's delay
pcm[i] is aligned with x[i] */
static double pause_suppression(const int16_t *x, const int16_t *clean, const int16_t *pcm, long n, long from)
{
long nfr = n / 160, i, j, k;
double pin = 0.0, pout = 0.0;
for (i = from; i < nfr - 2; i++) {
int quiet = 1;
for (j = i - 2; j <= i + 2 && quiet; j++) {
double e = 0.0;
for (k = 0; k < 160; k++)
e += (double)clean[160 * j + k] * clean[160 * j + k];
quiet = 10.0 * log10(e / 160.0 + 1e-3) < 20.0;
}
if (!quiet)
continue;
for (k = 160 * i; k < 160 * (i + 1); k++) {
pin += (double)x[k] * x[k];
pout += (double)pcm[k] * pcm[k];
}
}
return 10.0 * log10((pout + 1e-9) / (pin + 1e-9));
}
/* VAD recovery (inputs as E5's vad_* from tools/e5.py --vad-gen)
three triggers push the noise levels under the background of sn10 (es1 + white noise, 10 dB SNR, 0.5 s
noise lead-in): 120 zero samples prepended, digital-silence gaps in two pauses (0 from 0.16 s, constant +1
from 3.68 s, 8 frames each), and the noise raised 8 dB from 2.0 s
from 7.5 s on, pause frames must be suppressed at most 3 dB less than in the unmodified clip, i.e. the noise
levels have recovered (with the digital-silence guard, vad_gap never locks) */
static void test_vad_recovery(const char *vec, const char *inputs)
{
long n, nc, i, m;
int16_t *sn = load_raw(inputs, "sn10.d0.raw", &n), *clean = load_raw(vec, "e5/es1_lead0.5s.raw", &nc);
int16_t *x = malloc(sizeof(int16_t) * (size_t)(n + 120)), *cl = calloc((size_t)(n + 120), sizeof(int16_t));
const char *names[4] = {"sn10", "vad_on", "vad_gap", "vad_step"};
const long from = 375;
double ref = 0.0, g = pow(10.0, 8.0 / 20.0);
int t;
encode_result r;
xombe_enc_cfg cfg;
xombe_enc_cfg_default(&cfg);
if (nc < n)
n = nc;
for (t = 0; t < 4; t++) {
const int16_t *in = x;
long off = t == 1 ? 120 : 0;
double sup;
memset(x, 0, sizeof(int16_t) * (size_t)(n + 120));
for (i = 0; i < n; i++) {
cl[off + i] = clean[i];
x[off + i] = t == 3 && i >= 2 * FS ? clip16(clean[i] + g * (sn[i] - clean[i])) : sn[i];
}
if (t == 2) {
for (i = 8 * 160; i < 16 * 160; i++)
x[i] = 0;
for (i = 184 * 160; i < 192 * 160; i++)
x[i] = 1;
}
run_case(names[t], in, n + off, &cfg, &r);
m = 160 * r.frames - off;
sup = pause_suppression(x + off, cl + off, r.pcm + off, m < n ? m : n, from);
if (t == 0) {
ref = sup;
printf("E7 VAD recovery: sn10 pause frames from 7.5 s decoded at %+.1f dB\n", sup);
} else {
printf("E7 VAD recovery: %s %+.1f dB (%+.1f vs sn10, limit +3)\n", names[t], sup, sup - ref);
e7_check(sup - ref <= 3.0, "noise level not recovered after a VAD trigger");
}
free_result(&r);
}
free(sn);
free(clean);
free(x);
free(cl);
}
/* E7 robustness, mandatory:
digital silence decodes to -85 dBFS or less
clipped full-scale speech, sweeps, and stationary inputs keep E1/E2 (checked on every frame by run_case)
a stationary tone is absorbed (tone frames, or comfort noise after about 3 s without the tone detector)
ten minutes of mixed abuse leave the state finite and the codec quiet again on digital silence
informative: the sweeps' pitch accuracy */
static void test_e7(const char *vec, const char *inputs, double stress_seconds)
{
const long lead = FS / 2, lead_frames = lead / 160;
long n = 10 * FS, i, es1_n;
int16_t *x = calloc((size_t)(30 * FS), sizeof(int16_t)), *es1 = load_raw(vec, "e3/es1_orig.raw", &es1_n);
encode_result r;
xombe_enc_cfg cfg;
double lvl;
long tone_frames = 0, other_frames = 0, absorbed_at = -1;
xombe_enc_cfg_default(&cfg);
run_case("digital silence", x, n, &cfg, &r);
lvl = level_dbfs(r.pcm, 160 * r.frames);
printf("E7 digital silence: decoded %.1f dBFS (limit -85)\n", lvl);
e7_check(lvl <= -85.0, "digital silence above -85 dBFS");
free_result(&r);
for (i = 0; i < es1_n; i++)
x[i] = clip16(16.0 * es1[i]);
run_case("clipped full-scale speech", x, es1_n, &cfg, &r);
printf("E7 clipped full-scale speech: decoded %.1f dBFS, %ld frames\n", level_dbfs(r.pcm, 160 * r.frames),
r.frames);
free_result(&r);
sweep_report("rising AM comb sweep 50->500 Hz", 50.0, 500.0, x, 20 * FS);
sweep_report("falling AM comb sweep 500->50 Hz", 500.0, 50.0, x, 20 * FS);
/* tone detector on: every frame from two frames after the onset is a tone frame */
memset(x, 0, sizeof(int16_t) * 30 * FS);
for (i = lead; i < 8 * FS; i++)
x[i] = clip16(8000.0 * sin(2.0 * XOMBE_PI * 1000.0 * i / FS));
run_case("stationary 1 kHz tone", x, 8 * FS, &cfg, &r);
for (i = lead_frames + 2; i < r.frames; i++) {
tone_frames += r.cls[i] == XOMBE_CLASS_TONE;
other_frames += r.cls[i] != XOMBE_CLASS_TONE;
}
printf("E7 stationary 1 kHz tone (7.5 s): %ld tone frames, %ld others after onset + 2 frames\n", tone_frames,
other_frames);
e7_check(other_frames == 0, "stationary tone not coded as tone frames throughout");
free_result(&r);
/* tone detector off: the steady comb becomes background (comfort noise) about 3 s after its onset, at the
latest 4 s after it, and stays background */
cfg.tones = 0;
am_sweep(x, 8 * FS, lead, 150.0, 150.0, NULL);
for (i = lead; i < 8 * FS; i++)
x[i] = clip16(x[i] / (1.0 + 0.5 * sin(2.0 * XOMBE_PI * 3.5 * (double)(i - lead) / FS)));
run_case("stationary 150 Hz comb", x, 8 * FS, &cfg, &r);
for (i = r.frames - 1; i >= lead_frames && r.cls[i] == XOMBE_CLASS_SILENCE; i--)
absorbed_at = i;
printf("E7 stationary 150 Hz comb, tone detector off: background from %.2f s after onset\n",
absorbed_at < 0 ? -1.0 : (absorbed_at - lead_frames) * 0.02);
e7_check(absorbed_at >= 0 && absorbed_at - lead_frames <= 4 * 50, "steady comb not absorbed within 4 s");
free_result(&r);
free(x);
test_vad_recovery(vec, inputs);
if (stress_seconds > 0.0) {
long total = (long)(stress_seconds * FS), pos = 0, bad_samples = 0, quiet_start = -1, quiet_len = 0;
int16_t *s = malloc(sizeof(int16_t) * (size_t)total);
int seg = 0;
xombe_enc_cfg_default(&cfg);
while (pos < total) {
long len = (long)(2 + rnd() % 9) * FS, k;
int kind = seg++ % 6;
if (pos + len > total)
len = total - pos;
for (k = 0; k < len; k++) {
double v;
switch (kind) {
case 0: v = es1[k % es1_n]; break;
case 1: v = 3000.0 * (urand() - 0.5); break;
case 2: v = 16.0 * es1[k % es1_n]; break;
case 3: v = 9000.0 * sin(2.0 * XOMBE_PI * (300.0 + 2700.0 * k / len) * k / FS); break;
case 4: v = 0.0; break;
default: v = es1[k % es1_n] + 2000.0 * (urand() - 0.5); break;
}
s[pos + k] = clip16(v);
}
if (kind == 4 && len >= 2 * FS) {
quiet_start = pos;
quiet_len = len;
}
pos += len;
}
run_case("stress", s, total, &cfg, &r);
for (i = 0; i < 160 * r.frames; i++)
bad_samples += r.pcm[i] == 32767 || r.pcm[i] == -32768;
printf("E7 stress: %.0f s, %ld frames, %ld saturated output samples (informative), state %s\n",
stress_seconds, r.frames, bad_samples, r.state_finite ? "finite" : "NOT FINITE");
e7_check(r.state_finite, "encoder or decoder state not finite after the stress run");
if (quiet_start >= 0) {
/* last digital-silence stretch, from 1 s into it to its end */
long a = (quiet_start + FS) / 160, b = (quiet_start + quiet_len) / 160;
lvl = level_dbfs(r.pcm + 160 * a, 160 * (b - a));
printf("E7 stress: last digital silence (%.1f s) decodes to %.1f dBFS (limit -85)\n",
(b - a) * 0.02, lvl);
e7_check(lvl <= -85.0, "digital silence after the stress run above -85 dBFS");
}
free_result(&r);
free(s);
}
free(es1);
printf("E7: %s\n", e7_fail ? "FAIL" : "PASS");
}
int main(int argc, char **argv)
{
const char *vec = argc > 1 ? argv[1] : "vectors", *inputs = NULL;
int i, e7 = 0;
double stress = 0.0;
for (i = 2; i < argc; i++) {
if (!strcmp(argv[i], "--e7"))
e7 = 1;
else if (!strcmp(argv[i], "--stress") && i + 1 < argc)
stress = atof(argv[++i]);
else if (!strcmp(argv[i], "--inputs") && i + 1 < argc)
inputs = argv[++i];
}
if (e7 && !inputs) {
fprintf(stderr, "test_mirror: --e7 needs --inputs DIR, the dithered E3 inputs (scripts/gen_inputs.py)\n");
return 2;
}
test_files(vec);
test_forced(vec);
test_idempotence(5000);
if (e7)
test_e7(vec, inputs, stress);
printf("E1: %ld/%ld frames valid\n", e1_frames - e1_bad, e1_frames);
printf("E2 mirror: %ld/%ld frames equal (max |error| %.3g log2)\n", mirror_frames - mirror_bad, mirror_frames,
mirror_max_err);
printf("E2 forced tones: %ld requests among the frames above\n", forced_frames);
printf("E2 idempotence: %ld frames, %ld identical, %ld equivalent (unused HOC field), %ld clamped, %ld mismatches\n",
idem_frames, idem_exact, idem_equivalent, idem_clamped, idem_bad);
printf("E1/E2: %s\n", e1_bad || mirror_bad || idem_bad ? "FAIL" : "PASS");
return e1_bad || mirror_bad || idem_bad || e7_fail ? 1 : 0;
}
+221
View File
@@ -0,0 +1,221 @@
/* src/dsp/q15ops.h operations against 64-bit reference arithmetic on edge values and a pseudo-random sweep,
checks the C fallback on a host and the intrinsics on an Arm target with the DSP extension */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "../src/dsp/fft_q15.h"
static int fails;
static void check(const char *what, int64_t got, int64_t want, uint32_t a, uint32_t b)
{
if (got != want && fails++ < 10)
printf("%s(%08lx, %08lx): %lld, want %lld\n", what, (unsigned long)a, (unsigned long)b, (long long)got,
(long long)want);
}
static int64_t lo(uint32_t a)
{
return (int64_t)(a & 0xffffu) - (a & 0x8000u ? 65536 : 0);
}
static int64_t hi(uint32_t a)
{
return lo(a >> 16);
}
static int64_t wrap32(int64_t v)
{
v %= 4294967296LL;
if (v < 0)
v += 4294967296LL;
return v >= 2147483648LL ? v - 4294967296LL : v;
}
static int ref_clz64(uint64_t x)
{
int n = 64;
while (x) {
n--;
x >>= 1;
}
return n;
}
static int64_t sat16(int64_t v)
{
return v > 32767 ? 32767 : v < -32768 ? -32768 : v;
}
static int64_t floor_half(int64_t v)
{
return (int64_t)floor((double)v / 2.0);
}
static int64_t floor_div32(int64_t v)
{
return v >= 0 ? v / 4294967296LL : -((-v + 4294967295LL) / 4294967296LL);
}
static int64_t pair(int64_t l, int64_t h)
{
return (int64_t)(((uint32_t)l & 0xffffu) | ((uint32_t)h & 0xffffu) << 16);
}
static uint32_t ref_rbit(uint32_t x)
{
uint32_t r = 0;
int i;
for (i = 0; i < 32; i++)
r |= (x >> i & 1u) << (31 - i);
return r;
}
/* FFT against a double-precision DFT of its quantized input: SNR in dB of the 512-point transform of 1024 real
samples, packed as xombe__kern_spectrum packs them */
#define FM 512
#define PI 3.14159265358979323846
static double fft_snr(const double *in)
{
static uint32_t tw[FM / 2], x[FM];
static double zr[FM], zi[FM];
double peak = 0.0, g, sig = 0.0, err = 0.0;
int k, n, s;
for (k = 0; k < FM / 2; k++) {
double c = floor(cos(2.0 * PI * k / FM) * 32768.0 + 0.5);
double si = floor(-sin(2.0 * PI * k / FM) * 32768.0 + 0.5);
tw[k] = (uint32_t)pair(c > 32767 ? 32767 : (int64_t)c, si > 32767 ? 32767 : (int64_t)si);
}
for (n = 0; n < 2 * FM; n++)
if (fabs(in[n]) > peak)
peak = fabs(in[n]);
g = XOMBE_CFFT_Q15_PEAK / peak;
for (n = 0; n < FM; n++) {
zr[n] = floor(in[2 * n] * g + 0.5);
zi[n] = floor(in[2 * n + 1] * g + 0.5);
x[q15_rbit((uint32_t)n) >> 23] = (uint32_t)pair((int64_t)zr[n], (int64_t)zi[n]);
}
s = xombe__cfft_q15(x, FM, tw, XOMBE_CFFT_Q15_PEAK);
for (k = 0; k < FM; k++) {
double xr = 0.0, xi = 0.0, er, ei;
for (n = 0; n < FM; n++) {
double a = -2.0 * PI * (double)((k * n) % FM) / FM, c = cos(a), si = sin(a);
xr += zr[n] * c - zi[n] * si;
xi += zr[n] * si + zi[n] * c;
}
er = ldexp((double)lo(x[k]), s) - xr;
ei = ldexp((double)hi(x[k]), s) - xi;
sig += xr * xr + xi * xi;
err += er * er + ei * ei;
}
return 10.0 * log10(sig / err);
}
static double urand(uint32_t *s)
{
*s = *s * 1664525u + 1013904223u;
return (double)(*s >> 8) / 8388608.0 - 1.0;
}
/* noise, and voiced-like frames: harmonics of f0 with a falling envelope under the 199-point Hamming window,
centred on sample 0 as xombe__kern_spectrum centres it, with noise 60 dB down */
static void fft_tests(void)
{
static double in[2 * FM];
static const double f0s[] = {0.0125, 0.03, 0.06}; /* cycles/sample, 100, 240, 480 Hz */
uint32_t s = 7;
double snr, worst = 1e9;
int n, i, l;
for (n = 0; n < 2 * FM; n++)
in[n] = urand(&s);
snr = fft_snr(in);
printf("fft_q15 noise: %.1f dB\n", snr);
if (snr < 62.0)
fails++;
for (i = 0; i < 3; i++) {
memset(in, 0, sizeof in);
for (n = -99; n <= 99; n++) {
double v = 0.0, w = 0.54 + 0.46 * cos(PI * n / 99.0);
for (l = 1; l * f0s[i] < 0.5; l++)
v += cos(2.0 * PI * l * f0s[i] * n + l) / (double)l;
in[(n + 2 * FM) % (2 * FM)] = w * (v + 1e-3 * urand(&s));
}
snr = fft_snr(in);
if (snr < worst)
worst = snr;
printf("fft_q15 harmonic f0 %.4f: %.1f dB\n", f0s[i], snr);
}
if (worst < 57.0)
fails++;
}
static void one(uint32_t a, uint32_t b, uint32_t c, uint64_t d)
{
int64_t dot = lo(a) * lo(b) + hi(a) * hi(b);
int32_t acc = (int32_t)wrap32((int64_t)c);
int64_t acc64 = (int64_t)(d >> 1) - (int64_t)(d >> 2); /* keeps the sum within int64 */
uint32_t pk = (a & 0xffffu) | ((b << 2) & 0xffff0000u);
check("smuad", q15_smuad(a, b), wrap32(dot), a, b);
check("smlad", q15_smlad(a, b, acc), wrap32(acc + dot), a, b);
check("smlald", q15_smlald(a, b, acc64), acc64 + dot, a, b);
check("pack_lsl2", q15_pack_lsl2(a, b), pk, a, b);
check("smlsd", q15_smlsd(a, b, acc), wrap32(acc + lo(a) * lo(b) - hi(a) * hi(b)), a, b);
check("smladx", q15_smladx(a, b, acc), wrap32(acc + lo(a) * hi(b) + hi(a) * lo(b)), a, b);
check("qadd16", q15_qadd16(a, b), pair(sat16(lo(a) + lo(b)), sat16(hi(a) + hi(b))), a, b);
check("qsub16", q15_qsub16(a, b), pair(sat16(lo(a) - lo(b)), sat16(hi(a) - hi(b))), a, b);
check("shadd16", q15_shadd16(a, b), pair(floor_half(lo(a) + lo(b)), floor_half(hi(a) + hi(b))), a, b);
check("shsub16", q15_shsub16(a, b), pair(floor_half(lo(a) - lo(b)), floor_half(hi(a) - hi(b))), a, b);
check("qsax", q15_qsax(a, b), pair(sat16(lo(a) + hi(b)), sat16(hi(a) - lo(b))), a, b);
check("qasx", q15_qasx(a, b), pair(sat16(lo(a) - hi(b)), sat16(hi(a) + lo(b))), a, b);
check("shsax", q15_shsax(a, b), pair(floor_half(lo(a) + hi(b)), floor_half(hi(a) - lo(b))), a, b);
check("shasx", q15_shasx(a, b), pair(floor_half(lo(a) - hi(b)), floor_half(hi(a) + lo(b))), a, b);
check("pack_lsl1", q15_pack_lsl1(a, b), (a & 0xffffu) | ((b << 1) & 0xffff0000u), a, b);
check("rbit", q15_rbit(a), ref_rbit(a), a, 0);
check("smmulr", q15_smmulr((int32_t)a, (int32_t)b),
floor_div32((int64_t)(int32_t)a * (int32_t)b + 0x80000000LL), a, b);
check("umax16", q15_umax16(a, b),
((a >> 16) > (b >> 16) ? a >> 16 : b >> 16) << 16 | (((a & 0xffffu) > (b & 0xffffu) ? a : b) & 0xffffu),
a, b);
check("clz64", q15_clz64(d), ref_clz64(d), (uint32_t)(d >> 32), (uint32_t)d);
check("clz64", q15_clz64(d >> (a & 63)), ref_clz64(d >> (a & 63)), a, (uint32_t)d);
}
int main(void)
{
static const uint32_t edge[] = {0, 1, 0x7fff, 0x8000, 0xffff, 0x7fff7fff, 0x80008000, 0x80007fff,
0x7fff8000, 0xffffffff, 0x00010000, 0x12345678};
uint32_t s = 1;
int i, j;
for (i = 0; i < (int)(sizeof edge / sizeof edge[0]); i++)
for (j = 0; j < (int)(sizeof edge / sizeof edge[0]); j++) {
one(edge[i], edge[j], 0x7fffffff, 0);
one(edge[i], edge[j], 0x80000000u, ~0ull);
}
for (i = 0; i < 200000; i++) {
uint32_t a, b, c;
uint64_t d;
s = s * 1664525u + 1013904223u;
a = s;
s = s * 1664525u + 1013904223u;
b = s;
s = s * 1664525u + 1013904223u;
c = s;
s = s * 1664525u + 1013904223u;
d = (uint64_t)c << 32 | s;
one(a, b, c, d);
}
{
const int16_t v[3] = {-2, 3, 5};
uint32_t p = q15_ld2(v + 1);
check("ld2", lo(p) * 100 + hi(p), 305, p, 0);
}
fft_tests();
printf("q15ops (%s): %s\n",
#if defined(__ARM_FEATURE_DSP)
"DSP extension",
#else
"C fallback",
#endif
fails ? "FAIL" : "ok");
return fails != 0;
}
+296
View File
@@ -0,0 +1,296 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "xombe.h"
#include "../tools/io.h"
#define MAX_CALLS 20000
#define LEVEL_FLOOR_DB (-80.0)
enum { CAT_VOICE, CAT_SILENCE, CAT_TONE, CAT_REPEAT, CAT_MUTE, NCAT };
static const char *const cat_names[NCAT] = {"voice", "silence", "tone", "repeat", "mute"};
static const double lim_median[NCAT] = {0.5, 0.5, 0.25, 0.75, 0.25};
static const double lim_p90[NCAT] = {7.0, 4.0, 1.0, 7.0, 1.0};
static const double lim_share[NCAT] = {0.25, 0.12, 0.03, 0.25, 0.08};
typedef struct {
enum xombe_class cls;
enum xombe_conceal conceal;
int run;
long mute_src;
int tone_id, tone_ad;
} frame_info;
static double deltas[NCAT][MAX_CALLS];
static int ndeltas[NCAT];
static double snr_mute[MAX_CALLS], snr_cn[MAX_CALLS];
static int nsnr_mute, nsnr_cn;
static int steady_fail, steady_mute_n, steady_tone_n;
static double steady_mute_max, steady_tone_max;
static long frames_total, decision_fail;
static enum xombe_class parse_class(const char *p)
{
if (!strncmp(p, "\"voice\"", 7))
return XOMBE_CLASS_VOICE;
if (!strncmp(p, "\"erasure\"", 9))
return XOMBE_CLASS_ERASURE;
if (!strncmp(p, "\"silence\"", 9))
return XOMBE_CLASS_SILENCE;
return XOMBE_CLASS_TONE;
}
static enum xombe_conceal parse_conceal(const char *p)
{
if (!strncmp(p, "\"none\"", 6))
return XOMBE_CONCEAL_NONE;
if (!strncmp(p, "\"repeat\"", 8))
return XOMBE_CONCEAL_REPEAT;
return XOMBE_CONCEAL_MUTE;
}
static double level_db(const int16_t *x, int n)
{
double s = 0.0;
int i;
for (i = 0; i < n; i++)
s += (double)x[i] * x[i];
if (s <= 0.0)
return -1e9;
return 10.0 * log10(s / n) - 20.0 * log10(32768.0);
}
static int cmp_double(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return x < y ? -1 : x > y;
}
static double percentile(double *v, int n, double q)
{
double pos;
int i;
if (n == 0)
return 0.0;
qsort(v, (size_t)n, sizeof(double), cmp_double);
pos = q * (n - 1);
i = (int)floor(pos);
if (i >= n - 1)
return v[n - 1];
return v[i] + (pos - i) * (v[i + 1] - v[i]);
}
static int expect_field(const stream_reader *r, const char *e, const char *key, const char **out)
{
*out = e ? stream_key(e, key) : NULL;
if (*out)
return 1;
fprintf(stderr, "%s:%ld: missing \"expect\".\"%s\"\n", r->path, r->lineno, key);
return 0;
}
static int run_file(const char *path, int verbose)
{
stream_reader r;
stream_half h;
int have_prev = 0, ev, ok = 1;
long frame = -1;
frame_info cur, prev;
xombe_dec_mem mem;
xombe_dec *dec;
memset(&cur, 0, sizeof(cur));
memset(&prev, 0, sizeof(prev));
if (!stream_open(&r, path))
return 1;
dec = xombe_dec_init(&mem, XOMBE_DMR);
xombe_dec_set_noise(dec, XOMBE_NOISE_CONFORMANCE, 0);
while (ok && (ev = stream_next(&r, &h)) != STREAM_END) {
if (ev == STREAM_ERROR) {
ok = 0;
break;
}
if (ev == STREAM_SET) {
xombe_dec_set_errors(dec, r.eps_t, r.eps_1);
continue;
}
if (ev == STREAM_INIT) {
dec = xombe_dec_init(&mem, XOMBE_DMR);
xombe_dec_set_noise(dec, XOMBE_NOISE_CONFORMANCE, 0);
frame = -1;
have_prev = 0;
continue;
}
{
const uint8_t *d = h.d;
int16_t pcm[XOMBE_HALF_MAX], ref[XOMBE_HALF_MAX];
int i, n, nref = 0;
const char *q;
double ld, lr, dl, num = 0.0, den = 0.0;
int cat;
n = xombe_dec_half_bits(dec, h.bits, h.flags, h.second_half, h.nsamples, pcm);
if (n < 0) {
fprintf(stderr, "%s:%ld: half-frame call out of order\n", path, r.lineno);
ok = 0;
break;
}
if (!h.second_half) {
xombe_decision got;
const char *e = stream_key(h.line, "expect"), *cls, *conceal;
long run;
frame++;
frames_total++;
if (have_prev || frame > 0)
prev = cur;
have_prev = frame > 0;
memset(&cur, 0, sizeof(cur));
if (!expect_field(&r, e, "class", &cls) || !expect_field(&r, e, "conceal", &conceal) ||
!stream_int(&r, e, "run", &run)) {
ok = 0;
break;
}
cur.cls = parse_class(cls);
cur.conceal = parse_conceal(conceal);
cur.run = (int)run;
cur.mute_src = -2;
if ((q = stream_key(e, "mute_src")))
cur.mute_src = *q == '"' ? -1 : atol(q);
for (i = 0; i < 8; i++)
cur.tone_id = (cur.tone_id << 1) | d[12 + i];
for (i = 0; i < 6; i++)
cur.tone_ad = (cur.tone_ad << 1) | d[6 + i];
cur.tone_ad = (cur.tone_ad << 1) | d[44];
xombe_dec_decision_get(dec, &got);
if (got.cls != cur.cls || got.conceal != cur.conceal || got.run != cur.run ||
(cur.conceal == XOMBE_CONCEAL_MUTE && got.mute_src != cur.mute_src)) {
decision_fail++;
if (verbose && decision_fail <= 20)
fprintf(stderr, "%s frame %ld: expect %d/%d/%d/%ld got %d/%d/%d/%lld\n", path, frame,
cur.cls, cur.conceal, cur.run, cur.mute_src, got.cls, got.conceal, got.run,
(long long)got.mute_src);
}
}
q = stream_key(h.line, "pcm");
if (q && (q = strchr(q, '['))) {
q++;
while (nref < XOMBE_HALF_MAX && *q && *q != ']') {
char *endp;
ref[nref++] = (int16_t)strtol(q, &endp, 10);
if (endp == q)
break;
q = endp;
while (*q == ',' || *q == ' ')
q++;
}
}
if (nref != n) {
fprintf(stderr, "%s frame %ld: length %d, reference %d\n", path, frame, n, nref);
decision_fail++;
continue;
}
ld = level_db(pcm, n);
lr = level_db(ref, n);
dl = (ld > LEVEL_FLOOR_DB ? ld : LEVEL_FLOOR_DB) - (lr > LEVEL_FLOOR_DB ? lr : LEVEL_FLOOR_DB);
if (cur.conceal == XOMBE_CONCEAL_MUTE)
cat = CAT_MUTE;
else if (cur.conceal == XOMBE_CONCEAL_REPEAT)
cat = CAT_REPEAT;
else
cat = cur.cls == XOMBE_CLASS_SILENCE ? CAT_SILENCE : cur.cls == XOMBE_CLASS_TONE ? CAT_TONE
: CAT_VOICE;
deltas[cat][ndeltas[cat]++] = dl;
for (i = 0; i < n; i++) {
num += (double)ref[i] * ref[i];
den += ((double)ref[i] - pcm[i]) * ((double)ref[i] - pcm[i]);
}
if (have_prev) {
int steady_mute = cur.conceal == XOMBE_CONCEAL_MUTE && prev.conceal == XOMBE_CONCEAL_MUTE &&
prev.mute_src == cur.mute_src;
int steady_tone = cur.conceal == XOMBE_CONCEAL_NONE && cur.cls == XOMBE_CLASS_TONE &&
prev.conceal == XOMBE_CONCEAL_NONE && prev.cls == XOMBE_CLASS_TONE &&
prev.tone_id == cur.tone_id && prev.tone_ad == cur.tone_ad &&
((cur.tone_id >= 5 && cur.tone_id <= 122) ||
(cur.tone_id >= 128 && cur.tone_id <= 143));
int steady_cn = cur.conceal == XOMBE_CONCEAL_NONE && cur.cls == XOMBE_CLASS_SILENCE &&
(prev.conceal == XOMBE_CONCEAL_MUTE ||
(prev.conceal == XOMBE_CONCEAL_NONE && prev.cls == XOMBE_CLASS_SILENCE));
if (steady_mute) {
steady_mute_n++;
if (fabs(dl) > steady_mute_max)
steady_mute_max = fabs(dl);
if (fabs(dl) > 2.0)
steady_fail++;
if (lr >= LEVEL_FLOOR_DB && nsnr_mute < MAX_CALLS)
snr_mute[nsnr_mute++] = 10.0 * log10(num / (den > 0 ? den : 1e-9));
}
if (steady_tone) {
steady_tone_n++;
if (fabs(dl) > steady_tone_max)
steady_tone_max = fabs(dl);
if (fabs(dl) > 1.0)
steady_fail++;
}
if (steady_cn && nsnr_cn < MAX_CALLS && num > 0)
snr_cn[nsnr_cn++] = 10.0 * log10(num / (den > 0 ? den : 1e-9));
}
}
}
if (!stream_close(&r))
ok = 0;
return ok ? 0 : 1;
}
int main(int argc, char **argv)
{
int i, metrics = 0, fail = 0;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--metrics")) {
metrics = 1;
continue;
}
if (run_file(argv[i], 1))
return 2;
}
printf("T4(a) decisions: %ld/%ld frames match\n", frames_total - decision_fail, frames_total);
if (decision_fail)
fail = 1;
if (metrics) {
int c;
double m;
printf("T4(b) level, pooled |median| P90 |dL| share>3dB (limits)\n");
for (c = 0; c < NCAT; c++) {
double absd[MAX_CALLS], med, p90, share;
int k, over = 0, ok;
for (k = 0; k < ndeltas[c]; k++) {
absd[k] = fabs(deltas[c][k]);
over += absd[k] > 3.0;
}
med = fabs(percentile(deltas[c], ndeltas[c], 0.5));
p90 = percentile(absd, ndeltas[c], 0.9);
share = ndeltas[c] ? (double)over / ndeltas[c] : 0.0;
ok = med <= lim_median[c] && p90 <= lim_p90[c] && share <= lim_share[c];
printf(" %-8s n=%5d %6.3f %8.3f %8.1f%% (%.2f / %.1f / %.0f%%) %s\n", cat_names[c], ndeltas[c],
med, p90, 100.0 * share, lim_median[c], lim_p90[c], 100.0 * lim_share[c], ok ? "ok" : "FAIL");
if (!ok)
fail = 1;
}
printf("T4(c) steady state: mute calls %d (max |dL| %.2f dB, limit 2.0), tone calls %d (max %.2f dB, limit 1.0)"
", %d violations %s\n",
steady_mute_n, steady_mute_max, steady_tone_n, steady_tone_max, steady_fail,
steady_fail ? "FAIL" : "ok");
if (steady_fail)
fail = 1;
m = percentile(snr_mute, nsnr_mute, 0.5);
printf("T4(d) noise sync: steady mute median SNR %.1f dB over %d calls (>= 15) %s\n", m, nsnr_mute,
m >= 15.0 ? "ok" : "FAIL");
if (m < 15.0)
fail = 1;
m = percentile(snr_cn, nsnr_cn, 0.5);
printf("T4(d) noise sync: steady comfort noise median SNR %.1f dB over %d calls (>= 12) %s\n", m, nsnr_cn,
m >= 12.0 ? "ok" : "FAIL");
if (m < 12.0)
fail = 1;
}
printf("T4%s: %s\n", metrics ? "" : "(a)", fail ? "FAIL" : "PASS");
return fail;
}
+140
View File
@@ -0,0 +1,140 @@
#include <math.h>
#include <stdio.h>
#include "../src/internal.h"
#include "../src/tables/tables.h"
#include "../src/tables/dsp_tables.h"
#include "ref.h"
/* generated tables (scripts/gen_dsp_tables.py) against their closed forms, spectral blocks against the kernel
table's range, and the harmonic interpolation's end rules */
static int failures, checks;
static void check(int ok, const char *what, int i)
{
checks++;
if (!ok) {
failures++;
fprintf(stderr, "FAIL %s (item %d)\n", what, i);
}
}
static int rounds_to(float t, double v)
{
return fabs((double)t - v) <= 6e-8 * (fabs(v) > 1.0 ? fabs(v) : 1.0);
}
int main(void)
{
int J, m, i, L, k, N, n;
float a[XOMBE_LMAX + 1];
for (m = 0; m < 8; m++)
for (i = 0; i < 8; i++)
check(rounds_to(xombe__dct8[m][i], cos(XOMBE_PI * m * (i + 0.5) / 8.0)), "dct8", 8 * m + i);
for (J = 1; J <= XOMBE_DCT_BLK_J_MAX; J++) {
const float *kern = xombe__dct_blk + xombe__dct_blk_off[J];
check(xombe__dct_blk_off[J] + XOMBE_DCT_BLK_ROWS * J <= XOMBE_DCT_BLK_SIZE, "dct_blk extent", J);
for (m = 0; m < XOMBE_DCT_BLK_ROWS; m++)
for (i = 0; i < J; i++)
check(rounds_to(kern[m * J + i], cos(XOMBE_PI * m * (i + 0.5) / J)), "dct_blk", 100 * J + 10 * m + i);
}
for (L = 9; L <= XOMBE_LMAX; L++) {
int sum = 0;
for (k = 0; k < 4; k++) {
check(xombe__blk[L][k] >= 1 && xombe__blk[L][k] <= XOMBE_DCT_BLK_J_MAX, "block length in kernel range",
4 * L + k);
sum += xombe__blk[L][k];
}
check(sum == L, "blocks cover L", L);
check(rounds_to(xombe__half_log2[L], 0.5 * log2((double)L)), "half_log2", L);
}
for (i = 0; i < XOMBE_GRAIN_RAMP; i++) {
check(rounds_to(xombe__ramp_cos[i], cos(XOMBE_PI * i / XOMBE_GRAIN_RAMP)), "ramp_cos", i);
check(rounds_to(xombe__ramp_sin[i], sin(XOMBE_PI * i / XOMBE_GRAIN_RAMP)), "ramp_sin", i);
}
for (n = 0; n <= XOMBE_HALF_MAX; n++)
check(rounds_to(xombe__sqrt_n[n], sqrt((double)n)), "sqrt_n", n);
for (N = XOMBE_HALF_MIN; N <= XOMBE_HALF_MAX; N++)
check(rounds_to(xombe__rsqrt_half[N - XOMBE_HALF_MIN], 1.0 / sqrt((double)N)), "rsqrt_half", N);
for (i = 0; i < XOMBE_B0_COUNT - 1; i++) {
check(rounds_to(xombe__w0_mid[i], sqrt((double)xombe__w0[i] * xombe__w0[i + 1])), "w0_mid", i);
check(xombe__w0_mid[i] < xombe__w0[i] && xombe__w0_mid[i] > xombe__w0[i + 1], "w0_mid between", i);
}
for (k = 0; k < XOMBE_TW_N / 2; k++) {
double ang = -2.0 * XOMBE_PI * k / XOMBE_TW_N;
check(rounds_to(xombe__fft_tw[k].re, cos(ang)) && rounds_to(xombe__fft_tw[k].im, sin(ang)), "fft_tw", k);
}
#if XOMBE_HAVE_ENCODER
{
/* init-time tables against their closed forms */
double s = 0.0, s2 = 0.0, s4 = 0.0, h[2 * XOMBE_PITCH_LPF_HALF + 1];
float lo, hi;
int j;
for (i = 0; i < XOMBE_BASE_WINDOW; i++)
check(rounds_to(xombe__base_win[i], ref_hamming(i, XOMBE_BASE_WINDOW)), "base_win", i);
for (j = -XOMBE_PITCH_LPF_HALF; j <= XOMBE_PITCH_LPF_HALF; j++) {
double x = 0.25 * j, sinc = j == 0 ? 1.0 : sin(XOMBE_PI * x) / (XOMBE_PI * x);
h[j + XOMBE_PITCH_LPF_HALF] = 0.25 * sinc * (0.54 + 0.46 * cos(XOMBE_PI * j / XOMBE_PITCH_LPF_HALF));
s += h[j + XOMBE_PITCH_LPF_HALF];
}
for (j = 0; j < 2 * XOMBE_PITCH_LPF_HALF + 1; j++)
check(rounds_to(xombe__pitch_lpf[j], h[j] / s), "pitch_lpf", j);
for (j = 0; j < XOMBE_PITCH_WIN; j++)
s2 += ref_hamming(j, XOMBE_PITCH_WIN) * ref_hamming(j, XOMBE_PITCH_WIN);
for (j = 0; j < XOMBE_PITCH_WIN; j++) {
double w2 = ref_hamming(j, XOMBE_PITCH_WIN) * ref_hamming(j, XOMBE_PITCH_WIN) / s2;
check(rounds_to(xombe__pitch_w2[j], w2), "pitch_w2", j);
s4 += w2 * w2;
}
check(fabs(xombe__pitch_sum_w4 - s4) <= 6e-8 * s4, "pitch_sum_w4", 0);
for (i = 0; i < XOMBE_TONE_SEG; i++)
check(rounds_to(xombe__tone_win[i], 0.5 - 0.5 * cos(2.0 * XOMBE_PI * i / (XOMBE_TONE_SEG - 1))),
"tone_win", i);
for (i = 0; i < XOMBE_TONE_IDS; i++) { /* filter gain at each tone component, float within 2.2e-5 dB */
if (!xombe__tone_freqs(i, &lo, &hi))
continue;
check(fabs(xombe__tone_hpf_gain_db(lo) - ref_hpf_gain_db(lo)) <= 1e-4, "tone_hpf_gain_db", i);
check(fabs(xombe__tone_hpf_gain_db(hi) - ref_hpf_gain_db(hi)) <= 1e-4, "tone_hpf_gain_db", i);
}
}
/* window transform table reaches the widest harmonic fit: half the spacing at the highest pitch, widened
by the voicing metric's 2% jitter, plus the interpolation's next point */
check(0.5 * XOMBE_FFT * xombe__w0[0] * 1.02 * XOMBE_WTAB_OVERSAMPLE + 1.0 < XOMBE_WTAB_LEN - 1,
"window transform covers the harmonic fits", XOMBE_WTAB_LEN);
/* every analysis window, its energy, and its tabulated transform against double sums of the window */
for (n = XOMBE_BASE_WINDOW; n <= XOMBE_MAX_WINDOW; n += 2) {
static float w[XOMBE_MAX_WINDOW];
double s2 = 0.0, w0 = 0.0, worst = 0.0;
int h = (n - 1) / 2, q, j;
xombe__hamming(w, n);
for (i = 0; i < n; i++) {
check(fabs(w[i] - ref_hamming(i, n)) <= 1.2e-7, "hamming", 1000 * n + i);
s2 += ref_hamming(i, n) * ref_hamming(i, n);
w0 += ref_hamming(i, n);
}
check(fabs(xombe__hamming_sum2(n) - s2) <= 2e-7 * s2, "hamming_sum2", n); /* three roundings */
for (q = 0; q < XOMBE_WTAB_LEN; q++) {
double nu = 2.0 * XOMBE_PI * q / ((double)XOMBE_WTAB_OVERSAMPLE * XOMBE_FFT), v = 0.0;
for (j = -h; j <= h; j++)
v += ref_hamming(j + h, n) * cos(nu * j);
v = fabs(xombe__hamming_dtft(n, q, (long)XOMBE_WTAB_OVERSAMPLE * XOMBE_FFT) - v);
if (v > worst)
worst = v;
}
check(worst <= 1e-6 * w0, "hamming_dtft", n);
}
#endif
for (i = 0; i <= XOMBE_LMAX; i++)
a[i] = (float)i;
check(xombe__harmonic_lerp(a, 0, 0.7f) == 1.0f, "lerp holds a[1] below harmonic 1", 0);
check(xombe__harmonic_lerp(a, -3, 0.0f) == 1.0f, "lerp holds a[1] for negative positions", -3);
check(xombe__harmonic_lerp(a, XOMBE_LMAX, 0.5f) == (float)XOMBE_LMAX, "lerp holds a[LMAX] above", XOMBE_LMAX);
check(fabsf(xombe__harmonic_lerp(a, 10, 0.25f) - 10.25f) < 1e-5f, "lerp interior", 10);
printf("tables: %d/%d checks pass\n", checks - failures, checks);
return failures ? 1 : 0;
}
+152
View File
@@ -0,0 +1,152 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "tone_fit.h"
#define FRAMES 30
#define FIT_START (12 * 160)
static void tone_bits(int id, int ad, uint8_t bytes[7])
{
uint8_t d[49];
xombe__tone_frame_bits(id, ad, d);
xombe__pack49(d, bytes);
}
static void decode_tone(const uint8_t bytes[7], double *x)
{
xombe_dec dec;
int16_t pcm[160];
int f, i;
xombe_dec_set_noise(xombe_dec_init(&dec, XOMBE_DMR), XOMBE_NOISE_CONFORMANCE, 0);
for (f = 0; f < FRAMES; f++) {
xombe_dec_frame_bits(&dec, bytes, 0, pcm);
for (i = 0; i < 160; i++)
x[f * 160 + i] = pcm[i];
}
}
static void compare_reference_table(const char *dir)
{
static double x[FRAMES * 160];
char path[4096], line[512], bits[64], kind[32];
double max_df = 0.0, max_dl = 0.0;
int rows = 0;
FILE *f;
snprintf(path, sizeof(path), "%s/tone_table.tsv", dir);
f = fopen(path, "r");
if (!f) {
perror(path);
return;
}
while (fgets(line, sizeof(line), f)) {
double f1, f2 = 0.0, level, freq[2], amp[2];
uint8_t d[49], bytes[7];
int idx, i, nf, c;
if (line[0] == '#')
continue;
nf = sscanf(line, "%d %31s %63s %lf %lf %lf", &idx, kind, bits, &f1, &f2, &level);
if (nf == 5) {
level = f2;
nf = 1;
} else if (nf == 6) {
nf = 2;
} else {
continue;
}
for (i = 0; i < 49; i++)
d[i] = (uint8_t)(bits[i] == '1');
xombe__pack49(d, bytes);
decode_tone(bytes, x);
freq[0] = f1;
freq[1] = f2;
search_freqs(x + FIT_START, freq, nf, 0.01);
sinusoid_fit(x + FIT_START, FIT_LEN, freq, nf, amp);
for (c = 0; c < nf; c++) {
double df = fabs(freq[c] - (c ? f2 : f1)), dl = fabs(20.0 * log10(amp[c] / 32768.0) - level);
if (df > max_df)
max_df = df;
if (dl > max_dl)
max_dl = dl;
}
rows++;
}
fclose(f);
printf("reference tone table (informative): %d frames, max |frequency difference| %.2f Hz, "
"max |peak level difference| %.2f dB\n", rows, max_df, max_dl);
}
int main(int argc, char **argv)
{
static double x[FRAMES * 160];
int id, fail = 0, cases = 0;
double worst_f_single = 0.0, worst_f_dtmf = 0.0, worst_f_knox = 0.0, worst_f_progress = 0.0;
double worst_l_single = 0.0, worst_l_dual = 0.0;
for (id = 5; id <= 163; id++) {
float flo, fhi;
int kind = xombe__tone_id_accepted(id) ? xombe__tone_freqs(id, &flo, &fhi) : 0, ad;
double freq[2], nominal[2], amp[2];
int nf;
uint8_t bytes[7];
if (!kind)
continue;
nf = kind;
nominal[0] = flo;
nominal[1] = fhi;
tone_bits(id, 90, bytes);
decode_tone(bytes, x);
freq[0] = nominal[0];
freq[1] = nominal[1];
search_freqs(x + FIT_START, freq, nf, kind == 1 ? 0.005 : 0.05);
if (kind == 1) {
double err = fabs(freq[0] - nominal[0]);
if (err > worst_f_single)
worst_f_single = err;
if (err > 0.1) {
fail++;
printf("FAIL id %d: %.3f Hz, nominal %.3f\n", id, freq[0], nominal[0]);
}
} else {
double tol = id >= 160 ? 0.04 : 0.01;
int c;
for (c = 0; c < 2; c++) {
double rel = fabs(freq[c] - nominal[c]) / nominal[c];
double *worst = id >= 160 ? &worst_f_progress : id >= 144 ? &worst_f_knox : &worst_f_dtmf;
if (rel > *worst)
*worst = rel;
if (rel > tol) {
fail++;
printf("FAIL id %d component %d: %.2f Hz, nominal %.0f\n", id, c, freq[c], nominal[c]);
}
}
}
for (ad = 30; ad <= (kind == 1 ? 120 : 115); ad++) {
int c;
tone_bits(id, ad, bytes);
decode_tone(bytes, x);
sinusoid_fit(x + FIT_START, FIT_LEN, freq, nf, amp);
for (c = 0; c < nf; c++) {
double err = 20.0 * log10(amp[c] / 32768.0 + 1e-30) - expected_db(ad, freq[c]);
double *worst = kind == 1 ? &worst_l_single : &worst_l_dual;
if (fabs(err) > fabs(*worst))
*worst = err;
if (fabs(err) > 0.5) {
fail++;
printf("FAIL id %d AD %d component %d: level error %+.2f dB\n", id, ad, c, err);
}
}
cases++;
}
}
printf("T5: %d tone frames; worst single-tone frequency error %.4f Hz (limit 0.1)\n", cases, worst_f_single);
printf("T5: worst frequency error DTMF %.2f%% (limit 1%%), Knox %.2f%% (limit 1%%), call progress %.2f%% "
"(limit 4%%)\n",
100.0 * worst_f_dtmf, 100.0 * worst_f_knox, 100.0 * worst_f_progress);
printf("T5: worst level error single %+.3f dB, dual %+.3f dB (limit 0.5)\n", worst_l_single, worst_l_dual);
if (argc > 1)
compare_reference_table(argv[1]);
printf("T5: %s\n", fail ? "FAIL" : "PASS");
return fail ? 1 : 0;
}
+490
View File
@@ -0,0 +1,490 @@
/* AMBE+2 tone detector, reference vs merged (xombe__tone_detect over the generic search), on every segment position the
encoder reads: decoded tone frames (T5), synthetic E6 cases, the tone vectors, and speech and other non-tone
vectors. --full takes every AD in T5 (default every 6th), --list prints each disagreement, --time the slowest
segment of each detector. exits 1 on a regression (see verdict) */
#include "../src/enc/tone_detect.c" /* its fit helpers are static */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ref.h"
#define MAXFILES 64
#define T5_FRAMES 8
#define T5_FIRST 3 /* decoded frames before the first segment */
/* reference: AMBE+2 detector before the merge into xombe__tone_search, per-ID filter gain as tabulated then */
static float ref_hpf_db[XOMBE_TONE_IDS];
#define DUAL_REFINE_SPAN 0.025f
#define DUAL_TRIALS 24 /* 2 passes x 2 components x 3 steps x 2 signs */
/* the reference's float front end and correlation, as the float build has them */
static void ref_correlate(const float *x, int len, float hz, component *c)
{
float w = 2.0f * XOMBE_PI_F * hz / XOMBE_FS, hc = cosf(0.5f * w), hs = sinf(0.5f * w);
float cw = hc * hc - hs * hs, s = 0.0f, d = 0.0f, prev;
int n = len - 1;
if (cw >= 0.0f) {
float l = -4.0f * hs * hs;
for (; n > 0; n -= 2) {
d += x[n] + l * s;
s += d;
d += x[n - 1] + l * s;
s += d;
}
if (n == 0) {
d += x[0] + l * s;
s += d;
}
prev = s - d;
} else {
float l = 4.0f * hc * hc;
for (; n > 0; n -= 2) {
d = x[n] + l * s - d;
s = d - s;
d = x[n - 1] + l * s - d;
s = d - s;
}
if (n == 0) {
d = x[0] + l * s - d;
s = d - s;
}
prev = d - s;
}
c->hz = hz;
c->rc = s - cw * prev;
c->rs = 2.0f * hs * hc * prev;
c->h[0] = hc;
c->h[1] = hs;
c->m[0] = cosf((float)(2 * len - 1) * 0.5f * w);
c->m[1] = sinf((float)(2 * len - 1) * 0.5f * w);
}
static void ref_fit_component(const float *x, int len, float hz, component *c)
{
ref_correlate(x, len, hz, c);
gram(c, c, len, c->g);
}
static float ref_prepare(xombe_enc *e, const int16_t *seg, float *x, float pw[XOMBE_TONE_FFT / 2 + 1])
{
static const float min_amp = 32768.0f * 0.0031622777f;
xombe_cpx *X = e->tone_spec;
float mean, energy = 0.0f;
long sum = 0;
int n, k;
for (n = 0; n < XOMBE_TONE_SEG; n++)
sum += seg[n];
mean = (float)sum / XOMBE_TONE_SEG;
for (n = 0; n < XOMBE_TONE_SEG; n++) {
x[n] = (float)seg[n] - mean;
energy += x[n] * x[n];
}
if (energy / XOMBE_TONE_SEG < 0.5f * min_amp * min_amp)
return 0.0f;
memset(e->tone_spec, 0, sizeof(e->tone_spec));
for (n = 0; n < XOMBE_TONE_SEG; n++) {
float v = x[n] * xombe__tone_win[n];
if (n & 1)
X[n >> 1].im = v;
else
X[n >> 1].re = v;
}
xombe__rfft_packed(X, XOMBE_TONE_FFT, xombe__fft_tw, XOMBE_TW_N);
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++)
pw[k] = X[k].re * X[k].re + X[k].im * X[k].im;
return energy;
}
static float ref_band_total(const float *pw)
{
float total = 0.0f;
int k;
for (k = (int)ceilf(GATE_LO_HZ / BIN_HZ); k <= (int)floorf(GATE_HI_HZ / BIN_HZ); k++)
total += pw[k];
return total;
}
static int ref_gate_pass(const float *pw, const float nominal[2], float total)
{
float near = 0.0f;
int k, r0lo, r0hi, r1lo, r1hi;
gate_run(nominal[0], &r0lo, &r0hi);
gate_run(nominal[1], &r1lo, &r1hi);
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++)
if ((k >= r0lo && k <= r0hi) || (k >= r1lo && k <= r1hi))
near += pw[k];
return !(near < DUAL_GATE_SHARE * total);
}
/* returns 1 if seen[n] repeats an earlier pair, already rejected since none beats the current best */
static int visited(const float seen[][2], int n)
{
int i;
for (i = 0; i < n; i++)
if (seen[i][0] == seen[n][0] && seen[i][1] == seen[n][1])
return 1;
return 0;
}
static int ref_detect(xombe_enc *e, const int16_t *seg, int *id, int *ad)
{
float x[XOMBE_TONE_SEG], energy, total, best_dual = -1.0f, e1, amp1[2] = {0.0f, 0.0f};
component single;
float pw[XOMBE_TONE_FFT / 2 + 1];
int k, peak = 2, single_id = -1, dual_id = -1, dual_ad = 0, cand;
energy = ref_prepare(e, seg, x, pw);
if (energy == 0.0f)
return 0;
for (k = 3; k < XOMBE_TONE_FFT / 2; k++)
if (pw[k] > pw[peak])
peak = k;
{
float a = 0.5f * logf(pw[peak - 1] + 1e-30f), b = 0.5f * logf(pw[peak] + 1e-30f);
float c = 0.5f * logf(pw[peak + 1] + 1e-30f), den = a - 2.0f * b + c;
float delta = den != 0.0f ? 0.5f * (a - c) / den : 0.0f;
ref_fit_component(x, XOMBE_TONE_SEG, ((float)peak + delta) * BIN_HZ, &single);
}
e1 = fit(energy, &single, 1, XOMBE_TONE_SEG, amp1);
cand = (int)floorf(single.hz / SINGLE_ID_HZ + 0.5f);
if (e1 >= EXPLAINED_MIN && cand >= 5 && cand <= 122)
single_id = cand;
total = ref_band_total(pw);
for (cand = 128; cand <= 163; cand++) {
float lo, hi, nominal[2], amp[2], ex;
component comp[2];
float seen[DUAL_TRIALS + 1][2];
int pass, c, s, nseen;
if (xombe__tone_freqs(cand, &lo, &hi) != 2)
continue;
nominal[0] = lo;
nominal[1] = hi;
if (!ref_gate_pass(pw, nominal, total))
continue;
ref_fit_component(x, XOMBE_TONE_SEG, nominal[0], &comp[0]);
ref_fit_component(x, XOMBE_TONE_SEG, nominal[1], &comp[1]);
ex = fit(energy, comp, 2, XOMBE_TONE_SEG, amp);
seen[0][0] = comp[0].hz;
seen[0][1] = comp[1].hz;
nseen = 1;
for (pass = 0; pass < 2; pass++)
for (c = 0; c < 2; c++)
for (s = 0; s < 3; s++) {
static const float steps[3] = {0.01f, 0.005f, 0.0025f};
int sign;
for (sign = -1; sign <= 1; sign += 2) {
component keep = comp[c];
float hz = keep.hz + (float)sign * steps[s] * nominal[c], trial_amp[2] = {0.0f, 0.0f}, te;
if (fabsf(hz - nominal[c]) > DUAL_REFINE_SPAN * nominal[c] * (1.0f + 1e-6f))
continue;
seen[nseen][c] = hz;
seen[nseen][1 - c] = comp[1 - c].hz;
if (visited(seen, nseen))
continue;
nseen++;
ref_fit_component(x, XOMBE_TONE_SEG, hz, &comp[c]);
te = fit(energy, comp, 2, XOMBE_TONE_SEG, trial_amp);
if (te > ex) {
ex = te;
amp[0] = trial_amp[0];
amp[1] = trial_amp[1];
} else {
comp[c] = keep;
}
}
}
if (ex >= EXPLAINED_MIN && fabsf(20.0f * log10f((amp[0] + 1e-30f) / (amp[1] + 1e-30f))) <= DUAL_TWIST_DB &&
ex > best_dual) {
best_dual = ex;
dual_id = cand;
dual_ad = ad_from_level(0.5f * (peak_db(amp[0]) + peak_db(amp[1])) - ref_hpf_db[cand]);
}
}
if (dual_id >= 0 && (single_id < 0 || best_dual > e1 + DUAL_PREFERENCE)) {
*id = dual_id;
*ad = dual_ad;
return 1;
}
if (single_id >= 0) {
*id = single_id;
*ad = ad_from_level(peak_db(amp1[0]) - ref_hpf_db[single_id]);
return 1;
}
return 0;
}
/* the detector under test */
static int new_detect(xombe_enc *e, const int16_t *seg, int *id, int *ad)
{
return xombe__tone_detect(e, seg, id, ad);
}
typedef struct {
const char *name;
long segs, det[2], id_diff, ad_diff, max_dad, only[2], frames[2], truth, miss[2], wrong[2], ad_off[2];
} stats;
static struct xombe_enc enc_ref, enc_new;
static int list, timing;
static double slow_t[2];
static char slow_at[2][128];
static double now(void)
{
return (double)clock() / CLOCKS_PER_SEC;
}
static void reset_decide(void)
{
enc_ref.tone_prev_id = enc_new.tone_prev_id = -1;
enc_ref.tone_confirmed = enc_new.tone_confirmed = 0;
enc_ref.tone_hold_used = enc_new.tone_hold_used = 0;
enc_ref.tone_last_id = enc_new.tone_last_id = 0;
enc_ref.tone_last_ad = enc_new.tone_last_ad = 0;
}
/* both detectors on one segment, true_id > 0 names the tone it holds (0: no tone, -1: unknown) */
static void one(stats *s, const int16_t *seg, int true_id, int true_ad, const char *where, long pos)
{
struct xombe_enc *es[2] = {&enc_ref, &enc_new};
int det[2], id[2] = {-1, -1}, ad[2] = {0, 0}, k;
for (k = 0; k < 2; k++) {
double t0 = timing ? now() : 0.0;
det[k] = (k ? new_detect : ref_detect)(es[k], seg, &id[k], &ad[k]);
if (timing) {
double t = now() - t0;
if (t > slow_t[k]) {
slow_t[k] = t;
snprintf(slow_at[k], sizeof(slow_at[k]), "%s @%ld", where, pos);
}
}
if (!det[k])
id[k] = -1;
s->det[k] += det[k];
{
int tid, tad;
s->frames[k] += xombe__tone_decide(es[k], det[k], id[k], ad[k], &tid, &tad);
}
if (true_id > 0) {
if (!det[k])
s->miss[k]++;
else if (id[k] != true_id)
s->wrong[k]++;
else if (true_ad >= 0 && ad[k] != true_ad)
s->ad_off[k]++;
}
}
s->segs++;
s->truth += true_id > 0;
if (det[0] != det[1]) {
s->only[det[1]]++;
} else if (det[0] && id[0] != id[1]) {
s->id_diff++;
} else if (det[0] && ad[0] != ad[1]) {
int d = abs(ad[0] - ad[1]);
s->ad_diff++;
s->max_dad = d > s->max_dad ? d : s->max_dad;
} else {
return;
}
if (list)
printf(" %s @%ld: ref %d/%d new %d/%d (true %d/%d)\n", where, pos, id[0], ad[0], id[1], ad[1], true_id,
true_ad);
}
static void report(const stats *s)
{
printf("%-8s %7ld segs det %6ld %6ld tone frames %6ld %6ld ref-only %4ld new-only %4ld ID diff %4ld "
"AD diff %4ld (max %ld)",
s->name, s->segs, s->det[0], s->det[1], s->frames[0], s->frames[1], s->only[0], s->only[1], s->id_diff,
s->ad_diff, s->max_dad);
if (s->truth)
printf("\n%-8s %7ld true missed %4ld %4ld wrong ID %4ld %4ld AD off %4ld %4ld", "", s->truth, s->miss[0],
s->miss[1], s->wrong[0], s->wrong[1], s->ad_off[0], s->ad_off[1]);
printf("\n");
}
static int16_t *load(const char *path, long *n)
{
FILE *f = fopen(path, "rb");
long size;
int16_t *x;
if (!f) {
perror(path);
exit(2);
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
*n = size / 2;
x = calloc((size_t)*n + XOMBE_TONE_SEG, sizeof(int16_t)); /* zero tail, as the encoder flushes */
if (fread(x, sizeof(int16_t), (size_t)*n, f) != (size_t)*n)
exit(2);
fclose(f);
return x;
}
/* every segment at 160k of x[0..n), zeros past the end; tone true_id over [on, off) */
static void run_signal(stats *s, const int16_t *x, long n, const char *name, int true_id, int true_ad, long on,
long off)
{
long p;
reset_decide();
for (p = 0; p < n; p += XOMBE_FRAME) {
int t = true_id > 0 && p >= on && p + XOMBE_TONE_SEG <= off ? true_id : true_id > 0 ? -1 : true_id;
one(s, x + p, t, true_ad, name, p);
}
}
static void run_file(stats *s, const char *path, int tone)
{
long n;
int16_t *x = load(path, &n);
run_signal(s, x, n, path, tone ? -1 : 0, 0, 0, 0);
free(x);
}
static void run_t5(stats *s, int ad_step)
{
static int16_t x[T5_FRAMES * XOMBE_FRAME];
int id, ad, f;
for (id = 5; id <= 163; id++) {
float lo, hi;
if (!xombe__tone_id_accepted(id) || !xombe__tone_freqs(id, &lo, &hi))
continue;
for (ad = 30; ad <= 120; ad += ad_step) {
xombe_dec dec;
uint8_t d[49], bytes[7];
char where[32];
xombe__tone_frame_bits(id, ad, d);
xombe__pack49(d, bytes);
xombe_dec_set_noise(xombe_dec_init(&dec, XOMBE_DMR), XOMBE_NOISE_CONFORMANCE, 0);
for (f = 0; f < T5_FRAMES; f++)
xombe_dec_frame_bits(&dec, bytes, 0, x + f * XOMBE_FRAME);
snprintf(where, sizeof(where), "T5 id %d ad %d", id, ad);
reset_decide();
for (f = T5_FIRST; (f + 1) * XOMBE_FRAME + XOMBE_TONE_SEG - XOMBE_FRAME <= T5_FRAMES * XOMBE_FRAME; f++)
one(s, x + f * XOMBE_FRAME, id, ad, where, f * XOMBE_FRAME);
}
}
}
/* tools/e6.py gen: DTMF at -16 dBFS, Knox and call progress at -20, single tones at 300, 1000, 2000, and 3000 Hz
from -6 to -46 dBFS, each 0.4 s between 0.5 s and 0.3 s of silence, phases from a fixed LCG */
static void run_e6(stats *s)
{
static int16_t x[8000 + 1600 + XOMBE_TONE_SEG];
static const int singles[4] = {300, 1000, 2000, 3000};
unsigned lcg = 20261019u;
int c, n, len = 3200, on = 4000, total = on + len + 2400;
for (c = 0; c < 36 + 20; c++) {
double f[2], lev, ph[2];
int id, nf, i;
char where[32];
float lo, hi;
if (c < 36) {
id = 128 + c;
xombe__tone_freqs(id, &lo, &hi);
f[0] = lo;
f[1] = hi;
nf = 2;
lev = id < 144 ? -16.0 : -20.0;
} else {
f[0] = singles[(c - 36) / 5];
lev = -6.0 - 10.0 * ((c - 36) % 5);
id = (int)floor(f[0] / 31.25 + 0.5);
nf = 1;
}
for (i = 0; i < nf; i++) {
lcg = lcg * 1664525u + 1013904223u;
ph[i] = 2.0 * XOMBE_PI * (lcg >> 8) / 16777216.0;
}
memset(x, 0, sizeof(x));
for (n = 0; n < len; n++) {
double v = 0.0;
for (i = 0; i < nf; i++)
v += 32768.0 * pow(10.0, lev / 20.0) * cos(2.0 * XOMBE_PI * f[i] / XOMBE_FS * n + ph[i]);
v = floor(v + 0.5);
x[on + n] = (int16_t)(v > 32767 ? 32767 : v < -32768 ? -32768 : v);
}
snprintf(where, sizeof(where), "E6 id %d %.0f dBFS", id, lev);
run_signal(s, x, total, where, id, -1, on, on + len);
}
}
int main(int argc, char **argv)
{
static const char *tone_vec[] = {"e7/tones.raw", "dstar/tn.in.raw", "dstar/kx.in.raw", "dstar/tn.dec.raw",
"dstar/kx.dec.raw"};
static const char *speech_vec[] = {
"e3/es1_orig.raw", "e3/es2_orig.raw", "e3/es3_orig.raw", "e3/sn10_orig.raw",
"e3/ttsc_orig.raw", "e3/ttsf_orig.raw", "e3/ttsl_orig.raw",
"perceptual/es2_orig.raw", "perceptual/es3_orig.raw", "perceptual/es4_orig.raw",
"perceptual/es1_nsdtx_off_ref.raw", "perceptual/es1_nsdtx_on_ref.raw", "perceptual/es2_ref.raw",
"perceptual/es3_ref.raw", "perceptual/es4_ref.raw", "e5/es1_lead0.5s.raw", "e5/hp5.raw", "e5/low5.raw",
"e7/glide.raw", "e7/mix.raw", "e7/saw150.raw", "dstar/sp.in.raw", "dstar/nz.in.raw", "dstar/sp.dec.raw",
"dstar/sper.dec.raw", "dstar/nz.dec.raw"};
const char *extra_tone[MAXFILES], *extra_speech[MAXFILES];
stats t5, e6, tv, sp;
char path[4096];
int i, full = 0, ntone = 0, nspeech = 0, bad = 0;
if (argc < 2) {
fprintf(stderr, "usage: tone_cmp VEC [--full] [--list] [--time] [--tones FILE]... [--speech FILE]...\n");
return 2;
}
for (i = 2; i < argc; i++) {
if (!strcmp(argv[i], "--full"))
full = 1;
else if (!strcmp(argv[i], "--list"))
list = 1;
else if (!strcmp(argv[i], "--time"))
timing = 1;
else if (!strcmp(argv[i], "--tones") && i + 1 < argc && ntone < MAXFILES)
extra_tone[ntone++] = argv[++i];
else if (!strcmp(argv[i], "--speech") && i + 1 < argc && nspeech < MAXFILES)
extra_speech[nspeech++] = argv[++i];
else
return 2;
}
memset(&t5, 0, sizeof(t5));
memset(&e6, 0, sizeof(e6));
memset(&tv, 0, sizeof(tv));
memset(&sp, 0, sizeof(sp));
t5.name = "T5";
e6.name = "E6";
tv.name = "tones";
sp.name = "speech";
for (i = 0; i < XOMBE_TONE_IDS; i++) {
float lo, hi;
ref_hpf_db[i] = xombe__tone_freqs(i, &lo, &hi) ? (float)(0.5 * (ref_hpf_gain_db(lo) + ref_hpf_gain_db(hi)))
: 0.0f;
}
run_t5(&t5, full ? 1 : 6);
run_e6(&e6);
for (i = 0; i < (int)(sizeof(tone_vec) / sizeof(tone_vec[0])); i++) {
snprintf(path, sizeof(path), "%s/%s", argv[1], tone_vec[i]);
run_file(&tv, path, 1);
}
for (i = 0; i < ntone; i++)
run_file(&tv, extra_tone[i], 1);
for (i = 0; i < (int)(sizeof(speech_vec) / sizeof(speech_vec[0])); i++) {
snprintf(path, sizeof(path), "%s/%s", argv[1], speech_vec[i]);
run_file(&sp, path, 0);
}
for (i = 0; i < nspeech; i++)
run_file(&sp, extra_speech[i], 0);
printf("columns: reference, new\n");
report(&t5);
report(&e6);
report(&tv);
report(&sp);
if (timing)
printf("slowest: reference %.1f us (%s), new %.1f us (%s)\n", 1e6 * slow_t[0], slow_at[0], 1e6 * slow_t[1],
slow_at[1]);
/* verdict: no new speech detections, and no T5 or E6 tone the reference finds that the new one misses */
bad |= sp.only[1] != 0 || sp.frames[1] > sp.frames[0];
bad |= t5.miss[1] + t5.wrong[1] > t5.miss[0] + t5.wrong[0];
bad |= e6.miss[1] + e6.wrong[1] > e6.miss[0] + e6.wrong[0];
printf("tone_cmp: %s\n", bad ? "FAIL" : "PASS");
return bad;
}
+85
View File
@@ -0,0 +1,85 @@
#ifndef XOMBE_TEST_TONE_FIT_H
#define XOMBE_TEST_TONE_FIT_H
/* least-squares sinusoid fits of decoded tones, FIT_LEN samples */
#include <math.h>
#include <string.h>
#include "ref.h"
#define FIT_LEN 1600
static inline double sinusoid_fit(const double *x, int n, const double *freq, int nf, double *amp)
{
double basis[4][FIT_LEN], g[16], r[4], energy = 0.0, explained = 0.0;
int c, i, j, m = 2 * nf;
for (c = 0; c < nf; c++) {
double w = 2.0 * XOMBE_PI * freq[c] / 8000.0, cr = cos(w), ci = sin(w), pr = 1.0, pi = 0.0;
for (i = 0; i < n; i++) {
double t;
basis[2 * c][i] = pr;
basis[2 * c + 1][i] = pi;
t = pr * cr - pi * ci;
pi = pr * ci + pi * cr;
pr = t;
}
}
for (i = 0; i < m; i++) {
r[i] = 0.0;
for (j = 0; j < m; j++) {
double s = 0.0;
int k;
for (k = 0; k < n; k++)
s += basis[i][k] * basis[j][k];
g[i * m + j] = s;
}
for (j = 0; j < n; j++)
r[i] += basis[i][j] * x[j];
}
{
double rr[4];
memcpy(rr, r, sizeof(rr));
if (!ref_solve(g, r, m))
return 1e300;
for (i = 0; i < m; i++)
explained += r[i] * rr[i];
}
for (i = 0; i < n; i++)
energy += x[i] * x[i];
for (c = 0; c < nf; c++)
amp[c] = hypot(r[2 * c], r[2 * c + 1]);
return energy - explained;
}
static inline void search_freqs(const double *x, double *freq, int nf, double span)
{
int c, round;
double amp[2];
for (round = 0; round < 2; round++) {
for (c = 0; c < nf; c++) {
double centre = freq[c], step = centre * span / 100.0, best = freq[c], bestr = 1e300;
int pass, k;
for (pass = 0; pass < 4; pass++) {
for (k = -100; k <= 100; k++) {
double r;
freq[c] = centre + k * step;
r = sinusoid_fit(x, FIT_LEN, freq, nf, amp);
if (r < bestr) {
bestr = r;
best = freq[c];
}
}
centre = best;
step /= 50.0;
}
freq[c] = best;
}
}
}
static inline double expected_db(int ad, double f)
{
return 20.0 * log10(2.0 * exp2(xombe__tone_log2_amp(ad)) / 32768.0) + ref_hpf_gain_db(f);
}
#endif
+70
View File
@@ -0,0 +1,70 @@
#!/bin/sh
# tools.sh BUILD VECTORS: command-line contracts of xombe-enc, xombe-dec, and xombe-xc
B=$1; V=$2; T=$B/tools_out; mkdir -p "$T"; fails=0
expect() { # expect STATUS DESC CMD...
want=$1; what=$2; shift 2
"$@" > "$T/out.txt" 2> "$T/err.txt"; got=$?
if [ "$got" -ne "$want" ]; then echo "FAIL $what: exit $got, want $want"; cat "$T/err.txt"; fails=$((fails + 1)); fi
}
have() { [ -x "$B/$1" ]; }
partial() { # partial WHO: the last command reported the partial final frame
grep -q "error: partial final frame" "$T/err.txt" || { echo "FAIL $1 partial frame message"; fails=$((fails + 1)); }
}
for t in xombe-enc xombe-dec xombe-xc; do
have $t || continue
expect 0 "$t --help" "$B/$t" --help
grep -q "usage: $t" "$T/out.txt" || { echo "FAIL $t --help text"; fails=$((fails + 1)); }
expect 2 "$t unknown option" "$B/$t" --nope a b
expect 2 "$t missing paths" "$B/$t"
done
head -c 1001 "$V/dstar/sp.in.raw" > "$T/odd.raw"
head -c 100 "$V/dstar/sp.dstar" > "$T/odd.dstar"
if have xombe-enc; then
expect 0 "enc partial final frame" "$B/xombe-enc" "$T/odd.raw" "$T/odd.amb"
grep -q "partial final frame" "$T/err.txt" || { echo "FAIL enc partial frame warning"; fails=$((fails + 1)); }
expect 2 "enc bad on/off" "$B/xombe-enc" --ns maybe "$T/odd.raw" "$T/x"
expect 2 "enc bad number" "$B/xombe-enc" --vscale 0 "$T/odd.raw" "$T/x"
expect 2 "enc bad quantizer" "$B/xombe-enc" --quant maybe "$T/odd.raw" "$T/x"
expect 0 "enc open quantizer" "$B/xombe-enc" --quant open "$T/odd.raw" "$T/x"
if "$B/xombe-enc" --help | grep -q "^ --dstar .*not in this build"; then
expect 2 "enc --dstar without D-STAR" "$B/xombe-enc" --dstar "$T/odd.raw" "$T/x"
else
expect 2 "enc --dstar with --air" "$B/xombe-enc" --dstar --air "$T/odd.raw" "$T/x"
expect 0 "enc --dual" "$B/xombe-enc" --dual "$T/dual.dstar" "$T/odd.raw" "$T/dual.amb"
[ "$(wc -c < "$T/dual.dstar")" -eq 27 ] || { echo "FAIL enc --dual frame count"; fails=$((fails + 1)); }
fi
fi
if have xombe-dec; then
expect 2 "dec two input formats" "$B/xombe-dec" --bits --air "$T/odd.dstar" "$T/x"
expect 2 "dec bad --lost" "$B/xombe-dec" --lost 3-1 "$T/odd.dstar" "$T/x"
head -c 15 "$V/e3/es1.ref.d0.amb" > "$T/odd.amb"
expect 1 "dec truncated .amb frame" "$B/xombe-dec" "$T/odd.amb" "$T/x"
partial "dec"
if "$B/xombe-dec" --help | grep -q "^ --dstar .*not in this build"; then
expect 2 "dec --dstar without D-STAR" "$B/xombe-dec" --dstar "$T/odd.dstar" "$T/x"
else
expect 1 "dec truncated D-STAR frame" "$B/xombe-dec" --dstar "$T/odd.dstar" "$T/x"
partial "dec --dstar"
expect 0 "dec --lost" "$B/xombe-dec" --dstar --decisions --lost 2,5-6 "$V/dstar/sp.dstar" "$T/x"
[ "$(grep -c " erasure " "$T/err.txt")" -eq 3 ] || { echo "FAIL dec --lost decisions"; fails=$((fails + 1)); }
fi
fi
if have xombe-xc; then
expect 1 "xc truncated frame" "$B/xombe-xc" "$T/odd.dstar" "$T/x"
partial "xc"
expect 0 "xc --lost" "$B/xombe-xc" --decisions --lost 1 "$V/dstar/sp.r33" "$T/x"
[ "$(grep -c " erasure " "$T/err.txt")" -eq 1 ] || { echo "FAIL xc --lost decisions"; fails=$((fails + 1)); }
if "$B/xombe-xc" --help | grep -q "^ --reverse .*not in this build"; then
expect 2 "xc --reverse without the encoder" "$B/xombe-xc" --reverse "$V/dstar/sp.dstar" "$T/x"
else
expect 0 "xc --reverse --lost" "$B/xombe-xc" --reverse --decisions --lost 0 "$V/dstar/sp.dstar" "$T/x"
[ "$(grep -c " erasure " "$T/err.txt")" -eq 1 ] || { echo "FAIL xc --reverse --lost"; fails=$((fails + 1)); }
expect 0 "xc --reverse --amb" "$B/xombe-xc" --reverse --amb "$V/dstar/sper.dstar" "$T/rt.amb"
expect 0 "xc --amb" "$B/xombe-xc" --amb "$T/rt.amb" "$T/rt_amb.dstar"
"$B/xombe-xc" --reverse "$V/dstar/sper.dstar" "$T/rt.r33" && "$B/xombe-xc" "$T/rt.r33" "$T/rt_r33.dstar"
cmp -s "$T/rt_amb.dstar" "$T/rt_r33.dstar" || { echo "FAIL xc --amb round trip differs from r33"; fails=$((fails + 1)); }
fi
expect 1 "xc --amb on a non-.amb file" "$B/xombe-xc" --amb "$V/dstar/sp.r33" "$T/x"
fi
[ $fails -eq 0 ] && echo "tools: ok"
exit $fails
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""compares two stage dumps from test/trace_dump (or another implementation writing the same records) and
reports, per stage, how far the second is from the first
absolute differences: log-amplitude stages (DEQUANT, SMOOTH, SET, TARGET), VAD decision and metric (VAD),
and phases (PHASE, wrapped)
log2 ratios: linear amplitudes (ENHANCED, SHAPED), ignoring harmonics below --floor in the reference
SNR over the whole dump: SYNTH
records match by frame, half, and stage, a record whose length or f0 differs is a structural mismatch
exits 1 if any limit given on the command line is exceeded or any record is unmatched"""
import argparse
import math
import struct
import sys
STAGES = ['DEQUANT', 'SMOOTH', 'SET', 'ENHANCED', 'PHASE', 'SHAPED', 'SYNTH', 'TARGET', 'VAD']
LOG_STAGES = {'DEQUANT', 'SMOOTH', 'SET', 'TARGET', 'VAD'}
LIN_STAGES = {'ENHANCED', 'SHAPED'}
def read(path):
recs = {}
with open(path, 'rb') as f:
data = f.read()
pos = 0
while pos < len(data):
if pos + 12 > len(data):
sys.exit('%s: truncated record header at byte %d' % (path, pos))
frame, half, stage, n, f0 = struct.unpack_from('<IBBHf', data, pos)
pos += 12
if pos + 4 * n > len(data):
sys.exit('%s: truncated record at byte %d' % (path, pos))
v = struct.unpack_from('<%df' % n, data, pos)
pos += 4 * n
key = (frame, half, stage)
# a stage may fire more than once per half, keep them in order
recs.setdefault(key, []).append((f0, v))
return recs
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('ref')
ap.add_argument('test')
ap.add_argument('--floor', type=float, default=1e-3, help='linear amplitude below which ENHANCED/SHAPED '
'harmonics are not compared (default 1e-3, far below one output LSB)')
ap.add_argument('--max-log', type=float, help='limit on the log2 stages and linear-stage log2 ratios')
ap.add_argument('--max-phase', type=float, help='limit on PHASE differences, radians')
ap.add_argument('--min-snr', type=float, help='limit on SYNTH SNR, dB')
args = ap.parse_args()
a, b = read(args.ref), read(args.test)
stats = {s: {'n': 0, 'max': 0.0, 'where': None, 'sig': 0.0, 'err': 0.0, 'struct': 0} for s in STAGES}
unmatched = len(set(a) ^ set(b))
for key in sorted(set(a) & set(b)):
name = STAGES[key[2]] if key[2] < len(STAGES) else 'stage%d' % key[2]
st = stats.setdefault(name, {'n': 0, 'max': 0.0, 'where': None, 'sig': 0.0, 'err': 0.0, 'struct': 0})
for (f0a, va), (f0b, vb) in zip(a[key], b[key]):
st['n'] += 1
if len(va) != len(vb) or abs(f0a - f0b) > 1e-6 * max(abs(f0a), 1e-3):
st['struct'] += 1
continue
for i, (x, y) in enumerate(zip(va, vb)):
if name in LOG_STAGES:
d = abs(x - y)
elif name == 'PHASE':
d = abs(math.remainder(x - y, 2.0 * math.pi))
elif name in LIN_STAGES:
if x < args.floor:
continue
d = abs(math.log2(max(y, 1e-30) / x))
else:
st['sig'] += x * x
st['err'] += (x - y) * (x - y)
d = abs(x - y)
if d > st['max']:
st['max'], st['where'] = d, (key[0], key[1], i)
bad = unmatched > 0
print('%-9s %8s %6s %12s %s' % ('stage', 'records', 'struct', 'max diff', 'worst (frame, half, index)'))
for name, st in stats.items():
if not st['n']:
continue
line = '%-9s %8d %6d %12.3g %s' % (name, st['n'], st['struct'], st['max'], st['where'])
if name == 'SYNTH':
snr = 10 * math.log10(st['sig'] / st['err']) if st['err'] > 0 else float('inf')
line += ' SNR %.1f dB' % snr
if args.min_snr is not None and snr < args.min_snr:
bad = True
elif name == 'PHASE':
if args.max_phase is not None and st['max'] > args.max_phase:
bad = True
elif args.max_log is not None and st['max'] > args.max_log:
bad = True
bad |= st['struct'] > 0
print(line)
if unmatched:
print('%d records present in only one dump' % unmatched)
sys.exit(1 if bad else 0)
if __name__ == '__main__':
main()
+138
View File
@@ -0,0 +1,138 @@
/* dumps the codec's stage taps (src/state.h) for one input, for test/trace_cmp.py to compare two builds or
against another implementation, decoder stages in two 80-sample halves per frame, encoder stages in the default
configuration
OUT.trace: little-endian records, u32 frame, u8 half, u8 stage (enum xombe_stage), u16 n, f32 f0, n x f32
encoder records carry the frame they belong to (the call that returned its bits, less XOMBE_ENC_DELAY)
and half 0 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/internal.h"
#include "../tools/io.h"
typedef struct {
FILE *f;
const char *path;
uint32_t frame;
uint8_t half;
int failed;
} dump;
static void put_u32(uint8_t *p, uint32_t v)
{
p[0] = (uint8_t)v;
p[1] = (uint8_t)(v >> 8);
p[2] = (uint8_t)(v >> 16);
p[3] = (uint8_t)(v >> 24);
}
static void put_f32(uint8_t *p, float x)
{
uint32_t v;
memcpy(&v, &x, sizeof(v));
put_u32(p, v);
}
static void tap(void *ctx, enum xombe_stage stage, float f0, const float *v, int n)
{
dump *t = ctx;
uint8_t head[12], buf[4 * (XOMBE_HALF_MAX + XOMBE_LMAX)];
int i;
if (t->failed || n < 0 || n > (int)(sizeof(buf) / 4))
return;
put_u32(head, t->frame);
head[4] = t->half;
head[5] = (uint8_t)stage;
head[6] = (uint8_t)n;
head[7] = (uint8_t)(n >> 8);
put_f32(head + 8, f0);
for (i = 0; i < n; i++)
put_f32(buf + 4 * i, v[i]);
if (!io_write(t->f, head, sizeof(head), t->path) || !io_write(t->f, buf, 4 * (size_t)n, t->path))
t->failed = 1;
}
static int run_dec(FILE *in, const char *in_path, dump *t)
{
static xombe_dec_mem mem;
xombe_dec *d = xombe_dec_init(&mem, XOMBE_DMR);
uint8_t rec[IO_AMB_RECORD], bits[7];
char head[sizeof(IO_AMB_HEADER) - 1];
int16_t pcm[XOMBE_HALF_MAX];
size_t got;
xombe_dec_set_noise(d, XOMBE_NOISE_CONFORMANCE, 0);
if (fread(head, 1, sizeof(head), in) != sizeof(head) || memcmp(head, IO_AMB_HEADER, sizeof(head)) != 0) {
fprintf(stderr, "%s: not an .amb file\n", in_path);
return 0;
}
xombe__dec_set_tap(d, tap, t);
while ((got = fread(rec, 1, sizeof(rec), in)) == sizeof(rec)) {
io_amb_to_bytes(rec, bits);
t->half = 0;
xombe_dec_half_bits(d, bits, 0, 0, 80, pcm);
t->half = 1;
xombe_dec_half_bits(d, bits, 0, 1, 80, pcm);
t->frame++;
}
if (got) {
fprintf(stderr, "%s: truncated frame\n", in_path);
return 0;
}
return 1;
}
#if XOMBE_HAVE_ENCODER
static int run_enc(FILE *in, dump *t)
{
static xombe_enc_mem mem;
xombe_enc *e = xombe_enc_init(&mem, NULL);
int16_t pcm[XOMBE_FRAME];
uint8_t bits[7];
uint32_t call = 0;
int i;
xombe__enc_set_tap(e, tap, t);
t->half = 0;
for (;; call++) {
t->frame = call - XOMBE_ENC_DELAY;
if (io_read_pcm(in, pcm, XOMBE_FRAME) != XOMBE_FRAME)
break;
xombe_enc_frame_bits(e, pcm, NULL, bits, NULL);
}
for (i = 0; i < XOMBE_ENC_DELAY; i++, call++) {
t->frame = call - XOMBE_ENC_DELAY;
xombe_enc_frame_bits(e, NULL, NULL, bits, NULL);
}
return 1;
}
#endif
int main(int argc, char **argv)
{
dump t;
FILE *in;
int ok;
if (argc != 4 || (strcmp(argv[1], "dec") != 0 && strcmp(argv[1], "enc") != 0)) {
fprintf(stderr, "usage: trace_dump dec IN.amb OUT.trace | trace_dump enc IN.raw OUT.trace\n");
return 2;
}
#if !XOMBE_HAVE_ENCODER
if (strcmp(argv[1], "enc") == 0) {
fprintf(stderr, "trace_dump: built without the encoder\n");
return 2;
}
#endif
memset(&t, 0, sizeof(t));
if (!(in = io_open(argv[2], "rb")))
return 1;
t.path = argv[3];
if (!(t.f = io_open(argv[3], "wb")))
return 1;
#if XOMBE_HAVE_ENCODER
ok = strcmp(argv[1], "dec") == 0 ? run_dec(in, argv[2], &t) : run_enc(in, &t);
#else
ok = run_dec(in, argv[2], &t);
#endif
fclose(in);
ok &= io_close(t.f, argv[3]) && !t.failed;
return ok ? 0 : 1;
}