File size: 2,218 Bytes
547c405 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | """The simulated phone lines keep the audio's length and timing, and each codec leaves its mark."""
from pathlib import Path
import numpy as np
import pytest
from inworld.sava import audio
import channels
SPEECH = audio.load(str(Path(__file__).parent / "fixtures" / "speech.wav"))[: 16000 * 8]
def snr_db(reference: np.ndarray, heard: np.ndarray) -> float:
return float(10 * np.log10(np.sum(reference**2) / np.sum((heard - reference) ** 2)))
def shift(reference: np.ndarray, heard: np.ndarray, reach: int = 40) -> int:
"""How many samples ``heard`` lags ``reference``, by cross-correlation."""
scores = [np.dot(reference[reach:-reach], np.roll(heard, -lag)[reach:-reach]) for lag in range(-reach, reach + 1)]
return int(np.argmax(scores)) - reach
@pytest.mark.parametrize(("codec", "least", "most"), [("ULAW", 25, 60), ("ALAW", 25, 60), ("GSM610", 3, 25)])
def test_codec_changes_the_audio_but_not_its_timing(codec, least, most):
no_codec = channels.narrowband(SPEECH, codec=None)
heard = channels.narrowband(SPEECH, codec=codec)
assert heard.shape == SPEECH.shape and heard.dtype == np.float32 and np.isfinite(heard).all()
assert shift(no_codec, heard) == 0
assert least < snr_db(no_codec, heard) < most
def test_default_line_is_the_published_phone_condition():
# Not sample for sample: libsndfile's mu-law rounds differently from asrqb's. 46 dB apart.
assert snr_db(channels.TEST_CONDITIONS["phone"](SPEECH), channels.narrowband(SPEECH)) > 40
def test_random_lines_vary_and_stay_aligned():
rng = np.random.default_rng(0)
lines = [channels.random_line(SPEECH, rng) for _ in range(8)]
reference = channels.narrowband(SPEECH, codec=None)
assert all(line.shape == SPEECH.shape and np.isfinite(line).all() for line in lines)
# Other filter orders and band edges move the audio by a few samples; a frame is 640.
assert all(abs(shift(reference, line)) <= 8 for line in lines)
assert len({round(float(np.abs(line).sum()), 3) for line in lines}) == 8
# The level change is undone: a random line is about as loud as the plain one.
assert all(0.5 < np.sqrt(np.mean(line**2)) / np.sqrt(np.mean(reference**2)) < 2.0 for line in lines)
|