Include xombe source directly in repository instead of submodule

This commit is contained in:
root
2026-11-28 12:55:14 +01:00
parent d84d82617e
commit 3461bec633
303 changed files with 29260 additions and 4 deletions
+136
View File
@@ -0,0 +1,136 @@
"""paths, clip lists, file formats, and helpers shared by the scoring and checking scripts
import before numpy, it pins BLAS/OpenMP threads (unless the environment sets them) for the scripts' own pools
"""
import os
for _v in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS'):
os.environ.setdefault(_v, '1')
import hashlib
import math
import shlex
import shutil
import subprocess
import tempfile
import uuid
from concurrent.futures import ThreadPoolExecutor
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
VEC = os.path.join(ROOT, 'vectors')
E3V = os.path.join(VEC, 'e3')
E5V = os.path.join(VEC, 'e5')
E7V = os.path.join(VEC, 'e7')
BUILD = os.environ.get('XOMBE_BUILD', os.path.join(ROOT, 'build'))
E3IN = os.path.join(BUILD, 'e3in') # dithered E3 inputs, written by scripts/gen_inputs.py
FS = 8000
MAX_JOBS = 4
DEFAULT_DEC = shlex.quote(os.path.join(BUILD, 'xombe-dec')) + ' --conformance-noise {inp} {out}'
# E3 clips and the level dithers of their five inputs in dB, input k is round(10^(g/20)*x)
CLIPS = ['es1', 'es2', 'es3', 'sn10', 'ttsf', 'ttsc', 'ttsl']
DITHER_DB = [0.0, +0.025, -0.025, +0.05, -0.05]
# dual-tone IDs -> (high, low) Hz (DTMF, Knox 144..159, call progress 160..163), single tones are IDs 5..122 at
# 31.25 Hz x ID, must match src/common/tone_table.c
DUAL = {128: (1336, 941), 129: (1209, 697), 130: (1336, 697), 131: (1477, 697), 132: (1209, 770),
133: (1336, 770), 134: (1477, 770), 135: (1209, 852), 136: (1336, 852), 137: (1477, 852),
138: (1633, 697), 139: (1633, 770), 140: (1633, 852), 141: (1633, 941), 142: (1209, 941),
143: (1477, 941), 144: (1162, 820), 145: (1052, 606), 146: (1162, 606), 147: (1297, 606),
148: (1052, 672), 149: (1162, 672), 150: (1297, 672), 151: (1052, 743), 152: (1162, 743),
153: (1297, 743), 154: (1430, 606), 155: (1430, 672), 156: (1430, 743), 157: (1430, 820),
158: (1052, 820), 159: (1297, 820), 160: (440, 350), 161: (480, 440), 162: (620, 480), 163: (490, 350)}
TONE_IDS = set(range(5, 123)) | set(DUAL)
def read_amb(path):
"""frames of an .amb file as lists of 49 bits d0..d48"""
data = open(path, 'rb').read()
if data[:4] != b'.amb':
raise ValueError('%s: missing .amb header' % path)
if (len(data) - 4) % 8:
raise ValueError('%s: length is not 4 + 8*n bytes' % path)
frames = []
for off in range(4, len(data), 8):
fr = data[off:off + 8]
frames.append([(fr[1 + i // 8] >> (7 - i % 8)) & 1 for i in range(48)] + [fr[7] & 1])
return frames
def val(d, idx):
"""bits of d at positions idx, MSB first, as an integer"""
v = 0
for i in idx:
v = (v << 1) | d[i]
return v
def frame_class(d):
c = val(d, range(6))
return 'voice' if c < 60 else 'erasure' if c < 62 else 'silence' if c == 62 else 'tone'
def read_raw(path):
import numpy as np
return np.fromfile(path, '<i2').astype(float)
def decoder_id(cmd):
"""cache key for a decoder command: the command line and the executable's contents"""
h = hashlib.sha256(cmd.encode())
exe = shlex.split(cmd)[0]
if os.path.exists(exe):
h.update(open(exe, 'rb').read())
return h.hexdigest()[:24]
def decode_many(ambs, dec_cmd=DEFAULT_DEC, cache=None, jobs=MAX_JOBS):
"""decodes each .amb with dec_cmd (a shell command with {inp} and {out}), returns {amb: pcm}"""
tmpdir = None
if cache is None:
tmpdir = cache = tempfile.mkdtemp(prefix='xdec_')
os.makedirs(cache, exist_ok=True)
did = decoder_id(dec_cmd)
def one(amb):
key = hashlib.sha256((did + hashlib.sha256(open(amb, 'rb').read()).hexdigest()).encode()).hexdigest()[:24]
out = os.path.join(cache, key + '.raw')
if not os.path.exists(out):
tmp = out + '.%s.tmp' % uuid.uuid4().hex
subprocess.run(dec_cmd.format(inp=shlex.quote(os.path.abspath(amb)), out=shlex.quote(tmp)),
shell=True, check=True, capture_output=True)
os.replace(tmp, out)
return read_raw(out)
try:
with ThreadPoolExecutor(max(1, min(jobs, MAX_JOBS))) as ex:
pcm = list(ex.map(one, ambs))
finally:
if tmpdir:
shutil.rmtree(tmpdir, ignore_errors=True)
return dict(zip(ambs, pcm))
def p56(x, fs=FS):
"""active speech level in dBov (ITU-T P.56 method B)"""
import numpy as np
from scipy.signal import lfilter
x = np.asarray(x, float)
sq = float(np.sum(x * x))
if sq <= 0:
return -200.0
g = math.exp(-1 / (fs * 0.03))
q = lfilter([1 - g], [1, -g], lfilter([1 - g], [1, -g], np.abs(x)))
hang = int(0.2 * fs)
A, C = [], []
for j in range(16):
c = 2.0 ** j
cs = np.cumsum((q >= c).astype(float))
win = cs - np.concatenate([np.zeros(hang + 1), cs[:-(hang + 1)]])
n_act = int(np.sum(win > 0))
A.append(10 * math.log10(sq / n_act) if n_act else -200.0)
C.append(20 * math.log10(c))
d = np.array(A) - np.array(C) - 15.9
for j in range(1, 16):
if d[j - 1] >= 0 > d[j]:
t = d[j - 1] / (d[j - 1] - d[j])
return float(A[j - 1] + t * (A[j] - A[j - 1]) - 20 * math.log10(32768))
return float(A[0] - 20 * math.log10(32768))
+322
View File
@@ -0,0 +1,322 @@
#!/usr/bin/env python3
"""D-STAR conformance checks (make conformance-dstar) on in-repo data
usage: dstar_conf.py refs BUILD [--json OUT] stage comparisons against vectors/dstar (ctest dstar_*)
dstar_conf.py speech BUILD OUTDIR [--json] encode/decode and both transcoders on vectors/, scored
dstar_conf.py tones BUILD OUTDIR [--json] D-STAR tone frames on the E6 tone inputs, and transcoded
speech and tones read the dithered E3 inputs from --inputs DIR (scripts/gen_inputs.py, default BUILD/e3in)
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import CLIPS, E5V, FS, MAX_JOBS, read_raw
import argparse
import json
import re
import subprocess
from concurrent.futures import ProcessPoolExecutor
# speech: per path, the mean over the clips and the worst clip. limits are the measured values (the lower of
# float and q15) less 0.05 on mean PESQ and ViSQOL, 0.10 on the worst clip, 0.01 STOI, and 0.10 dB LSD. the scores
# against the input are low for every path (AMBE+2 itself: PESQ 2.45), */src rows score a transcoded decode
# against the source codec's own decode
SPEECH_LIMITS = {
# path: (mean PESQ, worst PESQ, mean ViSQOL, worst ViSQOL, mean STOI, mean LSD max)
'ambe2': None, # reference row
'dstar': (2.39, 1.72, 3.14, 1.18, 0.81, 7.71),
'dual': (2.38, 1.70, 3.13, 1.14, 0.81, 7.71),
'a2ds': (2.25, 1.69, 2.80, 1.24, 0.74, 8.29),
'dsa2': (2.21, 1.64, 2.88, 1.07, 0.77, 8.10),
'a2ds/src': (4.14, 3.82, 3.87, 3.23, 0.95, 2.74),
'dsa2/src': (3.99, 3.68, 4.04, 3.86, 0.94, 3.13),
}
# tones: frames from onset to the first tone frame and the level limit as E6. tones without a D-STAR code play as
# voice frames, their level limits are the measured worst case (float and q15) plus about 1 dB
TONE_ONSET, TONE_LEVEL_DB = 2, 1.0 # measured onset+0, 0.6 dB
VOICE_LEVEL_DB = 7.0 # measured 6.2 (knox_158)
XC_KNOX_LEVEL_DB = 10.5 # measured 9.7 (knox_146)
KNOX = range(144, 160)
def run(cmd, **kw):
r = subprocess.run(cmd, capture_output=True, text=True, **kw)
if r.returncode:
sys.exit('failed (%d): %s\n%s' % (r.returncode, ' '.join(cmd), r.stderr))
return r
def refs(build):
"""runs ctest's dstar_ tests verbosely and collects each comparison's agreement"""
r = subprocess.run(['ctest', '-V', '-R', '^dstar_', '-j', str(os.cpu_count() or 4)], cwd=build,
capture_output=True, text=True)
out = {}
col = re.compile(r'^(\d+): (\S+)\s+\S+\s+(\d+)/(\d+)\s+([\d.]+)%')
pcm = re.compile(r'^(\d+): .* (\d+) samples, max diff (\d+) LSB, rms diff ([\d.]+) LSB, ([\d.]+)% within (\d+) '
r'LSB, SNR ([-\d.inf]+) dB')
names, res = {}, {}
for line in r.stdout.splitlines():
m = re.match(r'^\s*\d+/\d+ Test\s+#(\d+): (\S+) \.+\s*(\*{3})?(\w+)', line)
if m:
names[m.group(1)] = m.group(2)
res[m.group(1)] = m.group(4) == 'Passed'
continue
m = col.match(line)
if m:
t = out.setdefault(m.group(1), {'cols': {}})
t['cols'][m.group(2)] = (int(m.group(3)), int(m.group(4)))
continue
m = pcm.match(line)
if m:
out.setdefault(m.group(1), {})['pcm'] = dict(samples=int(m.group(2)), max=int(m.group(3)),
rms=float(m.group(4)), within=float(m.group(5)),
lsb=int(m.group(6)), snr=m.group(7))
rows = []
for k in sorted(names, key=lambda k: names[k]):
n = names[k]
t = out.get(k, {})
row = dict(test=n, passed=res[k])
if t.get('cols'):
cols = t['cols']
worst = min(cols, key=lambda c: cols[c][0] / max(1, cols[c][1]))
row['records'] = max(v[1] for v in cols.values())
row['worst'] = (worst, 100.0 * cols[worst][0] / max(1, cols[worst][1]))
bc = [c for c in ('out', 'enc', 'd49', 'b') if c in cols]
if bc:
row['bytes'] = (bc[0], 100.0 * cols[bc[0]][0] / max(1, cols[bc[0]][1]))
row['bytes_n'] = cols[bc[0]]
if t.get('pcm'):
row['pcm'] = t['pcm']
rows.append(row)
print('%-34s %7s %-24s %-18s %s' % ('test', 'records', 'lowest column', 'frames/bytes', ''))
for w in rows:
if 'pcm' in w:
p = w['pcm']
desc = '%d samples, rms %.2f LSB, %.2f%% within %d LSB, SNR %s dB' % (p['samples'], p['rms'],
p['within'], p['lsb'], p['snr'])
print('%-34s %7s %-43s %s' % (w['test'], '', desc, 'ok' if w['passed'] else 'FAIL'))
elif 'records' in w:
print('%-34s %7d %-10s %8.3f%% %-18s %s' % (
w['test'], w['records'], w['worst'][0], w['worst'][1],
'%s %.3f%%' % w['bytes'] if 'bytes' in w else '-', 'ok' if w['passed'] else 'FAIL'))
else:
print('%-34s %7s %-43s %s' % (w['test'], '', 'exact file comparison', 'ok' if w['passed'] else 'FAIL'))
npass = sum(w['passed'] for w in rows)
agree = sum(w['bytes_n'][0] for w in rows if 'bytes_n' in w and 'selfcheck' not in w['test'])
total = sum(w['bytes_n'][1] for w in rows if 'bytes_n' in w and 'selfcheck' not in w['test'])
print('frames or records with equal output bytes/fields over the stage tests: %d/%d (%.3f%%)'
% (agree, total, 100.0 * agree / max(1, total)))
print('D-STAR refs: %d/%d tests pass' % (npass, len(rows)))
ok = r.returncode == 0 and npass == len(rows) and rows
return bool(ok), rows
def tool(build, name):
return os.path.join(build, name)
def make_paths(build, raw, od):
"""encodes, transcodes, and decodes one clip on every path, returns {path: (decoded, source-codec decoded)}"""
b = os.path.splitext(os.path.basename(raw))[0]
p = lambda ext: os.path.join(od, b + ext)
E, D, X = tool(build, 'xombe-enc'), tool(build, 'xombe-dec'), tool(build, 'xombe-xc')
run([E, '--air', raw, p('.r33')])
run([D, '--conformance-noise', '--air', p('.r33'), p('.a2.raw')])
run([E, '--dstar', raw, p('.dstar')])
run([D, '--conformance-noise', '--dstar', p('.dstar'), p('.ds.raw')])
run([E, '--dual', p('.dual.dstar'), raw, p('.dual.amb')])
run([D, '--conformance-noise', '--dstar', p('.dual.dstar'), p('.dual.raw')])
run([X, p('.r33'), p('.a2ds.dstar')])
run([D, '--conformance-noise', '--dstar', p('.a2ds.dstar'), p('.a2ds.raw')])
run([X, '--reverse', p('.dstar'), p('.dsa2.r33')])
run([D, '--conformance-noise', '--air', p('.dsa2.r33'), p('.dsa2.raw')])
return {'ambe2': p('.a2.raw'), 'dstar': p('.ds.raw'), 'dual': p('.dual.raw'), 'a2ds': p('.a2ds.raw'),
'dsa2': p('.dsa2.raw')}, {'a2ds': p('.a2.raw'), 'dsa2': p('.ds.raw')}
def score_one(args):
ref, deg = args
import score as S
r, d, lag = S.align(read_raw(ref), read_raw(deg))
o = S.score(r, d)
o['lag'] = lag
return o
def speech(build, od, clips):
os.makedirs(od, exist_ok=True)
jobs, keys = [], []
for raw in clips:
dec, src = make_paths(build, raw, od)
for k, f in dec.items():
jobs.append((raw, f))
keys.append((os.path.basename(raw), k))
for k, f in src.items():
jobs.append((f, dec[k]))
keys.append((os.path.basename(raw), k + '/src'))
with ProcessPoolExecutor(MAX_JOBS) as ex:
res = list(ex.map(score_one, jobs))
table = {}
for (clip, k), o in zip(keys, res):
table.setdefault(k, {})[clip] = o
ok = True
summary = {}
print('%-10s %6s %6s %7s %7s %6s %6s %s' % ('path', 'PESQ', 'min', 'ViSQOL', 'min', 'STOI', 'LSD', ''))
for k in ['ambe2', 'dstar', 'dual', 'a2ds', 'dsa2', 'a2ds/src', 'dsa2/src']:
rows = list(table[k].values())
if any(r.get('visqol_speech') is None for r in rows):
print('%-10s ViSQOL failed' % k)
ok = False
continue
mp = sum(r['pesq_nb'] for r in rows) / len(rows)
np_ = min(r['pesq_nb'] for r in rows)
mv = sum(r['visqol_speech'] for r in rows) / len(rows)
nv = min(r['visqol_speech'] for r in rows)
ms = sum(r['stoi'] for r in rows) / len(rows)
ml = sum(r['lsd_db'] for r in rows) / len(rows)
lim = SPEECH_LIMITS.get(k)
good = lim is None or (mp >= lim[0] and np_ >= lim[1] and mv >= lim[2] and nv >= lim[3] and ms >= lim[4]
and ml <= lim[5])
ok &= good
summary[k] = dict(pesq=mp, pesq_min=np_, visqol=mv, visqol_min=nv, stoi=ms, lsd=ml)
print('%-10s %6.3f %6.3f %7.3f %7.3f %6.3f %6.3f %s' % (
k, mp, np_, mv, nv, ms, ml, 'informative' if lim is None else 'ok' if good else 'FAIL'))
print('paths: ambe2 AMBE+2 encode/decode, dstar D-STAR only, dual the D-STAR output of the dual encoder,')
print(' a2ds AMBE+2 -> xombe-xc -> D-STAR decode, dsa2 D-STAR -> xombe-xc --reverse -> AMBE+2 decode,')
print(' */src the transcoded decode against the source codec\'s decode')
print('%d clips, scored against the encoder input (*/src: the source decode); limits (mean PESQ, worst PESQ, '
'mean ViSQOL, worst ViSQOL, mean STOI, mean LSD):' % len(clips))
for k, lim in SPEECH_LIMITS.items():
if lim:
print(' %-8s >= %.2f, >= %.2f, >= %.2f, >= %.2f, >= %.2f, <= %.2f' % ((k,) + lim))
return ok, dict(summary=summary, clips=table)
def tone_ids(build, dstar):
out = run([tool(build, 'dstar_dump_fec'), '--ids', dstar]).stdout.split('\n')
return [int(l.split()[2]) if l.split()[1] == 'tone' else None for l in out if l.strip()]
def ds163_case(od):
"""D-STAR detects tone 163 as 340 + 550 Hz and plays AMBE+2's 350 + 490 Hz"""
import numpy as np
n = np.arange(int(0.4 * FS))
A = 32768 * 10 ** (-20 / 20)
rng = np.random.default_rng(20261024)
tone = sum(A * np.cos(2 * np.pi * f / FS * n + rng.uniform(0, 2 * np.pi)) for f in (550.0, 340.0))
x = np.concatenate([np.zeros(FS // 2), tone, np.zeros(int(0.3 * FS))])
np.clip(np.round(x), -32768, 32767).astype('<i2').tofile(os.path.join(od, 'ds_163.raw'))
return dict(name='ds_163', file='ds_163.raw', segments=[dict(start=FS // 2, length=len(n), id=163,
freqs=[550.0, 340.0], play=[490.0, 350.0])])
def tones(build, od, clips):
import e6
os.makedirs(od, exist_ok=True)
e6.gen(od)
cases = json.load(open(os.path.join(od, 'cases.json'))) + [ds163_case(od)]
E, D, X = tool(build, 'xombe-enc'), tool(build, 'xombe-dec'), tool(build, 'xombe-xc')
ok = True
n_ok = 0
rows = []
fmt = lambda e: ' '.join('%+5.2f' % v if v is not None else ' n/a' for v in e)
print('%-14s %4s %-6s %-22s %-12s %-12s %s' % ('case', 'ID', 'kind', 'D-STAR frames', 'level dB', 'a2ds dB',
''))
for c in cases:
name = c['name']
raw = os.path.join(od, c['file'])
s = c['segments'][0]
kind = 'ds163' if name == 'ds_163' else 'voice' if s['id'] in KNOX or s['id'] == 163 else 'tone'
ds, r33, xds = (os.path.join(od, name + e) for e in ('.dstar', '.r33', '.xc.dstar'))
run([E, '--dstar', raw, ds])
run([D, '--conformance-noise', '--dstar', ds, ds + '.raw'])
x, y = read_raw(raw), read_raw(ds + '.raw')
ids = tone_ids(build, ds)
on_f, end_f = s['start'] // 160, min(len(ids), (s['start'] + s['length']) // 160 + 10)
seen = sorted({i for i in ids[on_f:end_f] if i is not None})
first = next((i for i in range(on_f, end_f) if ids[i] == s['id']), None)
if kind == 'voice':
ok_id = not seen
desc = 'voice frames' if ok_id else 'tone IDs %s' % seen
else:
ok_id = first is not None and first - on_f <= TONE_ONSET and seen == [s['id']]
desc = 'none' if first is None else 'onset+%d' % (first - on_f)
if seen != [s['id']]:
desc += ' IDs %s' % seen
def lev(sig):
"""level errors of the decoded components"""
si = e6.steady(x, s['start'] - 160, s['start'] + s['length'] + 160)
so = e6.steady(sig, s['start'] - 160, min(len(sig), s['start'] + s['length'] + 2400))
if not si or not so:
return [None]
lin, _ = e6.fit_levels(x[si[0]:si[0] + si[1]], s['freqs'])
play = s.get('play', s['freqs'])
lout, _ = e6.fit_levels(sig[so[0]:so[0] + so[1]], play)
return [o - i for o, i in zip(lout, lin)]
lim = VOICE_LEVEL_DB if kind == 'voice' else TONE_LEVEL_DB
err = lev(y)
good = ok_id and None not in err and all(abs(e) <= lim for e in err)
xdesc, xerr = '-', []
if kind != 'ds163':
# from AMBE+2: tone frames keep the ID, Knox tones become voice frames
run([E, '--air', raw, r33])
run([X, r33, xds])
run([D, '--conformance-noise', '--dstar', xds, xds + '.raw'])
xids = tone_ids(build, xds)
xseen = sorted({i for i in xids[on_f:end_f] if i is not None})
xknox = s['id'] in KNOX
ok_xid = (not xseen) if xknox else xseen == [s['id']]
xerr = lev(read_raw(xds + '.raw'))
xlim = XC_KNOX_LEVEL_DB if xknox else TONE_LEVEL_DB
good &= ok_xid and None not in xerr and all(abs(e) <= xlim for e in xerr)
xdesc = fmt(xerr) + ('' if ok_xid else ' IDs %s' % xseen)
n_ok += good
ok &= good
rows.append(dict(case=name, id=s['id'], kind=kind, first=None if first is None else first - on_f, ids=seen,
err=err, xc_err=xerr, ok=good))
print('%-14s %4d %-6s %-22s %-12s %-12s %s' % (name, s['id'], kind, desc, fmt(err), xdesc,
'ok' if good else 'FAIL'))
print('D-STAR tone cases: %d/%d pass' % (n_ok, len(cases)))
print(' tone: D-STAR tone frame of the ID within %d frames of onset, no other ID, level +/-%.1f dB, '
'and the same from AMBE+2 (a2ds)' % (TONE_ONSET, TONE_LEVEL_DB))
print(' voice: Knox 144..159 and AMBE+2\'s 163 (350 + 490 Hz) have no D-STAR tone code: voice frames, levels '
'+/-%.1f dB, Knox from AMBE+2 +/-%.1f dB' % (VOICE_LEVEL_DB, XC_KNOX_LEVEL_DB))
print(' ds163: 340 + 550 Hz is D-STAR\'s tone 163, played as 350 + 490 Hz')
bad = []
for raw in clips:
ds = os.path.join(od, 'speech_' + os.path.basename(raw) + '.dstar')
run([E, '--dstar', raw, ds])
n = sum(i is not None for i in tone_ids(build, ds))
if n:
bad.append((os.path.basename(raw), n))
print('D-STAR speech: %d clips, %s' % (len(clips), 'no tone frames' if not bad else 'tone frames in %s' % bad))
ok &= not bad
return ok, dict(cases=rows, speech_tone_frames=bad)
def main():
ap = argparse.ArgumentParser(description='D-STAR conformance')
ap.add_argument('cmd', choices=['refs', 'speech', 'tones'])
ap.add_argument('build')
ap.add_argument('outdir', nargs='?')
ap.add_argument('--json')
ap.add_argument('--inputs')
a = ap.parse_args()
build = os.path.abspath(a.build)
inputs = a.inputs or os.path.join(build, 'e3in')
clips = [os.path.join(inputs, c + '.d0.raw') for c in CLIPS] + \
[os.path.join(E5V, c + '.raw') for c in ('low5', 'hp5')]
if a.cmd == 'refs':
ok, data = refs(build)
elif a.cmd == 'speech':
ok, data = speech(build, a.outdir, clips)
else:
ok, data = tones(build, a.outdir, clips)
if a.json:
json.dump(dict(ok=ok, data=data), open(a.json, 'w'), indent=1)
print('D-STAR %s: %s' % (a.cmd, 'PASS' if ok else 'FAIL'))
return 0 if ok else 1
if __name__ == '__main__':
sys.exit(main())
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
import argparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import ROOT, TONE_IDS, read_amb, val
FEC_REF = os.path.join(ROOT, 'vectors', 'fec', 'fec_encode_vectors.txt')
B0 = [0, 1, 2, 3, 37, 38, 39]
B1 = [4, 5, 6, 7, 35]
def check_frame(d):
c = val(d, range(6))
bad = []
if c in (60, 61):
return 'erasure', None, None, ['erasure class (d0..d5 = %s) must not be emitted' % format(c, '06b')]
if c == 63:
ids = [val(d, range(s, s + 8)) for s in (12, 20, 28, 36)]
if len(set(ids)) != 1:
bad.append('tone ID copies differ %s' % ids)
if ids[0] not in TONE_IDS:
bad.append('tone ID %d not in {5..122, 128..143, 160..162}' % ids[0])
if any(d[45:49]):
bad.append('tone d45..d48 != 0')
return 'tone', None, ids[0], bad
b0, b1 = val(d, B0), val(d, B1)
if c == 62:
if b0 != 124:
bad.append('silence b0 = %d (expected 124)' % b0)
if b1 != 16:
bad.append('silence b1 = %d (expected 16)' % b1)
return 'silence', b0, b1, bad
if b0 > 119:
bad.append('voice b0 = %d > 119' % b0)
if 18 <= b1 <= 31:
bad.append('voice b1 = %d (pulse code)' % b1)
return 'voice', b0, b1, bad
def check_fec(path):
def load(p):
m = {}
for line in open(p):
line = line.split('#')[0].split()
if len(line) >= 2:
m[line[0].upper()] = line[1].upper()
return m
ref, cand = load(FEC_REF), load(path)
miss = [k for k in ref if k not in cand]
wrong = [k for k in ref if k in cand and cand[k] != ref[k]]
return len(ref), miss, wrong
def main():
ap = argparse.ArgumentParser(description='E1 bitstream validity')
ap.add_argument('files', nargs='*')
ap.add_argument('--input', help='raw input: also check one frame per 160 samples')
ap.add_argument('--fec', help='candidate FEC pairs in the fec_encode_vectors.txt format')
ap.add_argument('--frames', action='store_true')
ap.add_argument('--quiet', action='store_true')
a = ap.parse_args()
ok = True
for f in a.files:
frames = read_amb(f)
counts, nbad, tones = {}, 0, {}
for n, d in enumerate(frames):
cls, _, x, bad = check_frame(d)
counts[cls] = counts.get(cls, 0) + 1
if cls == 'tone':
tones[x] = tones.get(x, 0) + 1
if bad:
nbad += 1
if not a.quiet and (nbad <= 20 or a.frames):
print(' %s frame %d: %s' % (os.path.basename(f), n, '; '.join(bad)))
line = '%s: %d frames (%s)' % (f, len(frames), ', '.join('%s %d' % kv for kv in sorted(counts.items())))
if tones:
line += '; tone IDs ' + ', '.join('%d×%d' % kv for kv in sorted(tones.items()))
if a.input:
want = os.path.getsize(a.input) // 320
if len(frames) != want:
line += '; FRAME COUNT %d != %d' % (len(frames), want)
nbad += 1
print(line + ('; E1 PASS' if not nbad else '; E1 FAIL (%d frames)' % nbad))
ok &= not nbad
if a.fec:
n, miss, wrong = check_fec(a.fec)
good = not miss and not wrong
print('FEC: %d reference pairs, %d missing, %d wrong; %s' % (n, len(miss), len(wrong), 'PASS' if good else 'FAIL'))
ok &= good
return 0 if ok else 1
if __name__ == '__main__':
sys.exit(main())
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
import os
import sys
import argparse
import hashlib
import json
import shlex
import subprocess
import warnings
from concurrent.futures import ProcessPoolExecutor
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from common import BUILD, CLIPS, DEFAULT_DEC, DITHER_DB as DB, E3V, MAX_JOBS, decoder_id
LIM_CLIP, LIM_MEAN, LIM_VQ = -0.30, -0.08, -0.20
def sha(*parts):
h = hashlib.sha256()
for p in parts:
h.update(p if isinstance(p, bytes) else str(p).encode())
h.update(b'\0')
return h.hexdigest()[:24]
def score_pair(orig, deg, visqol):
import score as S
from pesq import pesq
r, d, lag = S.align(S.load(orig), S.load(deg))
o = {'pesq_nb': float(pesq(S.FS, r / 32768, d / 32768, 'nb')), 'lag': lag}
if visqol:
from scipy.signal import resample_poly
from visqol import VisqolApi
api = VisqolApi()
api.create(mode='speech')
with warnings.catch_warnings():
warnings.simplefilter('ignore')
o['visqol_speech'] = float(api.measure_from_arrays(resample_poly(r, 2, 1), resample_poly(d, 2, 1),
16000).moslqo)
return o
def job(args):
amb, orig, visqol, dec_cmd, dec_id, cache = args
key = sha(dec_id, open(amb, 'rb').read(), open(orig, 'rb').read(), visqol)
cf = os.path.join(cache, key + '.json')
if os.path.exists(cf):
return json.load(open(cf))
raw = os.path.join(cache, key + '.raw')
if not os.path.exists(raw):
tmp = raw + '.%d.tmp' % os.getpid()
subprocess.run(dec_cmd.format(inp=shlex.quote(amb), out=shlex.quote(tmp)), shell=True, check=True,
capture_output=True)
os.replace(tmp, raw)
o = score_pair(orig, raw, visqol)
tmp = cf + '.%d.tmp' % os.getpid()
json.dump(o, open(tmp, 'w'))
os.replace(tmp, cf)
return o
def main():
ap = argparse.ArgumentParser(description='E3 five-dither perceptual comparison against the reference encoder')
ap.add_argument('cand_dir')
ap.add_argument('--clips', default=','.join(CLIPS))
ap.add_argument('--jobs', type=int, default=MAX_JOBS)
ap.add_argument('--json')
ap.add_argument('--cand-pattern', default='{clip}.d{k}.amb')
ap.add_argument('--decoder', default=DEFAULT_DEC)
ap.add_argument('--vectors', default=E3V)
ap.add_argument('--cache', default=os.path.join(BUILD, 'e3cache'))
ap.add_argument('--quiet', action='store_true')
a = ap.parse_args()
a.jobs = max(1, min(a.jobs, MAX_JOBS))
clips = [c for c in a.clips.split(',') if c]
os.makedirs(a.cache, exist_ok=True)
dec_id = decoder_id(a.decoder)
tasks = []
for c in clips:
orig = os.path.join(a.vectors, c + '_orig.raw')
for k in range(len(DB)):
ref = os.path.join(a.vectors, '%s.ref.d%d.amb' % (c, k))
cand = os.path.join(a.cand_dir, a.cand_pattern.format(clip=c, k=k))
for p in (orig, ref, cand):
if not os.path.exists(p):
sys.exit('missing: ' + p)
for who, amb in (('ref', ref), ('cand', cand)):
tasks.append(((c, k, who), (os.path.abspath(amb), orig, k == 0, a.decoder, dec_id, a.cache)))
res = {}
with ProcessPoolExecutor(a.jobs) as ex:
for (tag, _), o in zip(tasks, ex.map(job, [t[1] for t in tasks])):
res[tag] = o
if not a.quiet:
print(' %-5s d%d %-4s PESQ %.3f%s' % (tag[0], tag[1], tag[2], o['pesq_nb'],
(' ViSQOL %.3f' % o['visqol_speech']) if 'visqol_speech' in o else ''),
file=sys.stderr, flush=True)
out = {'decoder': a.decoder, 'dithers_db': DB, 'clips': {}}
print('E3: PESQ-NB vs undithered original, decoder = %s' % a.decoder)
print('dither k: ' + ' '.join('%+7.3f' % g for g in DB) + ' (dB)')
print('%-5s %-4s ' % ('clip', 'enc') + ' '.join(' d%d ' % k for k in range(len(DB))) +
' mean ΔPESQ ViSQOL ΔViSQOL')
dps, dvs, fails = [], [], []
for c in clips:
row = {}
for who in ('ref', 'cand'):
p = [res[(c, k, who)]['pesq_nb'] for k in range(len(DB))]
row[who] = {'pesq': p, 'pesq_mean': sum(p) / len(p), 'visqol': res[(c, 0, who)]['visqol_speech']}
dp = row['cand']['pesq_mean'] - row['ref']['pesq_mean']
dv = row['cand']['visqol'] - row['ref']['visqol']
row['d_pesq'], row['d_visqol'] = dp, dv
row['d_pesq_per_dither'] = [x - y for x, y in zip(row['cand']['pesq'], row['ref']['pesq'])]
dps.append(dp)
dvs.append(dv)
ok = dp >= LIM_CLIP
if not ok:
fails.append('%s ΔPESQ %.3f < %.2f' % (c, dp, LIM_CLIP))
for who in ('ref', 'cand'):
r = row[who]
print('%-5s %-4s ' % (c if who == 'ref' else '', who) + ' '.join('%7.3f' % x for x in r['pesq']) +
' %7.3f' % r['pesq_mean'] + (' %+.3f%s' % (dp, '' if ok else '!') if who == 'cand' else ' ') +
' %7.3f' % r['visqol'] + (' %+.3f' % dv if who == 'cand' else ''))
print('%-5s %-4s ' % ('', 'Δ') + ' '.join('%+7.3f' % x for x in row['d_pesq_per_dither']))
out['clips'][c] = row
mp, mv = sum(dps) / len(dps), sum(dvs) / len(dvs)
if mp < LIM_MEAN:
fails.append('mean ΔPESQ %.3f < %.2f' % (mp, LIM_MEAN))
if mv < LIM_VQ:
fails.append('mean ΔViSQOL %.3f < %.2f' % (mv, LIM_VQ))
rm = sum(out['clips'][c]['ref']['pesq_mean'] for c in clips) / len(clips)
cm = sum(out['clips'][c]['cand']['pesq_mean'] for c in clips) / len(clips)
print('mean over %d clips: ref %.3f cand %.3f ΔPESQ %+.3f ΔViSQOL %+.3f' % (len(clips), rm, cm, mp, mv))
print('thresholds: per clip ΔPESQ >= %.2f, mean ΔPESQ >= %.2f, mean ΔViSQOL >= %.2f' % (LIM_CLIP, LIM_MEAN, LIM_VQ))
full = set(clips) == set(CLIPS)
print('E3%s: ' % ('' if full else ' (informative, partial clip set)') +
('PASS' if not fails else 'FAIL (' + '; '.join(fails) + ')'))
out.update(mean_d_pesq=mp, mean_d_visqol=mv, pass_=not fails and full, fails=fails)
if a.json:
json.dump(out, open(a.json, 'w'), indent=1)
return 0 if not fails else 1
if __name__ == '__main__':
sys.exit(main())
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import CLIPS, DEFAULT_DEC, E3V, MAX_JOBS, decode_many, p56, read_raw
import argparse
import json
LIM_E4 = 1.5
def main():
ap = argparse.ArgumentParser(description='E4 active speech level (ITU-T P.56 method B), g = 0 inputs')
ap.add_argument('cand_dir')
ap.add_argument('--clips', default=','.join(CLIPS))
ap.add_argument('--cand-pattern', default='{clip}.d0.amb')
ap.add_argument('--decoder', default=DEFAULT_DEC)
ap.add_argument('--vectors', default=E3V)
ap.add_argument('--cache')
ap.add_argument('--jobs', type=int, default=MAX_JOBS)
ap.add_argument('--json')
a = ap.parse_args()
clips = [c for c in a.clips.split(',') if c]
pairs = []
for c in clips:
cand = os.path.join(a.cand_dir, a.cand_pattern.format(clip=c, k=0))
ref = os.path.join(a.vectors, c + '.ref.d0.amb')
for p in (cand, ref, os.path.join(a.vectors, c + '_orig.raw')):
if not os.path.exists(p):
sys.exit('missing: ' + p)
pairs.append((c, cand, ref))
pcm = decode_many([p for _, c_, r_ in pairs for p in (c_, r_)], a.decoder, a.cache, a.jobs)
print('E4: active speech level, decoder = %s' % a.decoder)
print('%-6s %9s %9s %9s %7s' % ('clip', 'cand', 'ref', 'orig', 'diff'))
out, fails = {}, []
for c, cand, ref in pairs:
lc, lr = p56(pcm[cand]), p56(pcm[ref])
lo = p56(read_raw(os.path.join(a.vectors, c + '_orig.raw')))
ok = abs(lc - lr) <= LIM_E4
if not ok:
fails.append('%s %+.2f dB' % (c, lc - lr))
out[c] = dict(cand=lc, ref=lr, orig=lo, diff=lc - lr, ok=ok)
print('%-6s %9.2f %9.2f %9.2f %+7.2f %s' % (c, lc, lr, lo, lc - lr, '' if ok else 'FAIL'))
print('levels in dBov; limit |cand - ref| <= %.1f dB' % LIM_E4)
print('E4: ' + ('PASS' if not fails else 'FAIL (' + '; '.join(fails) + ')'))
if a.json:
json.dump(dict(clips=out, pass_=not fails, fails=fails), open(a.json, 'w'), indent=1)
return 0 if not fails else 1
if __name__ == '__main__':
sys.exit(main())
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import (DEFAULT_DEC, E3IN, E3V, E5V, FS, MAX_JOBS, decode_many, frame_class, p56, read_amb,
read_raw)
import argparse
import json
import math
import numpy as np
CLEAN_CLIPS = ['es1', 'es2', 'es3', 'ttsf', 'ttsc', 'ttsl']
LIM_CLIP = -0.30
LIM_CN_LEVEL, LIM_CN_SHAPE, CN_RANGE = 3.0, 4.0, 30.0
CLIP_MARGIN, CLIP_SKIP = 15.0, 3
def classes(amb):
return [frame_class(d) for d in read_amb(amb)]
def cn_stats(pcm, cls, min_run=5, trim=2):
from scipy.signal import welch
first_v = cls.index('voice') if 'voice' in cls else len(cls)
segs, i = [], first_v
while i < len(cls):
if cls[i] != 'silence':
i += 1
continue
j = i
while j < len(cls) and cls[j] == 'silence':
j += 1
if j - i >= min_run:
segs.append(pcm[160 * (i + trim):160 * (j - trim)])
i = j
segs = [s for s in segs if len(s)]
if not segs:
return None
x = np.concatenate(segs)
f, P = welch(x, FS, nperseg=256)
bands = np.array([10 * math.log10(np.sum(P[(f >= 500 * b) & (f < 500 * (b + 1))]) + 1e-12) for b in range(8)])
return dict(frames=len(x) // 160, level=10 * math.log10(np.mean(x * x) + 1e-12), bands=bands)
def pesq_vs(orig, deg):
import score as S
from pesq import pesq
r, d, _ = S.align(orig, deg)
return float(pesq(FS, r / 32768, d / 32768, 'nb'))
def clipped_frames(x, cls, tol=1):
al = p56(x)
n = min(len(cls), len(x) // 160)
fr = x[:n * 160].reshape(-1, 160)
loud = 10 * np.log10(np.mean(fr ** 2, 1) + 1e-9) - 20 * math.log10(32768) > al - CLIP_MARGIN
return al, [i for i in range(CLIP_SKIP, n) if cls[i] == 'silence' and loud[max(0, i - tol):i + tol + 1].all()]
def main():
ap = argparse.ArgumentParser(description='E5 noise clips, comfort noise and clipped speech')
ap.add_argument('e3_cand')
ap.add_argument('--e5-cand', help='encodes of vectors/e5/low5.raw and hp5.raw')
ap.add_argument('--cand-pattern', default='{clip}.d0.amb')
ap.add_argument('--e5-pattern', default='{name}.amb')
ap.add_argument('--inputs', default=E3IN, help='dithered E3 inputs from scripts/gen_inputs.py')
ap.add_argument('--ref-mode', action='store_true')
ap.add_argument('--decoder', default=DEFAULT_DEC)
ap.add_argument('--cache')
ap.add_argument('--jobs', type=int, default=MAX_JOBS)
ap.add_argument('--json')
a = ap.parse_args()
if a.ref_mode:
a.e3_cand, a.cand_pattern, a.e5_cand, a.e5_pattern = E3V, '{clip}.ref.d0.amb', E5V, '{name}.ref.amb'
noise = [('sn10', os.path.join(a.e3_cand, a.cand_pattern.format(clip='sn10', k=0)),
os.path.join(E3V, 'sn10.ref.d0.amb'), os.path.join(E3V, 'sn10_orig.raw'))]
if a.e5_cand:
for nm in ('low5', 'hp5'):
noise.append((nm, os.path.join(a.e5_cand, a.e5_pattern.format(name=nm)),
os.path.join(E5V, nm + '.ref.amb'), os.path.join(E5V, nm + '.raw')))
for _, c, r, o in noise:
for p in (c, r, o):
if not os.path.exists(p):
sys.exit('missing: ' + p)
pcm = decode_many([p for _, c, r, _ in noise for p in (c, r)], a.decoder, a.cache, a.jobs)
clean = read_raw(os.path.join(E5V, 'es1_lead0.5s.raw'))
out, fails = {'noise': {}, 'clipped': {}}, []
print('E5: decoder = %s, g = 0 input' % a.decoder)
print('%-5s %22s %22s %9s %9s %9s %s' % ('clip', 'PESQ noisy c/r/Δ', 'PESQ clean c/r/Δ', 'CN frames',
'CN level', 'shape', 'band diffs counted (dB)'))
for nm, c, r, o in noise:
noisy = read_raw(o)
pn = (pesq_vs(noisy, pcm[c]), pesq_vs(noisy, pcm[r]))
pc = (pesq_vs(clean, pcm[c]), pesq_vs(clean, pcm[r]))
res = dict(pesq_noisy=[pn[0], pn[1], pn[0] - pn[1]], pesq_clean=[pc[0], pc[1], pc[0] - pc[1]])
if pn[0] - pn[1] < LIM_CLIP:
fails.append('%s ΔPESQ vs noisy %.3f' % (nm, pn[0] - pn[1]))
cm, cr = cn_stats(pcm[c], classes(c)), cn_stats(pcm[r], classes(r))
cn_txt = 'no comfort noise in %s' % ('candidate' if cr else 'reference') if not (cm and cr) else ''
if cm and cr:
keep = cr['bands'] >= cr['bands'].max() - CN_RANGE
dl = cm['level'] - cr['level']
shape = (cm['bands'] - cr['bands']) - dl
sm = float(np.max(np.abs(shape[keep])))
res.update(cn_frames=[cm['frames'], cr['frames']], cn_level_diff=dl, band_shape=shape.tolist(),
bands_counted=keep.tolist(), shape_dev_max=sm)
if abs(dl) > LIM_CN_LEVEL:
fails.append('%s comfort-noise level %+.2f dB' % (nm, dl))
if sm > LIM_CN_SHAPE:
fails.append('%s comfort-noise shape %.2f dB' % (nm, sm))
cn_txt = '%4d/%-4d %+9.2f %9.2f %s' % (cm['frames'], cr['frames'], dl, sm,
' '.join(('%+.1f' % v) if k else ' .' for v, k in zip(shape, keep)))
elif cr and not cm:
fails.append('%s: candidate sends no comfort noise' % nm)
out['noise'][nm] = res
print('%-5s %6.3f/%5.3f/%+6.3f %6.3f/%5.3f/%+6.3f %s' % (nm, pn[0], pn[1], pn[0] - pn[1], pc[0], pc[1],
pc[0] - pc[1], cn_txt))
print(' limits: ΔPESQ vs noisy >= %.2f; CN level within ±%.0f dB; shape within ±%.0f dB over bands within'
' %.0f dB of the reference\'s strongest' % (LIM_CLIP, LIM_CN_LEVEL, LIM_CN_SHAPE, CN_RANGE))
print('Clipped speech: silence frames n >= %d with input frames n-1..n+1 within %.0f dB of the active level'
% (CLIP_SKIP, CLIP_MARGIN))
tot_c = tot_r = 0
for c in CLEAN_CLIPS:
amb = os.path.join(a.e3_cand, a.cand_pattern.format(clip=c, k=0))
if not os.path.exists(amb):
sys.exit('missing: ' + amb)
cls, cls_r = classes(amb), classes(os.path.join(E3V, c + '.ref.d0.amb'))
x = read_raw(os.path.join(a.inputs, c + '.d0.raw'))
al, bad = clipped_frames(x, cls)
_, bad_r = clipped_frames(x, cls_r)
tot_c += len(bad)
tot_r += len(bad_r)
out['clipped'][c] = dict(cand=bad, ref=bad_r)
print(' %-5s active %6.1f dBov silence frames %3d clipped: cand %d %s ref %d' %
(c, al, cls.count('silence'), len(bad), bad[:10] if bad else '', len(bad_r)))
print(' total clipped: cand %d, ref %d (limit: cand <= ref)' % (tot_c, tot_r))
if tot_c > tot_r:
fails.append('clipped speech frames %d > reference %d' % (tot_c, tot_r))
print('E5: ' + ('PASS' if not fails else 'FAIL (' + '; '.join(fails) + ')') +
('' if a.e5_cand else ' [low5/hp5 not checked]'))
if a.json:
json.dump(dict(out, pass_=not fails, fails=fails), open(a.json, 'w'), indent=1)
return 0 if not fails else 1
if __name__ == '__main__':
sys.exit(main())
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import (DEFAULT_DEC, DUAL, E7V, FS, MAX_JOBS, decode_many, frame_class, read_amb,
read_raw, val)
import argparse
import glob
import json
import math
import numpy as np
DTMF_NAMES = '0123456789ABCD*#'
LIM_LEVEL, LIM_ONSET, SEARCH = 1.0, 2, 0.05
PKG_CASE = dict(name='tones', file=os.path.join(E7V, 'tones.raw'), segments=[
dict(start=2400, length=4800, id=32, freqs=[1000.0]),
dict(start=9600, length=4800, id=133, freqs=[1336.0, 770.0]),
dict(start=16800, length=4800, id=161, freqs=[480.0, 440.0])])
def gen(outdir):
os.makedirs(outdir, exist_ok=True)
cases = []
specs = [('dtmf_%s' % ('star' if ch == '*' else 'hash' if ch == '#' else ch), 128 + i, DUAL[128 + i], -16.0)
for i, ch in enumerate(DTMF_NAMES)]
specs += [('knox_%d' % t, t, DUAL[t], -20.0) for t in range(144, 160)]
specs += [('cp_%d' % t, t, DUAL[t], -20.0) for t in (160, 161, 162, 163)]
specs += [('tone_%d_%d' % (f, -lev), int(round(f / 31.25)), (float(f),), float(lev))
for f in (300, 1000, 2000, 3000) for lev in (-6, -16, -26, -36, -46)]
rng = np.random.default_rng(20261019)
for name, tid, freqs, lev in specs:
n = np.arange(int(0.4 * FS))
A = 32768 * 10 ** (lev / 20)
tone = sum(A * np.cos(2 * np.pi * f / FS * n + rng.uniform(0, 2 * np.pi)) for f in freqs)
x = np.concatenate([np.zeros(FS // 2), tone, np.zeros(int(0.3 * FS))])
x = np.clip(np.round(x), -32768, 32767).astype('<i2')
x.tofile(os.path.join(outdir, name + '.raw'))
cases.append(dict(name=name, file=name + '.raw', segments=[
dict(start=FS // 2, length=len(n), id=tid, freqs=[float(f) for f in freqs], level_dbfs=lev)]))
json.dump(cases, open(os.path.join(outdir, 'cases.json'), 'w'), indent=1)
print('%d E6 inputs written to %s' % (len(cases), outdir))
def fit_levels(seg, freqs):
seg = np.asarray(seg, float)
t = np.arange(len(seg))
def fit(fs_):
A = np.stack([g(2 * np.pi * f / FS * t) for f in fs_ for g in (np.cos, np.sin)], 1)
c, *_ = np.linalg.lstsq(A, seg, rcond=None)
return [math.hypot(c[2 * i], c[2 * i + 1]) for i in range(len(fs_))], float(np.sum((seg - A @ c) ** 2))
best = list(freqs)
for i in range(len(freqs)):
cands = freqs[i] * (1 + np.linspace(-SEARCH, SEARCH, 401))
errs = []
for f in cands:
fs_ = list(best)
fs_[i] = f
errs.append(fit(fs_)[1])
best[i] = float(cands[int(np.argmin(errs))])
amps, _ = fit(best)
return [20 * math.log10(a / 32768 + 1e-12) for a in amps], best
def steady(x, lo, hi):
env = np.convolve(np.asarray(x[lo:hi], float) ** 2, np.ones(160) / 160, 'same')
if not len(env) or env.max() <= 0:
return None
on = np.where(env > 0.25 * env.max())[0]
st = on[0] + 800
if on[-1] - st <= 960:
return None
return lo + st, min(1600, on[-1] - st - 160)
def tone_ids(amb):
return [val(d, range(12, 20)) if frame_class(d) == 'tone' else None for d in read_amb(amb)]
def check(cases, cand_dir, pattern, dec, cache, jobs):
ambs = [os.path.join(cand_dir, pattern.format(name=c['name'])) for c in cases]
for p in ambs:
if not os.path.exists(p):
sys.exit('missing: ' + p)
pcm = decode_many(ambs, dec, cache, jobs)
n_ok = n_all = 0
rows = []
for c, amb in zip(cases, ambs):
x = read_raw(c['file'])
ids = tone_ids(amb)
y = pcm[amb]
for s in c['segments']:
n_all += 1
on_f = s['start'] // 160
end_f = min(len(ids), (s['start'] + s['length']) // 160 + 10)
first = next((i for i in range(on_f, end_f) if ids[i] == s['id']), None)
other = sorted({i for i in ids[on_f:end_f] if i is not None and i != s['id']})
ok_id = first is not None and first - on_f <= LIM_ONSET and not other
si = steady(x, s['start'] - 160, s['start'] + s['length'] + 160)
so = steady(y, s['start'] - 160, min(len(y), s['start'] + s['length'] + 2400))
if si and so:
lin, _ = fit_levels(x[si[0]:si[0] + si[1]], s['freqs'])
lout, fo = fit_levels(y[so[0]:so[0] + so[1]], s['freqs'])
err = [o - i for o, i in zip(lout, lin)]
else:
lin, lout, err, fo = [None], [None], [None], []
ok_lev = None not in err and all(abs(e) <= LIM_LEVEL for e in err)
ok = ok_id and ok_lev
n_ok += ok
rows.append(dict(case=c['name'], id=s['id'], first=None if first is None else first - on_f,
other_ids=other, level_in=lin, level_out=lout, err=err, f_out=fo, ok=ok))
print('%-14s ID %3d first tone frame %s other IDs %-8s level in %s err %s %s' % (
c['name'], s['id'], 'none' if first is None else 'onset+%d' % (first - on_f), other or '-',
' '.join('%6.2f' % v if v is not None else ' n/a' for v in lin),
' '.join('%+5.2f' % v if v is not None else ' n/a' for v in err), 'ok' if ok else 'FAIL'))
print('E6 tone cases: %d/%d pass (ID within %d frames of onset, no other IDs, level within ±%.1f dB)'
% (n_ok, n_all, LIM_ONSET, LIM_LEVEL))
return n_ok == n_all, rows
def speech(paths, exclude=('tones',)):
files = []
for p in paths:
files += sorted(glob.glob(os.path.join(p, '*.amb'))) if os.path.isdir(p) else [p]
files = [f for f in files if not any(os.path.basename(f).startswith(x) for x in exclude if x)]
bad = {}
for f in files:
n = sum(1 for i in tone_ids(f) if i is not None)
if n:
bad[f] = n
for f, n in bad.items():
print(' %s: %d tone frames' % (f, n))
print('E6 speech check: %d files, %s' % (len(files), 'no tone frames: PASS' if not bad else
'%d with tone frames: FAIL' % len(bad)))
return not bad, bad
def main():
ap = argparse.ArgumentParser(description='E6 tone frames')
sub = ap.add_subparsers(dest='cmd', required=True)
g = sub.add_parser('gen')
g.add_argument('outdir')
c = sub.add_parser('check')
c.add_argument('cases', help="cases.json from 'gen', or 'pkg' for vectors/e7/tones.raw")
c.add_argument('cand_dir', help="candidate directory ('ref' with 'pkg': the reference bitstream)")
c.add_argument('--pattern', default='{name}.amb')
c.add_argument('--decoder', default=DEFAULT_DEC)
c.add_argument('--cache')
c.add_argument('--jobs', type=int, default=MAX_JOBS)
c.add_argument('--json')
s = sub.add_parser('speech')
s.add_argument('paths', nargs='+')
s.add_argument('--exclude', default='tones')
a = ap.parse_args()
if a.cmd == 'gen':
gen(a.outdir)
return 0
if a.cmd == 'speech':
return 0 if speech(a.paths, a.exclude.split(','))[0] else 1
if a.cases == 'pkg':
cases = [PKG_CASE]
if a.cand_dir == 'ref':
a.cand_dir, a.pattern = E7V, '{name}.ref.amb'
else:
cases = json.load(open(a.cases))
base = os.path.dirname(os.path.abspath(a.cases))
for cs in cases:
cs['file'] = os.path.join(base, cs['file'])
ok, rows = check(cases, a.cand_dir, a.pattern, a.decoder, a.cache, a.jobs)
if a.json:
json.dump(dict(cases=rows, pass_=ok), open(a.json, 'w'), indent=1)
print('E6 (tone cases): ' + ('PASS' if ok else 'FAIL'))
return 0 if ok else 1
if __name__ == '__main__':
sys.exit(main())
+392
View File
@@ -0,0 +1,392 @@
#define _POSIX_C_SOURCE 200809L
#include "io.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
#define LINE_MAX_LEN (1 << 14)
const char *io_prog = "xombe";
void io_fail(const char *msg, const char *arg)
{
fprintf(stderr, "%s: %s%s\n", io_prog, arg ? arg : "", msg);
exit(2);
}
const char *io_class_name(int cls)
{
static const char *const names[] = {"voice", "erasure", "silence", "tone"};
return cls >= 0 && cls < 4 ? names[cls] : "?";
}
const char *io_conceal_name(int conceal)
{
static const char *const names[] = {"none", "repeat", "mute"};
return conceal >= 0 && conceal < 3 ? names[conceal] : "?";
}
void io_print_decision(long n, const xombe_decision *d, const char *out)
{
fprintf(stderr, "%ld %s %s %d ", n, io_class_name(d->cls), io_conceal_name(d->conceal), d->run);
if (d->conceal != XOMBE_CONCEAL_MUTE)
fputc('-', stderr);
else if (d->mute_src < 0)
fputs("init", stderr);
else
fprintf(stderr, "%lld", (long long)d->mute_src);
fprintf(stderr, " %d %d %d %d", d->e0, d->e1, d->bf, d->hb);
if (out)
fprintf(stderr, " %s", out);
fputc('\n', stderr);
}
void io_pack_bits(const uint8_t d[49], uint8_t bytes[XOMBE_BITS_BYTES])
{
int i;
memset(bytes, 0, XOMBE_BITS_BYTES);
for (i = 0; i < 49; i++)
if (d[i])
bytes[i >> 3] |= (uint8_t)(0x80 >> (i & 7));
}
void io_unpack_bits(const uint8_t bytes[XOMBE_BITS_BYTES], uint8_t d[49])
{
int i;
for (i = 0; i < 49; i++)
d[i] = (uint8_t)((bytes[i >> 3] >> (7 - (i & 7))) & 1);
}
void io_amb_from_bytes(const uint8_t bytes[XOMBE_BITS_BYTES], uint8_t rec[IO_AMB_RECORD])
{
rec[0] = 0;
memcpy(rec + 1, bytes, 6);
rec[7] = (uint8_t)(bytes[6] >> 7);
}
void io_amb_to_bytes(const uint8_t rec[IO_AMB_RECORD], uint8_t bytes[XOMBE_BITS_BYTES])
{
memcpy(bytes, rec + 1, 6);
bytes[6] = (uint8_t)((rec[7] & 1) << 7);
}
FILE *io_open(const char *path, const char *mode)
{
FILE *f;
if (!strcmp(path, "-"))
return mode[0] == 'r' ? stdin : stdout;
f = fopen(path, mode);
if (!f)
fprintf(stderr, "%s: %s\n", path, strerror(errno));
return f;
}
int io_close(FILE *f, const char *path)
{
int bad = ferror(f);
if (f == stdin || f == stdout)
bad |= fflush(f);
else
bad |= fclose(f);
if (bad)
fprintf(stderr, "%s: I/O error\n", path);
return !bad;
}
int io_write(FILE *f, const void *p, size_t n, const char *path)
{
if (fwrite(p, 1, n, f) == n)
return 1;
fprintf(stderr, "%s: write failed: %s\n", path, strerror(errno));
return 0;
}
int io_read_record(FILE *f, void *rec, size_t n, const char *path)
{
size_t got = fread(rec, 1, n, f);
if (got == n)
return 1;
if (got && !ferror(f)) {
fprintf(stderr, "%s: error: partial final frame\n", path);
return -1;
}
return 0;
}
size_t io_read_pcm(FILE *f, int16_t *pcm, size_t n)
{
uint8_t b[2 * 256];
size_t done = 0;
while (done < n) {
size_t want = n - done < 256 ? n - done : 256, got = fread(b, 2, want, f), i;
for (i = 0; i < got; i++)
pcm[done + i] = (int16_t)(uint16_t)(b[2 * i] | (b[2 * i + 1] << 8));
done += got;
if (got < want)
break;
}
return done;
}
int io_write_pcm(FILE *f, const int16_t *pcm, size_t n, const char *path)
{
uint8_t b[2 * 256];
while (n) {
size_t k = n < 256 ? n : 256, i;
for (i = 0; i < k; i++) {
uint16_t u = (uint16_t)pcm[i];
b[2 * i] = (uint8_t)(u & 0xFF);
b[2 * i + 1] = (uint8_t)(u >> 8);
}
if (!io_write(f, b, 2 * k, path))
return 0;
pcm += k;
n -= k;
}
return 1;
}
int io_parse_float(const char *s, float lo, float hi, float *out)
{
char *end;
double v;
errno = 0;
v = strtod(s, &end);
if (end == s || *end || errno || !(v >= lo && v <= hi))
return 0;
*out = (float)v;
return 1;
}
int io_frames_parse(const char *s, io_frames *out)
{
const char *p = s;
int n = 1;
for (; *p; p++)
n += *p == ',';
out->n = 0;
out->r = malloc((size_t)n * sizeof(*out->r));
if (!out->r)
return 0;
for (p = s;;) {
char *end;
long a, b;
errno = 0;
a = strtol(p, &end, 10);
if (end == p || a < 0 || errno)
break;
b = a;
if (*end == '-') {
p = end + 1;
b = strtol(p, &end, 10);
if (end == p || b < a || errno)
break;
}
out->r[out->n][0] = a;
out->r[out->n][1] = b;
out->n++;
if (!*end)
return 1;
if (*end != ',')
break;
p = end + 1;
}
free(out->r);
out->r = NULL;
out->n = 0;
return 0;
}
int io_frames_has(const io_frames *f, long i)
{
int k;
for (k = 0; k < f->n; k++)
if (i >= f->r[k][0] && i <= f->r[k][1])
return 1;
return 0;
}
#ifndef _WIN32
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;
}
#endif
int stream_open(stream_reader *r, const char *path)
{
size_t n = strlen(path);
memset(r, 0, sizeof(*r));
r->path = path;
r->pid = -1;
r->line = malloc(LINE_MAX_LEN);
if (!r->line)
return 0;
if (n > 3 && !strcmp(path + n - 3, ".gz")) {
#ifdef _WIN32
fprintf(stderr, "%s: .gz streams are unsupported on Windows\n", path);
#else
r->f = open_gzip(path, &r->pid);
if (!r->f)
fprintf(stderr, "%s: cannot run gzip: %s\n", path, strerror(errno));
#endif
} else {
r->f = io_open(path, "r");
}
if (!r->f) {
free(r->line);
r->line = NULL;
return 0;
}
return 1;
}
int stream_close(stream_reader *r)
{
int ok = 1;
if (r->f) {
ok = !ferror(r->f);
if (r->f != stdin)
fclose(r->f);
}
#ifndef _WIN32
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;
}
}
#endif
free(r->line);
r->line = NULL;
r->f = NULL;
return ok;
}
const char *stream_key(const char *s, const char *key)
{
char pat[64];
const char *p;
snprintf(pat, sizeof(pat), "\"%s\":", key);
p = strstr(s, pat);
return p ? p + strlen(pat) : NULL;
}
int stream_int(const stream_reader *r, const char *s, const char *key, long *out)
{
const char *p = stream_key(s, key);
char *end;
if (p) {
errno = 0;
*out = strtol(p, &end, 10);
if (end != p && !errno && (*end == ',' || *end == '}' || *end == ' '))
return 1;
}
fprintf(stderr, "%s:%ld: %s \"%s\"\n", r->path, r->lineno, p ? "malformed" : "missing", key);
return 0;
}
static int parse_bits(const stream_reader *r, const char *p, stream_half *h)
{
int i;
p += strspn(p, " ");
if (*p++ != '"')
goto bad;
for (i = 0; i < 49; i++) {
if (p[i] != '0' && p[i] != '1')
goto bad;
h->d[i] = (uint8_t)(p[i] == '1');
}
if (p[49] != '"')
goto bad;
io_pack_bits(h->d, h->bits);
return 1;
bad:
fprintf(stderr, "%s:%ld: \"bits\" is not a string of 49 binary digits\n", r->path, r->lineno);
return 0;
}
int stream_next(stream_reader *r, stream_half *h)
{
const char *p;
long v;
for (;;) {
size_t n;
if (!fgets(r->line, LINE_MAX_LEN, r->f))
return ferror(r->f) ? STREAM_ERROR : STREAM_END;
r->lineno++;
n = strlen(r->line);
if (n == LINE_MAX_LEN - 1 && r->line[n - 1] != '\n') {
fprintf(stderr, "%s:%ld: line too long\n", r->path, r->lineno);
return STREAM_ERROR;
}
if (r->line[strspn(r->line, " \t\r\n")])
break;
}
if ((p = stream_key(r->line, "set"))) {
p += strspn(p, " ");
if (!stream_int(r, r->line, "value", &v))
return STREAM_ERROR;
if (!strncmp(p, "\"eps_T\"", 7))
r->eps_t = (int)v;
else if (!strncmp(p, "\"eps_1\"", 7))
r->eps_1 = (int)v;
else if (!strncmp(p, "\"status_flags\"", 14))
r->status_flags = (unsigned)v;
else {
fprintf(stderr, "%s:%ld: unknown \"set\" key\n", r->path, r->lineno);
return STREAM_ERROR;
}
return STREAM_SET;
}
if (stream_key(r->line, "init")) {
r->eps_t = r->eps_1 = 0;
r->status_flags = 0;
return STREAM_INIT;
}
if ((p = stream_key(r->line, "bits"))) {
long second, ns, flags;
if (!parse_bits(r, p, h) || !stream_int(r, r->line, "second_half", &second) ||
!stream_int(r, r->line, "nsamples", &ns) || !stream_int(r, r->line, "flags", &flags))
return STREAM_ERROR;
h->second_half = second != 0;
h->nsamples = (int)ns;
h->flags = (unsigned)flags | r->status_flags;
h->line = r->line;
return STREAM_HALF;
}
fprintf(stderr, "%s:%ld: unrecognised line\n", r->path, r->lineno);
return STREAM_ERROR;
}
+93
View File
@@ -0,0 +1,93 @@
#ifndef XOMBE_TOOLS_IO_H
#define XOMBE_TOOLS_IO_H
/* file formats, checked I/O, and messages shared by the tools and test_stream */
#include <stdio.h>
#include <stdint.h>
#include "xombe.h"
enum io_format {
IO_AMB, /* ".amb" header, then 8 bytes per frame: a zero byte, d0..d47 MSB-first, d48 in the LSB */
IO_BITS, /* 49 bytes per frame, one bit per byte */
IO_AIR /* 9 bytes per frame, the 72-bit frame */
};
#define IO_AMB_HEADER ".amb"
#define IO_AMB_RECORD 8
#define IO_BITS_RECORD 49
#define IO_AIR_RECORD XOMBE_FRAME_BYTES
/* bytes: d0..d48 MSB-first, d48 in the MSB of bytes[6] (the library's voice bits) */
void io_pack_bits(const uint8_t d[49], uint8_t bytes[XOMBE_BITS_BYTES]);
void io_unpack_bits(const uint8_t bytes[XOMBE_BITS_BYTES], uint8_t d[49]);
void io_amb_from_bytes(const uint8_t bytes[XOMBE_BITS_BYTES], uint8_t rec[IO_AMB_RECORD]);
void io_amb_to_bytes(const uint8_t rec[IO_AMB_RECORD], uint8_t bytes[XOMBE_BITS_BYTES]);
/* tool name for messages, each tool sets it first */
extern const char *io_prog;
/* usage error: prints "io_prog: <arg><msg>" (arg may be NULL) and exits 2 */
void io_fail(const char *msg, const char *arg);
/* names of enum xombe_class and enum xombe_conceal values, "?" out of range */
const char *io_class_name(int cls);
const char *io_conceal_name(int conceal);
/* --decisions line on stderr: "n class conceal run mute e0 e1 bf hb[ out]", mute the mute set's source frame,
init, or - without a mute */
void io_print_decision(long n, const xombe_decision *d, const char *out);
/* "-" selects stdin or stdout, both report failures on stderr with the path and return NULL or 0 */
FILE *io_open(const char *path, const char *mode);
int io_close(FILE *f, const char *path);
int io_write(FILE *f, const void *p, size_t n, const char *path);
/* reads an n-byte record, returns 1, or 0 at the end of the input or on a read error (check ferror), or -1 for a
partial final record, reported as an error */
int io_read_record(FILE *f, void *rec, size_t n, const char *path);
/* raw audio, signed 16-bit little-endian samples whatever the host byte order
io_read_pcm returns the number of whole samples read */
size_t io_read_pcm(FILE *f, int16_t *pcm, size_t n);
int io_write_pcm(FILE *f, const int16_t *pcm, size_t n, const char *path);
/* parses a whole string as a number in [lo, hi], returns 0 if it is not one */
int io_parse_float(const char *s, float lo, float hi, float *out);
/* frame index set from "a,b-c,...", for --lost, io_frames_parse returns 0 for a malformed list */
typedef struct {
long (*r)[2];
int n;
} io_frames;
int io_frames_parse(const char *s, io_frames *out);
int io_frames_has(const io_frames *f, long i);
/* JSONL decoder streams, one {"init":...}, {"set":KEY,"value":N}, or half-frame object per line */
enum stream_event { STREAM_END, STREAM_HALF, STREAM_SET, STREAM_INIT, STREAM_ERROR };
typedef struct {
FILE *f;
long pid;
const char *path;
long lineno;
char *line;
/* latest "set" values, an "init" line resets them */
int eps_t, eps_1;
unsigned status_flags;
} stream_reader;
typedef struct {
uint8_t bits[XOMBE_BITS_BYTES];
uint8_t d[49];
unsigned flags; /* the line's flags OR the latest status_flags */
int second_half;
int nsamples;
const char *line; /* whole line, for further keys, valid until the next stream_next */
} stream_half;
/* a path ending in .gz is decompressed with gzip (run directly, without a shell) */
int stream_open(stream_reader *r, const char *path);
int stream_next(stream_reader *r, stream_half *h);
/* returns 0 when the input was read without error */
int stream_close(stream_reader *r);
/* text after "key": in s, or NULL */
const char *stream_key(const char *s, const char *key);
/* reads the integer after "key": in s, reports a missing or malformed value and returns 0 */
int stream_int(const stream_reader *r, const char *s, const char *key, long *out);
#endif
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
import os, sys, json, warnings
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import FS, read_raw as load
import numpy as np
from scipy.signal import resample_poly, stft
def align(r, d, maxlag=800):
n = min(len(r), len(d))
c = np.correlate(d[:n], r[:n], 'full')[n - 1 - maxlag:n + maxlag]
lag = int(np.argmax(np.abs(c))) - maxlag
if lag > 0: d = d[lag:]
elif lag < 0: d = np.concatenate([np.zeros(-lag), d])
n = min(len(r), len(d))
return r[:n], d[:n], lag
def lsd(r, d):
_, _, R = stft(r, FS, nperseg=256, noverlap=192)
_, _, D = stft(d, FS, nperseg=256, noverlap=192)
pr, pd = np.abs(R) ** 2, np.abs(D) ** 2
act = 10 * np.log10(pr.sum(0) + 1e-9) > 10 * np.log10(pr.sum(0).max() + 1e-9) - 40
band = (np.arange(pr.shape[0]) * FS / 256 >= 100) & (np.arange(pr.shape[0]) * FS / 256 <= 3800)
floor = pr.max() * 1e-6
x = 10 * np.log10(pr[band][:, act] + floor) - 10 * np.log10(pd[band][:, act] + floor)
return float(np.mean(np.sqrt(np.mean(x ** 2, 0))))
def segsnr(r, d, n=160):
k = len(r) // n
s = []
for i in range(k):
a, b = r[i * n:(i + 1) * n], d[i * n:(i + 1) * n]
e = np.sum(a ** 2)
if e < 1e-3 * n * 32768 ** 2 * 1e-6: continue
s.append(np.clip(10 * np.log10(e / (np.sum((a - b) ** 2) + 1e-9)), -10, 35))
return float(np.mean(s)) if s else float('nan')
def score(r, d):
out = {}
from pesq import pesq
out['pesq_nb'] = float(pesq(FS, r / 32768, d / 32768, 'nb'))
from pystoi import stoi
out['stoi'] = float(stoi(r, d, FS, extended=False))
try:
from visqol import VisqolApi
api = VisqolApi(); api.create(mode='speech')
r16, d16 = resample_poly(r, 2, 1), resample_poly(d, 2, 1)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
out['visqol_speech'] = float(api.measure_from_arrays(r16, d16, 16000).moslqo)
except Exception as e:
out['visqol_speech'] = None
out['visqol_error'] = str(e)
out['lsd_db'] = lsd(r, d)
out['segsnr_db'] = segsnr(r, d)
return out
if __name__ == '__main__':
a = [x for x in sys.argv[1:] if not x.startswith('--')]
r, d = load(a[0]), load(a[1])
lag = 0
if '--no-align' not in sys.argv: r, d, lag = align(r, d)
o = score(r, d); o['lag'] = lag; o['seconds'] = len(r) / FS
print(json.dumps(o) if '--json' in sys.argv else '\n'.join(f'{k:14s} {v}' for k, v in o.items()))
if 'visqol_error' in o:
print('ViSQOL failed: ' + o['visqol_error'], file=sys.stderr)
sys.exit(1)
+208
View File
@@ -0,0 +1,208 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "io.h"
#include "xombe.h"
#if XOMBE_HAVE_DSTAR
#define NO_DSTAR ""
#else
#define NO_DSTAR " (not in this build)"
#endif
static void usage(FILE *f, int status)
{
fprintf(f,
"usage: xombe-dec [options] IN OUT.raw\n"
" OUT.raw: 8 kHz s16le mono, 160 samples per frame. '-' is stdin or stdout\n"
"input formats (modes):\n"
" (default) AMBE+2 .amb file\n"
" --bits AMBE+2, 49 bytes per frame, one bit per byte\n"
" --air AMBE+2 72-bit air frames, 9 bytes, FEC applied\n"
" --dstar D-STAR (AMBE 2400) frames, 9 bytes as received, FEC applied" NO_DSTAR "\n"
" --stream AMBE+2 JSONL stream IN.jsonl[.gz], one half call per line\n"
"options:\n"
" --lost LIST frames lost, e.g. 3,10-12 (XOMBE_FLAG_LOST)\n"
" --conformance-noise\n"
" noise source that reproduces the test vectors (default: production source)\n"
" --decisions per-frame decisions to stderr: 'n class conceal run mute e0 e1 bf hb', mute: the\n"
" muted set's source frame, init, or -. e0 e1: Golay corrections, -1 if lost or\n"
" post-FEC (.amb, --bits)\n"
" --help this text\n"
" a truncated final frame is an error\n");
exit(status);
}
static void print_decision(const xombe_dec *d, long frame)
{
xombe_decision r;
xombe_dec_decision_get(d, &r);
io_print_decision(frame, &r, NULL);
}
static int read_frame(FILE *in, const char *path, enum io_format fmt, uint8_t bits[XOMBE_BITS_BYTES], uint8_t air[IO_AIR_RECORD])
{
uint8_t buf[IO_BITS_RECORD];
size_t want = fmt == IO_AMB ? IO_AMB_RECORD : fmt == IO_BITS ? IO_BITS_RECORD : IO_AIR_RECORD;
int i, got = io_read_record(in, fmt == IO_AIR ? air : buf, want, path);
if (got != 1)
return got;
if (fmt == IO_AMB) {
io_amb_to_bytes(buf, bits);
} else if (fmt == IO_BITS) {
for (i = 0; i < IO_BITS_RECORD; i++)
buf[i] &= 1;
io_pack_bits(buf, bits);
}
return 1;
}
static int run_stream(const char *path, const char *out_path, int conformance, int show)
{
stream_reader r;
stream_half h;
FILE *out;
long frame = -1;
xombe_dec_mem mem;
xombe_dec *dec;
int ev, ok = 1;
if (!stream_open(&r, path))
return 1;
out = io_open(out_path, "wb");
if (!out) {
stream_close(&r);
return 1;
}
dec = xombe_dec_init(&mem, XOMBE_DMR);
if (conformance)
xombe_dec_set_noise(dec, XOMBE_NOISE_CONFORMANCE, 0);
while (ok && (ev = stream_next(&r, &h)) != STREAM_END) {
if (ev == STREAM_ERROR) {
ok = 0;
} else if (ev == STREAM_SET) {
xombe_dec_set_errors(dec, r.eps_t, r.eps_1);
} else if (ev == STREAM_INIT) {
dec = xombe_dec_init(&mem, XOMBE_DMR);
if (conformance)
xombe_dec_set_noise(dec, XOMBE_NOISE_CONFORMANCE, 0);
frame = -1;
} else {
int16_t pcm[XOMBE_HALF_MAX];
int ns = xombe_dec_half_bits(dec, h.bits, h.flags, h.second_half, h.nsamples, pcm);
if (ns < 0) {
fprintf(stderr, "%s:%ld: half-frame call out of order\n", path, r.lineno);
ok = 0;
break;
}
ok = io_write_pcm(out, pcm, (size_t)ns, out_path);
if (!h.second_half) {
frame++;
if (show)
print_decision(dec, frame);
}
}
}
ok &= stream_close(&r);
ok &= io_close(out, out_path);
return ok ? 0 : 1;
}
int main(int argc, char **argv)
{
enum io_format fmt = IO_AMB;
int conformance = 0, show = 0, stream = 0, dstar = 0, np = 0, nfmt = 0, i, ok = 1, got;
io_frames lost = {NULL, 0};
const char *paths[2];
FILE *in, *out;
xombe_dec_mem mem;
xombe_dec *dec;
long frame = 0;
io_prog = "xombe-dec";
for (i = 1; i < argc; i++) {
const char *a = argv[i];
if (!strcmp(a, "--help"))
usage(stdout, 0);
else if (!strcmp(a, "--bits")) {
fmt = IO_BITS;
nfmt++;
} else if (!strcmp(a, "--air")) {
fmt = IO_AIR;
nfmt++;
} else if (!strcmp(a, "--dstar")) {
if (!XOMBE_HAVE_DSTAR)
io_fail(": not in this build (XOMBE_DSTAR=OFF)", a);
dstar = 1;
fmt = IO_AIR;
nfmt++;
} else if (!strcmp(a, "--stream")) {
stream = 1;
nfmt++;
} else if (!strcmp(a, "--lost") && i + 1 < argc) {
if (!io_frames_parse(argv[++i], &lost))
io_fail(": not a frame list (e.g. 3,10-12)", argv[i]);
} else if (!strcmp(a, "--conformance-noise"))
conformance = 1;
else if (!strcmp(a, "--decisions"))
show = 1;
else if (a[0] == '-' && a[1])
usage(stderr, 2);
else if (np < 2)
paths[np++] = a;
else
usage(stderr, 2);
}
if (np != 2)
usage(stderr, 2);
if (nfmt > 1)
io_fail("--bits, --air, --dstar and --stream are exclusive", NULL);
if (stream) {
if (lost.n)
io_fail("--lost does not apply to --stream", NULL);
return run_stream(paths[0], paths[1], conformance, show);
}
in = io_open(paths[0], "rb");
if (!in)
return 1;
if (fmt == IO_AMB) {
char hdr[4];
if (fread(hdr, 1, 4, in) != 4 || memcmp(hdr, IO_AMB_HEADER, 4)) {
fprintf(stderr, "%s: not an .amb file\n", paths[0]);
return 1;
}
}
out = io_open(paths[1], "wb");
if (!out)
return 1;
dec = xombe_dec_init(&mem, dstar ? XOMBE_DSTAR : XOMBE_DMR);
if (conformance)
xombe_dec_set_noise(dec, XOMBE_NOISE_CONFORMANCE, 0);
for (;;) {
uint8_t bits[XOMBE_BITS_BYTES], air[IO_AIR_RECORD];
int16_t pcm[160];
unsigned flags = io_frames_has(&lost, frame) ? XOMBE_FLAG_LOST : 0;
if ((got = read_frame(in, paths[0], fmt, bits, air)) != 1) {
ok = got == 0;
break;
}
if (fmt == IO_AIR)
xombe_dec_frame(dec, air, flags, pcm);
else
xombe_dec_frame_bits(dec, bits, flags, pcm);
if (show)
print_decision(dec, frame);
if (!io_write_pcm(out, pcm, 160, paths[1])) {
ok = 0;
break;
}
frame++;
}
if (ferror(in)) {
fprintf(stderr, "%s: read error\n", paths[0]);
ok = 0;
}
if (in != stdin)
fclose(in);
ok &= io_close(out, paths[1]);
free(lost.r);
return ok ? 0 : 1;
}
+210
View File
@@ -0,0 +1,210 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "io.h"
#include "xombe.h"
#if XOMBE_HAVE_DSTAR
#define NO_DSTAR ""
#else
#define NO_DSTAR " (not in this build)"
#endif
static void usage(FILE *f, int status)
{
fprintf(f,
"usage: xombe-enc [options] IN.raw OUT\n"
" IN.raw: 8 kHz s16le mono, a partial final frame is dropped. '-' is stdin or stdout\n"
"modes:\n"
" (default) AMBE+2: OUT is .amb, or .bits with --bits, or air frames with --air\n"
" --dstar D-STAR only: OUT is 9-byte D-STAR frames (.dstar)" NO_DSTAR "\n"
" --dual DSTAR_OUT both: AMBE+2 to OUT, D-STAR frames to DSTAR_OUT" NO_DSTAR "\n"
"AMBE+2 output format:\n"
" --bits 49 bytes per frame, one bit per byte\n"
" --air 72-bit air frames, 9 bytes, FEC applied\n"
"options:\n"
" --ns on|off noise suppression (default on)\n"
" --ns-strength S suppression strength, 0..1 (default 0.5)\n"
" --dtx on|off AMBE+2 silence frames for background (default on)\n"
" --tones on|off tone detection (default on)\n"
" --vscale S voicing decision scale, 0.001..1000000 (default 0.35)\n"
" --dstar-dtx on|off D-STAR null frames for background (default off)" NO_DSTAR "\n"
" --quant closed|open AMBE+2 amplitude quantizer, open is faster (default closed)\n"
" --help this text\n"
" --ns-strength and --vscale round S to thousandths. delay: 3 frames, 4 with D-STAR, flushed at the end\n");
exit(status);
}
static int on_off(const char *s)
{
if (!strcmp(s, "on"))
return 1;
if (!strcmp(s, "off"))
return 0;
io_fail(": expected on or off", s);
return 0;
}
static int quantizer(const char *s)
{
if (!strcmp(s, "closed"))
return XOMBE_ENC_QUANT_CLOSED;
if (!strcmp(s, "open"))
return XOMBE_ENC_QUANT_OPEN;
io_fail(": expected closed or open", s);
return 0;
}
static float number(const char *s, float lo, float hi)
{
float v;
if (!io_parse_float(s, lo, hi, &v)) {
fprintf(stderr, "%s: '%s' is not a number in %.7g..%.7g\n", io_prog, s, lo, hi);
exit(2);
}
return v;
}
/* the library takes the scales in thousandths */
static int permille(const char *s, float lo, float hi)
{
return (int)(number(s, lo, hi) * 1000.0f + 0.5f);
}
static int write_frame(FILE *out, enum io_format fmt, const uint8_t bits[XOMBE_BITS_BYTES], const char *path)
{
uint8_t buf[IO_BITS_RECORD];
if (fmt == IO_AMB) {
io_amb_from_bytes(bits, buf);
return io_write(out, buf, IO_AMB_RECORD, path);
}
if (fmt == IO_AIR) {
xombe_fec_encode(XOMBE_DMR, bits, buf);
return io_write(out, buf, IO_AIR_RECORD, path);
}
io_unpack_bits(bits, buf);
return io_write(out, buf, IO_BITS_RECORD, path);
}
static int write_dstar(FILE *out, const uint8_t bits[XOMBE_BITS_BYTES], const char *path)
{
uint8_t fr[XOMBE_FRAME_BYTES];
xombe_fec_encode(XOMBE_DSTAR, bits, fr);
return io_write(out, fr, sizeof(fr), path);
}
enum mode { MODE_AMBE2, MODE_DSTAR, MODE_DUAL };
/* one frame through the encoder, pcm NULL flushes, returns 1 if it wrote a frame. the DMR output goes to out in
fmt, the D-STAR output to out (--dstar) or dout (--dual) */
static int encode_frame(xombe_enc *enc, enum mode mode, const int16_t *pcm, FILE *out, enum io_format fmt,
const char *path, FILE *dout, const char *dpath, int *ok)
{
uint8_t dmr[XOMBE_BITS_BYTES], dstar[XOMBE_BITS_BYTES];
if (xombe_enc_frame_bits(enc, pcm, NULL, mode != MODE_DSTAR ? dmr : NULL, mode != MODE_AMBE2 ? dstar : NULL) != 1)
return 0;
if (mode == MODE_DSTAR)
*ok = write_dstar(out, dstar, path);
else
*ok = write_frame(out, fmt, dmr, path) && (mode != MODE_DUAL || write_dstar(dout, dstar, dpath));
return 1;
}
int main(int argc, char **argv)
{
xombe_enc_cfg cfg;
static xombe_enc_mem mem;
xombe_enc *enc;
const char *paths[2], *dpath = NULL;
enum io_format fmt = IO_AMB;
enum mode mode = MODE_AMBE2;
int np = 0, i, ok = 1, have_fmt = 0;
long frames = 0, written = 0;
FILE *in, *out, *dout = NULL;
io_prog = "xombe-enc";
xombe_enc_cfg_default(&cfg);
for (i = 1; i < argc; i++) {
const char *a = argv[i];
int more = i + 1 < argc;
if (!strcmp(a, "--help"))
usage(stdout, 0);
else if (!strcmp(a, "--air")) {
fmt = IO_AIR;
have_fmt = 1;
} else if (!strcmp(a, "--bits")) {
fmt = IO_BITS;
have_fmt = 1;
} else if (!strcmp(a, "--ns") && more)
cfg.ns = on_off(argv[++i]);
else if (!strcmp(a, "--ns-strength") && more)
cfg.ns_strength_permille = permille(argv[++i], 0.0f, 1.0f);
else if (!strcmp(a, "--dtx") && more)
cfg.dmr_dtx = on_off(argv[++i]);
else if (!strcmp(a, "--tones") && more)
cfg.tones = on_off(argv[++i]);
else if (!strcmp(a, "--quant") && more)
cfg.dmr_quant = quantizer(argv[++i]);
else if (!strcmp(a, "--vscale") && more)
cfg.voicing_scale_permille = permille(argv[++i], 0.001f, 1e6f);
else if (!strcmp(a, "--dstar") || (!strcmp(a, "--dual") && more) || (!strcmp(a, "--dstar-dtx") && more)) {
if (!XOMBE_HAVE_DSTAR)
io_fail(": not in this build (XOMBE_DSTAR=OFF)", a);
if (!strcmp(a, "--dstar"))
mode = MODE_DSTAR;
else if (!strcmp(a, "--dual")) {
mode = MODE_DUAL;
dpath = argv[++i];
} else
cfg.dstar_dtx = on_off(argv[++i]);
} else if (a[0] == '-' && a[1])
usage(stderr, 2);
else if (np < 2)
paths[np++] = a;
else
usage(stderr, 2);
}
if (np != 2)
usage(stderr, 2);
if (mode == MODE_DSTAR && have_fmt)
io_fail("--bits and --air select the AMBE+2 output's format, --dstar has none", NULL);
cfg.outputs = mode == MODE_AMBE2 ? XOMBE_ENC_DMR
: mode == MODE_DSTAR ? XOMBE_ENC_DSTAR
: XOMBE_ENC_DMR | XOMBE_ENC_DSTAR;
enc = xombe_enc_init(&mem, &cfg);
if (!enc)
io_fail("invalid encoder settings", NULL);
in = io_open(paths[0], "rb");
if (!in)
return 1;
out = io_open(paths[1], "wb");
if (!out)
return 1;
if (dpath && !(dout = io_open(dpath, "wb")))
return 1;
if (fmt == IO_AMB && mode != MODE_DSTAR)
ok = io_write(out, IO_AMB_HEADER, 4, paths[1]);
while (ok) {
int16_t pcm[160];
size_t got = io_read_pcm(in, pcm, 160);
if (got != 160) {
/* as the reference encoder's frame count */
if (got)
fprintf(stderr, "%s: partial final frame of %zu samples dropped\n", paths[0], got);
break;
}
frames++;
written += encode_frame(enc, mode, pcm, out, fmt, paths[1], dout, dpath, &ok);
}
if (ferror(in)) {
fprintf(stderr, "%s: read error\n", paths[0]);
ok = 0;
}
while (ok && written < frames)
written += encode_frame(enc, mode, NULL, out, fmt, paths[1], dout, dpath, &ok);
if (in != stdin)
fclose(in);
ok &= io_close(out, paths[1]);
if (dout)
ok &= io_close(dout, dpath);
return ok ? 0 : 1;
}
+131
View File
@@ -0,0 +1,131 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "io.h"
#include "xombe.h"
/* DMR rate-33 frames -> D-STAR frames, or back with --reverse (xombe_xc_frame)
--amb: the DMR side is .amb, through the FEC (exact on clean frames) */
#if XOMBE_HAVE_ENCODER
#define NO_REVERSE ""
#else
#define NO_REVERSE " (not in this build)"
#endif
static void usage(FILE *f, int status)
{
fprintf(f,
"usage: xombe-xc [options] IN.r33 OUT.dstar\n"
" xombe-xc --reverse [options] IN.dstar OUT.r33\n"
"modes:\n"
" (default) DMR rate 33 -> D-STAR\n"
" --reverse D-STAR -> DMR rate 33" NO_REVERSE "\n"
" r33: DMR rate-33 frames, 9 bytes (xombe-enc --air, xombe-dec --air)\n"
" dstar: D-STAR frames, 9 bytes (xombe-enc --dstar, xombe-dec --dstar). '-' is stdin or stdout\n"
"DMR format:\n"
" --amb .amb in place of r33, either direction (xombe-enc, xombe-dec)\n"
"options:\n"
" --lost LIST frames lost, e.g. 3,10-12 (XOMBE_FLAG_LOST)\n"
" --decisions per-frame decisions to stderr: 'n class conceal run mute e0 e1 bf hb out', as\n"
" xombe-dec's of the input, then the output kind\n"
" --help this text\n"
" no delay: one output frame per input frame. a truncated final frame is an error\n");
exit(status);
}
int main(int argc, char **argv)
{
static const char *const outk[] = {"voice", "pulse", "tone", "knox", "silence", "resend"};
static xombe_xc_mem mem;
const char *paths[2];
xombe_xc *x = NULL;
io_frames lost = {NULL, 0};
FILE *in, *out;
long n = 0;
xombe_fec fec;
int i, np = 0, show = 0, rev = 0, amb = 0, ok = 1, got;
io_prog = "xombe-xc";
for (i = 1; i < argc; i++) {
const char *a = argv[i];
if (!strcmp(a, "--help"))
usage(stdout, 0);
else if (!strcmp(a, "--decisions"))
show = 1;
else if (!strcmp(a, "--amb"))
amb = 1;
else if (!strcmp(a, "--reverse")) {
if (!XOMBE_HAVE_ENCODER)
io_fail(": not in this build (XOMBE_ENCODER=OFF)", a);
rev = 1;
} else if (!strcmp(a, "--lost") && i + 1 < argc) {
if (!io_frames_parse(argv[++i], &lost))
io_fail(": not a frame list (e.g. 3,10-12)", argv[i]);
} else if (np < 2 && (a[0] != '-' || !a[1]))
paths[np++] = a;
else
usage(stderr, 2);
}
if (np != 2)
usage(stderr, 2);
if (!(in = io_open(paths[0], "rb")))
return 1;
if (amb && !rev) {
char hdr[4];
if (fread(hdr, 1, 4, in) != 4 || memcmp(hdr, IO_AMB_HEADER, 4)) {
fprintf(stderr, "%s: not an .amb file\n", paths[0]);
if (in != stdin)
fclose(in);
return 1;
}
}
if (!(out = io_open(paths[1], "wb"))) {
if (in != stdin)
fclose(in);
return 1;
}
if (amb && rev && !io_write(out, IO_AMB_HEADER, 4, paths[1]))
ok = 0;
xombe_fec_init(&fec, XOMBE_DMR);
x = xombe_xc_init(&mem, rev ? XOMBE_DSTAR : XOMBE_DMR);
while (ok) {
uint8_t fr[XOMBE_FRAME_BYTES], ds[XOMBE_FRAME_BYTES], bits[XOMBE_BITS_BYTES], rec[IO_AMB_RECORD];
unsigned flags = io_frames_has(&lost, n) ? XOMBE_FLAG_LOST : 0;
if (amb && !rev) {
if ((got = io_read_record(in, rec, IO_AMB_RECORD, paths[0])) == 1) {
io_amb_to_bytes(rec, bits);
xombe_fec_encode(XOMBE_DMR, bits, fr);
}
} else
got = io_read_record(in, fr, XOMBE_FRAME_BYTES, paths[0]);
if (got != 1) {
ok = got == 0;
break;
}
xombe_xc_frame(x, fr, flags, ds);
if (show) {
xombe_xc_decision d;
xombe_xc_decision_get(x, &d);
io_print_decision(n, &d.in, outk[d.out]);
}
if (amb && rev) {
xombe_fec_stats st;
xombe_fec_decode(&fec, ds, bits, &st);
io_amb_from_bytes(bits, rec);
ok = io_write(out, rec, IO_AMB_RECORD, paths[1]);
} else
ok = io_write(out, ds, XOMBE_FRAME_BYTES, paths[1]);
if (!ok)
break;
n++;
}
if (ferror(in)) {
fprintf(stderr, "%s: read error\n", paths[0]);
ok = 0;
}
if (in != stdin)
fclose(in);
ok &= io_close(out, paths[1]);
free(lost.r);
return ok ? 0 : 1;
}