mirror of
https://github.com/ratspeak/rsLXST
synced 2026-11-22 23:10:37 +00:00
codec2: implement bounded native 700C with reference parity
This commit is contained in:
1 parent
b1e6a3f6f8
commit
d9d62f3c7f
16 files changed
+1723
-63
No files matched your search
@@ -110,8 +110,40 @@
|
||||
"upstreamCommit": "24ec3b7c5b9892c268e180802ee3a5ce7737f214",
|
||||
"crateChecksum": "3c3c8ba70382a99c0b5ebadf6ad50e7d98fb6eb9bcc4c0e30d422f6321798d99",
|
||||
"provenance": "crates/lxst-codec2/UPSTREAM.json",
|
||||
"additionalSources": [
|
||||
{
|
||||
"repository": "https://github.com/drowe67/codec2",
|
||||
"commit": "310777b1c6f1af0bc7c72f5b32f80f6fd9136962",
|
||||
"license": "LGPL-2.1-only",
|
||||
"source_sha256": {
|
||||
"src/codec2.c": "57dcb29bd9376bb32f9ea5d6f16e36a4b635ddf976683f0c0c46fd4989550bf5",
|
||||
"src/newamp1.c": "8df144b2ef72abdf2fc3ff66ec5c682694bdb4e940a668d1c13b3f4335168c93",
|
||||
"src/newamp1.h": "457f8357a8ca2f064f77cb68abebfe1acf4fb6be82802b43244d7c926d356423",
|
||||
"src/mbest.c": "91e0126fc7a001d9a019cea49545263ed0c58dc4418eea871549505bc5b935fc",
|
||||
"src/phase.c": "751d3123d070c42fcb235affe154219f3326fb0e8a13335f4b9e1389ab295eb2",
|
||||
"src/quantise.c": "a9b6dbadfee5c79b5ba346e606152c735d1096c2f3552a3da3b39c024469732f",
|
||||
"src/codebook/train_120_1.txt": "a3aa8da88db8b4a9168023c2269a4f4f9555aec20ed81a44752cce86c9d1d6f4",
|
||||
"src/codebook/train_120_2.txt": "2e57e1f514d9e1ff165f3a6dd1f689af2565de6195300ce0d468af9b7f2120b3",
|
||||
"src/codebook/newamp1_energy_q.txt": "ae75dc2e0fbd38bd2341795f00162a677251ec66deff6015015e19168d7bfee2",
|
||||
"src/sine.c": "9d286a353734f6968e6fd6502d089a95d46a226757a16346fa9b27169b958252",
|
||||
"src/nlp.c": "5c35a44bc3093bd74fe7411e48214ed38afd59b0b84206d73b1751343f27c3ba",
|
||||
"src/postfilter.c": "52fd7d3131e947b71644851224d09351fd53974c6f4abb2c25a1d0f8d12a0d07",
|
||||
"src/kiss_fft.c": "f16ca65e00a766c8c17bbd8c068168e9615c9b9e493fda2acf2822d743cc40c8",
|
||||
"src/kiss_fftr.c": "fcd5fb59beae112c91a53832e4ff24242ef3192fa57f0845dd8dcbf11e46c16d",
|
||||
"src/_kiss_fft_guts.h": "25fbd1b559e52dd255bc0129806c84c863f21bbafe652c83e169438cff517a9e",
|
||||
"src/defines.h": "2b0c3f83f38a8bb7f49b3fad6634e4acbb946216b2bba634264d3cb4440243f0"
|
||||
},
|
||||
"adaptation_notes": [
|
||||
"Fixed-storage newamp1 and 128-point phase FFTs; default postfilter on, front EQ off",
|
||||
"One 10 ms synthesis model at a time; per-instance random and predictor histories",
|
||||
"Shared analysis preserves C scalar precision and pitch-refinement accumulation order",
|
||||
"Corrected inherited background-estimator voicing condition and pitch-search inclusive endpoint/integer history bin",
|
||||
"Reference scalar promotions retained for windows, twiddles, notch filter and phase synthesis; numerical oracle disables compiler FMA contraction to match Rust scalar operations"
|
||||
]
|
||||
}
|
||||
],
|
||||
"notices": {
|
||||
"crates/lxst-codec2/NOTICE": "33cc10cd398e8e724030091025d885ec10ee16b9d95d707ad5df7fe812c17f84",
|
||||
"crates/lxst-codec2/NOTICE": "ff1ada84455bc83cd13a4313624a47661f367758784447842604f7c4b595a53c",
|
||||
"crates/lxst-codec2/licenses/KISS-FFT-BSD-3-Clause.txt": "49eea0111dfb7038dc18f74034cc517690395ebac8f7768f999133b16e4bf064",
|
||||
"crates/lxst-codec2/licenses/LGPL-2.1.txt": "9ebb6f82b7380a62ac74c5f0322c88e6744dedf2ebe1f54d6f088282b39844bf",
|
||||
"crates/lxst-codec2/licenses/upstream-Cargo.toml": "939e2818dcb2945f52eceb71b37b512bf1796da53a05e0a69276d5a2e55f9eed",
|
||||
|
||||
@@ -11,9 +11,21 @@ initialisation; per-instance synthesis RNG; exact libm math on all targets;
|
||||
checked public frame shapes; corrected real-FFT input copying; shared the
|
||||
identical forward FFT plan and removed unreachable mode/rate storage; separated
|
||||
phase scratch lifetime from inverse FFT scratch for the MCU stack. The public API
|
||||
exposes only native 1600/3200 modes at 8 kHz mono. Other private upstream modes
|
||||
exposes native 700C/1600/3200 modes at 8 kHz mono. Other private upstream modes
|
||||
are not a supported API. See UPSTREAM.json for immutable original provenance.
|
||||
|
||||
The native 700C implementation and immutable codebooks additionally adapt
|
||||
David Rowe's Codec2 C implementation, Copyright 2017, under LGPL-2.1-only:
|
||||
https://github.com/drowe67/codec2 at commit
|
||||
310777b1c6f1af0bc7c72f5b32f80f6fd9136962. Source/codebook hashes are recorded in
|
||||
UPSTREAM.json. Modified for rsLXST on 2026-10-01: Rust newamp1 spectral
|
||||
quantization and phase reconstruction, fixed M-best scratch and FFT plans,
|
||||
streamed synthesis models, explicit mode identity, and default 700C settings.
|
||||
Shared analysis and synthesis preserve reference scalar promotions in pitch,
|
||||
windows, FFT twiddles, notch filtering and phase arithmetic. KISS FFT changes
|
||||
retain its BSD-3-Clause attribution. Corrected inherited
|
||||
background-estimator voicing and pitch-search endpoint/history-bin behavior.
|
||||
|
||||
New wrapper, tests and storage adaptation are provided under LGPL-2.1-only.
|
||||
Third-party libm retains its own MIT license and appears in the workspace's
|
||||
locked third-party inventory. Packaging must retain the applicable notices and
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Bounded Rust Codec2
|
||||
|
||||
Allocation-free `no_std` native 1600/3200 bit/s speech at mono 8 kHz PCM16.
|
||||
Allocation-free `no_std` native 700C/1600/3200 speech at mono 8 kHz PCM16.
|
||||
This is the pinned Rust Codec2 port with fixed storage, per-instance synthesis
|
||||
randomness and pure-Rust `libm` math. It has no allocator dependency.
|
||||
|
||||
@@ -11,14 +11,25 @@ are independent. Independent sessions require separate states. `reset` erases
|
||||
histories in place. Native input/output frame lengths must match `Mode` exactly;
|
||||
length errors do not advance state or modify output.
|
||||
|
||||
LXST framing and negotiation belong to `lxst-core`, not this backend. 700C,
|
||||
700C uses 320 PCM samples and four encoded bytes per native frame (28 bits plus
|
||||
four zero padding bits). Its default spectral postfilter is enabled and front
|
||||
EQ is disabled, matching the pinned C reference. Mode identity is explicit;
|
||||
700C and 1600 have equal sample counts but different bitstreams.
|
||||
|
||||
LXST framing and negotiation belong to `lxst-core`, not this backend.
|
||||
Opus, memo containers, audio drivers and real-time target qualification are not
|
||||
provided here. Codec state plus worst-case nested DSP stack and I/O buffers must
|
||||
fit the selected device budget. A target build is not a timing/stack measurement.
|
||||
|
||||
`cargo test -p lxst-codec2 --release` checks allocation-free initialization,
|
||||
reset and streaming; rejected inputs; independent duplex histories; hostile
|
||||
correctly-sized decoder frames; and the real-FFT second-half input regression.
|
||||
correctly-sized decoder frames; padding; and FFT, pitch-search and background
|
||||
estimator regressions. 700C codebooks can be reproduced from the pinned C source
|
||||
using `tools/generate-codec2-700c-codebooks.py SOURCE --check`. Numerical
|
||||
comparison uses the pinned C reference with compiler FMA contraction disabled
|
||||
to match Rust scalar operations; default compiler contraction may accumulate
|
||||
phase differences. Native-frame compatibility and live peer interoperability
|
||||
are distinct qualification gates.
|
||||
|
||||
See [NOTICE](NOTICE), [UPSTREAM.json](UPSTREAM.json) and [licenses](licenses/)
|
||||
for source provenance, modifications and original license notices.
|
||||
@@ -15,5 +15,35 @@
|
||||
"quantise.rs": "f1e831fddee5a657e4139ac0808339cede5f5a8b6e9784eda600f3a714bb81bb",
|
||||
"codebookjvm.rs": "6a5aba7b9be606b2d7b16054e897d8862f3bd4ec24fa3f78ff5659b361bd7266",
|
||||
"nlp.rs": "d86f14abc7ce709d1a36a5b4dce3a2bab30ed5999a04548b61548c433897a0c6"
|
||||
},
|
||||
"codec2_700c": {
|
||||
"repository": "https://github.com/drowe67/codec2",
|
||||
"commit": "310777b1c6f1af0bc7c72f5b32f80f6fd9136962",
|
||||
"license": "LGPL-2.1-only",
|
||||
"source_sha256": {
|
||||
"src/codec2.c": "57dcb29bd9376bb32f9ea5d6f16e36a4b635ddf976683f0c0c46fd4989550bf5",
|
||||
"src/newamp1.c": "8df144b2ef72abdf2fc3ff66ec5c682694bdb4e940a668d1c13b3f4335168c93",
|
||||
"src/newamp1.h": "457f8357a8ca2f064f77cb68abebfe1acf4fb6be82802b43244d7c926d356423",
|
||||
"src/mbest.c": "91e0126fc7a001d9a019cea49545263ed0c58dc4418eea871549505bc5b935fc",
|
||||
"src/phase.c": "751d3123d070c42fcb235affe154219f3326fb0e8a13335f4b9e1389ab295eb2",
|
||||
"src/quantise.c": "a9b6dbadfee5c79b5ba346e606152c735d1096c2f3552a3da3b39c024469732f",
|
||||
"src/codebook/train_120_1.txt": "a3aa8da88db8b4a9168023c2269a4f4f9555aec20ed81a44752cce86c9d1d6f4",
|
||||
"src/codebook/train_120_2.txt": "2e57e1f514d9e1ff165f3a6dd1f689af2565de6195300ce0d468af9b7f2120b3",
|
||||
"src/codebook/newamp1_energy_q.txt": "ae75dc2e0fbd38bd2341795f00162a677251ec66deff6015015e19168d7bfee2",
|
||||
"src/sine.c": "9d286a353734f6968e6fd6502d089a95d46a226757a16346fa9b27169b958252",
|
||||
"src/nlp.c": "5c35a44bc3093bd74fe7411e48214ed38afd59b0b84206d73b1751343f27c3ba",
|
||||
"src/postfilter.c": "52fd7d3131e947b71644851224d09351fd53974c6f4abb2c25a1d0f8d12a0d07",
|
||||
"src/kiss_fft.c": "f16ca65e00a766c8c17bbd8c068168e9615c9b9e493fda2acf2822d743cc40c8",
|
||||
"src/kiss_fftr.c": "fcd5fb59beae112c91a53832e4ff24242ef3192fa57f0845dd8dcbf11e46c16d",
|
||||
"src/_kiss_fft_guts.h": "25fbd1b559e52dd255bc0129806c84c863f21bbafe652c83e169438cff517a9e",
|
||||
"src/defines.h": "2b0c3f83f38a8bb7f49b3fad6634e4acbb946216b2bba634264d3cb4440243f0"
|
||||
},
|
||||
"adaptation_notes": [
|
||||
"Fixed-storage newamp1 and 128-point phase FFTs; default postfilter on, front EQ off",
|
||||
"One 10 ms synthesis model at a time; per-instance random and predictor histories",
|
||||
"Shared analysis preserves C scalar precision and pitch-refinement accumulation order",
|
||||
"Corrected inherited background-estimator voicing condition and pitch-search inclusive endpoint/integer history bin",
|
||||
"Reference scalar promotions retained for windows, twiddles, notch filter and phase synthesis; numerical oracle disables compiler FMA contraction to match Rust scalar operations"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -27,18 +27,22 @@ use core::mem::MaybeUninit;
|
||||
pub enum Mode {
|
||||
Rate1600,
|
||||
Rate3200,
|
||||
Rate700C,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
pub const fn samples(self) -> usize {
|
||||
match self {
|
||||
Self::Rate1600 => 320,
|
||||
Self::Rate1600 | Self::Rate700C => 320,
|
||||
Self::Rate3200 => 160,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn bytes(self) -> usize {
|
||||
8
|
||||
match self {
|
||||
Self::Rate700C => 4,
|
||||
Self::Rate1600 | Self::Rate3200 => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +82,7 @@ impl Codec {
|
||||
self.native.initialise(match mode {
|
||||
Mode::Rate1600 => native::Codec2Mode::MODE_1600,
|
||||
Mode::Rate3200 => native::Codec2Mode::MODE_3200,
|
||||
Mode::Rate700C => native::Codec2Mode::MODE_700C,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -89,9 +94,10 @@ impl Codec {
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> Mode {
|
||||
match self.native.samples_per_frame() {
|
||||
320 => Mode::Rate1600,
|
||||
_ => Mode::Rate3200,
|
||||
match self.native.mode() {
|
||||
native::Codec2Mode::MODE_1600 => Mode::Rate1600,
|
||||
native::Codec2Mode::MODE_3200 => Mode::Rate3200,
|
||||
native::Codec2Mode::MODE_700C => Mode::Rate700C,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,6 +13,9 @@ mod codebookge;
|
||||
use self::codebookge::*;
|
||||
mod codebookjvm;
|
||||
use self::codebookjvm::*;
|
||||
#[rustfmt::skip]
|
||||
mod codebook700c;
|
||||
mod newamp1;
|
||||
|
||||
const WO_BITS: i32 = 7;
|
||||
const WO_E_BITS: u32 = 8;
|
||||
@@ -148,16 +151,16 @@ mod inner {
|
||||
}
|
||||
impl<const N: usize> kiss_fft_state<N> {
|
||||
pub fn initialise(&mut self, nfft: usize, inverse_fft: i32) {
|
||||
assert!((nfft == 256 || nfft == 512) && nfft <= N);
|
||||
assert!((nfft == 128 || nfft == 256 || nfft == 512) && nfft <= N);
|
||||
self.nfft = nfft;
|
||||
self.inverse = inverse_fft;
|
||||
self.twiddles.initialise(nfft, kiss_fft_cpx::new());
|
||||
for i in 0..nfft {
|
||||
let mut phase = -2.0 * PI * i as f32 / nfft as f32;
|
||||
let mut phase = -2.0 * core::f64::consts::PI * i as f64 / nfft as f64;
|
||||
if inverse_fft != 0 {
|
||||
phase *= -1.0;
|
||||
}
|
||||
self.twiddles[i] = kiss_fft_cpx::kf_cexp(phase);
|
||||
self.twiddles[i] = kiss_fft_cpx::kf_cexp(phase as f32);
|
||||
}
|
||||
let mut n = nfft;
|
||||
let mut p = 4;
|
||||
@@ -200,8 +203,9 @@ mod inner {
|
||||
self.super_twiddles
|
||||
.initialise(nfft / 2, kiss_fft_cpx::new());
|
||||
for i in 0..nfft / 2 {
|
||||
let mut phase =
|
||||
-3.14159265358979323846264338327 * ((i as f32 + 1.0) / nfft as f32 + 0.5);
|
||||
let mut phase = (-core::f64::consts::PI
|
||||
* (f64::from((i + 1) as f32 / nfft as f32) + 0.5))
|
||||
as f32;
|
||||
if inverse_fft != 0 {
|
||||
phase *= -1.0;
|
||||
}
|
||||
@@ -227,8 +231,12 @@ mod inner {
|
||||
self.Fs = c2const.Fs;
|
||||
self.m = c2const.m_pitch;
|
||||
for i in 0..self.m / DEC {
|
||||
self.w[i] = 0.5
|
||||
- 0.5 * (2.0 * PI * i as f32 / (self.m as f32 / DEC as f32 - 1.0)).dsp_cos();
|
||||
self.w[i] = (0.5
|
||||
- 0.5
|
||||
* f64::from(
|
||||
((2.0 * 3.141592654_f64 * i as f64 / (self.m / DEC - 1) as f64) as f32)
|
||||
.dsp_cos(),
|
||||
)) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -338,6 +346,7 @@ struct Codec2Internal {
|
||||
se: f32, // running sum of squared error
|
||||
nse: u32, // number of terms in sum
|
||||
post_filter_en: i32,
|
||||
newamp: newamp1::State,
|
||||
}
|
||||
|
||||
/*---------------------------------------------------------------------------*\
|
||||
@@ -402,7 +411,9 @@ fn make_analysis_window(
|
||||
}
|
||||
let mut j = 0;
|
||||
for i in m_pitch / 2 - nw / 2..m_pitch / 2 + nw / 2 {
|
||||
w[i] = 0.5 - 0.5 * (TWO_PI * (j as f32) / ((nw as f32) - 1.0)).dsp_cos();
|
||||
w[i] = (0.5
|
||||
- 0.5 * f64::from(((6.283185307_f64 * j as f64 / (nw - 1) as f64) as f32).dsp_cos()))
|
||||
as f32;
|
||||
m += w[i] * w[i];
|
||||
j += 1;
|
||||
}
|
||||
@@ -601,7 +612,7 @@ pub enum Codec2Mode {
|
||||
MODE_3200,
|
||||
|
||||
MODE_1600,
|
||||
//MODE_700C,
|
||||
MODE_700C,
|
||||
//MODE_450,
|
||||
//MODE_450PWB,
|
||||
}
|
||||
@@ -614,6 +625,10 @@ pub struct Codec2 {
|
||||
}
|
||||
|
||||
impl Codec2 {
|
||||
pub fn mode(&self) -> Codec2Mode {
|
||||
self.internal.mode
|
||||
}
|
||||
|
||||
/// Creates a new Codec2 object suitable for encoding or decoding audio
|
||||
pub fn initialise(&mut self, mode: Codec2Mode) {
|
||||
let c2 = self;
|
||||
@@ -643,6 +658,9 @@ impl Codec2 {
|
||||
c2.internal.gamma = LPCPF_GAMMA;
|
||||
c2.internal.post_filter_en = 1;
|
||||
c2.internal.random = 1;
|
||||
if matches!(mode, MODE_700C) {
|
||||
c2.internal.newamp.initialise();
|
||||
}
|
||||
for i in 0..LPC_ORD {
|
||||
c2.internal.prev_lsps_dec[i] = i as f32 * PI / (LPC_ORD as f32 + 1.0);
|
||||
}
|
||||
@@ -661,7 +679,7 @@ impl Codec2 {
|
||||
MODE_3200 => 64,
|
||||
|
||||
MODE_1600 => 64,
|
||||
// MODE_700C => 28,
|
||||
MODE_700C => 28,
|
||||
// MODE_450 => 18,
|
||||
// MODE_450PWB => 18,
|
||||
}
|
||||
@@ -672,6 +690,7 @@ impl Codec2 {
|
||||
match self.internal.mode {
|
||||
MODE_3200 => 160,
|
||||
MODE_1600 => 320,
|
||||
MODE_700C => 320,
|
||||
//MODE_450PWB => 640,
|
||||
}
|
||||
}
|
||||
@@ -683,6 +702,7 @@ impl Codec2 {
|
||||
MODE_3200 => self.codec2_encode_3200(bits, speech),
|
||||
|
||||
MODE_1600 => self.codec2_encode_1600(bits, speech),
|
||||
MODE_700C => self.codec2_encode_700c(bits, speech),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -693,6 +713,7 @@ impl Codec2 {
|
||||
MODE_3200 => self.codec2_decode_3200(speech, bits),
|
||||
|
||||
MODE_1600 => self.codec2_decode_1600(speech, bits),
|
||||
MODE_700C => self.codec2_decode_700c(speech, bits),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1946,7 +1967,7 @@ impl Codec2 {
|
||||
&self.internal.W,
|
||||
&mut self.internal.prev_f0_enc,
|
||||
);
|
||||
model.Wo = TWO_PI / pitch;
|
||||
model.Wo = (6.283185307_f64 / f64::from(pitch)) as f32;
|
||||
model.L = (PI / model.Wo) as usize;
|
||||
|
||||
// estimate model parameters
|
||||
@@ -1970,6 +1991,16 @@ impl Codec2 {
|
||||
// call boundary is deliberate on MCU stacks, including fat-LTO builds.
|
||||
#[inline(never)]
|
||||
fn synthesise_phase(&mut self, model: &mut MODEL, Aw: &[COMP]) {
|
||||
if matches!(self.internal.mode, MODE_700C) {
|
||||
phase_synth_zero_order(
|
||||
self.internal.n_samp,
|
||||
model,
|
||||
&mut self.internal.ex_phase,
|
||||
Aw,
|
||||
&mut self.internal.random,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// LPC based phase synthesis
|
||||
let mut H = [COMP::new(); MAX_AMP + 1];
|
||||
sample_phase(model, &mut H, Aw);
|
||||
@@ -2218,33 +2249,35 @@ fn estimate_amplitudes(model: &mut MODEL, Sw: &[COMP], _W: &[f32], est_phase: i3
|
||||
|
||||
\*---------------------------------------------------------------------------*/
|
||||
fn two_stage_pitch_refinement(c2const: &C2const, model: &mut MODEL, Sw: &[COMP]) {
|
||||
// Preserve the C reference's scalar precision before f32 storage. Changing
|
||||
// these operations to f32 changes candidate/bin selection near boundaries.
|
||||
// Coarse refinement
|
||||
// pitch refinment minimum, maximum and step
|
||||
let mut pmax = TWO_PI / model.Wo + 5.0;
|
||||
let mut pmin = TWO_PI / model.Wo - 5.0;
|
||||
let mut pmax = (6.283185307_f64 / f64::from(model.Wo) + 5.0) as f32;
|
||||
let mut pmin = (6.283185307_f64 / f64::from(model.Wo) - 5.0) as f32;
|
||||
let mut pstep = 1.0;
|
||||
hs_pitch_refinement(model, Sw, pmin, pmax, pstep);
|
||||
|
||||
// Fine refinement
|
||||
|
||||
pmax = TWO_PI / model.Wo + 1.0;
|
||||
pmin = TWO_PI / model.Wo - 1.0;
|
||||
pmax = (6.283185307_f64 / f64::from(model.Wo) + 1.0) as f32;
|
||||
pmin = (6.283185307_f64 / f64::from(model.Wo) - 1.0) as f32;
|
||||
pstep = 0.25;
|
||||
hs_pitch_refinement(model, Sw, pmin, pmax, pstep);
|
||||
|
||||
// Limit range
|
||||
|
||||
if model.Wo < TWO_PI / (c2const.p_max as f32) {
|
||||
model.Wo = TWO_PI / (c2const.p_max as f32);
|
||||
if model.Wo < (6.283185307_f64 / c2const.p_max as f64) as f32 {
|
||||
model.Wo = (6.283185307_f64 / c2const.p_max as f64) as f32;
|
||||
}
|
||||
if model.Wo > TWO_PI / (c2const.p_min as f32) {
|
||||
model.Wo = TWO_PI / (c2const.p_min as f32);
|
||||
if model.Wo > (6.283185307_f64 / c2const.p_min as f64) as f32 {
|
||||
model.Wo = (6.283185307_f64 / c2const.p_min as f64) as f32;
|
||||
}
|
||||
|
||||
model.L = (PI / model.Wo).dsp_floor() as usize;
|
||||
model.L = ((3.141592654_f64 / f64::from(model.Wo)) as f32).dsp_floor() as usize;
|
||||
|
||||
// trap occasional round off issues with floorf()
|
||||
if model.Wo * model.L as f32 >= 0.95 * PI {
|
||||
if f64::from(model.Wo * model.L as f32) >= 0.95 * 3.141592654_f64 {
|
||||
model.L -= 1;
|
||||
}
|
||||
// assert(model.Wo*model.L < PI);
|
||||
@@ -2269,7 +2302,7 @@ fn two_stage_pitch_refinement(c2const: &C2const, model: &mut MODEL, Sw: &[COMP])
|
||||
fn hs_pitch_refinement(model: &mut MODEL, Sw: &[COMP], pmin: f32, pmax: f32, pstep: f32) {
|
||||
// Initialisation
|
||||
|
||||
model.L = (PI / model.Wo) as usize; // use initial pitch est. for L
|
||||
model.L = (3.141592654_f64 / f64::from(model.Wo)) as usize; // use initial pitch est. for L
|
||||
let mut Wom = model.Wo; // Wo that maximises E
|
||||
let mut Em = 0.0; // mamimum energy
|
||||
let r = TWO_PI / FFT_ENC as f32; // number of rads/bin
|
||||
@@ -2279,13 +2312,16 @@ fn hs_pitch_refinement(model: &mut MODEL, Sw: &[COMP], pmin: f32, pmax: f32, pst
|
||||
let mut p = pmin; // current pitch
|
||||
while p <= pmax {
|
||||
let mut E = 0.0; //energy for current pitch
|
||||
let Wo = TWO_PI / p; // current "test" fundamental freq.
|
||||
let Wo = (6.283185307_f64 / f64::from(p)) as f32; // current "test" fundamental freq.
|
||||
|
||||
let bin_step = Wo * one_on_r;
|
||||
let mut bin = bin_step;
|
||||
// Sum harmonic magnitudes
|
||||
for m in 1..model.L + 1 {
|
||||
for _ in 1..model.L + 1 {
|
||||
// bin for current harmonic centre
|
||||
let b = (m as f32 * Wo * one_on_r + 0.5) as usize;
|
||||
let b = (f64::from(bin) + 0.5) as usize;
|
||||
E += Sw[b].r * Sw[b].r + Sw[b].i * Sw[b].i;
|
||||
bin += bin_step;
|
||||
}
|
||||
// Compare to see if this is a maximum
|
||||
|
||||
@@ -2304,6 +2340,32 @@ mod tests {
|
||||
extern crate std;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn background_estimate_tracks_quiet_unvoiced_speech_only() {
|
||||
let mut model = MODEL::new(160.0);
|
||||
model.L = 10;
|
||||
model.A[1..=10].fill(10.0); // 20 dB, below the background threshold.
|
||||
let mut random = 1;
|
||||
let mut estimate = 0.0;
|
||||
model.voiced = 0;
|
||||
postfilter(&mut model, &mut estimate, &mut random);
|
||||
assert!(estimate > 0.0);
|
||||
let previous = estimate;
|
||||
model.voiced = 1;
|
||||
postfilter(&mut model, &mut estimate, &mut random);
|
||||
assert_eq!(
|
||||
estimate, previous,
|
||||
"voiced speech must not raise background noise"
|
||||
);
|
||||
model.voiced = 0;
|
||||
model.A[1..=10].fill(1000.0);
|
||||
postfilter(&mut model, &mut estimate, &mut random);
|
||||
assert_eq!(
|
||||
estimate, previous,
|
||||
"loud unvoiced speech must not train background noise"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_fft_preserves_second_half_input() {
|
||||
let mut storage = std::boxed::Box::<crate::Codec>::new_uninit();
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
// Codec2 700C/newamp1, adapted to fixed-storage Rust from David Rowe's
|
||||
// codec2.c, newamp1.c, mbest.c, phase.c and quantise.c (Copyright 2017).
|
||||
// Source commit and hashes: ../../UPSTREAM.json. LGPL-2.1-only; see NOTICE
|
||||
// and licenses/LGPL-2.1.txt. No C code or allocator is linked at runtime.
|
||||
use super::{codebook700c::*, *};
|
||||
|
||||
const K: usize = 20;
|
||||
const NFFT: usize = 128;
|
||||
const NS: usize = NFFT / 2 + 1;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct State {
|
||||
frequencies: [f32; K],
|
||||
previous: [f32; K],
|
||||
wo_left: f32,
|
||||
voiced_left: i32,
|
||||
forward: kiss_fft_state<NFFT>,
|
||||
inverse: kiss_fft_state<NFFT>,
|
||||
}
|
||||
|
||||
// Match the portable upstream POW10F configuration used by the pinned oracle.
|
||||
fn pow10(value: f32) -> f32 {
|
||||
libm::expf(2.302585092994046_f32 * value)
|
||||
}
|
||||
|
||||
// Double-expression variant preserves the C macro promotion before expf.
|
||||
fn pow10_double(value: f64) -> f32 {
|
||||
libm::expf((f64::from(2.302585092994046_f32) * value) as f32)
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub(super) fn initialise(&mut self) {
|
||||
fn mel(hz: f32) -> f32 {
|
||||
libm::floorf(
|
||||
(2595.0 * f64::from(libm::log10f((1.0 + f64::from(hz) / 700.0) as f32)) + 0.5)
|
||||
as f32,
|
||||
)
|
||||
}
|
||||
let start = mel(200.0);
|
||||
let step = (mel(3700.0) - start) / (K - 1) as f32;
|
||||
let mut value = start;
|
||||
for frequency in &mut self.frequencies {
|
||||
*frequency = (0.7 * (f64::from(pow10_double(f64::from(value) / 2595.0)) - 1.0)) as f32;
|
||||
value += step;
|
||||
}
|
||||
self.previous.fill(0.0);
|
||||
self.wo_left = 0.0;
|
||||
self.voiced_left = 0;
|
||||
self.forward.initialise(NFFT, 0);
|
||||
self.inverse.initialise(NFFT, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve upstream's parabolic interpolation and strict tie ordering. All
|
||||
// callers have monotonically increasing frequency axes with at least 3 points.
|
||||
fn interpolate(y: &mut [f32], xp: &[f32], yp: &[f32], x: &[f32]) {
|
||||
debug_assert!(xp.len() >= 3 && xp.len() == yp.len() && y.len() == x.len());
|
||||
let mut k = 0;
|
||||
for (yi, &xi) in y.iter_mut().zip(x) {
|
||||
while xp[k + 1] < xi && k < xp.len() - 3 {
|
||||
k += 1;
|
||||
}
|
||||
let (x1, x2, x3) = (xp[k], xp[k + 1], xp[k + 2]);
|
||||
let (y1, y2, y3) = (yp[k], yp[k + 1], yp[k + 2]);
|
||||
let a = ((y3 - y2) / (x3 - x2) - (y2 - y1) / (x2 - x1)) / (x3 - x1);
|
||||
let b = ((y3 - y2) / (x3 - x2) * (x2 - x1) + (y2 - y1) / (x2 - x1) * (x3 - x2)) / (x3 - x1);
|
||||
*yi = a * (xi - x2) * (xi - x2) + b * (xi - x2) + y2;
|
||||
}
|
||||
}
|
||||
|
||||
fn harmonic_frequency(model: &MODEL, m: usize) -> f32 {
|
||||
(f64::from(m as f32 * model.Wo) * 4.0 / core::f64::consts::PI) as f32
|
||||
}
|
||||
|
||||
fn rate_k(model: &MODEL, frequencies: &[f32; K]) -> [f32; K] {
|
||||
let mut amplitudes = [0.0_f32; MAX_AMP + 1];
|
||||
let mut harmonics = [0.0_f32; MAX_AMP + 1];
|
||||
let mut peak = -100.0_f32;
|
||||
for m in 1..=model.L {
|
||||
amplitudes[m] = 20.0 * libm::log10f((f64::from(model.A[m]) + 1e-16) as f32);
|
||||
peak = peak.max(amplitudes[m]);
|
||||
harmonics[m] = harmonic_frequency(model, m);
|
||||
}
|
||||
for amplitude in &mut amplitudes[1..=model.L] {
|
||||
*amplitude = amplitude.max(peak - 50.0);
|
||||
}
|
||||
let mut result = [0.0; K];
|
||||
interpolate(
|
||||
&mut result,
|
||||
&harmonics[1..=model.L],
|
||||
&litudes[1..=model.L],
|
||||
frequencies,
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
// Fixed five-candidate M-best search. Strict < preserves the first codebook
|
||||
// entry on ties, including ties crossing the two-stage search order.
|
||||
fn quantize(target: &[f32; K]) -> (usize, usize) {
|
||||
let mut best = [(1e32_f32, 0_usize); 5];
|
||||
for (index, vector) in VQ1.chunks_exact(K).enumerate() {
|
||||
let mut error = 0.0;
|
||||
for k in 0..K {
|
||||
let difference = vector[k] - target[k];
|
||||
error += difference * difference;
|
||||
}
|
||||
if let Some(position) = best.iter().position(|entry| error < entry.0) {
|
||||
for n in (position + 1..best.len()).rev() {
|
||||
best[n] = best[n - 1];
|
||||
}
|
||||
best[position] = (error, index);
|
||||
}
|
||||
}
|
||||
// Only the winning second-stage entry is consumed by the reference codec;
|
||||
// retaining its best 1 gives the same strict ordering as the full list.
|
||||
let mut result = (1e32_f32, 0, 0);
|
||||
for (_, first) in best {
|
||||
let mut residual = [0.0; K];
|
||||
for k in 0..K {
|
||||
residual[k] = target[k] - VQ1[first * K + k];
|
||||
}
|
||||
for (second, vector) in VQ2.chunks_exact(K).enumerate() {
|
||||
let mut error = 0.0;
|
||||
for k in 0..K {
|
||||
let difference = vector[k] - residual[k];
|
||||
error += difference * difference;
|
||||
}
|
||||
if error < result.0 {
|
||||
result = (error, first, second);
|
||||
}
|
||||
}
|
||||
}
|
||||
(result.1, result.2)
|
||||
}
|
||||
|
||||
fn encode_model(model: &MODEL, state: &State, constants: &C2const) -> [i32; 4] {
|
||||
let mut vector = rate_k(model, &state.frequencies);
|
||||
let mut sum = 0.0;
|
||||
for value in vector {
|
||||
sum += value;
|
||||
}
|
||||
let mean = sum / K as f32;
|
||||
for value in &mut vector {
|
||||
*value -= mean;
|
||||
}
|
||||
// The pinned default disables front EQ. Its unused diagnostic/EQ history
|
||||
// has no effect on the wire data and is not retained in the bounded backend.
|
||||
let (first, second) = quantize(&vector);
|
||||
let mut energy = 0;
|
||||
let mut error = f32::MAX;
|
||||
for (index, value) in ENERGY.iter().enumerate() {
|
||||
let difference = value - mean;
|
||||
let candidate = difference * difference;
|
||||
if candidate < error {
|
||||
error = candidate;
|
||||
energy = index;
|
||||
}
|
||||
}
|
||||
let pitch = if model.voiced != 0 {
|
||||
let min = constants.Wo_min.dsp_log10();
|
||||
let max = constants.Wo_max.dsp_log10();
|
||||
let normal = (model.Wo.dsp_log10() - min) / (max - min);
|
||||
(64.0 * normal + 0.5).dsp_floor().clamp(1.0, 63.0) as i32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
[first as i32, second as i32, energy as i32, pitch]
|
||||
}
|
||||
|
||||
fn decode_vector(indexes: &[i32; 4], frequencies: &[f32; K]) -> [f32; K] {
|
||||
let mut result = [0.0; K];
|
||||
let mut pre = [0.0; K];
|
||||
let (mut before, mut after) = (0.0, 0.0);
|
||||
for k in 0..K {
|
||||
result[k] = VQ1[indexes[0] as usize * K + k] + VQ2[indexes[1] as usize * K + k];
|
||||
pre[k] = 20.0 * libm::log10f((f64::from(frequencies[k]) / 0.3) as f32);
|
||||
result[k] += pre[k];
|
||||
before += pow10_double(f64::from(result[k]) / 10.0);
|
||||
result[k] *= 1.5;
|
||||
after += pow10_double(f64::from(result[k]) / 10.0);
|
||||
}
|
||||
let gain = 10.0 * (after / before).dsp_log10();
|
||||
for k in 0..K {
|
||||
result[k] -= gain;
|
||||
result[k] -= pre[k];
|
||||
result[k] += ENERGY[indexes[2] as usize];
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn rate_l(model: &mut MODEL, vector: &[f32; K], frequencies: &[f32; K]) {
|
||||
let mut levels = [0.0; K + 2];
|
||||
let mut axis = [0.0; K + 2];
|
||||
levels[1..=K].copy_from_slice(vector);
|
||||
axis[1..=K].copy_from_slice(frequencies);
|
||||
axis[K + 1] = 4.0;
|
||||
let mut harmonics = [0.0; MAX_AMP + 1];
|
||||
let mut amplitudes = [0.0; MAX_AMP + 1];
|
||||
for m in 1..=model.L {
|
||||
harmonics[m] = harmonic_frequency(model, m);
|
||||
}
|
||||
interpolate(
|
||||
&mut amplitudes[1..=model.L],
|
||||
&axis,
|
||||
&levels,
|
||||
&harmonics[1..=model.L],
|
||||
);
|
||||
for m in 1..=model.L {
|
||||
model.A[m] = pow10_double(f64::from(amplitudes[m]) / 20.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the cepstral FFT scratch lifetime separate from synthesis. One 10 ms
|
||||
// model is reconstructed at a time instead of retaining four models and H[].
|
||||
#[inline(never)]
|
||||
fn determine_phase(model: &MODEL, state: &State, h: &mut [COMP; MAX_AMP + 1]) {
|
||||
let mut amplitudes = [0.0; MAX_AMP + 1];
|
||||
let mut harmonics = [0.0; MAX_AMP + 1];
|
||||
for m in 1..=model.L {
|
||||
amplitudes[m] = 20.0 * model.A[m].dsp_log10();
|
||||
harmonics[m] = harmonic_frequency(model, m);
|
||||
}
|
||||
let mut spectrum = [0.0; NS];
|
||||
let mut frequencies = [0.0; NS];
|
||||
for (i, frequency) in frequencies.iter_mut().enumerate() {
|
||||
*frequency = 8.0 * i as f32 / NFFT as f32;
|
||||
}
|
||||
interpolate(
|
||||
&mut spectrum,
|
||||
&harmonics[1..=model.L],
|
||||
&litudes[1..=model.L],
|
||||
&frequencies,
|
||||
);
|
||||
let mut input = [COMP::new(); NFFT];
|
||||
let mut output = [COMP::new(); NFFT];
|
||||
input[0].r = spectrum[0];
|
||||
for i in 1..NS {
|
||||
input[i].r = spectrum[i];
|
||||
input[NFFT - i].r = spectrum[i];
|
||||
}
|
||||
kiss_fft::kiss_fft(&state.inverse, &input, &mut output);
|
||||
for value in &mut output {
|
||||
value.r /= NFFT as f32;
|
||||
value.i /= NFFT as f32;
|
||||
}
|
||||
input.fill(COMP::new());
|
||||
input[0] = output[0];
|
||||
input[NS - 1] = output[NS - 1];
|
||||
for i in 1..NS - 1 {
|
||||
input[i].r = output[i].r + output[NFFT - i].r;
|
||||
input[i].i = output[i].i + output[NFFT - i].i;
|
||||
}
|
||||
kiss_fft::kiss_fft(&state.forward, &input, &mut output);
|
||||
let scale = (20.0 / f64::from(libm::logf(10.0))) as f32;
|
||||
for m in 1..=model.L {
|
||||
let bin = libm::floorf(
|
||||
(0.5 + f64::from(m as f32 * model.Wo * NFFT as f32) / (2.0 * core::f64::consts::PI))
|
||||
as f32,
|
||||
) as usize;
|
||||
debug_assert!(bin < NS);
|
||||
let phase = output[bin].i / scale;
|
||||
h[m].r = phase.dsp_cos();
|
||||
h[m].i = phase.dsp_sin();
|
||||
}
|
||||
}
|
||||
|
||||
impl Codec2 {
|
||||
pub(super) fn codec2_encode_700c(&mut self, bits: &mut [u8], speech: &[i16]) {
|
||||
let mut model = MODEL::new(self.internal.c2const.p_max as f32);
|
||||
for frame in speech.chunks_exact(80) {
|
||||
self.analyse_one_frame(&mut model, frame);
|
||||
}
|
||||
let indexes = encode_model(&model, &self.internal.newamp, &self.internal.c2const);
|
||||
bits.fill(0);
|
||||
let mut offset = 0;
|
||||
for (value, width) in indexes.into_iter().zip([9, 9, 4, 6]) {
|
||||
pack_natural_or_gray(bits, &mut offset, value, width, 0);
|
||||
}
|
||||
debug_assert_eq!(offset, 28);
|
||||
}
|
||||
|
||||
pub(super) fn codec2_decode_700c(&mut self, speech: &mut [i16], bits: &[u8]) {
|
||||
let mut offset = 0;
|
||||
let mut indexes = [0; 4];
|
||||
for (value, width) in indexes.iter_mut().zip([9, 9, 4, 6]) {
|
||||
*value = unpack_natural_or_gray(bits, &mut offset, width, 0);
|
||||
}
|
||||
let right = decode_vector(&indexes, &self.internal.newamp.frequencies);
|
||||
let unvoiced_wo = (2.0 * core::f64::consts::PI / 100.0) as f32;
|
||||
let voiced_right = i32::from(indexes[3] != 0);
|
||||
let wo_right = if voiced_right != 0 {
|
||||
let min = self.internal.c2const.Wo_min.dsp_log10();
|
||||
let step = (self.internal.c2const.Wo_max.dsp_log10() - min) / 64.0;
|
||||
pow10(min + step * indexes[3] as f32)
|
||||
} else {
|
||||
unvoiced_wo
|
||||
};
|
||||
for frame in 0..4 {
|
||||
let mut model = MODEL::new(self.internal.c2const.p_max as f32);
|
||||
let c = 1.0 - frame as f32 / 4.0;
|
||||
let left = &self.internal.newamp;
|
||||
match (left.voiced_left != 0, voiced_right != 0) {
|
||||
(true, true) => {
|
||||
model.Wo = (f64::from(left.wo_left * c)
|
||||
+ f64::from(wo_right) * (1.0 - f64::from(c)))
|
||||
as f32;
|
||||
model.voiced = 1;
|
||||
}
|
||||
(true, false) if frame < 2 => {
|
||||
model.Wo = left.wo_left;
|
||||
model.voiced = 1;
|
||||
}
|
||||
(false, true) if frame >= 2 => {
|
||||
model.Wo = wo_right;
|
||||
model.voiced = 1;
|
||||
}
|
||||
_ => {
|
||||
model.Wo = unvoiced_wo;
|
||||
model.voiced = 0;
|
||||
}
|
||||
}
|
||||
model.L = libm::floorf((core::f64::consts::PI / f64::from(model.Wo)) as f32) as usize;
|
||||
let mut vector = [0.0; K];
|
||||
for k in 0..K {
|
||||
vector[k] = (f64::from(left.previous[k] * c)
|
||||
+ f64::from(right[k]) * (1.0 - f64::from(c)))
|
||||
as f32;
|
||||
}
|
||||
rate_l(&mut model, &vector, &left.frequencies);
|
||||
let mut h = [COMP::new(); MAX_AMP + 1];
|
||||
determine_phase(&model, left, &mut h);
|
||||
self.synthesise_one_frame(
|
||||
&mut speech[80 * frame..80 * (frame + 1)],
|
||||
&mut model,
|
||||
&h,
|
||||
1.5,
|
||||
);
|
||||
}
|
||||
self.internal.newamp.previous = right;
|
||||
self.internal.newamp.wo_left = wo_right;
|
||||
self.internal.newamp.voiced_left = voiced_right;
|
||||
}
|
||||
}
|
||||
@@ -102,7 +102,7 @@ const nlp_fir: [f32; 48] = [
|
||||
];
|
||||
|
||||
//const PMAX_M: i32 = 320; /* maximum NLP analysis window size */
|
||||
const COEFF: f32 = 0.95; /* notch filter parameter */
|
||||
const COEFF: f64 = 0.95; /* notch filter parameter */
|
||||
const PE_FFT_SIZE: i32 = 512; /* DFT size for pitch estimation */
|
||||
const DEC: i32 = 5; /* decimation factor */
|
||||
const SAMPLE_RATE: i32 = 8000;
|
||||
@@ -148,7 +148,7 @@ fn post_process_sub_multiples(
|
||||
let mut mult = 2;
|
||||
let min_bin = PE_FFT_SIZE * DEC / pmax;
|
||||
let mut cmax_bin = gmax_bin;
|
||||
let prev_f0_bin = (*prev_f0) * ((PE_FFT_SIZE * DEC) as f32) / (SAMPLE_RATE as f32);
|
||||
let prev_f0_bin = ((*prev_f0) * ((PE_FFT_SIZE * DEC) as f32) / (SAMPLE_RATE as f32)) as i32;
|
||||
|
||||
while gmax_bin / mult >= min_bin {
|
||||
let b = gmax_bin / mult; /* determine search interval */
|
||||
@@ -160,14 +160,14 @@ fn post_process_sub_multiples(
|
||||
/* lower threshold to favour previous frames pitch estimate,
|
||||
this is a form of pitch tracking */
|
||||
|
||||
let thresh = if (prev_f0_bin > bmin as f32) && (prev_f0_bin < bmax as f32) {
|
||||
let thresh = if (prev_f0_bin > bmin as i32) && (prev_f0_bin < bmax as i32) {
|
||||
CNLP * 0.5 * gmax
|
||||
} else {
|
||||
CNLP * gmax
|
||||
};
|
||||
let mut lmax = 0.0;
|
||||
let mut lmax_bin = bmin;
|
||||
for b in bmin..bmax {
|
||||
for b in bmin..=bmax {
|
||||
/* look for maximum in interval */
|
||||
if Fw[b].r > lmax {
|
||||
lmax = Fw[b].r;
|
||||
@@ -186,6 +186,34 @@ fn post_process_sub_multiples(
|
||||
cmax_bin as f32 * SAMPLE_RATE as f32 / (PE_FFT_SIZE as f32 * DEC as f32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn submultiple_search_includes_upper_interval_endpoint() {
|
||||
let mut spectrum = [COMP::new(); PE_FFT_SIZE as usize];
|
||||
spectrum[80].r = 100.0;
|
||||
spectrum[48].r = 50.0; // Upper endpoint of the 80/2 search interval.
|
||||
assert_eq!(
|
||||
post_process_sub_multiples(&spectrum, 20, 160, 100.0, 80, &50.0),
|
||||
150.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pitch_history_uses_an_integer_bin_before_threshold_comparison() {
|
||||
let mut spectrum = [COMP::new(); PE_FFT_SIZE as usize];
|
||||
spectrum[80].r = 100.0;
|
||||
spectrum[40].r = 20.0; // Above tracking threshold, below normal threshold.
|
||||
let previous = 32.5 * SAMPLE_RATE as f32 / (PE_FFT_SIZE * DEC) as f32;
|
||||
assert_eq!(
|
||||
post_process_sub_multiples(&spectrum, 20, 160, 100.0, 80, &previous),
|
||||
250.0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/*---------------------------------------------------------------------------*\
|
||||
|
||||
FUNCTION....: fdmdv_16_to_8()
|
||||
@@ -287,7 +315,7 @@ pub fn nlp(
|
||||
for i in m - n..m {
|
||||
/* notch filter at DC */
|
||||
let mut notch = nlp.sq[i] - nlp.mem_x;
|
||||
notch += COEFF * nlp.mem_y;
|
||||
notch = (f64::from(notch) + COEFF * f64::from(nlp.mem_y)) as f32;
|
||||
nlp.mem_x = nlp.sq[i];
|
||||
nlp.mem_y = notch;
|
||||
nlp.sq[i] = notch + 1.0; /* With 0 input vectors to codec,
|
||||
|
||||
@@ -950,7 +950,8 @@ pub fn phase_synth_zero_order(
|
||||
*/
|
||||
|
||||
*ex_phase += (model.Wo) * n_samp as f32;
|
||||
*ex_phase -= TWO_PI * (*ex_phase / TWO_PI + 0.5).dsp_floor();
|
||||
let turns = ((f64::from(*ex_phase) / 6.283185307_f64 + 0.5) as f32).dsp_floor();
|
||||
*ex_phase = (f64::from(*ex_phase) - 6.283185307_f64 * f64::from(turns)) as f32;
|
||||
|
||||
for m in 1..model.L + 1 {
|
||||
// generate excitation
|
||||
@@ -963,7 +964,8 @@ pub fn phase_synth_zero_order(
|
||||
// phase is not needed in the unvoiced case, but no harm in
|
||||
// keeping it.
|
||||
|
||||
let phi = TWO_PI * codec2_rand(random) / CODEC2_RAND_MAX;
|
||||
let phi = (6.283185307_f64 * f64::from(codec2_rand(random))
|
||||
/ f64::from(CODEC2_RAND_MAX)) as f32;
|
||||
Ex[m].r = phi.dsp_cos();
|
||||
Ex[m].i = phi.dsp_sin();
|
||||
}
|
||||
@@ -975,7 +977,7 @@ pub fn phase_synth_zero_order(
|
||||
|
||||
// modify sinusoidal phase
|
||||
|
||||
let new_phi = A_[m].i.dsp_atan2(A_[m].r + 1E-12);
|
||||
let new_phi = A_[m].i.dsp_atan2((f64::from(A_[m].r) + 1E-12) as f32);
|
||||
model.phi[m] = new_phi;
|
||||
}
|
||||
}
|
||||
@@ -1328,7 +1330,9 @@ pub fn synthesise(
|
||||
|
||||
// Now set up frequency domain synthesised speech
|
||||
for l in 1..model.L + 1 {
|
||||
let mut b = (l as f32 * model.Wo * FFT_DEC as f32 / TWO_PI + 0.5) as usize;
|
||||
// Preserve the reference C promotion at the bin boundary.
|
||||
let mut b =
|
||||
(f64::from(l as f32 * model.Wo * FFT_DEC as f32) / 6.283185307_f64 + 0.5) as usize;
|
||||
if b > ((FFT_DEC / 2) - 1) {
|
||||
b = (FFT_DEC / 2) - 1;
|
||||
}
|
||||
@@ -1367,7 +1371,7 @@ pub fn synthesise(
|
||||
}
|
||||
|
||||
const BG_THRESH: f32 = 40.0; // only consider low levels signals for bg_est
|
||||
const BG_BETA: f32 = 0.1; // averaging filter constant
|
||||
const BG_BETA: f64 = 0.1; // reference scalar precision for the averaging filter
|
||||
const BG_MARGIN: f32 = 6.0; // harmonics this far above BG noise are
|
||||
// randomised. Helped make bg noise less
|
||||
// spikey (impulsive) for mmt1, but speech was
|
||||
@@ -1432,18 +1436,22 @@ pub fn postfilter(model: &mut MODEL, bg_est: &mut f32, random: &mut u32) {
|
||||
// of the threshold is to prevent updating during high level
|
||||
// speech.
|
||||
|
||||
if e < BG_THRESH && model.voiced != 0 {
|
||||
*bg_est = *bg_est * (1.0 - BG_BETA) + e * BG_BETA;
|
||||
if e < BG_THRESH && model.voiced == 0 {
|
||||
*bg_est = (f64::from(*bg_est) * (1.0 - BG_BETA) + f64::from(e) * BG_BETA) as f32;
|
||||
}
|
||||
// now mess with phases during voiced frames to make any harmonics
|
||||
// less then our background estimate unvoiced.
|
||||
|
||||
// let mut uv = 0;
|
||||
let thresh = 10.0_f32.dsp_powf((*bg_est + BG_MARGIN) / 20.0);
|
||||
let thresh = libm::expf(
|
||||
(f64::from(2.302585092994046_f32) * ((f64::from(*bg_est) + f64::from(BG_MARGIN)) / 20.0))
|
||||
as f32,
|
||||
);
|
||||
if model.voiced != 0 {
|
||||
for m in 1..model.L + 1 {
|
||||
if model.A[m] < thresh {
|
||||
model.phi[m] = (TWO_PI / CODEC2_RAND_MAX) * codec2_rand(random);
|
||||
model.phi[m] = ((6.283185307_f64 / f64::from(CODEC2_RAND_MAX))
|
||||
* f64::from(codec2_rand(random))) as f32;
|
||||
//uv++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ static ALLOCATOR: Meter = Meter;
|
||||
// One process/thread: unrelated parallel test allocations cannot contaminate
|
||||
// the count. Large states are allocated before measurement and initialised in place.
|
||||
fn main() {
|
||||
for mode in [Mode::Rate1600, Mode::Rate3200] {
|
||||
for mode in [Mode::Rate1600, Mode::Rate3200, Mode::Rate700C] {
|
||||
let mut duplex_storage = Box::<Codec>::new_uninit();
|
||||
let mut encoder_storage = Box::<Codec>::new_uninit();
|
||||
let mut decoder_storage = Box::<Codec>::new_uninit();
|
||||
@@ -28,6 +28,7 @@ fn main() {
|
||||
let encoder = Codec::initialise(&mut encoder_storage, mode);
|
||||
let decoder = Codec::initialise(&mut decoder_storage, mode);
|
||||
let samples = mode.samples();
|
||||
let bytes = mode.bytes();
|
||||
let mut input = [0_i16; 320];
|
||||
let mut expected = [0_i16; 320];
|
||||
let mut actual = [0_i16; 320];
|
||||
@@ -58,24 +59,40 @@ fn main() {
|
||||
);
|
||||
assert_eq!(same, [0xA5; 8]);
|
||||
assert_eq!(
|
||||
duplex.encode(&input[..samples], &mut same[..7]),
|
||||
duplex.encode(&input[..samples], &mut same[..bytes - 1]),
|
||||
Err(Error::EncodedLength)
|
||||
);
|
||||
actual.fill(123);
|
||||
assert_eq!(
|
||||
duplex.decode(&encoded[..7], &mut actual[..samples]),
|
||||
duplex.decode(&encoded[..bytes - 1], &mut actual[..samples]),
|
||||
Err(Error::EncodedLength)
|
||||
);
|
||||
assert_eq!(
|
||||
duplex.decode(&encoded, &mut actual[..samples - 1]),
|
||||
duplex.decode(&encoded[..bytes], &mut actual[..samples - 1]),
|
||||
Err(Error::PcmLength)
|
||||
);
|
||||
assert!(actual.iter().all(|v| *v == 123));
|
||||
encoder.encode(&input[..samples], &mut encoded).unwrap();
|
||||
duplex.encode(&input[..samples], &mut same).unwrap();
|
||||
assert_eq!(encoded, same, "receive activity changed encoder history");
|
||||
decoder.decode(&encoded, &mut expected[..samples]).unwrap();
|
||||
duplex.decode(&encoded, &mut actual[..samples]).unwrap();
|
||||
encoder
|
||||
.encode(&input[..samples], &mut encoded[..bytes])
|
||||
.unwrap();
|
||||
duplex
|
||||
.encode(&input[..samples], &mut same[..bytes])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
encoded[..bytes],
|
||||
same[..bytes],
|
||||
"receive activity changed encoder history"
|
||||
);
|
||||
assert!(same[bytes..].iter().all(|byte| *byte == 0xA5));
|
||||
if mode == Mode::Rate700C {
|
||||
assert_eq!(encoded[3] & 0x0f, 0, "700C native padding");
|
||||
}
|
||||
decoder
|
||||
.decode(&encoded[..bytes], &mut expected[..samples])
|
||||
.unwrap();
|
||||
duplex
|
||||
.decode(&encoded[..bytes], &mut actual[..samples])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
expected[..samples],
|
||||
actual[..samples],
|
||||
@@ -87,7 +104,7 @@ fn main() {
|
||||
decoder.reset(mode);
|
||||
}
|
||||
}
|
||||
// Every 64-bit payload is valid codec data. Exercise decoder indices on
|
||||
// Every correctly-sized payload is valid codec data. Exercise decoder indices on
|
||||
// hostile but correctly-sized frames, including both extrema.
|
||||
for frame in 0..10000 {
|
||||
for byte in &mut encoded {
|
||||
@@ -98,7 +115,9 @@ fn main() {
|
||||
_ => (rng >> 24) as u8,
|
||||
};
|
||||
}
|
||||
duplex.decode(&encoded, &mut actual[..samples]).unwrap();
|
||||
duplex
|
||||
.decode(&encoded[..bytes], &mut actual[..samples])
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
ALLOCATIONS.load(Relaxed),
|
||||
@@ -107,7 +126,8 @@ fn main() {
|
||||
);
|
||||
let other = match mode {
|
||||
Mode::Rate1600 => Mode::Rate3200,
|
||||
Mode::Rate3200 => Mode::Rate1600,
|
||||
Mode::Rate3200 => Mode::Rate700C,
|
||||
Mode::Rate700C => Mode::Rate1600,
|
||||
};
|
||||
duplex.reset(other);
|
||||
assert_eq!(duplex.mode(), other);
|
||||
|
||||
@@ -32,6 +32,7 @@ impl Codec2Backend for &mut lxst_codec2::Codec {
|
||||
match lxst_codec2::Codec::mode(self) {
|
||||
lxst_codec2::Mode::Rate1600 => Codec2Mode::Mode1600,
|
||||
lxst_codec2::Mode::Rate3200 => Codec2Mode::Mode3200,
|
||||
lxst_codec2::Mode::Rate700C => Codec2Mode::Mode700C,
|
||||
}
|
||||
}
|
||||
fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error> {
|
||||
|
||||
@@ -14,6 +14,7 @@ impl Codec2Backend for Native {
|
||||
match self.0.mode() {
|
||||
Mode::Rate1600 => Codec2Mode::Mode1600,
|
||||
Mode::Rate3200 => Codec2Mode::Mode3200,
|
||||
Mode::Rate700C => Codec2Mode::Mode700C,
|
||||
}
|
||||
}
|
||||
fn encode_native(&mut self, pcm: &[i16], bytes: &mut [u8]) -> Result<(), Self::Error> {
|
||||
@@ -34,6 +35,7 @@ pub(crate) struct Codec2Audio {
|
||||
impl Codec2Audio {
|
||||
fn new(profile: Profile) -> Result<Self, Error> {
|
||||
let mode = match profile {
|
||||
Profile::BandwidthUltraLow => Mode::Rate700C,
|
||||
Profile::BandwidthVeryLow => Mode::Rate1600,
|
||||
Profile::BandwidthLow => Mode::Rate3200,
|
||||
_ => return Err(Error::Audio("unsupported native Codec2 profile".into())),
|
||||
|
||||
@@ -4051,7 +4051,11 @@ async fn native_codec2_duplex_and_input_lease_use_the_real_link() {
|
||||
|
||||
#[test]
|
||||
fn native_codec2_rejects_bad_shapes_and_mode_without_poisoning_valid_media() {
|
||||
for profile in [Profile::BandwidthVeryLow, Profile::BandwidthLow] {
|
||||
for profile in [
|
||||
Profile::BandwidthUltraLow,
|
||||
Profile::BandwidthVeryLow,
|
||||
Profile::BandwidthLow,
|
||||
] {
|
||||
let mut encoder = media::AudioEncoder::new(profile).unwrap();
|
||||
let mut invalid = synthetic_frame_for_profile(profile);
|
||||
invalid.samples[0] = f32::NAN;
|
||||
@@ -4066,5 +4070,4 @@ fn native_codec2_rejects_bad_shapes_and_mode_without_poisoning_valid_media() {
|
||||
packet.payload[0] = mode;
|
||||
assert!(decoder.decode_frame(&packet).is_ok());
|
||||
}
|
||||
assert!(media::AudioEncoder::new(Profile::BandwidthUltraLow).is_err());
|
||||
}
|
||||
@@ -142,6 +142,7 @@ def build_inventory() -> dict:
|
||||
"repository": provenance["repository"], "source": "local-adaptation",
|
||||
"upstreamCommit": provenance["commit"], "crateChecksum": provenance["crate_sha256"],
|
||||
"provenance": "crates/lxst-codec2/UPSTREAM.json",
|
||||
"additionalSources": [provenance["codec2_700c"]],
|
||||
"notices": {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in [adapted / "NOTICE", *sorted((adapted / "licenses").iterdir())]},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate immutable Rust 700C codebooks from the pinned Codec2 source tree."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BACKEND = ROOT / "crates/lxst-codec2"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("source", type=Path)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
provenance = json.loads((BACKEND / "UPSTREAM.json").read_text())["codec2_700c"]
|
||||
lines = [
|
||||
"// Generated by tools/generate-codec2-700c-codebooks.py; do not edit.",
|
||||
"// Codec2 codebooks, Copyright David Rowe 2017. LGPL-2.1-only.",
|
||||
f"// Source: {provenance['repository']} at {provenance['commit']}.",
|
||||
"// Exact input hashes and original notices: UPSTREAM.json and NOTICE.",
|
||||
"",
|
||||
]
|
||||
for name, relative, width, count in [
|
||||
("VQ1", "src/codebook/train_120_1.txt", 20, 512),
|
||||
("VQ2", "src/codebook/train_120_2.txt", 20, 512),
|
||||
("ENERGY", "src/codebook/newamp1_energy_q.txt", 1, 16),
|
||||
]:
|
||||
raw = (args.source / relative).read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == provenance["source_sha256"][relative], relative
|
||||
dimensions, entries, *values = raw.decode().split()
|
||||
assert (int(dimensions), int(entries), len(values)) == (width, count, width * count)
|
||||
lines.append(f"pub(super) static {name}: [f32; {len(values)}] = [")
|
||||
for i in range(0, len(values), width):
|
||||
lines.append(" " + ", ".join(values[i:i + width]) + ",")
|
||||
lines.extend(["];", ""])
|
||||
output = "\n".join(lines)
|
||||
path = BACKEND / "src/native/codebook700c.rs"
|
||||
if args.check:
|
||||
assert path.read_text() == output, "700C codebooks differ from pinned generation"
|
||||
else:
|
||||
path.write_text(output)
|
||||
print("700C codebooks: pinned source hashes and 20×512 + 20×512 + 16 entries verified")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user