Compare commits

..
6 Commits
306 changed files with 29318 additions and 251 deletions
-3
View File
@@ -1,3 +0,0 @@
[submodule "xombe"]
path = xombe
url = https://github.com/x0rro/xombe
+39 -246
View File
@@ -2,7 +2,7 @@
Versione modificata di **AMBEd** (dal progetto XLX) integrata con il vocoder software **[xombe](https://github.com/x0rro/xombe)** (AMBE+ / AMBE2+) come Git submodule. Versione modificata di **AMBEd** (dal progetto XLX) integrata con il vocoder software **[xombe](https://github.com/x0rro/xombe)** (AMBE+ / AMBE2+) come Git submodule.
Permette la transcodifica cross-mode **D-STAR ↔ DMR / YSF-DN / NXDN** e il supporto **M17 (Codec2)** / **P25 (IMBE)** senza dongle hardware USB DVSI (con supporto opzionale per dongle FTDI). Permette la transcodifica cross-mode **D-STAR <-> DMR / YSF-DN / NXDN** e il supporto **M17 (Codec2)** / **P25 (IMBE)** senza dongle hardware USB DVSI (con supporto opzionale per dongle FTDI).
## Requisiti ## Requisiti
@@ -10,261 +10,54 @@ Permette la transcodifica cross-mode **D-STAR ↔ DMR / YSF-DN / NXDN** e il sup
- `git` - `git`
Su Debian / Ubuntu / Raspbian: Su Debian / Ubuntu / Raspbian:
```bash ```bash
sudo apt update && sudo apt install -y build-essential cmake git sudo apt update && sudo apt install -y build-essential cmake git
```
## Download e compilazione
Clona il repository includendo il submodule `xombe`:
# AMBEd
AMBEd is the transcoder daemon for XLXd. It converts voice between the digital
modes on a reflector, using DVSI hardware for AMBE and software vocoders for
Codec2 and IMBE. It also evens out levels, so stations sound alike whichever
mode they use.
Version 1.5.0
## Codecs
| Codec | Modes | Vocoder |
|---|---|---|
| AMBE+ | D-Star | DVSI hardware |
| AMBE2+ | DMR, YSF, NXDN | DVSI hardware |
| Codec2 3200 bps | M17 | Software |
| IMBE | P25 | Software |
DMR, YSF and NXDN share a codec, so voice between them isn't transcoded and
AMBEd sees all three as DMR.
## Transcoding paths
| From | To | How |
|---|---|---|
| D-Star | DMR/YSF/NXDN | Hardware decode, hardware encode |
| DMR/YSF/NXDN | D-Star | Hardware decode, hardware encode |
| D-Star, DMR/YSF/NXDN | M17, P25 | Hardware decode, software encode |
| M17 | D-Star, DMR/YSF/NXDN | Software decode, hardware encode |
| M17 | P25 | Software decode, software encode |
| P25 | D-Star, DMR/YSF/NXDN | Software decode, hardware encode |
| P25 | M17 | Software decode, software encode |
An M17 or P25 input uses 2 hardware channels, one for each AMBE encoder.
## Hardware
- DF2ET's [AMBE3003USB](https://github.com/phl0/AMBE3003USB)
- LX3JL's [USB-3006](https://github.com/lx3jl/usb-3006)
- DVSI USB-3000, USB-3003 and USB-3012
- NWDR ThumbDV and ThumbDV-3
- DVMEGA AMBE3000 and AMBE3003
| Device | Hardware channels | Transcoding channels | Software vocoders (IMBE and Codec2) |
|---|---|---|---|
| 3000 (pair) | 2 | 2 | 1 each |
| 3003 (single) | 3 | 2 | 1 each |
| 3003 (pair) | 6 | 6 | 3 each |
| 3003 + 3000 (pair) | 4 | 4 | 2 each |
| 3006 | 6 | 6 | 3 each |
| 3012 | 12 | 12 | 6 each |
- USB-3000 devices must be used in pairs, or paired with a USB-3003.
- Several devices can be used at once.
- Avoid USB hubs, they can be unreliable.
- The maximum number of concurrent streams is worked out from the hardware.
## Installation
1. Install the FTDI D2XX drivers from the FTDI website and follow their
instructions. Tested on 1.4.6.
2. Install the build tools:
```bash ```bash
apt-get install build-essential git clone https://git.arifvg.it/iv3jdv/ambed-xombe.git /ambed
cd /ambed
make -j$(nproc)
``` ```
3. Build and install: Il `Makefile` compila automaticamente `libxombe.a` (solo target libreria, evitando i test non compatibili con GCC 8 su ARMv7) e poi l'eseguibile `ambed`.
### Opzioni di compilazione
- **Con supporto hardware FTDI (USB-3000/3003) + xombe:**
```bash
make USE_FTDI=1 -j$(nproc)
```
- **Usando una cartella `xombe` esterna:**
```bash
make XOMBE_DIR=/percorso/a/xombe -j$(nproc)
```
- **Pulizia completa (inclusa la build di `xombe`):**
```bash
make distclean
```
## Configurazione (`ambed.ini`)
Parametri aggiunti per il pool di vocoder software `xombe`:
| Parametro | Descrizione | Valori consigliati |
| :--- | :--- | :--- |
| `XOMBE_THREADS` | Numero di thread worker (uno per core CPU) | `4` |
| `XOMBE_PAIRS_PER_THREAD` | Coppie di canali (D-STAR + DMR) per thread | `6` su x86_64, `2`–`3` su ARM (es. Raspberry Pi) |
Avvio manuale:
```bash ```bash
git clone https://github.com/LX3JL/xlxd.git ./ambed ./ambed.ini
cd xlxd/ambed
make clean
make
make install
``` ```
This installs to `/ambed`. `ambed.ini` is only copied if there isn't one ## Note tecniche
already, so your tuning is kept.
Always run `make clean` first after updating. The makefile doesn't track - **Architetture testate:** `x86_64` e `armv7l` (Raspbian 32-bit).
header changes, so a plain `make` can link old and new code together. - **Endianness PCM:** `CXombeInterface` gestisce la conversione tra il PCM nativo (`int16_t` little-endian) di `xombe` e il PCM big-endian interno di `CVoicePacket` / `CSignalProcessor` per i percorsi M17 e P25.
## Running
```
ambed [ambed.ini]
```
Everything is set in `ambed.ini`. Set `LISTEN_IP` first: `127.0.0.1` if xlxd is on
the same machine, otherwise the machine's own address. Without the file AMBEd
uses the defaults in `main.h` and listens on `127.0.0.1`.
AMBEd must run as root because of the FTDI driver, and the kernel's own FTDI
driver, the `ftdi_sio` module, must be unloaded so it doesn't claim the
dongles. Plug in at least one device first.
To run it as a service, copy `../scripts/ambed.service` to
`/etc/systemd/system/`:
```ini
[Unit]
Description=AMBE Transcoder Daemon
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=root
Group=root
# free the dongles from the kernel's FTDI serial driver, so the FTDI D2XX
# driver can claim them
ExecStartPre=-/sbin/rmmod ftdi_sio
ExecStart=/ambed/ambed /ambed/ambed.ini
Restart=on-abnormal
RestartSec=5
[Install]
WantedBy=multi-user.target
```
Then enable and start it:
```bash
systemctl daemon-reload
systemctl enable --now ambed
```
Or start it by hand with `/ambed/run`.
At startup AMBEd finds and configures every device, then reports:
```
Starting AMBEd 1.5.0
Codec interfaces initialized successfully : 6 channels available
Software vocoders : 3 IMBE (P25), 3 Codec2 (M17)
Max concurrent streams: 3 (from 6 vocoder channels)
AMBEd started and listening on 127.0.0.1:10100
Voice packets marked as DSCP 46
```
## Audio processing
Every path runs through the same chain:
```
decode -> <MODE>_TO_PCM -> bandpass filter -> AGC -> PCM_TO_<MODE> -> encode
```
- **`<MODE>_TO_PCM`** corrects what each mode's decoder does to the level, so
every mode reaches the AGC at about the same level.
- **Bandpass filter** keeps 300-3400 Hz.
- **AGC** corrects what each station does to the level: mic gain, radio and
voice.
- **`PCM_TO_<MODE>`** sets the level for each encoder.
### AGC
The AGC works like the one on an HF receiver: fast down, hold through gaps, then
up, faster the further a station is below the target.
- It follows the speech peaks, the loud parts of words, so it levels the speaker
and leaves the shape of the speech alone for the vocoders.
- Pauses and noise below `AGC_GATE` leave the gain where it is.
- Each stream starts at 0 dB, so very short transmissions aren't fully levelled.
- A peak limiter leaves room for the highest `PCM_TO_<MODE>`, so a boost can't
clip an encoder.
## Tuning
`ambed.ini` overrides the defaults in `main.h` without a rebuild. AMBEd checks it
every 3 minutes. Most changes apply from the next stream, so a transmission
already running keeps its levels, and DSCP changes apply at once.
`LISTEN_IP` and `LISTEN_PORT` need a restart. A setting left out uses its default.
A bad value is logged and ignored, and the value in use stays.
| Setting | Default | Meaning |
|---|---|---|
| `LISTEN_IP` | 127.0.0.1 | IP to bind to |
| `LISTEN_PORT` | 10100 | UDP port, xlxd's `TRANSCODER_PORT` must match |
| `DSCP_MARKING_ENABLE` | 1 | Mark voice packets for QoS |
| `DSCP_VALUE` | 46 | DSCP value, 0-63, 46 is EF |
| `STREAM_ACTIVITY_TIMEOUT` | 3 s | Close a stream after this long with no packets |
| `TUNING_LOG` | 1 | Log levels when a stream closes |
| `DSTAR_TO_PCM` | -10 dB | D-Star decode gain |
| `DMR_TO_PCM` | -1.5 dB | DMR, YSF and NXDN decode gain |
| `M17_TO_PCM` | -10.75 dB | M17 decode gain |
| `P25_TO_PCM` | -3.75 dB | P25 decode gain |
| `PCM_TO_DSTAR` | +11.5 dB | D-Star encode gain |
| `PCM_TO_DMR` | 0 dB | DMR, YSF and NXDN encode gain |
| `PCM_TO_M17` | +5.25 dB | M17 encode gain |
| `PCM_TO_P25` | +0.75 dB | P25 encode gain |
| `USE_AGC` | 1 | AGC on or off |
| `AGC_TARGET` | -41 dBFS | Speech peak level to aim for |
| `AGC_CLAMPING` | 9 dB | Most the gain can move either way, 0 leaves the audio alone |
| `AGC_ATTACK` | 150 ms | How fast the gain comes down |
| `AGC_HANG` | 1000 ms | How long the gain holds before it can rise |
| `AGC_RECOVERY` | 2 | How fast the gain rises, dB/s for each dB below the target |
| `AGC_RECOVERY_MIN` | 3 dB/s | Slowest rise |
| `AGC_RECOVERY_MAX` | 20 dB/s | Fastest rise |
| `AGC_GATE` | -60 dBFS | Frames quieter than this don't move the gain |
| `USE_BANDPASSFILTER` | 1 | Bandpass filter on or off |
### Tuning log
When a stream closes, AMBEd logs the voice level at each stage. Pauses aren't
counted, and a level is the mean absolute sample value. Set `TUNING_LOG=0` to
turn this off.
```
Tuning: stream 1 XLX672 M17 input, 440 voice frames of 540
Tuning: decoded level -30.5 dBFS peak -8.9 dBFS clipped 0.00%
Tuning: M17_TO_PCM -10.75 level -45.6 dBFS peak -19.9 dBFS clipped 0.00%
Tuning: AGC target -41.0 dBFS speech peaks -43.6 dBFS gain average -3.7 dB, -4.5 to +0.4 dB at limit 0.0% high 0.0% low limiter 0.00%
Tuning: after AGC level -49.3 dBFS peak -23.7 dBFS clipped 0.00%
Tuning: PCM_TO_DSTAR +11.50 level -37.8 dBFS peak -12.2 dBFS clipped 0.00%
Tuning: PCM_TO_DMR +0.00 level -49.3 dBFS peak -23.7 dBFS clipped 0.00%
Tuning: PCM_TO_P25 +0.75 level -48.5 dBFS peak -22.9 dBFS clipped 0.00%
```
The callsign shown is the reflector's, as AMBEd isn't told who is talking.
### How to tune
For a step-by-step guide covering AMBEd and XLXd's gains together, see the
[Audio Tuning Guide](../AUDIO-TUNING.md). In short:
1. Look at several stations on each mode, not just your own radio.
2. Set each `<MODE>_TO_PCM` so typical stations on that mode average near 0 dB
of AGC gain.
3. If most modes sit high or low, move `AGC_TARGET`.
4. A station at one limit for most of a stream is too far off for the AGC to
correct.
5. Use `PCM_TO_<MODE>` to match how each mode sounds on air, and back one off if
it shows clipping.
To see levels without changing the audio, set `AGC_CLAMPING=0`. Speech peaks are
still logged.
## Build-time options
These are in `main.h`:
| Setting | Default | Meaning |
|---|---|---|
| `CONFIG_RELOAD_PERIOD` | 180 s | How often `ambed.ini` is checked |
## License
Created by Jean-Luc Deltombe (LX3JL). AMBEd is part of xlxd, free software under
the GNU General Public License v3 or later.
+16
View File
@@ -0,0 +1,16 @@
[Unit]
Description=AMBEd Transcoder Daemon (xombe)
After=network.target
Before=xlxd.service
[Service]
Type=simple
WorkingDirectory=/ambed
ExecStart=/ambed/ambed /ambed/ambed.ini
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+4 -2
View File
@@ -1,4 +1,4 @@
CC?=g++ CC=g++
XOMBE_DIR?=./xombe XOMBE_DIR?=./xombe
USE_FTDI?=0 USE_FTDI?=0
@@ -59,5 +59,7 @@ distclean: clean
install: install:
mkdir -p /ambed mkdir -p /ambed
cp $(EXECUTABLE) /ambed/ cp $(EXECUTABLE) /ambed/
cp ./run /ambed/
test -f /ambed/ambed.ini || cp ./ambed.ini /ambed/ test -f /ambed/ambed.ini || cp ./ambed.ini /ambed/
cp ./ambed.service /etc/systemd/system/
systemctl daemon-reload
@echo "Installazione completata. Avvia con: sudo systemctl enable --now ambed.service"
Submodule xombe deleted from 2f0a8e7446
+45
View File
@@ -0,0 +1,45 @@
name: CI
on:
push:
pull_request:
permissions:
contents: read
jobs:
linux:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
cc: [gcc, clang]
env:
CC: ${{ matrix.cc }}
steps:
- uses: actions/checkout@v4
- run: make check WERROR=ON
macos:
strategy:
fail-fast: false
matrix:
runner: [macos-15, macos-15-intel]
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- run: make check
mingw:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
shared: ['OFF', 'ON']
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y --no-install-recommends gcc-mingw-w64-x86-64
- run: >-
cmake -S . -B build -DCMAKE_SYSTEM_NAME=Windows -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc
-DBUILD_SHARED_LIBS=${{ matrix.shared }} -DXOMBE_WERROR=ON
- run: cmake --build build -j4
+67
View File
@@ -0,0 +1,67 @@
name: Release
on:
push:
tags: ['v*']
permissions:
contents: read
jobs:
source:
runs-on: ubuntu-24.04
container: docker.io/library/debian@sha256:2dc419c6d7fe3dad0a2f9fd469c34cc90b0f9ba642d8fde837fe3d7d34a0e7f1
steps:
- name: checkout without git, for the locked packages
uses: actions/checkout@v4
- run: sh scripts/release_deps.sh
- run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: checkout with git
uses: actions/checkout@v4
- name: tag matches version
run: |
ver=$(for p in MAJOR MINOR PATCH; do
sed -n "s/^#define XOMBE_VERSION_$p \([0-9][0-9]*\)\$/\1/p" include/xombe.h
done | paste -sd. -)
test "${GITHUB_REF_NAME#v}" = "$ver"
- run: scripts/release_tarball.sh HEAD dist
- uses: actions/upload-artifact@v4
with:
name: source
path: |
dist/*.tar.xz
dist/*.buildinfo
if-no-files-found: error
release:
needs: source
runs-on: ubuntu-24.04
permissions:
contents: write
id-token: write
attestations: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: source
path: out
- run: cd out && sha256sum -- xombe-* | LC_ALL=C sort -k2 > SHA256SUMS
- name: sums match the tag
run: |
git fetch -q --depth=1 origin "+$GITHUB_REF:$GITHUB_REF"
git for-each-ref --format='%(contents)' "$GITHUB_REF" | grep -E '^[0-9a-f]{64} xombe-' > tag-sums
diff tag-sums out/SHA256SUMS
- uses: actions/attest-build-provenance@v2
with:
subject-path: |
out/*.tar.xz
out/*.buildinfo
- name: draft release
env:
GH_TOKEN: ${{ github.token }}
run: |
ver=${GITHUB_REF_NAME#v}
awk -v h="## $ver" '$0 == h { on = 1; next } on && /^## / { exit } on' CHANGELOG.md > notes.md
gh release create "$GITHUB_REF_NAME" --draft --verify-tag \
--title "xombe $ver" --notes-file notes.md out/xombe-* out/SHA256SUMS
+6
View File
@@ -0,0 +1,6 @@
/build/
/build-*/
/out/
__pycache__/
*.pyc
/dist/
+13
View File
@@ -0,0 +1,13 @@
# changelog
## 0.1.0
first release
- decoder for AMBE 2400 (D-STAR) and AMBE+2 half-rate (DMR)
- encoder for D-STAR and DMR
- single encoder produces both outputs
- one API for both codecs, picked by `enum xombe_codec`
- transcoding between codecs in parameter space (without converting to PCM)
- q15 kernel for Cortex-M33 with DSP extension (RP2350)
- conformance and test suites
+282
View File
@@ -0,0 +1,282 @@
cmake_minimum_required(VERSION 3.13)
# The version lives in xombe.h; CMake reads it from there.
file(STRINGS include/xombe.h XOMBE_VERSION_LINES REGEX "^#define XOMBE_VERSION_(MAJOR|MINOR|PATCH) ")
foreach(part MAJOR MINOR PATCH)
string(REGEX REPLACE ".*#define XOMBE_VERSION_${part} ([0-9]+).*" "\\1" XOMBE_VERSION_${part}
"${XOMBE_VERSION_LINES}")
endforeach()
project(xombe VERSION ${XOMBE_VERSION_MAJOR}.${XOMBE_VERSION_MINOR}.${XOMBE_VERSION_PATCH} LANGUAGES C)
include(GNUInstallDirs)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
option(XOMBE_ENCODER "Build the encoder" ON)
option(XOMBE_DSTAR "Build the D-STAR (AMBE 2400) codec: decoder, FEC, encoder output and the transcoders" ON)
option(XOMBE_SANITIZE "Build with address and undefined-behaviour sanitizers" OFF)
option(XOMBE_WERROR "Treat warnings as errors" OFF)
# Built into a parent project (add_subdirectory, FetchContent), xombe is the library alone by default.
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
set(XOMBE_TOP_LEVEL ON)
else()
set(XOMBE_TOP_LEVEL OFF)
endif()
# the tools and tests are POSIX-only test tools (fork, sh), only the library is portable
if(XOMBE_TOP_LEVEL AND NOT WIN32)
set(XOMBE_POSIX_DEFAULT ON)
else()
set(XOMBE_POSIX_DEFAULT OFF)
endif()
option(XOMBE_BUILD_TOOLS "Build the xombe-enc, xombe-dec and xombe-xc tools (POSIX only)" ${XOMBE_POSIX_DEFAULT})
option(XOMBE_BUILD_TESTS "Build the tests (POSIX only)" ${XOMBE_POSIX_DEFAULT})
if(WIN32 AND (XOMBE_BUILD_TOOLS OR XOMBE_BUILD_TESTS))
message(WARNING "xombe: the tools and tests are POSIX-only, unsupported on Windows")
endif()
option(XOMBE_INSTALL "Generate the install rules" ${XOMBE_TOP_LEVEL})
set(XOMBE_KERNELS float CACHE STRING "Codec kernel backend: float, or q15 (fixed point with the Arm DSP extension)")
set_property(CACHE XOMBE_KERNELS PROPERTY STRINGS float q15)
if(NOT XOMBE_KERNELS MATCHES "^(float|q15)$")
message(FATAL_ERROR "XOMBE_KERNELS must be float or q15, not ${XOMBE_KERNELS}")
endif()
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# Warning and sanitizer flags apply to xombe's own targets only, so a project that adds xombe with
# add_subdirectory() keeps its own flags.
function(xombe_target_options target)
if(CMAKE_C_COMPILER_ID MATCHES "^(GNU|Clang|AppleClang)$")
# no a*b+c -> FMA contraction (clang's default), so output is bit-identical with and without FMA hardware
target_compile_options(${target} PRIVATE -Wall -Wextra -ffp-contract=off)
if(XOMBE_WERROR)
target_compile_options(${target} PRIVATE -Werror)
endif()
elseif(MSVC)
target_compile_options(${target} PRIVATE /W4)
if(XOMBE_WERROR)
target_compile_options(${target} PRIVATE /WX)
endif()
endif()
if(XOMBE_SANITIZE)
target_compile_options(${target} PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer
-fno-sanitize-recover=all)
target_link_options(${target} PRIVATE -fsanitize=address,undefined)
endif()
endfunction()
set(XOMBE_HAVE_ENCODER ${XOMBE_ENCODER})
set(XOMBE_HAVE_DSTAR ${XOMBE_DSTAR})
if(XOMBE_KERNELS STREQUAL q15)
set(XOMBE_KERNELS_Q15 1)
else()
set(XOMBE_KERNELS_Q15 0)
endif()
configure_file(src/xombe_config.h.in ${CMAKE_CURRENT_BINARY_DIR}/include/xombe_config.h)
set(XOMBE_COMMON
src/common/bits.c src/common/params.c src/common/tone_table.c src/common/version.c src/common/voicing.c
src/dsp/fft.c src/dsp/window.c src/dsp/biquad.c src/dsp/lcg.c
src/tables/tables.c src/tables/dsp_tables.c src/tables/cq_q15_tables.c)
set(XOMBE_DEC
src/dec/decoder.c src/dec/smooth.c src/dec/enhance.c src/dec/synth_voiced.c
src/dec/synth_unvoiced.c src/dec/synth_tone.c src/dec/conceal.c src/dec/dkern_${XOMBE_KERNELS}.c)
set(XOMBE_KERN_float src/enc/kern_float.c)
set(XOMBE_KERN_q15 src/enc/kern_q15_spec.c src/enc/kern_q15_lf.c src/enc/kern_q15_pitch.c)
set(XOMBE_ENC
src/enc/encoder.c src/enc/analysis.c src/enc/pitch.c src/enc/voicing_metric.c ${XOMBE_KERN_${XOMBE_KERNELS}}
src/enc/vad.c src/enc/ns.c src/enc/comfort.c src/enc/tone_detect.c src/enc/quant.c src/enc/frontend.c
src/enc/ambe2_enc.c)
set(XOMBE_FECSRC src/fec/golay.c src/fec/pn.c src/fec/interleave.c src/fec/stats.c)
set(XOMBE_DSTARSRC src/dstar/fec.c src/dstar/params.c src/dstar/decoder.c src/common/cquant.c
src/tables/dstar_tables.c)
set(XOMBE_SOURCES ${XOMBE_COMMON} ${XOMBE_DEC} ${XOMBE_FECSRC})
if(XOMBE_ENCODER)
list(APPEND XOMBE_SOURCES ${XOMBE_ENC})
if(NOT XOMBE_DSTAR)
list(APPEND XOMBE_SOURCES src/common/cquant.c) # AMBE+2 closed-loop quantizer, in XOMBE_DSTARSRC otherwise
endif()
endif()
if(XOMBE_DSTAR)
list(APPEND XOMBE_SOURCES ${XOMBE_DSTARSRC})
if(XOMBE_ENCODER)
list(APPEND XOMBE_SOURCES src/dstar/dstar_enc.c src/dstar/dstar_tone.c src/tables/dstar_enc_tables.c)
endif()
list(APPEND XOMBE_SOURCES src/dstar/xc.c src/dstar/xcode.c)
if(XOMBE_ENCODER)
list(APPEND XOMBE_SOURCES src/dstar/xrev.c)
endif()
endif()
# static or shared by BUILD_SHARED_LIBS (static when unset)
add_library(xombe ${XOMBE_SOURCES})
add_library(xombe::xombe ALIAS xombe)
function(xombe_library_options target)
target_include_directories(${target}
PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
PRIVATE src)
# MSVC's C runtime has the math functions, and there is no libm
if(NOT MSVC)
target_link_libraries(${target} PUBLIC m)
endif()
xombe_target_options(${target})
endfunction()
xombe_library_options(xombe)
# symbols are hidden but the XOMBE_API functions (xombe_config.h). the ABI can change with each minor version
# while the major is 0, so the soname carries the minor version too
if(PROJECT_VERSION_MAJOR EQUAL 0)
set(XOMBE_SOVERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR})
else()
set(XOMBE_SOVERSION ${PROJECT_VERSION_MAJOR})
endif()
set_target_properties(xombe PROPERTIES C_VISIBILITY_PRESET hidden VERSION ${PROJECT_VERSION}
SOVERSION ${XOMBE_SOVERSION})
get_target_property(XOMBE_TYPE xombe TYPE)
if(XOMBE_TYPE STREQUAL SHARED_LIBRARY)
# XOMBE_API's dllimport on Windows (xombe_config.h)
target_compile_definitions(xombe INTERFACE XOMBE_SHARED)
set(XOMBE_PC_CFLAGS " -DXOMBE_SHARED")
endif()
# libm: a shared libxombe brings its own, a static one needs it on every link line, not only with --static
if(NOT MSVC)
if(XOMBE_TYPE STREQUAL SHARED_LIBRARY)
set(XOMBE_PC_LIBS_PRIVATE -lm)
else()
set(XOMBE_PC_LIBS " -lm")
endif()
endif()
function(xombe_executable name)
add_executable(${name} ${ARGN})
target_link_libraries(${name} xombe)
xombe_target_options(${name})
endfunction()
if(XOMBE_BUILD_TOOLS)
xombe_executable(xombe-dec tools/xombe-dec.c tools/io.c)
if(XOMBE_ENCODER)
xombe_executable(xombe-enc tools/xombe-enc.c tools/io.c)
endif()
if(XOMBE_DSTAR)
xombe_executable(xombe-xc tools/xombe-xc.c tools/io.c)
endif()
endif()
if(XOMBE_INSTALL)
install(TARGETS xombe EXPORT xombeTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES include/xombe.h ${CMAKE_CURRENT_BINARY_DIR}/include/xombe_config.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(EXPORT xombeTargets NAMESPACE xombe:: FILE xombeConfig.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/xombe)
include(CMakePackageConfigHelpers)
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/xombeConfigVersion.cmake
COMPATIBILITY SameMinorVersion)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/xombeConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/xombe)
# xombe.pc finds the prefix from its own directory, so it holds under cmake --install --prefix. an absolute
# CMAKE_INSTALL_LIBDIR or INCLUDEDIR stays absolute
if(IS_ABSOLUTE ${CMAKE_INSTALL_LIBDIR})
set(XOMBE_PC_PREFIX ${CMAKE_INSTALL_PREFIX})
else()
file(RELATIVE_PATH XOMBE_PC_PREFIX ${CMAKE_INSTALL_FULL_LIBDIR}/pkgconfig ${CMAKE_INSTALL_PREFIX})
string(REGEX REPLACE "/$" "" XOMBE_PC_PREFIX "\${pcfiledir}/${XOMBE_PC_PREFIX}")
endif()
foreach(d LIBDIR INCLUDEDIR)
if(IS_ABSOLUTE ${CMAKE_INSTALL_${d}})
set(XOMBE_PC_${d} ${CMAKE_INSTALL_${d}})
else()
set(XOMBE_PC_${d} "\${prefix}/${CMAKE_INSTALL_${d}}")
endif()
endforeach()
configure_file(xombe.pc.in ${CMAKE_CURRENT_BINARY_DIR}/xombe.pc @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/xombe.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
if(XOMBE_BUILD_TOOLS)
install(TARGETS xombe-dec RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
if(XOMBE_ENCODER)
install(TARGETS xombe-enc RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
if(XOMBE_DSTAR)
install(TARGETS xombe-xc RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
endif()
endif()
if(NOT XOMBE_BUILD_TESTS)
return()
endif()
enable_testing()
set(VEC ${CMAKE_CURRENT_SOURCE_DIR}/vectors)
# tests of the internals (xombe__*, src/) link a static build, the shared one exports only the API
if(XOMBE_TYPE STREQUAL SHARED_LIBRARY)
add_library(xombe_static_for_tests STATIC ${XOMBE_SOURCES})
xombe_library_options(xombe_static_for_tests)
else()
add_library(xombe_static_for_tests ALIAS xombe)
endif()
function(xombe_internal_executable name)
add_executable(${name} ${ARGN})
target_link_libraries(${name} xombe_static_for_tests)
target_include_directories(${name} PRIVATE src)
xombe_target_options(${name})
endfunction()
xombe_executable(test_api test/test_api.c)
add_test(NAME api COMMAND test_api)
xombe_executable(sizes test/sizes.c)
add_test(NAME sizes COMMAND sizes)
xombe_internal_executable(test_fec test/test_fec.c)
add_test(NAME t1_fec COMMAND test_fec ${VEC}/fec)
xombe_executable(test_stream test/test_stream.c tools/io.c)
add_test(NAME t4a_decisions COMMAND test_stream
${VEC}/stream/mixed_stream_0.jsonl.gz ${VEC}/stream/mixed_stream_1.jsonl.gz
${VEC}/stream/mixed_stream_2.jsonl.gz ${VEC}/stream/mixed_stream_3.jsonl.gz)
xombe_internal_executable(test_tones test/test_tones.c)
add_test(NAME t5_tones COMMAND test_tones ${VEC}/tones)
xombe_internal_executable(test_tables test/test_tables.c)
add_test(NAME tables COMMAND test_tables)
xombe_internal_executable(test_q15ops test/test_q15ops.c)
add_test(NAME q15ops COMMAND test_q15ops)
# The same test of the intrinsics, when an Arm cross compiler and qemu-arm are at hand.
find_program(XOMBE_ARM_CC arm-none-eabi-gcc)
find_program(XOMBE_QEMU_ARM qemu-arm)
if(XOMBE_ARM_CC AND XOMBE_QEMU_ARM)
add_test(NAME q15ops_arm COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/test/q15ops_arm.sh ${XOMBE_ARM_CC}
${XOMBE_QEMU_ARM} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
endif()
# Stage dumps for test/trace_cmp.py; not a test itself.
xombe_internal_executable(trace_dump test/trace_dump.c tools/io.c)
if(XOMBE_ENCODER)
xombe_internal_executable(test_mirror test/test_mirror.c)
add_test(NAME e1_e2_encoder COMMAND test_mirror ${VEC})
xombe_internal_executable(test_enc_tone test/test_enc_tone.c)
add_test(NAME enc_tone COMMAND test_enc_tone ${VEC})
xombe_internal_executable(tone_cmp test/tone_cmp.c)
add_test(NAME tone_cmp COMMAND tone_cmp ${VEC})
endif()
# kernel backends against float (test/test_kern_*.c), one file per q15 track
set(XOMBE_KERN_TESTS dec)
if(XOMBE_ENCODER)
list(APPEND XOMBE_KERN_TESTS spec tone)
endif()
if(XOMBE_DSTAR)
list(APPEND XOMBE_KERN_TESTS cq)
endif()
foreach(t ${XOMBE_KERN_TESTS})
xombe_internal_executable(test_kern_${t} test/test_kern_${t}.c)
add_test(NAME kern_${t} COMMAND test_kern_${t} ${VEC})
endforeach()
if(XOMBE_BUILD_TOOLS)
add_test(NAME tools COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/test/tools.sh ${CMAKE_CURRENT_BINARY_DIR} ${VEC})
endif()
include(test/dstar.cmake)
get_property(skipped GLOBAL PROPERTY XOMBE_SKIPPED_TESTS)
if(skipped)
list(LENGTH skipped n)
string(REPLACE ";" " " skipped "${skipped}")
message(WARNING "xombe: no Python 3, ${n} D-STAR comparison tests skipped: ${skipped}")
endif()
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 x0rro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+39
View File
@@ -0,0 +1,39 @@
BUILD ?= build
SAN_BUILD ?= build-asan
Q15_BUILD ?= build-q15
CMAKE ?= cmake
PYTHON ?= python3
CMAKE_FLAGS ?=
# WERROR=ON turns warnings into errors in every build
WERROR ?= OFF
JOBS ?= $(shell nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
.PHONY: all check check-q15 conformance conformance-dstar clean
all:
$(CMAKE) -S . -B $(BUILD) -DCMAKE_BUILD_TYPE=Release -DXOMBE_WERROR=$(WERROR) $(CMAKE_FLAGS)
$(CMAKE) --build $(BUILD) -j$(JOBS)
# release, q15 (check-q15), and ASan/UBSan builds
check: all check-q15
cd $(BUILD) && ctest --output-on-failure -j$(JOBS)
$(CMAKE) -S . -B $(SAN_BUILD) -DCMAKE_BUILD_TYPE=Debug -DXOMBE_SANITIZE=ON -DXOMBE_WERROR=$(WERROR) $(CMAKE_FLAGS)
$(CMAKE) --build $(SAN_BUILD) -j$(JOBS)
cd $(SAN_BUILD) && ctest --output-on-failure -j$(JOBS)
@n=$$(cd $(BUILD) && ctest -N -L no_python | sed -n 's/^Total Tests: //p'); \
if [ "$${n:-0}" -gt 0 ]; then echo "make check: $$n tests skipped per build (no Python 3)"; fi
# the q15 kernels, with q15ops_arm when arm-none-eabi-gcc and qemu-arm are installed
check-q15:
$(CMAKE) -S . -B $(Q15_BUILD) -DCMAKE_BUILD_TYPE=Release -DXOMBE_WERROR=$(WERROR) -DXOMBE_KERNELS=q15 $(CMAKE_FLAGS)
$(CMAKE) --build $(Q15_BUILD) -j$(JOBS)
cd $(Q15_BUILD) && ctest --output-on-failure -j$(JOBS)
conformance: all
sh test/conformance.sh $(BUILD) $(PYTHON)
conformance-dstar: all
sh test/conformance_dstar.sh $(BUILD) $(PYTHON)
clean:
rm -rf $(BUILD) $(SAN_BUILD) $(Q15_BUILD)
+181
View File
@@ -0,0 +1,181 @@
# xombe
C99 library implementing AMBE 2400 and AMBE+2 used by D-STAR and DMR. decoders,
a single input dual output encoder, parameter-space transcoders, and FEC.
## minimum usage
play a DMR call saved by dsd (`.amb`):
xombe-dec call.amb - | aplay -q -f S16_LE -r 8000
encode a wav for DMR:
sox talk.wav -t raw -r 8000 -c 1 -b 16 -e signed -L - | xombe-enc - talk.amb
to decode DMR air frames in C:
#include <xombe.h>
static xombe_dec_mem mem;
xombe_dec *dec = xombe_dec_init(&mem, XOMBE_DMR); /* or XOMBE_DSTAR */
xombe_dec_frame(dec, frame, 0, pcm); /* 9 bytes in, 160 samples out */
when a frame is lost set flags to `XOMBE_FLAG_LOST` (frame can be NULL). frames
with FEC applied (49 bits, `.amb`) are decoded by `xombe_dec_frame_bits`.
to encode:
static xombe_enc_mem mem;
xombe_enc *enc = xombe_enc_init(&mem, NULL); /* NULL: default settings */
if (xombe_enc_frame(enc, pcm, NULL, dmr, NULL) == 1) /* 160 samples in */
send(dmr); /* lags input by 3 frames */
for (i = 0; i < xombe_enc_delay(enc); i++) { /* at end of input */
xombe_enc_frame(enc, NULL, NULL, dmr, NULL);
send(dmr);
}
for D-STAR output, set `cfg.outputs` and pass a buffer as the last argument.
every call is documented in `include/xombe.h`.
## features
- AMBE+2 and AMBE 2400 decoders with frame-loss concealment
- encoders with noise suppression, DTX, and tone detection
- send DTMF, Knox and call-progress tones from the encoder
- DMR and D-STAR channel FEC, both directions
- transcode DMR to D-STAR and back in parameter space (no PCM)
- no malloc or globals: all state is caller-managed
- fixed-point build for Cortex-M with the DSP extension
- hardened against malformed and malicious inputs
benchmarks on a raspberry pi pico 2 (RP2350):
- 150 MHz (stock), q15 encoder uses 41% of one core, decoder 6%
- 200 MHz (no overvolt), three full-duplex channels fit across two cores
## building
needs cmake 3.13 and a C99 compiler.
git clone https://github.com/x0rro/xombe && cd xombe
make
make check # optional
sudo cmake --install build
pass build options to `make` as `CMAKE_FLAGS="-DXOMBE_KERNELS=q15 ..."`, or run
cmake yourself.
once installed, there are two main ways of using the library.
- cmake: `find_package(xombe)` and link `xombe::xombe`
- `pkg-config xombe` for the compile and link flags.
the library builds on all platforms. the tools and tests require POSIX.
### build options
-DXOMBE_KERNELS=float|q15 q15 is fixed point for M33 DSP (default float)
-DBUILD_SHARED_LIBS=ON shared library (default static)
-DXOMBE_ENCODER=OFF decoder only
-DXOMBE_DSTAR=OFF DMR only
float and q15 builds encode slightly differently, and their decoded audio
differs by a few LSB. both pass the same tests.
### testing
make check # release, q15 and sanitizer builds
make conformance PYTHON=python3 # scores encoded and decoded speech
make conformance-dstar PYTHON=python3
`make check` runs a few more tests if python 3 is installed. the conformance
targets need numpy, scipy, pesq, pystoi and visqol.
## file formats
.raw 8 kHz signed 16-bit little-endian mono
.amb dsd's format: ".amb", then 8 bytes per frame
.bits 49 bytes per frame, one bit per byte
.air 72-bit DMR air frames (xombe does FEC and interleaving)
.r33 same as .air
.dstar 72-bit D-STAR voice frames (xombe does FEC and interleaving)
## xombe-dec
xombe-dec [options] IN OUT.raw
--bits IN is .bits
--air IN is .air, decoded through the FEC
--dstar IN is .dstar
(default: .amb)
--lost LIST treat these frames as lost, from 0, e.g. 3,10-12
--decisions print each frame's class and concealment on stderr
--help list all options
## xombe-enc
xombe-enc [options] IN.raw OUT
--bits write .bits
--air write .air
--dstar write .dstar only
--dual DSTAR_OUT write .dstar to DSTAR_OUT as well as AMBE+2 to OUT
(default: .amb)
--ns on|off noise suppression (default on)
--ns-strength S how hard to suppress (0-1, default 0.5)
--dtx on|off send silence frames for background noise (default on)
--dstar-dtx on|off same for D-STAR (default off)
--tones on|off detect tones and send as tone frames (default on)
--vscale S voicing decision scale, 0.6 voices less (default 0.35)
--quant closed|open open is faster but sounds worse (default closed)
--help list all options
## xombe-xc
xombe-xc [options] IN.r33 OUT.dstar # DMR to D-STAR
xombe-xc --reverse [options] IN.dstar OUT.r33 # D-STAR to DMR
--amb DMR side is .amb instead of .r33 (for D-STAR in dsd)
--lost LIST treat these frames as lost, from 0, e.g. 3,10-12
--decisions print each frame's class and concealment on stderr
## verifying a release
each release is a tag signed by x0rro (`x0rroRF@proton.me`), key fingerprint
`638C 5D53 640A CEFB 79B6 87AA 3E93 43F0 B819 4BFF`. the tag message has the
hashes of the release tarball and its buildinfo:
git tag -v v0.1.0
### reproducing a release
release tarballs are reproducible. rebuild one on x86_64 in the debian container
named in `scripts/release_lock.sh`:
git clone -b v0.1.0 https://github.com/x0rro/xombe && cd xombe && mkdir out
podman run --rm -v "$PWD:/src" -v "$PWD/out:/out" \
docker.io/library/debian@sha256:2dc419c6d7fe3dad0a2f9fd469c34cc90b0f9ba642d8fde837fe3d7d34a0e7f1 \
sh -c 'cd /src && scripts/release_deps.sh && git config --global safe.directory /src &&
scripts/release_tarball.sh HEAD /out && cd /out && sha256sum *'
the hashes it prints match the tag's.
## patent note
patents covering methods used in this code may still be in force in some
jurisdictions. if that applies to you, get a license from the patent holder
before using it.
## copyright
copyright (c) 2026 x0rro
released under MIT license, see LICENSE
+362
View File
@@ -0,0 +1,362 @@
#ifndef XOMBE_H
#define XOMBE_H
#include <stddef.h>
#include <stdint.h>
#include "xombe_config.h"
/* DMR (AMBE+2 half rate) and D-STAR (AMBE 2400) decoders, encoder, channel FEC, and transcoders between the two.
every call that handles frames takes the codec as an enum xombe_codec, at init or as an argument, and treats
both codecs the same way
build options, recorded in xombe_config.h as 0/1 and guarding the declarations below:
XOMBE_HAVE_ENCODER the encoder (CMake XOMBE_ENCODER, default on)
XOMBE_HAVE_DSTAR the D-STAR codec and the transcoders (XOMBE_DSTAR, default on). without it an init for
XOMBE_DSTAR returns NULL
XOMBE_KERNELS_Q15 fixed-point kernels (XOMBE_KERNELS=q15), larger encoder state
the decoder and the FEC are always built
frames: a frame is the 72-bit channel frame as sent, XOMBE_FRAME_BYTES bytes MSB first, FEC included: DMR's
rate-33 frame or D-STAR's voice frame. the voice bits without FEC are XOMBE_BITS_BYTES bytes MSB first, DMR
d0..d48, D-STAR d0..d47 and a zero bit. the *_bits calls and xombe_fec_* take them, everything else frames
conventions, for every object here:
- state is opaque and caller-allocated, the library never allocates and has no mutable globals. pass init
the *_SIZE bytes, aligned for any scalar type: the matching *_mem union (static, automatic, or a struct
member) or malloc(*_size()). init returns the handle (the same address), or NULL if mem is NULL or the
settings are invalid. there is no deinit: drop or reuse the memory, init again to reset
- *_size() is the exact size, at most *_SIZE. sizes can change between versions, compare xombe_version()
with XOMBE_VERSION when the library may come from elsewhere
- no thread safety inside an instance: one thread at a time per instance. distinct instances are independent
- handles and required buffers must be valid, they are not checked. buffers are caller-owned and only
accessed during the call
- PCM frames are 20 ms: 160 samples of 8 kHz signed 16-bit PCM
- *_frame calls return 1 when the output holds the frame for an input, 0 when it holds something else (the
encoder's silence frame while its delay fills, a decoder's pending half-frame), -1 for a call the object
cannot take (nothing written or consumed)
- decoders and transcoders take the XOMBE_FLAG_* flags and report each frame through *_decision_get
- unknown flag bits are reserved, pass 0
- the calls that take a codec at init are inline here and pick a per-codec function (xombe__*, not part of the
API), so a program that names one codec as a constant links none of the other's code */
#ifdef __cplusplus
extern "C" {
#endif
#define XOMBE_VERSION_MAJOR 0
#define XOMBE_VERSION_MINOR 1
#define XOMBE_VERSION_PATCH 0
#define XOMBE_VERSION (XOMBE_VERSION_MAJOR * 10000 + XOMBE_VERSION_MINOR * 100 + XOMBE_VERSION_PATCH)
/* the XOMBE_VERSION the library was built with */
XOMBE_API int xombe_version(void);
enum xombe_codec {
XOMBE_DMR = 0, /* AMBE+2 half rate, 49 voice bits, DMR rate-33 FEC */
XOMBE_DSTAR = 1 /* AMBE 2400, 48 voice bits, D-STAR FEC */
};
#define XOMBE_FRAME_BYTES 9
#define XOMBE_BITS_BYTES 7
/* flags of every call that decodes or transcodes a frame
LOST: the frame was not received, its input is not read (may be NULL). concealed as a bad frame (repeat, mute
after three concealed frames in a row), the error counts and the running error rate are left alone
BF, HB: the *_bits calls only, the error rule's flags as xombe_fec_decode returns them. calls that take frames
compute them */
#define XOMBE_FLAG_LOST 0x1u
#define XOMBE_FLAG_BF 0x4u /* bad frame: conceal by repeating */
#define XOMBE_FLAG_HB 0x8u /* high error rate: mute */
#define XOMBE_HALF_MIN 76
#define XOMBE_HALF_MAX 84
enum xombe_class {
XOMBE_CLASS_VOICE = 0,
XOMBE_CLASS_ERASURE = 1,
XOMBE_CLASS_SILENCE = 2,
XOMBE_CLASS_TONE = 3
};
enum xombe_conceal {
XOMBE_CONCEAL_NONE = 0,
XOMBE_CONCEAL_REPEAT = 1,
XOMBE_CONCEAL_MUTE = 2
};
/* decoder noise source: production (the default), or the conformance generator, which reproduces the test vectors */
enum xombe_noise_mode {
XOMBE_NOISE_PRODUCTION = 0,
XOMBE_NOISE_CONFORMANCE = 1
};
/* a decoder's account of the last frame. before the first frame all 0 but mute_src = e0 = e1 = -1 */
typedef struct {
enum xombe_class cls; /* ERASURE for a DMR erasure frame or a lost one, SILENCE for a DMR silence frame
or a D-STAR null frame */
enum xombe_conceal conceal; /* what played in place of the frame: NONE, REPEAT, or MUTE */
int run; /* concealed frames in a row up to this one, 0 if it was not concealed */
int64_t mute_src; /* with MUTE: frame (0 = first) the muted set came from, -1 for the initial set */
int e0, e1; /* as xombe_fec_stats eps0 and eps1, -1 if lost or from a *_bits call */
int bf, hb; /* error rule: bad frame, high error rate (*_bits calls: the flags passed), 0 if
lost */
} xombe_decision;
/* channel FEC: voice bits <-> frames, stateless but for the running error rate
eps0, eps1: Golay corrections in the two protected words, DMR 0..4 and 0..3, D-STAR 0..4 each, 4 =
uncorrectable. eps_t: their sum. bf, hb: the codec's error rule
eps_r: running error rate 0.95*eps_r + 0.05*eps_t/n per frame, n 47 (DMR) or 48 (D-STAR), Q24 (1 << 24 = 1.0) */
typedef struct {
int eps0, eps1, eps_t;
int bf, hb;
uint32_t eps_r;
} xombe_fec_stats;
typedef struct {
int codec;
uint32_t eps_r;
float er;
} xombe_fec; /* contents private, set by xombe_fec_init */
XOMBE_API int xombe__fec_init_dmr(xombe_fec *f);
XOMBE_API int xombe__fec_init_dstar(xombe_fec *f);
XOMBE_API void xombe__fec_encode_dmr(const uint8_t bits[XOMBE_BITS_BYTES], uint8_t frame[XOMBE_FRAME_BYTES]);
XOMBE_API int xombe__fec_encode_dstar(const uint8_t bits[XOMBE_BITS_BYTES], uint8_t frame[XOMBE_FRAME_BYTES]);
/* returns 0, -1 for a codec not built (f unchanged) */
static inline int xombe_fec_init(xombe_fec *f, enum xombe_codec codec)
{
return codec == XOMBE_DMR ? xombe__fec_init_dmr(f) : codec == XOMBE_DSTAR ? xombe__fec_init_dstar(f) : -1;
}
/* returns 0, -1 with nothing written for a codec not built */
static inline int xombe_fec_encode(enum xombe_codec codec, const uint8_t bits[XOMBE_BITS_BYTES],
uint8_t frame[XOMBE_FRAME_BYTES])
{
if (codec == XOMBE_DMR) {
xombe__fec_encode_dmr(bits, frame);
return 0;
}
return codec == XOMBE_DSTAR ? xombe__fec_encode_dstar(bits, frame) : -1;
}
/* fills st (may be NULL), returns the frame's XOMBE_FLAG_* word */
XOMBE_API unsigned xombe_fec_decode(xombe_fec *f, const uint8_t frame[XOMBE_FRAME_BYTES],
uint8_t bits[XOMBE_BITS_BYTES], xombe_fec_stats *st);
/* decoder: frames or voice bits in, PCM out, no delay. FEC decoded here, classes, concealment, then synthesis
DMR: an erasure frame or a bad one repeats the last played set, a high running error rate mutes
D-STAR: classes voice, tone, or null frame (b0 124 or 125, and the DTX fill b0 127, ff x 9). a bad voice frame
repeats the last played set, a high running error rate mutes */
typedef struct xombe_dec xombe_dec;
#define XOMBE_DEC_SIZE 5248
typedef union {
int64_t align_i;
void *align_p;
unsigned char bytes[XOMBE_DEC_SIZE];
} xombe_dec_mem;
XOMBE_API size_t xombe_dec_size(void);
XOMBE_API xombe_dec *xombe__dec_init_dmr(void *mem);
XOMBE_API xombe_dec *xombe__dec_init_dstar(void *mem);
static inline xombe_dec *xombe_dec_init(void *mem, enum xombe_codec codec)
{
return codec == XOMBE_DMR ? xombe__dec_init_dmr(mem) : codec == XOMBE_DSTAR ? xombe__dec_init_dstar(mem) : NULL;
}
/* noise source and its seed (0: default), restarts the source. init sets XOMBE_NOISE_PRODUCTION, seed 0.
call before the first frame, returns 0, -1 for an unknown mode */
XOMBE_API int xombe_dec_set_noise(xombe_dec *d, enum xombe_noise_mode mode, uint32_t seed);
/* flags: 0 or XOMBE_FLAG_LOST. writes 160 samples, returns 1. after an unpaired first half it only ends that
frame and returns 0: pcm[0..79] zeros, pcm[80..159] the pending second half, in unread, so pass it again */
XOMBE_API int xombe_dec_frame(xombe_dec *d, const uint8_t in[XOMBE_FRAME_BYTES], unsigned flags, int16_t pcm[160]);
/* one half-frame of n samples, n clamped to 76..84 (pcm holds XOMBE_HALF_MAX whatever n), returns the count
written. calls alternate first half (second_half 0, reads in and flags) and second half (in unread, may be
NULL), a call out of that order writes nothing and returns -1. two halves of 80 equal xombe_dec_frame */
XOMBE_API int xombe_dec_half(xombe_dec *d, const uint8_t in[XOMBE_FRAME_BYTES], unsigned flags, int second_half,
int n, int16_t *pcm);
/* xombe_dec_frame and xombe_dec_half for voice bits, FEC done by the caller. flags: XOMBE_FLAG_LOST, or
XOMBE_FLAG_BF | XOMBE_FLAG_HB as xombe_fec_decode returns them */
XOMBE_API int xombe_dec_frame_bits(xombe_dec *d, const uint8_t bits[XOMBE_BITS_BYTES], unsigned flags,
int16_t pcm[160]);
XOMBE_API int xombe_dec_half_bits(xombe_dec *d, const uint8_t bits[XOMBE_BITS_BYTES], unsigned flags,
int second_half, int n, int16_t *pcm);
/* *_bits calls: FEC error counts for adaptive smoothing (xombe_fec_stats eps_t, eps1), kept until set again.
the frame calls set them from their own FEC */
XOMBE_API void xombe_dec_set_errors(xombe_dec *d, int eps_t, int eps1);
XOMBE_API void xombe_dec_decision_get(const xombe_dec *d, xombe_decision *out);
/* tone frame of AMBE+2 tone ID id (5..122, 128..163) at level ad (0..127), as xombe_enc_tone. D-STAR sends the
tone at AD max(ad, 8), as the encoder and the transcoder do. returns 0, -1 with nothing written for an id or ad
out of range, a codec not built, or a D-STAR id without a tone code (Knox IDs 144..159) */
XOMBE_API int xombe__tone_frame_dmr(int id, int ad, uint8_t out[XOMBE_FRAME_BYTES]);
XOMBE_API int xombe__tone_frame_dstar(int id, int ad, uint8_t out[XOMBE_FRAME_BYTES]);
static inline int xombe_tone_frame(enum xombe_codec codec, int id, int ad, uint8_t out[XOMBE_FRAME_BYTES])
{
return codec == XOMBE_DMR ? xombe__tone_frame_dmr(id, ad, out)
: codec == XOMBE_DSTAR ? xombe__tone_frame_dstar(id, ad, out)
: -1;
}
/* encoder outputs, xombe_enc_cfg.outputs. XOMBE_ENC_DSTAR needs XOMBE_HAVE_DSTAR, init refuses it otherwise */
#define XOMBE_ENC_DMR 0x1u
#define XOMBE_ENC_DSTAR 0x2u
/* DMR amplitude quantizers, xombe_enc_cfg.dmr_quant */
#define XOMBE_ENC_QUANT_CLOSED 0 /* weighted closed-loop search, better quality */
#define XOMBE_ENC_QUANT_OPEN 1 /* open loop, faster */
#if XOMBE_HAVE_ENCODER
/* encoder delay, frames: DMR alone, and with the D-STAR output on. D-STAR's tone rules look one frame further
ahead than the pitch tracker (a tone-in-noise frame needs the next frame's tone decision). both outputs share
the delay: with both on the DMR frames are those of a DMR-only encoder, one call later */
#define XOMBE_ENC_DELAY 3
#define XOMBE_ENC_DSTAR_DELAY (XOMBE_ENC_DELAY + 1)
typedef struct xombe_enc xombe_enc;
/* state size: larger with q15 kernels, and XOMBE_ENC_DSTAR_SIZE more with D-STAR, whether or not used. without
D-STAR, XOMBE_ENC_CQ_SIZE more for the closed-loop quantizer's workspace (with D-STAR it shares the D-STAR's) */
#if XOMBE_HAVE_DSTAR
#define XOMBE_ENC_DSTAR_SIZE 21504
#define XOMBE_ENC_CQ_SIZE 0
#else
#define XOMBE_ENC_DSTAR_SIZE 0
#define XOMBE_ENC_CQ_SIZE 19968
#endif
#if XOMBE_KERNELS_Q15
#define XOMBE_ENC_SIZE (39424 + XOMBE_ENC_DSTAR_SIZE + XOMBE_ENC_CQ_SIZE)
#else
#define XOMBE_ENC_SIZE (25088 + XOMBE_ENC_DSTAR_SIZE + XOMBE_ENC_CQ_SIZE)
#endif
typedef union {
int64_t align_i;
void *align_p;
unsigned char bytes[XOMBE_ENC_SIZE];
} xombe_enc_mem;
/* xombe_enc_cfg_default's values in parentheses, flags are on when nonzero */
typedef struct {
int ns; /* noise suppression (on) */
int ns_strength_permille; /* noise suppression strength, 0..1000 (500) */
int tones; /* tone detection, both outputs (on) */
int voicing_scale_permille; /* voicing decision scale, > 0 (350, 600 is less heavily voiced) */
unsigned outputs; /* XOMBE_ENC_DMR and/or XOMBE_ENC_DSTAR (DMR, 0 means DMR) */
int dmr_dtx; /* DMR silence frames for background (on) */
int dstar_dtx; /* D-STAR null frames for background (off) */
int dmr_quant; /* DMR amplitude quantizer, XOMBE_ENC_QUANT_* (CLOSED) */
} xombe_enc_cfg;
/* tone sent in place of one input frame's speech, xombe_enc_frame */
typedef struct {
int id; /* AMBE+2 tone ID: 5..122 single tones at 31.25 Hz * id, 128..163 dual tones (DTMF 128..143, Knox
144..159, call progress 160..163) */
int ad; /* level 0..127, each component's amplitude 16384 * 10^(0.03555 * (ad - 127)), 0.711 dB per step */
} xombe_enc_tone;
/* encoder: PCM in, frames of either or both codecs out from one analysis, xombe_enc_delay(e) frames late */
XOMBE_API void xombe_enc_cfg_default(xombe_enc_cfg *cfg);
XOMBE_API size_t xombe_enc_size(void);
/* cfg NULL: the defaults, cfg is copied. returns NULL if mem is NULL or cfg is invalid: ns_strength_permille
outside 0..1000, voicing_scale_permille <= 0, an unknown outputs bit, XOMBE_ENC_DSTAR without
XOMBE_HAVE_DSTAR, or an unknown dmr_quant */
XOMBE_API xombe_enc *xombe_enc_init(void *mem, const xombe_enc_cfg *cfg);
/* XOMBE_ENC_DELAY, or XOMBE_ENC_DSTAR_DELAY when the D-STAR output is on */
XOMBE_API int xombe_enc_delay(const xombe_enc *e);
/* returns 1 when the frames hold the input xombe_enc_delay(e) calls earlier, else 0. pcm NULL: 160 zeros, at the
end of input call it xombe_enc_delay(e) times so every input frame has its output. tone: this frame sent as a
tone, even with cfg.tones 0, NULL for none. the tone frame is the output xombe_enc_delay(e) calls later, pcm is
still analysed. D-STAR gets the tone at AD max(ad, 8), or for a Knox ID a voice frame from the tone table
dmr and dstar may be NULL. an output the encoder does not produce, or any output before the delay has elapsed,
is written as that codec's silence frame (D-STAR: the null frame). with both on the D-STAR frames differ
slightly from a D-STAR-only encoder's: the DMR voicing then drives the shared noise tracking
returns -1 with nothing consumed for a tone id or ad out of range */
XOMBE_API int xombe_enc_frame(xombe_enc *e, const int16_t *pcm, const xombe_enc_tone *tone,
uint8_t dmr[XOMBE_FRAME_BYTES], uint8_t dstar[XOMBE_FRAME_BYTES]);
/* xombe_enc_frame writing voice bits */
XOMBE_API int xombe_enc_frame_bits(xombe_enc *e, const int16_t *pcm, const xombe_enc_tone *tone,
uint8_t dmr[XOMBE_BITS_BYTES], uint8_t dstar[XOMBE_BITS_BYTES]);
#endif
#if XOMBE_HAVE_DSTAR
/* transcoder between DMR and D-STAR frames, in the parameter domain: the source decoder's FEC, error rule,
classes, concealment, and dequantization, then the parameters requantized against the target decoder's
prediction memory. one frame out per frame in, no delay, nothing to flush. from D-STAR needs
XOMBE_HAVE_ENCODER, init returns NULL without it
DMR -> D-STAR
voice nearest D-STAR pitch, per-kHz voicing, amplitudes resampled to the D-STAR harmonics
silence all-unvoiced voice frame from the comfort-noise amplitudes
tone D-STAR tone frame, same tone and level. Knox tones (IDs 144..159, no D-STAR code) become voice
frames at the tone table's f0
concealed what the DMR decoder plays (its repeat or mute set), for a concealed tone the last output frame
again
D-STAR -> DMR
voice nearest DMR pitch, voicing from the previous and current D-STAR b1, amplitudes resampled to the
DMR harmonics
pulse an all-unvoiced D-STAR frame whose b0 maps to a pulse: DMR pulse frame (b1 18..31)
tone DMR tone frame, same tone ID and level (Knox tones arrive as voice frames and stay voice)
silence null frames and mutes: the standard DMR silence frame
concealed the D-STAR decoder's repeat set, requantized with the last good frame's voicing and pitch */
#define XOMBE_XC_DELAY 0
typedef struct xombe_xc xombe_xc;
#define XOMBE_XC_SIZE 23168
#define XOMBE_XC_SHARED_SIZE 3712 /* without the workspace, for xombe_xc_init_shared */
typedef union {
int64_t align_i;
void *align_p;
unsigned char bytes[XOMBE_XC_SIZE];
} xombe_xc_mem;
typedef union {
int64_t align_i;
void *align_p;
unsigned char bytes[XOMBE_XC_SHARED_SIZE];
} xombe_xc_shared_mem;
/* a transcoder's quantizer workspace: scratch only, nothing in it lives between calls, so transcoders that never
run at the same time can share one (xombe_xc_init_shared). XOMBE_XC_SIZE includes its own */
#define XOMBE_QWS_SIZE 19968
typedef union {
int64_t align_i;
void *align_p;
unsigned char bytes[XOMBE_QWS_SIZE];
} xombe_qws_mem;
enum xombe_xc_out {
XOMBE_XC_OUT_VOICE = 0, /* voice frame (to D-STAR: also for DMR silence) */
XOMBE_XC_OUT_PULSE = 1, /* to DMR: pulse frame, b1 18..31 */
XOMBE_XC_OUT_TONE = 2, /* tone frame */
XOMBE_XC_OUT_KNOX = 3, /* to D-STAR: voice frame for a Knox tone */
XOMBE_XC_OUT_SILENCE = 4, /* to DMR: the standard silence frame */
XOMBE_XC_OUT_RESEND = 5 /* to D-STAR: the previous output again (initially the D-STAR null frame) */
};
typedef struct {
xombe_decision in; /* the source decoder's account of the input frame */
enum xombe_xc_out out;
} xombe_xc_decision;
XOMBE_API size_t xombe_xc_size(void);
XOMBE_API xombe_xc *xombe__xc_init_dmr(void *mem);
XOMBE_API xombe_xc *xombe__xc_init_dstar(void *mem);
XOMBE_API xombe_xc *xombe__xc_init_shared_dmr(void *mem, void *ws);
XOMBE_API xombe_xc *xombe__xc_init_shared_dstar(void *mem, void *ws);
/* from: the input frames' codec, the output is the other one */
static inline xombe_xc *xombe_xc_init(void *mem, enum xombe_codec from)
{
return from == XOMBE_DMR ? xombe__xc_init_dmr(mem) : from == XOMBE_DSTAR ? xombe__xc_init_dstar(mem) : NULL;
}
/* mem: XOMBE_XC_SHARED_SIZE bytes (an xombe_xc_shared_mem). ws: XOMBE_QWS_SIZE bytes (an xombe_qws_mem),
zeroed here, shared only between transcoders called from one thread. NULL if either is NULL */
static inline xombe_xc *xombe_xc_init_shared(void *mem, enum xombe_codec from, void *ws)
{
return from == XOMBE_DMR ? xombe__xc_init_shared_dmr(mem, ws)
: from == XOMBE_DSTAR ? xombe__xc_init_shared_dstar(mem, ws)
: NULL;
}
/* flags: 0 or XOMBE_FLAG_LOST. returns 1, out holds this input's frame */
XOMBE_API int xombe_xc_frame(xombe_xc *x, const uint8_t in[XOMBE_FRAME_BYTES], unsigned flags,
uint8_t out[XOMBE_FRAME_BYTES]);
XOMBE_API void xombe_xc_decision_get(const xombe_xc *x, xombe_xc_decision *out);
#endif
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# fetch_librispeech.sh [OUT]: four LibriSpeech dev-clean-2 utterances as 8 kHz raw at -26 dBov
# (OUT defaults to build/librispeech in the source tree), needs curl, sox, and a Python with numpy and scipy
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
OUT=${1:-$ROOT/build/librispeech}
PY=${PYTHON:-python3}
URL=https://www.openslr.org/resources/31/dev-clean-2.tar.gz
SHA256=176ec501490eced2d6c1f89f4f0ddc7dfe799e649e5322f8ba49fe3ff50c8012
for t in curl sox; do
command -v $t > /dev/null || { echo "$t not found" >&2; exit 1; }
done
if command -v sha256sum > /dev/null; then
sha() { sha256sum "$1"; }
elif command -v shasum > /dev/null; then
sha() { shasum -a 256 "$1"; }
else
echo "sha256sum or shasum not found" >&2; exit 1
fi
"$PY" -c 'import numpy, scipy' 2> /dev/null || { echo "$PY has no numpy or scipy (set PYTHON)" >&2; exit 1; }
mkdir -p "$OUT"
cd "$OUT"
if [ ! -f dev-clean-2.tar.gz ]; then
curl -L -o dev-clean-2.tar.gz.part "$URL"
mv dev-clean-2.tar.gz.part dev-clean-2.tar.gz
fi
digest=$(sha dev-clean-2.tar.gz | cut -d' ' -f1)
[ "$digest" = "$SHA256" ] || { echo "unexpected SHA-256 $digest for dev-clean-2.tar.gz" >&2; exit 1; }
for spec in lsf1:2035-147960-0000 lsm1:6295-244435-0010 lsm2:1272-135031-0010 lsf2:84-121550-0001; do
name=${spec%%:*}
utt=${spec#*:}
spk=$(echo "$utt" | cut -d- -f1)
chap=$(echo "$utt" | cut -d- -f2)
member=LibriSpeech/dev-clean-2/$spk/$chap/$utt.flac
tar -xzf dev-clean-2.tar.gz "$member"
sox "$member" -r 8000 -b 16 -e signed-integer -c 1 -t raw "$name.raw" rate -v
"$PY" - "$ROOT/tools" "$name.raw" <<'PYEOF'
import sys
sys.path.insert(0, sys.argv[1])
import numpy as np
from common import p56
x = np.fromfile(sys.argv[2], '<i2').astype(float)
y = np.clip(np.round(x * 10 ** ((-26.0 - p56(x)) / 20)), -32768, 32767).astype('<i2')
y.tofile(sys.argv[2])
print('%s: %.1f dBov' % (sys.argv[2], p56(y)))
PYEOF
done
echo "wrote lsf1.raw lsm1.raw lsm2.raw lsf2.raw to $OUT"
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""writes src/tables/cq_q15_tables.c, the q15 closed-loop quantizer's int16 images of the PRBA codebooks"""
import os
import re
import struct
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
OUT = os.path.join(ROOT, 'src', 'tables', 'cq_q15_tables.c')
SETS = [ # name, file, prba24, prba58, ok_prba24, ok_prba58
('ambe2', 'tables.c', 'xombe__prba24', 'xombe__prba58', None, None),
('dstar', 'dstar_tables.c', 'xombe__ds_prba24', 'xombe__ds_prba58', 'xombe__ds_ok_prba24', 'xombe__ds_ok_prba58'),
]
PAIRS24 = [(0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2)]
PAIRS58 = [(0, 0), (1, 1), (2, 2), (3, 3), (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
def fl32(x):
return struct.unpack('f', struct.pack('f', x))[0]
def f32(x):
"""x rounded to the nearest float, printed to read back exactly"""
v = fl32(x)
s = '%.9g' % v
if 'e' not in s and '.' not in s:
s += '.0'
return s + 'f'
def f32_up(x):
"""the smallest float >= x, x >= 0"""
v = fl32(x)
if v < x:
v = struct.unpack('f', struct.pack('I', struct.unpack('I', struct.pack('f', v))[0] + 1))[0]
return v
def table(src, name, cols):
body = re.search(name + r'\[\d+\]\[%d\] = \{(.*?)\};' % cols, src, re.S).group(1)
v = [fl32(float(t.rstrip('f'))) for t in re.findall(r'[-+0-9.eE]+f', body)]
return [v[i:i + cols] for i in range(0, len(v), cols)]
def mask(src, name, n):
if not name:
return [1] * n
body = re.search(name + r'\[%d\] = \{(.*?)\};' % n, src, re.S).group(1)
return [int(t) for t in body.replace(',', ' ').split()]
def rnd(v):
"""nearest integer, halves away from zero: |v - rnd(v)| <= 1/2"""
return int(v + 0.5) if v >= 0 else -int(-v + 0.5)
def scale(maxabs):
"""largest t with maxabs * 2^t <= 32767"""
t = 0
while maxabs * 2.0 ** (t + 1) <= 32767:
t += 1
while maxabs * 2.0 ** t > 32767:
t -= 1
return t
def image(rows, pairs, words):
"""monomials x_a x_b (a < b doubled) at 2^-tm, then x at 2^-tx, as int16 pairs padded to words"""
dim = len(rows[0])
mono = [[(1.0 if a == b else 2.0) * r[a] * r[b] for a, b in pairs] for r in rows] # exact in double
tm = scale(max(abs(v) for m in mono for v in m))
tx = scale(max(abs(v) for r in rows for v in r))
ints = []
for r, m in zip(rows, mono):
h = [rnd(v * 2.0 ** tm) for v in m] + [rnd(v * 2.0 ** tx) for v in r]
h += [0] * (2 * words - len(h))
ints.append(h)
mmax = [max(abs(h[k]) for h in ints) / 2.0 ** tm for k in range(len(pairs))]
xmax = [max(abs(h[len(pairs) + a]) for h in ints) / 2.0 ** tx for a in range(dim)]
return ints, tm, tx, mmax, xmax
def words_c(h):
return '{' + ', '.join('0x%08xu' % ((h[2 * k] & 0xffff) | (h[2 * k + 1] & 0xffff) << 16)
for k in range(len(h) // 2)) + '}'
def floats(v):
return '{' + ', '.join(f32(f32_up(x)) for x in v) + '}'
def emit(out, name, src, n24, n58, ok24, ok58):
p24, p58 = table(src, n24, 3), table(src, n58, 4)
u24, u58 = mask(src, ok24, len(p24)), mask(src, ok58, len(p58))
i24, tm24, tx24, m24, x24 = image(p24, PAIRS24, 5)
i58, tm58, tx58, m58, x58 = image(p58, PAIRS58, 8)
# n3, n4 as the float code forms them, rounded up past its rounding
n3 = max(sum(v * v for v in r) for r, u in zip(p24, u24) if u) * (1 + 2.0 ** -20)
n4 = max(sum(v * v for v in r) for r, u in zip(p58, u58) if u) * (1 + 2.0 ** -20)
used = [r for r, u in zip(p58, u58) if u]
sx = [sum(r[a] for r in used) for a in range(4)]
sxx = [[sum(r[a] * r[b] for r in used) for b in range(4)] for a in range(4)]
out.append('static const uint32_t r24_%s[%d][5] = {' % (name, len(i24)))
out += [' ' + words_c(h) + ',' for h in i24]
out.append('};')
out.append('static const uint32_t r58_%s[%d][8] = {' % (name, len(i58)))
out += [' ' + words_c(h) + ',' for h in i58]
out.append('};')
out.append('const xombe_cq_q15_tab xombe__cq_q15_%s = {' % name)
out.append(' r24_%s, r58_%s, %d, %d, %d, %d,' % (name, name, tm24, tx24, tm58, tx58))
tail = [floats(m24), floats(x24), floats(m58), floats(x58), f32(f32_up(n3)), f32(f32_up(n4)), str(len(used)),
'{' + ', '.join(f32(v) for v in sx) + '}',
'{' + ', '.join('{' + ', '.join(f32(v) for v in row) + '}' for row in sxx) + '}']
line = ' '
for i, t in enumerate(tail):
for tok in t.split(' '):
if len(line) + 1 + len(tok) > 116:
out.append(line)
line = ' '
line += ' ' + tok
line += ',' if i < len(tail) - 1 else '};'
out.append(line)
def main():
out = ['/* generated by scripts/gen_cq_tables.py, do not edit */', '#include "cq_q15_tables.h"', '',
'#if XOMBE_KERNELS_Q15 && (XOMBE_HAVE_ENCODER || XOMBE_HAVE_DSTAR)']
for name, fn, n24, n58, ok24, ok58 in SETS:
src = open(os.path.join(ROOT, 'src', 'tables', fn)).read()
if name == 'dstar':
out.append('#if XOMBE_HAVE_DSTAR')
emit(out, name, src, n24, n58, ok24, ok58)
if name == 'dstar':
out.append('#endif')
out.append('#else')
out.append('typedef int xombe__cq_q15_tables_unused;')
out.append('#endif')
with open(OUT, 'w') as f:
f.write('\n'.join(out) + '\n')
if __name__ == '__main__':
main()
+230
View File
@@ -0,0 +1,230 @@
#!/usr/bin/env python3
"""writes src/tables/dsp_tables.c, closed-form values computed in double and rounded to float"""
import math
import os
import re
import struct
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
OUT = os.path.join(ROOT, 'src', 'tables', 'dsp_tables.c')
TABLES = os.path.join(ROOT, 'src', 'tables', 'tables.c')
DCT_BLK_J_MAX = 17 # XOMBE_DCT_BLK_J_MAX, largest spectral block length (xombe__blk)
DCT_BLK_ROWS = 6 # XOMBE_DCT_BLK_ROWS, one kernel row per DCT coefficient m = 0..5
GRAIN_RAMP = 16 # XOMBE_GRAIN_RAMP
HALF_MIN, HALF_MAX = 76, 84
LMAX = 56
B0_COUNT = 120
TW_N = 1024 # analysis FFT, smaller transforms take every (TW_N/n)-th twiddle
FFT = 1024 # XOMBE_FFT
BASE_WINDOW = 199
PITCH_LPF_HALF = 10
PITCH_WIN = 301
TONE_SEG = 240
TONE_FFT = 512 # XOMBE_TONE_FFT
def f32(x):
"""x rounded to the nearest float, printed to read back exactly"""
if abs(x) < 1e-12: # cos(pi/2) and similar are exactly 0
x = 0.0
v = struct.unpack('f', struct.pack('f', x))[0]
s = '%.9g' % v
if 'e' not in s and '.' not in s:
s += '.0'
return s + 'f'
def fl32(x):
"""x rounded to float, the result of a float operation whose exact value is x"""
return struct.unpack('f', struct.pack('f', x))[0]
def round_q(v):
"""(int)(v + (v < 0 ? -0.5f : 0.5f)) for float v"""
return int(fl32(v + (-0.5 if v < 0 else 0.5)))
def rows(values, per_line=6, indent=' '):
lines = []
for i in range(0, len(values), per_line):
lines.append(indent + ', '.join(values[i:i + per_line]) + ',')
return '\n'.join(lines)
def w0_table():
"""xombe__w0 as spelled in tables.c (the standard's pitch table as float)"""
src = open(TABLES).read()
body = re.search(r'xombe__w0\[XOMBE_B0_COUNT\] = \{(.*?)\};', src, re.S).group(1)
vals = [struct.unpack('f', struct.pack('f', float(v.rstrip('f'))))[0] for v in body.replace(',', ' ').split()]
assert len(vals) == B0_COUNT and all(a > b for a, b in zip(vals, vals[1:]))
return vals
def hamming(i, n):
return 0.54 - 0.46 * math.cos(2.0 * math.pi * i / (n - 1))
def dct(J, m, i):
return math.cos(math.pi * m * (i + 0.5) / J)
def main():
out = ['/* generated by scripts/gen_dsp_tables.py, do not edit */', '#include "dsp_tables.h"', '']
out.append('const float xombe__dct8[8][8] = {')
for m in range(8):
out.append(' {' + ', '.join(f32(dct(8, m, i)) for i in range(8)) + '},')
out.append('};')
out.append('')
offs, vals = [], []
for J in range(DCT_BLK_J_MAX + 1):
offs.append(str(len(vals)))
for m in range(DCT_BLK_ROWS):
vals.extend(f32(dct(J, m, i)) for i in range(J))
out.append('const unsigned short xombe__dct_blk_off[XOMBE_DCT_BLK_J_MAX + 1] = {')
out.append(rows(offs, 12))
out.append('};')
out.append('')
out.append('const float xombe__dct_blk[XOMBE_DCT_BLK_SIZE] = {')
out.append(rows(vals))
out.append('};')
out.append('')
out.append('const float xombe__ramp_cos[XOMBE_GRAIN_RAMP] = {')
out.append(rows([f32(math.cos(math.pi * j / GRAIN_RAMP)) for j in range(GRAIN_RAMP)]))
out.append('};')
out.append('')
out.append('const float xombe__ramp_sin[XOMBE_GRAIN_RAMP] = {')
out.append(rows([f32(math.sin(math.pi * j / GRAIN_RAMP)) for j in range(GRAIN_RAMP)]))
out.append('};')
out.append('')
out.append('const float xombe__sqrt_n[XOMBE_HALF_MAX + 1] = {')
out.append(rows([f32(math.sqrt(n)) for n in range(HALF_MAX + 1)]))
out.append('};')
out.append('')
out.append('const float xombe__rsqrt_half[XOMBE_HALF_MAX - XOMBE_HALF_MIN + 1] = {')
out.append(rows([f32(1.0 / math.sqrt(N)) for N in range(HALF_MIN, HALF_MAX + 1)]))
out.append('};')
out.append('')
out.append('const float xombe__half_log2[XOMBE_LMAX + 1] = {')
out.append(rows(['0.0f'] + [f32(0.5 * math.log2(L)) for L in range(1, LMAX + 1)]))
out.append('};')
out.append('')
w0 = w0_table()
out.append('const float xombe__w0_mid[XOMBE_B0_COUNT - 1] = {')
out.append(rows([f32(math.sqrt(w0[b] * w0[b + 1])) for b in range(B0_COUNT - 1)]))
out.append('};')
out.append('')
out.append('const xombe_cpx xombe__fft_tw[XOMBE_TW_N / 2] = {')
tw = []
for k in range(TW_N // 2):
ang = -2.0 * math.pi * k / TW_N
tw.append('{%s, %s}' % (f32(math.cos(ang)), f32(math.sin(ang))))
out.append(rows(tw, 3))
out.append('};')
out.append('')
out.append('#if XOMBE_HAVE_ENCODER')
out.append('const float xombe__base_win[XOMBE_BASE_WINDOW] = {')
out.append(rows([f32(hamming(i, BASE_WINDOW)) for i in range(BASE_WINDOW)]))
out.append('};')
out.append('')
h = []
for j in range(-PITCH_LPF_HALF, PITCH_LPF_HALF + 1):
x = 0.25 * j
sinc = 1.0 if j == 0 else math.sin(math.pi * x) / (math.pi * x)
h.append(0.25 * sinc * (0.54 + 0.46 * math.cos(math.pi * j / PITCH_LPF_HALF)))
s = 0.0
for v in h:
s += v
lpf = [f32(float(f32(v)[:-1]) / s) for v in h]
out.append('const float xombe__pitch_lpf[2 * XOMBE_PITCH_LPF_HALF + 1] = {')
out.append(rows(lpf))
out.append('};')
out.append('')
# q15 low-pass taps (kern_q15_pitch.c) from the float taps, in float arithmetic as C computes it
# g[m] = h[20 - m] scaled so sum |g| <= 65536 after rounding (a 32-bit SMLAD sum of int16 can't overflow),
# paired, and again shifted by one
lpf = [fl32(float(v[:-1])) for v in lpf]
total = 0.0
for v in lpf:
total = fl32(total + abs(v))
gain = fl32(65000.0 / total)
g = [round_q(fl32(lpf[2 * PITCH_LPF_HALF - m] * gain)) for m in range(2 * PITCH_LPF_HALF + 1)]
taps = 2 * PITCH_LPF_HALF + 2
ga = g + [0] * (taps - len(g))
gb = [0] + g + [0] * (taps - 1 - len(g))
def pairs(t):
return ['0x%08xu' % ((t[i] & 0xffff) | (t[i + 1] & 0xffff) << 16) for i in range(0, taps, 2)]
out.append('#if XOMBE_KERNELS_Q15')
out.append('const uint32_t xombe__pitch_lpf_q15[2][XOMBE_PITCH_LPF_PAIRS] = {')
for t in (ga, gb):
out.append(' {')
out.append(rows(pairs(t), 6, ' ' * 8))
out.append(' },')
out.append('};')
out.append('const float xombe__pitch_lpf_q15_gain = %s;' % f32(gain))
def q15(v):
return min(32767, math.floor(v * 32768.0 + 0.5)) & 0xffff
tq = []
for j in range(FFT // 4):
ang = -2.0 * math.pi * j / (FFT // 2)
tq.append('0x%08xu' % (q15(math.cos(ang)) | q15(math.sin(ang)) << 16))
out.append('const uint32_t xombe__fft_tw_q15[XOMBE_FFT / 4] = {')
out.append(rows(tq, 6))
out.append('};')
tq = []
for j in range(TONE_FFT // 4):
ang = -2.0 * math.pi * j / (TONE_FFT // 2)
tq.append('0x%08xu' % (q15(math.cos(ang)) | q15(math.sin(ang)) << 16))
out.append('const uint32_t xombe__tone_tw_q15[XOMBE_TONE_FFT / 4] = {')
out.append(rows(tq, 6))
out.append('};')
out.append('#endif')
out.append('')
w = [hamming(j, PITCH_WIN) for j in range(PITCH_WIN)]
s2 = s4 = 0.0
for v in w:
s2 += v * v
w2 = [v * v / s2 for v in w]
for v in w2:
s4 += v * v
out.append('const float xombe__pitch_w2[XOMBE_PITCH_WIN] = {')
out.append(rows([f32(v) for v in w2]))
out.append('};')
out.append('const float xombe__pitch_sum_w4 = %s;' % f32(s4))
# q15 pitch window (kern_q15_pitch.c) from the float table, scaled to peak 32767, first half (symmetric)
w2f = [fl32(float(f32(v)[:-1])) for v in w2]
w2_gain = fl32(32767.0 / max(w2f))
w2q = [round_q(fl32(v * w2_gain)) for v in w2f]
assert w2q == w2q[::-1]
w2q = w2q[:PITCH_WIN // 2 + 1]
out.append('#if XOMBE_KERNELS_Q15')
out.append('const int16_t xombe__pitch_w2_q15[XOMBE_PITCH_HALF + 1] = {')
out.append(rows([str(v) for v in w2q], 12))
out.append('};')
out.append('const float xombe__pitch_w2_q15_gain = %s;' % f32(w2_gain))
out.append('#endif')
out.append('')
out.append('const float xombe__tone_win[XOMBE_TONE_SEG] = {')
out.append(rows([f32(0.5 - 0.5 * math.cos(2.0 * math.pi * i / (TONE_SEG - 1))) for i in range(TONE_SEG)]))
out.append('};')
out.append('#endif')
assert len(vals) == DCT_BLK_ROWS * sum(range(DCT_BLK_J_MAX + 1))
with open(OUT, 'w') as f:
f.write('\n'.join(out) + '\n')
if __name__ == '__main__':
main()
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""writes src/tables/dstar_enc_tables.c and dstar_enc_tables.h, the D-STAR encoder's noise reference and windows
m_noise(N, b0) in scripts/data/dstar_tables.json is the fitted encoder model's mean voicing metric over 8 seeded
numpy white-noise draws, which C cannot reproduce, so it is tabulated for the (N, b0) pairs the encoder can reach,
as round(m*65536) in 16 bits (m < 1, smallest 0.18, relative error <= 3e-5)"""
import json
import math
import os
import struct
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
OUT_C = os.path.join(ROOT, 'src', 'tables', 'dstar_enc_tables.c')
OUT_H = os.path.join(ROOT, 'src', 'tables', 'dstar_enc_tables.h')
DATA = os.path.join(ROOT, 'scripts', 'data', 'dstar_tables.json')
N_MIN, N_MAX = 199, 321
N_COUNT = (N_MAX - N_MIN) // 2 + 1
B0_VOICE_MAX = 123
SCALE = 65536
TONE_LEN, NZ_LEN = 160, 134
def f32(x):
t = '%.9g' % struct.unpack('<f', struct.pack('<f', x))[0]
return t + ('f' if ('.' in t or 'e' in t) else '.0f')
def hann(n):
return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def main():
with open(DATA) as f:
windows = json.load(f)['m_noise']
assert [w['N'] for w in windows] == list(range(N_MIN, N_MAX + 1, 2))
lo, cnt, off, data = [], [], [], []
for w in windows:
assert 0 <= w['b0_lo'] and w['b0_lo'] + len(w['rows']) - 1 <= B0_VOICE_MAX
lo.append(w['b0_lo'])
cnt.append(len(w['rows']))
off.append(len(data))
for m in w['rows']:
q = [int(round(v * SCALE)) for v in m]
assert len(q) == 8 and all(0 < v < SCALE for v in q), (w['N'], m)
data.append(q)
rows = len(data)
h = '''#ifndef XOMBE_DSTAR_ENC_TABLES_H
#define XOMBE_DSTAR_ENC_TABLES_H
/* D-STAR encoder white-noise voicing reference m_noise(N, b0), generated by scripts/gen_dstar_enc_tables.py,
do not edit
window N = %d + 2i (i < XOMBE_DS_MN_WINDOWS) has rows for b0 lo[i]..lo[i] + cnt[i] - 1 from row off[i],
each row the 8 band values x %d */
#define XOMBE_DS_MN_N_MIN %d
#define XOMBE_DS_MN_WINDOWS %d
#define XOMBE_DS_MN_ROWS %d
#define XOMBE_DS_MN_SCALE %d.0f
extern const unsigned char xombe__ds_mn_lo[XOMBE_DS_MN_WINDOWS];
extern const unsigned char xombe__ds_mn_cnt[XOMBE_DS_MN_WINDOWS];
extern const unsigned short xombe__ds_mn_off[XOMBE_DS_MN_WINDOWS];
extern const unsigned short xombe__ds_mn[XOMBE_DS_MN_ROWS][8];
/* tone detector segment and tone-in-noise window lengths in samples, Hann windows 0.5 - 0.5*cos(2*pi*i/(n - 1)) */
#define XOMBE_DS_TONE_LEN %d
#define XOMBE_DS_NZ_LEN %d
extern const float xombe__ds_tone_win[XOMBE_DS_TONE_LEN];
extern const float xombe__ds_nz_win[XOMBE_DS_NZ_LEN];
#endif
''' % (N_MIN, SCALE, N_MIN, N_COUNT, rows, SCALE, TONE_LEN, NZ_LEN)
def vec(name, ctype, v, per=16):
lines = [' ' + ', '.join(str(x) for x in v[i:i + per]) + ',' for i in range(0, len(v), per)]
return 'const %s %s[%d] = {\n%s\n};\n' % (ctype, name, len(v), '\n'.join(lines))
c = ['/* generated by scripts/gen_dstar_enc_tables.py, do not edit */\n#include "dstar_enc_tables.h"\n']
c.append(vec('xombe__ds_mn_lo', 'unsigned char', lo))
c.append(vec('xombe__ds_mn_cnt', 'unsigned char', cnt))
c.append(vec('xombe__ds_mn_off', 'unsigned short', off))
c.append('const unsigned short xombe__ds_mn[XOMBE_DS_MN_ROWS][8] = {\n%s\n};\n' %
'\n'.join(' {%s},' % ', '.join(str(x) for x in r) for r in data))
for name, n in (('xombe__ds_tone_win', 'XOMBE_DS_TONE_LEN'), ('xombe__ds_nz_win', 'XOMBE_DS_NZ_LEN')):
w = [f32(v) for v in hann(TONE_LEN if n.endswith('TONE_LEN') else NZ_LEN)]
c.append('const float %s[%s] = {\n%s\n};\n' % (name, n, '\n'.join(
' ' + ', '.join(w[i:i + 8]) + ',' for i in range(0, len(w), 8))))
with open(OUT_C, 'w') as f:
f.write('\n'.join(c))
with open(OUT_H, 'w') as f:
f.write(h)
print('%d windows, %d rows, %d bytes' % (N_COUNT, rows, rows * 16 + N_COUNT * 4))
if __name__ == '__main__':
main()
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""writes src/tables/dstar_tables.c and dstar_tables.h, the D-STAR (AMBE 2400) tables, from the fitted values
in scripts/data/dstar_tables.json"""
import json
import math
import os
import struct
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
OUT_C = os.path.join(ROOT, 'src', 'tables', 'dstar_tables.c')
OUT_H = os.path.join(ROOT, 'src', 'tables', 'dstar_tables.h')
DATA = os.path.join(ROOT, 'scripts', 'data', 'dstar_tables.json')
B0_COUNT = 128
LMAX = 56
BANDS_PER_UNIT = 16.0 # 8000 / 500, harmonic l at f0 lies in 500 Hz band floor(l*f0*16)
TONE_NONE = 255
def fl32(x):
return struct.unpack('f', struct.pack('f', float(x)))[0]
def f32(x):
"""x rounded to the nearest float, printed to read back exactly"""
v = fl32(x)
s = '%.9g' % v
if 'e' not in s and '.' not in s:
s += '.0'
return s + 'f'
def rows(values, per_line=6, indent=' '):
return '\n'.join(indent + ', '.join(values[i:i + per_line]) + ',' for i in range(0, len(values), per_line))
def c_matrix(name, ctype, dims, data, fmt):
out = ['const %s %s%s = {' % (ctype, name, ''.join('[%s]' % d for d in dims))]
if len(dims) == 1:
out.append(rows([fmt(v) for v in data], 6 if fmt is f32 else 16))
else:
for r in data:
out.append(' {' + ', '.join(fmt(v) for v in r) + '},')
out.append('};')
return out
def main():
with open(DATA) as f:
T = json.load(f)
p0, p1, rho, grho = float(T['p0']), float(T['p1']), float(T['rho']), float(T['grho'])
w0 = [2.0 ** (p0 + p1 * (b + 0.5)) for b in range(B0_COUNT)]
lt = [int(min(max(math.floor(0.4627 / f), 9), LMAX)) for f in w0]
# decoder's per-harmonic band in float as params.c computes it, ((float)l*f0)*16 with f0 the float table
# value, must equal the double floor(l*f0*8000/500)
for b in range(B0_COUNT):
for l in range(1, lt[b] + 1):
c = int(fl32(fl32(l * fl32(w0[b])) * BANDS_PER_UNIT))
assert c == int(l * w0[b] * 8000.0 / 500.0), (b, l)
dg, p24, p58, hoc = T['DG'], T['PRBA24'], T['PRBA58'], T['HOC']
assert (len(dg), len(p24), len(p58), [len(h) for h in hoc]) == (64, 512, 128, [16, 16, 16, 8])
assert all(len(r) == 4 for h in hoc for r in h)
ok_dg, ok24, ok58, ok_hoc = T['ok_DG'], T['ok_PRBA24'], T['ok_PRBA58'], T['ok_HOC']
# b1 -> flags of 500 Hz bands 0..7 as the decoder plays them (code 4 plays as 12)
vuv = [[int(ch) for ch in s] for s in T['VUV0']]
# D-STAR tone index T -> AMBE+2 tone ID: T 0..15 DTMF (T = 4*column + row), 16..19 call progress,
# 37..154 single tones at 31.25*(T - 32) Hz, every other T invalid
tone = [TONE_NONE if t is None else t for t in T['tone_id']]
# b0 of the D-STAR voice frame carrying Knox tone ID 144 + i (observed)
knox_b0 = T['knox_b0']
assert (len(vuv), len(tone), len(knox_b0)) == (16, 256, 16)
c = ['/* generated by scripts/gen_dstar_tables.py, do not edit */',
'#include "dstar_tables.h"', '']
c += c_matrix('xombe__ds_w0', 'float', ['XOMBE_DS_B0_COUNT'], w0, f32) + ['']
c += c_matrix('xombe__ds_lt', 'unsigned char', ['XOMBE_DS_B0_COUNT'], lt, str) + ['']
c += c_matrix('xombe__ds_dg', 'float', ['64'], dg, f32) + ['']
c += c_matrix('xombe__ds_prba24', 'float', ['512', '3'], p24, f32) + ['']
c += c_matrix('xombe__ds_prba58', 'float', ['128', '4'], p58, f32) + ['']
for k, n in enumerate([16, 16, 16, 8]):
c += c_matrix('xombe__ds_hoc%d' % (k + 5), 'float', [str(n), '4'], hoc[k], f32) + ['']
c += c_matrix('xombe__ds_ok_dg', 'unsigned char', ['64'], ok_dg, str) + ['']
c += c_matrix('xombe__ds_ok_prba24', 'unsigned char', ['512'], ok24, str) + ['']
c += c_matrix('xombe__ds_ok_prba58', 'unsigned char', ['128'], ok58, str) + ['']
for k, n in enumerate([16, 16, 16, 8]):
c += c_matrix('xombe__ds_ok_hoc%d' % (k + 5), 'unsigned char', [str(n)], ok_hoc[k], str) + ['']
c += c_matrix('xombe__ds_vuv', 'unsigned char', ['16', '8'], vuv, str) + ['']
c += c_matrix('xombe__ds_tone_id', 'unsigned char', ['256'], tone, str) + ['']
c += c_matrix('xombe__ds_knox_b0', 'unsigned char', ['16'], knox_b0, str)
h = '''#ifndef XOMBE_DSTAR_TABLES_H
#define XOMBE_DSTAR_TABLES_H
/* D-STAR (AMBE 2400) tables, generated by scripts/gen_dstar_tables.py, do not edit
each value is a fitted double rounded once to float, spectral block lengths are AMBE+2's xombe__blk */
#define XOMBE_DS_B0_COUNT %(nb0)d
/* pitch grid f0 = 2^(P0 + P1*(b0 + 1/2)) cycles/sample, from doubles %(p0)r and %(p1)r */
#define XOMBE_DS_P0 %(p0f)s
#define XOMBE_DS_P1 %(p1f)s
/* amplitude prediction weight and gain recursion (0: b2 is an absolute gain index) */
#define XOMBE_DS_RHO %(rho)s
#define XOMBE_DS_GRHO %(grho)s
#define XOMBE_DS_TONE_NONE %(none)d
/* f0 in cycles/sample and L = floor(0.4627/f0) clamped to 9..56, both from the double f0 (voice b0 0..123) */
extern const float xombe__ds_w0[XOMBE_DS_B0_COUNT];
extern const unsigned char xombe__ds_lt[XOMBE_DS_B0_COUNT];
/* gain (b2), PRBA (b3, b4), and HOC (b5..b8, rows of 4, first min(J, 6) - 2 used) codebooks */
extern const float xombe__ds_dg[64];
extern const float xombe__ds_prba24[512][3];
extern const float xombe__ds_prba58[128][4];
extern const float xombe__ds_hoc5[16][4];
extern const float xombe__ds_hoc6[16][4];
extern const float xombe__ds_hoc7[16][4];
extern const float xombe__ds_hoc8[8][4];
/* 1 where the fit had data for the entry, the closed-loop quantizer skips the others */
extern const unsigned char xombe__ds_ok_dg[64];
extern const unsigned char xombe__ds_ok_prba24[512];
extern const unsigned char xombe__ds_ok_prba58[128];
extern const unsigned char xombe__ds_ok_hoc5[16];
extern const unsigned char xombe__ds_ok_hoc6[16];
extern const unsigned char xombe__ds_ok_hoc7[16];
extern const unsigned char xombe__ds_ok_hoc8[8];
/* b1 -> eight 500 Hz band flags as the decoder plays them (code 4 plays as 12) */
extern const unsigned char xombe__ds_vuv[16][8];
/* tone index T (8 bits) -> AMBE+2 tone ID, or XOMBE_DS_TONE_NONE */
extern const unsigned char xombe__ds_tone_id[256];
/* encoder sends Knox tones (AMBE+2 IDs 144..159, no D-STAR tone code) as voice frames at this b0 per ID */
extern const unsigned char xombe__ds_knox_b0[16];
#endif
''' % dict(nb0=B0_COUNT, p0=p0, p1=p1, p0f=f32(p0), p1f=f32(p1), rho=f32(rho), grho=f32(grho),
none=TONE_NONE)
with open(OUT_C, 'w') as f:
f.write('\n'.join(c) + '\n')
with open(OUT_H, 'w') as f:
f.write(h)
print('wrote', OUT_C, OUT_H)
if __name__ == '__main__':
main()
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
import argparse
import hashlib
import os
import struct
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools'))
from common import CLIPS, DITHER_DB as GAINS_DB, E3IN, E3V
def dither(samples, gain_db):
g = 10.0 ** (gain_db / 20.0)
out = []
for x in samples:
y = round(g * x)
out.append(32767 if y > 32767 else -32768 if y < -32768 else y)
return out
def main():
ap = argparse.ArgumentParser(description='Regenerate the dithered E3 inputs and check them against SHA256SUMS')
ap.add_argument('--dir', default=E3V)
ap.add_argument('--out', default=E3IN, help='output directory (default $XOMBE_BUILD/e3in)')
ap.add_argument('--write-manifest', action='store_true')
a = ap.parse_args()
out_dir = a.out
os.makedirs(out_dir, exist_ok=True)
manifest_path = os.path.join(a.dir, 'SHA256SUMS')
expected = {}
if not a.write_manifest and not os.path.exists(manifest_path):
print('%s is missing; regenerate it with --write-manifest' % manifest_path, file=sys.stderr)
return 1
if not a.write_manifest:
for line in open(manifest_path):
digest, name = line.split()
expected[name] = digest
lines, bad = [], 0
for clip in CLIPS:
raw = open(os.path.join(a.dir, clip + '_orig.raw'), 'rb').read()
x = struct.unpack('<%dh' % (len(raw) // 2), raw)
for k, g in enumerate(GAINS_DB):
data = struct.pack('<%dh' % len(x), *dither(x, g))
name = '%s.d%d.raw' % (clip, k)
open(os.path.join(out_dir, name), 'wb').write(data)
digest = hashlib.sha256(data).hexdigest()
lines.append('%s %s' % (digest, name))
if not a.write_manifest and expected.get(name) != digest:
print('MISMATCH %s' % name)
bad += 1
if a.write_manifest:
open(manifest_path, 'w').write('\n'.join(lines) + '\n')
print('wrote %s' % manifest_path)
else:
print('%d inputs regenerated, %d mismatches against SHA256SUMS' % (len(lines), bad))
return 1 if bad else 0
if __name__ == '__main__':
sys.exit(main())
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# release_buildinfo.sh: the tools behind a release tarball and, on Debian, every installed package
set -eu
git --version
xz --version | head -n 1
if command -v dpkg-query > /dev/null; then
dpkg-query -W -f='${db:Status-Abbrev} ${Package}:${Architecture} ${Version}\n' |
awk '$1 == "ii" { print $2, $3 }' | LC_ALL=C sort
fi
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# release_deps.sh: installs release_packages.lock into the release container (release_lock.sh's base), from
# deb.debian.org or else the snapshot
set -eu
here=$(cd "$(dirname "$0")" && pwd)
rm -f /etc/apt/sources.list.d/*
printf '%s\n' 'deb http://deb.debian.org/debian trixie main' \
'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20261111T000000Z trixie main' \
> /etc/apt/sources.list
apt-get -o Acquire::Retries=5 update || true
# shellcheck disable=SC2046
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $(cat "$here/release_packages.lock")
rm -rf /var/lib/apt/lists/*
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# release_lock.sh: prints the packages (name=version) that release_deps.sh's snapshot adds to the base image, the
# contents of release_packages.lock. CONTAINER picks the engine (podman)
set -eu
base=docker.io/library/debian@sha256:2dc419c6d7fe3dad0a2f9fd469c34cc90b0f9ba642d8fde837fe3d7d34a0e7f1
here=$(cd "$(dirname "$0")" && pwd)
engine=${CONTAINER:-podman}
snap=$(grep -o 'http://snapshot\.debian\.org/archive/debian/[0-9TZ]*' "$here/release_deps.sh")
"$engine" run --rm "$base" sh -euc '
export DEBIAN_FRONTEND=noninteractive
q() { dpkg-query -W -f="\${Package}=\${Version}\n" | LC_ALL=C sort; }
q > /tmp/base
rm -f /etc/apt/sources.list.d/*
echo "deb [check-valid-until=no] $1 trixie main" > /etc/apt/sources.list
apt-get -qq -o Acquire::Retries=5 update
apt-get -qq install -y --no-install-recommends ca-certificates git xz-utils > /dev/null
q | LC_ALL=C comm -13 /tmp/base -
' _ "$snap"
+36
View File
@@ -0,0 +1,36 @@
ca-certificates=20250419
git-man=1:2.47.3-0+deb13u1
git=1:2.47.3-0+deb13u1
libbrotli1=1.1.0-2+b7
libcom-err2=1.47.2-3+b12
libcurl3t64-gnutls=8.14.1-2+deb13u5
liberror-perl=0.17030-1
libexpat1=2.8.3-1~deb13u1
libffi8=3.4.8-2
libgdbm-compat4t64=1.24-2
libgdbm6t64=1.24-2
libgnutls30t64=3.8.9-3+deb13u4
libgssapi-krb5-2=1.21.3-5+deb13u1
libidn2-0=2.3.8-2
libk5crypto3=1.21.3-5+deb13u1
libkeyutils1=1.6.3-6
libkrb5-3=1.21.3-5+deb13u1
libkrb5support0=1.21.3-5+deb13u1
libldap2=2.6.10+dfsg-1
libnghttp2-14=1.64.0-1.1+deb13u1
libnghttp3-9=1.8.0-1
libngtcp2-16=1.11.0-1+deb13u1
libngtcp2-crypto-gnutls8=1.11.0-1+deb13u1
libp11-kit0=0.25.5-3
libperl5.40=5.40.1-6+deb13u1
libpsl5t64=0.21.2-1.1+b1
librtmp1=2.4+20151223.gitfa8646d.1-2+b5
libsasl2-2=2.1.28+dfsg1-9
libsasl2-modules-db=2.1.28+dfsg1-9
libssh2-1t64=1.11.1-1+deb13u2
libtasn1-6=4.20.0-2+deb13u1
libunistring5=1.3-2
openssl=3.5.7-1~deb13u2
perl-modules-5.40=5.40.1-6+deb13u1
perl=5.40.1-6+deb13u1
xz-utils=5.8.1-1+deb13u1
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
# release_tarball.sh [REF [OUT]]: writes xombe-X.Y.Z.tar.xz (git archive of REF, default HEAD) and
# xombe-X.Y.Z.buildinfo to OUT (default dist). byte-identical across hosts in the release container
# (release_deps.sh), the version is REF's include/xombe.h
set -eu
ref=${1:-HEAD}
root=$(cd "$(dirname "$0")/.." && pwd)
out=${2:-$root/dist}
part() { git -C "$root" show "$ref:include/xombe.h" | sed -n "s/^#define XOMBE_VERSION_$1 \([0-9][0-9]*\)\$/\1/p"; }
ver=$(part MAJOR).$(part MINOR).$(part PATCH)
case $ver in
*[!0-9.]* | .* | *..* | *.) echo "no XOMBE_VERSION_MAJOR/MINOR/PATCH in $ref:include/xombe.h" >&2; exit 1 ;;
esac
name=xombe-$ver
mkdir -p "$out"
git -C "$root" archive --format=tar --prefix="$name/" "$ref" -- . ':!.gitignore' | xz -9 -T1 > "$out/$name.tar.xz"
"$root/scripts/release_buildinfo.sh" > "$out/$name.buildinfo"
+188
View File
@@ -0,0 +1,188 @@
#!/bin/sh
# size_table.sh [WORKDIR]: state sizes (test/sizes.c) and worst-case stack per public call for the four builds
# (float and q15 kernels, XOMBE_DSTAR off and on), as Markdown tables. stack is from -fcallgraph-info=su
# (GCC 10 or later) walked over the library's call graph, on the host and, when arm-none-eabi-gcc is installed,
# on a Cortex-M33 build. WORKDIR (default: a temporary directory, removed at the end) holds the builds.
# needs cmake and python3, CC picks the host compiler, ARM_CC the cross compiler
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
PY=${PYTHON:-python3}
ARM_CC=${ARM_CC:-arm-none-eabi-gcc}
JOBS=${JOBS:-4}
if [ $# -gt 0 ]; then
W=$1
mkdir -p "$W"
else
W=$(mktemp -d)
trap 'rm -rf "$W"' EXIT
fi
CI="-fstack-usage -fcallgraph-info=su"
ARM_FLAGS="-mcpu=cortex-m33 -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16"
CONFIGS="float:OFF float:ON q15:OFF q15:ON"
command -v "$ARM_CC" > /dev/null && arm=1 || arm=0
build() { # build DIR KERNELS DSTAR [cmake options]
d=$1 k=$2 ds=$3
shift 3
cmake -S "$ROOT" -B "$d" -DCMAKE_BUILD_TYPE=Release -DXOMBE_KERNELS=$k -DXOMBE_DSTAR=$ds -DXOMBE_BUILD_TOOLS=OFF \
-DXOMBE_INSTALL=OFF "$@" > "$d.log" 2>&1 && cmake --build "$d" -j "$JOBS" >> "$d.log" 2>&1 ||
{ cat "$d.log" >&2; exit 1; }
}
for c in $CONFIGS; do
k=${c%:*} ds=${c#*:}
build "$W/host-$k-$ds" $k $ds -DXOMBE_BUILD_TESTS=ON "-DCMAKE_C_FLAGS=$CI"
if [ $arm = 1 ]; then
build "$W/m33-$k-$ds" $k $ds -DXOMBE_BUILD_TESTS=OFF -DCMAKE_SYSTEM_NAME=Generic -DCMAKE_C_COMPILER="$ARM_CC" \
-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY "-DCMAKE_C_FLAGS_RELEASE=-O2 -DNDEBUG" "-DCMAKE_C_FLAGS=$ARM_FLAGS $CI"
fi
done
echo "### State (bytes) and encoder delay (frames), $(uname -m)"
echo
"$W/host-float-OFF/sizes" --header
for c in $CONFIGS; do
"$W/host-${c%:*}-${c#*:}/sizes"
done
echo
targets="x86-64"
[ $arm = 1 ] && targets="$targets M33"
echo "### Worst-case stack per public call (bytes)"
echo
"$PY" - "$ROOT" "$W" "$targets" $CONFIGS << 'EOF'
import glob, os, re, sys
root, work, targets, configs = sys.argv[1], sys.argv[2], sys.argv[3].split(), sys.argv[4:]
node_re = re.compile(r'node: \{ title: "([^"]*)" label: "([^"]*)"')
edge_re = re.compile(r'edge: \{ sourcename: "([^"]*)" targetname: "([^"]*)"(?: label: "([^"]*)")?')
comment_re = re.compile(r'/\*.*?\*/|//[^\n]*', re.S)
def short(title):
return title.rsplit(':', 1)[-1]
def address_taken(stack):
"""functions named in the library sources other than in a call or declaration: the targets an indirect call
may reach, for a static function only in its own file"""
text = {}
for f in glob.glob(os.path.join(root, 'src', '**', '*.[ch]'), recursive=True):
text[os.path.realpath(f)] = comment_re.sub(' ', open(f).read())
out = set()
for t in stack:
name = short(t)
files = [os.path.realpath(t.rsplit(':', 1)[0])] if ':' in t else list(text)
pat = re.compile(r'(?<![.>\w])%s\b(?!\s*\()' % re.escape(name))
if any(pat.search(text.get(f, '')) for f in files):
out.add(t)
return out
def load(build):
"""call graph of the library's objects: {fn: bytes}, {fn: [callees]}, flags, unresolved indirect calls"""
stack, calls, flag, src_lines, where_def = {}, {}, {}, {}, {}
for ci in glob.glob(os.path.join(build, 'CMakeFiles', '*', 'src', '**', '*.ci'), recursive=True):
for line in open(ci):
m = node_re.match(line)
if m:
parts = m.group(2).split('\\n')
if len(parts) > 2:
n, kind = re.match(r'(\d+) bytes \((.*)\)', parts[2]).groups()
t = m.group(1)
stack[t] = max(stack.get(t, 0), int(n))
where_def[t] = parts[1].rsplit(':', 2)[0]
if kind == 'dynamic':
flag[t] = 'unbounded'
calls.setdefault(t, set())
continue
m = edge_re.match(line)
if m:
src, dst, where = m.groups()
if dst == '__indirect_call':
dst = 'indirect@' + (where or '?')
calls.setdefault(src, set()).add(dst)
by_short = {}
for t in stack:
by_short.setdefault(short(t), []).append(t)
taken = address_taken(stack)
unresolved = set()
for src in list(calls):
out = set()
for dst in calls[src]:
if dst.startswith('indirect@'):
f, l = dst[len('indirect@'):].rsplit(':', 2)[:2]
text = src_lines.setdefault(f, open(f).read().split('\n') if os.path.exists(f) else [])
text = text[int(l) - 1] if int(l) <= len(text) else ''
if 'XOMBE_TAP' in text:
continue # test tap callback, runs on the caller's own stack
if taken:
out.update(taken)
else:
unresolved.add('%s:%s' % (os.path.relpath(f, root), l))
elif dst in stack:
out.add(dst)
elif dst in by_short and len(by_short[dst]) == 1:
out.add(by_short[dst][0])
# otherwise a library outside xombe (libc, libm), not counted
calls[src] = out
return stack, calls, flag, unresolved, taken, where_def
def worst(fn, stack, calls, memo, path):
if fn in path:
return None # recursion
if fn in memo:
return memo[fn]
path.add(fn)
best = 0
for c in calls.get(fn, ()):
w = worst(c, stack, calls, memo, path)
if w is None:
path.discard(fn)
return None
best = max(best, w)
path.discard(fn)
memo[fn] = stack.get(fn, 0) + best
return memo[fn]
cols, notes = [], []
for t in targets:
for c in configs:
k, ds = c.split(':')
b = os.path.join(work, '%s-%s-%s' % ('host' if t == 'x86-64' else 'm33', k, ds))
stack, calls, flag, unresolved, taken, where_def = load(b)
memo, res = {}, {}
for fn in stack:
if fn.startswith('xombe_') and not fn.startswith('xombe__') and ':' not in fn:
w = worst(fn, stack, calls, memo, set())
res[fn] = 'recursive' if w is None else str(w)
if ds == 'ON':
# the DMR-only encoder never enters src/dstar: the same walk without those functions
dsdir = os.path.join(os.path.realpath(root), 'src', 'dstar') + os.sep
amb = {f: {c for c in cs if not os.path.realpath(where_def.get(c, '')).startswith(dsdir)}
for f, cs in calls.items()}
for fn in ('xombe_enc_frame', 'xombe_enc_frame_bits'):
if fn in stack:
w = worst(fn, stack, amb, {}, set())
res[fn + ', DMR output only'] = 'recursive' if w is None else str(w)
cols.append(('%s %s D-STAR %s' % (t, k, ds.lower()), res))
if unresolved:
notes.append('%s %s D-STAR %s: unresolved indirect calls at %s' % (t, k, ds.lower(),
', '.join(sorted(unresolved))))
notes.append('%s %s D-STAR %s: indirect calls bounded by %s' % (t, k, ds.lower(),
', '.join(sorted(map(short, taken)))))
if flag:
notes.append('%s %s D-STAR %s: unbounded dynamic stack in %s' % (t, k, ds.lower(),
', '.join(sorted(flag))))
names = sorted(set().union(*[set(r) for _, r in cols]))
print('| call | ' + ' | '.join(c for c, _ in cols) + ' |')
print('|---|' + '---|' * len(cols))
for n in names:
fn, _, what = n.partition(', ')
print('| `%s`%s | ' % (fn, ' (%s)' % what if what else '') + ' | '.join(r.get(n, '-') for _, r in cols) + ' |')
print()
print('stack of libc and libm callees not included, test tap callbacks not included')
for n in notes:
print(n)
EOF
+99
View File
@@ -0,0 +1,99 @@
#include "bits.h"
#include "xombe.h"
static const uint8_t b0_bits[] = {0, 1, 2, 3, 37, 38, 39};
static const uint8_t b1_bits[] = {4, 5, 6, 7, 35};
static const uint8_t b2_bits[] = {8, 9, 10, 11, 36};
static const uint8_t b3_bits[] = {12, 13, 14, 15, 16, 17, 18, 19, 43};
static const uint8_t b4_bits[] = {20, 21, 22, 23, 40, 41, 42};
static const uint8_t b5_bits[] = {24, 25, 26, 27, 44};
static const uint8_t b6_bits[] = {28, 29, 30, 45};
static const uint8_t b7_bits[] = {31, 32, 33, 46};
static const uint8_t b8_bits[] = {34, 47, 48};
static const uint8_t *const field_bits[9] = {b0_bits, b1_bits, b2_bits, b3_bits, b4_bits,
b5_bits, b6_bits, b7_bits, b8_bits};
static const uint8_t field_width[9] = {7, 5, 5, 9, 7, 5, 4, 4, 3};
void xombe__unpack_bits(const uint8_t *bytes, int count, uint8_t *bits)
{
int i;
for (i = 0; i < count; i++)
bits[i] = (uint8_t)((bytes[i >> 3] >> (7 - (i & 7))) & 1);
}
void xombe__pack_bits(const uint8_t *bits, int count, uint8_t *bytes)
{
int i;
for (i = 0; i < (count + 7) / 8; i++)
bytes[i] = 0;
for (i = 0; i < count; i++)
if (bits[i])
bytes[i >> 3] |= (uint8_t)(0x80 >> (i & 7));
}
void xombe__unpack49(const uint8_t bytes[7], uint8_t d[49])
{
xombe__unpack_bits(bytes, 49, d);
}
void xombe__pack49(const uint8_t d[49], uint8_t bytes[7])
{
xombe__pack_bits(d, 49, bytes);
}
int xombe__popcount32(uint32_t v)
{
int n = 0;
for (; v; v &= v - 1)
n++;
return n;
}
int xombe__get_bits(const uint8_t *d, int first, int count)
{
int v = 0, i;
for (i = 0; i < count; i++)
v = (v << 1) | d[first + i];
return v;
}
void xombe__put_bits(uint8_t *d, int first, int count, int value)
{
int i;
for (i = 0; i < count; i++)
d[first + i] = (uint8_t)((value >> (count - 1 - i)) & 1);
}
int xombe__frame_class(const uint8_t d[49])
{
int c = xombe__get_bits(d, 0, 6);
if (c < 60)
return XOMBE_CLASS_VOICE;
if (c < 62)
return XOMBE_CLASS_ERASURE;
if (c == 62)
return XOMBE_CLASS_SILENCE;
return XOMBE_CLASS_TONE;
}
void xombe__get_fields(const uint8_t d[49], int b[9])
{
int f, i;
for (f = 0; f < 9; f++) {
int v = 0;
for (i = 0; i < field_width[f]; i++)
v = (v << 1) | d[field_bits[f][i]];
b[f] = v;
}
}
void xombe__put_fields(const int b[9], uint8_t d[49])
{
int f, i;
for (f = 0; f < 9; f++) {
int w = field_width[f];
for (i = 0; i < w; i++)
d[field_bits[f][i]] = (uint8_t)((b[f] >> (w - 1 - i)) & 1);
}
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef XOMBE_BITS_H
#define XOMBE_BITS_H
#include <stdint.h>
/* one bit per byte <-> packed MSB first */
void xombe__unpack_bits(const uint8_t *bytes, int count, uint8_t *bits);
void xombe__pack_bits(const uint8_t *bits, int count, uint8_t *bytes);
void xombe__unpack49(const uint8_t bytes[7], uint8_t d[49]);
void xombe__pack49(const uint8_t d[49], uint8_t bytes[7]);
int xombe__popcount32(uint32_t v);
int xombe__frame_class(const uint8_t d[49]);
void xombe__get_fields(const uint8_t d[49], int b[9]);
void xombe__put_fields(const int b[9], uint8_t d[49]);
/* count <= 24 bits starting at d[first], MSB first */
int xombe__get_bits(const uint8_t *d, int first, int count);
void xombe__put_bits(uint8_t *d, int first, int count, int value);
#endif
+31
View File
@@ -0,0 +1,31 @@
#ifndef XOMBE_CONSTS_H
#define XOMBE_CONSTS_H
#define XOMBE_FS 8000.0f
/* Hz -> cycles/sample, the unit of every frequency (f0 = 1/period) but the tone tables and tone detector */
#define XOMBE_HZ(f) ((f) / XOMBE_FS)
#define XOMBE_DB(db) ((db) / 3.01029996f) /* dB -> log2 power units */
/* 8 voicing bands of 500 Hz, 16 = 8000/500 per cycle/sample, so the band of f is floor(16*f), exact in binary */
#define XOMBE_BANDS_PER_UNIT 16.0f
/* decoder boosts harmonics above this by f/XOMBE_HF_CORNER, encoder targets pre-compensate half of that */
#define XOMBE_HF_CORNER XOMBE_HZ(2400.0f)
#define XOMBE_RHO 0.65f
#define XOMBE_AMP_MIN (-15.0f)
#define XOMBE_AMP_MAX (15.0f - 1.0f / 2048.0f)
#define XOMBE_GAIN_MAX 13.0f
#define XOMBE_SILENCE_F0 0.031324f
#define XOMBE_SILENCE_L 15
#define XOMBE_SILENCE_GAIN_OFFSET 2.0f
#define XOMBE_PULSE_F0 (64.346f / 8000.0f)
#define XOMBE_PULSE_L 56
#define XOMBE_PULSE_B1_MIN 18
#define XOMBE_SILENCE_B0 124
#define XOMBE_SILENCE_B1 16
/* AMBE+2 silence frame, 7 bytes as xombe_dec_frame takes them */
#define XOMBE_SILENCE_FRAME {0xF8, 0x01, 0xA9, 0x9F, 0x8C, 0xE0, 0x80}
#define XOMBE_UNVOICED_B1 16
#define XOMBE_PI 3.14159265358979323846
#define XOMBE_PI_F 3.14159265f
#define XOMBE_LOG2_10 3.32192809f
#endif
File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
#ifndef XOMBE_CQUANT_H
#define XOMBE_CQUANT_H
/* weighted closed-loop spectral-amplitude quantizer (b2..b8) in float32, on either table set
model (params.h): a = clip((Tv - mean Tv) + base + G), base = rho*(Pt - mean Pt) - 1/2 log2 L,
G = min(dg[b2] + grho*Gprev, gmax), Tv = A3*prba24[b3] + A4*prba58[b4] + sum_k H_k*hoc_k[b5+k], matrices per L
search, all errors weighted by w and mean-removed:
1. HOC open loop (nearest in the block-DCT domain), then up to iters rounds of the best (b3, b4) pair over
all 512 x 128 given HOC, then HOC per block given the pair (two passes)
2. the best n_pairs pairs given that HOC, each with its own HOC search and the n_gain gains nearest the
weighted continuous gain, scored by the exact clipped reconstruction
entries an ok mask marks unusable are skipped. the search clips to [-15, 15] for both sets, not to amax
with ws->cap > 0 a pair search stops after cap units of work (a pair 1, a row 4), keeping the best pairs so
far. its lowest-bound row always completes, the others run in ascending bound order, so a search takes at
most max(cap + 4, 132) units. cap 0 is exact
arrays are indexed 1..L (0 unused), fields come back in b[2..8] */
#include "../internal.h"
#if XOMBE_KERNELS_Q15
#include "../tables/cq_q15_tables.h"
#endif
#define XOMBE_CQ_MAX_PAIRS 8
#define XOMBE_CQ_MAX_GAIN 8
#define XOMBE_CQ_HOC_ROWS 72 /* sum of the HOC row counts, AMBE+2's 32 + 16 + 16 + 8 */
#define XOMBE_CQ_J_MAX 17 /* longest spectral block */
#define XOMBE_CQ_AMAX 15.0f /* search's upper clip, both sets */
#define XOMBE_CQ_CAP 1250 /* encoder and transcoder ws.cap */
/* encoder and transcoder settings: weights gamma and floor, then n_pairs, n_gain, iters, and clip_passes */
#define XOMBE_CQ_QWEIGHT 0.5f
#define XOMBE_CQ_WEIGHT_FLOOR 0.05f
#define XOMBE_CQ_N_PAIRS 4
#define XOMBE_CQ_N_GAIN 3
#define XOMBE_CQ_ITERS 2
#define XOMBE_CQ_CLIP_PASSES 2
#if XOMBE_KERNELS_Q15
/* q15 kernels: the same search with the pair-search bounds in int16 SIMD against the codebook images
(cq_q15_tables.h) and the HOC errors as quadratic forms, every bound lowered by its proven rounding error, so
pruning still never excludes a pair the exhaustive search keeps. pair errors and the final scoring stay float.
about 12 KB, keep it off the stack on small targets. zero it before first use, xombe__cq_prepare keeps the
maps of L across calls with the same set and L */
typedef struct {
const xombe_amp_tables *ts;
const xombe_cq_q15_tab *qt; /* ts's images, NULL: exhaustive pair search */
int L;
int pos[4], J[4], M[4]; /* block k: harmonics pos..pos+J-1, M = min(J, 6) */
float w[XOMBE_LMAX + 1], sw; /* weights, sw = sum w */
float b1[XOMBE_LMAX + 1]; /* Tv's map from (G2..G8) at harmonic l of block k: c0[k] + b1[l] c1[k] */
float c0[4][7], c1[4][7];
float mu[7]; /* weighted column means of that map */
float Q[7][7]; /* (A - mean)^T W (A - mean) */
float H[XOMBE_LMAX + 1][4]; /* HOC synthesis: 2cos(pi m (i + 1/2)/J), m = 2..M-1, block-local i */
float hq[XOMBE_CQ_HOC_ROWS]; /* every HOC row c: c^T H^T W H c, over its block */
float hl[XOMBE_CQ_HOC_ROWS]; /* and c*H^T w */
int hoc_off[4]; /* block k's first row in hq, hl */
float e4q[128]; /* prba58 rows' quadratic terms x4^T Q44 x4 */
float e4[128]; /* e4 of the current pair search */
/* pair-search bounds (prba_pairs), integers v stand for v * 2^-exponent */
int chol_ok; /* 0: Q44 not safely positive definite, or no images: exhaustive */
float Lc[4][4]; /* Q44 = Lc Lc^T */
float Mz[4][3]; /* Lc^-1 Q43 */
float dir[4], pmax; /* principal direction of the rows p = Lc^T x4, max |p| */
float ps[128]; /* usable rows' projections dir*p, ascending */
short pord[128]; /* their prba58 rows */
int n4; /* their count */
int col_ok; /* the column bound (roles swapped) is available */
float L3[3][3], M3[3][4]; /* Q33 = L3 L3^T, M3 = L3^-1 Q34 */
int32_t sq4[128]; /* per prba58 row: x4^T(Q44 - M3^T M3)x4 at 2^-sq4_x, |.| <= 2^29 */
int sq4_x;
float sq4_d, mw4, n4max; /* its error bound, rounding magnitude, max |x4| */
float colb[128]; /* per prba58 row: bound S' - slack in the current search */
float fps[128]; /* columns left after the first row, in projection order */
short ford[128];
int32_t sq[512]; /* per prba24 row: x3^T(Q33 - Mz^T Mz)x3 at 2^-sq_x, |.| <= 2^29 */
int sq_x;
float sq_d, mw, n3max; /* its error bound, rounding magnitude, max |x3| */
int32_t sb[512]; /* per prba24 row: bound S - slack = sb * sb_s - sb_k, INT32_MAX unusable */
float sb_s, sb_k;
int32_t dz[512]; /* per prba24 row: dir*(Mz x3) = dz * dz_s within dz_e */
float dz_s, dz_e;
int brute; /* 1: no pruning in the pair search (testing) */
int cap; /* pair-search cap in units, 0: none (set after zeroing) */
int work; /* most units a pair search took since xombe__cq_prepare */
} xombe_cq_ws;
#else
/* one search's workspace: per-L maps, w-only terms, and HOC candidates, filled by xombe__cq_prepare
about 19 KB, keep it off the stack on small targets. zero it before first use, xombe__cq_prepare keeps the
maps of L across calls with the same set and L */
typedef struct {
const xombe_amp_tables *ts;
int L;
int pos[4], J[4], M[4];
float w[XOMBE_LMAX + 1], sw;
float A[XOMBE_LMAX + 1][7]; /* Tv's linear map from (G2..G8) = (prba24, prba58) */
float Wm[XOMBE_LMAX + 1][7]; /* w*(A - weighted column mean) */
float Q[7][7];
float H[XOMBE_LMAX + 1][4];
float hv[XOMBE_CQ_HOC_ROWS * XOMBE_CQ_J_MAX]; /* every HOC row's block values (H_k @ hoc_k[n]) */
int hv_off[4];
float e4q[128];
float e4[128];
int chol_ok;
float Lc[4][4];
float Mz[4][3];
float dir[4], pmax;
float ps[128];
short pord[128];
int n4;
int col_ok;
float L3[3][3], M3[3][4];
float sq4[128], mw4, n4max;
float colb[128];
float fps[128];
short ford[128];
float sq[512], mw, n3max;
float sb[512];
float dz[512];
int brute;
int cap;
int work;
} xombe_cq_ws;
#endif
typedef struct {
int b[9]; /* b[2..8] */
float err; /* sum w (a - clip(target))^2, a the search's clipped reconstruction */
float u[XOMBE_LMAX + 1]; /* winner's unclipped reconstruction */
} xombe_cq_result;
/* w[l] = max(2^(gamma (t[l] - max t)), floor), l = 1..L */
void xombe__cq_amp_weights(const float *target, int L, float gamma, float floor_, float *w);
/* fills the workspace for set ts, L harmonics, and weights w[1..L] (NULL: unweighted) */
void xombe__cq_prepare(xombe_cq_ws *ws, const xombe_amp_tables *ts, int L, const float *w);
/* closed-loop search on a prepared workspace: residual r = target - rho(Pt - mean Pt), clipped target,
base = rho(Pt - mean Pt) - 1/2 log2 L, previous gain Gprev
n_pairs <= XOMBE_CQ_MAX_PAIRS, n_gain <= XOMBE_CQ_MAX_GAIN */
void xombe__cq_closed(xombe_cq_ws *ws, const float *r, const float *target, const float *base, float Gprev,
int n_pairs, int n_gain, int iters, xombe_cq_result *res);
/* quantizes target[1..L] (clipped here to [-15, XOMBE_CQ_AMAX]) on set ts against prediction pt[1..L]
(xombe__predict_from of the memory) and its gain Gprev. closed 0 is open loop, res->err and res->u unset */
void xombe__cq_quantize(xombe_cq_ws *ws, const xombe_amp_tables *ts, const float *target, int L, const float *pt,
float Gprev, const float *w, int closed, int n_pairs, int n_gain, int iters, int clip_passes,
xombe_cq_result *res);
#if XOMBE_HAVE_ENCODER
/* closed-loop search on the AMBE+2 set against predictor pi vs the encoder's open-loop choice (xombe__quantize),
closed wins unless open's weighted error against the decoder's reconstruction is smaller, ties go closed
target clipped to [-15, 15 - 2^-11]. returns 1 if the open-loop choice won, res->b holds the pick, res->err
its error (the closed search's own for a closed pick), bclosed/bopen (b[2..8]) may be NULL */
int xombe__cq_search_ambe2(xombe_cq_ws *ws, const xombe_pred *pi, const float *target, int L, const float *w,
int n_pairs, int n_gain, xombe_cq_result *res, int *bclosed, int *bopen);
#endif
#endif
+223
View File
@@ -0,0 +1,223 @@
#include <math.h>
#include <string.h>
#include "params.h"
#include "consts.h"
#include "../tables/tables.h"
#include "../tables/dsp_tables.h"
const xombe_amp_tables xombe__amp_ambe2 = {
xombe__dg, 32, xombe__prba24, 512, xombe__prba58, 128,
{&xombe__hoc5[0][0], &xombe__hoc6[0][0], &xombe__hoc7[0][0], &xombe__hoc8[0][0]}, {32, 16, 16, 8},
xombe__blk, 0, 0, 0, {0, 0, 0, 0},
XOMBE_RHO, 0.5f, XOMBE_GAIN_MAX, XOMBE_AMP_MIN, XOMBE_AMP_MAX};
float xombe__clamp_amp(float a)
{
if (a < XOMBE_AMP_MIN)
return XOMBE_AMP_MIN;
if (a > XOMBE_AMP_MAX)
return XOMBE_AMP_MAX;
return a;
}
float xombe__hf_tilt(float f)
{
return f > XOMBE_HF_CORNER ? log2f(f / XOMBE_HF_CORNER) : 0.0f;
}
/* L = floor(0.4627/f0): harmonics below about 3.7 kHz, clamped to 9..XOMBE_LMAX */
#define L_SCALE 0.4627f
#define L_MIN 9
int xombe__L_from_f0(float f0)
{
int L = (int)floorf(L_SCALE / f0);
if (L < L_MIN)
L = L_MIN;
if (L > XOMBE_LMAX)
L = XOMBE_LMAX;
return L;
}
int xombe__nearest_row(const float *tab, int rows, int stride, int used, const float *t, const unsigned char *mask)
{
float best = 0.0f;
int j, m, bi = 0, found = 0;
for (j = 0; j < rows; j++) {
float d = 0.0f;
if (mask && !mask[j])
continue;
for (m = 0; m < used; m++) {
float e = tab[j * stride + m] - t[m];
d += e * e;
}
if (!found || d < best) {
found = 1;
best = d;
bi = j;
}
}
return bi;
}
void xombe__pred_init(xombe_pred *pi)
{
memset(pi, 0, sizeof(*pi));
pi->cls = XOMBE_CLASS_VOICE;
pi->L = XOMBE_SILENCE_L;
pi->f0 = XOMBE_SILENCE_F0;
}
float xombe__harmonic_lerp(const float a[XOMBE_LMAX + 1], int i, float f)
{
if (i < 1)
return a[1];
if (i >= XOMBE_LMAX)
return a[XOMBE_LMAX];
return (1.0f - f) * a[i] + f * a[i + 1];
}
void xombe__predict(const xombe_pred *pi, int L, float pt[XOMBE_LMAX + 1])
{
xombe__predict_from(pi->L, pi->a, L, pt);
}
void xombe__predict_from(int Lp, const float ap[XOMBE_LMAX + 1], int L, float pt[XOMBE_LMAX + 1])
{
int l;
pt[0] = 0.0f;
for (l = 1; l <= L; l++) {
/* harmonic l maps to l*Lp/L of the previous frame, split exactly into i + num % L / L */
int num = l * Lp;
int i = num / L;
float f = (float)(num % L) / (float)L;
/* i reaches XOMBE_LMAX only for l = L with Lp = XOMBE_LMAX, so f = 0 and a[XOMBE_LMAX] is in bounds */
pt[l] = xombe__harmonic_lerp(ap, i, f);
}
}
const float *xombe__hoc_table(int k, int *rows)
{
*rows = xombe__amp_ambe2.n_hoc[k];
return xombe__amp_ambe2.hoc[k];
}
void xombe__spectral_shape(const int b[9], int L, float t[XOMBE_LMAX + 1])
{
xombe__spectral_shape_ts(&xombe__amp_ambe2, b, L, t);
}
void xombe__spectral_shape_ts(const xombe_amp_tables *ts, const int b[9], int L, float t[XOMBE_LMAX + 1])
{
float g[9], r[8];
int i, m, k, pos = 1;
g[1] = 0.0f;
for (m = 0; m < 3; m++)
g[2 + m] = ts->prba24[b[3]][m];
for (m = 0; m < 4; m++)
g[5 + m] = ts->prba58[b[4]][m];
for (i = 0; i < 8; i++) {
float s = 0.0f;
for (m = 1; m <= 8; m++)
s += (m == 1 ? 1.0f : 2.0f) * g[m] * xombe__dct8[m - 1][i];
r[i] = s;
}
for (k = 0; k < 4; k++) {
int J = ts->blk[L][k];
int top = J < 6 ? J : 6;
float c[7];
const float *hoc = ts->hoc[k] + 4 * b[5 + k];
const float *kern = xombe__dct_blk + xombe__dct_blk_off[J];
c[1] = (r[2 * k] + r[2 * k + 1]) * 0.5f;
c[2] = (r[2 * k] - r[2 * k + 1]) * 0.35355339f; /* 1/(2*sqrt 2) */
for (m = 3; m <= 6; m++)
c[m] = m <= top ? hoc[m - 3] : 0.0f;
for (i = 0; i < J; i++) {
float s = 0.0f;
for (m = 2; m <= top; m++)
s += c[m] * kern[(m - 1) * J + i];
t[pos++] = c[1] + 2.0f * s;
}
}
t[0] = 0.0f;
}
void xombe__assemble(const float t[XOMBE_LMAX + 1], const float pt[XOMBE_LMAX + 1], int L, float gamma,
float a[XOMBE_LMAX + 1])
{
xombe__assemble_ts(&xombe__amp_ambe2, t, pt, L, gamma, a);
}
void xombe__assemble_ts(const xombe_amp_tables *ts, const float t[XOMBE_LMAX + 1], const float pt[XOMBE_LMAX + 1],
int L, float gamma, float a[XOMBE_LMAX + 1])
{
float mt = 0.0f, mp = 0.0f, off;
int l;
for (l = 1; l <= L; l++) {
mt += t[l];
mp += pt[l];
}
mt /= (float)L;
mp /= (float)L;
off = gamma - xombe__half_log2[L];
a[0] = 0.0f;
for (l = 1; l <= L; l++) {
float v = (t[l] - mt) + ts->rho * (pt[l] - mp) + off;
a[l] = v < ts->amin ? ts->amin : v > ts->amax ? ts->amax : v;
}
for (l = L + 1; l <= XOMBE_LMAX; l++)
a[l] = a[L];
}
float xombe__gain_ts(const xombe_amp_tables *ts, int b2, float Gprev)
{
float G = ts->dg[b2] + ts->grho * Gprev;
return G < ts->gmax ? G : ts->gmax;
}
float xombe__gain(int b2, float prev_gamma, int silence)
{
const xombe_amp_tables *ts = &xombe__amp_ambe2;
float g = ts->dg[b2] + ts->grho * prev_gamma - (silence ? XOMBE_SILENCE_GAIN_OFFSET : 0.0f);
return g < ts->gmax ? g : ts->gmax;
}
void xombe__dequant(const int b[9], const xombe_pred *pi, int silence, xombe_params *out)
{
float t[XOMBE_LMAX + 1], pt[XOMBE_LMAX + 1];
out->pulse = 0;
if (silence) {
out->f0 = XOMBE_SILENCE_F0;
out->L = XOMBE_SILENCE_L;
} else if (b[1] >= XOMBE_PULSE_B1_MIN) {
out->pulse = 1;
out->f0 = XOMBE_PULSE_F0;
out->L = XOMBE_PULSE_L;
} else {
out->f0 = xombe__w0[b[0]];
out->L = xombe__lt[b[0]];
}
out->gamma = xombe__gain(b[2], pi->gamma, silence);
xombe__spectral_shape(b, out->L, t);
xombe__predict(pi, out->L, pt);
xombe__assemble(t, pt, out->L, out->gamma, out->a);
}
void xombe__pred_store_voice(xombe_pred *pi, const xombe_params *p, const uint8_t v2[8])
{
int l;
pi->cls = XOMBE_CLASS_VOICE;
pi->L = p->L;
pi->f0 = p->f0;
pi->gamma = p->gamma;
for (l = 0; l <= XOMBE_LMAX; l++)
pi->a[l] = l <= p->L ? p->a[l] : p->a[p->L];
memcpy(pi->v2, v2, 8);
}
void xombe__pred_store_other(xombe_pred *pi, int cls)
{
pi->cls = cls;
memset(pi->v2, 0, 8);
}
+71
View File
@@ -0,0 +1,71 @@
#ifndef XOMBE_PARAMS_H
#define XOMBE_PARAMS_H
#include "../state.h"
/* spectral-amplitude tables and constants of one codec, AMBE+2 (xombe__amp_ambe2) or D-STAR (xombe__amp_dstar)
t = block-DCT spectral shape of b3..b8 (xombe__spectral_shape_ts), harmonics 1..L
G = min(dg[b2] + grho*G_prev, gmax)
a = clamp((t - mean t) + rho*(pt - mean pt) + G - 1/2 log2 L, amin, amax), pt = prediction from the previous frame
ok_* mark entries the closed-loop quantizer may pick (1) and unfitted ones it skips (0), NULL means all */
typedef struct {
const float *dg;
int n_dg;
const float (*prba24)[3];
int n_prba24;
const float (*prba58)[4];
int n_prba58;
const float *hoc[4]; /* b5..b8: rows of 4 floats, the first min(J, 6) - 2 used */
int n_hoc[4];
const unsigned char (*blk)[4]; /* block lengths J per L, [57][4] */
const unsigned char *ok_dg, *ok_prba24, *ok_prba58, *ok_hoc[4];
float rho, grho, gmax, amin, amax;
} xombe_amp_tables;
extern const xombe_amp_tables xombe__amp_ambe2;
typedef struct {
int L;
int pulse;
float f0;
float gamma;
float a[XOMBE_LMAX + 1];
} xombe_params;
/* log amplitude of harmonics with no component (tone sets' other harmonics), synthesizes as 0 */
#define XOMBE_AMP_OFF (-1000.0f)
float xombe__clamp_amp(float a);
/* decoder's high-frequency boost: log2(f/XOMBE_HF_CORNER) above the corner, else 0 */
float xombe__hf_tilt(float f);
int xombe__L_from_f0(float f0);
/* row of tab (rows x stride floats) nearest t[0..used) in squared error, first on ties, rows with mask[j] 0
skipped (mask NULL: none), 0 if every row is */
int xombe__nearest_row(const float *tab, int rows, int stride, int used, const float *t, const unsigned char *mask);
void xombe__pred_init(xombe_pred *pi);
/* (1 - f)*a[i] + f*a[i + 1] over log amplitudes a[1..XOMBE_LMAX], holding a[1] below harmonic 1 and
a[XOMBE_LMAX] from harmonic XOMBE_LMAX up */
float xombe__harmonic_lerp(const float a[XOMBE_LMAX + 1], int i, float f);
void xombe__predict(const xombe_pred *pi, int L, float pt[XOMBE_LMAX + 1]);
/* prediction pt[1..L] from a previous frame of Lp harmonics, ap[1..XOMBE_LMAX] extended past Lp */
void xombe__predict_from(int Lp, const float ap[XOMBE_LMAX + 1], int L, float pt[XOMBE_LMAX + 1]);
/* HOC codebook of block k (b5..b8) and its row count, rows of 4 floats, bound to the AMBE+2 tables */
const float *xombe__hoc_table(int k, int *rows);
/* xombe__spectral_shape_ts bound to the AMBE+2 tables */
void xombe__spectral_shape(const int b[9], int L, float t[XOMBE_LMAX + 1]);
void xombe__spectral_shape_ts(const xombe_amp_tables *ts, const int b[9], int L, float t[XOMBE_LMAX + 1]);
/* xombe__assemble_ts bound to the AMBE+2 tables */
void xombe__assemble(const float t[XOMBE_LMAX + 1], const float pt[XOMBE_LMAX + 1], int L, float gamma,
float a[XOMBE_LMAX + 1]);
/* a[1..L] by the xombe_amp_tables model on set ts, a[L + 1..XOMBE_LMAX] = a[L] */
void xombe__assemble_ts(const xombe_amp_tables *ts, const float t[XOMBE_LMAX + 1], const float pt[XOMBE_LMAX + 1],
int L, float gamma, float a[XOMBE_LMAX + 1]);
/* G = min(dg[b2] + grho*Gprev, gmax) on set ts */
float xombe__gain_ts(const xombe_amp_tables *ts, int b2, float Gprev);
/* AMBE+2 gain, as xombe__gain_ts but a silence frame takes off XOMBE_SILENCE_GAIN_OFFSET before the cap */
float xombe__gain(int b2, float prev_gamma, int silence);
void xombe__dequant(const int b[9], const xombe_pred *pi, int silence, xombe_params *out);
void xombe__pred_store_voice(xombe_pred *pi, const xombe_params *p, const uint8_t v2[8]);
void xombe__pred_store_other(xombe_pred *pi, int cls);
#endif
+30
View File
@@ -0,0 +1,30 @@
#ifndef XOMBE_PROF_H
#define XOMBE_PROF_H
/* encoder stage cycles for a Cortex-M bench (-DXOMBE_PROF_DWT): XOMBE_PF(k, stmt) runs stmt and adds its DWT
cycles to xombe__pf[k], without XOMBE_PROF_DWT it runs stmt alone
stages: 0 push, 1 analyze, 2 AMBE+2 voicing, 3 D-STAR voicing, 4 background, 5 AMBE+2 emit, 6 D-STAR emit,
7 D-STAR tone push
nested: 8 front end voicing and 9 voicing metric in 3, 10 AMBE+2 tone detector in 1, 11 detection and
12 tone-in-noise pass in 7, 13 D-STAR quantizer, 14 D-STAR targets in 6
15 sums L over the D-STAR quantizer calls */
#ifdef XOMBE_PROF_DWT
extern unsigned long xombe__pf[16];
#define XOMBE_PF_NOW() (*(volatile unsigned long *)0xE0001004u) /* DWT_CYCCNT, counter enabled by the caller */
#define XOMBE_PF(k, ...) \
do { \
unsigned long xombe_pf_t0 = XOMBE_PF_NOW(); \
__VA_ARGS__; \
xombe__pf[k] += XOMBE_PF_NOW() - xombe_pf_t0; \
} while (0)
#define XOMBE_PF_ADD(k, n) (xombe__pf[k] += (unsigned long)(n))
#else
#define XOMBE_PF(k, ...) \
do { \
__VA_ARGS__; \
} while (0)
#define XOMBE_PF_ADD(k, n) ((void)0)
#endif
#endif
+137
View File
@@ -0,0 +1,137 @@
#include <math.h>
#include "tone_table.h"
#include "bits.h"
#include "../state.h"
#if XOMBE_HAVE_DSTAR
#include "../dstar/dstar_internal.h"
#endif
/* single tones synthesize as harmonic l1 of an f0 at most this */
#define SINGLE_F0_MAX_HZ 250.0f
#define DUAL_FIRST XOMBE_TONE_DUAL_FIRST
#define DUAL_IDS XOMBE_TONE_DUALS
/* dual tones 128..163 by id - 128, low and high frequencies in Hz
DTMF 128..143 and call progress 160..162: DVSI AMBE-3000R Vocoder Chip Users Manual, Table 103
Knox 144..159 and call progress 163: US 7,970,606 B2, Table 1 ("MBE tone parameters") */
static const short dual_low[DUAL_IDS] = {941, 697, 697, 697, 770, 770, 770, 852, 852, 852, 697, 770,
852, 941, 941, 941, 820, 606, 606, 606, 672, 672, 672, 743,
743, 743, 606, 672, 743, 820, 820, 820, 350, 440, 480, 350};
static const short dual_high[DUAL_IDS] = {1336, 1209, 1336, 1477, 1209, 1336, 1477, 1209, 1336, 1477, 1633, 1633,
1633, 1633, 1209, 1477, 1162, 1052, 1162, 1297, 1052, 1162, 1297, 1052,
1162, 1297, 1430, 1430, 1430, 1430, 1052, 1297, 440, 480, 620, 490};
/* f0 (Hz) and harmonic numbers l1 < l2 synthesizing each dual tone, US 7,970,606 B2, Table 1 */
static const float dual_f0[DUAL_IDS] = {
/* 128..143, DTMF */
78.50f, 173.48f, 70.0f, 87.0f, 109.95f, 191.68f, 70.17f, 71.06f, 121.58f, 212.0f, 116.41f, 96.15f,
71.0f, 234.26f, 134.38f, 134.35f,
/* 144..159, Knox */
68.33f, 150.89f, 67.82f, 86.50f, 95.79f, 166.92f, 67.70f, 74.74f, 105.90f, 92.78f, 101.55f, 84.02f,
67.83f, 102.30f, 117.0f, 117.49f,
/* 160..163, call progress */
87.78f, 70.83f, 122.0f, 70.0f};
static const unsigned char dual_l[DUAL_IDS][2] = {
{12, 17}, {4, 7}, {10, 19}, {8, 17}, {7, 11}, {4, 7}, {11, 21}, {12, 17},
{7, 11}, {4, 7}, {6, 14}, {8, 17}, {12, 23}, {4, 7}, {7, 9}, {7, 11},
{12, 17}, {4, 7}, {9, 17}, {7, 15}, {7, 11}, {4, 7}, {10, 19}, {10, 14},
{7, 11}, {8, 14}, {6, 14}, {8, 17}, {11, 21}, {8, 14}, {7, 9}, {7, 11},
{4, 5}, {6, 7}, {4, 5}, {5, 7}};
int xombe__tone_id_accepted(int id)
{
return (id >= 5 && id <= 122) || (id >= DUAL_FIRST && id < DUAL_FIRST + DUAL_IDS);
}
int xombe__tone_valid(int id, int ad)
{
return xombe__tone_id_accepted(id) && ad >= 0 && ad <= 127;
}
int xombe__tone_freqs(int id, float *f_low, float *f_high)
{
if (id >= 5 && id <= 122) {
*f_low = *f_high = 31.25f * (float)id;
return 1;
}
if (id >= DUAL_FIRST && id < DUAL_FIRST + DUAL_IDS) {
*f_low = dual_low[id - DUAL_FIRST];
*f_high = dual_high[id - DUAL_FIRST];
return 2;
}
return 0;
}
void xombe__tone_harmonics(int id, float *f0_hz, int *l1, int *l2)
{
float lo, hi;
int kind = xombe__tone_freqs(id, &lo, &hi);
*l1 = *l2 = 0;
*f0_hz = SINGLE_F0_MAX_HZ;
if (kind == 1) {
*l1 = (int)ceilf(lo / SINGLE_F0_MAX_HZ);
*f0_hz = lo / (float)*l1;
} else if (kind == 2) {
*f0_hz = dual_f0[id - DUAL_FIRST];
*l1 = dual_l[id - DUAL_FIRST][0];
*l2 = dual_l[id - DUAL_FIRST][1];
}
}
/* 16384*10^(0.03555*(ad - 127)), in log2 */
#define TONE_LOG2_FULL 14.0f
#define TONE_LOG2_PER_AD 0.118094543f /* 0.03555*log2 10 */
float xombe__tone_log2_amp(int ad)
{
return TONE_LOG2_FULL + TONE_LOG2_PER_AD * (float)(ad - 127);
}
int xombe__tone_frame_parse(const uint8_t d[49], int *id, int *ad)
{
int c[4], i, dist = 0;
for (i = 0; i < 4; i++)
c[i] = xombe__get_bits(d, 12 + 8 * i, 8);
*id = c[0];
*ad = (xombe__get_bits(d, 6, 6) << 1) | d[44];
for (i = 1; i < 4; i++)
dist += xombe__popcount32((uint32_t)(c[0] ^ c[i]));
if ((c[1] >> 4) != (c[0] >> 4) || dist > 5 || !xombe__tone_id_accepted(c[0]))
return 0;
return 1;
}
int xombe__tone_frame_dmr(int id, int ad, uint8_t out[9])
{
uint8_t d[49], bits[7];
if (!xombe__tone_valid(id, ad))
return -1;
xombe__tone_frame_bits(id, ad, d);
xombe__pack49(d, bits);
xombe__fec_encode_dmr(bits, out);
return 0;
}
int xombe__tone_frame_dstar(int id, int ad, uint8_t out[9])
{
#if XOMBE_HAVE_DSTAR
return xombe__ds_tone_frame_id(id, ad, out);
#else
(void)id;
(void)ad;
(void)out;
return -1;
#endif
}
void xombe__tone_frame_bits(int id, int ad, uint8_t d[49])
{
int i;
for (i = 0; i < 49; i++)
d[i] = 0;
xombe__put_bits(d, 0, 6, 63);
xombe__put_bits(d, 6, 6, ad >> 1);
for (i = 0; i < 4; i++)
xombe__put_bits(d, 12 + 8 * i, 8, id);
d[44] = (uint8_t)(ad & 1);
}
+26
View File
@@ -0,0 +1,26 @@
#ifndef XOMBE_TONE_TABLE_H
#define XOMBE_TONE_TABLE_H
#include <stdint.h>
/* tone level ad: amplitude 16384 * 10^(XOMBE_TONE_AD_LOG10 * (ad - 127)) */
#define XOMBE_TONE_AD_LOG10 0.03555f
#define XOMBE_TONE_DB_PER_AD 0.7110f
#define XOMBE_TONE_DUAL_FIRST 128
#define XOMBE_TONE_DUALS 36
#define XOMBE_TONE_KNOX_FIRST 144
#define XOMBE_TONE_KNOX_COUNT 16
int xombe__tone_id_accepted(int id);
/* id accepted and level code ad 0..127, what a public tone request may name */
int xombe__tone_valid(int id, int ad);
int xombe__tone_freqs(int id, float *f_low, float *f_high);
void xombe__tone_harmonics(int id, float *f0_hz, int *l1, int *l2);
/* log2 synthesized amplitude of each tone component for level code ad */
float xombe__tone_log2_amp(int ad);
/* tone frame: class 63, AD in d6..d11 + d44, the ID four times from d12
returns 0 if the copies disagree too much or the ID is not accepted */
int xombe__tone_frame_parse(const uint8_t d[49], int *id, int *ad);
void xombe__tone_frame_bits(int id, int ad, uint8_t d[49]);
#endif
+6
View File
@@ -0,0 +1,6 @@
#include "xombe.h"
int xombe_version(void)
{
return XOMBE_VERSION;
}
+47
View File
@@ -0,0 +1,47 @@
#include "voicing.h"
#include "consts.h"
#include "../state.h"
#include "../tables/tables.h"
void xombe__v2_from_b1(int b1, uint8_t v2[8])
{
int j;
for (j = 0; j < 8; j++)
v2[j] = xombe__vuv[b1][j];
}
void xombe__f3_first_half(const uint8_t v2_prev[8], const uint8_t v2[8], uint8_t v1[8])
{
int j;
for (j = 0; j < 8; j++)
v1[j] = (uint8_t)(v2_prev[j] && v2[j]);
}
static int band_of(float f)
{
int j = (int)(f * XOMBE_BANDS_PER_UNIT);
return j > 7 ? 7 : j;
}
int xombe__voiced_at(const uint8_t vb[8], float f)
{
return vb[band_of(f)] || vb[band_of(f + 0.5f / XOMBE_BANDS_PER_UNIT)];
}
void xombe__harmonic_voicing(const uint8_t vb[8], float f0, int L, uint8_t vh[XOMBE_LMAX + 1])
{
int l;
vh[0] = 0;
for (l = 1; l <= XOMBE_LMAX; l++) {
float f = (float)l * f0;
vh[l] = (uint8_t)(l <= L && xombe__voiced_at(vb, f));
}
}
int xombe__count_voiced(const uint8_t vb[8])
{
int j, n = 0;
for (j = 0; j < 8; j++)
n += vb[j] != 0;
return n;
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef XOMBE_VOICING_H
#define XOMBE_VOICING_H
#include <stdint.h>
#include "../state.h"
void xombe__v2_from_b1(int b1, uint8_t v2[8]);
void xombe__f3_first_half(const uint8_t v2_prev[8], const uint8_t v2[8], uint8_t v1[8]);
/* 1 if the band holding f, or the one half a band higher, is voiced */
int xombe__voiced_at(const uint8_t vb[8], float f);
void xombe__harmonic_voicing(const uint8_t vb[8], float f0, int L, uint8_t vh[XOMBE_LMAX + 1]);
int xombe__count_voiced(const uint8_t vb[8]);
#endif
+15
View File
@@ -0,0 +1,15 @@
#include <limits.h>
#include "../internal.h"
int xombe__conceal_decide(xombe_dec_core *d, int bad, int hb)
{
int last_three_concealed = (d->hist & 7u) == 7u;
int c = XOMBE_CONCEAL_NONE;
if (hb)
c = XOMBE_CONCEAL_MUTE;
else if (bad)
c = last_three_concealed ? XOMBE_CONCEAL_MUTE : XOMBE_CONCEAL_REPEAT;
d->hist = ((d->hist << 1) | (c != XOMBE_CONCEAL_NONE ? 1u : 0u)) & 7u;
d->run = c == XOMBE_CONCEAL_NONE ? 0 : d->run < INT_MAX ? d->run + 1 : INT_MAX;
return c;
}
+445
View File
@@ -0,0 +1,445 @@
#include <math.h>
#include <string.h>
#include "../internal.h"
#include "../dsp/fmath.h"
#if XOMBE_HAVE_DSTAR
#include "../dstar/dsd_state.h"
#endif
#define AVG_F0_INIT XOMBE_HZ(111.63f)
#define LAMBDA_INIT 7.0f
#define INIT_SET_F0 XOMBE_HZ(250.0f)
#define INIT_SET_L 14
#define INIT_SET_LOG2_AMP (-3.321928095f) /* log2(0.1) */
#define DEFAULT_PRNG_SEED 0x12345678u
static const struct xombe_dec_rules ambe2_rules = {xombe__harmonic_voicing, 0.0098f};
void xombe__dec_silence_set(xombe_set *s)
{
int l;
memset(s, 0, sizeof(*s));
s->cls = XOMBE_CLASS_SILENCE;
s->prepared = 1;
s->L = INIT_SET_L;
s->f0 = INIT_SET_F0;
s->e[0] = XOMBE_AMP_OFF;
for (l = 1; l <= XOMBE_LMAX; l++)
s->a[l] = s->e[l] = INIT_SET_LOG2_AMP;
}
XOMBE_STATIC_ASSERT(sizeof(struct xombe_dec) <= XOMBE_DEC_SIZE, decoder_state_fits_XOMBE_DEC_SIZE);
size_t xombe_dec_size(void)
{
return sizeof(struct xombe_dec);
}
void xombe__dec_core_reset(xombe_dec_core *d)
{
memset(d, 0, sizeof(*d));
d->rules = &ambe2_rules;
xombe__pred_init(&d->pi);
d->lambda = LAMBDA_INIT;
d->avg_f0 = AVG_F0_INIT;
d->frame = -1;
d->mute_src = -1;
d->decision.mute_src = -1;
d->decision.e0 = d->decision.e1 = -1;
xombe__dec_silence_set(&d->mute);
xombe__dec_silence_set(&d->played);
d->p1 = d->p2 = d->played;
}
void xombe__dec_reset(xombe_dec *d)
{
memset(d, 0, sizeof(*d));
xombe__dec_core_reset(&d->c);
d->prev_f0 = INIT_SET_F0;
d->noise_mode = XOMBE_NOISE_PRODUCTION;
d->prng = DEFAULT_PRNG_SEED;
xombe__noise_init(d);
xombe__hpf_init(&d->hpf, 1.0f);
xombe__fec_init_dmr(&d->fec);
}
static void dmr_start_bits(xombe_dec *d, const uint8_t bits[7], unsigned flags)
{
d->c.eps_t = d->err_t;
d->c.eps_1 = d->err_1;
xombe__dec_start_frame(&d->c, bits, flags);
}
static const struct xombe_dec_ops dmr_ops = {dmr_start_bits};
xombe_dec *xombe__dec_init_dmr(void *mem)
{
xombe_dec *d = mem;
if (!d)
return NULL;
xombe__dec_reset(d);
d->ops = &dmr_ops;
return d;
}
xombe_dec *xombe__dec_init_dstar(void *mem)
{
#if XOMBE_HAVE_DSTAR
xombe_dec *d = mem;
if (!d)
return NULL;
xombe__dec_reset(d);
xombe__fec_init_dstar(&d->fec);
xombe__dsd_logic_init(&d->ds, &d->c);
d->ops = &xombe__dsd_ops;
return d;
#else
(void)mem;
return NULL;
#endif
}
int xombe_dec_set_noise(xombe_dec *d, enum xombe_noise_mode mode, uint32_t seed)
{
if (mode != XOMBE_NOISE_CONFORMANCE && mode != XOMBE_NOISE_PRODUCTION)
return -1;
d->noise_mode = mode;
d->prng = seed ? seed : DEFAULT_PRNG_SEED;
xombe__noise_init(d);
return 0;
}
void xombe__dec_set_tap(xombe_dec *d, xombe_tap_fn fn, void *ctx)
{
d->c.tap = fn;
d->c.tap_ctx = ctx;
}
void xombe_dec_set_errors(xombe_dec *d, int eps_t, int eps1)
{
d->err_t = eps_t;
d->err_1 = eps1;
}
void xombe_dec_decision_get(const xombe_dec *d, xombe_decision *out)
{
*out = d->c.decision;
}
/* log amplitude of a at harmonic position x >= 0 */
static float harmonic_interp(const float *a, float x)
{
int i = (int)x;
return xombe__harmonic_lerp(a, i, x - (float)i);
}
void xombe__dec_set_from_params(xombe_set *s, int cls, float f0, int L, const float *a, const uint8_t *vb)
{
memset(s, 0, sizeof(*s));
s->cls = cls;
s->f0 = f0;
s->L = L;
memcpy(s->a, a, sizeof(s->a));
if (vb)
memcpy(s->vb, vb, 8);
}
static void first_half_voice_after_voice(const xombe_dec_core *d, const xombe_set *c, const uint8_t *v1, xombe_set *p1)
{
float f1, rc, rp, a1[XOMBE_LMAX + 1];
int l, L1;
if (!xombe__count_voiced(d->pi.v2))
f1 = c->f0;
else if (!xombe__count_voiced(c->vb))
f1 = d->pi.f0;
else
f1 = sqrtf(d->pi.f0 * c->f0);
L1 = xombe__L_from_f0(f1);
rc = f1 / c->f0;
rp = f1 / d->pi.f0;
a1[0] = 0.0f;
for (l = 1; l <= L1; l++) {
float sc = harmonic_interp(c->a, (float)l * rc);
float sp = harmonic_interp(d->pi.a, (float)l * rp);
a1[l] = xombe__clamp_amp(0.5f * (sc + sp));
}
for (l = L1 + 1; l <= XOMBE_LMAX; l++)
a1[l] = a1[L1];
xombe__dec_set_from_params(p1, XOMBE_CLASS_VOICE, f1, L1, a1, v1);
}
static void decode_normal(xombe_dec_core *d, const uint8_t bits[49], int cls)
{
xombe_set c;
xombe_params p;
uint8_t v2[8], v1[8];
int b[9];
memset(v2, 0, sizeof(v2));
memset(v1, 0, sizeof(v1));
xombe__get_fields(bits, b);
if (cls == XOMBE_CLASS_VOICE) {
xombe__dequant(b, &d->pi, 0, &p);
XOMBE_TAP(d, XOMBE_STAGE_DEQUANT, p.f0, p.a + 1, p.L);
xombe__v2_from_b1(b[1], v2);
xombe__f3_first_half(d->pi.v2, v2, v1);
xombe__smooth(d, p.a, p.L, p.f0);
XOMBE_TAP(d, XOMBE_STAGE_SMOOTH, p.f0, p.a + 1, p.L);
xombe__dec_set_from_params(&c, XOMBE_CLASS_VOICE, p.f0, p.L, p.a, v2);
} else if (cls == XOMBE_CLASS_SILENCE) {
xombe__dequant(b, &d->pi, 1, &p);
XOMBE_TAP(d, XOMBE_STAGE_DEQUANT, p.f0, p.a + 1, p.L);
xombe__smooth(d, p.a, p.L, p.f0);
XOMBE_TAP(d, XOMBE_STAGE_SMOOTH, p.f0, p.a + 1, p.L);
xombe__dec_set_from_params(&c, XOMBE_CLASS_SILENCE, p.f0, p.L, p.a, NULL);
} else {
int id, ad;
xombe__tone_frame_parse(bits, &id, &ad);
xombe__tone_set(&c, id, ad);
}
xombe__dec_play(d, &c, v1, &p, v2);
}
void xombe__dec_play(xombe_dec_core *d, const xombe_set *cur, const uint8_t v1[8], const xombe_params *p,
const uint8_t v2[8])
{
const xombe_set c = *cur;
int l, last = d->pi.cls;
if (c.cls == XOMBE_CLASS_TONE || last == XOMBE_CLASS_TONE) {
d->p1 = c;
} else if (last == XOMBE_CLASS_SILENCE) {
d->p1 = c;
memcpy(d->p1.vb, v1, 8);
if (c.cls == XOMBE_CLASS_VOICE)
for (l = 0; l <= XOMBE_LMAX; l++)
d->p1.a[l] = 0.5f * c.a[l];
} else if (c.cls == XOMBE_CLASS_SILENCE) {
if (!d->prev_concealed)
xombe__dec_set_from_params(&d->p1, XOMBE_CLASS_VOICE, d->pi.f0, d->pi.L, d->pi.a, d->pi.v2);
else
d->p1 = c;
} else {
first_half_voice_after_voice(d, &c, v1, &d->p1);
}
d->p2 = c;
if (c.cls == XOMBE_CLASS_VOICE)
xombe__pred_store_voice(&d->pi, p, v2);
else
xombe__pred_store_other(&d->pi, c.cls);
}
void xombe__dec_conceal_sets(xombe_dec_core *d, int conceal)
{
d->p1 = conceal == XOMBE_CONCEAL_MUTE ? d->mute : d->played;
d->p1.repeat = 1;
d->p2 = d->p1;
}
void xombe__dec_start_frame(xombe_dec_core *d, const uint8_t bytes[7], unsigned flags)
{
uint8_t bits[49];
int cls, bad, hb, conceal, tone_ok = 1;
d->frame++;
if (flags & XOMBE_FLAG_LOST) {
memset(bits, 0, sizeof(bits));
cls = XOMBE_CLASS_ERASURE;
flags = 0;
} else {
xombe__unpack49(bytes, bits);
cls = xombe__frame_class(bits);
}
if (cls == XOMBE_CLASS_TONE) {
int id, ad;
tone_ok = xombe__tone_frame_parse(bits, &id, &ad);
}
hb = (flags & XOMBE_FLAG_HB) != 0;
bad = (flags & XOMBE_FLAG_BF) || cls == XOMBE_CLASS_ERASURE || !tone_ok;
conceal = xombe__conceal_decide(d, bad, hb);
d->decision.cls = cls;
d->decision.conceal = conceal;
d->decision.run = d->run;
d->decision.mute_src = conceal == XOMBE_CONCEAL_MUTE ? d->mute_src : -1;
d->decision.e0 = d->decision.e1 = -1;
d->decision.bf = (flags & XOMBE_FLAG_BF) != 0;
d->decision.hb = hb;
if (conceal != XOMBE_CONCEAL_NONE)
xombe__dec_conceal_sets(d, conceal);
else
decode_normal(d, bits, cls);
d->prev_concealed = conceal != XOMBE_CONCEAL_NONE;
}
static void prepare_set(xombe_set *s)
{
int l;
if (s->prepared || s->repeat)
return;
for (l = 0; l <= XOMBE_LMAX; l++)
s->e[l] = l >= 1 && l <= s->L ? s->a[l] : XOMBE_AMP_OFF;
if (s->cls == XOMBE_CLASS_VOICE) {
xombe__phases(s->a, s->L, s->phi);
xombe__enhance(s->a, s->L, s->f0, s->e);
} else {
memset(s->phi, 0, sizeof(s->phi));
}
s->prepared = 1;
}
static void synth_half(xombe_dec *d, xombe_set *s, int first_half, int N, int16_t *pcm)
{
float M[XOMBE_LMAX + 1], x[XOMBE_HALF_MAX];
uint8_t vh[XOMBE_LMAX + 1];
int n, l, tone = s->cls == XOMBE_CLASS_TONE, voiced;
prepare_set(s);
if (!tone && d->c.tap) {
float lin[XOMBE_LMAX + 1];
for (l = 1; l <= s->L; l++)
lin[l] = xombe__exp2f(s->e[l]);
XOMBE_TAP(&d->c, XOMBE_STAGE_SET, s->f0, s->a + 1, s->L);
XOMBE_TAP(&d->c, XOMBE_STAGE_ENHANCED, s->f0, lin + 1, s->L);
}
if (s->cls == XOMBE_CLASS_VOICE)
XOMBE_TAP(&d->c, XOMBE_STAGE_PHASE, s->f0, s->phi + 1, s->L);
if (s->cls == XOMBE_CLASS_SILENCE && !s->repeat) {
d->c.mute = *s;
d->c.mute_src = d->c.frame;
}
if (tone) {
for (l = 0; l <= XOMBE_LMAX; l++)
vh[l] = (uint8_t)(l >= 1 && l <= s->L);
} else {
d->c.rules->harm_voicing(s->vb, s->f0, s->L, vh);
}
memset(M, 0, sizeof(M));
if (tone) {
for (l = 1; l <= s->L; l++)
if (s->e[l] > XOMBE_AMP_OFF)
M[l] = xombe__exp2f(s->e[l]);
} else {
if (first_half && xombe__count_voiced(s->vb) >= 4)
d->c.avg_f0 = 0.9f * d->c.avg_f0 + 0.1f * s->f0;
xombe__shape(s->e, M, s->L, s->f0, d->c.avg_f0);
}
XOMBE_TAP(&d->c, XOMBE_STAGE_SHAPED, s->f0, M + 1, s->L);
memset(x, 0, sizeof(x));
xombe__synth_unvoiced(d, s, M, vh, N, x);
voiced = tone || xombe__count_voiced(s->vb) > 0;
xombe__synth_voiced(d, s, M, vh, voiced, N, x);
XOMBE_TAP(&d->c, XOMBE_STAGE_SYNTH, s->f0, x, N);
for (n = 0; n < N; n++) {
float y = floorf(xombe__hpf_step(&d->hpf, x[n]) + 0.5f);
if (y > 32767.0f)
y = 32767.0f;
if (y < -32768.0f)
y = -32768.0f;
pcm[n] = (int16_t)y;
}
}
void xombe__dec_synth(xombe_dec *d, int second_half, int N, int16_t *pcm)
{
if (!second_half) {
synth_half(d, &d->c.p1, 1, N, pcm);
} else {
synth_half(d, &d->c.p2, 0, N, pcm);
d->c.played = d->c.p2;
}
}
void xombe__dec_skip_synth(xombe_dec_core *d)
{
const xombe_set *h[2];
int i;
h[0] = &d->p1;
h[1] = &d->p2;
for (i = 0; i < 2; i++)
if (h[i]->cls == XOMBE_CLASS_SILENCE && !h[i]->repeat) {
d->mute = *h[i];
d->mute_src = d->frame;
}
d->played = d->p2;
}
int xombe__dec_half_begin(xombe_dec *d, int second_half, int n)
{
if ((second_half != 0) != d->second_half_next)
return -1;
d->second_half_next = !second_half;
return n < XOMBE_HALF_MIN ? XOMBE_HALF_MIN : n > XOMBE_HALF_MAX ? XOMBE_HALF_MAX : n;
}
/* the codec's start_bits of a frame through the decoder's FEC */
static void start_frame(xombe_dec *d, const uint8_t in[9], unsigned flags)
{
uint8_t bits[7];
xombe_fec_stats st;
memset(bits, 0, sizeof(bits));
if (flags & XOMBE_FLAG_LOST) {
d->ops->start_bits(d, bits, XOMBE_FLAG_LOST);
return;
}
flags = xombe_fec_decode(&d->fec, in, bits, &st);
d->err_t = st.eps_t;
d->err_1 = st.eps1;
d->ops->start_bits(d, bits, flags);
d->c.decision.e0 = st.eps0;
d->c.decision.e1 = st.eps1;
}
int xombe_dec_half_bits(xombe_dec *d, const uint8_t bits[7], unsigned flags, int second_half, int n, int16_t *pcm)
{
int N = xombe__dec_half_begin(d, second_half, n);
if (N < 0)
return -1;
second_half = second_half != 0;
if (!second_half)
d->ops->start_bits(d, bits, flags);
xombe__dec_synth(d, second_half, N, pcm);
return N;
}
int xombe_dec_half(xombe_dec *d, const uint8_t in[9], unsigned flags, int second_half, int n, int16_t *pcm)
{
int N = xombe__dec_half_begin(d, second_half, n);
if (N < 0)
return -1;
second_half = second_half != 0;
if (!second_half)
start_frame(d, in, flags);
xombe__dec_synth(d, second_half, N, pcm);
return N;
}
int xombe_dec_frame_bits(xombe_dec *d, const uint8_t bits[XOMBE_BITS_BYTES], unsigned flags, int16_t pcm[160])
{
int fresh = xombe_dec_half_bits(d, bits, flags, 0, 80, pcm) >= 0;
if (!fresh)
memset(pcm, 0, 80 * sizeof(*pcm));
xombe_dec_half_bits(d, bits, flags, 1, 80, pcm + 80);
return fresh;
}
int xombe_dec_frame(xombe_dec *d, const uint8_t in[XOMBE_FRAME_BYTES], unsigned flags, int16_t pcm[160])
{
int fresh = xombe_dec_half(d, in, flags, 0, 80, pcm) >= 0;
if (!fresh)
memset(pcm, 0, 80 * sizeof(*pcm));
xombe_dec_half(d, in, flags, 1, 80, pcm + 80);
return fresh;
}
void xombe__dec_start_air(xombe_dec_core *d, xombe_fec *fec, const uint8_t air[9], unsigned flags, uint8_t bits[7])
{
xombe_fec_stats st;
memset(bits, 0, 7);
if (flags & XOMBE_FLAG_LOST) {
xombe__dec_start_frame(d, bits, XOMBE_FLAG_LOST);
return;
}
flags = xombe_fec_decode(fec, air, bits, &st);
d->eps_t = st.eps_t;
d->eps_1 = st.eps1;
xombe__dec_start_frame(d, bits, flags);
d->decision.e0 = st.eps0;
d->decision.e1 = st.eps1;
}
+133
View File
@@ -0,0 +1,133 @@
#include <math.h>
#include <string.h>
#include "dkernels.h"
#include "../tables/dsp_tables.h"
#define GRAIN_RAMP XOMBE_GRAIN_RAMP
#define WT_SIZE XOMBE_WT_SIZE
#define UV_FFT XOMBE_UV_FFT
#define UV_BINS XOMBE_UV_BINS
XOMBE_STATIC_ASSERT(WT_SIZE <= XOMBE_IRFFT_MAX, wavetable_fits_irfft);
XOMBE_STATIC_ASSERT(XOMBE_TW_N % WT_SIZE == 0, twiddles_cover_wavetable);
XOMBE_STATIC_ASSERT(UV_FFT <= XOMBE_IRFFT_MAX, uv_fft_fits_irfft);
XOMBE_STATIC_ASSERT(XOMBE_TW_N % UV_FFT == 0, twiddles_cover_uv_fft);
XOMBE_STATIC_ASSERT(XOMBE_LMAX <= XOMBE_HALF_MAX, sqrt_table_covers_L);
void xombe__dk_wavetable(const xombe_set *s, const float *M, const uint8_t *vh, float tab[XOMBE_WT_SIZE])
{
xombe_cpx spec[WT_SIZE / 2 + 1];
int l;
memset(spec, 0, sizeof(spec));
for (l = 1; l <= s->L && l <= XOMBE_LMAX; l++) {
float psi;
if (!vh[l] || M[l] == 0.0f)
continue;
psi = s->phi[l] - 2.0f * XOMBE_PI_F * l * XOMBE_EPOCH_REF * s->f0;
spec[l].re = WT_SIZE * M[l] * cosf(psi);
spec[l].im = WT_SIZE * M[l] * sinf(psi);
}
xombe__irfft(spec, tab, WT_SIZE, xombe__fft_tw, XOMBE_TW_N);
}
/* 0.5*(1 - cos(pi*(j + frac)/GRAIN_RAMP)) for integer j, cf and sf the cos and sin of pi*frac/GRAIN_RAMP */
static float ramp(int j, float cf, float sf)
{
return 0.5f * (1.0f - (xombe__ramp_cos[j] * cf - xombe__ramp_sin[j] * sf));
}
void xombe__dk_add_grain(float *buf, int N, float P, float fhat, float period, const float *tab)
{
float E = P + period;
int nb = (int)ceilf(P), ne = (int)floorf(E), n0 = nb, n1 = ne + GRAIN_RAMP, n;
/* fade-in over n - P = (n - nb) + (nb - P), fade-out over E + GRAIN_RAMP - n = (GRAIN_RAMP + ne - n) + (E - ne):
integer table steps rotated by a fraction fixed for the grain */
float ai = XOMBE_PI_F * ((float)nb - P) / GRAIN_RAMP, ao = XOMBE_PI_F * (E - (float)ne) / GRAIN_RAMP;
float cs = cosf(ai), ss = sinf(ai), ce = cosf(ao), se = sinf(ao);
if (n0 < 0)
n0 = 0;
if (n1 > N + XOMBE_TAIL - 1)
n1 = N + XOMBE_TAIL - 1;
for (n = n0; n <= n1; n++) {
float th = (n - P) * fhat, x, fr, w;
int i;
th -= floorf(th);
x = th * WT_SIZE;
i = (int)x;
fr = x - i;
if (n < P + GRAIN_RAMP)
w = ramp(n - nb, cs, ss);
else if (n <= E)
w = 1.0f;
else
w = ramp(GRAIN_RAMP + ne - n, ce, se);
buf[n] += w * (tab[i & (WT_SIZE - 1)] * (1.0f - fr) + tab[(i + 1) & (WT_SIZE - 1)] * fr);
}
}
/* sqrt(n/N), crossfade gain n samples into a half-frame of N, rs = 1/sqrt(N) */
static float fade(int n, float rs)
{
return xombe__sqrt_n[n] * rs;
}
static int round_half_up(float x)
{
return (int)floorf(x + 0.5f);
}
void xombe__dk_unvoiced(const int16_t *seg, int N, const xombe_set *cur, const float *M, const uint8_t *vh,
float avg_f0, float y[XOMBE_UV_FFT])
{
float buf[UV_FFT];
xombe_cpx X[UV_BINS], Y[UV_BINS];
float beta = UV_FFT * cur->f0, rs = xombe__rsqrt_half[N - XOMBE_HALF_MIN], sqrt_L = xombe__sqrt_n[cur->L];
int n, k, l, upper = 0, low;
int silence = cur->cls == XOMBE_CLASS_SILENCE;
memset(buf, 0, sizeof(buf));
for (n = 0; n < 2 * N; n++) {
float w = n < N ? fade(n, rs) : fade(2 * N - n, rs);
buf[n] = w * (float)seg[n];
}
xombe__rfft(buf, X, UV_FFT, xombe__fft_tw, XOMBE_TW_N);
memset(Y, 0, sizeof(Y));
for (l = 1; l <= cur->L; l++) {
int lo = round_half_up((l - 0.5f) * beta), hi = round_half_up((l + 0.5f) * beta);
if (lo > UV_BINS - 1)
lo = UV_BINS - 1;
if (hi > UV_BINS - 1)
hi = UV_BINS - 1;
if (l == cur->L)
upper = hi;
if (hi <= lo)
continue;
if (silence) {
float g = XOMBE_CN_GAIN * sqrt_L * M[l];
for (k = lo; k < hi; k++) {
Y[k].re = X[k].re * g;
Y[k].im = X[k].im * g;
}
} else if (!vh[l]) {
float e = 0.0f;
float g;
for (k = lo; k < hi; k++)
e += X[k].re * X[k].re + X[k].im * X[k].im;
e /= (hi - lo);
if (e <= 0.0f)
continue;
g = XOMBE_UV_GAIN * (sqrt_L * xombe__sqrt_n[N]) * M[l] / sqrtf(e);
for (k = lo; k < hi; k++) {
Y[k].re = X[k].re * g;
Y[k].im = X[k].im * g;
}
}
}
if (upper > XOMBE_UV_TOP_BIN)
upper = XOMBE_UV_TOP_BIN;
for (k = upper; k < UV_BINS; k++)
Y[k].re = Y[k].im = 0.0f;
low = (int)(UV_FFT * avg_f0);
for (k = 0; k < low && k < UV_BINS; k++)
Y[k].re = Y[k].im = 0.0f;
xombe__irfft(Y, y, UV_FFT, xombe__fft_tw, XOMBE_TW_N);
}
+342
View File
@@ -0,0 +1,342 @@
/* q15 decoder kernels (dkernels.h, XOMBE_KERNELS=q15): unvoiced transforms through the block-floating-point Q15
FFT. the wavetable keeps the float one, Q15's ~65 dB on its sparse spectra moves PCM by up to 10 LSB */
#include <float.h>
#include <math.h>
#include <string.h>
#include "dkernels.h"
#include "../tables/dsp_tables.h"
#include "../dsp/fft_q15.h"
#include "../dsp/fmath.h"
#define GRAIN_RAMP XOMBE_GRAIN_RAMP
#define WT_SIZE XOMBE_WT_SIZE
#define UV_FFT XOMBE_UV_FFT
#define UV_BINS XOMBE_UV_BINS
#define QM (UV_FFT / 2) /* complex points of the unvoiced transforms */
#define QM_LOG2 7
#define TW_STEP (XOMBE_TW_N / UV_FFT) /* xombe__fft_tw[k*TW_STEP] = exp(-2 pi i k/UV_FFT) */
XOMBE_STATIC_ASSERT(WT_SIZE <= XOMBE_IRFFT_MAX, wavetable_fits_irfft);
XOMBE_STATIC_ASSERT(XOMBE_TW_N % WT_SIZE == 0, twiddles_cover_wavetable);
XOMBE_STATIC_ASSERT(1 << QM_LOG2 == QM, qm_log2);
XOMBE_STATIC_ASSERT(XOMBE_TW_N % UV_FFT == 0, twiddles_cover_uv_fft);
XOMBE_STATIC_ASSERT(2 * XOMBE_HALF_MAX <= UV_FFT, segment_fits_uv_fft);
XOMBE_STATIC_ASSERT(XOMBE_LMAX <= XOMBE_HALF_MAX, sqrt_table_covers_L);
/* exp(-2 pi i j/QM) for j < QM/2, Q15 rounded and held below 1, as int16 pairs (re, im) */
static const uint32_t tw_q15[QM / 2] = {
0x00007fffu, 0xf9b87fd9u, 0xf3747f62u, 0xed387e9du, 0xe7077d8au, 0xe0e67c2au,
0xdad87a7du, 0xd4e17885u, 0xcf047642u, 0xc94673b6u, 0xc3a970e3u, 0xbe326dcau,
0xb8e36a6eu, 0xb3c066d0u, 0xaecc62f2u, 0xaa0a5ed7u, 0xa57e5a82u, 0xa12955f6u,
0x9d0e5134u, 0x99304c40u, 0x9592471du, 0x923641ceu, 0x8f1d3c57u, 0x8c4a36bau,
0x89be30fcu, 0x877b2b1fu, 0x85832528u, 0x83d61f1au, 0x827618f9u, 0x816312c8u,
0x809e0c8cu, 0x80270648u, 0x80000000u, 0x8027f9b8u, 0x809ef374u, 0x8163ed38u,
0x8276e707u, 0x83d6e0e6u, 0x8583dad8u, 0x877bd4e1u, 0x89becf04u, 0x8c4ac946u,
0x8f1dc3a9u, 0x9236be32u, 0x9592b8e3u, 0x9930b3c0u, 0x9d0eaeccu, 0xa129aa0au,
0xa57ea57eu, 0xaa0aa129u, 0xaecc9d0eu, 0xb3c09930u, 0xb8e39592u, 0xbe329236u,
0xc3a98f1du, 0xc9468c4au, 0xcf0489beu, 0xd4e1877bu, 0xdad88583u, 0xe0e683d6u,
0xe7078276u, 0xed388163u, 0xf374809eu, 0xf9b88027u
};
/* nearest integer (ties to even), |v| < 2^22 */
static int32_t round_q(float v)
{
uint32_t u;
v += 12582912.0f;
memcpy(&u, &v, sizeof(u));
return (int32_t)(u & 0x7fffffu) - 0x400000;
}
static uint32_t pack(int32_t lo, int32_t hi)
{
return ((uint32_t)lo & 0xffffu) | (uint32_t)hi << 16;
}
static float block_gain(float m)
{
float g = m > 0.0f ? (float)XOMBE_CFFT_Q15_PEAK / m : 0.0f;
return g <= FLT_MAX ? g : 0.0f;
}
static uint32_t rev(int k)
{
return q15_rbit((uint32_t)k) >> (32 - QM_LOG2);
}
/* xombe__irfft for UV_FFT points: float pre-twiddle, then the inverse complex transform as the forward one on
swapped halves (swap(FFT(swap(z))) is the unscaled inverse) */
static void irfft_q15(const xombe_cpx *in, float *out)
{
xombe_cpx z[QM];
uint32_t x[QM];
float m = 0.0f, g, sc;
int k, s;
/* points k and QM - k from the same two bins, w[QM - k] = -conj(w[k]) */
for (k = 0; k <= QM / 2; k++) {
xombe_cpx a = in[k], b = in[QM - k], w = xombe__fft_tw[k * TW_STEP];
float er = 0.5f * (a.re + b.re), ei = 0.5f * (a.im - b.im), dr = 0.5f * (a.re - b.re), di = 0.5f * (a.im + b.im);
float pr = dr * w.re + di * w.im, pi = di * w.re - dr * w.im;
z[k].re = er - pi;
z[k].im = ei + pr;
m = fmaxf(m, fmaxf(fabsf(z[k].re), fabsf(z[k].im)));
if (k == 0 || k == QM / 2)
continue;
/* bins swapped: er, -ei, -dr, and di against -conj(w), the same pr */
pi = dr * w.im - di * w.re;
z[QM - k].re = er - pi;
z[QM - k].im = pr - ei;
m = fmaxf(m, fmaxf(fabsf(z[QM - k].re), fabsf(z[QM - k].im)));
}
g = block_gain(m);
if (g == 0.0f) {
memset(out, 0, sizeof(float) * UV_FFT);
return;
}
for (k = 0; k < QM; k++)
x[rev(k)] = pack(round_q(z[k].im * g), round_q(z[k].re * g));
s = xombe__cfft_q15(x, QM, tw_q15, XOMBE_CFFT_Q15_PEAK);
sc = (float)(1 << s) / (g * (float)QM);
for (k = 0; k < QM; k++) {
out[2 * k] = (float)q15_hi(x[k]) * sc;
out[2 * k + 1] = (float)q15_lo(x[k]) * sc;
}
}
/* xombe__rfft of UV_FFT samples q[] times 1/g (q block-scaled to XOMBE_CFFT_Q15_PEAK), bins 0..QM */
static void rfft_q15(const int16_t *q, float g, xombe_cpx *X)
{
uint32_t x[QM];
float h;
int k, s;
for (k = 0; k < QM; k++)
x[rev(k)] = q15_ld2(q + 2 * k);
s = xombe__cfft_q15(x, QM, tw_q15, XOMBE_CFFT_Q15_PEAK);
h = 0.5f * (float)(1 << s) / g;
for (k = 0; k <= QM / 2; k++) {
uint32_t a = x[k], b = x[(QM - k) & (QM - 1)];
float er = (float)(q15_lo(a) + q15_lo(b)), ei = (float)(q15_hi(a) - q15_hi(b));
float orr = (float)(q15_hi(a) + q15_hi(b)), oi = (float)(q15_lo(b) - q15_lo(a)), pr, pi;
xombe_cpx w;
if (k < QM / 2) {
w = xombe__fft_tw[k * TW_STEP];
} else {
w.re = 0.0f;
w.im = -1.0f;
}
pr = w.re * orr - w.im * oi;
pi = w.re * oi + w.im * orr;
X[k].re = h * (er + pr);
X[k].im = h * (ei + pi);
X[QM - k].re = h * (er - pr);
X[QM - k].im = h * (pi - ei);
}
}
/* float wavetable transform: z of QM points (bit-reversed order) transformed in place, forward, radix-2^2 passes
as in fft_q15.h, twiddles exp(-2 pi i j/QM) = xombe__fft_tw[j*2*TW_STEP] */
static void cfft_wt(xombe_cpx *x)
{
const int ts = 2 * TW_STEP;
int len, i, j;
for (i = 0; i < QM; i += 4) {
xombe_cpx x0 = x[i], x1 = x[i + 1], x2 = x[i + 2], x3 = x[i + 3];
float ar = x0.re + x1.re, ai = x0.im + x1.im, br = x0.re - x1.re, bi = x0.im - x1.im;
float cr = x2.re + x3.re, ci = x2.im + x3.im, dr = x2.re - x3.re, di = x2.im - x3.im;
x[i].re = ar + cr;
x[i].im = ai + ci;
x[i + 2].re = ar - cr;
x[i + 2].im = ai - ci;
x[i + 1].re = br + di; /* b + (-i)*d */
x[i + 1].im = bi - dr;
x[i + 3].re = br - di;
x[i + 3].im = bi + dr;
}
for (len = 8; 2 * len <= QM; len <<= 2) {
int q = len >> 1, sa = ts * (QM / len), sb = sa >> 1;
for (i = 0; i < QM; i += 2 * len) {
xombe_cpx *p = x + i;
for (j = 0; j < q; j++) {
xombe_cpx wa = xombe__fft_tw[j * sa], wb = xombe__fft_tw[j * sb];
xombe_cpx u0 = p[j], u1 = p[j + q], u2 = p[j + 2 * q], u3 = p[j + 3 * q];
float t1r = u1.re * wa.re - u1.im * wa.im, t1i = u1.re * wa.im + u1.im * wa.re;
float t3r = u3.re * wa.re - u3.im * wa.im, t3i = u3.re * wa.im + u3.im * wa.re;
float y0r = u0.re + t1r, y0i = u0.im + t1i, y1r = u0.re - t1r, y1i = u0.im - t1i;
float y2r = u2.re + t3r, y2i = u2.im + t3i, y3r = u2.re - t3r, y3i = u2.im - t3i;
float t2r = y2r * wb.re - y2i * wb.im, t2i = y2r * wb.im + y2i * wb.re;
float t4r = y3r * wb.re - y3i * wb.im, t4i = y3r * wb.im + y3i * wb.re;
p[j].re = y0r + t2r;
p[j].im = y0i + t2i;
p[j + 2 * q].re = y0r - t2r;
p[j + 2 * q].im = y0i - t2i;
p[j + q].re = y1r + t4i; /* y1 + (-i)*t4 */
p[j + q].im = y1i - t4r;
p[j + 3 * q].re = y1r - t4i;
p[j + 3 * q].im = y1i + t4r;
}
}
}
if (len <= QM) {
int q = QM >> 1;
for (j = 0; j < q; j++) {
xombe_cpx w = xombe__fft_tw[j * ts], a = x[j], b = x[j + q];
float tr = b.re * w.re - b.im * w.im, ti = b.re * w.im + b.im * w.re;
x[j].re = a.re + tr;
x[j].im = a.im + ti;
x[j + q].re = a.re - tr;
x[j + q].im = a.im - ti;
}
}
}
XOMBE_STATIC_ASSERT(WT_SIZE == UV_FFT && XOMBE_LMAX < QM / 2, wavetable_bins_below_mirror);
/* xombe__irfft of a wavetable spectrum, bins above XOMBE_LMAX zero: pre-twiddle into swapped halves, the forward
transform above, scaled by 1/QM */
static void irfft_wt(const xombe_cpx *in, float *out)
{
xombe_cpx z[QM];
int k;
memset(z, 0, sizeof(z));
for (k = 1; k <= XOMBE_LMAX; k++) {
xombe_cpx a = in[k], w = xombe__fft_tw[k * TW_STEP];
/* in[QM - k] = 0, so z[k] and z[QM - k] both come from in[k] alone, w[QM - k] = -conj(w) */
float er = 0.5f * a.re, ei = 0.5f * a.im;
float pr = er * w.re + ei * w.im, pi = ei * w.re - er * w.im;
z[rev(k)].re = ei + pr; /* swapped (im, re) */
z[rev(k)].im = er - pi;
pi = er * w.im - ei * w.re;
z[rev(QM - k)].re = pr - ei;
z[rev(QM - k)].im = er - pi;
}
cfft_wt(z);
for (k = 0; k < QM; k++) {
out[2 * k] = z[k].im * (1.0f / QM);
out[2 * k + 1] = z[k].re * (1.0f / QM);
}
}
void xombe__dk_wavetable(const xombe_set *s, const float *M, const uint8_t *vh, float tab[XOMBE_WT_SIZE])
{
xombe_cpx spec[WT_SIZE / 2 + 1];
int l;
memset(spec, 0, sizeof(spec));
for (l = 1; l <= s->L && l <= XOMBE_LMAX; l++) {
float psi, cp, sp;
if (!vh[l] || M[l] == 0.0f)
continue;
psi = s->phi[l] - 2.0f * XOMBE_PI_F * l * XOMBE_EPOCH_REF * s->f0;
xombe__sincosf(psi, &sp, &cp);
spec[l].re = WT_SIZE * M[l] * cp;
spec[l].im = WT_SIZE * M[l] * sp;
}
irfft_wt(spec, tab);
}
static float ramp(int j, float cf, float sf)
{
return 0.5f * (1.0f - (xombe__ramp_cos[j] * cf - xombe__ramp_sin[j] * sf));
}
/* tab at phase ph (cycles in 2^-32 units), linear between entries */
static float tab_at(const float *tab, uint32_t ph)
{
int i = (int)(ph >> 24);
float t0 = tab[i], t1 = tab[(i + 1) & (WT_SIZE - 1)];
return t0 + (float)(ph & 0xffffffu) * (1.0f / 16777216.0f) * (t1 - t0);
}
XOMBE_STATIC_ASSERT(WT_SIZE == 256, wavetable_index_is_top_byte);
/* phase (n - P)*fhat as a 32-bit fraction accumulated from n0, fade-in, flat, and fade-out runs split ahead */
void xombe__dk_add_grain(float *buf, int N, float P, float fhat, float period, const float *tab)
{
float E = P + period, th;
int nb = (int)ceilf(P), ne = (int)floorf(E), n0 = nb, n1 = ne + GRAIN_RAMP, nin = (int)ceilf(P + GRAIN_RAMP), n;
float ai = XOMBE_PI_F * ((float)nb - P) / GRAIN_RAMP, ao = XOMBE_PI_F * (E - (float)ne) / GRAIN_RAMP;
float cs, ss, ce, se;
uint32_t ph, inc = (uint32_t)(fhat * 4294967296.0f); /* fhat < 1/16 */
xombe__sincosf(ai, &ss, &cs);
xombe__sincosf(ao, &se, &ce);
if (n0 < 0)
n0 = 0;
if (n1 > N + XOMBE_TAIL - 1)
n1 = N + XOMBE_TAIL - 1;
th = ((float)n0 - P) * fhat;
th -= floorf(th);
ph = ((uint32_t)(th * 16777216.0f) & 0xffffffu) << 8;
for (n = n0; n <= n1 && n < nin; n++, ph += inc)
buf[n] += ramp(n - nb, cs, ss) * tab_at(tab, ph);
for (; n <= n1 && n <= ne; n++, ph += inc)
buf[n] += tab_at(tab, ph);
for (; n <= n1; n++, ph += inc)
buf[n] += ramp(GRAIN_RAMP + ne - n, ce, se) * tab_at(tab, ph);
}
/* noise samples to the FFT's input peak, the fades are at most 1 */
#define NOISE_Q ((float)XOMBE_CFFT_Q15_PEAK / 32768.0f)
static float fade(int n, float rs)
{
return xombe__sqrt_n[n] * rs;
}
static int round_half_up(float x)
{
return (int)floorf(x + 0.5f);
}
void xombe__dk_unvoiced(const int16_t *seg, int N, const xombe_set *cur, const float *M, const uint8_t *vh,
float avg_f0, float y[XOMBE_UV_FFT])
{
int16_t q[UV_FFT];
xombe_cpx X[UV_BINS], Y[UV_BINS];
float beta = UV_FFT * cur->f0, rs = xombe__rsqrt_half[N - XOMBE_HALF_MIN], sqrt_L = xombe__sqrt_n[cur->L];
int n, k, l, upper = 0, low;
int silence = cur->cls == XOMBE_CLASS_SILENCE;
memset(q, 0, sizeof(q));
for (n = 0; n < N; n++)
q[n] = (int16_t)round_q((float)seg[n] * (fade(n, rs) * NOISE_Q));
for (; n < 2 * N; n++)
q[n] = (int16_t)round_q((float)seg[n] * (fade(2 * N - n, rs) * NOISE_Q));
rfft_q15(q, NOISE_Q, X);
memset(Y, 0, sizeof(Y));
for (l = 1; l <= cur->L; l++) {
int lo = round_half_up((l - 0.5f) * beta), hi = round_half_up((l + 0.5f) * beta);
if (lo > UV_BINS - 1)
lo = UV_BINS - 1;
if (hi > UV_BINS - 1)
hi = UV_BINS - 1;
if (l == cur->L)
upper = hi;
if (hi <= lo)
continue;
if (silence) {
float g = XOMBE_CN_GAIN * sqrt_L * M[l];
for (k = lo; k < hi; k++) {
Y[k].re = X[k].re * g;
Y[k].im = X[k].im * g;
}
} else if (!vh[l]) {
float e = 0.0f;
float g;
for (k = lo; k < hi; k++)
e += X[k].re * X[k].re + X[k].im * X[k].im;
e /= (hi - lo);
if (e <= 0.0f)
continue;
g = XOMBE_UV_GAIN * (sqrt_L * xombe__sqrt_n[N]) * M[l] / sqrtf(e);
for (k = lo; k < hi; k++) {
Y[k].re = X[k].re * g;
Y[k].im = X[k].im * g;
}
}
}
if (upper > XOMBE_UV_TOP_BIN)
upper = XOMBE_UV_TOP_BIN;
for (k = upper; k < UV_BINS; k++)
Y[k].re = Y[k].im = 0.0f;
low = (int)(UV_FFT * avg_f0);
for (k = 0; k < low && k < UV_BINS; k++)
Y[k].re = Y[k].im = 0.0f;
irfft_q15(Y, y);
}
+29
View File
@@ -0,0 +1,29 @@
#ifndef XOMBE_DKERNELS_H
#define XOMBE_DKERNELS_H
/* decoder inner loops, dkern_float.c or dkern_q15.c (XOMBE_KERNELS=q15) */
#include "../internal.h"
#define XOMBE_EPOCH_REF 16 /* sample of a grain the wavetable's phases refer to */
#define XOMBE_UV_FFT 256
#define XOMBE_UV_BINS (XOMBE_UV_FFT / 2 + 1)
/* sqrt(12)/2^16 takes uniform 16-bit noise to unit variance. unvoiced bands are normalized by their energy, so only
the comfort-noise gain carries this scale */
#define XOMBE_UV_NOISE_SCALE (3.4641016151377544f / 65536.0f)
#define XOMBE_UV_GAIN 1.449f
#define XOMBE_CN_GAIN (1.147f * XOMBE_UV_NOISE_SCALE)
#define XOMBE_UV_TOP_BIN 121
/* one period of set s's voiced harmonics (vh[l], amplitudes M[l]) in XOMBE_WT_SIZE samples */
void xombe__dk_wavetable(const xombe_set *s, const float *M, const uint8_t *vh, float tab[XOMBE_WT_SIZE]);
/* adds one pitch period (period = 1/fhat samples) of tab starting at P to buf[0..N + XOMBE_TAIL), faded in over
the first XOMBE_GRAIN_RAMP samples and out over XOMBE_GRAIN_RAMP samples after its end */
void xombe__dk_add_grain(float *buf, int N, float P, float fhat, float period, const float *tab);
/* y[0..2N): noise seg[0..2N) under sqrt(n/N) fades in and out, its spectrum shaped to set cur's unvoiced bands
(every band for silence) with gains M[l], cleared below avg_f0 and above band L and XOMBE_UV_TOP_BIN */
void xombe__dk_unvoiced(const int16_t *seg, int N, const xombe_set *cur, const float *M, const uint8_t *vh,
float avg_f0, float y[XOMBE_UV_FFT]);
#endif
+137
View File
@@ -0,0 +1,137 @@
#include <math.h>
#include "../internal.h"
#include "../dsp/fmath.h"
#define PHASE_TAIL_SLOPE 0.7212f
#define PHASE_MIRROR 64
static float phase_seq(const float *a, int L, int n)
{
if (n < 0)
n = -n;
if (n > PHASE_MIRROR)
n = 2 * PHASE_MIRROR - n;
if (n == 0)
return 0.0f;
if (n <= L)
return a[n];
return a[L] - PHASE_TAIL_SLOPE * (float)(n - L);
}
#define PHASE_TAPS 19 /* odd m = 1..PHASE_TAPS */
/* d/m, a reciprocal multiply in q15 builds */
static float tap(float d, int m)
{
#if XOMBE_KERNELS_Q15
static const float inv_m[PHASE_TAPS + 1] = {0.0f, 1.0f, 0.0f, 1.0f / 3, 0.0f, 1.0f / 5, 0.0f, 1.0f / 7, 0.0f,
1.0f / 9, 0.0f, 1.0f / 11, 0.0f, 1.0f / 13, 0.0f, 1.0f / 15, 0.0f,
1.0f / 17, 0.0f, 1.0f / 19};
return d * inv_m[m];
#else
return d / (float)m;
#endif
}
void xombe__phases(const float *a, int L, float *phi)
{
const float k = (float)(2.0 * 0.69314718055994531 / XOMBE_PI); /* 2 ln 2 / pi */
float t[XOMBE_LMAX + PHASE_TAPS + 1]; /* phase_seq at 0..L + PHASE_TAPS */
int l, m;
for (l = 0; l <= L + PHASE_TAPS; l++)
t[l] = phase_seq(a, L, l);
phi[0] = 0.0f;
for (l = 1; l <= XOMBE_LMAX; l++) {
float s = 0.0f;
if (l <= L)
for (m = 1; m <= PHASE_TAPS; m += 2)
s += tap(t[l + m] - t[l >= m ? l - m : m - l], m);
phi[l] = k * s;
}
}
#define ENH_GAIN (0.96f * XOMBE_PI_F)
#define ENH_LOG2_W_MIN (-1.0f) /* log2 0.5 */
#define ENH_LOG2_W_MAX 0.263034406f /* log2 1.2 */
/* c[l], s[l] = cos, sin of w0*l for l = 1..L, by rotation in q15 builds (error about l ulp) */
static void harmonic_cs(float w0, int L, float *c, float *s)
{
int l;
#if XOMBE_KERNELS_Q15
float c1, s1;
xombe__sincosf(w0, &s1, &c1);
c[1] = c1;
s[1] = s1;
for (l = 2; l <= L; l++) {
c[l] = c[l - 1] * c1 - s[l - 1] * s1;
s[l] = s[l - 1] * c1 + c[l - 1] * s1;
}
#else
for (l = 1; l <= L; l++)
xombe__sincosf(w0 * (float)l, &s[l], &c[l]);
#endif
}
/* spectral enhancement in the log domain: e = a + log2 W + log2 gamma
W = sqrt(M)*(num/den)^(1/4) above harmonic L/8 (else 1), clamped to 0.5..1.2,
num/den = 0.96 pi (r0^2 + r1^2 - 2 r0 r1 cos(w0 l))/(w0 r0 (r0^2 - r1^2)), r0, r1 the power and first
autocorrelation of M = 2^a, gamma restores the power r0
powers are relative to the strongest harmonic so every sum is scale-free: with p = 2^(2(a - amax)) and
rho = r1/r0, num/den = 0.96 pi ((1 - rho cos)^2 + (rho sin)^2)/(w0 r0 (1 - rho)(1 + rho)) * 2^(-2 amax) */
void xombe__enhance(const float *a, int L, float f0, float *e)
{
float w0 = 2.0f * XOMBE_PI_F * f0, amax = a[1], r0 = 0.0f, r1 = 0.0f, sum = 0.0f, rho, lg;
float lw[XOMBE_LMAX + 1], c[XOMBE_LMAX + 1], s[XOMBE_LMAX + 1];
int l;
for (l = 2; l <= L; l++)
if (a[l] > amax)
amax = a[l];
harmonic_cs(w0, L, c, s);
for (l = 1; l <= L; l++) {
float p = xombe__exp2f(2.0f * (a[l] - amax));
r0 += p;
r1 += p * c[l];
}
rho = r1 / r0; /* r0 >= 1, the strongest harmonic contributes 1 */
for (l = 1; l <= L; l++) {
float w = 0.0f;
if (8 * l > L) {
float u = 1.0f - rho * c[l], v = rho * s[l];
float den = w0 * r0 * ((1.0f - rho) * (1.0f + rho));
if (den > 0.0f) {
w = 0.5f * (a[l] - amax) + 0.25f * xombe__log2f(ENH_GAIN * (u * u + v * v) / den);
if (w < ENH_LOG2_W_MIN)
w = ENH_LOG2_W_MIN;
if (w > ENH_LOG2_W_MAX)
w = ENH_LOG2_W_MAX;
}
}
lw[l] = w;
sum += xombe__exp2f(2.0f * (w + a[l] - amax));
}
lg = 0.5f * (xombe__log2f(r0) - xombe__log2f(sum)); /* sum >= 1/4 from the strongest harmonic, W >= 1/2 */
for (l = 1; l <= L; l++)
e[l] = a[l] + lw[l] + lg;
}
#define SHAPE_LOW_MAX XOMBE_HZ(200.0f) /* low roll-off corner: the average pitch, at most this */
/* xombe__hf_tilt through fmath.h, must match it */
static float hf_tilt(float f)
{
return f > XOMBE_HF_CORNER ? xombe__log2f(f / XOMBE_HF_CORNER) : 0.0f;
}
void xombe__shape(const float *e, float *M, int L, float f0, float avg_f0)
{
float fc = avg_f0 < SHAPE_LOW_MAX ? avg_f0 : SHAPE_LOW_MAX;
int l;
for (l = 1; l <= L; l++) {
float f = (float)l * f0, g = e[l];
if (f < fc)
g += 2.0f * xombe__log2f(f / fc);
g += hf_tilt(f);
M[l] = xombe__exp2f(g);
}
}
+38
View File
@@ -0,0 +1,38 @@
#include <math.h>
#include "../internal.h"
#define LAMBDA_FAST 0.98f
#define SMOOTH_GAP 2.0f
#define SMOOTH_MARGIN 5.5f
void xombe__smooth(xombe_dec_core *d, float *a, int L, float f0)
{
float sum = 0.0f, r, tau;
int l;
for (l = 1; l <= L; l++)
sum += a[l] * a[l];
r = sqrtf(sum / (float)L);
if (r > d->lambda - 1.0f)
d->lambda = LAMBDA_FAST * d->lambda + (1.0f - LAMBDA_FAST) * r;
else
d->lambda -= d->rules->lambda_decay;
if (d->eps_t > 3 || d->eps_1 > 1) {
float ratio = f0 / d->pi.f0;
tau = d->lambda + SMOOTH_MARGIN - 0.5f * (float)d->eps_1;
for (l = 1; l <= L; l++) {
float x = (float)l * ratio;
int i = (int)x;
float ps = xombe__harmonic_lerp(d->pi.a, i, x - (float)i);
float g = 6.0f * (float)l * f0;
float e;
if (g > 2.0f)
g = 2.0f;
e = a[l] - (tau - g);
if (a[l] - ps > SMOOTH_GAP && e > 0.0f)
a[l] += (ps - a[l]) * (e < 0.5f ? e : 0.5f);
a[l] = xombe__clamp_amp(a[l]);
}
}
for (l = L + 1; l <= XOMBE_LMAX; l++)
a[l] = a[L];
}
+21
View File
@@ -0,0 +1,21 @@
#include <string.h>
#include "../internal.h"
void xombe__tone_set(xombe_set *s, int id, int ad)
{
float f0_hz, amp = xombe__tone_log2_amp(ad);
int l, l1, l2, top;
memset(s, 0, sizeof(*s));
for (l = 0; l <= XOMBE_LMAX; l++)
s->e[l] = XOMBE_AMP_OFF;
xombe__tone_harmonics(id, &f0_hz, &l1, &l2);
s->cls = XOMBE_CLASS_TONE;
s->prepared = 1;
s->f0 = XOMBE_HZ(f0_hz);
top = l2 > l1 ? l2 : l1;
s->L = top > 9 ? top : 9;
if (l1 > 0)
s->e[l1] = amp;
if (l2 > 0)
s->e[l2] = amp;
}
+67
View File
@@ -0,0 +1,67 @@
#include <string.h>
#include "dkernels.h"
#include "../tables/dsp_tables.h"
static int16_t noise_draw(xombe_dec *d)
{
if (d->noise_mode == XOMBE_NOISE_PRODUCTION) {
uint32_t x = d->prng;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
d->prng = x;
return (int16_t)((int)(x >> 16) - 32768);
}
return xombe__lcg_draw(&d->lcg);
}
void xombe__noise_init(xombe_dec *d)
{
int i;
d->lcg = 0;
for (i = 0; i < XOMBE_TAIL; i++)
d->noise_hist[i] = noise_draw(d);
memset(d->uv_overlap, 0, sizeof(d->uv_overlap));
}
static void noise_reset(xombe_dec *d)
{
memset(d->noise_hist, 0, sizeof(d->noise_hist));
}
static void noise_segment(xombe_dec *d, int N, int16_t *seg)
{
int16_t buf[XOMBE_TAIL + XOMBE_HALF_MAX];
int i;
memcpy(buf, d->noise_hist, sizeof(d->noise_hist));
for (i = 0; i < N; i++)
buf[XOMBE_TAIL + i] = noise_draw(d);
memcpy(seg, buf, sizeof(buf[0]) * 2 * N);
memcpy(d->noise_hist, buf + N, sizeof(d->noise_hist));
}
static float fade(int n, float rs)
{
return xombe__sqrt_n[n] * rs;
}
void xombe__synth_unvoiced(xombe_dec *d, const xombe_set *cur, const float *M, const uint8_t *vh, int N,
float *out)
{
int16_t seg[2 * XOMBE_HALF_MAX];
float y[XOMBE_UV_FFT], rs = xombe__rsqrt_half[N - XOMBE_HALF_MIN];
int n;
if (cur->cls == XOMBE_CLASS_TONE) {
noise_reset(d);
for (n = 0; n < N; n++)
out[n] += d->uv_overlap[n] * fade(N - n, rs);
memset(d->uv_overlap, 0, sizeof(d->uv_overlap));
return;
}
noise_segment(d, N, seg);
xombe__dk_unvoiced(seg, N, cur, M, vh, d->c.avg_f0, y);
for (n = 0; n < N; n++)
out[n] += d->uv_overlap[n] * fade(N - n, rs) + y[n] * fade(n, rs);
memset(d->uv_overlap, 0, sizeof(d->uv_overlap));
memcpy(d->uv_overlap, y + N, sizeof(float) * N);
}
+122
View File
@@ -0,0 +1,122 @@
#include <string.h>
#include "dkernels.h"
#define WT_SIZE XOMBE_WT_SIZE
/* epochs per half-frame: tracks stay below 0.0625 cycles/sample (500 Hz), so at most 6 in 84 samples */
#define EPOCH_MAX 8
/* octave jumps below OCTAVE_MAX, the epoch track follows the octave instead of jumping
doubled: previous f0 between OCTAVE_UP_LO and OCTAVE_UP_HI of the current
halved: current f0 between OCTAVE_DOWN_LO and OCTAVE_DOWN_HI of the previous */
#define OCTAVE_UP_LO 0.4f
#define OCTAVE_UP_HI 0.6f
#define OCTAVE_DOWN_LO 0.41667f
#define OCTAVE_DOWN_HI 0.625f
#define OCTAVE_MAX XOMBE_HZ(250.0f)
/* epochs of a pitch track over a half-frame of N samples: phase (in periods) starts at th0, frequency ramps
linearly from fs to fs + delta, so the phase at n is th0 + n*(fs + n*delta/(2N)), the running sum of the
midpoint frequencies fs + (n + 1/2)*delta/N, evaluated in closed form so float rounding does not accumulate
each integer the phase reaches is an epoch. within its sample the phase is th + u*inc + h*u*(u - 1), inc the
sample's increment, h = delta/(2N), the epoch placed by linear interpolation u = (k - th)/inc, then one
Newton step on the curvature term. returns the epoch count (floor of the phase at N), that phase in *th_end */
static int epoch_track(float th0, float fs, float delta, int N, float t[EPOCH_MAX], float *th_end)
{
float h = 0.5f * delta / (float)N, th = th0;
int n, k = 1, count = 0;
for (n = 0; n < N; n++) {
float m = (float)(n + 1), next = th0 + m * (fs + h * m), inc = next - th;
while ((float)k <= next && count < EPOCH_MAX) {
float u = ((float)k - th) / inc;
u -= h * u * (u - 1.0f) / (inc + h * (2.0f * u - 1.0f));
t[count++] = (float)n + u;
k++;
}
th = next;
}
*th_end = th;
return count;
}
void xombe__synth_voiced(xombe_dec *d, const xombe_set *cur, const float *M, const uint8_t *vh, int cur_voiced,
int N, float *out)
{
float wcur[WT_SIZE], old[XOMBE_HALF_MAX + XOMBE_TAIL], fresh[XOMBE_HALF_MAX + XOMBE_TAIL];
int pv = d->prev_voiced, cv = cur_voiced, any = pv || cv;
float fp = d->prev_f0, fc = cur->f0, fs = 0.0f, fe = 0.0f;
float pc = d->pitch_phase, ec_start = d->epoch, ec = d->epoch;
float delta, phi = pc, phi_new = 0.0f, inv_N = 1.0f / (float)N, t_old[EPOCH_MAX], t_new[EPOCH_MAX];
float per_p = 1.0f / fp, per_c = 1.0f / fc;
int up = 0, down = 0, K = 0, K_new = 0, k, n;
if (pv && cv) {
fs = fp;
if (OCTAVE_UP_LO * fc < fp && fp < OCTAVE_UP_HI * fc && fp < OCTAVE_MAX) {
up = 1;
fe = fc / 2.0f;
} else if (OCTAVE_DOWN_LO * fp < fc && fc < OCTAVE_DOWN_HI * fp && fc < OCTAVE_MAX) {
down = 1;
fe = 2.0f * fc;
} else {
fe = fc;
}
} else if (pv) {
fs = fe = fp;
} else if (cv) {
fs = fe = fc;
}
delta = fe - fs;
if (any)
K = epoch_track(pc, fs, delta, N, t_old, &phi);
memset(old, 0, sizeof(old));
memcpy(old, d->tail, sizeof(d->tail));
if (pv)
for (k = 0; k < K; k++)
xombe__dk_add_grain(old, N, t_old[k], fp, per_p, d->wprev);
for (n = 0; n < N; n++)
out[n] += (1.0f - (float)n * inv_N) * old[n];
memset(fresh, 0, sizeof(fresh));
if (cv) {
float pp = pc, dp = delta, fsp = fs;
xombe__dk_wavetable(cur, M, vh, wcur);
/* across an octave jump the new track runs at twice (up) or half (down) the old one's rate */
if (up) {
pp = 2.0f * pc;
if (pp >= 1.0f) {
pp -= 1.0f;
ec = -(pp / 2.0f) * per_p;
}
dp = 2.0f * delta;
fsp = 2.0f * fs;
} else if (down) {
pp = pc / 2.0f;
dp = delta / 2.0f;
fsp = fs / 2.0f;
}
K_new = epoch_track(pp, fsp, dp, N, t_new, &phi_new);
xombe__dk_add_grain(fresh, N, ec, fc, per_c, wcur);
for (k = 0; k < K_new; k++)
xombe__dk_add_grain(fresh, N, t_new[k], fc, per_c, wcur);
}
for (n = 0; n < N; n++)
out[n] += ((float)n * inv_N) * fresh[n];
memcpy(d->tail, fresh + N, sizeof(d->tail));
if (!any) {
d->pitch_phase = 0.0f;
d->epoch = 0.0f;
} else {
d->pitch_phase = cv ? phi_new - K_new : phi - K;
if (cv && K_new > 0)
d->epoch = t_new[K_new - 1] - N;
else if (pv && K > 0)
d->epoch = t_old[K - 1] - N;
else
d->epoch = ec_start - N;
}
if (cv)
memcpy(d->wprev, wcur, sizeof(wcur));
d->prev_f0 = cur->f0;
d->prev_voiced = cv;
}
+20
View File
@@ -0,0 +1,20 @@
#include "../internal.h"
#include "biquad.h"
void xombe__hpf_init(xombe_hpf *f, float gain)
{
f->x1 = f->s1 = f->s2 = f->y1 = f->y2 = 0.0f;
f->gain = gain;
}
float xombe__hpf_step(xombe_hpf *f, float x)
{
float s = x - f->x1 + (float)HPF_POLE1 * f->s1;
float y = s - 2.0f * f->s1 + f->s2 + (float)HPF_A1 * f->y1 - (float)HPF_A2 * f->y2;
f->x1 = x;
f->s2 = f->s1;
f->s1 = s;
f->y2 = f->y1;
f->y1 = y;
return y * f->gain;
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef XOMBE_BIQUAD_H
#define XOMBE_BIQUAD_H
/* high-pass: first-order section (pole HPF_POLE1) and second-order (1 - HPF_A1 z^-1 + HPF_A2 z^-2),
three zeros at DC */
#define HPF_POLE1 0.9428
#define HPF_A1 1.9394
#define HPF_A2 0.9428
#endif
+95
View File
@@ -0,0 +1,95 @@
#include "../internal.h"
static void cfft(xombe_cpx *x, int m, const xombe_cpx *tw, int stride, int inverse)
{
int i, j, len;
for (i = 1, j = 0; i < m; i++) {
int bit = m >> 1;
for (; j & bit; bit >>= 1)
j ^= bit;
j |= bit;
if (i < j) {
xombe_cpx t = x[i];
x[i] = x[j];
x[j] = t;
}
}
for (len = 2; len <= m; len <<= 1) {
int half = len >> 1, step = stride * (m / len);
for (i = 0; i < m; i += len) {
for (j = 0; j < half; j++) {
xombe_cpx w = tw[j * step];
xombe_cpx a = x[i + j], b = x[i + j + half], t;
if (inverse)
w.im = -w.im;
t.re = b.re * w.re - b.im * w.im;
t.im = b.re * w.im + b.im * w.re;
x[i + j].re = a.re + t.re;
x[i + j].im = a.im + t.im;
x[i + j + half].re = a.re - t.re;
x[i + j + half].im = a.im - t.im;
}
}
}
}
void xombe__rfft(const float *in, xombe_cpx *out, int n, const xombe_cpx *tw, int tw_n_real)
{
int k;
for (k = 0; k < n / 2; k++) {
out[k].re = in[2 * k];
out[k].im = in[2 * k + 1];
}
xombe__rfft_packed(out, n, tw, tw_n_real);
}
void xombe__rfft_packed(xombe_cpx *out, int n, const xombe_cpx *tw, int tw_n_real)
{
int m = n / 2, k, s = tw_n_real / n;
cfft(out, m, tw, 2 * s, 0);
out[m] = out[0];
for (k = 0; k <= m / 2; k++) {
xombe_cpx z1 = out[k], z2 = out[m - k], e, o, w, r1, r2;
e.re = 0.5f * (z1.re + z2.re);
e.im = 0.5f * (z1.im - z2.im);
o.re = 0.5f * (z1.im + z2.im);
o.im = -0.5f * (z1.re - z2.re);
if (k < m / 2 || k == 0) {
w = tw[k * s];
} else {
w.re = 0.0f;
w.im = -1.0f;
}
r1.re = e.re + w.re * o.re - w.im * o.im;
r1.im = e.im + w.re * o.im + w.im * o.re;
r2.re = e.re - w.re * o.re + w.im * o.im;
r2.im = -(e.im - (w.re * o.im + w.im * o.re));
out[k] = r1;
out[m - k] = r2;
}
}
void xombe__irfft(const xombe_cpx *in, float *out, int n, const xombe_cpx *tw, int tw_n_real)
{
xombe_cpx z[XOMBE_IRFFT_MAX / 2];
int m = n / 2, k, s = tw_n_real / n;
float scale = 1.0f / (float)m;
for (k = 0; k < m; k++) {
xombe_cpx a = in[k], b = in[m - k], fe, fo, d, w;
fe.re = 0.5f * (a.re + b.re);
fe.im = 0.5f * (a.im - b.im);
d.re = 0.5f * (a.re - b.re);
d.im = 0.5f * (a.im + b.im);
w = tw[k * s];
w.im = -w.im;
fo.re = d.re * w.re - d.im * w.im;
fo.im = d.re * w.im + d.im * w.re;
z[k].re = fe.re - fo.im;
z[k].im = fe.im + fo.re;
}
cfft(z, m, tw, 2 * s, 1);
for (k = 0; k < m; k++) {
out[2 * k] = z[k].re * scale;
out[2 * k + 1] = z[k].im * scale;
}
}
+186
View File
@@ -0,0 +1,186 @@
#ifndef XOMBE_FFT_Q15_H
#define XOMBE_FFT_Q15_H
/* block-floating-point complex FFT on packed Q15 pairs (q15ops.h: re low, im high), decimation in time in
radix-2^2 passes: stages 2 and 4 with twiddles 1 and -i, then stage pairs (len, 2*len), then a radix-2 stage
when log2 m is odd
a bound b on the magnitudes decides halving: a stage halves (SHADD16/SHSUB16 and the exchanged forms) only
when unhalved outputs (QADD16/QSUB16) could pass 32767. b doubles through an unhalved stage, holds through a
halved one, and is tightened after each pass from the largest output component, read off the OR of
v ^ (v << 1). twiddle products are rounded in Q30 by SMLSD/SMLADX */
#include "q15ops.h"
/* largest bound a stage passes unhalved, its outputs reach 2b + 2 with the twiddle's rounding */
#define XOMBE_CFFT_Q15_FREE 16382
/* largest input peak, sqrt 2 * peak <= XOMBE_CFFT_Q15_FREE so the first stage runs unhalved */
#define XOMBE_CFFT_Q15_PEAK 11583
/* ceil(sqrt 2 * v) for 0 <= v < 2^16 */
static inline int32_t xombe__q15_sqrt2_up(int32_t v)
{
return (int32_t)(((uint32_t)v * 46341u + 32767u) >> 15);
}
#if defined(__GNUC__)
#define XOMBE_Q15_INLINE static inline __attribute__((always_inline))
#else
#define XOMBE_Q15_INLINE static inline
#endif
/* b*w, rounded */
XOMBE_Q15_INLINE uint32_t xombe__q15_cmul(uint32_t b, uint32_t w)
{
return q15_pack_lsl1((uint32_t)(q15_smlsd(b, w, 0x4000) >> 15), (uint32_t)q15_smladx(b, w, 0x4000));
}
/* a + b, a - b, a + (-i)*b, and a - (-i)*b, halved when h */
XOMBE_Q15_INLINE uint32_t xombe__q15_add(uint32_t a, uint32_t b, int h)
{
return h ? q15_shadd16(a, b) : q15_qadd16(a, b);
}
XOMBE_Q15_INLINE uint32_t xombe__q15_sub(uint32_t a, uint32_t b, int h)
{
return h ? q15_shsub16(a, b) : q15_qsub16(a, b);
}
XOMBE_Q15_INLINE uint32_t xombe__q15_addni(uint32_t a, uint32_t b, int h)
{
return h ? q15_shsax(a, b) : q15_qsax(a, b);
}
XOMBE_Q15_INLINE uint32_t xombe__q15_subni(uint32_t a, uint32_t b, int h)
{
return h ? q15_shasx(a, b) : q15_qasx(a, b);
}
/* detector bits of v: bit q of each half set where bits q and q - 1 differ */
XOMBE_Q15_INLINE uint32_t xombe__q15_det(uint32_t v)
{
return v ^ (v << 1);
}
/* stages 2 and 4 (twiddles 1 and -i) on each group of four points, halved per h1 and h2 */
XOMBE_Q15_INLINE uint32_t xombe__cfft_q15_first(uint32_t *x, int m, int h1, int h2)
{
uint32_t det = 0;
int i;
for (i = 0; i < m; i += 4) {
uint32_t x0 = x[i], x1 = x[i + 1], x2 = x[i + 2], x3 = x[i + 3], y0, y1, y2, y3, z0, z1, z2, z3;
y0 = xombe__q15_add(x0, x1, h1);
y1 = xombe__q15_sub(x0, x1, h1);
y2 = xombe__q15_add(x2, x3, h1);
y3 = xombe__q15_sub(x2, x3, h1);
x[i] = z0 = xombe__q15_add(y0, y2, h2);
x[i + 1] = z1 = xombe__q15_addni(y1, y3, h2);
x[i + 2] = z2 = xombe__q15_sub(y0, y2, h2);
x[i + 3] = z3 = xombe__q15_subni(y1, y3, h2);
det |= xombe__q15_det(z0) | xombe__q15_det(z1) | xombe__q15_det(z2) | xombe__q15_det(z3);
}
return det;
}
/* stages len and 2*len as one radix-2^2 pass, halved per h1 and h2: in each block of 2*len, points j, j + q,
j + 2q, and j + 3q for j < q = len/2, the second stage's odd twiddle the first's times -i */
XOMBE_Q15_INLINE uint32_t xombe__cfft_q15_r22(uint32_t *x, int m, int len, const uint32_t *tw, int h1, int h2)
{
uint32_t det = 0;
int q = len >> 1, sa = m / len, sb = sa >> 1, i, j;
for (i = 0; i < m; i += 2 * len) {
uint32_t *p = x + i;
for (j = 0; j < q; j++) {
uint32_t wa = tw[j * sa], wb = tw[j * sb], y0, y1, y2, y3, z0, z1, z2, z3, t;
t = xombe__q15_cmul(p[j + q], wa);
y0 = xombe__q15_add(p[j], t, h1);
y1 = xombe__q15_sub(p[j], t, h1);
t = xombe__q15_cmul(p[j + 3 * q], wa);
y2 = xombe__q15_add(p[j + 2 * q], t, h1);
y3 = xombe__q15_sub(p[j + 2 * q], t, h1);
t = xombe__q15_cmul(y2, wb);
p[j] = z0 = xombe__q15_add(y0, t, h2);
p[j + 2 * q] = z2 = xombe__q15_sub(y0, t, h2);
t = xombe__q15_cmul(y3, wb);
p[j + q] = z1 = xombe__q15_addni(y1, t, h2);
p[j + 3 * q] = z3 = xombe__q15_subni(y1, t, h2);
det |= xombe__q15_det(z0) | xombe__q15_det(z1) | xombe__q15_det(z2) | xombe__q15_det(z3);
}
}
return det;
}
/* last stage (len = m) alone */
XOMBE_Q15_INLINE uint32_t xombe__cfft_q15_r2(uint32_t *x, int m, const uint32_t *tw, int h)
{
uint32_t det = 0;
int q = m >> 1, j;
for (j = 0; j < q; j++) {
uint32_t t = xombe__q15_cmul(x[j + q], tw[j]), a = x[j], u, v;
x[j] = u = xombe__q15_add(a, t, h);
x[j + q] = v = xombe__q15_sub(a, t, h);
det |= xombe__q15_det(u) | xombe__q15_det(v);
}
return det;
}
/* whether the next stage halves, updating bound b and halving count s */
static inline int xombe__cfft_q15_halve(int32_t *b, int *s)
{
if (*b > XOMBE_CFFT_Q15_FREE) {
*b += 1;
++*s;
return 1;
}
*b = 2 * *b + 2;
return 0;
}
/* tightens b from a pass's detector bits: every component has |v| <= 2^q for the top bit q (bit 0 of each half
may hold the other half's sign) */
static inline void xombe__cfft_q15_tighten(int32_t *b, uint32_t det)
{
uint32_t d = (det | det >> 16) & 0xfffeu;
int32_t bq = xombe__q15_sqrt2_up((int32_t)1 << (d ? 31 - q15_clz32(d) : 0));
if (*b > bq)
*b = bq;
}
/* transforms m points x (m a power of two >= 4, bit-reversed order) in place into natural order, twiddles
tw[j] = exp(-2 pi i j/m) for j < m/2 in Q15. no input component may exceed peak, sqrt 2 * peak <=
XOMBE_CFFT_Q15_FREE. returns the halving count s, x holds the transform times 2^-s
each pass decides its stages' halvings from the bound alone and is checked once at its end */
static int xombe__cfft_q15(uint32_t *x, int m, const uint32_t *tw, int32_t peak)
{
int32_t b = xombe__q15_sqrt2_up(peak);
int len, s = 0, h1, h2;
uint32_t det;
h1 = xombe__cfft_q15_halve(&b, &s);
h2 = xombe__cfft_q15_halve(&b, &s);
switch (h1 << 1 | h2) {
case 0: det = xombe__cfft_q15_first(x, m, 0, 0); break;
case 1: det = xombe__cfft_q15_first(x, m, 0, 1); break;
case 2: det = xombe__cfft_q15_first(x, m, 1, 0); break;
default: det = xombe__cfft_q15_first(x, m, 1, 1); break;
}
xombe__cfft_q15_tighten(&b, det);
for (len = 8; 2 * len <= m; len <<= 2) {
h1 = xombe__cfft_q15_halve(&b, &s);
h2 = xombe__cfft_q15_halve(&b, &s);
switch (h1 << 1 | h2) {
case 0: det = xombe__cfft_q15_r22(x, m, len, tw, 0, 0); break;
case 1: det = xombe__cfft_q15_r22(x, m, len, tw, 0, 1); break;
case 2: det = xombe__cfft_q15_r22(x, m, len, tw, 1, 0); break;
default: det = xombe__cfft_q15_r22(x, m, len, tw, 1, 1); break;
}
xombe__cfft_q15_tighten(&b, det);
}
if (len <= m) {
if (xombe__cfft_q15_halve(&b, &s))
xombe__cfft_q15_r2(x, m, tw, 1);
else
xombe__cfft_q15_r2(x, m, tw, 0);
}
return s;
}
#endif
+139
View File
@@ -0,0 +1,139 @@
#ifndef XOMBE_FMATH_H
#define XOMBE_FMATH_H
/* exp2, log2, and sincos for the inner loops: libm in float builds, which keep it as the reference, polynomials
within a few ulp of libm in q15 builds (XOMBE_KERNELS=q15) */
#include <math.h>
#include <stdint.h>
#include <string.h>
#include "xombe_config.h"
#if XOMBE_KERNELS_Q15
/* round to nearest for |x| < 2^22: x + 1.5*2^23 holds the integer in its fraction field, offset by 2^22 */
#define XOMBE_FMATH_RND 12582912.0f
static inline float xombe__fmath_from_bits(uint32_t u)
{
float f;
memcpy(&f, &u, sizeof(f));
return f;
}
static inline int32_t xombe__fmath_rnd_int(float t)
{
uint32_t u;
memcpy(&u, &t, sizeof(u));
return (int32_t)(u & 0x7fffffu) - 0x400000;
}
/* x = k + f, |f| <= 1/2, 2^f by the Cephes exp2f polynomial, 2^k in the exponent field. libm outside
(-126, 128), where the result may be subnormal, infinite, or NaN */
static inline float xombe__exp2f(float x)
{
float t, f, p;
int32_t k;
if (!(x > -126.0f && x < 128.0f))
return exp2f(x);
t = x + XOMBE_FMATH_RND;
k = xombe__fmath_rnd_int(t);
f = x - (t - XOMBE_FMATH_RND);
p = 1.535336188319500e-4f;
p = p * f + 1.339887440266574e-3f;
p = p * f + 9.618437357674640e-3f;
p = p * f + 5.550332471162809e-2f;
p = p * f + 2.402264791363012e-1f;
p = p * f + 6.931472028550421e-1f;
p = p * f + 1.0f;
if (k > 127) /* x >= 127.5, 2^128 is not a float */
return p * xombe__fmath_from_bits((uint32_t)(127 + 127) << 23) * 2.0f;
return p * xombe__fmath_from_bits((uint32_t)(k + 127) << 23);
}
/* x = 2^e * (1 + m), 1 + m in [sqrt(1/2), sqrt 2), ln(1 + m) by the Cephes logf polynomial, times log2(e) in two
parts (1 and log2(e) - 1) so m and e enter unrounded. libm for zero, subnormals, negatives, infinity, and NaN */
static inline float xombe__log2f(float x)
{
uint32_t u;
int32_t e;
float m, z, y, p;
if (!(x >= 1.17549435e-38f && x <= 3.40282347e38f))
return log2f(x);
memcpy(&u, &x, sizeof(u));
e = (int32_t)(u >> 23) - 127;
u = (u & 0x7fffffu) | 0x3f800000u;
if (u > 0x3fb504f3u) { /* above sqrt 2 */
u -= 0x00800000u;
e++;
}
m = xombe__fmath_from_bits(u) - 1.0f;
z = m * m;
p = 7.0376836292e-2f;
p = p * m - 1.1514610310e-1f;
p = p * m + 1.1676998740e-1f;
p = p * m - 1.2420140846e-1f;
p = p * m + 1.4249322787e-1f;
p = p * m - 1.6668057665e-1f;
p = p * m + 2.0000714765e-1f;
p = p * m - 2.4999993993e-1f;
p = p * m + 3.3333331174e-1f;
y = m * z * p - 0.5f * z;
return y * 0.44269504088896341f + m * 0.44269504088896341f + y + m + (float)e;
}
/* x = q*pi/2 + r, |r| <= pi/4, with pi/2 in three parts (Cody-Waite), the first two short enough that q*part is
exact for |q| < 2^11, then the Cephes sinf and cosf polynomials. libm for |x| >= 2^11 */
static inline void xombe__sincosf(float x, float *s, float *c)
{
float t, r, z, sp, cp;
int32_t q;
if (!(fabsf(x) < 2048.0f)) {
*s = sinf(x);
*c = cosf(x);
return;
}
t = x * 0.636619772f + XOMBE_FMATH_RND;
q = xombe__fmath_rnd_int(t);
t -= XOMBE_FMATH_RND;
r = x - t * 1.5703125f;
r -= t * 4.837512969970703125e-4f;
r -= t * 7.54978995489188216e-8f;
z = r * r;
sp = -1.9515295891e-4f;
sp = sp * z + 8.3321608736e-3f;
sp = sp * z - 1.6666654611e-1f;
sp = r + r * z * sp;
cp = 2.443315711809948e-5f;
cp = cp * z - 1.388731625493765e-3f;
cp = cp * z + 4.166664568298827e-2f;
cp = 1.0f - 0.5f * z + z * z * cp;
switch (q & 3) {
case 0: *s = sp; *c = cp; break;
case 1: *s = cp; *c = -sp; break;
case 2: *s = -sp; *c = -cp; break;
default: *s = -cp; *c = sp; break;
}
}
#else
static inline float xombe__exp2f(float x)
{
return exp2f(x);
}
static inline float xombe__log2f(float x)
{
return log2f(x);
}
static inline void xombe__sincosf(float x, float *s, float *c)
{
*s = sinf(x);
*c = cosf(x);
}
#endif
#endif
+12
View File
@@ -0,0 +1,12 @@
#include "../internal.h"
uint16_t xombe__lcg_next(uint16_t u)
{
return (uint16_t)((173u * u + 13849u) & 0xFFFFu);
}
int16_t xombe__lcg_draw(uint16_t *u)
{
*u = xombe__lcg_next(*u);
return (int16_t)(*u >= 32768 ? (int)*u - 65536 : (int)*u);
}
+297
View File
@@ -0,0 +1,297 @@
#ifndef XOMBE_Q15OPS_H
#define XOMBE_Q15OPS_H
/* fixed-point kernel DSP operations on packed int16 pairs (low half first) with ACLE semantics: Arm DSP
extension instructions where the target has them (__ARM_FEATURE_DSP), the same arithmetic in C elsewhere
a pair is a uint32_t of the two halves' bits, 32-bit results wrap modulo 2^32 as the instructions do (they
only set the Q flag) */
#include <stdint.h>
#include <string.h>
static inline int32_t q15_lo(uint32_t a)
{
return (int16_t)(uint16_t)(a & 0xffffu);
}
static inline int32_t q15_hi(uint32_t a)
{
return (int16_t)(uint16_t)(a >> 16);
}
#if defined(__ARM_FEATURE_DSP)
#include <arm_acle.h>
/* lo(a)*lo(b) + hi(a)*hi(b) */
static inline int32_t q15_smuad(uint32_t a, uint32_t b)
{
return __smuad((int16x2_t)a, (int16x2_t)b);
}
/* acc + lo(a)*lo(b) + hi(a)*hi(b) */
static inline int32_t q15_smlad(uint32_t a, uint32_t b, int32_t acc)
{
return __smlad((int16x2_t)a, (int16x2_t)b, acc);
}
/* acc + lo(a)*lo(b) + hi(a)*hi(b) in 64 bits */
static inline int64_t q15_smlald(uint32_t a, uint32_t b, int64_t acc)
{
return __smlald((int16x2_t)a, (int16x2_t)b, acc);
}
/* pair (lo(a), lo(b << 2)), PKHBT with a shifted top operand */
static inline uint32_t q15_pack_lsl2(uint32_t a, uint32_t b)
{
uint32_t r;
__asm__("pkhbt %0, %1, %2, lsl #2" : "=r"(r) : "r"(a), "r"(b));
return r;
}
/* x != 0 */
static inline int q15_clz32(uint32_t x)
{
return (int)__clz(x);
}
/* lo(a)*lo(b) - hi(a)*hi(b) + acc */
static inline int32_t q15_smlsd(uint32_t a, uint32_t b, int32_t acc)
{
return __smlsd((int16x2_t)a, (int16x2_t)b, acc);
}
/* lo(a)*hi(b) + hi(a)*lo(b) + acc */
static inline int32_t q15_smladx(uint32_t a, uint32_t b, int32_t acc)
{
return __smladx((int16x2_t)a, (int16x2_t)b, acc);
}
/* halves' sums and differences, saturated (QADD16, QSUB16) or halved and rounded down (SHADD16, SHSUB16) */
static inline uint32_t q15_qadd16(uint32_t a, uint32_t b)
{
return (uint32_t)__qadd16((int16x2_t)a, (int16x2_t)b);
}
static inline uint32_t q15_qsub16(uint32_t a, uint32_t b)
{
return (uint32_t)__qsub16((int16x2_t)a, (int16x2_t)b);
}
static inline uint32_t q15_shadd16(uint32_t a, uint32_t b)
{
return (uint32_t)__shadd16((int16x2_t)a, (int16x2_t)b);
}
static inline uint32_t q15_shsub16(uint32_t a, uint32_t b)
{
return (uint32_t)__shsub16((int16x2_t)a, (int16x2_t)b);
}
/* exchanged forms a + (-i)*b and a - (-i)*b for complex pairs (re, im): (lo(a) + hi(b), hi(a) - lo(b))
(QSAX) and (lo(a) - hi(b), hi(a) + lo(b)) (QASX), saturated or halved */
static inline uint32_t q15_qsax(uint32_t a, uint32_t b)
{
return (uint32_t)__qsax((int16x2_t)a, (int16x2_t)b);
}
static inline uint32_t q15_qasx(uint32_t a, uint32_t b)
{
return (uint32_t)__qasx((int16x2_t)a, (int16x2_t)b);
}
static inline uint32_t q15_shsax(uint32_t a, uint32_t b)
{
return (uint32_t)__shsax((int16x2_t)a, (int16x2_t)b);
}
static inline uint32_t q15_shasx(uint32_t a, uint32_t b)
{
return (uint32_t)__shasx((int16x2_t)a, (int16x2_t)b);
}
/* pair (lo(a), lo(b << 1)) */
static inline uint32_t q15_pack_lsl1(uint32_t a, uint32_t b)
{
uint32_t r;
__asm__("pkhbt %0, %1, %2, lsl #1" : "=r"(r) : "r"(a), "r"(b));
return r;
}
static inline uint32_t q15_rbit(uint32_t x)
{
return __rbit(x);
}
/* per-half unsigned max (USUB16 then SEL on its GE bits) */
static inline uint32_t q15_umax16(uint32_t a, uint32_t b)
{
uint32_t r;
__asm__("usub16 %0, %1, %2\n\tsel %0, %1, %2" : "=&r"(r) : "r"(a), "r"(b) : "cc");
return r;
}
/* a*b / 2^32 rounded to nearest, halves up */
static inline int32_t q15_smmulr(int32_t a, int32_t b)
{
int32_t r;
__asm__("smmulr %0, %1, %2" : "=r"(r) : "r"(a), "r"(b));
return r;
}
#else
/* each product fits in int32, sums wrap in uint32 as the instructions do */
static inline int32_t q15_smuad(uint32_t a, uint32_t b)
{
return (int32_t)((uint32_t)(q15_lo(a) * q15_lo(b)) + (uint32_t)(q15_hi(a) * q15_hi(b)));
}
static inline int32_t q15_smlad(uint32_t a, uint32_t b, int32_t acc)
{
return (int32_t)((uint32_t)acc + (uint32_t)(q15_lo(a) * q15_lo(b)) + (uint32_t)(q15_hi(a) * q15_hi(b)));
}
static inline int64_t q15_smlald(uint32_t a, uint32_t b, int64_t acc)
{
return (int64_t)((uint64_t)acc + (uint64_t)(int64_t)(q15_lo(a) * q15_lo(b)) +
(uint64_t)(int64_t)(q15_hi(a) * q15_hi(b)));
}
static inline uint32_t q15_pack_lsl2(uint32_t a, uint32_t b)
{
return (a & 0xffffu) | ((b << 2) & 0xffff0000u);
}
static inline int q15_clz32(uint32_t x)
{
int n = 0;
if (!(x & 0xffff0000u)) {
n += 16;
x <<= 16;
}
if (!(x & 0xff000000u)) {
n += 8;
x <<= 8;
}
if (!(x & 0xf0000000u)) {
n += 4;
x <<= 4;
}
if (!(x & 0xc0000000u)) {
n += 2;
x <<= 2;
}
return x & 0x80000000u ? n : n + 1;
}
static inline int32_t q15_smlsd(uint32_t a, uint32_t b, int32_t acc)
{
return (int32_t)((uint32_t)acc + (uint32_t)(q15_lo(a) * q15_lo(b)) - (uint32_t)(q15_hi(a) * q15_hi(b)));
}
static inline int32_t q15_smladx(uint32_t a, uint32_t b, int32_t acc)
{
return (int32_t)((uint32_t)acc + (uint32_t)(q15_lo(a) * q15_hi(b)) + (uint32_t)(q15_hi(a) * q15_lo(b)));
}
static inline uint32_t q15_pair(int32_t lo, int32_t hi)
{
return ((uint32_t)lo & 0xffffu) | (uint32_t)hi << 16;
}
static inline int32_t q15_sat(int32_t v)
{
return v > 32767 ? 32767 : v < -32768 ? -32768 : v;
}
/* right shift of a negative value is implementation-defined in C, these halve with a floor */
static inline int32_t q15_half(int32_t v)
{
return (v - (v & 1)) / 2;
}
static inline uint32_t q15_qadd16(uint32_t a, uint32_t b)
{
return q15_pair(q15_sat(q15_lo(a) + q15_lo(b)), q15_sat(q15_hi(a) + q15_hi(b)));
}
static inline uint32_t q15_qsub16(uint32_t a, uint32_t b)
{
return q15_pair(q15_sat(q15_lo(a) - q15_lo(b)), q15_sat(q15_hi(a) - q15_hi(b)));
}
static inline uint32_t q15_shadd16(uint32_t a, uint32_t b)
{
return q15_pair(q15_half(q15_lo(a) + q15_lo(b)), q15_half(q15_hi(a) + q15_hi(b)));
}
static inline uint32_t q15_shsub16(uint32_t a, uint32_t b)
{
return q15_pair(q15_half(q15_lo(a) - q15_lo(b)), q15_half(q15_hi(a) - q15_hi(b)));
}
static inline uint32_t q15_qsax(uint32_t a, uint32_t b)
{
return q15_pair(q15_sat(q15_lo(a) + q15_hi(b)), q15_sat(q15_hi(a) - q15_lo(b)));
}
static inline uint32_t q15_qasx(uint32_t a, uint32_t b)
{
return q15_pair(q15_sat(q15_lo(a) - q15_hi(b)), q15_sat(q15_hi(a) + q15_lo(b)));
}
static inline uint32_t q15_shsax(uint32_t a, uint32_t b)
{
return q15_pair(q15_half(q15_lo(a) + q15_hi(b)), q15_half(q15_hi(a) - q15_lo(b)));
}
static inline uint32_t q15_shasx(uint32_t a, uint32_t b)
{
return q15_pair(q15_half(q15_lo(a) - q15_hi(b)), q15_half(q15_hi(a) + q15_lo(b)));
}
static inline uint32_t q15_pack_lsl1(uint32_t a, uint32_t b)
{
return (a & 0xffffu) | ((b << 1) & 0xffff0000u);
}
static inline uint32_t q15_rbit(uint32_t x)
{
x = (x >> 1 & 0x55555555u) | (x & 0x55555555u) << 1;
x = (x >> 2 & 0x33333333u) | (x & 0x33333333u) << 2;
x = (x >> 4 & 0x0f0f0f0fu) | (x & 0x0f0f0f0fu) << 4;
x = (x >> 8 & 0x00ff00ffu) | (x & 0x00ff00ffu) << 8;
return x >> 16 | x << 16;
}
static inline uint32_t q15_umax16(uint32_t a, uint32_t b)
{
uint32_t l = (a & 0xffffu) > (b & 0xffffu) ? a & 0xffffu : b & 0xffffu;
return ((a >> 16) > (b >> 16) ? a & 0xffff0000u : b & 0xffff0000u) | l;
}
static inline int32_t q15_smmulr(int32_t a, int32_t b)
{
return (int32_t)(((int64_t)a * b + 0x80000000) >> 32);
}
#endif
/* 64 for x = 0 */
static inline int q15_clz64(uint64_t x)
{
uint32_t h = (uint32_t)(x >> 32), l = (uint32_t)x;
if (h)
return q15_clz32(h);
return l ? 32 + q15_clz32(l) : 64;
}
/* p need only be 2-byte aligned */
static inline uint32_t q15_ld2(const int16_t *p)
{
uint32_t v;
memcpy(&v, p, 4);
return v;
}
#endif
+65
View File
@@ -0,0 +1,65 @@
#include <math.h>
#include "../internal.h"
/* sin(pi*r/m) for m > 0, r reduced exactly to |r| <= m/2 first so the argument carries a single rounding
however large r is (the reduced |r| must be exact in float: m < 2^24) */
float xombe__sin_ratio(long r, long m)
{
r %= 2 * m;
if (r > m)
r -= 2 * m;
else if (r < -m)
r += 2 * m;
if (2 * r > m)
r = m - r;
else if (2 * r < -m)
r = -m - r;
return sinf(XOMBE_PI_F * ((float)r / (float)m));
}
/* cos(2 pi i/(n - 1)) as sin(pi (4i + n - 1)/(2(n - 1))) */
void xombe__hamming(float *w, int n)
{
int i;
for (i = 0; i < n; i++)
w[i] = 0.54f - 0.46f * xombe__sin_ratio(4L * i + (n - 1), 2L * (n - 1));
}
/* over i = 0..n-1 the cosine sums to 1 and its square to (n + 1)/2 (n > 3) */
float xombe__hamming_sum2(int n)
{
return 0.2916f * (float)n + 0.1058f * (float)(n + 1) - 0.4968f;
}
/* sin(n*x)/sin(x) at x = pi*p/m, |p| < m */
static float dirichlet(int n, long p, long m)
{
return p == 0 ? (float)n : xombe__sin_ratio((long)n * p, m) / xombe__sin_ratio(p, m);
}
/* xombe__sin_ratio(t, g) for g a power of two, without divisions */
static float sin_ratio_pow2(long t, long g)
{
t &= 2 * g - 1;
if (t > g)
t -= 2 * g;
if (2 * t > g)
t = g - t;
else if (2 * t < -g)
t = -g - t;
return sinf(XOMBE_PI_F * ((float)t * (1.0f / (float)g)));
}
/* transform of the centred xombe__hamming(n) at q/g cycles/sample (0 <= q < g/2): Dirichlet kernels at
x = pi*q/g and x +/- pi/(n - 1), over the common denominator g*(n - 1) */
float xombe__hamming_dtft(int n, long q, long g)
{
long p = q * (n - 1), m = g * (n - 1);
/* for g a power of two the centre kernel's ratios reduce exactly to multiples of 1/g: sin_ratio(n*p, m)
reduces n*p to (n - 1) times n*q reduced mod 2g, and the float quotient r/m equals the exact product
t*(1/g) */
if (q > 0 && (g & (g - 1)) == 0)
return 0.54f * (sin_ratio_pow2((long)n * q, g) / sin_ratio_pow2(q, g)) +
0.23f * (dirichlet(n, p - g, m) + dirichlet(n, p + g, m));
return 0.54f * dirichlet(n, p, m) + 0.23f * (dirichlet(n, p - g, m) + dirichlet(n, p + g, m));
}
+154
View File
@@ -0,0 +1,154 @@
#include <string.h>
#include "../internal.h"
#include "dsd_state.h"
/* D-STAR decoder on the AMBE+2 set machinery and synthesis (dec/decoder.c), differing in frame logic here,
parameters (params.c), and ds_rules */
/* xombe__ds_harm_voicing leaves vh above L alone */
static void harm_voicing(const uint8_t vb[8], float f0, int L, uint8_t vh[XOMBE_LMAX + 1])
{
memset(vh, 0, XOMBE_LMAX + 1);
xombe__ds_harm_voicing(vb, f0, L, vh);
}
static const struct xombe_dec_rules ds_rules = {harm_voicing, XOMBE_DS_LAMBDA_DECAY};
void xombe__dsd_logic_init(xombe_dsd_logic *s, xombe_dec_core *d)
{
memset(s, 0, sizeof(*s));
d->rules = &ds_rules;
}
static void voice(xombe_dec_core *d, const int b[9])
{
xombe_params p;
xombe_set c;
uint8_t v1[8];
const uint8_t *v2 = xombe__ds_vuv[b[1] & 15];
memset(&p, 0, sizeof(p));
p.f0 = xombe__ds_f0(b[0]);
p.L = xombe__ds_L(b[0]);
xombe__ds_amps(b, p.L, d->pi.L, d->pi.a, d->pi.gamma, NULL, &p.gamma, p.a);
XOMBE_TAP(d, XOMBE_STAGE_DEQUANT, p.f0, p.a + 1, p.L);
xombe__f3_first_half(d->pi.v2, v2, v1);
xombe__smooth(d, p.a, p.L, p.f0);
XOMBE_TAP(d, XOMBE_STAGE_SMOOTH, p.f0, p.a + 1, p.L);
xombe__dec_set_from_params(&c, XOMBE_CLASS_VOICE, p.f0, p.L, p.a, v2);
xombe__dec_play(d, &c, v1, &p, v2);
}
/* concealed and null frames: the second half is a fresh copy without the repeat flag, so a silence set there
plays as the mute set */
static void play_pair(xombe_dec_core *d, const xombe_set *s)
{
d->p1 = *s;
d->p1.repeat = 1;
d->p2 = *s;
d->p2.repeat = 0;
}
static void conceal(xombe_dsd_logic *s, xombe_dec_core *d, int c)
{
play_pair(d, c == XOMBE_CONCEAL_MUTE ? &d->mute : &d->played);
s->log = c == XOMBE_CONCEAL_MUTE ? XOMBE_DSD_LOG_MUTE : XOMBE_DSD_LOG_REPEAT;
}
/* the rest of the frame's decision once c, what plays, is known */
static void decided(xombe_dec_core *d, int c)
{
d->decision.conceal = (enum xombe_conceal)c;
d->decision.run = d->run;
d->decision.mute_src = c == XOMBE_CONCEAL_MUTE ? d->mute_src : -1;
d->prev_concealed = c != XOMBE_CONCEAL_NONE;
}
void xombe__dsd_start_frame(xombe_dsd_logic *s, xombe_dec_core *d, const xombe_ds_frame *f, unsigned flags,
int eps_t, int eps1)
{
xombe_decision *dc = &d->decision;
xombe_ds_flags ef;
int c = XOMBE_CONCEAL_NONE;
d->frame++;
dc->e0 = dc->e1 = -1;
if (!f) {
dc->cls = XOMBE_CLASS_ERASURE;
dc->bf = dc->hb = 0;
s->eT = s->e1 = 0;
c = xombe__conceal_decide(d, 1, 0);
conceal(s, d, c);
decided(d, c);
return;
}
ef.bf = (flags & XOMBE_FLAG_BF) != 0;
ef.hb = (flags & XOMBE_FLAG_HB) != 0;
ef.eT = eps_t < 6 ? 0 : eps_t;
ef.e1 = eps_t < 6 ? 0 : eps1;
dc->bf = ef.bf;
dc->hb = ef.hb;
s->eT = d->eps_t = ef.eT;
s->e1 = d->eps_1 = ef.e1;
if (f->cls == XOMBE_DS_NULL) {
/* fixed silence set, the memory keeps its amplitudes but its class becomes silence, so the next voice
frame starts at half amplitude. bf and hb are ignored */
xombe_set z;
dc->cls = XOMBE_CLASS_SILENCE;
xombe__conceal_decide(d, 0, 0);
xombe__dec_silence_set(&z);
play_pair(d, &z);
xombe__pred_store_other(&d->pi, XOMBE_CLASS_SILENCE);
s->log = XOMBE_DSD_LOG_NULL;
} else if (f->cls == XOMBE_DS_VOICE && ef.bf) {
/* bad voice frame updates the memory as if good (unless hb, then nothing changes) and plays a repeat of
the last played set, never a mute */
xombe_set last = d->played;
dc->cls = XOMBE_CLASS_VOICE;
xombe__conceal_decide(d, 1, 0); /* counts as concealed */
c = XOMBE_CONCEAL_REPEAT;
if (ef.hb) {
s->log = XOMBE_DSD_LOG_MUTE;
} else {
voice(d, f->b);
s->log = XOMBE_DSD_LOG_VOICE;
}
play_pair(d, &last);
} else if (f->cls == XOMBE_DS_VOICE) {
dc->cls = XOMBE_CLASS_VOICE;
c = xombe__conceal_decide(d, 0, ef.hb);
if (c != XOMBE_CONCEAL_NONE) {
conceal(s, d, c);
} else {
voice(d, f->b);
s->log = XOMBE_DSD_LOG_VOICE;
}
} else {
/* played as the AMBE+2 tone frame of its ID and level, an unknown tone index is a bad frame */
dc->cls = XOMBE_CLASS_TONE;
c = xombe__conceal_decide(d, ef.bf || f->tid < 0, ef.hb);
if (c != XOMBE_CONCEAL_NONE) {
conceal(s, d, c);
} else {
static const uint8_t none[8];
xombe_set t;
xombe__tone_set(&t, f->tid, f->AD);
xombe__dec_play(d, &t, none, NULL, none);
s->log = XOMBE_DSD_LOG_TONE;
}
}
decided(d, c);
}
static void start_bits(xombe_dec *d, const uint8_t bits[7], unsigned flags)
{
xombe_ds_frame f;
uint8_t data[XOMBE_DS_DATA_BITS];
if (flags & XOMBE_FLAG_LOST) {
xombe__dsd_start_frame(&d->ds, &d->c, NULL, flags, d->err_t, d->err_1);
return;
}
xombe__ds_unpack(bits, data);
xombe__ds_frame_from_data(data, &f);
xombe__dsd_start_frame(&d->ds, &d->c, &f, flags, d->err_t, d->err_1);
}
const struct xombe_dec_ops xombe__dsd_ops = {start_bits};
+28
View File
@@ -0,0 +1,28 @@
#ifndef XOMBE_DSD_STATE_H
#define XOMBE_DSD_STATE_H
/* D-STAR frame logic on the shared decoder core (decoder.c), state xombe_dsd_logic in state.h */
#include "dstar_internal.h"
/* what a frame logged, a bad voice frame logs voice (or mute with hb set) but plays a repeat */
enum {
XOMBE_DSD_LOG_VOICE,
XOMBE_DSD_LOG_TONE,
XOMBE_DSD_LOG_NULL,
XOMBE_DSD_LOG_REPEAT,
XOMBE_DSD_LOG_MUTE
};
/* sets up s and the D-STAR rules of a reset d */
void xombe__dsd_logic_init(xombe_dsd_logic *s, xombe_dec_core *d);
/* frame logic of one frame up to its sets. f from xombe__ds_frame_from_bits, NULL for a lost frame. flags: the
error rule's XOMBE_FLAG_BF and XOMBE_FLAG_HB, eps_t and eps1 its error counts (xombe_fec_stats). sets the
decision's e0 and e1 to -1 */
void xombe__dsd_start_frame(xombe_dsd_logic *s, xombe_dec_core *d, const xombe_ds_frame *f, unsigned flags,
int eps_t, int eps1);
/* xombe_dec's frame logic for D-STAR */
extern const struct xombe_dec_ops xombe__dsd_ops;
#endif
+179
View File
@@ -0,0 +1,179 @@
#include <math.h>
#include <string.h>
#include "dstar_enc.h"
#include "../tables/dstar_enc_tables.h"
#include "../common/prof.h"
#define DS_GAIN_DB 0.2f
#define DS_GAIN_LOG2 (DS_GAIN_DB / 6.02059991f) /* dB -> log2 amplitude */
XOMBE_STATIC_ASSERT(sizeof(xombe_ds_enc) <= XOMBE_DS_ENC_STATE, ds_enc_state_fits_XOMBE_DS_ENC_STATE);
void xombe__ds_enc_reset(xombe_ds_enc *s)
{
s->s_vn = XOMBE_DS_S_VN;
xombe__ds_mirror_init(&s->mirror);
}
void xombe__ds_enc_init(xombe_enc *e)
{
xombe__ds_enc_reset(XOMBE_DS_ENC(e));
xombe__ds_tone_init(&XOMBE_DS_ENC(e)->tones);
XOMBE_DS_ENC(e)->ws.cap = XOMBE_CQ_CAP;
}
void xombe__ds_m_noise(int N, int b0, float mn[8])
{
int i = (N - XOMBE_DS_MN_N_MIN) / 2, lo, hi, j;
const unsigned short *r;
if (i < 0)
i = 0;
if (i > XOMBE_DS_MN_WINDOWS - 1)
i = XOMBE_DS_MN_WINDOWS - 1;
lo = xombe__ds_mn_lo[i];
hi = lo + xombe__ds_mn_cnt[i] - 1;
if (b0 < lo)
b0 = lo;
if (b0 > hi)
b0 = hi;
r = xombe__ds_mn[xombe__ds_mn_off[i] + b0 - lo];
for (j = 0; j < 8; j++)
mn[j] = (float)r[j] * (1.0f / XOMBE_DS_MN_SCALE);
}
int xombe__ds_b1_search(const float a[8], const float w[8])
{
float best = 0.0f;
int c, j, bi = 0;
for (c = 0; c < 16; c++) {
const unsigned char *V = xombe__ds_vuv[c];
float cost = 0.0f;
if (c == XOMBE_DS_B1_SKIP)
continue;
for (j = 0; j < 8; j++) {
float d = V[j] ? 1.0f - a[j] : a[j];
cost += w[j] * d * d;
}
if (c == 0 || cost < best) {
best = cost;
bi = c;
}
}
return bi;
}
int xombe__ds_soft(const float m[8], const float mn[8], float s_vn, int speech2, float a[8])
{
int j, any = 0;
for (j = 0; j < 8; j++) {
a[j] = speech2 ? xombe__voicing_map(s_vn * (m[j] / mn[j])) : 0.0f;
any |= a[j] > 0.5f;
}
return !any;
}
void xombe__ds_enc_voicing(xombe_enc *e, xombe_fe_frame *a, xombe_be_ns *ns)
{
xombe_ds_enc *s = XOMBE_DS_ENC(e);
xombe_ds_enc_frame *fr = &s->fr;
memset(fr, 0, sizeof(*fr));
fr->no_band_voiced = 1;
fr->cls = XOMBE_DS_CLS_NULL;
if (e->cfg.tones) {
fr->det = s->tones.ndet;
fr->trk = s->tones.ntrk;
fr->tone = s->tones.tone;
}
if (fr->tone.on) {
fr->cls = fr->tone.T < 0 ? XOMBE_DS_CLS_KNOX : XOMBE_DS_CLS_TONE;
} else if (a->active || !e->cfg.dstar_dtx) {
fr->cls = XOMBE_DS_CLS_VOICE;
fr->voice = 1;
XOMBE_PF(8, xombe__fe_voice(e, a));
fr->b0 = xombe__ds_b0_from_f0(a->fstar);
fr->f0 = xombe__ds_f0(fr->b0);
fr->L = xombe__ds_L(fr->b0);
XOMBE_PF(9, xombe__voicing_metric_sp(e, xombe__fe_s2_prepared(e, a), fr->f0, fr->m, fr->w));
xombe__ds_m_noise(a->nw, fr->b0, fr->mn);
fr->no_band_voiced = xombe__ds_soft(fr->m, fr->mn, s->s_vn, a->speech2, fr->a);
fr->b1 = xombe__ds_b1_search(fr->a, fr->w);
memcpy(fr->V, xombe__ds_vuv[fr->b1], 8);
}
ns->no_band_voiced[0] = ns->no_band_voiced[1] = fr->no_band_voiced;
ns->mem = &s->ns_mem;
if (e->cfg.ns)
xombe__ns_bin_voicing(fr->V, 0, ns->vbin);
}
void xombe__ds_enc_targets(const xombe_spec *S, float win_sum2, float f0, int L, const float *G, const uint8_t V[8],
float at[XOMBE_LMAX + 1])
{
float P[XOMBE_SPEC_BINS];
int l;
xombe__kern_bin_power(S, win_sum2, P);
xombe__enc_integrate(P, L, f0, at);
xombe__enc_hf_precomp(at, L, f0);
if (G) {
uint8_t vh[XOMBE_LMAX + 1];
float da[XOMBE_LMAX + 1];
xombe__ds_harm_voicing(V, f0, L, vh);
xombe__ns_harmonic_offsets(G, L, f0, vh, da);
for (l = 1; l <= L; l++)
at[l] += da[l];
}
for (l = 1; l <= L; l++) {
at[l] += DS_GAIN_LOG2;
if (at[l] < XOMBE_AMP_MIN)
at[l] = XOMBE_AMP_MIN;
}
}
void xombe__ds_enc_amps(xombe_ds_enc *s, int b0, int b1, const float at[XOMBE_LMAX + 1], int b[9])
{
float w[XOMBE_LMAX + 1], pt[XOMBE_LMAX + 1];
xombe_cq_result res;
int L = xombe__ds_L(b0), k;
xombe__cq_amp_weights(at, L, XOMBE_CQ_QWEIGHT, XOMBE_CQ_WEIGHT_FLOOR, w);
xombe__ds_mirror_predict(&s->mirror, L, pt);
XOMBE_PF(13, xombe__cq_quantize(&s->ws, &xombe__amp_dstar, at, L, pt, s->mirror.G, w, 1, XOMBE_CQ_N_PAIRS,
XOMBE_CQ_N_GAIN, XOMBE_CQ_ITERS, XOMBE_CQ_CLIP_PASSES, &res));
XOMBE_PF_ADD(15, L);
b[0] = b0;
b[1] = b1;
for (k = 2; k < 9; k++)
b[k] = res.b[k];
xombe__ds_mirror_commit(&s->mirror, b, NULL);
}
void xombe__ds_enc_frame(xombe_enc *e, const xombe_fe_frame *a, const xombe_be_ns *ns, uint8_t out[7])
{
static const uint8_t null_bits[7] = XOMBE_DS_NULL_BITS;
xombe_ds_enc *s = XOMBE_DS_ENC(e);
const xombe_ds_enc_frame *fr = &s->fr;
float at[XOMBE_LMAX + 1];
int b[9];
if (fr->cls == XOMBE_DS_CLS_KNOX) { /* voice frame from the tone table, no VAD gate or suppression */
int k;
for (k = 0; s->tones.knox[k].id != -fr->tone.T; k++)
;
xombe__ds_knox_amps(s, k, fr->tone.level, b);
s->fr.b0 = b[0];
s->fr.b1 = b[1];
xombe__ds_fields_bits(b, out);
return;
}
if (!fr->voice) { /* tone and NULL frames leave the mirror alone */
if (fr->cls == XOMBE_DS_CLS_TONE) {
uint8_t d[XOMBE_DS_DATA_BITS];
xombe__ds_tone_bits(fr->tone.T, xombe__ds_tone_q(fr->tone.level), d);
xombe__ds_pack(d, out);
} else {
memcpy(out, null_bits, 7);
}
return;
}
XOMBE_PF(14, xombe__ds_enc_targets(&a->S2, a->win_sum2, fr->f0, fr->L, e->cfg.ns ? ns->G2 : NULL, fr->V,
at));
xombe__ds_enc_amps(s, fr->b0, fr->b1, at, b);
xombe__ds_fields_bits(b, out);
}
+103
View File
@@ -0,0 +1,103 @@
#ifndef XOMBE_DSTAR_ENC_H
#define XOMBE_DSTAR_ENC_H
/* D-STAR back end, phases B and D of enc/frontend.h (voice, NULL, tone, and Knox frames). encoder.c calls:
xombe__ds_tone_push every call with cfg.tones, right after the input is taken, even before the delay
has passed
xombe__ds_enc_voicing phase B, after xombe__fe_analyze and the AMBE+2 phase B: class (tone or Knox from
the tone pipeline, else NULL when cfg.dstar_dtx and inactive, else voice), b0, and
band voicing. tone and Knox frames count as unvoiced like NULL frames. voice frames
share the prepared S2 with AMBE+2. fills ns->no_band_voiced[2] (no a_j above 1/2),
ns->mem, and with cfg.ns ns->vbin (band flags without the +250 Hz OR)
xombe__fe_background phase C, D-STAR gains in ns->G1/G2 when cfg.ns, the frame uses G2
xombe__ds_enc_force_tone phase D for a forced tone, before xombe__ds_enc_frame: tone frame at the AMBE+2
level ad, a Knox ID a Knox frame
xombe__ds_enc_frame phase D, writes the voice bits
state: e->ds, zeroed by xombe_enc_init before xombe__ds_enc_init, XOMBE_DS_ENC(e) is the typed view */
#include "../enc/frontend.h"
#include "../common/cquant.h"
#include "dstar_internal.h"
#define XOMBE_DS_S_VN 0.35f /* voicing scale on the noise-normalised metric */
/* tone pipeline (dstar_tone.c). after the call appending input frame t, the detector has run on t - 1 (segment
ends 20 samples into t), the run rule has decided t - 3 (reads two detections ahead), and t - 4, the encoded
frame, has its final tone (tone-in-noise reads the next frame's decision) */
#define XOMBE_DS_TONE_RING 4 /* indexed by frame mod 4 */
#define XOMBE_DS_NZ_FLOOR 50 /* noise floor is the quietest of the last N + 1 frames */
typedef struct {
int on; /* 0: no tone */
int T; /* D-STAR tone index, or -ID for a Knox tone */
float level; /* real-valued AMBE+2 level, 127 + level term / 0.711 + TONE_ADOFF */
} xombe_ds_tone;
typedef struct {
int n_frames;
xombe_ds_tone detected[XOMBE_DS_TONE_RING];
int run[XOMBE_DS_TONE_RING]; /* run length ending at each detection, capped at 3 */
xombe_ds_tone confirmed[XOMBE_DS_TONE_RING]; /* detections the run rule keeps, and held tones */
xombe_ds_tone held;
int hold_left;
float level_db[XOMBE_DS_NZ_FLOOR + 1]; /* ring of frame levels */
int n_levels, level_pos;
xombe_ds_tone ndet, ntrk, tone; /* encoded frame's detection, run-rule tone, and final tone */
int nknox; /* Knox IDs in the tone table, with their pairs */
xombe_tone_pair knox[XOMBE_TONE_KNOX_COUNT];
float knox_f0[XOMBE_TONE_KNOX_COUNT]; /* table f0 in cycles/sample, and harmonics */
uint8_t knox_l[XOMBE_TONE_KNOX_COUNT][2];
} xombe_ds_tones;
#define XOMBE_DS_CLS_VOICE 0
#define XOMBE_DS_CLS_NULL 1
#define XOMBE_DS_CLS_TONE 2
#define XOMBE_DS_CLS_KNOX 3
/* phase B result */
typedef struct {
int cls; /* XOMBE_DS_CLS_* */
xombe_ds_tone det, trk, tone; /* detection, run rule, final */
int voice; /* 1 voice, 0 NULL (dtx) */
int b0, b1, L;
float f0;
float m[8], mn[8]; /* band metric and its white-noise reference */
float a[8], w[8]; /* soft voicing after the VAD gate, band weights */
uint8_t V[8]; /* xombe__ds_vuv[b1], 0 on NULL frames */
int no_band_voiced; /* no a_j above 1/2, 1 on NULL frames */
} xombe_ds_enc_frame;
typedef struct {
float s_vn;
xombe_ns_mem ns_mem; /* D-STAR gain smoothing */
xombe_ds_mirror mirror; /* decoder's prediction memory */
xombe_ds_tones tones;
xombe_ds_enc_frame fr; /* phase B -> D */
xombe_cq_ws ws; /* only the last L's maps live between frames */
} xombe_ds_enc;
#define XOMBE_DS_ENC(e) ((xombe_ds_enc *)(void *)(e)->ds.bytes)
void xombe__ds_enc_init(xombe_enc *e);
/* every call with cfg.tones, even when the front end returns no frame */
void xombe__ds_tone_push(xombe_enc *e);
void xombe__ds_tone_init(xombe_ds_tones *s);
/* Knox voice frame fields for entry k at level AD, committed to the mirror */
void xombe__ds_knox_amps(xombe_ds_enc *s, int k, float AD, int b[9]);
void xombe__ds_enc_voicing(xombe_enc *e, xombe_fe_frame *a, xombe_be_ns *ns);
void xombe__ds_enc_force_tone(xombe_enc *e, int id, int ad);
void xombe__ds_enc_frame(xombe_enc *e, const xombe_fe_frame *a, const xombe_be_ns *ns, uint8_t out[7]);
/* pieces run by test/dstar_dump_enc_be.c on recorded inputs */
void xombe__ds_enc_reset(xombe_ds_enc *s); /* s_vn default, mirror reset */
void xombe__ds_m_noise(int N, int b0, float mn[8]); /* tables/dstar_enc_tables.h */
int xombe__ds_b1_search(const float a[8], const float w[8]);
/* noise normalisation and VAD gate, returns no_band_voiced */
int xombe__ds_soft(const float m[8], const float mn[8], float s_vn, int speech2, float a[8]);
/* targets at[1..L], G NULL for no noise suppression */
void xombe__ds_enc_targets(const xombe_spec *S, float win_sum2, float f0, int L, const float *G, const uint8_t V[8],
float at[XOMBE_LMAX + 1]);
/* weights, closed-loop quantization against the mirror, and commit */
void xombe__ds_enc_amps(xombe_ds_enc *s, int b0, int b1, const float at[XOMBE_LMAX + 1], int b[9]);
#endif
+171
View File
@@ -0,0 +1,171 @@
#ifndef XOMBE_DSTAR_INTERNAL_H
#define XOMBE_DSTAR_INTERNAL_H
/* D-STAR (AMBE 2400) core
frame: 72 bits (9 bytes, MSB first), three interleaved 24-bit words:
A = Golay(24,12)(da), B = Golay(24,12)(db) ^ pn24(da), C = 24 uncoded bits
data: d[0..47] = da, db, C (MSB first)
fields: b0..b8 are 7, 4, 6, 9, 7, 4, 4, 4, 3 bits, scattered over d */
#include <stdint.h>
#include "../internal.h"
#include "../tables/tables.h"
#include "../tables/dstar_tables.h"
#define XOMBE_DS_FRAME_BYTES 9
#define XOMBE_DS_DATA_BITS 48
#define XOMBE_DS_GOLAY_BAD 4 /* error count of an uncorrectable Golay(24,12) word */
/* special b0 codes, b0 0..123 are voice */
#define XOMBE_DS_B0_VOICE_MAX 123
#define XOMBE_DS_B0_SILENCE 124 /* standard silence frame, XOMBE_DS_NULL_FRAME */
#define XOMBE_DS_B0_NULL125 125 /* plays as 124 */
#define XOMBE_DS_B0_TONE 126
#define XOMBE_DS_B0_FILL 127 /* DTX fill (ff x 9), plays as 124 */
/* fields 124 0 4 165 41 10 7 7 5, both Golay words clean */
#define XOMBE_DS_NULL_FRAME {0x9E, 0x8D, 0x32, 0x88, 0x26, 0x1A, 0x3F, 0x61, 0xE8}
#define XOMBE_DS_NULL_BITS {0xF8, 0x54, 0xAA, 0x9D, 0xE8, 0x0A, 0x00} /* its voice bits */
/* null frames play f0 250 Hz, L 14, all unvoiced, M 0.1 */
#define XOMBE_DS_NULL_F0 (250.0f / 8000.0f)
#define XOMBE_DS_NULL_L 14
#define XOMBE_DS_NULL_M 0.1f
#define XOMBE_DS_B1_SKIP 4 /* plays as 12, never sent */
#define XOMBE_DS_B1_VOICED 15 /* all bands voiced */
#define XOMBE_DS_GAIN_MAX 13.0f
/* D-STAR clamps a to [-15, 15 - 1e-9], which rounds to 15.0f (AMBE+2: 15 - 2^-11) */
#define XOMBE_DS_AMP_MAX 15.0f
#define XOMBE_DS_LAMBDA_DECAY (20.0f / 2048.0f) /* smoothing level decay per frame (AMBE+2: 0.0098) */
/* every 7-bit b0 is voice, tone, or null, so xombe__ds_classify never returns XOMBE_DS_ERASURE, it is for
callers that lose a frame */
enum {
XOMBE_DS_VOICE = 0,
XOMBE_DS_TONE,
XOMBE_DS_NULL,
XOMBE_DS_ERASURE
};
/* everything the receive side learns from 9 bytes */
typedef struct {
uint32_t A, B, C; /* deinterleaved 24-bit words as received */
uint32_t pn; /* pn24(da) */
int da, db; /* corrected 12-bit data of A and of B ^ pn */
int ea, eb; /* corrected errors, XOMBE_DS_GOLAY_BAD = uncorrectable */
uint8_t d[XOMBE_DS_DATA_BITS]; /* one bit per byte */
int b[9];
int cls; /* XOMBE_DS_VOICE, TONE, or NULL */
int T, AD; /* tone frames: 8-bit tone index and AMBE+2 level 8..127, else -1 */
int tid; /* AMBE+2 tone ID, -1 for invalid T or not a tone frame */
} xombe_ds_frame;
/* Golay(24,12) = Golay(23,12) (data in bits 23..12) || even parity. decode returns the error count 0..3, or 4
when uncorrectable (three corrections and a parity mismatch), and the data bits as the 23-bit decoder
corrected them */
uint32_t xombe__ds_golay24_encode(uint32_t data12);
int xombe__ds_golay24_decode(uint32_t cw24, int *data12);
/* B's 24-bit whitening sequence seeded from A's data, AMBE+2's LCG, 24 steps */
uint32_t xombe__ds_pn24(int da);
/* A = bits 0, 6, ..., 66, 1, 7, ..., 67, B = A + 2, C = A + 4, MSB first */
void xombe__ds_deinterleave(const uint8_t in[9], uint32_t *A, uint32_t *B, uint32_t *C);
void xombe__ds_interleave(uint32_t A, uint32_t B, uint32_t C, uint8_t out[9]);
void xombe__ds_get_fields(const uint8_t d[48], int b[9]);
void xombe__ds_put_fields(const int b[9], uint8_t d[48]); /* each field masked to its width */
int xombe__ds_classify(int b0);
/* full receive path: FEC, data bits, fields, class, and tone fields */
void xombe__ds_fec_decode(const uint8_t in[9], xombe_ds_frame *f);
/* the part after FEC: d, fields, class, and tone fields (A, B, C, pn, da, db, ea, eb untouched) */
void xombe__ds_frame_from_data(const uint8_t d[48], xombe_ds_frame *f);
/* data bits <-> voice bits (7 bytes, MSB first, the last bit zero) */
void xombe__ds_pack(const uint8_t d[48], uint8_t bits[7]);
void xombe__ds_unpack(const uint8_t bits[7], uint8_t d[48]);
/* xombe_fec_encode and xombe_fec_decode for D-STAR, st not NULL */
void xombe__ds_fec_encode_bits(const uint8_t bits[7], uint8_t frame[9]);
unsigned xombe__ds_fec_decode_bits(xombe_fec *fec, const uint8_t frame[9], uint8_t bits[7], xombe_fec_stats *st);
/* xombe_tone_frame for D-STAR */
int xombe__ds_tone_frame_id(int id, int ad, uint8_t out[9]);
void xombe__ds_encode_bits(const uint8_t d[48], uint8_t out[9]);
/* always writes out, a field out of range clamped to its width. returns 0, or -1 if any was clamped */
int xombe__ds_encode_fields(const int b[9], uint8_t out[9]);
/* xombe__ds_encode_fields writing voice bits */
int xombe__ds_fields_bits(const int b[9], uint8_t bits[7]);
/* tone frames carry the level in half steps q = floor(2*level) clamped to 16..254: F = q/2 - 8 in bits
12..16, 43, 44 and q & 1 in bit 17, so the decoder plays AD = q/2 + (q & 1), rounded half up, capped at 127 */
int xombe__ds_tone_q(float level);
/* AMBE+2 level ad as a tone level: q = 2*ad - 1, which plays as AD ad */
#define XOMBE_DS_AD_LEVEL(ad) ((float)(ad) - 0.5f)
/* D-STAR tone index of an AMBE+2 tone ID, -1 if it has none (Knox) */
int xombe__ds_tone_code(int id);
void xombe__ds_tone_bits(int T, int q, uint8_t d[48]);
void xombe__ds_tone_frame(int T, int q, uint8_t out[9]);
/* level AD = 4*bits(12..16) + bit 17 + bits(43,44) + 8, capped at 127 */
int xombe__ds_tone_index(const uint8_t d[48]);
int xombe__ds_tone_level(const uint8_t d[48]);
/* fitted error rule, stateful over the stream. per frame, with eT = ea + eb:
er = 0.95*er + 0.05*eT/48, bf (repeat) iff ea >= 4, hb (mute) iff er > 0.096,
smoothing inputs eT and e1 = eb, both 0 when eT < 6. null frames ignore bf and hb but still advance er */
typedef struct {
float er;
} xombe_ds_err;
typedef struct {
int bf, hb, eT, e1;
} xombe_ds_flags;
void xombe__ds_err_init(xombe_ds_err *s);
void xombe__ds_err_update(xombe_ds_err *s, int ea, int eb, xombe_ds_flags *out);
/* D-STAR amplitude tables: rho 0.8, gain recursion 0, gmax 13, clamp [-15, XOMBE_DS_AMP_MAX], fitted codebooks,
and their ok masks */
extern const xombe_amp_tables xombe__amp_dstar;
/* voice frames fill everything up to a, others only cls, b, and the tone fields */
typedef struct {
int cls;
int b[9];
float f0; /* cycles/sample */
int L;
uint8_t V[8]; /* 500 Hz band flags, xombe__ds_vuv[b1] */
uint8_t vl[XOMBE_LMAX + 1]; /* per-harmonic voicing vl[1..L] */
float Tv[XOMBE_LMAX + 1]; /* spectral shape before mean removal, Tv[1..L] */
float G;
float a[XOMBE_LMAX + 1]; /* log2 amplitudes a[1..L], a[L + 1..XOMBE_LMAX] = a[L] */
int T, tid, AD; /* tone frames, else -1 */
} xombe_ds_params;
/* dequantizer prediction memory, a extended to a[L + 1..XOMBE_LMAX] = a[L], reset L 15, a 0, G 0, copyable by
assignment */
typedef struct {
int L;
float G;
float a[XOMBE_LMAX + 1];
} xombe_ds_mirror;
/* any b0 0..127 */
float xombe__ds_f0(int b0);
int xombe__ds_L(int b0);
int xombe__ds_b0_from_f0(float f0); /* nearest pitch index in log f0, 0..123 */
/* harmonic l takes band min(floor(l*f0*16), 7) of V, without AMBE+2's +250 Hz OR, vl[0] = 0 */
void xombe__ds_harm_voicing(const uint8_t V[8], float f0, int L, uint8_t vl[XOMBE_LMAX + 1]);
/* Tv, G, and a of fields b at L harmonics against an explicit memory (Lp, ap extended, Gp), Tv may be NULL.
the decoder's memory is smoothed on error frames, so it calls this, smooths a, then stores its own memory,
the mirror never smooths */
void xombe__ds_amps(const int b[9], int L, int Lp, const float ap[XOMBE_LMAX + 1], float Gp,
float Tv[XOMBE_LMAX + 1], float *G, float a[XOMBE_LMAX + 1]);
void xombe__ds_mirror_init(xombe_ds_mirror *m);
/* prediction pt[1..L] for a frame of L harmonics */
void xombe__ds_mirror_predict(const xombe_ds_mirror *m, int L, float pt[XOMBE_LMAX + 1]);
/* decodes b against the memory without changing it. b0 > 123 gives only the class, tone fields need the data
bits (xombe__ds_params_from_frame) */
void xombe__ds_dequant(const int b[9], const xombe_ds_mirror *m, xombe_ds_params *p);
/* decodes b and stores L, a, and G for a voice frame. returns 1 for voice, 0 otherwise (memory unchanged),
p may be NULL */
int xombe__ds_mirror_commit(xombe_ds_mirror *m, const int b[9], xombe_ds_params *p);
/* received frame's parameters against the mirror, committing voice frames */
int xombe__ds_params_from_frame(xombe_ds_mirror *m, const xombe_ds_frame *f, xombe_ds_params *p);
#endif
+264
View File
@@ -0,0 +1,264 @@
#include <math.h>
#include <string.h>
#include "dstar_enc.h"
#include "../tables/dstar_enc_tables.h"
#include "../common/tone_table.h"
#include "../common/prof.h"
/* D-STAR encoder tone pipeline
detect least-squares detector (xombe__tone_search) on XOMBE_DS_TONE_LEN samples from 160t + TONE_OFF, over
single tones and the dual tones with a D-STAR code (DTMF, call progress, and 163), then if none a
second pass over the Knox pairs alone (T = -ID), so a Knox candidate never changes a D-STAR decision
run rule a tone frame lies in a run of at least MINRUN detections of the same T (MINRUN_SINGLE for single
tones, whose runs also continue across one 31.25 Hz step), after which HOLD frames without a
detection repeat the last tone
in noise with no tone on the frame or either neighbour after the run rule, a DTMF detection on the
XOMBE_DS_NZ_LEN-sample window from 160n + NZ_OFF at threshold NZ_EMIN is a tone frame when its
residual is within NZ_RES_DB of the noise floor
detection level is the AMBE+2 level 127 + L/0.711 + TONE_ADOFF, L the detector's level in dB */
#define TONE_EMIN 0.99f /* minimum explained energy fraction */
#define TONE_OFF 20
#define TONE_ADOFF 0.6f
#define MINRUN 2
#define MINRUN_SINGLE 3
#define HOLD 1
#define SINGLE_T_MIN 37 /* D-STAR T of the lowest single tone */
#define NZ_OFF (-80)
#define NZ_EMIN 0.85f
#define NZ_RES_DB 10.0f
#define KNOX_REST 5.5f /* encoder's other Knox harmonics this far below the tone level, log2 */
#define KNOX_GAIN 0.9f /* target offset, log2 */
#define RING XOMBE_DS_TONE_RING
/* encoded frame is 4 behind the newest, the run rule decides the frame after it from two detections ahead */
XOMBE_STATIC_ASSERT(XOMBE_ENC_DELAY + XOMBE_ENC_LOOKAHEAD == 4, tone_pipeline_matches_the_delay);
XOMBE_STATIC_ASSERT(-NZ_OFF <= XOMBE_ENC_RAW_LEAD, tone_in_noise_window_in_raw_lead);
XOMBE_STATIC_ASSERT(XOMBE_DS_TONE_LEN <= XOMBE_TONE_SEG && XOMBE_DS_NZ_LEN <= XOMBE_TONE_SEG, ds_tone_segments_fit);
/* DTMF 128..143, call progress 160..162, and 163, high component first */
static int dual_pairs(xombe_tone_pair p[20])
{
int id, n = 0;
for (id = 128; id <= 162; id++) {
float lo, hi;
if (id > 143 && id < 160)
continue;
xombe__tone_freqs(id, &lo, &hi);
p[n].id = (short)id;
p[n].hz[0] = hi;
p[n].hz[1] = lo;
n++;
}
/* D-STAR T 19 (AMBE+2 163) is detected as 340 + 550 Hz, not the AMBE+2 table's 350 + 490 Hz */
p[n].id = 163;
p[n].hz[0] = 550.0f;
p[n].hz[1] = 340.0f;
return n + 1;
}
/* tone-in-noise candidates, the 16 DTMF pairs in D-STAR T order */
static void dtmf_pairs(xombe_tone_pair p[16])
{
int T;
for (T = 0; T < 16; T++) {
float lo, hi;
p[T].id = xombe__ds_tone_id[T];
xombe__tone_freqs(p[T].id, &lo, &hi);
p[T].hz[0] = hi;
p[T].hz[1] = lo;
}
}
static void set_tone(xombe_ds_tone *d, int T, float level)
{
d->on = 1;
d->T = T;
d->level = 127.0f + level / XOMBE_TONE_DB_PER_AD + TONE_ADOFF;
}
/* run continues on the same T, or single tones one step apart */
static int same_tone(int a, int b)
{
return a == b || (a >= SINGLE_T_MIN && b >= SINGLE_T_MIN && (a - b <= 1 && b - a <= 1));
}
void xombe__ds_tone_init(xombe_ds_tones *s)
{
int id;
memset(s, 0, sizeof(*s));
/* Knox IDs that the AMBE+2 tone table gives a harmonic pair for */
for (id = XOMBE_TONE_KNOX_FIRST; id < XOMBE_TONE_KNOX_FIRST + XOMBE_TONE_KNOX_COUNT; id++) {
float f0;
int l1, l2;
xombe__tone_harmonics(id, &f0, &l1, &l2);
if (l1 <= 0 || l2 <= 0)
continue;
s->knox[s->nknox].id = (short)id;
s->knox[s->nknox].hz[0] = f0 * (float)l2;
s->knox[s->nknox].hz[1] = f0 * (float)l1;
s->knox_f0[s->nknox] = f0 / XOMBE_FS;
s->knox_l[s->nknox][0] = (uint8_t)l1;
s->knox_l[s->nknox][1] = (uint8_t)l2;
s->nknox++;
}
}
static void detect(xombe_enc *e, xombe_ds_tones *s, int m, const int16_t *seg)
{
xombe_tone_pair pairs[20];
xombe_tone_search ts;
xombe_tone_seg sg;
xombe_tone_hit h;
xombe_ds_tone *d = &s->detected[m % RING];
const xombe_ds_tone *p = &s->detected[(m + RING - 1) % RING];
int run = 0;
ts.len = XOMBE_DS_TONE_LEN;
ts.win = xombe__ds_tone_win;
ts.emin = TONE_EMIN;
ts.singles = 1;
ts.fine_peak = 1;
ts.pairs = pairs;
ts.npairs = dual_pairs(pairs);
d->on = 0;
xombe__tone_prepare(e, seg, &ts, &sg);
if (xombe__tone_search(&sg, &ts, &h)) {
set_tone(d, xombe__ds_tone_code(h.id), h.level);
} else if (s->nknox) {
ts.singles = 0;
ts.pairs = s->knox;
ts.npairs = s->nknox;
if (xombe__tone_search(&sg, &ts, &h))
set_tone(d, -h.id, h.level);
}
if (d->on) {
run = 1;
if (m > 0 && p->on && same_tone(d->T, p->T)) {
run = s->run[(m + RING - 1) % RING] + 1;
run = run > MINRUN_SINGLE ? MINRUN_SINGLE : run;
}
}
s->run[m % RING] = run;
}
/* run rule on frame m, detections of m + 1 and m + 2 already in the ring */
static void decide(xombe_ds_tones *s, int m)
{
const xombe_ds_tone *d = &s->detected[m % RING];
xombe_ds_tone *o = &s->confirmed[m % RING];
o->on = 0;
if (d->on) {
int need = d->T >= SINGLE_T_MIN ? MINRUN_SINGLE : MINRUN, len = s->run[m % RING], k;
for (k = 1; k <= MINRUN_SINGLE - 1 && len < need; k++) {
const xombe_ds_tone *a = &s->detected[(m + k - 1) % RING], *b = &s->detected[(m + k) % RING];
if (!b->on || !same_tone(b->T, a->T))
break;
len++;
}
if (len >= need) {
*o = *d;
s->held = *d;
s->hold_left = HOLD;
} else {
s->hold_left = 0;
}
} else if (s->hold_left > 0) {
*o = s->held;
s->hold_left--;
}
}
/* frame n's final tone from the run rule or the tone-in-noise pass, raw is frame n's input */
static void finish(xombe_enc *e, xombe_ds_tones *s, int n, const int16_t *raw)
{
int64_t sum = 0;
float floor_db;
int i;
for (i = 0; i < XOMBE_FRAME; i++)
sum += (int32_t)raw[i] * raw[i];
s->level_db[s->level_pos] = 10.0f * log10f((float)sum / XOMBE_FRAME + 1e-9f);
s->level_pos = (s->level_pos + 1) % (XOMBE_DS_NZ_FLOOR + 1);
if (s->n_levels <= XOMBE_DS_NZ_FLOOR)
s->n_levels++;
s->ndet = s->detected[n % RING];
s->ntrk = s->confirmed[n % RING];
s->tone = s->ntrk;
if (s->tone.on || (n > 0 && s->confirmed[(n + RING - 1) % RING].on) || s->confirmed[(n + 1) % RING].on)
return;
{
xombe_tone_pair pairs[16];
xombe_tone_search ts;
xombe_tone_seg sg;
xombe_tone_hit h;
dtmf_pairs(pairs);
ts.len = XOMBE_DS_NZ_LEN;
ts.win = xombe__ds_nz_win;
ts.emin = NZ_EMIN;
ts.singles = 0;
ts.fine_peak = 0;
ts.pairs = pairs;
ts.npairs = 16;
xombe__tone_prepare(e, raw + NZ_OFF, &ts, &sg);
if (!xombe__tone_search(&sg, &ts, &h))
return;
floor_db = s->level_db[0];
for (i = 1; i < s->n_levels; i++)
floor_db = s->level_db[i] < floor_db ? s->level_db[i] : floor_db;
if (10.0f * log10f((h.res > 1e-9f ? h.res : 1e-9f) / XOMBE_DS_NZ_LEN) > floor_db + NZ_RES_DB)
return;
set_tone(&s->tone, xombe__ds_tone_code(h.id), h.level);
}
}
void xombe__ds_tone_push(xombe_enc *e)
{
xombe_ds_tones *s = &XOMBE_DS_ENC(e)->tones;
int t = s->n_frames++;
if (t >= 1)
XOMBE_PF(11, detect(e, s, t - 1, xombe__fe_raw(e, 1) + TONE_OFF));
if (t >= 3)
decide(s, t - 3);
if (t >= 4)
XOMBE_PF(12, finish(e, s, t - 4, xombe__fe_raw(e, 4)));
}
void xombe__ds_enc_force_tone(xombe_enc *e, int id, int ad)
{
xombe_ds_enc_frame *fr = &XOMBE_DS_ENC(e)->fr;
int T = xombe__ds_tone_code(id);
fr->voice = 0;
fr->tone.on = 1;
if (T >= 0) {
fr->cls = XOMBE_DS_CLS_TONE;
fr->tone.T = T;
fr->tone.level = XOMBE_DS_AD_LEVEL(ad);
} else {
fr->cls = XOMBE_DS_CLS_KNOX;
fr->tone.T = -id;
fr->tone.level = (float)ad;
}
}
void xombe__ds_knox_amps(xombe_ds_enc *s, int k, float AD, int b[9])
{
const xombe_ds_tones *t = &s->tones;
float f0 = t->knox_f0[k], lm = XOMBE_TONE_AD_LOG10 * (AD - 127.0f) * XOMBE_LOG2_10, at[XOMBE_LMAX + 1], f0d;
int L = xombe__L_from_f0(f0), b0 = xombe__ds_knox_b0[t->knox[k].id - XOMBE_TONE_KNOX_FIRST], Ld, l, j;
/* target peak, log2 min(16384*10^(0.03555*(AD - 127)), 2^14) */
lm = (lm > 0.0f ? 0.0f : lm) + 14.0f;
if (t->knox_l[k][0] > L && t->knox_l[k][1] > L)
lm -= KNOX_REST;
f0d = xombe__ds_f0(b0);
Ld = xombe__ds_L(b0);
for (l = 1; l <= Ld; l++)
at[l] = lm - KNOX_REST;
/* each tone on its nearest D-STAR harmonic */
for (j = 0; j < 2; j++) {
int h = (int)floorf((float)t->knox_l[k][j] * f0 / f0d + 0.5f);
if (h >= 1 && h <= Ld)
at[h] = lm;
}
for (l = 1; l <= Ld; l++)
at[l] += KNOX_GAIN;
xombe__ds_enc_amps(s, b0, XOMBE_DS_B1_VOICED, at, b);
}
+324
View File
@@ -0,0 +1,324 @@
#include <math.h>
#include <string.h>
#include "dstar_internal.h"
/* data bits of b0..b8, MSB first */
static const uint8_t field_width[9] = {7, 4, 6, 9, 7, 4, 4, 4, 3};
static const uint8_t field_bits[48] = {
0, 1, 2, 3, 4, 5, 47, /* b0 */
37, 38, 39, 40, /* b1 */
6, 7, 8, 9, 41, 42, /* b2 */
10, 11, 12, 13, 14, 15, 16, 43, 44, /* b3 */
17, 18, 19, 20, 21, 45, 46, /* b4 */
22, 23, 24, 25, /* b5 */
26, 27, 28, 29, /* b6 */
30, 31, 32, 33, /* b7 */
34, 35, 36, /* b8 */
};
/* tone frames: index T at these data bits, 7-bit level F at the next, half step at bit 17 */
static const uint8_t tone_t_bits[8] = {6, 7, 8, 9, 41, 42, 10, 11};
static const uint8_t tone_f_bits[7] = {12, 13, 14, 15, 16, 43, 44};
#define TONE_HALF_BIT 17
uint32_t xombe__ds_golay24_encode(uint32_t data12)
{
uint32_t c23 = xombe__golay23_encode(data12 & 0xFFFu);
return (c23 << 1) | (uint32_t)(xombe__popcount32(c23) & 1);
}
int xombe__ds_golay24_decode(uint32_t cw24, int *data12)
{
uint32_t c23;
int w = xombe__golay23_decode((cw24 >> 1) & 0x7FFFFFu, &c23);
int parity_ok = ((xombe__popcount32(c23) + (int)(cw24 & 1u)) & 1) == 0;
*data12 = (int)(c23 >> 11);
if (w == 3 && !parity_ok)
return XOMBE_DS_GOLAY_BAD;
return w + !parity_ok;
}
uint32_t xombe__ds_pn24(int da)
{
uint16_t u = (uint16_t)(16u * ((unsigned)da & 0xFFFu));
uint32_t out = 0;
int n;
for (n = 0; n < 24; n++) {
u = xombe__lcg_next(u);
out = (out << 1) | ((u >> 15) & 1u);
}
return out;
}
/* air bit of A's word bit n (n = 0 the MSB), B and C are 2 and 4 later */
static int pos_a(int n)
{
return n < 12 ? 6 * n : 6 * (n - 12) + 1;
}
void xombe__ds_deinterleave(const uint8_t in[9], uint32_t *A, uint32_t *B, uint32_t *C)
{
uint32_t w[3] = {0, 0, 0};
int n, k;
for (n = 0; n < 24; n++)
for (k = 0; k < 3; k++) {
int p = pos_a(n) + 2 * k;
w[k] = (w[k] << 1) | (uint32_t)((in[p >> 3] >> (7 - (p & 7))) & 1);
}
*A = w[0];
*B = w[1];
*C = w[2];
}
void xombe__ds_interleave(uint32_t A, uint32_t B, uint32_t C, uint8_t out[9])
{
uint32_t w[3];
int n, k;
w[0] = A;
w[1] = B;
w[2] = C;
memset(out, 0, 9);
for (n = 0; n < 24; n++)
for (k = 0; k < 3; k++) {
int p = pos_a(n) + 2 * k;
out[p >> 3] |= (uint8_t)(((w[k] >> (23 - n)) & 1u) << (7 - (p & 7)));
}
}
void xombe__ds_get_fields(const uint8_t d[48], int b[9])
{
int k, j, i = 0;
for (k = 0; k < 9; k++) {
int v = 0;
for (j = 0; j < field_width[k]; j++)
v = (v << 1) | (d[field_bits[i++]] & 1);
b[k] = v;
}
}
void xombe__ds_put_fields(const int b[9], uint8_t d[48])
{
int k, j, i = 0;
for (k = 0; k < 9; k++)
for (j = 0; j < field_width[k]; j++)
d[field_bits[i++]] = (uint8_t)((b[k] >> (field_width[k] - 1 - j)) & 1);
}
int xombe__ds_classify(int b0)
{
if (b0 <= XOMBE_DS_B0_VOICE_MAX)
return XOMBE_DS_VOICE;
if (b0 == XOMBE_DS_B0_TONE)
return XOMBE_DS_TONE;
return XOMBE_DS_NULL;
}
static int bits_at(const uint8_t d[48], const uint8_t *idx, int n)
{
int v = 0, i;
for (i = 0; i < n; i++)
v = (v << 1) | (d[idx[i]] & 1);
return v;
}
int xombe__ds_tone_index(const uint8_t d[48])
{
return bits_at(d, tone_t_bits, 8);
}
int xombe__ds_tone_level(const uint8_t d[48])
{
/* 4*bits(12..16) + bits(43, 44) is the 7-bit F */
int ad = bits_at(d, tone_f_bits, 7) + d[TONE_HALF_BIT] + 8;
return ad < 127 ? ad : 127;
}
void xombe__ds_fec_decode(const uint8_t in[9], xombe_ds_frame *f)
{
uint8_t d[XOMBE_DS_DATA_BITS];
int i;
xombe__ds_deinterleave(in, &f->A, &f->B, &f->C);
f->ea = xombe__ds_golay24_decode(f->A, &f->da);
f->pn = xombe__ds_pn24(f->da);
f->eb = xombe__ds_golay24_decode(f->B ^ f->pn, &f->db);
for (i = 0; i < 12; i++) {
d[i] = (uint8_t)((f->da >> (11 - i)) & 1);
d[12 + i] = (uint8_t)((f->db >> (11 - i)) & 1);
}
for (i = 0; i < 24; i++)
d[24 + i] = (uint8_t)((f->C >> (23 - i)) & 1u);
xombe__ds_frame_from_data(d, f);
}
void xombe__ds_frame_from_data(const uint8_t d[48], xombe_ds_frame *f)
{
memcpy(f->d, d, XOMBE_DS_DATA_BITS);
xombe__ds_get_fields(f->d, f->b);
f->cls = xombe__ds_classify(f->b[0]);
f->T = f->AD = f->tid = -1;
if (f->cls == XOMBE_DS_TONE) {
f->T = xombe__ds_tone_index(f->d);
f->AD = xombe__ds_tone_level(f->d);
if (xombe__ds_tone_id[f->T] != XOMBE_DS_TONE_NONE)
f->tid = xombe__ds_tone_id[f->T];
}
}
void xombe__ds_encode_bits(const uint8_t d[48], uint8_t out[9])
{
uint32_t da = 0, db = 0, c = 0;
int i;
for (i = 0; i < 12; i++) {
da = (da << 1) | (d[i] & 1u);
db = (db << 1) | (d[12 + i] & 1u);
}
for (i = 24; i < 48; i++)
c = (c << 1) | (d[i] & 1u);
xombe__ds_interleave(xombe__ds_golay24_encode(da), xombe__ds_golay24_encode(db) ^ xombe__ds_pn24((int)da), c,
out);
}
/* d of fields b, each clamped to its width, returns 0, or -1 if any was clamped */
static int clamped_fields(const int b[9], uint8_t d[48])
{
int c[9], k, r = 0;
for (k = 0; k < 9; k++) {
int top = (1 << field_width[k]) - 1;
c[k] = b[k] < 0 ? 0 : b[k] > top ? top : b[k];
r |= c[k] != b[k];
}
xombe__ds_put_fields(c, d);
return r ? -1 : 0;
}
int xombe__ds_encode_fields(const int b[9], uint8_t out[9])
{
uint8_t d[48];
int r = clamped_fields(b, d);
xombe__ds_encode_bits(d, out);
return r;
}
int xombe__ds_fields_bits(const int b[9], uint8_t bits[7])
{
uint8_t d[48];
int r = clamped_fields(b, d);
xombe__ds_pack(d, bits);
return r;
}
int xombe__ds_tone_q(float level)
{
/* 2*level is exact in float, so no epsilon against double rounding */
float q = floorf(2.0f * level);
if (!(q >= 16.0f)) /* also NaN */
return 16;
return q > 254.0f ? 254 : (int)q;
}
int xombe__ds_tone_code(int id)
{
int T;
for (T = 0; T < 256; T++)
if (xombe__ds_tone_id[T] == id)
return T;
return -1;
}
void xombe__ds_pack(const uint8_t d[48], uint8_t bits[7])
{
memset(bits, 0, 7);
xombe__pack_bits(d, XOMBE_DS_DATA_BITS, bits);
}
void xombe__ds_unpack(const uint8_t bits[7], uint8_t d[48])
{
xombe__unpack_bits(bits, XOMBE_DS_DATA_BITS, d);
}
void xombe__ds_fec_encode_bits(const uint8_t bits[7], uint8_t frame[9])
{
uint8_t d[XOMBE_DS_DATA_BITS];
xombe__ds_unpack(bits, d);
xombe__ds_encode_bits(d, frame);
}
unsigned xombe__ds_fec_decode_bits(xombe_fec *fec, const uint8_t frame[9], uint8_t bits[7], xombe_fec_stats *st)
{
uint32_t A, B, C;
int da, db, ea, eb;
xombe_ds_err er;
xombe_ds_flags fl;
xombe__ds_deinterleave(frame, &A, &B, &C);
ea = xombe__ds_golay24_decode(A, &da);
eb = xombe__ds_golay24_decode(B ^ xombe__ds_pn24(da), &db);
da &= 0xFFF;
db &= 0xFFF;
bits[0] = (uint8_t)(da >> 4);
bits[1] = (uint8_t)(((da & 15) << 4) | (db >> 8));
bits[2] = (uint8_t)db;
bits[3] = (uint8_t)(C >> 16);
bits[4] = (uint8_t)(C >> 8);
bits[5] = (uint8_t)C;
bits[6] = 0;
er.er = fec->er;
xombe__ds_err_update(&er, ea, eb, &fl);
fec->er = er.er;
st->eps0 = ea;
st->eps1 = eb;
st->eps_t = ea + eb;
st->bf = fl.bf;
st->hb = fl.hb;
st->eps_r = (uint32_t)(er.er * 16777216.0f + 0.5f);
return (fl.bf ? XOMBE_FLAG_BF : 0u) | (fl.hb ? XOMBE_FLAG_HB : 0u);
}
int xombe__ds_tone_frame_id(int id, int ad, uint8_t out[9])
{
int T = xombe__tone_valid(id, ad) ? xombe__ds_tone_code(id) : -1;
if (T < 0)
return -1;
xombe__ds_tone_frame(T, xombe__ds_tone_q(XOMBE_DS_AD_LEVEL(ad)), out);
return 0;
}
void xombe__ds_tone_bits(int T, int q, uint8_t d[48])
{
int j, F;
if (q < 16)
q = 16;
if (q > 254)
q = 254;
F = q / 2 - 8;
memset(d, 0, 48);
for (j = 0; j < 6; j++)
d[j] = 1; /* b0 = 126: bits 0..5 set, bit 47 clear */
for (j = 0; j < 8; j++)
d[tone_t_bits[j]] = (uint8_t)((T >> (7 - j)) & 1);
for (j = 0; j < 7; j++)
d[tone_f_bits[j]] = (uint8_t)((F >> (6 - j)) & 1);
d[TONE_HALF_BIT] = (uint8_t)(q & 1);
}
void xombe__ds_tone_frame(int T, int q, uint8_t out[9])
{
uint8_t d[48];
xombe__ds_tone_bits(T, q, d);
xombe__ds_encode_bits(d, out);
}
void xombe__ds_err_init(xombe_ds_err *s)
{
s->er = 0.0f;
}
void xombe__ds_err_update(xombe_ds_err *s, int ea, int eb, xombe_ds_flags *out)
{
int eT = ea + eb;
s->er = 0.95f * s->er + 0.05f * (float)eT / 48.0f;
out->bf = ea >= 4;
out->hb = s->er > 0.096f;
if (eT < 6)
eT = eb = 0;
out->eT = eT;
out->e1 = eb;
}
+104
View File
@@ -0,0 +1,104 @@
#include <math.h>
#include <string.h>
#include "dstar_internal.h"
const xombe_amp_tables xombe__amp_dstar = {
xombe__ds_dg, 64, xombe__ds_prba24, 512, xombe__ds_prba58, 128,
{&xombe__ds_hoc5[0][0], &xombe__ds_hoc6[0][0], &xombe__ds_hoc7[0][0], &xombe__ds_hoc8[0][0]}, {16, 16, 16, 8},
xombe__blk, xombe__ds_ok_dg, xombe__ds_ok_prba24, xombe__ds_ok_prba58,
{xombe__ds_ok_hoc5, xombe__ds_ok_hoc6, xombe__ds_ok_hoc7, xombe__ds_ok_hoc8},
XOMBE_DS_RHO, XOMBE_DS_GRHO, XOMBE_DS_GAIN_MAX, XOMBE_AMP_MIN, XOMBE_DS_AMP_MAX};
#define DS_RESET_L 15
float xombe__ds_f0(int b0)
{
return xombe__ds_w0[b0 & (XOMBE_DS_B0_COUNT - 1)];
}
int xombe__ds_b0_from_f0(float f0)
{
int b = (int)floorf((log2f(f0) - XOMBE_DS_P0) / XOMBE_DS_P1);
return b < 0 ? 0 : b > XOMBE_DS_B0_VOICE_MAX ? XOMBE_DS_B0_VOICE_MAX : b;
}
int xombe__ds_L(int b0)
{
return xombe__ds_lt[b0 & (XOMBE_DS_B0_COUNT - 1)];
}
void xombe__ds_harm_voicing(const uint8_t V[8], float f0, int L, uint8_t vl[XOMBE_LMAX + 1])
{
int l;
vl[0] = 0;
for (l = 1; l <= L; l++) {
/* scripts/gen_dstar_tables.py checks this float index matches the double one for every voice b0 and
harmonic */
int j = (int)((float)l * f0 * XOMBE_BANDS_PER_UNIT);
vl[l] = V[j < 7 ? j : 7];
}
}
void xombe__ds_amps(const int b[9], int L, int Lp, const float ap[XOMBE_LMAX + 1], float Gp,
float Tv[XOMBE_LMAX + 1], float *G, float a[XOMBE_LMAX + 1])
{
const xombe_amp_tables *ts = &xombe__amp_dstar;
float t[XOMBE_LMAX + 1], pt[XOMBE_LMAX + 1], g;
xombe__spectral_shape_ts(ts, b, L, t);
xombe__predict_from(Lp, ap, L, pt);
g = xombe__gain_ts(ts, b[2], Gp);
xombe__assemble_ts(ts, t, pt, L, g, a);
*G = g;
if (Tv)
memcpy(Tv, t, sizeof(t));
}
void xombe__ds_mirror_init(xombe_ds_mirror *m)
{
memset(m, 0, sizeof(*m));
m->L = DS_RESET_L;
}
void xombe__ds_mirror_predict(const xombe_ds_mirror *m, int L, float pt[XOMBE_LMAX + 1])
{
xombe__predict_from(m->L, m->a, L, pt);
}
void xombe__ds_dequant(const int b[9], const xombe_ds_mirror *m, xombe_ds_params *p)
{
memcpy(p->b, b, sizeof(p->b));
p->cls = xombe__ds_classify(b[0]);
p->T = p->tid = p->AD = -1;
if (p->cls != XOMBE_DS_VOICE) {
p->L = 0;
return;
}
p->f0 = xombe__ds_f0(b[0]);
p->L = xombe__ds_L(b[0]);
memcpy(p->V, xombe__ds_vuv[b[1] & 15], 8);
xombe__ds_harm_voicing(p->V, p->f0, p->L, p->vl);
xombe__ds_amps(b, p->L, m->L, m->a, m->G, p->Tv, &p->G, p->a);
}
int xombe__ds_mirror_commit(xombe_ds_mirror *m, const int b[9], xombe_ds_params *p)
{
xombe_ds_params tmp;
if (!p)
p = &tmp;
xombe__ds_dequant(b, m, p);
if (p->cls != XOMBE_DS_VOICE)
return 0;
m->L = p->L;
m->G = p->G;
memcpy(m->a, p->a, sizeof(m->a));
return 1;
}
int xombe__ds_params_from_frame(xombe_ds_mirror *m, const xombe_ds_frame *f, xombe_ds_params *p)
{
int voice = xombe__ds_mirror_commit(m, f->b, p);
p->T = f->T;
p->tid = f->tid;
p->AD = f->AD;
return voice;
}
+45
View File
@@ -0,0 +1,45 @@
#ifndef XOMBE_DSTAR_TRACE_H
#define XOMBE_DSTAR_TRACE_H
/* transcoder per-frame records for tests, filled when the state's trace pointer is set */
#include "../state.h"
/* DMR -> D-STAR half of xombe_xc (xcode.c), dumped by test/dstar_dump_xc.c */
typedef struct xombe_xc_trace {
int cls; /* AMBE+2 class, XOMBE_CLASS_ERASURE for a concealed frame */
int conceal; /* enum xombe_conceal */
int cls_out; /* class of the set transcoded (the played set when concealed) */
int has_rb, rb[9]; /* AMBE+2 fields, frames decoded normally */
int has_par; /* voice and silence sets: f0, L, a, V2 */
float f0; /* cycles/sample */
int L;
float a[XOMBE_LMAX + 1];
uint8_t V2[8], V1[8];
int has_v1; /* frames decoded normally: V1 and G */
float G;
int pulse, tid, AD; /* tid, AD -1 when none */
int has_soft;
float soft[4]; /* per-kHz voiced fraction */
int tL, tb0; /* quantizer target tgt[1..tL] and its pitch, tb0 -1 when not quantized */
float tgt[XOMBE_LMAX + 1];
int has_b, b[9]; /* D-STAR fields of the output (of the resent frame for a resend) */
} xombe_xc_trace;
/* D-STAR -> DMR half of xombe_xc (xrev.c), dumped by test/dstar_dump_xrev.c */
typedef struct xombe_xr_trace {
int in_cls; /* XOMBE_XR_IN_* (xc_state.h) */
int scls; /* class of the D-STAR decoder's played set */
int has_db, db[9]; /* D-STAR fields, frames not lost */
int has_par; /* voice and silence sets: f0, L, a */
float f0;
int L;
float a[XOMBE_LMAX + 1];
int tid, AD; /* -1 when none */
int tL; /* quantizer target tgt[1..tL], 0 when not quantized */
float tgt[XOMBE_LMAX + 1];
int has_b, b[9]; /* AMBE+2 fields of voice and pulse frames */
uint8_t d49[49];
} xombe_xr_trace;
#endif
+81
View File
@@ -0,0 +1,81 @@
#include <string.h>
#include "../internal.h"
#include "xc_state.h"
/* xombe_xc: the DMR -> D-STAR half (xcode.c) or the D-STAR -> DMR half (xrev.c) by the input codec, each reached
only through its own init so a program using one leaves the other out */
XOMBE_STATIC_ASSERT(sizeof(struct xombe_xc_own) <= XOMBE_XC_SIZE, xc_state_fits_XOMBE_XC_SIZE);
XOMBE_STATIC_ASSERT(sizeof(struct xombe_xc) <= XOMBE_XC_SHARED_SIZE, xc_state_fits_XOMBE_XC_SHARED_SIZE);
XOMBE_STATIC_ASSERT(sizeof(xombe_cq_ws) <= XOMBE_QWS_SIZE, cq_ws_fits_XOMBE_QWS_SIZE);
size_t xombe_xc_size(void)
{
return sizeof(struct xombe_xc_own);
}
static int fwd_frame(xombe_xc *x, const uint8_t in[9], unsigned flags, uint8_t out[9])
{
return xombe__xc_fwd_frame(&x->u.f, in, flags, out);
}
xombe_xc *xombe__xc_init_shared_dmr(void *mem, void *ws)
{
xombe_xc *x = mem;
if (!x || !ws)
return NULL;
xombe__xc_fwd_init(&x->u.f, ws);
x->from = XOMBE_DMR;
x->frame = fwd_frame;
return x;
}
#if XOMBE_HAVE_ENCODER
static int rev_frame(xombe_xc *x, const uint8_t in[9], unsigned flags, uint8_t out[9])
{
return xombe__xc_rev_frame(&x->u.r, in, flags, out);
}
#endif
xombe_xc *xombe__xc_init_shared_dstar(void *mem, void *ws)
{
#if XOMBE_HAVE_ENCODER
xombe_xc *x = mem;
if (!x || !ws)
return NULL;
xombe__xc_rev_init(&x->u.r, ws);
x->from = XOMBE_DSTAR;
x->frame = rev_frame;
return x;
#else
(void)mem;
(void)ws;
return NULL;
#endif
}
xombe_xc *xombe__xc_init_dmr(void *mem)
{
return mem ? xombe__xc_init_shared_dmr(mem, &((struct xombe_xc_own *)mem)->ws) : NULL;
}
xombe_xc *xombe__xc_init_dstar(void *mem)
{
return mem ? xombe__xc_init_shared_dstar(mem, &((struct xombe_xc_own *)mem)->ws) : NULL;
}
int xombe_xc_frame(xombe_xc *x, const uint8_t in[XOMBE_FRAME_BYTES], unsigned flags, uint8_t out[XOMBE_FRAME_BYTES])
{
return x->frame(x, in, flags, out);
}
void xombe_xc_decision_get(const xombe_xc *x, xombe_xc_decision *out)
{
if (x->from == XOMBE_DSTAR) {
out->in = x->u.r.d.decision;
out->out = (enum xombe_xc_out)x->u.r.out;
} else {
out->in = x->u.f.d.decision;
out->out = (enum xombe_xc_out)x->u.f.out;
}
}
+65
View File
@@ -0,0 +1,65 @@
#ifndef XOMBE_XC_STATE_H
#define XOMBE_XC_STATE_H
/* transcoder state behind xombe.h's xombe_xc handle (xc.c), the DMR -> D-STAR half (xcode.c) and the
D-STAR -> DMR half (xrev.c) */
#include "dstar_internal.h"
#include "dsd_state.h"
#include "../common/cquant.h"
struct xombe_xc_trace;
struct xombe_xr_trace;
/* DMR -> D-STAR */
typedef struct {
xombe_dec_core d; /* DMR frame logic and sets */
xombe_fec fec;
xombe_ds_mirror mirror; /* D-STAR decoder's prediction memory */
uint8_t last[XOMBE_DS_FRAME_BYTES];
int have_last_b, last_b[9]; /* fields of last, if it was a voice frame */
int out; /* enum xombe_xc_out of the last frame */
struct xombe_xc_trace *trace; /* trace.h */
xombe_cq_ws *ws; /* quantizer workspace, own or shared, nothing in it lives between frames */
} xombe_xc_fwd;
enum { XOMBE_XR_IN_VOICE, XOMBE_XR_IN_TONE, XOMBE_XR_IN_NULL, XOMBE_XR_IN_REPEAT, XOMBE_XR_IN_MUTE };
/* D-STAR -> DMR */
typedef struct {
xombe_dec_core d; /* D-STAR frame logic and sets (with s) */
xombe_dsd_logic s;
xombe_fec fec;
xombe_pred pi; /* DMR decoder's prediction memory */
int prev_b1; /* previous D-STAR voice frame's b1, -1 after any other frame but a repeat */
int have_last, last_db[9]; /* fields of the last good D-STAR voice frame */
int have_tone, tone_id, tone_ad;
int out;
struct xombe_xr_trace *trace;
xombe_cq_ws *ws;
} xombe_xc_rev;
struct xombe_xc {
int from; /* enum xombe_codec */
int (*frame)(struct xombe_xc *x, const uint8_t in[9], unsigned flags, uint8_t out[9]);
union {
xombe_xc_fwd f;
xombe_xc_rev r;
} u;
};
/* xombe_xc_init's layout: the state, then its own workspace */
struct xombe_xc_own {
struct xombe_xc x;
xombe_cq_ws ws;
};
/* each half's init (ws zeroed here), frame, and output class */
void xombe__xc_fwd_init(xombe_xc_fwd *x, xombe_cq_ws *ws);
int xombe__xc_fwd_frame(xombe_xc_fwd *x, const uint8_t in[9], unsigned flags, uint8_t out[9]);
#if XOMBE_HAVE_ENCODER
void xombe__xc_rev_init(xombe_xc_rev *x, xombe_cq_ws *ws);
int xombe__xc_rev_frame(xombe_xc_rev *x, const uint8_t in[9], unsigned flags, uint8_t out[9]);
#endif
#endif
+254
View File
@@ -0,0 +1,254 @@
#include <math.h>
#include <string.h>
#include "../internal.h"
#include "../common/tone_table.h"
#include "xc_state.h"
#include "trace.h"
/* AMBE+2 rate-33 -> D-STAR parameter transcoder */
#define XC_VTHR 0.5f /* band voiced if its energy-weighted voiced fraction is above this */
#define XC_KNOX_REST 4.0f /* transcoder's other Knox harmonics this far below the tones, log2 */
#define XC_PULSE_FIRST 18 /* AMBE+2 pulse frames: b1 18..31 */
#define XC_PULSE_LAST 31
/* AMBE+2 pulse frame b1 18..31 -> D-STAR b0 as DVSI converts it, 30 -> 80 inferred as the one unused value of
the 64..116 step-4 grid */
static const uint8_t pulse_b0[XC_PULSE_LAST - XC_PULSE_FIRST + 1] = {88, 92, 96, 100, 64, 68, 112, 116,
72, 76, 104, 108, 80, 84};
void xombe__xc_fwd_init(xombe_xc_fwd *x, xombe_cq_ws *ws)
{
static const uint8_t null_frame[XOMBE_DS_FRAME_BYTES] = XOMBE_DS_NULL_FRAME;
memset(x, 0, sizeof(*x));
x->ws = ws;
memset(x->ws, 0, sizeof(*x->ws));
x->ws->cap = XOMBE_CQ_CAP;
xombe__dec_core_reset(&x->d);
xombe__fec_init_dmr(&x->fec);
xombe__ds_mirror_init(&x->mirror);
memcpy(x->last, null_frame, XOMBE_DS_FRAME_BYTES);
}
/* energy-weighted voiced fraction per 1 kHz band of harmonics 1..L, harmonic voicing with AMBE+2's +250 Hz OR */
static void band_soft(const float *a, int L, float f0, const uint8_t V[8], float s[4])
{
float num[4] = {0.0f, 0.0f, 0.0f, 0.0f}, den[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float f = f0 * XOMBE_FS;
int l, j;
for (l = 1; l <= L; l++) {
float fr = (float)l * f, w;
int j1, j2;
j = (int)(fr / 1000.0f);
if (j > 3)
continue;
j1 = (int)(fr / 500.0f);
j2 = (int)((fr + 250.0f) / 500.0f);
w = exp2f(2.0f * a[l]);
num[j] += (V[j1 > 7 ? 7 : j1] || V[j2 > 7 ? 7 : j2]) ? w : 0.0f;
den[j] += w;
}
for (j = 0; j < 4; j++)
s[j] = den[j] > 0.0f ? num[j] / den[j] : 0.0f;
}
/* the code nearest the per-band decisions s > XC_VTHR (bit 3 = 0..1 kHz), never XOMBE_DS_B1_SKIP: least sum of
|s - XC_VTHR| over the bands it flips, first on ties */
static int b1_from_soft(const float s[4])
{
float best = 0.0f;
int c, j, want = 0, bc = -1;
for (j = 0; j < 4; j++)
want |= (s[j] > XC_VTHR) << (3 - j);
for (c = 0; c < 16; c++) {
float cost = 0.0f;
if (c == XOMBE_DS_B1_SKIP)
continue;
for (j = 0; j < 4; j++)
if (((c ^ want) >> (3 - j)) & 1)
cost += fabsf(s[j] - XC_VTHR);
if (bc < 0 || cost < best) {
best = cost;
bc = c;
}
}
return bc;
}
/* a[1..L] at harmonics of f0 -> D-STAR voice frame: resampled linearly in harmonic number to the harmonics of
b0 (nearest pitch of f0 if b0 < 0), quantized against the mirror and committed */
static void requant(xombe_xc_fwd *x, float f0, const float *a, int L, int b1, int b0, int b[9])
{
float tgt[XOMBE_LMAX + 1], w[XOMBE_LMAX + 1], pt[XOMBE_LMAX + 1], f0d;
xombe_cq_result res;
int Ld, l, k;
if (b0 < 0)
b0 = xombe__ds_b0_from_f0(f0);
f0d = xombe__ds_f0(b0);
Ld = xombe__ds_L(b0);
tgt[0] = 0.0f;
for (l = 1; l <= Ld; l++) {
float h = (float)l * f0d / f0, fr;
int i;
h = h < 1.0f ? 1.0f : h > (float)L ? (float)L : h;
i = (int)h;
fr = h - (float)i;
tgt[l] = (1.0f - fr) * a[i] + fr * a[i < L ? i + 1 : L];
}
xombe__cq_amp_weights(tgt, Ld, XOMBE_CQ_QWEIGHT, XOMBE_CQ_WEIGHT_FLOOR, w);
xombe__ds_mirror_predict(&x->mirror, Ld, pt);
xombe__cq_quantize(x->ws, &xombe__amp_dstar, tgt, Ld, pt, x->mirror.G, w, 1, XOMBE_CQ_N_PAIRS, XOMBE_CQ_N_GAIN,
XOMBE_CQ_ITERS, XOMBE_CQ_CLIP_PASSES, &res);
b[0] = b0;
b[1] = b1;
for (k = 2; k < 9; k++)
b[k] = res.b[k];
xombe__ds_mirror_commit(&x->mirror, b, NULL);
if (x->trace) {
x->trace->tL = Ld;
x->trace->tb0 = b0;
memcpy(x->trace->tgt, tgt, sizeof(tgt));
}
}
/* Knox tone as a voice frame at the table f0: the two tone harmonics at the tone level
log2 min(16384 * 10^(0.03555 (AD - 127)), 2^14), the others XC_KNOX_REST below, all bands voiced.
returns 0 if the tone table has no pair for id */
static int knox(xombe_xc_fwd *x, int id, int AD, int b[9])
{
float f0hz, f0, lm, a[XOMBE_LMAX + 1];
int l1, l2, L, l;
xombe__tone_harmonics(id, &f0hz, &l1, &l2);
if (l1 <= 0 || l2 <= 0)
return 0;
f0 = f0hz / XOMBE_FS;
lm = XOMBE_TONE_AD_LOG10 * (float)(AD - 127) * XOMBE_LOG2_10;
lm = (lm > 0.0f ? 0.0f : lm) + 14.0f;
L = xombe__L_from_f0(f0);
for (l = 1; l <= L; l++)
a[l] = lm - XC_KNOX_REST;
if (l1 <= L)
a[l1] = lm;
if (l2 <= L)
a[l2] = lm;
requant(x, f0, a, L, XOMBE_DS_B1_VOICED, -1, b);
return 1;
}
/* silence and pulse pitches 250.60 Hz and 64.346 Hz as the 2^-19 fractions consts.h rounds, the resampling
positions l * f0d / f0 otherwise move by up to 1.2e-5 relative, enough to change quantizer picks */
static float exact_f0(float f0)
{
if (f0 == XOMBE_SILENCE_F0)
return 16423.0f / 524288.0f;
if (f0 == XOMBE_PULSE_F0)
return 4217.0f / 524288.0f;
return f0;
}
int xombe__xc_fwd_frame(xombe_xc_fwd *x, const uint8_t in[9], unsigned flags, uint8_t out[9])
{
xombe_dec_core *d = &x->d;
const xombe_decision *dc = &d->decision;
xombe_xc_trace *tr = x->trace;
const xombe_set *s = &d->p2;
uint8_t bits[7];
int b[9], id = -1, ad = -1, voice_b = 0, cls;
memset(bits, 0, sizeof(bits));
xombe__dec_start_air(d, &x->fec, in, flags, bits);
xombe__dec_skip_synth(d);
cls = s->cls;
if (cls == XOMBE_CLASS_TONE && dc->conceal == XOMBE_CONCEAL_NONE) {
uint8_t d49[49];
xombe__unpack49(bits, d49);
xombe__tone_frame_parse(d49, &id, &ad);
}
if (tr) {
uint8_t d49[49];
memset(tr, 0, sizeof(*tr));
tr->cls = dc->cls;
tr->conceal = dc->conceal;
tr->cls_out = cls;
tr->tid = tr->AD = tr->tb0 = -1;
if (dc->conceal == XOMBE_CONCEAL_NONE) {
xombe__unpack49(bits, d49);
if (cls != XOMBE_CLASS_TONE) {
tr->has_rb = tr->has_v1 = 1;
xombe__get_fields(d49, tr->rb);
memcpy(tr->V1, d->p1.vb, 8);
tr->G = d->pi.gamma;
}
}
}
if (cls == XOMBE_CLASS_TONE && dc->conceal != XOMBE_CONCEAL_NONE) {
/* the AMBE+2 decoder replays the tone set: resend the last frame, which the D-STAR decoder decodes anew */
if (x->have_last_b)
xombe__ds_mirror_commit(&x->mirror, x->last_b, NULL);
memcpy(out, x->last, XOMBE_DS_FRAME_BYTES);
x->out = XOMBE_XC_OUT_RESEND;
if (tr && x->have_last_b) {
tr->has_b = 1;
memcpy(tr->b, x->last_b, sizeof(tr->b));
}
return 1;
}
if (cls == XOMBE_CLASS_TONE) {
int T = xombe__ds_tone_code(id);
if (tr) {
tr->tid = id;
tr->AD = ad;
}
if (T >= 0) {
xombe__ds_tone_frame(T, xombe__ds_tone_q(XOMBE_DS_AD_LEVEL(ad)), out);
x->out = XOMBE_XC_OUT_TONE;
} else if (id >= XOMBE_TONE_KNOX_FIRST && id < XOMBE_TONE_KNOX_FIRST + XOMBE_TONE_KNOX_COUNT &&
knox(x, id, ad, b)) {
voice_b = 1;
x->out = XOMBE_XC_OUT_KNOX;
} else {
memcpy(out, x->last, XOMBE_DS_FRAME_BYTES);
x->out = XOMBE_XC_OUT_RESEND;
x->have_last_b = 0;
return 1;
}
} else {
/* voice, or silence as an all-unvoiced voice frame from its comfort-noise amplitudes */
float soft[4] = {0.0f, 0.0f, 0.0f, 0.0f};
int pulse = 0, b0 = -1;
if (cls == XOMBE_CLASS_VOICE && dc->conceal == XOMBE_CONCEAL_NONE) {
uint8_t d49[49];
int rb[9];
xombe__unpack49(bits, d49);
xombe__get_fields(d49, rb);
pulse = rb[1] >= XC_PULSE_FIRST && rb[1] <= XC_PULSE_LAST;
if (pulse)
b0 = pulse_b0[rb[1] - XC_PULSE_FIRST];
}
if (cls == XOMBE_CLASS_VOICE && !pulse)
band_soft(s->a, s->L, s->f0, s->vb, soft);
if (tr) {
tr->has_par = 1;
tr->f0 = s->f0;
tr->L = s->L;
memcpy(tr->a, s->a, sizeof(tr->a));
memcpy(tr->V2, s->vb, 8);
tr->pulse = pulse;
tr->has_soft = cls == XOMBE_CLASS_VOICE && !pulse;
memcpy(tr->soft, soft, sizeof(soft));
}
requant(x, exact_f0(s->f0), s->a, s->L, b1_from_soft(soft), b0, b);
voice_b = 1;
x->out = XOMBE_XC_OUT_VOICE;
}
if (voice_b)
xombe__ds_encode_fields(b, out);
memcpy(x->last, out, XOMBE_DS_FRAME_BYTES);
x->have_last_b = voice_b;
if (voice_b)
memcpy(x->last_b, b, sizeof(b));
if (tr && voice_b) {
tr->has_b = 1;
memcpy(tr->b, b, sizeof(b));
}
return 1;
}
+205
View File
@@ -0,0 +1,205 @@
#include <string.h>
#include "../internal.h"
#include "../common/bits.h"
#include "../common/tone_table.h"
#include "../tables/dsp_tables.h"
#include "xc_state.h"
#include "trace.h"
/* D-STAR -> AMBE+2 rate-33 parameter transcoder */
#define XR_OCTAVE_F0 (400.0f / 8000.0f) /* pitches above take the AMBE+2 index of half their f0 */
#define XR_PULSE_F0 (4217.0f / 524288.0f) /* the pulse pitch as the 2^-19 fraction XOMBE_PULSE_F0 rounds */
/* all-unvoiced D-STAR b0 -> AMBE+2 pulse code b1 18..31, DVSI's conversion where seen, else the pulse whose
AMBE+2 -> D-STAR b0 is nearest, first on ties. 0: a plain all-unvoiced frame */
static const uint8_t pulse_code[XOMBE_DS_B0_VOICE_MAX + 1] = {
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 22, 0, 23, 23, 0, 26, 26, 0, 0,
27, 0, 28, 27, 30, 30, 30, 0, 0, 31, 31, 0, 18, 18, 20, 19, 19, 19, 20, 23, 21, 20, 0, 21, 21,
0, 20, 20, 20, 28, 28, 27, 28, 29, 31, 27, 28, 24, 24, 24, 25, 25, 25, 19, 0, 25, 25, 25, 25};
/* D-STAR b1 -> AMBE+2 b1 by the previous D-STAR frame: DVSI's conversion where seen, else the code nearest in
Hamming distance to the D-STAR bands each split in two. rows: previous b1 <= 0 or not a voice frame, 15,
anything else */
static const uint8_t vuv_map[3][16] = {{16, 16, 14, 5, 16, 0, 4, 0, 12, 8, 6, 6, 10, 7, 9, 0},
{16, 16, 14, 5, 16, 0, 4, 0, 12, 8, 6, 6, 9, 7, 4, 0},
{16, 16, 14, 5, 16, 0, 4, 0, 12, 8, 6, 6, 8, 7, 0, 0}};
static const uint8_t std_silence[7] = XOMBE_SILENCE_FRAME;
void xombe__xc_rev_init(xombe_xc_rev *x, xombe_cq_ws *ws)
{
memset(x, 0, sizeof(*x));
xombe__dec_core_reset(&x->d);
xombe__dsd_logic_init(&x->s, &x->d);
xombe__fec_init_dstar(&x->fec);
xombe__pred_init(&x->pi);
x->ws = ws;
memset(x->ws, 0, sizeof(*x->ws));
x->ws->cap = XOMBE_CQ_CAP;
x->prev_b1 = -1;
}
/* nearest AMBE+2 pitch index in log f0, the lower index on ties */
static int a2_b0(float f0)
{
int b = 0;
if (f0 > XR_OCTAVE_F0)
f0 *= 0.5f;
while (b < XOMBE_B0_COUNT - 1 && f0 < xombe__w0_mid[b])
b++;
return b;
}
/* a[1..L] at harmonics of f0 -> AMBE+2 frame b0, b1 at L2 harmonics of f2: resampled linearly in harmonic
number, quantized against the prediction memory and stored */
static void requant(xombe_xc_rev *x, float f0, const float *a, int L, int b0, int b1, int L2, float f2,
const uint8_t v2[8], uint8_t d49[49])
{
float tgt[XOMBE_LMAX + 1], w[XOMBE_LMAX + 1];
xombe_cq_result res;
xombe_params rec;
int b[9], l, k;
tgt[0] = 0.0f;
for (l = 1; l <= L2; l++) {
float h = (float)l * f2 / f0, fr;
int i;
h = h < 1.0f ? 1.0f : h > (float)L ? (float)L : h;
i = (int)h;
fr = h - (float)i;
tgt[l] = (1.0f - fr) * a[i] + fr * a[i < L ? i + 1 : L];
}
xombe__cq_amp_weights(tgt, L2, XOMBE_CQ_QWEIGHT, XOMBE_CQ_WEIGHT_FLOOR, w);
xombe__cq_search_ambe2(x->ws, &x->pi, tgt, L2, w, XOMBE_CQ_N_PAIRS, XOMBE_CQ_N_GAIN, &res, NULL, NULL);
b[0] = b0;
b[1] = b1;
for (k = 2; k < 9; k++)
b[k] = res.b[k];
xombe__dequant(b, &x->pi, 0, &rec);
xombe__pred_store_voice(&x->pi, &rec, v2);
memset(d49, 0, 49);
xombe__put_fields(b, d49);
if (x->trace) {
x->trace->tL = L2;
memcpy(x->trace->tgt, tgt, sizeof(tgt));
x->trace->has_b = 1;
memcpy(x->trace->b, b, sizeof(b));
}
}
/* the voice set (f0, a[1..L]) with fields db of its D-STAR frame -> AMBE+2 voice or pulse frame */
static int voice(xombe_xc_rev *x, const int db[9], float f0, const float *a, int L, uint8_t d49[49])
{
static const uint8_t unvoiced[8];
int code = db[1] == 0 ? pulse_code[db[0]] : 0, b0, b1;
if (code) {
/* pulse positions by code, DVSI's choice for 26..31 varies (24 or 103) */
b0 = code <= 23 ? 103 : code <= 25 ? 30 : 24;
requant(x, f0, a, L, b0, code, XOMBE_PULSE_L, XR_PULSE_F0, unvoiced, d49);
return XOMBE_XC_OUT_PULSE;
}
b1 = vuv_map[x->prev_b1 <= 0 ? 0 : x->prev_b1 == 15 ? 1 : 2][db[1]];
/* DVSI's first-half codebook choice by the previous output's bands */
if (b1 == 0 && memchr(x->pi.v2, 0, 8))
b1 = 1;
else if (b1 == XOMBE_UNVOICED_B1 && memchr(x->pi.v2, 1, 8))
b1 = XOMBE_UNVOICED_B1 + 1;
b0 = a2_b0(f0);
requant(x, f0, a, L, b0, b1, xombe__lt[b0], xombe__w0[b0], xombe__vuv[b1], d49);
return XOMBE_XC_OUT_VOICE;
}
static int tone(xombe_xc_rev *x, int id, int ad, uint8_t d49[49])
{
xombe__tone_frame_bits(id, ad, d49);
xombe__pred_store_other(&x->pi, XOMBE_CLASS_TONE);
return XOMBE_XC_OUT_TONE;
}
static int silence(xombe_xc_rev *x, uint8_t d49[49])
{
xombe__unpack49(std_silence, d49);
xombe__pred_store_other(&x->pi, XOMBE_CLASS_SILENCE);
return XOMBE_XC_OUT_SILENCE;
}
int xombe__xc_rev_frame(xombe_xc_rev *x, const uint8_t in[9], unsigned flags, uint8_t out[9])
{
xombe_dsd_logic *s = &x->s;
const xombe_set *p = &x->d.p2;
xombe_xr_trace *tr = x->trace;
xombe_ds_frame f;
xombe_fec_stats st;
uint8_t d49[49], bits[7];
int lost = (flags & XOMBE_FLAG_LOST) != 0, ic, o;
if (lost) {
xombe__dsd_start_frame(s, &x->d, NULL, 0, 0, 0);
} else {
uint8_t data[XOMBE_DS_DATA_BITS];
unsigned fl = xombe_fec_decode(&x->fec, in, bits, &st);
xombe__ds_unpack(bits, data);
xombe__ds_frame_from_data(data, &f);
xombe__dsd_start_frame(s, &x->d, &f, fl, st.eps_t, st.eps1);
x->d.decision.e0 = st.eps0;
x->d.decision.e1 = st.eps1;
}
xombe__dec_skip_synth(&x->d);
if (s->log == XOMBE_DSD_LOG_MUTE)
ic = XOMBE_XR_IN_MUTE;
else if (s->log == XOMBE_DSD_LOG_NULL)
ic = XOMBE_XR_IN_NULL;
else if (x->d.decision.conceal != XOMBE_CONCEAL_NONE)
ic = XOMBE_XR_IN_REPEAT;
else
ic = s->log == XOMBE_DSD_LOG_TONE ? XOMBE_XR_IN_TONE : XOMBE_XR_IN_VOICE;
if (tr) {
memset(tr, 0, sizeof(*tr));
tr->in_cls = ic;
tr->scls = p->cls;
tr->tid = tr->AD = -1;
if (!lost) {
tr->has_db = 1;
memcpy(tr->db, f.b, sizeof(f.b));
}
if (p->cls == XOMBE_CLASS_VOICE || p->cls == XOMBE_CLASS_SILENCE) {
tr->has_par = 1;
tr->f0 = p->f0;
tr->L = p->L;
memcpy(tr->a, p->a, sizeof(tr->a));
}
}
if (ic == XOMBE_XR_IN_VOICE) {
x->have_last = 1;
memcpy(x->last_db, f.b, sizeof(f.b));
o = voice(x, f.b, p->f0, p->a, p->L, d49);
x->prev_b1 = f.b[1];
} else if (ic == XOMBE_XR_IN_TONE) {
x->have_tone = 1;
x->tone_id = f.tid;
x->tone_ad = f.AD;
x->prev_b1 = -1;
o = tone(x, f.tid, f.AD, d49);
if (tr) {
tr->tid = f.tid;
tr->AD = f.AD;
}
} else if (ic == XOMBE_XR_IN_REPEAT && p->cls == XOMBE_CLASS_VOICE && x->have_last) {
o = voice(x, x->last_db, p->f0, p->a, p->L, d49);
} else if (ic == XOMBE_XR_IN_REPEAT && p->cls == XOMBE_CLASS_TONE && x->have_tone) {
o = tone(x, x->tone_id, x->tone_ad, d49);
if (tr)
tr->tid = x->tone_id;
} else {
if (ic != XOMBE_XR_IN_REPEAT)
x->prev_b1 = -1;
o = silence(x, d49);
}
xombe__pack49(d49, bits);
xombe__fec_encode_dmr(bits, out);
x->out = o;
if (tr)
memcpy(tr->d49, d49, 49);
return 1;
}
+146
View File
@@ -0,0 +1,146 @@
#include <math.h>
#include <string.h>
#include "frontend.h"
#include "../tables/dsp_tables.h"
#include "../common/cquant.h"
#if XOMBE_HAVE_DSTAR
#include "../dstar/dstar_enc.h"
/* D-STAR back end's workspace: the two emits never overlap, and xombe__cq_prepare rebuilds its maps when the
table set changes, so D-STAR output is unaffected */
#define A2_CQ_WS(e) (&XOMBE_DS_ENC(e)->ws)
#else
#define A2_CQ_WS(e) ((xombe_cq_ws *)(void *)(e)->cq.bytes)
XOMBE_STATIC_ASSERT(sizeof(xombe_cq_ws) <= XOMBE_ENC_CQ_SIZE, cq_ws_fits_XOMBE_ENC_CQ_SIZE);
#endif
/* AMBE+2 back end, phases B and D of frontend.h */
/* pitch index nearest fhat on a log scale, ties to the higher pitch (xombe__w0 descends) */
static int nearest_pitch_index(float fhat)
{
int b = 0;
while (b < XOMBE_B0_COUNT - 1 && fhat < xombe__w0_mid[b])
b++;
return b;
}
static int any_above_half(const float a[8])
{
int j;
for (j = 0; j < 8; j++)
if (a[j] > 0.5f)
return 1;
return 0;
}
static void choose_pitch_and_voicing(xombe_enc *e, xombe_fe_frame *a, xombe_a2_frame *f)
{
float w1[8], w2[8], f0, fh1;
int *b = f->b;
xombe__fe_voice(e, a);
b[0] = nearest_pitch_index(a->fstar);
f0 = xombe__w0[b[0]];
fh1 = e->pi.cls == XOMBE_CLASS_VOICE ? sqrtf(e->pi.f0 * f0) : f0;
xombe__voicing_soft(e, &a->S1, fh1, e->voicing_scale, f->soft1, w1);
xombe__voicing_soft_sp(e, xombe__fe_s2_prepared(e, a), f0, e->voicing_scale, f->soft2, w2);
if (!a->speech1)
memset(f->soft1, 0, sizeof(f->soft1));
if (!a->speech2)
memset(f->soft2, 0, sizeof(f->soft2));
b[1] = xombe__choose_b1(f->soft2, w2, f->soft1, w1, e->pi.v2);
xombe__v2_from_b1(b[1], f->v2);
}
/* voice frames only, silence's gain offset and fixed L stay open loop. the workspace starts zeroed
(xombe_enc_init), cap is set on every call */
static void quantize_closed(xombe_enc *e, int L, const float *target, int b[9])
{
xombe_cq_ws *ws = A2_CQ_WS(e);
float w[XOMBE_LMAX + 1];
xombe_cq_result res;
int k;
ws->cap = XOMBE_CQ_CAP;
xombe__cq_amp_weights(target, L, XOMBE_CQ_QWEIGHT, XOMBE_CQ_WEIGHT_FLOOR, w);
xombe__cq_search_ambe2(ws, &e->pi, target, L, w, XOMBE_CQ_N_PAIRS, XOMBE_CQ_N_GAIN, &res, NULL, NULL);
for (k = 2; k < 9; k++)
b[k] = res.b[k];
}
static void emit_quantized(xombe_enc *e, int silence, int L, float target[XOMBE_LMAX + 1], int b[9],
const uint8_t v2[8], uint8_t d[49])
{
int l;
for (l = 1; l <= L; l++)
target[l] = xombe__clamp_amp(target[l]);
XOMBE_TAP(e, XOMBE_STAGE_TARGET, silence ? XOMBE_SILENCE_F0 : xombe__w0[b[0]], target + 1, L);
if (!silence && e->cfg.dmr_quant == XOMBE_ENC_QUANT_CLOSED)
quantize_closed(e, L, target, b);
else
xombe__quantize(&e->pi, silence, L, target, b);
memset(d, 0, 49);
xombe__put_fields(b, d);
if (silence) {
xombe__pred_store_other(&e->pi, XOMBE_CLASS_SILENCE);
} else {
xombe_params rec;
xombe__dequant(b, &e->pi, 0, &rec);
xombe__pred_store_voice(&e->pi, &rec, v2);
}
}
static void emit_voice(xombe_enc *e, const xombe_fe_frame *a, const xombe_a2_frame *f, const xombe_be_ns *ns,
int b[9], uint8_t d[49])
{
float f0 = xombe__w0[b[0]], Pw[XOMBE_SPEC_BINS], target[XOMBE_LMAX + 1];
int L = xombe__lt[b[0]];
xombe__kern_bin_power(&a->S2, a->win_sum2, Pw);
xombe__enc_integrate(Pw, L, f0, target);
xombe__enc_hf_precomp(target, L, f0);
if (e->cfg.ns)
xombe__ns_apply_voice(ns->G2, target, L, f0, f->v2);
emit_quantized(e, 0, L, target, b, f->v2, d);
}
static void emit_silence(xombe_enc *e, uint8_t d[49])
{
static const uint8_t no_voicing[8];
float target[XOMBE_LMAX + 1];
int b[9];
xombe__cn_targets(e, target);
if (e->cfg.ns)
xombe__ns_apply_silence(e, target, XOMBE_SILENCE_L, XOMBE_SILENCE_F0);
b[0] = XOMBE_SILENCE_B0;
b[1] = XOMBE_SILENCE_B1;
emit_quantized(e, 1, XOMBE_SILENCE_L, target, b, no_voicing, d);
}
void xombe__a2_voicing(xombe_enc *e, xombe_fe_frame *a, xombe_a2_frame *f, xombe_be_ns *ns)
{
f->cls = a->tone ? XOMBE_CLASS_TONE : (a->active || !e->cfg.dmr_dtx) ? XOMBE_CLASS_VOICE : XOMBE_CLASS_SILENCE;
memset(f->v2, 0, sizeof(f->v2));
memset(f->soft1, 0, sizeof(f->soft1));
memset(f->soft2, 0, sizeof(f->soft2));
if (f->cls == XOMBE_CLASS_VOICE)
choose_pitch_and_voicing(e, a, f);
ns->no_band_voiced[0] = !any_above_half(f->soft1);
ns->no_band_voiced[1] = !any_above_half(f->soft2);
ns->mem = &e->ns_mem;
if (e->cfg.ns)
xombe__ns_bin_voicing(f->v2, 1, ns->vbin);
}
void xombe__a2_emit(xombe_enc *e, const xombe_fe_frame *a, xombe_a2_frame *f, const xombe_be_ns *ns,
uint8_t bits[7])
{
uint8_t d[49];
if (f->cls == XOMBE_CLASS_TONE) {
xombe__tone_frame_bits(a->tone_id, a->tone_ad, d);
xombe__pred_store_other(&e->pi, XOMBE_CLASS_TONE);
} else if (f->cls == XOMBE_CLASS_VOICE) {
emit_voice(e, a, f, ns, f->b, d);
} else {
emit_silence(e, d);
}
xombe__pack49(d, bits);
}
+53
View File
@@ -0,0 +1,53 @@
#include <math.h>
#include <string.h>
#include "../internal.h"
#include "../tables/dsp_tables.h"
#include "kernels.h"
void xombe__enc_set_window(xombe_enc *e, int n)
{
if (e->win_len == n)
return;
e->win_len = n;
e->win_sum2 = xombe__hamming_sum2(n);
#if !XOMBE_KERNELS_Q15 /* q15: the kernel builds e->win and its own table, e->wtab stays unused */
{
int q;
xombe__hamming(e->win, n);
for (q = 0; q < XOMBE_WTAB_LEN; q++)
e->wtab[q] = xombe__hamming_dtft(n, q, (long)XOMBE_WTAB_OVERSAMPLE * XOMBE_FFT);
}
#endif
xombe__kern_window_init(e);
}
void xombe__enc_integrate(const float *P, int L, float f0, float *a)
{
float step = f0 * XOMBE_FFT;
int l, k;
a[0] = 0.0f;
for (l = 1; l <= L; l++) {
float lo = ((float)l - 0.5f) * step, hi = ((float)l + 0.5f) * step, m2 = 0.0f;
int k0 = (int)floorf(lo + 0.5f), k1 = (int)ceilf(hi + 0.5f);
if (k0 < 0)
k0 = 0;
if (k1 > XOMBE_SPEC_BINS - 1)
k1 = XOMBE_SPEC_BINS - 1;
/* bin overlap with [lo, hi], bounds may include bins that do not overlap */
for (k = k0; k <= k1; k++) {
float c = fminf((float)k + 0.5f, hi) - fmaxf((float)k - 0.5f, lo);
if (c > 0.0f)
m2 += (c > 1.0f ? 1.0f : c) * P[k];
}
a[l] = m2 > 0.0f ? 0.5f * log2f(m2) : XOMBE_AMP_MIN;
if (a[l] < XOMBE_AMP_MIN)
a[l] = XOMBE_AMP_MIN;
}
}
void xombe__enc_hf_precomp(float *a, int L, float f0)
{
int l;
for (l = 1; l <= L; l++)
a[l] -= 0.5f * xombe__hf_tilt((float)l * f0);
}
+37
View File
@@ -0,0 +1,37 @@
#include <string.h>
#include "../internal.h"
#define CN_FAST_UPDATES 16
#define CN_CLIP_RATIO 4.0f
#define CN_CLIP_MIN_POWER 1.0f
#define CN_LEVEL_OFFSET 0.21f
void xombe__cn_half(xombe_enc *e, const float *P, int noise, int confident_run)
{
int k;
if (!e->cn_ready) {
if (noise) {
memcpy(e->cn_power, P, sizeof(e->cn_power));
e->cn_ready = 1;
e->cn_updates = 0;
}
return;
}
if (confident_run >= XOMBE_CONFIDENT_RUN) {
float alpha = e->cn_updates < CN_FAST_UPDATES ? 0.5f : 0.1f;
for (k = 0; k < XOMBE_SPEC_BINS; k++) {
float ceiling = CN_CLIP_RATIO * (e->cn_power[k] > CN_CLIP_MIN_POWER ? e->cn_power[k] : CN_CLIP_MIN_POWER);
float p = P[k] < ceiling ? P[k] : ceiling;
e->cn_power[k] = (1.0f - alpha) * e->cn_power[k] + alpha * p;
}
e->cn_updates++;
}
}
void xombe__cn_targets(const xombe_enc *e, float *a)
{
int l;
xombe__enc_integrate(e->cn_power, XOMBE_SILENCE_L, XOMBE_SILENCE_F0, a);
for (l = 1; l <= XOMBE_SILENCE_L; l++)
a[l] = xombe__clamp_amp(a[l] + CN_LEVEL_OFFSET);
}
+199
View File
@@ -0,0 +1,199 @@
#include <string.h>
#include "frontend.h"
#include "../common/prof.h"
#include "../dstar/dstar_internal.h"
#if XOMBE_HAVE_DSTAR
#include "../dstar/dstar_enc.h"
#endif
#define INPUT_HPF_GAIN 0.9427f
#if XOMBE_HAVE_DSTAR
#define ALL_OUTPUTS (XOMBE_ENC_DMR | XOMBE_ENC_DSTAR)
#else
#define ALL_OUTPUTS XOMBE_ENC_DMR
#endif
static const uint8_t silence_frame_bytes[7] = XOMBE_SILENCE_FRAME;
static const uint8_t null_bits[7] = XOMBE_DS_NULL_BITS;
#if !XOMBE_HAVE_DSTAR
static const uint8_t null_frame_bytes[XOMBE_DS_FRAME_BYTES] = XOMBE_DS_NULL_FRAME;
#endif
void xombe_enc_cfg_default(xombe_enc_cfg *cfg)
{
cfg->ns = 1;
cfg->ns_strength_permille = 500;
cfg->dmr_dtx = 1;
cfg->tones = 1;
cfg->voicing_scale_permille = 350;
cfg->outputs = XOMBE_ENC_DMR;
cfg->dstar_dtx = 0;
cfg->dmr_quant = XOMBE_ENC_QUANT_CLOSED;
}
XOMBE_STATIC_ASSERT(sizeof(struct xombe_enc) <= XOMBE_ENC_SIZE, encoder_state_fits_XOMBE_ENC_SIZE);
#if XOMBE_HAVE_DSTAR
XOMBE_STATIC_ASSERT(XOMBE_ENC_DSTAR_DELAY == XOMBE_ENC_DELAY + XOMBE_ENC_LOOKAHEAD, dstar_delay_is_the_lookahead);
#endif
int xombe_enc_delay(const xombe_enc *e)
{
return XOMBE_ENC_DELAY + e->lookahead;
}
size_t xombe_enc_size(void)
{
return sizeof(struct xombe_enc);
}
static int cfg_valid(const xombe_enc_cfg *cfg)
{
return cfg->ns_strength_permille >= 0 && cfg->ns_strength_permille <= 1000 && cfg->voicing_scale_permille > 0 &&
(cfg->outputs & ~ALL_OUTPUTS) == 0 &&
(cfg->dmr_quant == XOMBE_ENC_QUANT_CLOSED || cfg->dmr_quant == XOMBE_ENC_QUANT_OPEN);
}
xombe_enc *xombe_enc_init(void *mem, const xombe_enc_cfg *cfg)
{
xombe_enc *e = mem;
xombe_enc_cfg c;
if (cfg)
c = *cfg;
else
xombe_enc_cfg_default(&c);
if (!e || !cfg_valid(&c))
return NULL;
c.ns = c.ns != 0;
c.dmr_dtx = c.dmr_dtx != 0;
c.tones = c.tones != 0;
c.dstar_dtx = c.dstar_dtx != 0;
if (!c.outputs)
c.outputs = XOMBE_ENC_DMR;
memset(e, 0, sizeof(*e));
e->cfg = c;
e->ns_strength = (float)c.ns_strength_permille / 1000.0f;
e->voicing_scale = (float)c.voicing_scale_permille / 1000.0f;
xombe__hpf_init(&e->hpf, INPUT_HPF_GAIN);
xombe__pitch_init(e);
e->base_win_sum2 = xombe__hamming_sum2(XOMBE_BASE_WINDOW);
xombe__enc_set_window(e, XOMBE_BASE_WINDOW);
xombe__pred_init(&e->pi);
e->tone_prev_id = -1;
#if XOMBE_HAVE_DSTAR
if (c.outputs & XOMBE_ENC_DSTAR)
e->lookahead = XOMBE_ENC_LOOKAHEAD;
xombe__ds_enc_init(e);
#endif
return e;
}
void xombe__enc_set_tap(xombe_enc *e, xombe_tap_fn fn, void *ctx)
{
e->tap = fn;
e->tap_ctx = ctx;
}
#ifdef XOMBE_PROF_DWT
unsigned long xombe__pf[16];
#endif
static int tone_valid(const xombe_enc_tone *t)
{
return !t || xombe__tone_valid(t->id, t->ad);
}
/* ambe2 and dstar may be NULL, a disabled output gets its silence frame. a forced tone replaces only phase D's
class, so analysis and background tracking see the frame as unforced */
static int encode(xombe_enc *e, const int16_t pcm[XOMBE_FRAME], const xombe_enc_tone *tone, uint8_t *ambe2,
uint8_t *dstar)
{
xombe_fe_frame a;
xombe_a2_frame f2;
xombe_be_ns ns[XOMBE_BE_COUNT], *be[XOMBE_BE_COUNT];
const uint8_t *req;
int i, ready;
memmove(e->tone_req[1], e->tone_req[0], sizeof(e->tone_req) - sizeof(e->tone_req[0]));
e->tone_req[0][0] = (uint8_t)(tone ? tone->id : 0);
e->tone_req[0][1] = (uint8_t)(tone ? tone->ad : 0);
req = e->tone_req[XOMBE_ENC_DELAY + e->lookahead];
XOMBE_PF(0, ready = xombe__fe_push(e, pcm));
#if XOMBE_HAVE_DSTAR
if ((e->cfg.outputs & XOMBE_ENC_DSTAR) && e->cfg.tones)
XOMBE_PF(7, xombe__ds_tone_push(e));
#endif
if (!ready) {
if (ambe2)
memcpy(ambe2, silence_frame_bytes, 7);
if (dstar)
memcpy(dstar, null_bits, 7);
return 0;
}
for (i = 0; i < XOMBE_BE_COUNT; i++)
be[i] = NULL;
XOMBE_PF(1, xombe__fe_analyze(e, &a));
if (e->cfg.outputs & XOMBE_ENC_DMR) {
be[XOMBE_BE_AMBE2] = &ns[XOMBE_BE_AMBE2];
XOMBE_PF(2, xombe__a2_voicing(e, &a, &f2, be[XOMBE_BE_AMBE2]));
}
#if XOMBE_HAVE_DSTAR
if (e->cfg.outputs & XOMBE_ENC_DSTAR) {
be[XOMBE_BE_DSTAR] = &ns[XOMBE_BE_DSTAR];
XOMBE_PF(3, xombe__ds_enc_voicing(e, &a, be[XOMBE_BE_DSTAR]));
}
#endif
XOMBE_PF(4, xombe__fe_background(e, &a, be));
if (be[XOMBE_BE_AMBE2]) {
uint8_t tmp[7];
if (req[0]) {
f2.cls = XOMBE_CLASS_TONE;
a.tone_id = req[0];
a.tone_ad = req[1];
}
XOMBE_PF(5, xombe__a2_emit(e, &a, &f2, be[XOMBE_BE_AMBE2], ambe2 ? ambe2 : tmp));
} else if (ambe2) {
memcpy(ambe2, silence_frame_bytes, 7);
}
#if XOMBE_HAVE_DSTAR
if (be[XOMBE_BE_DSTAR]) {
uint8_t tmp[7];
if (req[0])
xombe__ds_enc_force_tone(e, req[0], req[1]);
XOMBE_PF(6, xombe__ds_enc_frame(e, &a, be[XOMBE_BE_DSTAR], dstar ? dstar : tmp));
} else if (dstar) {
memcpy(dstar, null_bits, 7);
}
#else
if (dstar)
memcpy(dstar, null_bits, 7);
#endif
return 1;
}
static const int16_t zeros[XOMBE_FRAME];
int xombe_enc_frame(xombe_enc *e, const int16_t *pcm, const xombe_enc_tone *tone, uint8_t dmr[XOMBE_FRAME_BYTES],
uint8_t dstar[XOMBE_FRAME_BYTES])
{
uint8_t a[7], d[7];
int r = xombe_enc_frame_bits(e, pcm, tone, dmr ? a : NULL, dstar ? d : NULL);
if (r < 0)
return r;
if (dmr)
xombe__fec_encode_dmr(a, dmr);
#if XOMBE_HAVE_DSTAR
if (dstar)
xombe__ds_fec_encode_bits(d, dstar);
#else
if (dstar)
memcpy(dstar, null_frame_bytes, XOMBE_DS_FRAME_BYTES);
#endif
return r;
}
int xombe_enc_frame_bits(xombe_enc *e, const int16_t *pcm, const xombe_enc_tone *tone,
uint8_t dmr[XOMBE_BITS_BYTES], uint8_t dstar[XOMBE_BITS_BYTES])
{
if (!tone_valid(tone))
return -1;
return encode(e, pcm ? pcm : zeros, tone, dmr, dstar);
}
+166
View File
@@ -0,0 +1,166 @@
#include <math.h>
#include <string.h>
#include "frontend.h"
#include "../tables/dsp_tables.h"
#include "../common/prof.h"
/* each call appends one frame to the XOMBE_ENC_BUF-sample history. the encoded frame starts at frame_base(e)
<= FRAME_BASE, pitch analysis runs on the frame before the newest (so its one-frame look-ahead is complete) */
#define FRAME XOMBE_FRAME
#define FRAME_BASE (XOMBE_ENC_BUF - (XOMBE_ENC_DELAY + 1 + XOMBE_ENC_LOOKAHEAD) * FRAME)
#define PITCH_FRAME_BASE (XOMBE_ENC_BUF - 2 * FRAME)
#define HALF1_CENTRE 40
#define HALF2_CENTRE 120
#define BASE_WINDOW XOMBE_BASE_WINDOW
XOMBE_STATIC_ASSERT(FRAME_BASE + HALF1_CENTRE - (XOMBE_MAX_WINDOW - 1) / 2 >= 0, analysis_window_in_buffer);
XOMBE_STATIC_ASSERT(FRAME_BASE + HALF2_CENTRE + (XOMBE_MAX_WINDOW - 1) / 2 < XOMBE_ENC_BUF, analysis_window_end);
XOMBE_STATIC_ASSERT(FRAME_BASE == XOMBE_ENC_BUF - XOMBE_ENC_RAW, raw_history_starts_at_frame);
XOMBE_STATIC_ASSERT(HALF1_CENTRE - (BASE_WINDOW - 1) / 2 >= -XOMBE_ENC_RAW_LEAD, vad_flat_window_in_raw_lead);
XOMBE_STATIC_ASSERT(XOMBE_TONE_SEG <= XOMBE_ENC_RAW, tone_segment_in_buffer);
XOMBE_STATIC_ASSERT(PITCH_FRAME_BASE + HALF2_CENTRE - XOMBE_PITCH_HALF - XOMBE_PITCH_LPF_HALF >= 0,
pitch_window_in_buffer);
XOMBE_STATIC_ASSERT(PITCH_FRAME_BASE + HALF2_CENTRE + XOMBE_PITCH_HALF + XOMBE_PITCH_LPF_HALF < XOMBE_ENC_BUF,
pitch_window_end);
/* one twiddle table serves both transform sizes */
XOMBE_STATIC_ASSERT(XOMBE_TW_N % XOMBE_FFT == 0, twiddles_cover_analysis_fft);
XOMBE_STATIC_ASSERT(XOMBE_TW_N % XOMBE_TONE_FFT == 0, twiddles_cover_tone_fft);
#define HANGOVER_FRAMES 2
/* returns 1 if active, counting hangover */
static int detect_activity(xombe_enc *e, xombe_fe_frame *f)
{
float tap[2];
const int h = (BASE_WINDOW - 1) / 2;
xombe__kern_spectrum(f->xh + HALF1_CENTRE, xombe__base_win, BASE_WINDOW, &f->S1);
xombe__kern_spectrum(f->xh + HALF2_CENTRE, xombe__base_win, BASE_WINDOW, &f->S2);
xombe__kern_bin_power(&f->S1, e->base_win_sum2, f->P1);
xombe__kern_bin_power(&f->S2, e->base_win_sum2, f->P2);
xombe__vad_half(e, f->P1, xombe__vad_flat(f->raw + HALF1_CENTRE - h, BASE_WINDOW), &f->speech1, &f->vad1);
e->confident_run = (!f->speech1 && f->vad1 < XOMBE_CONFIDENT) ? e->confident_run + 1 : 0;
f->run1 = e->confident_run;
xombe__vad_half(e, f->P2, xombe__vad_flat(f->raw + HALF2_CENTRE - h, BASE_WINDOW), &f->speech2, &f->vad2);
e->confident_run = (!f->speech2 && f->vad2 < XOMBE_CONFIDENT) ? e->confident_run + 1 : 0;
f->run2 = e->confident_run;
tap[0] = (float)f->speech1;
tap[1] = f->vad1;
XOMBE_TAP(e, XOMBE_STAGE_VAD, 0.0f, tap, 2);
tap[0] = (float)f->speech2;
tap[1] = f->vad2;
XOMBE_TAP(e, XOMBE_STAGE_VAD, 0.0f, tap, 2);
if (f->speech1 || f->speech2) {
e->hangover = HANGOVER_FRAMES;
return 1;
}
if (e->hangover > 0) {
e->hangover--;
return 1;
}
return 0;
}
static int frame_base(const xombe_enc *e)
{
return XOMBE_ENC_BUF - (XOMBE_ENC_DELAY + 1 + e->lookahead) * FRAME;
}
/* pitch analyses sit in a ring of XOMBE_ENC_DELAY slots, the tracked frame is the oldest, whose slot the next
call overwrites. its period goes to e->period[0], the encoded frame is e->lookahead older */
int xombe__fe_push(xombe_enc *e, const int16_t pcm[XOMBE_FRAME])
{
int k = e->calls;
int i;
memmove(e->raw, e->raw + FRAME, sizeof(e->raw[0]) * (XOMBE_ENC_RAW_LEAD + XOMBE_ENC_RAW - FRAME));
memmove(e->xh, e->xh + FRAME, sizeof(float) * (XOMBE_ENC_BUF - FRAME));
for (i = 0; i < FRAME; i++) {
e->raw[XOMBE_ENC_RAW_LEAD + XOMBE_ENC_RAW - FRAME + i] = pcm[i];
e->xh[XOMBE_ENC_BUF - FRAME + i] = xombe__hpf_step(&e->hpf, (float)pcm[i]);
}
if (k < XOMBE_ENC_DELAY + e->lookahead)
e->calls++;
if (k >= 1) {
xombe__pitch_errors(e, e->xh + PITCH_FRAME_BASE + HALF2_CENTRE, e->pitch_slot);
e->pitch_slot = (e->pitch_slot + 1) % XOMBE_ENC_DELAY;
}
if (k >= XOMBE_ENC_DELAY) {
int cur = e->pitch_slot;
#if XOMBE_ENC_LOOKAHEAD
for (i = e->lookahead; i > 0; i--)
e->period[i] = e->period[i - 1];
#endif
e->period[0] = xombe__pitch_track(e, cur, (cur + 1) % XOMBE_ENC_DELAY, (cur + 2) % XOMBE_ENC_DELAY);
}
return k >= XOMBE_ENC_DELAY + e->lookahead;
}
const int16_t *xombe__fe_raw(const xombe_enc *e, int back)
{
return e->raw + XOMBE_ENC_RAW_LEAD + XOMBE_ENC_RAW - (back + 1) * FRAME;
}
void xombe__fe_analyze(xombe_enc *e, xombe_fe_frame *a)
{
a->xh = e->xh + frame_base(e);
a->raw = xombe__fe_raw(e, XOMBE_ENC_DELAY + e->lookahead);
a->active = detect_activity(e, a);
a->tone_det = a->tone_det_id = a->tone_det_ad = 0;
a->tone = a->tone_id = a->tone_ad = 0;
if (e->cfg.tones && (e->cfg.outputs & XOMBE_ENC_DMR)) {
XOMBE_PF(10, a->tone_det = xombe__tone_detect(e, a->raw, &a->tone_det_id, &a->tone_det_ad));
a->tone = xombe__tone_decide(e, a->tone_det, a->tone_det_id, a->tone_det_ad, &a->tone_id, &a->tone_ad);
}
a->period = e->period[e->lookahead];
a->have_voice = 0;
a->have_lf2 = 0;
a->nw = BASE_WINDOW;
a->fstar = 0.0f;
a->win_sum2 = e->base_win_sum2;
}
void xombe__fe_voice(xombe_enc *e, xombe_fe_frame *a)
{
if (a->have_voice)
return;
a->nw = xombe__pitch_window_len(a->period);
xombe__enc_set_window(e, a->nw);
if (a->nw != BASE_WINDOW) {
xombe__kern_spectrum(a->xh + HALF1_CENTRE, e->win, a->nw, &a->S1);
xombe__kern_spectrum(a->xh + HALF2_CENTRE, e->win, a->nw, &a->S2);
}
a->fstar = 1.0f / xombe__pitch_refine(e, &a->S2, a->period);
a->win_sum2 = e->win_sum2;
a->have_voice = 1;
a->have_lf2 = 0;
}
const xombe_lf_spec *xombe__fe_s2_prepared(xombe_enc *e, xombe_fe_frame *a)
{
if (!a->have_lf2) {
xombe__voicing_prepare(e, &a->S2, &a->lf2);
a->have_lf2 = 1;
}
return &a->lf2;
}
void xombe__fe_background(xombe_enc *e, const xombe_fe_frame *a, xombe_be_ns *be[XOMBE_BE_COUNT])
{
if (e->cfg.ns) {
float X1[XOMBE_NS_BINS], X2[XOMBE_NS_BINS];
const xombe_be_ns *primary = be[XOMBE_BE_AMBE2] ? be[XOMBE_BE_AMBE2] : be[XOMBE_BE_DSTAR];
int i;
xombe__ns_bins(a->P1, X1);
xombe__ns_bins(a->P2, X2);
xombe__ns_update(e, X1, a->speech1, a->run1, primary->no_band_voiced[0]);
for (i = 0; i < XOMBE_BE_COUNT; i++)
if (be[i])
xombe__ns_gain(e, be[i]->mem, X1, a->speech1, a->vad1, be[i]->vbin, be[i]->G1);
xombe__ns_update(e, X2, a->speech2, a->run2, primary->no_band_voiced[1]);
for (i = 0; i < XOMBE_BE_COUNT; i++)
if (be[i])
xombe__ns_gain(e, be[i]->mem, X2, a->speech2, a->vad2, be[i]->vbin, be[i]->G2);
}
xombe__cn_half(e, a->P1, !a->speech1, a->run1);
xombe__cn_half(e, a->P2, !a->speech2, a->run2);
}
+90
View File
@@ -0,0 +1,90 @@
#ifndef XOMBE_FRONTEND_H
#define XOMBE_FRONTEND_H
/* encoder front end, shared by the back ends (AMBE+2 ambe2_enc.c, D-STAR dstar/dstar_enc.c) enabled in
e->cfg.outputs. encoder.c runs each frame in four phases:
A front end once per frame: xombe__fe_push, xombe__fe_analyze, and on demand xombe__fe_voice (costly,
later calls free)
B voicing per back end, filling its xombe_be_ns
C shared background tracking (xombe__fe_background): one noise update per half, no_band_voiced taken from
the primary back end (AMBE+2 if enabled, else D-STAR), then per back end gains, then comfort noise
D emit per back end with its own gains, a forced tone (encoder.c) replaces the class here, B and C saw the
frame as unforced
a disabled back end does no B or D work and keeps no gain memory, so AMBE+2 output does not depend on
whether D-STAR is enabled.
after xombe__fe_voice a back end may also read nw, fstar, win_sum2, and S1/S2 under nw, and e->win, e->wtab,
and the kernels' window tables stay set to nw until the next frame */
#include "kernels.h"
/* phase A record of the frame being encoded */
typedef struct {
const float *xh; /* high-passed input at frame start */
const int16_t *raw; /* unfiltered input at frame start, XOMBE_ENC_RAW_LEAD samples of history before it */
/* half-frame spectra centred on samples 40 and 120, under XOMBE_BASE_WINDOW until xombe__fe_voice, then
under the nw-point pitch-adaptive window */
xombe_spec S1, S2;
float P1[XOMBE_SPEC_BINS], P2[XOMBE_SPEC_BINS]; /* bin powers under the base window */
int speech1, speech2; /* per-half VAD decisions */
float vad1, vad2; /* per-half VAD metrics, log2 units */
int run1, run2; /* confident-background run after each half */
int active; /* either half speech, or within hangover */
/* AMBE+2 tone detector result (all 0 when cfg.tones or AMBE+2 is off), then the decision after confirmation
and hold: tone 1 with the ID and amplitude to send */
int tone_det, tone_det_id, tone_det_ad;
int tone, tone_id, tone_ad;
float period; /* tracked pitch period, samples */
/* valid when have_voice */
int have_voice;
int nw; /* pitch-adaptive window length, e->win, e->wtab, and the kernels' window follow it */
float fstar; /* refined fundamental, cycles/sample */
float win_sum2; /* window sum of squares */
/* S2 under nw prepared for the voicing metric, valid when have_lf2 */
int have_lf2;
xombe_lf_spec lf2;
} xombe_fe_frame;
/* back end indexes into the xombe__fe_background array */
#define XOMBE_BE_AMBE2 0
#define XOMBE_BE_DSTAR 1
#define XOMBE_BE_COUNT 2
/* one back end's part in background tracking, phase B -> C -> D */
typedef struct {
/* in, from phase B */
int no_band_voiced[2]; /* per half: no band clearly voiced, noise update input when primary */
uint8_t vbin[XOMBE_NS_BINS]; /* voicing at each suppression bin centre, both halves,
needed only when cfg.ns */
xombe_ns_mem *mem; /* back end's own gain smoothing memory */
/* out, from phase C when cfg.ns: per-half suppression gains */
float G1[XOMBE_NS_BINS], G2[XOMBE_NS_BINS];
} xombe_be_ns;
/* returns 1 once a frame is ready to encode, after XOMBE_ENC_DELAY + e->lookahead calls */
int xombe__fe_push(xombe_enc *e, const int16_t pcm[XOMBE_FRAME]);
/* unfiltered input from the start of the frame `back` frames before the newest (0 = newest, the encoded frame is
XOMBE_ENC_DELAY + e->lookahead back), XOMBE_ENC_RAW_LEAD samples of history before the oldest */
const int16_t *xombe__fe_raw(const xombe_enc *e, int back);
/* call once for each push that returned 1 */
void xombe__fe_analyze(xombe_enc *e, xombe_fe_frame *a);
/* sets a->have_voice, no-op when already done */
void xombe__fe_voice(xombe_enc *e, xombe_fe_frame *a);
/* S2 under nw prepared for the voicing metric, shared by the back ends. kernels keep one prepared spectrum, so
call right before the S2 line fits */
const xombe_lf_spec *xombe__fe_s2_prepared(xombe_enc *e, xombe_fe_frame *a);
/* phase C, be[XOMBE_BE_*] NULL for disabled back ends, at least one enabled */
void xombe__fe_background(xombe_enc *e, const xombe_fe_frame *a, xombe_be_ns *be[XOMBE_BE_COUNT]);
/* AMBE+2 back end (ambe2_enc.c) */
typedef struct {
int cls; /* XOMBE_CLASS_VOICE, SILENCE or TONE */
int b[9]; /* voice frames: b0 and b1 after phase B, all after phase D */
float soft1[8], soft2[8]; /* soft band voicing per half, 0 unless voice */
uint8_t v2[8]; /* second-half band voicing, 0 unless voice */
} xombe_a2_frame;
void xombe__a2_voicing(xombe_enc *e, xombe_fe_frame *a, xombe_a2_frame *f, xombe_be_ns *ns);
void xombe__a2_emit(xombe_enc *e, const xombe_fe_frame *a, xombe_a2_frame *f, const xombe_be_ns *ns,
uint8_t bits[7]);
#endif
+131
View File
@@ -0,0 +1,131 @@
#include <string.h>
#include "kernels.h"
#include "../tables/dsp_tables.h"
void xombe__kern_spectrum(const float *centre, const float *w, int n, xombe_spec *S)
{
float buf[XOMBE_FFT];
int half = (n - 1) / 2, j;
memset(buf, 0, sizeof(buf));
for (j = -half; j <= half; j++)
buf[(j + XOMBE_FFT) % XOMBE_FFT] = centre[j] * w[half + j];
xombe__rfft(buf, S->b, XOMBE_FFT, xombe__fft_tw, XOMBE_TW_N);
}
void xombe__kern_bin_power(const xombe_spec *S, float sum_w2, float *P)
{
int k;
float scale = 1.0f / (XOMBE_FFT * sum_w2);
for (k = 0; k < XOMBE_SPEC_BINS; k++)
P[k] = (S->b[k].re * S->b[k].re + S->b[k].im * S->b[k].im) * scale;
}
void xombe__kern_window_init(xombe_enc *e)
{
(void)e;
}
void xombe__kern_pitch_acf(xombe_enc *e, const float *centre, int slot)
{
float u[XOMBE_PITCH_WIN], e0 = 0.0f;
int i, j, t;
for (i = 0; i < XOMBE_PITCH_WIN; i++) {
float s = 0.0f;
for (j = -XOMBE_PITCH_LPF_HALF; j <= XOMBE_PITCH_LPF_HALF; j++)
s += xombe__pitch_lpf[j + XOMBE_PITCH_LPF_HALF] * centre[i - XOMBE_PITCH_HALF - j];
e0 += s * s * xombe__pitch_w2[i];
u[i] = s * xombe__pitch_w2[i];
}
for (t = 0; t < XOMBE_PITCH_WIN; t++) {
float r = 0.0f;
for (i = 0; i + t < XOMBE_PITCH_WIN; i++)
r += u[i] * u[i + t];
e->pacf[slot].f[t] = r;
}
e->pe0[slot] = e0;
}
/* P on a quarter-sample grid, so K, k*P, and its integer part are exact */
float xombe__kern_error_at(const xombe_enc *e, int slot, float P)
{
const float *r = e->pacf[slot].f;
float e0 = e->pe0[slot], sum = r[0], val;
int k, K = (int)((float)(XOMBE_PITCH_WIN - 1) / P);
for (k = 1; k <= K; k++) {
float t = (float)k * P, f;
int i = (int)t;
f = t - (float)i;
sum += 2.0f * (f > 0.0f ? (1.0f - f) * r[i] + f * r[i + 1] : r[i]);
}
val = (e0 - P * sum) / (e0 * (1.0f - P * xombe__pitch_sum_w4));
return val > 0.0f ? val : 0.0f;
}
void xombe__kern_lf_prepare(xombe_enc *e, const xombe_spec *S, int kmin, int kmax, xombe_lf_spec *sp)
{
(void)e;
(void)kmin;
(void)kmax;
sp->S = S;
sp->g = 1.0f;
}
/* window values kept per harmonic for the residual pass, a wider harmonic recomputes the rest */
#define LINE_FIT_KEEP 64
/* window transform nu_bins from its centre, interpolated in e->wtab */
static float window_value(const xombe_enc *e, float nu_bins)
{
float x = fabsf(nu_bins) * XOMBE_WTAB_OVERSAMPLE;
int i = (int)x;
float f = x - (float)i;
if (i >= XOMBE_WTAB_LEN - 1)
return e->wtab[XOMBE_WTAB_LEN - 1];
return (1.0f - f) * e->wtab[i] + f * e->wtab[i + 1];
}
float xombe__kern_line_fit(const xombe_enc *e, const xombe_lf_spec *sp, float period, int kmin, int kmax,
float band_resid[8], float band_energy[8])
{
const xombe_cpx *S = sp->S->b;
float per_harm = XOMBE_FFT / period, total = 0.0f, wk[LINE_FIT_KEEP];
int k = kmin < 1 ? 1 : kmin, l = xombe__harmonic_of(k, period), next = l;
memset(band_resid, 0, 8 * sizeof(float));
memset(band_energy, 0, 8 * sizeof(float));
while (k <= kmax) {
int k0 = k, n = 0, band;
float sw_re = 0.0f, sw_im = 0.0f, ww = 0.0f, ee = 0.0f, resid = 0.0f, A_re = 0.0f, A_im = 0.0f;
do {
float w = window_value(e, (float)k - (float)l * per_harm);
sw_re += S[k].re * w;
sw_im += S[k].im * w;
ww += w * w;
ee += S[k].re * S[k].re + S[k].im * S[k].im;
if (n < LINE_FIT_KEEP)
wk[n] = w;
n++;
k++;
} while (k <= kmax && (next = xombe__harmonic_of(k, period)) == l);
if (l == 0) {
l = next;
continue;
}
/* residual summed term by term, ee - |sw|^2/ww cancels on a strongly harmonic band (relative error 1e-3
against 1e-4 in float) */
if (ww > 0.0f) {
A_re = sw_re / ww;
A_im = sw_im / ww;
}
for (n = 0; k0 < k; k0++, n++) {
float w = n < LINE_FIT_KEEP ? wk[n] : window_value(e, (float)k0 - (float)l * per_harm),
dr = S[k0].re - A_re * w, di = S[k0].im - A_im * w;
resid += dr * dr + di * di;
}
band = xombe__band_of(l, period);
band_resid[band] += resid;
band_energy[band] += ee;
total += resid;
l = next;
}
return total;
}
+32
View File
@@ -0,0 +1,32 @@
#ifndef XOMBE_KERN_Q15_H
#define XOMBE_KERN_Q15_H
/* helpers shared by the q15 kernels (kern_q15_*.c) */
#include <float.h>
#include "kernels.h"
#include "../dsp/q15ops.h"
static inline int round_q(float v)
{
return (int)(v + (v < 0.0f ? -0.5f : 0.5f));
}
/* block scale taking peak magnitude m to peak, 0 when m is 0 or subnormal enough to overflow the scale (block
counts as zero) */
static inline float q15_gain(float m, float peak)
{
float g = m > 0.0f ? peak / m : 0.0f;
return g <= FLT_MAX ? g : 0.0f;
}
/* |v| < 2^63 to float without the library call, top 31 bits through a 32-bit conversion */
static inline float i64_to_float(int64_t v)
{
int64_t a = v < 0 ? -v : v;
int sh = (a >> 31) ? 33 - q15_clz64((uint64_t)a) : 0;
float f = (float)(int32_t)(a >> sh) * (float)(1u << sh);
return v < 0 ? -f : f;
}
#endif
+130
View File
@@ -0,0 +1,130 @@
/* q15 line fit (kernels.h, XOMBE_KERNELS=q15): int16 block-scaled spectrum with exact prefix sums of |S|^2 and
exact 64-bit MACs, so the residual comes from ee - |sw|^2/ww in one pass without float cancellation */
#include <assert.h>
#include <string.h>
#include "kern_q15.h"
/* line fit table runs past the float table's end on its clamped last value, interpolating equal tail values
is exact */
XOMBE_STATIC_ASSERT(XOMBE_LF_WT_OFF >= XOMBE_WTAB_LEN, lf_table_padded);
/* weights (1 - f, f) in Q14 for the fraction f of Q16 position x */
static uint32_t lf_coef(int32_t x)
{
uint32_t f = (uint32_t)(x & 0xffff) >> 2;
return (f << 16) | (16384u - f);
}
/* n bins of re (im at XOMBE_LF_IM) against the window from entries w, w + XOMBE_WTAB_OVERSAMPLE, ..., weight
pair c, two bins per MAC */
static void lf_run(const int16_t *re, int n, const uint32_t *w, uint32_t c, int64_t *psr, int64_t *psi,
int64_t *pww)
{
int64_t sr = 0, si = 0, ww = 0;
const int16_t *end = re + (n & ~1);
for (; re != end; re += 2, w += 2 * XOMBE_WTAB_OVERSAMPLE) {
uint32_t wp = q15_pack_lsl2((uint32_t)(q15_smuad(w[0], c) >> 14),
(uint32_t)q15_smuad(w[XOMBE_WTAB_OVERSAMPLE], c));
sr = q15_smlald(q15_ld2(re), wp, sr);
si = q15_smlald(q15_ld2(re + XOMBE_LF_IM), wp, si);
ww = q15_smlald(wp, wp, ww);
}
if (n & 1) {
int32_t v = q15_smuad(w[0], c) >> 14;
sr += (int32_t)re[0] * v;
si += (int32_t)re[XOMBE_LF_IM] * v;
ww += v * v;
}
*psr = sr;
*psi = si;
*pww = ww;
}
/* low 32 bits of x >> sh, 0 < sh < 32 */
static uint32_t lf_shr(uint64_t x, int sh)
{
return (uint32_t)x >> sh | (uint32_t)(x >> 32) << (32 - sh);
}
float xombe__kern_line_fit(const xombe_enc *e, const xombe_lf_spec *sp, float period, int kmin, int kmax,
float band_resid[8], float band_energy[8])
{
const int16_t *re = sp->S->v;
const uint64_t *ep = e->kq.ep;
float per_harm = XOMBE_FFT / period, total = 0.0f, inv_g2, g = sp->g;
uint64_t be[8] = {0, 0, 0, 0, 0, 0, 0, 0};
/* period exact in Q19 for 16 <= period <= XOMBE_FFT (24-bit mantissa), so harmonic and band edges compare
exactly in integers: bin j is past harmonic l when j*period >= (l + 1/2)*XOMBE_FFT, as xombe__harmonic_of
(midway goes up), band b = floor(l*XOMBE_BANDS_PER_UNIT/period). H = per_harm in Q20 (< 2^27) from 2^49/pq,
taken 64 low so 56..73 under the true value (float rounding <= 8), and (2l + 1)*73 < 2^21 for l <= 513, so
the edge estimates are exact or one low */
int32_t pq = (int32_t)(period * 524288.0f), H = (int32_t)(562949953421312.0f / (float)pq) - 64;
int k = kmin < 1 ? 1 : kmin, l = xombe__harmonic_of(k, period);
/* bins lie within per_harm/2 + 1 of their harmonic, inside the table's padding. callers' periods are >= 18
samples: pitch refinement >= 20, voicing metric at table f0 <= 0.0524 with 2 % jitter. per_harm >= 1 gives
every harmonic a bin */
assert(per_harm <= 2.0f * (XOMBE_LF_PAD_BINS - 2) && per_harm >= 1.0f && kmax <= XOMBE_FFT / 2);
memset(band_resid, 0, 8 * sizeof(float));
memset(band_energy, 0, 8 * sizeof(float));
if (g == 0.0f)
return 0.0f; /* all-zero spectrum fits exactly */
inv_g2 = 1.0f / (g * g);
for (; k <= kmax; l++) {
int64_t sr = 0, si = 0, ww = 0, t = (int64_t)(2 * l + 1) << 28; /* (l + 1/2)*XOMBE_FFT in Q19 */
uint64_t ee;
float resid, pos;
int64_t lb = (int64_t)l << 23; /* l*XOMBE_BANDS_PER_UNIT in Q19 */
int32_t xs;
int kend = (int)(((2 * l + 1) * H + 2097151) >> 21), band;
if ((int64_t)kend * pq < t)
kend++;
if (kend > kmax + 1)
kend = kmax + 1;
if (l == 0) {
k = kend;
continue;
}
ee = ep[kend] - ep[k];
/* table position of the first bin, in bins, the rest lie within per_harm/2 + 1 bins. in Q16 entries it
steps exactly XOMBE_WTAB_OVERSAMPLE per bin */
pos = (float)k - (float)l * per_harm;
xs = (int32_t)(pos * (XOMBE_WTAB_OVERSAMPLE * 65536.0f));
lf_run(re + k, kend - k, &e->kq.wt[XOMBE_LF_WT_OFF + (xs >> 16)], lf_coef(xs), &sr, &si, &ww);
k = kend;
if (ww > 0) {
/* sums to 31 bits so products fit in 64: |sr|, |si| <= sqrt(ee*ww) need no say in the shift.
numerator >= 0 up to rounding */
int32_t e3, w3, r3, i3;
int64_t num;
int sh = 33 - q15_clz64(ee | (uint64_t)ww);
if (sh <= 0) {
sh = 0;
e3 = (int32_t)ee;
w3 = (int32_t)ww;
r3 = (int32_t)sr;
i3 = (int32_t)si;
} else { /* sh <= 32 - 22, sums below 2^41 */
e3 = (int32_t)lf_shr(ee, sh);
w3 = (int32_t)lf_shr((uint64_t)ww, sh);
r3 = (int32_t)lf_shr((uint64_t)sr, sh);
i3 = (int32_t)lf_shr((uint64_t)si, sh);
}
num = (int64_t)e3 * w3 - (int64_t)r3 * r3 - (int64_t)i3 * i3;
resid = num > 0 ? i64_to_float(num) / (float)w3 * (float)(1u << sh) : 0.0f;
} else {
resid = i64_to_float((int64_t)ee);
}
resid *= inv_g2;
band = (int)(((int64_t)l * H) >> 26);
if ((int64_t)(band + 1) * pq <= lb)
band++;
if (band > 7)
band = 7;
band_resid[band] += resid;
be[band] += ee;
total += resid;
}
for (l = 0; l < 8; l++)
band_energy[l] = i64_to_float((int64_t)be[l]) * inv_g2;
return total;
}
+228
View File
@@ -0,0 +1,228 @@
/* q15 pitch kernels (kernels.h, XOMBE_KERNELS=q15): int16 block-scaled input, SMLAD low-pass two outputs per
pass, low-pass output and its windowed product block-shifted to int16, energy and autocorrelation exact in 64
bits, lags normalized to r[0] = 32767 by one reciprocal (float scale in pacf_scale). quarter-sample periods make
the interpolation exact in Q2. also the analysis window and the line fit's window table */
#include "kern_q15.h"
#include "../tables/dsp_tables.h"
#define PE_N (XOMBE_PITCH_WIN + 1) /* window padded to even */
#define PE_X (XOMBE_PITCH_WIN + 2 * XOMBE_PITCH_LPF_HALF + 1) /* input samples with one pad, even */
#define PE_P (PE_N / 2 + 1) /* pairs of the window, zero-padded by one */
XOMBE_STATIC_ASSERT(PE_N % 2 == 0 && PE_X % 2 == 0, pe_even);
XOMBE_STATIC_ASSERT(PE_N <= XOMBE_PITCH_WIN + 1, pe_rq_fits_pacf);
XOMBE_STATIC_ASSERT((long)XOMBE_WTAB_OVERSAMPLE * XOMBE_FFT * (XOMBE_MAX_WINDOW - 1) < (1L << 23), window_phase_fits);
/* 2^k, -126 <= k <= 127 */
static float pow2f(int k)
{
uint32_t b = (uint32_t)(k + 127) << 23;
float f;
memcpy(&f, &b, sizeof(f));
return f;
}
/* v * 2^-sh rounded, held below 2^15, |v| < 2^(15 + sh) */
static int16_t shr_q15(int32_t v, int sh)
{
if (sh > 0)
v = ((v >> (sh - 1)) + 1) >> 1;
else
v = (int32_t)((uint32_t)v << -sh);
return (int16_t)(v > 32767 ? 32767 : v);
}
/* Q15 pitch window at i, mirrored */
static int32_t w2q(int i)
{
return xombe__pitch_w2_q15[i <= XOMBE_PITCH_HALF ? i : XOMBE_PITCH_WIN - 1 - i];
}
static int mag_bits(uint32_t m)
{
return m ? 32 - q15_clz32(m) : 0;
}
void xombe__kern_pitch_acf(xombe_enc *e, const float *centre, int slot)
{
int16_t x[PE_X], *rq = e->pacf[slot].q;
int32_t sv[PE_N];
uint32_t up[2 * PE_P]; /* up[j] = (u[2j], u[2j + 1]), up[PE_P + j] = (u[2j + 1], u[2j + 2]) */
float m = 0.0f, gx, cs, cu, b = 0.0f;
const float *c = centre - XOMBE_PITCH_HALF - XOMBE_PITCH_LPF_HALF;
int i, t, sh1, sh2, sh = 0;
uint32_t smax = 0, umax = 0;
int64_t e0 = 0;
for (i = 0; i < PE_X - 1; i++)
if (fabsf(c[i]) > m)
m = fabsf(c[i]);
gx = q15_gain(m, 32767.0f);
for (i = 0; i < PE_X - 1; i++)
x[i] = (int16_t)round_q(c[i] * gx);
x[PE_X - 1] = 0;
/* |sv| < 2^31: sum |taps| <= 65536 */
for (i = 0; i < XOMBE_PITCH_WIN; i += 2) {
int32_t sa = 0, sb = 0;
const int16_t *p = x + i;
int q;
for (q = 0; q < XOMBE_PITCH_LPF_PAIRS; q++) {
uint32_t d = q15_ld2(p + 2 * q);
sa = q15_smlad(d, xombe__pitch_lpf_q15[0][q], sa);
sb = q15_smlad(d, xombe__pitch_lpf_q15[1][q], sb);
}
if (i + 1 == XOMBE_PITCH_WIN)
sb = 0;
sv[i] = sa;
sv[i + 1] = sb;
smax |= (uint32_t)(sa < 0 ? -sa : sa) | (uint32_t)(sb < 0 ? -sb : sb);
}
/* the OR of the magnitudes has the max's top bit, so s = sv * 2^-sh1 and u = s*w2 * 2^-sh2 peak in
[2^14, 2^15). s*(s*w2) < 2^45, e0 < 2^54. x holds s, then u */
sh1 = mag_bits(smax) - 15;
for (i = 0; i < XOMBE_PITCH_WIN; i++) {
int32_t s = shr_q15(sv[i], sh1), p = s * w2q(i);
x[i] = (int16_t)s;
e0 += (int64_t)s * p;
umax |= (uint32_t)(p < 0 ? -p : p);
}
sh2 = mag_bits(umax) - 15;
for (i = 0; i < XOMBE_PITCH_WIN; i++)
x[i] = shr_q15(x[i] * w2q(i), sh2);
for (; i < 2 * PE_P + 1; i++)
x[i] = 0;
for (i = 0; i < PE_P; i++) {
up[i] = (uint16_t)x[2 * i] | (uint32_t)(uint16_t)x[2 * i + 1] << 16;
up[PE_P + i] = (uint16_t)x[2 * i + 1] | (uint32_t)(uint16_t)x[2 * i + 2] << 16;
}
/* float value of one unit of s and of u */
cs = gx > 0.0f ? pow2f(sh1) / (gx * xombe__pitch_lpf_q15_gain) : 0.0f;
cu = cs * pow2f(sh2) / xombe__pitch_w2_q15_gain;
e->pe0[slot] = i64_to_float(e0) * cs * cs / xombe__pitch_w2_q15_gain;
e->pacf_scale[slot] = 0.0f;
/* lags t..t + 3 over the pairs of lag t, zero padding makes the extra products vanish. all four read at one
pointer, so the loop's accumulators stay in registers */
for (t = 0; t < XOMBE_PITCH_WIN; t += 4) {
int64_t a[4] = {0, 0, 0, 0};
int k;
const uint32_t *pv = up, *pe = up + (XOMBE_PITCH_WIN - t + 1) / 2, *pb = up + t / 2;
for (; pv != pe; pv++, pb++) {
uint32_t v = *pv;
a[0] = q15_smlald(v, pb[0], a[0]);
a[2] = q15_smlald(v, pb[1], a[2]);
a[1] = q15_smlald(v, pb[PE_P], a[1]);
a[3] = q15_smlald(v, pb[PE_P + 1], a[3]);
}
if (t == 0) {
if (a[0] <= 0) { /* all-zero input */
memset(rq, 0, PE_N * sizeof(*rq));
return;
}
/* r[0] >= 2^28 (u peaks >= 2^14) shifted below 2^31, |r[t]| <= r[0] (Cauchy-Schwarz),
b = 32767*2^44/r[0] < 2^31 */
sh = 33 - q15_clz64((uint64_t)a[0]);
sh = sh > 0 ? sh : 0;
e->pacf_scale[slot] = i64_to_float(a[0]) * cu * cu * (1.0f / (32767.0f * 4.0f));
b = 32767.0f * 17592186044416.0f / (float)(int32_t)(a[0] >> sh);
}
for (k = 0; k < 4 && t + k < XOMBE_PITCH_WIN; k++)
rq[t + k] = (int16_t)(((int64_t)(int32_t)(a[k] >> sh) * (int32_t)b + ((int64_t)1 << 43)) >> 44);
}
rq[0] = 32767;
rq[PE_N - 1] = 0; /* lag XOMBE_PITCH_WIN, past the window */
}
/* reads lags in pairs (r[i], r[i + 1]) at any i */
float xombe__kern_error_at(const xombe_enc *e, int slot, float P)
{
const int16_t *rq = e->pacf[slot].q;
float e0 = e->pe0[slot], val;
/* K = floor((XOMBE_PITCH_WIN - 1)/P) for P = p4/4 */
int k, p4 = (int)(4.0f * P + 0.5f), K = 4 * (XOMBE_PITCH_WIN - 1) / p4, t4 = p4;
int32_t sum = 0;
for (k = 1; k <= K; k++, t4 += p4) {
uint32_t f = (uint32_t)t4 & 3u;
sum = q15_smlad(q15_ld2(rq + (t4 >> 2)), (f << 16) | (4u - f), sum);
}
/* sum is in quarters, r[0] = 32767 */
val = (e0 - P * e->pacf_scale[slot] * (float)(2 * sum + 4 * 32767)) / (e0 * (1.0f - P * xombe__pitch_sum_w4));
return val > 0.0f ? val : 0.0f;
}
/* sin(pi*y), |y| <= 1/2, minimax fit of sin(pi*y)/y, relative error < 2e-7 in float */
static float sinpi(float y)
{
float y2 = y * y;
return y * (3.141592741f + y2 * (-5.167709827f + y2 * (2.550069809f + y2 * (-0.598242104f + y2 * 0.0775603801f))));
}
/* sin(pi*y), |y| < 0.032, Taylor to y^5, relative error < 3e-10 */
static float sinpi_small(float y)
{
float y2 = y * y;
return y * (3.14159274f + y2 * (-5.16771278f + y2 * 2.55016404f));
}
/* xombe__sin_ratio for 0 <= r < 2m, m < 2^23, im = 1/m */
static float sin_frac(int32_t r, int32_t m, float im)
{
if (r > m)
r -= 2 * m;
if (2 * r > m)
r = m - r;
else if (2 * r < -m)
r = -m - r;
return sinpi((float)r * im);
}
/* e->win = xombe__hamming(n), n = e->win_len, and the line fit's table of its transform, xombe__hamming_dtft at
q/g cycles/sample (g = XOMBE_WTAB_OVERSAMPLE*XOMBE_FFT), 0.54*D(x) + 0.23*(D(x - b) + D(x + b)) with
D(x) = sin(n*x)/sin(x), x = pi*q/g, b = pi/(n - 1). every phase is an exact integer ratio stepped in q:
x -/+ b = pi*(q*(n - 1) -/+ g)/(g*(n - 1)).
table in Q15 scaled to peak, mirrored into kq.wt indexed by the integer part s of the signed Q16 position, so it
steps XOMBE_WTAB_OVERSAMPLE per bin across the centre. s >= 0 holds (wq[s], wq[s + 1]), s < 0 holds
(wq[-s], wq[-s - 1]), past XOMBE_WTAB_LEN entries it holds the last value as the float fit's table does */
void xombe__kern_window_init(xombe_enc *e)
{
enum { G = XOMBE_WTAB_OVERSAMPLE * XOMBE_FFT };
uint32_t *wt = e->kq.wt + XOMBE_LF_WT_OFF;
int16_t wq[XOMBE_WTAB_LEN];
int n = e->win_len, i, q, cur, next;
/* m < 2^23 for n <= XOMBE_MAX_WINDOW. |rm|, |rp| = |q*(n - 1) -/+ g| < 0.032 m (q/g < 0.027, 1/(n - 1) < 0.0051),
tc, tm, tp = n*q, n*rm, n*rp mod 2g or 2m */
int32_t m = G * (n - 1), rm = -G, rp = G, tc = 0, tm = 2 * m - n * G, tp = n * G;
float im = 1.0f / (float)m, ih = 1.0f / (float)(2 * (n - 1)), gain = 0.0f;
/* cos(2*pi*i/(n - 1)) = sin(pi*(n - 1 - 4i)/(2(n - 1))), symmetric */
for (i = 0; i <= (n - 1) / 2; i++)
e->win[i] = e->win[n - 1 - i] = 0.54f - 0.46f * sinpi((float)(n - 1 - 4 * i) * ih);
for (q = 0; q < XOMBE_WTAB_LEN; q++) {
float a = sinpi_small((float)q * (1.0f / G)), bm = sinpi_small((float)rm * im);
float bp = sinpi_small((float)rp * im);
float A = sin_frac(tc, G, 1.0f / G), Bm = sin_frac(tm, m, im), Bp = sin_frac(tp, m, im), w;
if (q > 0 && rm != 0) /* one division, a*bm*bp >= 1e-12 */
w = (0.54f * A * bm * bp + 0.23f * a * (Bm * bp + Bp * bm)) / (a * bm * bp);
else
w = 0.54f * (q > 0 ? A / a : (float)n) + 0.23f * ((rm != 0 ? Bm / bm : (float)n) + Bp / bp);
if (q == 0)
gain = q15_gain(w, 32767.0f); /* a positive window's transform peaks at 0 */
wq[q] = (int16_t)round_q(w * gain);
rm += n - 1;
rp += n - 1;
tc += n;
if (tc >= 2 * G)
tc -= 2 * G;
tm += n * (n - 1);
if (tm >= 2 * m)
tm -= 2 * m;
tp += n * (n - 1);
if (tp >= 2 * m)
tp -= 2 * m;
}
/* wq[q] = entry q, last entry past the end, entry -q is entry q - 1 swapped */
cur = wq[0];
for (q = 0; q <= XOMBE_LF_WT_OFF; q++, cur = next) {
next = wq[q + 1 < XOMBE_WTAB_LEN ? q + 1 : XOMBE_WTAB_LEN - 1];
wt[q] = (uint16_t)cur | (uint32_t)(uint16_t)next << 16;
if (q > 0)
wt[-q] = wt[q - 1] >> 16 | wt[q - 1] << 16;
}
}
+217
View File
@@ -0,0 +1,217 @@
/* q15 analysis spectrum and its line fit preparation (kernels.h, XOMBE_KERNELS=q15) */
#include <string.h>
#include "kern_q15.h"
#include "../dsp/fft_q15.h"
#include "../tables/dsp_tables.h"
/* the XOMBE_FFT-point real transform runs as an SP_M-point complex one on sample pairs, then a real-input split */
#define SP_M (XOMBE_FFT / 2)
#define SP_LOG2 9
XOMBE_STATIC_ASSERT(1 << SP_LOG2 == SP_M, sp_log2);
XOMBE_STATIC_ASSERT(XOMBE_MAX_WINDOW < XOMBE_FFT, sp_window_fits);
XOMBE_STATIC_ASSERT(XOMBE_LF_BINS == XOMBE_SPEC_BINS, sp_bins);
/* keeps one copy of the bulky stages when the compiler clones kern_spectrum for constant arguments */
#if defined(__GNUC__)
#define SP_NOINLINE __attribute__((noinline))
#else
#define SP_NOINLINE
#endif
#if defined(__GNUC__) && !defined(__clang__)
#define SP_NOCLONE __attribute__((noclone))
#else
#define SP_NOCLONE
#endif
/* 2^e, -126 <= e <= 127 */
static float sp_pow2(int e)
{
uint32_t u = (uint32_t)(e + 127) << 23;
float f;
memcpy(&f, &u, sizeof f);
return f;
}
static inline uint32_t sp_abs(int32_t v)
{
return (uint32_t)(v < 0 ? -v : v);
}
/* bins k and SP_M - k from transform pairs a = x[k], b = x[SP_M - k] and split twiddle w, as r[0..3] = re, im of
bin k then of bin SP_M - k, in Q14 of the bins. no overflow: a dual product is at most |w| * |a| <= 2^15.5 * 2^15,
a bin component at most (1 + sqrt 2) * 2^15 * 2^14 */
static inline void sp_bins(uint32_t a, uint32_t b, uint32_t w, int32_t r[4])
{
uint32_t bx = b >> 16 | b << 16;
int32_t er = (q15_lo(a) + q15_lo(b)) * 8192, ei = (q15_hi(a) - q15_hi(b)) * 8192;
/* w * (a - conj b) / i: re = wr*ai + wi*ar + wr*bi - wi*br, im = wr*br + wi*bi - (wr*ar - wi*ai) */
int32_t pr = (q15_smladx(w, a, 0) >> 2) + (q15_smlsd(w, bx, 0) >> 2);
int32_t pi = (q15_smuad(w, b) >> 2) - (q15_smlsd(w, a, 0) >> 2);
r[0] = er + pr;
r[1] = ei + pi;
r[2] = er - pr;
r[3] = pi - ei;
}
/* top halves of |v0| and |v1| as a pair, each |v| taken as v ^ (v >> 31), which is |v| or |v| - 1 */
static inline uint32_t sp_top(int32_t v0, int32_t v1)
{
return ((uint32_t)(v1 ^ (v1 >> 31)) & 0xffff0000u) | (uint32_t)(v0 ^ (v0 >> 31)) >> 16;
}
/* splits transform x of the pairs in place, returns h with every |component| <= (h + 1) * 2^16. layout after:
bin 0 re at x[0] (im 0), bins 1..SP_M/2 - 1 re at x[k] and im at x[SP_M - k], x[SP_M/2] a copy of bin
SP_M/2's im, bins SP_M/2..SP_M re then im at x[SP_M + 2*(k - SP_M/2)]. every write lands on a word already read.
split twiddle exp(-2 pi i k/XOMBE_FFT) is xombe__fft_tw_q15[k/2] for even k, times SP_W1 for odd k */
#define SP_W1 0xff377fffu /* exp(-2 pi i/XOMBE_FFT) in Q15 */
static SP_NOINLINE uint32_t sp_split(uint32_t *x)
{
const uint32_t *tw = xombe__fft_tw_q15;
int32_t r[4];
uint32_t m = 0;
int k;
/* k = 0 pairs x[0] with itself, its im (0) lands on x[SP_M] before k = SP_M/2 writes there */
for (k = 0; k <= SP_M / 2; k++) {
uint32_t *u = x + SP_M + 2 * (SP_M / 2 - k), w = tw[k >> 1];
if (k & 1)
w = xombe__q15_cmul(w, SP_W1);
sp_bins(x[k], x[(SP_M - k) & (SP_M - 1)], w, r);
x[k] = (uint32_t)r[0];
x[SP_M - k] = (uint32_t)r[1];
u[0] = (uint32_t)r[2];
u[1] = (uint32_t)r[3];
m = q15_umax16(m, q15_umax16(sp_top(r[0], r[1]), sp_top(r[2], r[3])));
}
return (m >> 16) > (m & 0xffffu) ? m >> 16 : m & 0xffffu;
}
/* (v0, v1) * 2^p * c / 2^32 rounded, as an int16 pair */
static inline uint32_t sp_q2(int32_t v0, int32_t v1, int p, int32_t c)
{
return (uint16_t)q15_smmulr((int32_t)((uint32_t)v0 << p), c) |
(uint32_t)q15_smmulr((int32_t)((uint32_t)v1 << p), c) << 16;
}
static inline void sp_st2(int16_t *d, uint32_t v)
{
memcpy(d, &v, sizeof v);
}
/* packs centre[j] * w[half + j] * g rounded, |j| <= half, as sample j mod XOMBE_FFT of pairs in bit-reversed order */
static SP_NOINLINE void sp_input(uint32_t *x, const float *centre, const float *w, int half, float g)
{
int j;
memset(x, 0, SP_M * sizeof(x[0]));
for (j = -half; j <= half; j++) {
int i = (j + XOMBE_FFT) & (XOMBE_FFT - 1);
int16_t q = (int16_t)round_q(centre[j] * w[half + j] * g);
memcpy((char *)x + (q15_rbit((uint32_t)(i >> 1)) >> (32 - SP_LOG2)) * 4 + (i & 1) * 2, &q, sizeof q);
}
}
/* S->v from split output v, |v| <= mx, mx * 2^p in [2^30, 2^31), c = 32767 * 2^32 / (mx * 2^p) */
static SP_NOINLINE void sp_store(xombe_spec *S, const int32_t *v, int p, int32_t c)
{
int16_t *re = S->v, *im = re + XOMBE_LF_IM;
int k;
for (k = 0; k < SP_M / 2; k += 2) {
sp_st2(re + k, sp_q2(v[k], v[k + 1], p, c));
sp_st2(im + k, sp_q2(v[SP_M - k], v[SP_M - k - 1], p, c));
}
for (k = SP_M / 2; k < SP_M; k += 2) {
const int32_t *u = v + SP_M + 2 * (k - SP_M / 2);
sp_st2(re + k, sp_q2(u[0], u[2], p, c));
sp_st2(im + k, sp_q2(u[1], u[3], p, c));
}
sp_st2(re + SP_M, sp_q2(v[2 * SP_M], 0, p, c));
sp_st2(im + SP_M, 0);
im[0] = 0; /* the loop took it from x[SP_M] */
}
/* samples block-scaled to XOMBE_CFFT_Q15_PEAK, packed in pairs in bit-reversed order for the block-floating-point
FFT, split in integer, bins scaled to int16 */
SP_NOINLINE SP_NOCLONE void xombe__kern_spectrum(const float *centre, const float *w, int n, xombe_spec *S)
{
uint32_t x[2 * SP_M + 2];
const int32_t *v = (const int32_t *)x;
float m = 0.0f, g;
uint32_t mx;
int32_t c;
int half = (n - 1) / 2, j, k, s, p;
for (j = -half; j <= half; j++) {
float a = fabsf(centre[j] * w[half + j]);
if (a > m)
m = a;
}
g = q15_gain(m, (float)XOMBE_CFFT_Q15_PEAK);
S->sc = 0.0f;
if (g == 0.0f)
goto zero;
sp_input(x, centre, w, half, g);
s = xombe__cfft_q15(x, SP_M, xombe__fft_tw_q15, XOMBE_CFFT_Q15_PEAK);
/* the bound from the top halves is within 2^-10 of the largest component, else an exact scan */
mx = sp_split(x);
if (mx >= 1024) {
mx = (mx + 1) << 16;
} else {
for (mx = 0, k = 0; k < 2 * SP_M + 2; k++)
if (sp_abs(v[k]) > mx)
mx = sp_abs(v[k]);
if (mx == 0)
goto zero;
}
/* |v| * 2^p <= mx * 2^p < 2^31, so |v| * 2^p * c / 2^32 <= 32767 after rounding for either sign. the largest
component rounds to 32767 for an exact mx */
p = q15_clz32(mx) - 1;
c = (int32_t)(((uint64_t)32767 << 32) / (mx << p));
sp_store(S, v, p, c);
/* x held the transform of the scaled input times 2^-s, v is Q14 of it */
S->sc = sp_pow2(18 + s - p) / ((float)c * g);
return;
zero:
memset(S->v, 0, sizeof(S->v));
}
/* exact |S[k]|^2 < 2^31, one rounding to float */
void xombe__kern_bin_power(const xombe_spec *S, float sum_w2, float *P)
{
const int16_t *re = S->v, *im = re + XOMBE_LF_IM;
float scale = S->sc * S->sc / (XOMBE_FFT * sum_w2);
int k;
for (k = 0; k < XOMBE_SPEC_BINS; k++)
P[k] = (float)((int32_t)re[k] * re[k] + (int32_t)im[k] * im[k]) * scale;
}
/* prefix sums of |S|^2 over kmin..kmax. the line fit's residual cancels in 31-bit sums, so a range whose peak is
below 16384 is shifted up into e->kq.spec, otherwise the bins are read in place */
void xombe__kern_lf_prepare(xombe_enc *e, const xombe_spec *S, int kmin, int kmax, xombe_lf_spec *sp)
{
const int16_t *re = S->v, *im = re + XOMBE_LF_IM;
uint64_t *ep = e->kq.ep, acc = 0;
uint32_t det = 0, d;
int32_t f;
int k, l;
/* every component fits q + 1 signed bits for the top detector bit q (bit 0 of each half may hold the other
half's sign), shifted up by 15 - q it stays within int16 */
for (k = kmin; k <= kmax; k += 2) /* may take in bin kmax + 1 <= XOMBE_SPEC_BINS - 1 */
det |= xombe__q15_det(q15_ld2(re + k)) | xombe__q15_det(q15_ld2(im + k));
d = (det | det >> 16) & 0xfffeu;
l = d ? q15_clz32(d) - 16 : 14;
f = (int32_t)1 << l;
ep[kmin] = 0;
for (k = kmin; k <= kmax; k++) {
int32_t r = re[k] * f, i = im[k] * f;
if (l) {
e->kq.spec.v[k] = (int16_t)r;
e->kq.spec.v[XOMBE_LF_IM + k] = (int16_t)i;
}
acc += (uint32_t)(r * r) + (uint32_t)(i * i);
ep[k + 1] = acc;
}
sp->S = S;
if (l) {
e->kq.spec.sc = S->sc * sp_pow2(-l);
sp->S = &e->kq.spec;
}
sp->g = sp->S->sc > 0.0f ? 1.0f / sp->S->sc : 0.0f;
}
+35
View File
@@ -0,0 +1,35 @@
#ifndef XOMBE_KERN_STATE_H
#define XOMBE_KERN_STATE_H
/* kernel backend state, last member of struct xombe_enc, empty for float, and the analysis spectrum's layout,
which only the backend reads (kernels.h) */
#if XOMBE_KERNELS_Q15
#define XOMBE_LF_BINS (XOMBE_FFT / 2 + 1)
#define XOMBE_LF_IM (XOMBE_LF_BINS + 1)
/* block floating point, bin k = (v[k], v[XOMBE_LF_IM + k]) * sc, components within +/-32767 and the largest
within 2^-10 of it, sc 0 and v all zero for an all-zero spectrum. XOMBE_LF_IM even, so re[k] and im[k] share
alignment for the line fit's pair loads */
typedef struct xombe_spec {
int16_t v[XOMBE_LF_IM + XOMBE_LF_BINS + 1];
float sc;
} xombe_spec;
/* q15 line fit window table and prepared spectrum, off the stack.
wt: indexed by signed table position, out to XOMBE_LF_PAD_BINS bins either side of a harmonic
ep: prefix sums of |S|^2 in the prepared spectrum's units
spec: a prepared range shifted up, when its peak is below 16384 */
#define XOMBE_LF_PAD_BINS 64
#define XOMBE_LF_WT_OFF (XOMBE_LF_PAD_BINS * XOMBE_WTAB_OVERSAMPLE)
typedef struct {
uint32_t wt[2 * XOMBE_LF_WT_OFF + 1];
uint64_t ep[XOMBE_LF_BINS + 1];
xombe_spec spec;
} xombe_kern_q15;
#define XOMBE_KERN_STATE xombe_kern_q15 kq;
#else
typedef struct xombe_spec {
xombe_cpx b[XOMBE_SPEC_BINS];
} xombe_spec;
#define XOMBE_KERN_STATE
#endif
#endif
+55
View File
@@ -0,0 +1,55 @@
#ifndef XOMBE_KERNELS_H
#define XOMBE_KERNELS_H
/* encoder inner loops, kern_float.c or kern_q15_*.c (XOMBE_KERNELS=q15) */
#include <math.h>
#include "../internal.h"
/* analysis spectrum S (xombe_spec, layout per backend in kern_state.h): XOMBE_SPEC_BINS bins of the
XOMBE_FFT-point transform of centre[-h..h] under window w of n = 2h + 1 points, centred on sample 0 */
void xombe__kern_spectrum(const float *centre, const float *w, int n, xombe_spec *S);
/* P[k] = |S[k]|^2 / (XOMBE_FFT * sum_w2), XOMBE_SPEC_BINS float bins */
void xombe__kern_bin_power(const xombe_spec *S, float sum_w2, float *P);
/* called by xombe__enc_set_window for a new e->win_len, after it rebuilds e->win and e->wtab (float), or to build
e->win itself (q15, which leaves e->wtab unused) */
void xombe__kern_window_init(xombe_enc *e);
/* autocorrelation of the low-passed, windowed signal around centre into slot's pacf, energy into pe0[slot] */
void xombe__kern_pitch_acf(xombe_enc *e, const float *centre, int slot);
/* P on the quarter-sample grid, slot not silent */
float xombe__kern_error_at(const xombe_enc *e, int slot, float P);
/* spectrum prepared for line fits, may keep data in e so valid only until the next prepare */
typedef struct {
const xombe_spec *S;
float g;
} xombe_lf_spec;
/* kmin >= 1, later fits must stay within kmin..kmax */
void xombe__kern_lf_prepare(xombe_enc *e, const xombe_spec *S, int kmin, int kmax, xombe_lf_spec *sp);
/* returns the residual of the least-squares fit of the window transform, one complex amplitude per harmonic,
to bins kmin..kmax, with per-band residual and bin energy.
q15: XOMBE_FFT / (2*XOMBE_LF_PAD_BINS - 4) <= period <= XOMBE_FFT, kmax <= XOMBE_FFT / 2 */
float xombe__kern_line_fit(const xombe_enc *e, const xombe_lf_spec *sp, float period, int kmin, int kmax,
float band_resid[8], float band_energy[8]);
/* voicing metric on a spectrum prepared once, to try several pitches, valid until the next prepare */
void xombe__voicing_prepare(xombe_enc *e, const xombe_spec *S, xombe_lf_spec *sp);
void xombe__voicing_metric_sp(xombe_enc *e, const xombe_lf_spec *sp, float fhat, float m[8], float w[8]);
void xombe__voicing_soft_sp(xombe_enc *e, const xombe_lf_spec *sp, float fhat, float scale, float a[8], float w[8]);
/* nearest harmonic of bin k, midway goes up. computed from period, not 1/period, so 1/8-sample grid periods
are exact and midway bins assign the same in any precision */
static inline int xombe__harmonic_of(int k, float period)
{
return (int)floorf((float)k * period / XOMBE_FFT + 0.5f);
}
static inline int xombe__band_of(int l, float period)
{
int band = (int)floorf((float)l * XOMBE_BANDS_PER_UNIT / period);
return band > 7 ? 7 : band;
}
#endif
+172
View File
@@ -0,0 +1,172 @@
#include <math.h>
#include <string.h>
#include "../internal.h"
/* 100 Hz suppression bins, NS_BINS_PER_UNIT per cycle/sample */
#define NS_BINS_PER_UNIT 80.0f
/* voiced harmonics take half the suppression below NS_VOICED_FULL, a share rising with frequency up to
NS_VOICED_RAMP */
#define NS_VOICED_FULL XOMBE_HZ(400.0f)
#define NS_VOICED_RAMP XOMBE_HZ(800.0f)
#define NS_GAIN_SLOPE 1.35f
#define NS_FAST 0.25f
#define NS_SLOW 0.1f
#define NS_FLOOR_UP 1.0444f
#define NS_FLOOR_DOWN 0.9591f
#define NS_MIN_LOG2 (-16.0f)
void xombe__ns_bins(const float *P, float Xm[XOMBE_NS_BINS])
{
float acc[XOMBE_NS_BINS];
int k;
memset(acc, 0, sizeof(acc));
for (k = 0; k < XOMBE_SPEC_BINS; k++) {
int b = (int)((float)k / XOMBE_FFT * NS_BINS_PER_UNIT);
if (b < XOMBE_NS_BINS)
acc[b] += P[k];
}
for (k = 0; k < XOMBE_NS_BINS; k++)
Xm[k] = sqrtf(acc[k]);
}
float xombe__ns_shape(float f)
{
static const float fx[6] = {0.0f, XOMBE_HZ(500.0f), XOMBE_HZ(1400.0f), XOMBE_HZ(3000.0f), XOMBE_HZ(3900.0f),
XOMBE_HZ(4000.0f)};
static const float fy[6] = {0.25f, 0.25f, 1.0f, 1.0f, 0.5f, 0.5f};
int i;
if (f <= fx[0])
return fy[0];
for (i = 1; i < 6; i++)
if (f <= fx[i])
return fy[i - 1] + (fy[i] - fy[i - 1]) * (f - fx[i - 1]) / (fx[i] - fx[i - 1]);
return fy[5];
}
void xombe__ns_update(xombe_enc *e, const float Xm[XOMBE_NS_BINS], int speech, int confident_run,
int no_band_voiced)
{
float s = e->ns_strength;
int k;
if (!e->ns_ready) {
memcpy(e->ns_noise, Xm, sizeof(e->ns_noise));
e->ns_floor = 0.5f * s;
e->ns_ready = 1;
} else if (confident_run >= XOMBE_CONFIDENT_RUN) {
for (k = 0; k < XOMBE_NS_BINS; k++)
e->ns_noise[k] = (1.0f - NS_FAST) * e->ns_noise[k] + NS_FAST * Xm[k];
} else if (no_band_voiced) {
for (k = 0; k < XOMBE_NS_BINS; k++)
if (e->ns_noise[k] > Xm[k] / 3.0f)
e->ns_noise[k] = (1.0f - NS_SLOW) * e->ns_noise[k] + NS_SLOW * Xm[k];
}
e->ns_floor *= speech ? NS_FLOOR_UP : NS_FLOOR_DOWN;
if (e->ns_floor < 0.5f * s)
e->ns_floor = 0.5f * s;
if (e->ns_floor > s)
e->ns_floor = s;
}
void xombe__ns_bin_voicing(const uint8_t vb[8], int ambe2_rule, uint8_t vbin[XOMBE_NS_BINS])
{
int k;
for (k = 0; k < XOMBE_NS_BINS; k++) {
float fc = ((float)k + 0.5f) / NS_BINS_PER_UNIT;
int j = (int)(fc * XOMBE_BANDS_PER_UNIT);
vbin[k] = (uint8_t)(ambe2_rule ? xombe__voiced_at(vb, fc) : vb[j > 7 ? 7 : j]);
}
}
void xombe__ns_gain(const xombe_enc *e, xombe_ns_mem *m, const float Xm[XOMBE_NS_BINS], int speech, float v,
const uint8_t vbin[XOMBE_NS_BINS], float G[XOMBE_NS_BINS])
{
float g[XOMBE_NS_BINS], gf[XOMBE_NS_BINS], mu;
int k;
for (k = 0; k < XOMBE_NS_BINS; k++) {
float fc = ((float)k + 0.5f) / NS_BINS_PER_UNIT;
float xp = vbin[k] ? Xm[k] : Xm[k] * (1.0f + xombe__ns_shape(fc)) * 0.5f;
float gk = 0.0f;
if (xp > e->ns_noise[k]) {
gk = NS_GAIN_SLOPE * (1.0f - e->ns_noise[k] / xp);
if (gk > 1.0f)
gk = 1.0f;
}
g[k] = gk;
}
for (k = 0; k < XOMBE_NS_BINS; k++) {
float lo = g[k > 0 ? k - 1 : 0], hi = g[k < XOMBE_NS_BINS - 1 ? k + 1 : XOMBE_NS_BINS - 1];
gf[k] = 0.25f * lo + 0.5f * g[k] + 0.25f * hi;
}
mu = speech ? 0.0f : (XOMBE_VAD_THRESHOLD - v) / XOMBE_VAD_THRESHOLD;
if (mu < 0.0f)
mu = 0.0f;
if (mu > 1.0f)
mu = 1.0f;
for (k = 0; k < XOMBE_NS_BINS; k++) {
float fc = ((float)k + 0.5f) / NS_BINS_PER_UNIT;
float gs = m->have_prev ? 0.5f * (gf[k] + m->prev_gain[k]) : gf[k];
float fk = vbin[k] ? e->ns_floor : e->ns_floor * xombe__ns_shape(fc);
float mx = gs > fk ? gs : fk;
if (mx > 1.0f)
mx = 1.0f;
G[k] = (1.0f - mu) * mx + mu * fk;
}
memcpy(m->prev_gain, gf, sizeof(gf));
m->have_prev = 1;
}
static float log2_floored(float x)
{
float d = x > 0.0f ? log2f(x) : NS_MIN_LOG2;
return d < NS_MIN_LOG2 ? NS_MIN_LOG2 : d;
}
void xombe__ns_harmonic_offsets(const float G[XOMBE_NS_BINS], int L, float f0, const uint8_t *vh, float *da)
{
int l;
for (l = 1; l <= L; l++) {
float f = (float)l * f0, pos = f * NS_BINS_PER_UNIT - 0.5f, gl, d;
int i;
if (pos <= 0.0f) {
gl = G[0];
} else if (pos >= XOMBE_NS_BINS - 1) {
gl = G[XOMBE_NS_BINS - 1];
} else {
i = (int)pos;
gl = G[i] + (G[i + 1] - G[i]) * (pos - (float)i);
}
d = log2_floored(gl);
if (vh[l]) {
if (f < NS_VOICED_FULL)
d *= 0.5f;
else if (f < NS_VOICED_RAMP)
d *= f / NS_VOICED_RAMP;
}
da[l] = d;
}
}
void xombe__ns_apply_voice(const float G[XOMBE_NS_BINS], float *a, int L, float f0, const uint8_t v2[8])
{
uint8_t vh[XOMBE_LMAX + 1];
float da[XOMBE_LMAX + 1];
int l;
xombe__harmonic_voicing(v2, f0, L, vh);
xombe__ns_harmonic_offsets(G, L, f0, vh, da);
for (l = 1; l <= L; l++) {
a[l] += da[l];
if (a[l] < XOMBE_AMP_MIN)
a[l] = XOMBE_AMP_MIN;
}
}
void xombe__ns_apply_silence(const xombe_enc *e, float *a, int L, float f0)
{
int l;
for (l = 1; l <= L; l++) {
float f = (float)l * f0;
a[l] += log2_floored(e->ns_floor * xombe__ns_shape(f));
if (a[l] < XOMBE_AMP_MIN)
a[l] = XOMBE_AMP_MIN;
}
}
+185
View File
@@ -0,0 +1,185 @@
#include <math.h>
#include <string.h>
#include "kernels.h"
/* period grid from 21 samples in half-sample steps, index i is period (GRID_BASE + i)/2 */
#define GRID_BASE 42
#define DIGITAL_SILENCE_E0 1e-2f
/* tracking range 0.8..1.2 of a period, as TRACK_*_NUM/TRACK_DEN */
#define TRACK_LO_NUM 4
#define TRACK_HI_NUM 6
#define TRACK_DEN 5
#define BACKWARD_ACCEPT 0.48f
#define HALVING_PERIOD 100.0f
#define HALVING_MARGIN 0.1f
#define INITIAL_PERIOD 100.0f
#define REFINE_TOP XOMBE_HZ(2000.0f) /* refinement fits harmonics below this */
/* refinement tries period +/-1 sample in 1/REFINE_STEPS steps, none below REFINE_MIN_PERIOD */
#define REFINE_STEPS 8
#define REFINE_MIN_PERIOD 20.0f
/* submultiple P/n replaces the forward estimate P when its cumulative error c has c <= LOOSE and c/c(P) <=
LOOSE_RATIO, c <= TIGHT and c/c(P) <= TIGHT_RATIO, or c <= ANY */
#define SUBMULT_LOOSE 0.85f
#define SUBMULT_LOOSE_RATIO 1.7f
#define SUBMULT_TIGHT 0.4f
#define SUBMULT_TIGHT_RATIO 3.5f
#define SUBMULT_ANY 0.05f
void xombe__pitch_init(xombe_enc *e)
{
e->p_prev = INITIAL_PERIOD;
e->e_prev1 = e->e_prev2 = 0.0f;
}
static float grid_period(int i)
{
return 0.5f * (float)(GRID_BASE + i);
}
static int grid_index(float P)
{
return (int)(2.0f * P + 0.5f) - GRID_BASE;
}
/* b > 0 */
static int floor_div(int a, int b)
{
return a >= 0 ? a / b : -((-a + b - 1) / b);
}
static float error_at(const xombe_enc *e, int slot, float P)
{
return e->psilent[slot] ? 1.0f : xombe__kern_error_at(e, slot, P);
}
void xombe__pitch_errors(xombe_enc *e, const float *centre, int slot)
{
int i;
xombe__kern_pitch_acf(e, centre, slot);
e->psilent[slot] = e->pe0[slot] < DIGITAL_SILENCE_E0;
for (i = 0; i < XOMBE_PITCH_GRID; i++)
e->perr[slot][i] = error_at(e, slot, grid_period(i));
}
/* in exact arithmetic, since 0.8*P and 1.2*P land on the grid for some P and those ends are included */
static void grid_range(int i, int *lo, int *hi)
{
*lo = -floor_div(TRACK_DEN * GRID_BASE - TRACK_LO_NUM * (GRID_BASE + i), TRACK_DEN);
*hi = floor_div(TRACK_HI_NUM * (GRID_BASE + i) - TRACK_DEN * GRID_BASE, TRACK_DEN);
if (*lo < 0)
*lo = 0;
if (*hi > XOMBE_PITCH_GRID - 1)
*hi = XOMBE_PITCH_GRID - 1;
}
static int argmin_range(const float *v, int lo, int hi)
{
int i, best = lo;
for (i = lo + 1; i <= hi; i++)
if (v[i] < v[best])
best = i;
return best;
}
XOMBE_STATIC_ASSERT(XOMBE_PITCH_GRID <= 256, grid_index_fits_uchar);
/* argmin_range(v, lo[i], hi[i]) for every i, lo[i] when empty, first on ties. linear time with a monotonic deque,
both ends being nondecreasing in i */
static void sliding_argmin(const float *v, const unsigned char *lo, const unsigned char *hi, unsigned char *out)
{
unsigned char dq[XOMBE_PITCH_GRID];
int i, head = 0, tail = 0, next = 0;
for (i = 0; i < XOMBE_PITCH_GRID; i++) {
if (lo[i] > hi[i]) {
out[i] = lo[i];
continue;
}
if (next < lo[i])
next = lo[i];
for (; next <= hi[i]; next++) {
while (tail > head && v[dq[tail - 1]] > v[next])
tail--;
dq[tail++] = (unsigned char)next;
}
while (dq[head] < lo[i])
head++;
out[i] = dq[head];
}
}
float xombe__pitch_track(xombe_enc *e, int cur, int next1, int next2)
{
const float *E0 = e->perr[cur], *E1 = e->perr[next1], *E2 = e->perr[next2];
float min2[XOMBE_PITCH_GRID], ce_f[XOMBE_PITCH_GRID], ce_b, period;
unsigned char rlo[XOMBE_PITCH_GRID], rhi[XOMBE_PITCH_GRID], am[XOMBE_PITCH_GRID];
int i, lo, hi, pb, pf, n;
if (e->psilent[cur])
return e->p_prev;
grid_range(grid_index(e->p_prev), &lo, &hi);
pb = lo <= hi ? argmin_range(E0, lo, hi) : 0;
ce_b = E0[pb] + e->e_prev1 + e->e_prev2;
for (i = 0; i < XOMBE_PITCH_GRID; i++) {
grid_range(i, &lo, &hi);
rlo[i] = (unsigned char)lo;
rhi[i] = (unsigned char)hi;
}
sliding_argmin(E2, rlo, rhi, am);
for (i = 0; i < XOMBE_PITCH_GRID; i++)
min2[i] = E2[am[i]];
sliding_argmin(E1, rlo, rhi, am);
for (i = 0; i < XOMBE_PITCH_GRID; i++)
ce_f[i] = E0[i] + E1[am[i]] + min2[am[i]];
pf = argmin_range(ce_f, 0, XOMBE_PITCH_GRID - 1);
for (n = (GRID_BASE + pf) / GRID_BASE; n >= 2; n--) {
/* grid index nearest P/n, halves up: floor((GRID_BASE + pf)/n - GRID_BASE + 1/2) */
int idx = floor_div(2 * (GRID_BASE + pf - n * GRID_BASE) + n, 2 * n);
float c, ratio;
if (idx < 0)
idx = 0;
c = ce_f[idx];
ratio = c / (ce_f[pf] > 1e-9f ? ce_f[pf] : 1e-9f);
if ((c <= SUBMULT_LOOSE && ratio <= SUBMULT_LOOSE_RATIO) || (c <= SUBMULT_TIGHT && ratio <= SUBMULT_TIGHT_RATIO) ||
c <= SUBMULT_ANY) {
pf = idx;
break;
}
}
i = (ce_b <= BACKWARD_ACCEPT || ce_b <= ce_f[pf]) ? pb : pf;
period = grid_period(i);
e->e_prev2 = e->e_prev1;
e->e_prev1 = E0[i];
e->p_prev = period;
if (period > HALVING_PERIOD && error_at(e, cur, 0.5f * period) <= E0[i] + HALVING_MARGIN)
period /= 2.0f;
return period;
}
int xombe__pitch_window_len(float period)
{
int n = 2 * (int)floorf((2.5f * period - 1.0f) / 2.0f + 0.5f) + 1;
if (n < XOMBE_BASE_WINDOW)
n = XOMBE_BASE_WINDOW;
if (n > XOMBE_MAX_WINDOW)
n = XOMBE_MAX_WINDOW;
return n;
}
float xombe__pitch_refine(xombe_enc *e, const xombe_spec *S, float period)
{
float best = 0.0f, band_r[8], band_e[8], best_p = period;
int d, found = 0, kmax = (int)(REFINE_TOP * XOMBE_FFT);
xombe_lf_spec sp;
xombe__kern_lf_prepare(e, S, 1, kmax, &sp);
for (d = -REFINE_STEPS; d <= REFINE_STEPS; d++) {
float p = period + (float)d / REFINE_STEPS, r;
if (p < REFINE_MIN_PERIOD)
continue;
r = xombe__kern_line_fit(e, &sp, p, (int)ceilf(0.5f * XOMBE_FFT / p), kmax, band_r, band_e);
if (!found || r < best) {
found = 1;
best = r;
best_p = p;
}
}
return best_p;
}
+54
View File
@@ -0,0 +1,54 @@
#include "../internal.h"
#include "../tables/tables.h"
#include "../tables/dsp_tables.h"
void xombe__quantize(const xombe_pred *pi, int silence, int L, const float *target, int b[9])
{
float pt[XOMBE_LMAX + 1];
float r[XOMBE_LMAX + 1], mean_t = 0.0f, mean_p = 0.0f, R[8], G[9], C[4][7];
int l, k, m, i, pos = 1;
xombe__predict(pi, L, pt);
for (l = 1; l <= L; l++) {
mean_t += target[l];
mean_p += pt[l];
}
mean_t /= (float)L;
mean_p /= (float)L;
{
float dgamma = mean_t + xombe__half_log2[L] - xombe__amp_ambe2.grho * pi->gamma;
if (silence)
dgamma += XOMBE_SILENCE_GAIN_OFFSET;
b[2] = xombe__nearest_row(xombe__dg, 32, 1, 1, &dgamma, NULL);
}
for (l = 1; l <= L; l++)
r[l] = target[l] - XOMBE_RHO * (pt[l] - mean_p);
for (k = 0; k < 4; k++) {
int J = xombe__blk[L][k], top = J < 6 ? J : 6;
const float *kern = xombe__dct_blk + xombe__dct_blk_off[J];
for (m = 1; m <= 6; m++) {
float s = 0.0f;
if (m <= top)
for (i = 0; i < J; i++)
s += r[pos + i] * kern[(m - 1) * J + i];
C[k][m] = m <= top ? s / (float)J : 0.0f;
}
if (J < 2)
C[k][2] = 0.0f;
pos += J;
R[2 * k] = C[k][1] + 1.41421356f * C[k][2];
R[2 * k + 1] = C[k][1] - 1.41421356f * C[k][2];
}
for (m = 1; m <= 8; m++) {
float s = 0.0f;
for (i = 0; i < 8; i++)
s += R[i] * xombe__dct8[m - 1][i];
G[m] = s / 8.0f;
}
b[3] = xombe__nearest_row(&xombe__prba24[0][0], 512, 3, 3, &G[2], NULL);
b[4] = xombe__nearest_row(&xombe__prba58[0][0], 128, 4, 4, &G[5], NULL);
for (k = 0; k < 4; k++) {
int J = xombe__blk[L][k], used = (J < 6 ? J : 6) - 2, rows;
const float *tab = xombe__hoc_table(k, &rows);
b[5 + k] = used > 0 ? xombe__nearest_row(tab, rows, 4, used, &C[k][3], NULL) : 0;
}
}
+720
View File
@@ -0,0 +1,720 @@
#include <math.h>
#include <string.h>
#include "../internal.h"
#include "../tables/dsp_tables.h"
#include "../dsp/biquad.h"
#if XOMBE_KERNELS_Q15
#include "kern_q15.h"
#include "../dsp/fft_q15.h"
#endif
#define EXPLAINED_MIN 0.99f
#define DUAL_GATE_SHARE 0.7f
#define DUAL_GATE_SPAN 0.10f
#define DUAL_TWIST_DB 10.0f
#define DUAL_PREFERENCE 0.01f
#define SINGLE_ID_HZ 31.25f /* single-tone IDs are multiples of this frequency */
#define GATE_LO_HZ 100.0f /* dual-tone gate reference band GATE_LO_HZ..GATE_HI_HZ */
#define GATE_HI_HZ 3900.0f
#define BIN_HZ (XOMBE_FS / XOMBE_TONE_FFT)
XOMBE_STATIC_ASSERT(XOMBE_TONE_FFT >= 2 * XOMBE_TONE_SEG, tone_fft_pads_the_segment);
#if XOMBE_KERNELS_Q15
#define DUAL_SLACK 1e-3f /* rounding allowance on an explained fraction of 1 */
#define TWIST_RATIO 3.16227766f /* 10^(DUAL_TWIST_DB/20) */
#define GATE_NUM 7u /* DUAL_GATE_SHARE = GATE_NUM/GATE_DEN */
#define GATE_DEN 10u
typedef uint64_t pow_sum;
/* sin and cos of 2*pi*t for |t| < 2^21, reduced exactly to a quarter turn q/4 plus f, |f| <= 1/8, Taylor
polynomials to a^9 and a^8 in a = 2*pi*f, truncation under 1e-9 */
static void sincos_turn(float t, float *s, float *c)
{
int q = round_q(4.0f * t);
float a = 2.0f * XOMBE_PI_F * (t - 0.25f * (float)q), a2 = a * a, sn, cs;
sn = a * (1.0f + a2 * (-1.0f / 6 + a2 * (1.0f / 120 + a2 * (-1.0f / 5040 + a2 * (1.0f / 362880)))));
cs = 1.0f + a2 * (-0.5f + a2 * (1.0f / 24 + a2 * (-1.0f / 720 + a2 * (1.0f / 40320))));
switch (q & 3) {
case 0: *s = sn; *c = cs; break;
case 1: *s = cs; *c = -sn; break;
case 2: *s = -sn; *c = -cs; break;
default: *s = -cs; *c = sn; break;
}
}
#else
typedef float pow_sum;
#endif
/* one sinusoid of the fit */
typedef struct {
float hz; /* Hz, w below is radians/sample */
float rc, rs; /* sum of x[n]*cos(w*n) and of x[n]*sin(w*n) */
float h[2]; /* cos and sin of w/2 */
float m[2]; /* cos and sin of (2*len - 1)*w/2 */
float g[4]; /* own Gram block gram(c, c), set by fit_component */
} component;
#if XOMBE_KERNELS_Q15
/* hz, h, and m of c */
static void angles(int len, float hz, component *c)
{
float u = hz * (0.5f / XOMBE_FS); /* w/2 in turns */
c->hz = hz;
sincos_turn(u, &c->h[1], &c->h[0]);
sincos_turn((float)(2 * len - 1) * u, &c->m[1], &c->m[0]);
}
#endif
/* correlates x with cos and sin at hz, Goertzel run from x[len - 1] down so its final states need no rotation,
in Reinsch's form (d = s[n] -/+ s[n - 1]), as plain Goertzel loses about 5 bits near 0 Hz and fs/2 */
static void correlate(const float *x, int len, float hz, component *c)
{
#if XOMBE_KERNELS_Q15
float hc, hs;
angles(len, hz, c);
hc = c->h[0];
hs = c->h[1];
#else
float w = 2.0f * XOMBE_PI_F * hz / XOMBE_FS, hc = cosf(0.5f * w), hs = sinf(0.5f * w);
#endif
float cw = hc * hc - hs * hs, s = 0.0f, d = 0.0f, prev;
int n = len - 1;
if (cw >= 0.0f) {
float l = -4.0f * hs * hs;
for (; n > 0; n -= 2) {
d += x[n] + l * s;
s += d;
d += x[n - 1] + l * s;
s += d;
}
if (n == 0) {
d += x[0] + l * s;
s += d;
}
prev = s - d;
} else {
float l = 4.0f * hc * hc;
for (; n > 0; n -= 2) {
d = x[n] + l * s - d;
s = d - s;
d = x[n - 1] + l * s - d;
s = d - s;
}
if (n == 0) {
d = x[0] + l * s - d;
s = d - s;
}
prev = d - s;
}
c->rc = s - cw * prev;
c->rs = 2.0f * hs * hc * prev;
#if !XOMBE_KERNELS_Q15
c->hz = hz;
c->h[0] = hc;
c->h[1] = hs;
c->m[0] = cosf((float)(2 * len - 1) * 0.5f * w);
c->m[1] = sinf((float)(2 * len - 1) * 0.5f * w);
#endif
}
/* sums of cos(th*n) and sin(th*n) over the segment, a Dirichlet kernel, from cos and sin of th/2 (h) and of
(2*len - 1)*th/2 (m) */
static void dsum(const float h[2], const float m[2], int len, float *c, float *s)
{
if (fabsf(h[1]) < 1e-6f) {
*c = (float)len;
*s = 0.0f;
return;
}
*c = 0.5f + 0.5f * m[1] / h[1];
*s = 0.5f * (h[0] - m[0]) / h[1];
}
/* Gram block of a and b, rows cos_a, sin_a, columns cos_b, sin_b, row-major, dsum angles by angle addition */
static void gram(const component *a, const component *b, int len, float g[4])
{
float cd, sd, cs, ss, hd[2], md[2], hs[2], ms[2];
hd[0] = a->h[0] * b->h[0] + a->h[1] * b->h[1];
hd[1] = a->h[1] * b->h[0] - a->h[0] * b->h[1];
md[0] = a->m[0] * b->m[0] + a->m[1] * b->m[1];
md[1] = a->m[1] * b->m[0] - a->m[0] * b->m[1];
hs[0] = a->h[0] * b->h[0] - a->h[1] * b->h[1];
hs[1] = a->h[1] * b->h[0] + a->h[0] * b->h[1];
ms[0] = a->m[0] * b->m[0] - a->m[1] * b->m[1];
ms[1] = a->m[1] * b->m[0] + a->m[0] * b->m[1];
dsum(hd, md, len, &cd, &sd);
dsum(hs, ms, len, &cs, &ss);
g[0] = 0.5f * (cd + cs);
g[1] = 0.5f * (ss - sd);
g[2] = 0.5f * (ss + sd);
g[3] = 0.5f * (cd - cs);
}
/* correlate plus own Gram block, so a trial moving one component recomputes only its own */
static void fit_component(const float *x, int len, float hz, component *c)
{
correlate(x, len, hz, c);
gram(c, c, len, c->g);
}
#if XOMBE_KERNELS_Q15
/* correlations of x already taken in one search, keyed by frequency (hz 0: empty slot). pairs share
frequencies (DTMF rows and columns) and revisit trial steps, so on the worst frames over half the
correlations repeat */
#define MEMO_LOG2 7
#define MEMO_SLOTS (1 << MEMO_LOG2)
#define MEMO_PROBES 8
typedef struct {
float hz[MEMO_SLOTS], rc[MEMO_SLOTS], rs[MEMO_SLOTS];
} corr_memo;
/* fit_component through the memo, a full probe run computes without storing */
static void memo_component(corr_memo *mo, const float *x, int len, float hz, component *c)
{
uint32_t bits;
int i, probe;
memcpy(&bits, &hz, sizeof(bits));
i = (int)((bits * 2654435761u) >> (32 - MEMO_LOG2));
for (probe = 0; probe < MEMO_PROBES; probe++, i = (i + 1) & (MEMO_SLOTS - 1)) {
if (mo->hz[i] == hz) {
angles(len, hz, c);
c->rc = mo->rc[i];
c->rs = mo->rs[i];
gram(c, c, len, c->g);
return;
}
if (mo->hz[i] == 0.0f) {
fit_component(x, len, hz, c);
mo->hz[i] = hz;
mo->rc[i] = c->rc;
mo->rs[i] = c->rs;
return;
}
}
fit_component(x, len, hz, c);
}
/* pair_fit's memo parameter and argument, absent in float builds */
#define PAIR_COMPONENT(x, len, hz, c) memo_component(mo, x, len, hz, c)
#define PAIR_MEMO corr_memo *mo,
#define PAIR_MEMO_ARG &memo,
#else
#define PAIR_COMPONENT(x, len, hz, c) fit_component(x, len, hz, c)
#define PAIR_MEMO
#define PAIR_MEMO_ARG
#endif
/* solves 2x2 m*p = r, returns 0 if m is singular */
static int solve2(const float m[4], const float r[2], float p[2])
{
float det = m[0] * m[3] - m[1] * m[2];
if (fabsf(det) <= 1e-6f * (m[0] * m[0] + m[3] * m[3]))
return 0;
p[0] = (m[3] * r[0] - m[1] * r[1]) / det;
p[1] = (m[0] * r[1] - m[2] * r[0]) / det;
return 1;
}
static float magnitude(const float p[2])
{
#if XOMBE_KERNELS_Q15
return sqrtf(p[0] * p[0] + p[1] * p[1]);
#else
return hypotf(p[0], p[1]);
#endif
}
/* least-squares fit of nf (1 or 2) sinusoids, returns the fraction of energy explained and each amplitude,
0 and amplitudes 0 for a singular system. two components solved by blocks (Schur complement of the first block) */
static float fit(float energy, const component *c, int nf, int len, float amp[2])
{
const float *A = c[0].g;
float ra[2], pa[2], explained;
amp[0] = amp[1] = 0.0f;
ra[0] = c[0].rc;
ra[1] = c[0].rs;
if (nf == 1) {
if (!solve2(A, ra, pa))
return 0.0f;
explained = pa[0] * ra[0] + pa[1] * ra[1];
} else {
const float *B = c[1].g;
float C[4], Y[4], y[2], S[4], rhs[2], pb[2], col[2], cj[2], rb[2];
int j;
rb[0] = c[1].rc;
rb[1] = c[1].rs;
gram(&c[0], &c[1], len, C);
if (!solve2(A, ra, y))
return 0.0f;
for (j = 0; j < 2; j++) { /* Y = A^-1*C, column by column */
cj[0] = C[j];
cj[1] = C[2 + j];
if (!solve2(A, cj, col))
return 0.0f;
Y[j] = col[0];
Y[2 + j] = col[1];
}
/* S = B - C^T*Y, rhs = rb - C^T*y */
S[0] = B[0] - (C[0] * Y[0] + C[2] * Y[2]);
S[1] = B[1] - (C[0] * Y[1] + C[2] * Y[3]);
S[2] = B[2] - (C[1] * Y[0] + C[3] * Y[2]);
S[3] = B[3] - (C[1] * Y[1] + C[3] * Y[3]);
rhs[0] = rb[0] - (C[0] * y[0] + C[2] * y[1]);
rhs[1] = rb[1] - (C[1] * y[0] + C[3] * y[1]);
if (!solve2(S, rhs, pb))
return 0.0f;
pa[0] = y[0] - (Y[0] * pb[0] + Y[1] * pb[1]);
pa[1] = y[1] - (Y[2] * pb[0] + Y[3] * pb[1]);
amp[1] = magnitude(pb);
explained = pa[0] * ra[0] + pa[1] * ra[1] + pb[0] * rb[0] + pb[1] * rb[1];
}
amp[0] = magnitude(pa);
return explained / energy;
}
static int in_gate(int k, float nominal)
{
return fabsf((float)k * BIN_HZ - nominal) <= DUAL_GATE_SPAN * nominal;
}
/* bins *lo..*hi of nominal's dual-tone gate, empty when *lo > *hi. the gate is at least a bin wide and k*BIN_HZ
is exact, so in_gate holds on one run of k containing the nearest bin, each end a step or two from its estimate */
static void gate_run(float nominal, int *lo, int *hi)
{
int k0 = (int)(nominal / BIN_HZ + 0.5f), k;
if (k0 > XOMBE_TONE_FFT / 2)
k0 = XOMBE_TONE_FFT / 2;
if (!in_gate(k0, nominal)) {
*lo = 1;
*hi = 0;
return;
}
k = (int)ceilf((1.0f - DUAL_GATE_SPAN) * nominal / BIN_HZ);
k = k < 0 ? 0 : k > k0 ? k0 : k;
while (k > 0 && in_gate(k - 1, nominal))
k--;
while (k < k0 && !in_gate(k, nominal))
k++;
*lo = k;
k = (int)floorf((1.0f + DUAL_GATE_SPAN) * nominal / BIN_HZ);
k = k < k0 ? k0 : k > XOMBE_TONE_FFT / 2 ? XOMBE_TONE_FFT / 2 : k;
while (k < XOMBE_TONE_FFT / 2 && in_gate(k + 1, nominal))
k++;
while (k > k0 && !in_gate(k, nominal))
k--;
*hi = k;
}
static int ad_from_level(float level_db_minus_filter)
{
int ad = (int)floorf(127.0f + level_db_minus_filter / XOMBE_TONE_DB_PER_AD + 0.5f);
return ad < 0 ? 0 : ad > 127 ? 127 : ad;
}
static float peak_db(float amp)
{
return 20.0f * log10f(amp / 32768.0f + 1e-30f);
}
#if !XOMBE_KERNELS_Q15
static void spectrum(xombe_enc *e, const float *x, int len, const float *win, float pw[XOMBE_TONE_FFT / 2 + 1])
{
xombe_cpx *X = e->tone_spec;
int n, k;
/* packed two samples per bin for xombe__rfft_packed */
memset(e->tone_spec, 0, sizeof(e->tone_spec));
for (n = 0; n < len; n++) {
float v = x[n] * win[n];
if (n & 1)
X[n >> 1].im = v;
else
X[n >> 1].re = v;
}
xombe__rfft_packed(X, XOMBE_TONE_FFT, xombe__fft_tw, XOMBE_TW_N);
for (k = 0; k <= XOMBE_TONE_FFT / 2; k++)
pw[k] = X[k].re * X[k].re + X[k].im * X[k].im;
}
#else
#define SPEC_M (XOMBE_TONE_FFT / 2)
#define SPEC_LOG2 8
XOMBE_STATIC_ASSERT(1 << SPEC_LOG2 == SPEC_M, spec_log2);
/* bin powers of the windowed segment through the SPEC_M point block-floating-point FFT of sample pairs, in
place over pw: samples block-scaled to XOMBE_CFFT_Q15_PEAK, real-input split in integer, one power unit for
every bin of the segment */
static void spectrum(xombe_enc *e, const float *x, int len, const float *win, uint32_t pw[XOMBE_TONE_FFT / 2 + 1])
{
uint32_t *z = pw;
float m = 0.0f, g;
int n, k;
(void)e;
for (n = 0; n < len; n++) {
float a = fabsf(x[n] * win[n]);
m = a > m ? a : m;
}
g = q15_gain(m, (float)XOMBE_CFFT_Q15_PEAK);
memset(z, 0, SPEC_M * sizeof(*z));
if (g == 0.0f) {
pw[SPEC_M] = 0;
return;
}
for (n = 0; n < len; n += 2) {
int32_t lo = round_q(x[n] * win[n] * g), hi = n + 1 < len ? round_q(x[n + 1] * win[n + 1] * g) : 0;
z[q15_rbit((uint32_t)(n >> 1)) >> (32 - SPEC_LOG2)] = ((uint32_t)lo & 0xffffu) | (uint32_t)hi << 16;
}
xombe__cfft_q15(z, SPEC_M, xombe__tone_tw_q15, XOMBE_CFFT_Q15_PEAK);
/* bins k and SPEC_M - k from Z[k] and Z[SPEC_M - k], 2*X[k] = E + W^k*O with W^k = xombe__fft_tw_q15[k]:
components of E and O within +/-2^16, so |2*X| <= 2^17.5 and |2*X|^2 >> 4 <= 2^31. the Q15 product
sums reach 2^32 and take 64 bits */
for (k = 0; k <= SPEC_M / 2; k++) {
uint32_t a = z[k], b = z[(SPEC_M - k) & (SPEC_M - 1)];
int32_t er = q15_lo(a) + q15_lo(b), ei = q15_hi(a) - q15_hi(b);
int32_t orr = q15_hi(a) + q15_hi(b), oi = q15_lo(b) - q15_lo(a), wr = 0, wi = -32768, pr, pi, r0, i0, r1, i1;
if (k < SPEC_M / 2) {
wr = q15_lo(xombe__fft_tw_q15[k]);
wi = q15_hi(xombe__fft_tw_q15[k]);
}
pr = (int32_t)(((int64_t)wr * orr - (int64_t)wi * oi + 16384) >> 15);
pi = (int32_t)(((int64_t)wr * oi + (int64_t)wi * orr + 16384) >> 15);
r0 = er + pr;
i0 = ei + pi;
r1 = er - pr;
i1 = pi - ei;
pw[k] = (uint32_t)(((uint64_t)((int64_t)r0 * r0) + (uint64_t)((int64_t)i0 * i0)) >> 4);
pw[SPEC_M - k] = (uint32_t)(((uint64_t)((int64_t)r1 * r1) + (uint64_t)((int64_t)i1 * i1)) >> 4);
}
}
#endif
/* mean-removed segment into x, returns its energy or 0 below the -50 dBFS sinusoid floor. above it, fills pw
with the zero-padded bin powers of the segment under win */
static float prepare(xombe_enc *e, const int16_t *seg, int len, const float *win, float *x,
xombe_tone_pow pw[XOMBE_TONE_FFT / 2 + 1])
{
static const float min_amp = 32768.0f * 0.0031622777f; /* -50 dBFS peak */
float mean, energy = 0.0f;
long sum = 0;
int n;
for (n = 0; n < len; n++)
sum += seg[n];
mean = (float)sum / len;
for (n = 0; n < len; n++) {
x[n] = (float)seg[n] - mean;
energy += x[n] * x[n];
}
if (energy / len < 0.5f * min_amp * min_amp)
return 0.0f;
spectrum(e, x, len, win, pw);
return energy;
}
static pow_sum band_total(const xombe_tone_pow *pw)
{
pow_sum total = 0;
int k;
for (k = (int)ceilf(GATE_LO_HZ / BIN_HZ); k <= (int)floorf(GATE_HI_HZ / BIN_HZ); k++)
total += pw[k];
return total;
}
/* at least DUAL_GATE_SHARE of total within DUAL_GATE_SPAN of either nominal frequency */
static int gate_pass(const xombe_tone_pow *pw, const float nominal[2], pow_sum total)
{
pow_sum near = 0;
int k, r0lo, r0hi, r1lo, r1hi, klo, khi;
/* summed in ascending bins over the union of the two runs */
gate_run(nominal[0], &r0lo, &r0hi);
gate_run(nominal[1], &r1lo, &r1hi);
klo = r0lo <= r0hi ? r0lo : r1lo;
khi = r0lo <= r0hi ? r0hi : r1hi;
if (r1lo <= r1hi) {
klo = r1lo < klo ? r1lo : klo;
khi = r1hi > khi ? r1hi : khi;
}
for (k = klo; k <= khi; k++)
if ((k >= r0lo && k <= r0hi) || (k >= r1lo && k <= r1hi))
near += pw[k];
#if XOMBE_KERNELS_Q15
return near * GATE_DEN >= total * GATE_NUM;
#else
return !(near < DUAL_GATE_SHARE * total);
#endif
}
#define FINE_FFT 8192 /* single-tone peak grid */
#define FINE_HZ (XOMBE_FS / FINE_FFT)
#define FINE_LO 103 /* FINE_FFT bins in GATE_LO_HZ..GATE_HI_HZ */
#define FINE_HI 3993
#define REFINE_SPAN 0.4f /* single-tone refinement, +/- fine bins around the peak */
#define REFINE_ITERS 12
/* explained fraction moves at most ~0.15 per Hz for a 160-sample segment (the fit subspace turns at most
2*pi*rms(n)/fs radians per Hz), so refining within REFINE_SPAN (0.39 Hz) gains under 0.06 and a fit this far
below the threshold cannot reach it */
#define REFINE_REACH 0.1f
#define DUAL_STEP 0.0025f /* relative dual search step, steps are 4, 2, and 1 of these */
#define DUAL_STEPS_MAX 10 /* +/-2.5% of nominal in steps */
#define PAIR_TRIALS 24 /* pair_fit trials, 2 passes x 3 steps x 2 components x 2 signs */
float xombe__tone_hpf_gain_db(float hz)
{
const float p1 = (float)HPF_POLE1, a1 = (float)HPF_A1, a2 = (float)HPF_A2;
float w = 2.0f * XOMBE_PI_F * hz / XOMBE_FS, cr = cosf(w), ci = -sinf(w), c2r = cosf(2.0f * w),
c2i = -sinf(2.0f * w);
float zr = 1.0f - cr, zi = -ci, nr = zr * zr - zi * zi, ni = 2.0f * zr * zi;
float n3r = nr * zr - ni * zi, n3i = nr * zi + ni * zr;
float d1r = 1.0f - p1 * cr, d1i = -p1 * ci, d2r = 1.0f - a1 * cr + a2 * c2r, d2i = -a1 * ci + a2 * c2i;
float num = n3r * n3r + n3i * n3i, den = (d1r * d1r + d1i * d1i) * (d2r * d2r + d2i * d2i);
return 10.0f * log10f(num / den);
}
/* windowed segment power at FINE_FFT bin k */
static float fine_power(const float *xw, int len, int k)
{
component c;
correlate(xw, len, (float)k * FINE_HZ, &c);
return c.rc * c.rc + c.rs * c.rs;
}
/* largest pw bin in the gate band, in bins, placed by a parabola through log magnitudes: the Hann peak is
near-Gaussian, so within 0.1 Hz */
static float coarse_peak(const xombe_tone_pow *pw)
{
int k, kc = -1, klo = (int)ceilf(GATE_LO_HZ / BIN_HZ), khi = (int)floorf(GATE_HI_HZ / BIN_HZ);
float la, lb, lc, d;
for (k = klo; k <= khi; k++)
if (kc < 0 || pw[k] > pw[kc])
kc = k;
la = 0.5f * logf((float)pw[kc - 1] + 1e-30f);
lb = 0.5f * logf((float)pw[kc] + 1e-30f);
lc = 0.5f * logf((float)pw[kc + 1] + 1e-30f);
d = la - 2.0f * lb + lc;
return (float)kc + (d != 0.0f ? 0.5f * (la - lc) / d : 0.0f);
}
/* largest FINE_FFT bin in the gate band plus a parabola through log magnitudes, found by climbing the fine grid
from the coarse peak */
static float peak_hz(const float *x, const float *win, int len, const xombe_tone_pow *pw)
{
int kf = (int)floorf(coarse_peak(pw) * (float)(FINE_FFT / XOMBE_TONE_FFT) + 0.5f), n;
float xw[XOMBE_TONE_SEG], pm, pl, pr, a, b, c, den;
for (n = 0; n < len; n++)
xw[n] = x[n] * win[n];
kf = kf < FINE_LO ? FINE_LO : kf > FINE_HI ? FINE_HI : kf;
pm = fine_power(xw, len, kf);
pl = fine_power(xw, len, kf - 1);
pr = fine_power(xw, len, kf + 1);
while (pr > pm && kf < FINE_HI) {
kf++;
pl = pm;
pm = pr;
pr = fine_power(xw, len, kf + 1);
}
while (pl > pm && kf > FINE_LO) {
kf--;
pr = pm;
pm = pl;
pl = fine_power(xw, len, kf - 1);
}
a = 0.5f * logf(pl + 1e-30f);
b = 0.5f * logf(pm + 1e-30f);
c = 0.5f * logf(pr + 1e-30f);
den = a - 2.0f * b + c;
return ((float)kf + (den != 0.0f ? 0.5f * (a - c) / den : 0.0f)) * FINE_HZ;
}
/* ternary search for the best single-tone fit within REFINE_SPAN fine bins of f1 */
static float fit_refined(const float *x, int len, float energy, float f1, float amp[2])
{
float lo = f1 - REFINE_SPAN * FINE_HZ, hi = f1 + REFINE_SPAN * FINE_HZ, unused[2];
component c;
int it;
for (it = 0; it < REFINE_ITERS; it++) {
float fa = lo + (hi - lo) / 3.0f, fb = hi - (hi - lo) / 3.0f, ea, eb;
fit_component(x, len, fa, &c);
ea = fit(energy, &c, 1, len, unused);
fit_component(x, len, fb, &c);
eb = fit(energy, &c, 1, len, unused);
if (ea > eb)
hi = fb;
else
lo = fa;
}
fit_component(x, len, 0.5f * (lo + hi), &c);
return fit(energy, &c, 1, len, amp);
}
/* coordinate search in relative steps of 4, 2, and 1 DUAL_STEP, each pass trying each step on the first
component then the second, up then down */
static float pair_fit(PAIR_MEMO const float *x, int len, float energy, const float nominal[2], float hz[2],
float amp[2])
{
static const int steps[3] = {4, 2, 1};
component comp[2];
int d[2] = {0, 0}, seen[PAIR_TRIALS + 1], pass, s, c, sign, nseen = 1;
float best, trial_amp[2] = {0.0f, 0.0f};
PAIR_COMPONENT(x, len, nominal[0], &comp[0]);
PAIR_COMPONENT(x, len, nominal[1], &comp[1]);
best = fit(energy, comp, 2, len, amp);
seen[0] = 0;
for (pass = 0; pass < 2; pass++)
for (s = 0; s < 3; s++)
for (c = 0; c < 2; c++)
for (sign = 1; sign >= -1; sign -= 2) {
int nd = d[c] + sign * steps[s], key, i;
component keep = comp[c];
float te;
if (nd > DUAL_STEPS_MAX || nd < -DUAL_STEPS_MAX)
continue;
key = c ? d[0] * 64 + nd : nd * 64 + d[1];
for (i = 0; i < nseen && seen[i] != key; i++)
;
if (i < nseen) /* a pair already evaluated explains no more than best */
continue;
seen[nseen++] = key;
PAIR_COMPONENT(x, len, nominal[c] * (1.0f + DUAL_STEP * (float)nd), &comp[c]);
te = fit(energy, comp, 2, len, trial_amp);
if (te > best) {
best = te;
d[c] = nd;
amp[0] = trial_amp[0];
amp[1] = trial_amp[1];
} else {
comp[c] = keep;
}
}
hz[0] = comp[0].hz;
hz[1] = comp[1].hz;
return best;
}
/* components more than DUAL_TWIST_DB apart, amp > 0 */
static int twisted(const float amp[2])
{
#if XOMBE_KERNELS_Q15
return amp[0] > TWIST_RATIO * amp[1] || amp[1] > TWIST_RATIO * amp[0];
#else
return fabsf(20.0f * log10f(amp[0] / amp[1])) > DUAL_TWIST_DB;
#endif
}
void xombe__tone_prepare(xombe_enc *e, const int16_t *seg, const xombe_tone_search *ts, xombe_tone_seg *sg)
{
sg->energy = prepare(e, seg, ts->len, ts->win, sg->x, sg->pw);
}
int xombe__tone_search(const xombe_tone_seg *sg, const xombe_tone_search *ts, xombe_tone_hit *hit)
{
const float *x = sg->x;
const xombe_tone_pow *pw = sg->pw;
pow_sum total;
float energy = sg->energy, e1 = 0.0f, best = -1.0f, best_level = 0.0f, best_res = 0.0f;
int i, single = 0, dual = -1, len = ts->len, npairs = ts->npairs;
#if XOMBE_KERNELS_Q15
corr_memo memo;
int memo_ready = 0;
#endif
hit->id = -1;
if (energy == 0.0f)
return 0;
if (ts->singles) {
float f1 = ts->fine_peak ? peak_hz(x, ts->win, len, pw) : coarse_peak(pw) * BIN_HZ, amp[2];
int cand = (int)floorf(f1 / SINGLE_ID_HZ + 0.5f);
component c;
fit_component(x, len, f1, &c);
e1 = fit(energy, &c, 1, len, amp);
if (ts->fine_peak && e1 >= ts->emin - REFINE_REACH)
e1 = fit_refined(x, len, energy, f1, amp);
if (e1 >= ts->emin && cand >= 5 && cand <= 122) {
single = 1;
hit->id = cand;
hit->e = e1;
hit->level = peak_db(amp[0] > 1e-9f ? amp[0] : 1e-9f) - xombe__tone_hpf_gain_db(f1);
hit->res = energy * (1.0f - e1);
}
}
#if XOMBE_KERNELS_Q15
/* a least-squares fit explains at most the whole energy, so a dual cannot beat e1 + DUAL_PREFERENCE past 1
plus rounding slack */
if (single && e1 + DUAL_PREFERENCE > 1.0f + DUAL_SLACK)
npairs = 0;
#endif
total = band_total(pw);
for (i = 0; i < npairs; i++) {
const xombe_tone_pair *p = &ts->pairs[i];
float hz[2], amp[2], ex;
if (!gate_pass(pw, p->hz, total))
continue;
#if XOMBE_KERNELS_Q15
if (!memo_ready) {
memset(memo.hz, 0, sizeof(memo.hz));
memo_ready = 1;
}
#endif
ex = pair_fit(PAIR_MEMO_ARG x, len, energy, p->hz, hz, amp);
if (ex < ts->emin || amp[0] <= 0.0f || amp[1] <= 0.0f || twisted(amp))
continue;
if (ex > best) {
best = ex;
dual = p->id;
best_level = 0.5f * ((peak_db(amp[0]) - xombe__tone_hpf_gain_db(hz[0])) +
(peak_db(amp[1]) - xombe__tone_hpf_gain_db(hz[1])));
best_res = energy * (1.0f - ex);
}
}
if (dual >= 0 && (!single || best > e1 + DUAL_PREFERENCE)) {
hit->id = dual;
hit->e = best;
hit->level = best_level;
hit->res = best_res;
}
return hit->id >= 0;
}
int xombe__tone_detect(xombe_enc *e, const int16_t *seg, int *id, int *ad)
{
xombe_tone_pair pairs[XOMBE_TONE_DUALS];
xombe_tone_search ts;
xombe_tone_seg sg;
xombe_tone_hit h;
int i;
ts.len = XOMBE_TONE_SEG;
ts.win = xombe__tone_win;
ts.emin = EXPLAINED_MIN;
ts.singles = 1;
ts.fine_peak = 0;
ts.pairs = pairs;
ts.npairs = XOMBE_TONE_DUALS;
xombe__tone_prepare(e, seg, &ts, &sg);
if (sg.energy == 0.0f)
return 0;
for (i = 0; i < ts.npairs; i++) {
pairs[i].id = (short)(XOMBE_TONE_DUAL_FIRST + i);
xombe__tone_freqs(pairs[i].id, &pairs[i].hz[0], &pairs[i].hz[1]);
}
if (!xombe__tone_search(&sg, &ts, &h))
return 0;
*id = h.id;
*ad = ad_from_level(h.level);
return 1;
}
int xombe__tone_decide(xombe_enc *e, int detected, int det_id, int det_ad, int *id, int *ad)
{
int tone = 0;
if (detected && det_id == e->tone_prev_id) {
e->tone_confirmed = 1;
e->tone_hold_used = 0;
e->tone_last_id = det_id;
e->tone_last_ad = det_ad;
tone = 1;
} else if (!detected && e->tone_confirmed && !e->tone_hold_used) {
e->tone_hold_used = 1;
tone = 1;
} else {
e->tone_confirmed = 0;
}
e->tone_prev_id = detected ? det_id : -1;
*id = e->tone_last_id;
*ad = e->tone_last_ad;
return tone;
}
+184
View File
@@ -0,0 +1,184 @@
#include <math.h>
#include <string.h>
#include "../internal.h"
#define VAD_BAND_OFFSET 1e-3f
#define VAD_FLOOR_REL 1e-3f
#define VAD_FLOOR_ABS 1.0f
#define ABSORB_SPREAD XOMBE_DB(4.0f)
/* digital silence (any constant code): FLAT_RUN equal consecutive input samples in a window */
#define FLAT_RUN 16
/* history: log2 powers in Q10, their sum in linear Q20. smoothed powers lie in [VAD_BAND_OFFSET, 2^30] (int16
input's total power), so logs fit int16 and 300 linear values int64, and a value leaving the history removes
exactly what it added */
#define HIST_LOG_ONE 1024
#define HIST_LIN_ONE 1048576.0f
#define VAD_LOW XOMBE_HZ(100.0f)
#define VAD_HIGH XOMBE_HZ(4000.0f)
static void band_powers(const float *P, float E[8])
{
int k, b;
for (b = 0; b < 8; b++)
E[b] = VAD_BAND_OFFSET;
for (k = 0; k < XOMBE_SPEC_BINS; k++) {
float f = (float)k / XOMBE_FFT;
if (f < VAD_LOW || f >= VAD_HIGH)
continue;
b = (int)(f * XOMBE_BANDS_PER_UNIT);
E[b] += P[k];
}
}
static int16_t hist_log(float x)
{
return (int16_t)floorf(log2f(x) * HIST_LOG_ONE + 0.5f);
}
static int64_t hist_lin(int16_t q)
{
return (int64_t)(exp2f((float)q / HIST_LOG_ONE) * HIST_LIN_ONE + 0.5f);
}
static float noise_floor(const float nl[8])
{
float m = 0.0f;
int b;
for (b = 0; b < 8; b++)
if (nl[b] > m)
m = nl[b];
m *= VAD_FLOOR_REL;
return m > VAD_FLOOR_ABS ? m : VAD_FLOOR_ABS;
}
static float vad_metric(const float E[8], const float nl[8], float fl)
{
float best = 0.0f, second = 0.0f;
int b;
for (b = 0; b < 8; b++) {
float snr = log2f((E[b] > fl ? E[b] : fl) / (nl[b] > fl ? nl[b] : fl));
if (snr < 0.0f)
snr = 0.0f;
if (snr > best) {
second = best;
best = snr;
} else if (snr > second) {
second = snr;
}
}
return 0.5f * (best + second);
}
/* minimum-statistics release (Martin, 2001), returns 1 if any band moved. a band above its noise level in every
half of the 3 s history is locked (its background reads as speech, so the noise update can't raise it), and its
level rises to the minimum smoothed power over the history. clean speech dips to the background in pauses, so
the level overshoots only when a pauseless sound fills the whole history */
static int vad_release(xombe_enc *e)
{
int b, i, moved = 0;
for (b = 0; b < 8; b++) {
int lo = INT16_MAX;
if (e->vad_above[b] < XOMBE_VAD_HIST)
continue;
for (i = 0; i < XOMBE_VAD_HIST; i++)
if (e->vad_hist[i][b] < lo)
lo = e->vad_hist[i][b];
if ((float)lo > log2f(e->vad_nl[b]) * HIST_LOG_ONE) {
e->vad_nl[b] = exp2f((float)lo / HIST_LOG_ONE);
moved = 1;
}
}
return moved;
}
/* returns 1 if x[0..n) holds FLAT_RUN equal consecutive samples */
int xombe__vad_flat(const int16_t *x, int n)
{
int i, run = 1;
for (i = 1; i < n; i++) {
run = x[i] == x[i - 1] ? run + 1 : 1;
if (run >= FLAT_RUN)
return 1;
}
return 0;
}
/* flat: window holds digital silence (xombe__vad_flat), which can't lower the noise levels */
void xombe__vad_half(xombe_enc *e, const float *P, int flat, int *speech, float *v)
{
float E[8], fl;
int16_t *row;
int b, i, redo = 0;
band_powers(P, E);
if (!e->vad_ready) {
memcpy(e->vad_nl, E, sizeof(E));
memcpy(e->vad_smooth, E, sizeof(E));
e->vad_ready = 1;
} else {
for (b = 0; b < 8; b++)
e->vad_smooth[b] = 0.8f * e->vad_smooth[b] + 0.2f * E[b];
}
fl = noise_floor(e->vad_nl);
*v = vad_metric(E, e->vad_nl, fl);
*speech = *v >= XOMBE_VAD_THRESHOLD;
for (b = 0; b < 8; b++) {
if ((E[b] > fl ? E[b] : fl) > (e->vad_nl[b] > fl ? e->vad_nl[b] : fl)) {
if (e->vad_above[b] < XOMBE_VAD_HIST)
e->vad_above[b]++;
} else {
e->vad_above[b] = 0;
}
}
if (!*speech) {
for (b = 0; b < 8; b++) {
float nl;
if (E[b] < e->vad_nl[b] / 4.0f)
nl = 0.5f * e->vad_nl[b] + 0.5f * E[b];
else
nl = 0.9f * e->vad_nl[b] + 0.1f * E[b];
if (!flat || nl > e->vad_nl[b])
e->vad_nl[b] = nl;
}
}
/* stationarity test floors stored smoothed powers at each half's own fl */
row = e->vad_hist[e->vad_hist_pos];
for (b = 0; b < 8; b++) {
if (e->vad_hist_n == XOMBE_VAD_HIST)
e->vad_hist_sum[b] -= hist_lin(row[b]);
row[b] = hist_log(e->vad_smooth[b]);
e->vad_hist_sum[b] += hist_lin(row[b]);
}
e->vad_hist_fl[e->vad_hist_pos] = hist_log(fl);
e->vad_hist_pos = (e->vad_hist_pos + 1) % XOMBE_VAD_HIST;
if (e->vad_hist_n < XOMBE_VAD_HIST)
e->vad_hist_n++;
if (e->vad_hist_n == XOMBE_VAD_HIST) {
int steady = 1;
for (b = 0; b < 8 && steady; b++) {
int lo = INT16_MAX, hi = INT16_MIN;
for (i = 0; i < XOMBE_VAD_HIST; i++) {
int x = e->vad_hist[i][b] > e->vad_hist_fl[i] ? e->vad_hist[i][b] : e->vad_hist_fl[i];
if (x < lo)
lo = x;
if (x > hi)
hi = x;
}
steady = hi - lo <= ABSORB_SPREAD * HIST_LOG_ONE;
}
if (steady) {
for (b = 0; b < 8; b++) {
float mean = (float)e->vad_hist_sum[b] / (XOMBE_VAD_HIST * HIST_LIN_ONE);
if (mean > e->vad_nl[b])
e->vad_nl[b] = mean;
}
redo = 1;
}
redo |= vad_release(e);
}
/* redecide after absorption or release, without a second noise update */
if (redo) {
fl = noise_floor(e->vad_nl);
*v = vad_metric(E, e->vad_nl, fl);
*speech = *v >= XOMBE_VAD_THRESHOLD;
}
}
+92
View File
@@ -0,0 +1,92 @@
#include <string.h>
#include "kernels.h"
#define METRIC_TOP XOMBE_HZ(3950.0f) /* metric fits harmonics below this */
#define JITTER_STEPS 9
#define JITTER_STEP 0.005f
#define SOFT_OFFSET (-0.661f)
#define WEIGHT_FLOOR 1e-3f
#define FIRST_HALF_WEIGHT 0.5f
#define B1_SEARCH_MAX 17
#define METRIC_KMAX ((int)(METRIC_TOP * XOMBE_FFT) - 1)
void xombe__voicing_prepare(xombe_enc *e, const xombe_spec *S, xombe_lf_spec *sp)
{
xombe__kern_lf_prepare(e, S, 1, METRIC_KMAX, sp);
}
void xombe__voicing_metric_sp(xombe_enc *e, const xombe_lf_spec *sp, float fhat, float m[8], float w[8])
{
float br[8], be[8], be0[8];
int kmax = METRIC_KMAX, j, s;
for (j = 0; j < 8; j++)
m[j] = 1e30f;
for (s = 0; s < JITTER_STEPS; s++) {
float eps = (float)(s - JITTER_STEPS / 2) * JITTER_STEP;
xombe__kern_line_fit(e, sp, 1.0f / (fhat * (1.0f + eps)), 1, kmax, br, be);
if (s == JITTER_STEPS / 2)
memcpy(be0, be, sizeof(be0));
for (j = 0; j < 8; j++) {
float mj = be[j] > 0.0f ? br[j] / be[j] : 1.0f;
if (mj < m[j])
m[j] = mj;
}
}
for (j = 0; j < 8; j++) {
float wj = be0[j] / (XOMBE_FFT * e->win_sum2);
w[j] = wj > WEIGHT_FLOOR ? wj : WEIGHT_FLOOR;
}
}
void xombe__voicing_metric(xombe_enc *e, const xombe_spec *S, float fhat, float m[8], float w[8])
{
xombe_lf_spec sp;
xombe__voicing_prepare(e, S, &sp);
xombe__voicing_metric_sp(e, &sp, fhat, m, w);
}
float xombe__voicing_map(float sm)
{
float soft = sm > 0.0f ? SOFT_OFFSET - 0.5f * log2f(sm) : 1.0f;
return soft < 0.0f ? 0.0f : soft > 1.0f ? 1.0f : soft;
}
void xombe__voicing_soft_sp(xombe_enc *e, const xombe_lf_spec *sp, float fhat, float scale, float a[8], float w[8])
{
float m[8];
int j;
xombe__voicing_metric_sp(e, sp, fhat, m, w);
for (j = 0; j < 8; j++)
a[j] = xombe__voicing_map(scale * m[j]);
}
void xombe__voicing_soft(xombe_enc *e, const xombe_spec *S, float fhat, float scale, float a[8], float w[8])
{
xombe_lf_spec sp;
xombe__voicing_prepare(e, S, &sp);
xombe__voicing_soft_sp(e, &sp, fhat, scale, a, w);
}
int xombe__choose_b1(const float a2[8], const float w2[8], const float a1[8], const float w1[8],
const uint8_t v2_prev[8])
{
float best = 0.0f;
int b1, j, choice = XOMBE_UNVOICED_B1;
for (b1 = 0; b1 <= B1_SEARCH_MAX; b1++) {
uint8_t v2[8], v1[8];
float c = 0.0f;
xombe__v2_from_b1(b1, v2);
xombe__f3_first_half(v2_prev, v2, v1);
for (j = 0; j < 8; j++) {
float d2 = v2[j] ? 1.0f - a2[j] : a2[j];
float d1 = v1[j] ? 1.0f - a1[j] : a1[j];
c += w2[j] * d2 * d2 + FIRST_HALF_WEIGHT * w1[j] * d1 * d1;
}
if (b1 == 0 || c < best) {
best = c;
choice = b1;
}
}
return choice;
}
+54
View File
@@ -0,0 +1,54 @@
#include "../internal.h"
#define GOLAY_POLY 0xC75u
static uint32_t golay_remainder(uint32_t v)
{
int bit;
for (bit = 22; bit >= 11; bit--)
if (v & (1u << bit))
v ^= GOLAY_POLY << (bit - 11);
return v;
}
uint32_t xombe__golay23_encode(uint32_t data12)
{
uint32_t shifted = (data12 & 0xFFFu) << 11;
return shifted | golay_remainder(shifted);
}
int xombe__golay23_decode(uint32_t received, uint32_t *codeword)
{
uint32_t syn = golay_remainder(received & 0x7FFFFFu), data_syn[12];
int i, j, k;
if (xombe__popcount32(syn) <= 3) {
*codeword = (received ^ syn) & 0x7FFFFFu;
return xombe__popcount32(syn);
}
for (i = 0; i < 12; i++)
data_syn[i] = golay_remainder(1u << (11 + i));
for (i = 0; i < 12; i++) {
uint32_t s = syn ^ data_syn[i];
if (xombe__popcount32(s) <= 2) {
*codeword = (received ^ (1u << (11 + i)) ^ s) & 0x7FFFFFu;
return 1 + xombe__popcount32(s);
}
}
for (i = 0; i < 12; i++)
for (j = i + 1; j < 12; j++) {
uint32_t s = syn ^ data_syn[i] ^ data_syn[j];
if (xombe__popcount32(s) <= 1) {
*codeword = (received ^ (1u << (11 + i)) ^ (1u << (11 + j)) ^ s) & 0x7FFFFFu;
return 2 + xombe__popcount32(s);
}
}
for (i = 0; i < 12; i++)
for (j = i + 1; j < 12; j++)
for (k = j + 1; k < 12; k++)
if ((syn ^ data_syn[i] ^ data_syn[j] ^ data_syn[k]) == 0) {
*codeword = (received ^ (1u << (11 + i)) ^ (1u << (11 + j)) ^ (1u << (11 + k))) & 0x7FFFFFu;
return 3;
}
*codeword = received & 0x7FFFFFu;
return 3;
}
+17
View File
@@ -0,0 +1,17 @@
#include "../internal.h"
void xombe__interleave(const uint8_t w[72], uint8_t air_bits[72])
{
int i, k;
for (i = 0; i < 18; i++)
for (k = 0; k < 4; k++)
air_bits[4 * i + k] = w[18 * k + i];
}
void xombe__deinterleave(const uint8_t air_bits[72], uint8_t w[72])
{
int i, k;
for (i = 0; i < 18; i++)
for (k = 0; k < 4; k++)
w[18 * k + i] = air_bits[4 * i + k];
}
+13
View File
@@ -0,0 +1,13 @@
#include "../internal.h"
uint32_t xombe__pn_mask(uint32_t d0_12)
{
uint16_t u = (uint16_t)(16u * (d0_12 & 0xFFFu));
uint32_t mask = 0;
int n;
for (n = 0; n < 23; n++) {
u = xombe__lcg_next(u);
mask = (mask << 1) | ((u >> 15) & 1u);
}
return mask;
}
+131
View File
@@ -0,0 +1,131 @@
#include "../internal.h"
#if XOMBE_HAVE_DSTAR
#include "../dstar/dstar_internal.h"
#endif
/* running error rate in Q24: eps_r <- 0.95*eps_r + 0.05*eps_t/47 = (893*eps_r + 2^24*eps_t)/940, rounded once
HB above 0.096, from ceil(0.096*2^24) */
#define EPS_R_ONE (1ull << 24)
#define EPS_R_HB_MIN 1610613u
static uint32_t take(const uint8_t *bits, int count)
{
return (uint32_t)xombe__get_bits(bits, 0, count);
}
static void put(uint8_t *bits, int count, uint32_t v)
{
xombe__put_bits(bits, 0, count, (int)v);
}
static int parity(uint32_t v)
{
return xombe__popcount32(v) & 1;
}
static void dmr_encode(const uint8_t bits[7], uint8_t air[9])
{
uint8_t d[49], w[72], a[72];
uint32_t data0, data1, c0, c1;
int i;
xombe__unpack49(bits, d);
data0 = take(d, 12);
data1 = take(d + 12, 12);
c0 = xombe__golay23_encode(data0);
c0 = (c0 << 1) | (uint32_t)parity(c0);
c1 = xombe__golay23_encode(data1) ^ xombe__pn_mask(data0);
put(w, 24, c0);
put(w + 24, 23, c1);
for (i = 0; i < 25; i++)
w[47 + i] = d[24 + i];
xombe__interleave(w, a);
xombe__pack_bits(a, 72, air);
}
void xombe__fec_encode_dmr(const uint8_t bits[7], uint8_t frame[9])
{
dmr_encode(bits, frame);
}
int xombe__fec_encode_dstar(const uint8_t bits[7], uint8_t frame[9])
{
#if XOMBE_HAVE_DSTAR
xombe__ds_fec_encode_bits(bits, frame);
return 0;
#else
(void)bits;
(void)frame;
return -1;
#endif
}
void xombe__fec_stats_update(xombe_fec *f, xombe_fec_stats *st)
{
st->eps_t = st->eps0 + st->eps1;
st->bf = st->eps0 >= 4 || (st->eps0 >= 2 && st->eps_t >= 6);
f->eps_r = (uint32_t)((893u * (uint64_t)f->eps_r + EPS_R_ONE * (uint64_t)st->eps_t + 470u) / 940u);
st->eps_r = f->eps_r;
st->hb = f->eps_r >= EPS_R_HB_MIN;
}
static unsigned dmr_decode(xombe_fec *f, const uint8_t air[9], uint8_t bits[7], xombe_fec_stats *st)
{
uint8_t a[72], w[72], d[49];
uint32_t c0, c1, cw0, cw1;
int i, w0, received_parity;
xombe__unpack_bits(air, 72, a);
xombe__deinterleave(a, w);
c0 = take(w, 24);
received_parity = (int)(c0 & 1u);
w0 = xombe__golay23_decode(c0 >> 1, &cw0);
if ((parity(cw0) ^ received_parity) == 0)
st->eps0 = w0;
else
st->eps0 = w0 <= 2 ? w0 + 1 : 4;
c1 = take(w + 24, 23) ^ xombe__pn_mask(cw0 >> 11);
st->eps1 = xombe__golay23_decode(c1, &cw1);
put(d, 12, cw0 >> 11);
put(d + 12, 12, cw1 >> 11);
for (i = 0; i < 25; i++)
d[24 + i] = w[47 + i];
xombe__pack49(d, bits);
xombe__fec_stats_update(f, st);
return (st->bf ? XOMBE_FLAG_BF : 0u) | (st->hb ? XOMBE_FLAG_HB : 0u);
}
static void reset(xombe_fec *f, int codec)
{
f->codec = codec;
f->eps_r = 0;
f->er = 0.0f;
}
int xombe__fec_init_dmr(xombe_fec *f)
{
reset(f, XOMBE_DMR);
return 0;
}
int xombe__fec_init_dstar(xombe_fec *f)
{
#if XOMBE_HAVE_DSTAR
reset(f, XOMBE_DSTAR);
return 0;
#else
(void)f;
return -1;
#endif
}
/* both codecs' decoders behind one call: the decoder's frame calls reach it, its *_bits calls do not */
unsigned xombe_fec_decode(xombe_fec *f, const uint8_t frame[9], uint8_t bits[7], xombe_fec_stats *st)
{
xombe_fec_stats local;
if (!st)
st = &local;
#if XOMBE_HAVE_DSTAR
if (f->codec == XOMBE_DSTAR)
return xombe__ds_fec_decode_bits(f, frame, bits, st);
#endif
return dmr_decode(f, frame, bits, st);
}
+201
View File
@@ -0,0 +1,201 @@
#ifndef XOMBE_INTERNAL_H
#define XOMBE_INTERNAL_H
#include <stdint.h>
#include "xombe.h"
#include "state.h"
#include "common/consts.h"
#include "common/bits.h"
#include "common/params.h"
#include "common/voicing.h"
#include "common/tone_table.h"
/* C99 has no _Static_assert, a negative array size fails the build */
#define XOMBE_STATIC_ASSERT(cond, name) typedef char xombe_static_assert_##name[(cond) ? 1 : -1]
/* largest xombe__irfft size, it keeps n/2 points of scratch on the stack */
#define XOMBE_IRFFT_MAX 256
/* n real samples in, n/2 + 1 bins out */
void xombe__rfft(const float *in, xombe_cpx *out, int n, const xombe_cpx *tw, int tw_n_real);
/* in place: io[k] holds samples 2k and 2k + 1 for k < n/2 on entry, bin k for k <= n/2 on return */
void xombe__rfft_packed(xombe_cpx *io, int n, const xombe_cpx *tw, int tw_n_real);
/* n <= XOMBE_IRFFT_MAX */
void xombe__irfft(const xombe_cpx *in, float *out, int n, const xombe_cpx *tw, int tw_n_real);
float xombe__sin_ratio(long r, long m);
void xombe__hamming(float *w, int n);
float xombe__hamming_sum2(int n);
float xombe__hamming_dtft(int n, long q, long g);
void xombe__hpf_init(xombe_hpf *f, float gain);
float xombe__hpf_step(xombe_hpf *f, float x);
uint16_t xombe__lcg_next(uint16_t u);
int16_t xombe__lcg_draw(uint16_t *u); /* next value as a signed 16-bit sample */
uint32_t xombe__golay23_encode(uint32_t data12);
/* corrects up to 3 errors in a 23-bit word, returns the count, *codeword gets the word (data in bits 22..11)
an uncorrectable word also returns 3 and comes back unchanged, the FEC statistics depend on that count */
int xombe__golay23_decode(uint32_t received, uint32_t *codeword);
uint32_t xombe__pn_mask(uint32_t d0_12);
void xombe__interleave(const uint8_t w[72], uint8_t air_bits[72]);
void xombe__deinterleave(const uint8_t air_bits[72], uint8_t w[72]);
/* DMR error rule and running error rate from st->eps0 and eps1 */
void xombe__fec_stats_update(xombe_fec *f, xombe_fec_stats *st);
/* installs a stage tap (state.h), fn NULL removes it */
void xombe__dec_set_tap(xombe_dec *d, xombe_tap_fn fn, void *ctx);
/* where the D-STAR decoder's rules differ from AMBE+2's in the shared decoder, set at reset */
struct xombe_dec_rules {
/* vh[0..XOMBE_LMAX] from the band voicing, 0 above L */
void (*harm_voicing)(const uint8_t vb[8], float f0, int L, uint8_t vh[XOMBE_LMAX + 1]);
float lambda_decay; /* smoothing level decay per frame */
};
/* a codec's frame logic, set by its init: start_bits begins a frame from voice bits (unread if lost) and the
error counts in err_t and err_1 */
struct xombe_dec_ops {
void (*start_bits)(xombe_dec *d, const uint8_t bits[7], unsigned flags);
};
void xombe__smooth(xombe_dec_core *d, float *a, int L, float f0);
void xombe__phases(const float *a, int L, float *phi);
/* e[1..L]: log2 amplitudes a[1..L] after spectral enhancement */
void xombe__enhance(const float *a, int L, float f0, float *e);
/* M[1..L] = 2^(e + spectral tilt): low harmonics rolled off below the average pitch, high ones boosted */
void xombe__shape(const float *e, float *M, int L, float f0, float avg_f0);
void xombe__tone_set(xombe_set *s, int id, int ad);
void xombe__synth_voiced(xombe_dec *d, const xombe_set *cur, const float *M, const uint8_t *vh, int cur_voiced,
int N, float *out);
void xombe__synth_unvoiced(xombe_dec *d, const xombe_set *cur, const float *M, const uint8_t *vh, int N,
float *out);
void xombe__noise_init(xombe_dec *d);
int xombe__conceal_decide(xombe_dec_core *d, int bad, int hb);
/* frame-independent decoder machinery, shared by the AMBE+2 parser (dec/decoder.c) and dstar/decoder.c
a parser either conceals (xombe__dec_conceal_sets: mute or last played set, first half flagged repeat) or plays
the frame's set (xombe__dec_play: picks the first-half set from the previous class, makes cur the second half,
stores voice parameters p and band flags v2 in the prediction memory, v1 is a voice frame's first-half
voicing), then xombe__dec_synth synthesizes each half. the frame logic takes the core, synthesis the whole
decoder */
void xombe__dec_core_reset(xombe_dec_core *d);
void xombe__dec_reset(xombe_dec *d);
void xombe__dec_silence_set(xombe_set *s); /* initial silence set: f0 250 Hz, L 14, every amplitude 0.1 */
void xombe__dec_set_from_params(xombe_set *s, int cls, float f0, int L, const float *a, const uint8_t *vb);
void xombe__dec_play(xombe_dec_core *d, const xombe_set *cur, const uint8_t v1[8], const xombe_params *p,
const uint8_t v2[8]);
void xombe__dec_conceal_sets(xombe_dec_core *d, int conceal);
/* half-call order check: -1 if second_half is not the half due, else advances it and returns n clamped to
XOMBE_HALF_MIN..XOMBE_HALF_MAX */
int xombe__dec_half_begin(xombe_dec *d, int second_half, int n);
void xombe__dec_synth(xombe_dec *d, int second_half, int N, int16_t *pcm);
/* AMBE+2 frame logic without synthesis: xombe__dec_start_frame classifies, conceals, or decodes 7 bytes (unread if
lost) into p1 and p2, then xombe__dec_skip_synth updates the mute and played sets as the two half-frame calls
would */
void xombe__dec_start_frame(xombe_dec_core *d, const uint8_t bytes[7], unsigned flags);
void xombe__dec_skip_synth(xombe_dec_core *d);
/* xombe__dec_start_frame of a DMR frame through fec, flags 0 or XOMBE_FLAG_LOST, bits gets the decoded voice
bits (zeros if lost) */
void xombe__dec_start_air(xombe_dec_core *d, xombe_fec *fec, const uint8_t air[9], unsigned flags, uint8_t bits[7]);
#if XOMBE_HAVE_ENCODER
/* VAD threshold, metric in log2 power units
confident noise half: metric below XOMBE_CONFIDENT, noise suppression and comfort noise
adapt from the XOMBE_CONFIDENT_RUN-th in a row */
#define XOMBE_VAD_THRESHOLD XOMBE_DB(4.0f)
#define XOMBE_CONFIDENT XOMBE_DB(2.0f)
#define XOMBE_CONFIDENT_RUN 4
void xombe__enc_set_tap(xombe_enc *e, xombe_tap_fn fn, void *ctx);
void xombe__enc_set_window(xombe_enc *e, int n);
void xombe__enc_integrate(const float *P, int L, float f0, float *a);
void xombe__enc_hf_precomp(float *a, int L, float f0);
void xombe__pitch_init(xombe_enc *e);
void xombe__pitch_errors(xombe_enc *e, const float *centre, int slot);
float xombe__pitch_track(xombe_enc *e, int cur, int next1, int next2);
float xombe__pitch_refine(xombe_enc *e, const xombe_spec *S, float period);
int xombe__pitch_window_len(float period);
/* voicing metric per 500 Hz band (residual over energy of the harmonic line fit, min over +/-2% pitch jitter)
and band weights, soft value of a scaled metric sm = clip(-0.661 - log2(sm)/2, 0, 1), and both for one scale */
void xombe__voicing_metric(xombe_enc *e, const xombe_spec *S, float fhat, float m[8], float w[8]);
float xombe__voicing_map(float sm);
void xombe__voicing_soft(xombe_enc *e, const xombe_spec *S, float fhat, float scale, float a[8], float w[8]);
int xombe__choose_b1(const float a2[8], const float w2[8], const float a1[8], const float w1[8],
const uint8_t v2_prev[8]);
int xombe__vad_flat(const int16_t *x, int n);
void xombe__vad_half(xombe_enc *e, const float *P, int flat, int *speech, float *v);
void xombe__ns_bins(const float *P, float Xm[XOMBE_NS_BINS]);
float xombe__ns_shape(float f);
/* noise suppression per half-frame (enc/frontend.h phase C)
xombe__ns_update: shared noise estimate (from the confident_run-th confident noise half, or slowly in halves
with no band voiced) and suppression floor (up in speech, down otherwise)
xombe__ns_gain: one back end's gains G from that estimate, its own smoothing memory m, and vbin, the voicing it
codes at each bin's centre
xombe__ns_bin_voicing: vbin from 500 Hz band flags, ambe2_rule voices a bin if its band or the band 250 Hz
above is (xombe__voiced_at), else the band alone */
void xombe__ns_update(xombe_enc *e, const float Xm[XOMBE_NS_BINS], int speech, int confident_run,
int no_band_voiced);
void xombe__ns_bin_voicing(const uint8_t vb[8], int ambe2_rule, uint8_t vbin[XOMBE_NS_BINS]);
void xombe__ns_gain(const xombe_enc *e, xombe_ns_mem *m, const float Xm[XOMBE_NS_BINS], int speech, float v,
const uint8_t vbin[XOMBE_NS_BINS], float G[XOMBE_NS_BINS]);
/* log2 gain offsets da[1..L] of the harmonics of f0 from gains G, voicing vh[1..L] (voiced harmonics below
800 Hz take part of the suppression), xombe__ns_apply_voice adds them to a[1..L] with AMBE+2 band voicing v2,
floored at XOMBE_AMP_MIN */
void xombe__ns_harmonic_offsets(const float G[XOMBE_NS_BINS], int L, float f0, const uint8_t *vh, float *da);
void xombe__ns_apply_voice(const float G[XOMBE_NS_BINS], float *a, int L, float f0, const uint8_t v2[8]);
void xombe__ns_apply_silence(const xombe_enc *e, float *a, int L, float f0);
void xombe__cn_half(xombe_enc *e, const float *P, int noise, int confident_run);
void xombe__cn_targets(const xombe_enc *e, float *a);
/* AMBE+2 tone detector on XOMBE_TONE_SEG samples from seg, gives tone ID and level code
(xombe__tone_search with singles, the 36 dual tones, emin 0.99, coarse peak) */
int xombe__tone_detect(xombe_enc *e, const int16_t *seg, int *id, int *ad);
/* least-squares tone detector over a segment length and tone set, the level at each component's own frequency */
typedef struct {
short id;
float hz[2]; /* in the fit's order */
} xombe_tone_pair;
typedef struct {
int len; /* segment length, at most XOMBE_TONE_SEG */
const float *win; /* its Hann window */
float emin; /* explained-fraction threshold */
int singles; /* single tones (IDs 5..122) are candidates */
int fine_peak; /* single-tone peak on an 8192-point grid refined in the fit (ternary search, +/-0.4 bin),
else the parabola on the XOMBE_TONE_FFT grid */
const xombe_tone_pair *pairs;
int npairs;
} xombe_tone_search;
typedef struct {
int id; /* -1: none */
float e; /* fit's explained fraction */
float level; /* dB re full scale less the decoder filter's gain, AD = 127 + level/0.711 */
float res; /* fit's residual energy */
} xombe_tone_hit;
#if XOMBE_KERNELS_Q15
typedef uint32_t xombe_tone_pow; /* bin power in a per-segment unit, only ratios within a segment mean anything */
#else
typedef float xombe_tone_pow;
#endif
/* segment as the search reads it: x less its mean, pw bin powers of x under the window, zero-padded */
typedef struct {
float x[XOMBE_TONE_SEG];
xombe_tone_pow pw[XOMBE_TONE_FFT / 2 + 1];
float energy; /* of x, 0 below the detector's floor */
} xombe_tone_seg;
/* sg for ts->len samples from seg under ts->win, which any search on sg must share */
void xombe__tone_prepare(xombe_enc *e, const int16_t *seg, const xombe_tone_search *ts, xombe_tone_seg *sg);
int xombe__tone_search(const xombe_tone_seg *sg, const xombe_tone_search *ts, xombe_tone_hit *hit);
/* decoder output filter's gain at hz, dB */
float xombe__tone_hpf_gain_db(float hz);
int xombe__tone_decide(xombe_enc *e, int detected, int det_id, int det_ad, int *id, int *ad);
void xombe__quantize(const xombe_pred *pi, int silence, int L, const float *target, int b[9]);
#endif
#endif
+236
View File
@@ -0,0 +1,236 @@
#ifndef XOMBE_STATE_H
#define XOMBE_STATE_H
/* decoder and encoder state behind the opaque handles of xombe.h */
#include <stdint.h>
#include "xombe.h"
#define XOMBE_LMAX 56
#define XOMBE_TAIL 84
#define XOMBE_WT_SIZE 256 /* voiced wavetable length, a power of 2 */
typedef struct {
float re, im;
} xombe_cpx;
/* per-stage taps for tests (test/trace_dump.c), each passes n values and their f0 */
enum xombe_stage {
XOMBE_STAGE_DEQUANT, /* a[1..L] after dequantization */
XOMBE_STAGE_SMOOTH, /* a[1..L] after smoothing */
XOMBE_STAGE_SET, /* a[1..L] of the set a half-frame plays (silence and voice sets) */
XOMBE_STAGE_ENHANCED, /* linear M[1..L] after enhancement (silence sets: 2^a) */
XOMBE_STAGE_PHASE, /* phi[1..L] (voice sets) */
XOMBE_STAGE_SHAPED, /* M[1..L] as synthesized, after the tilt (tone sets: tone amplitudes) */
XOMBE_STAGE_SYNTH, /* a half-frame's N samples before the output high-pass */
XOMBE_STAGE_TARGET, /* encoder amplitude targets a[1..L] as quantized */
XOMBE_STAGE_VAD, /* encoder VAD per half: decision (1 = speech) and metric v in log2 units, f0 = 0 */
XOMBE_STAGE_COUNT
};
typedef void (*xombe_tap_fn)(void *ctx, enum xombe_stage stage, float f0, const float *v, int n);
#define XOMBE_TAP(o, stage, f0, v, n) \
do { \
if ((o)->tap) \
(o)->tap((o)->tap_ctx, (stage), (f0), (v), (n)); \
} while (0)
typedef struct {
int cls;
int L;
float f0;
float gamma;
float a[XOMBE_LMAX + 1];
uint8_t v2[8];
} xombe_pred;
typedef struct {
int cls;
int repeat;
int prepared;
int L;
float f0;
float a[XOMBE_LMAX + 1];
float e[XOMBE_LMAX + 1]; /* log2 amplitudes before the tilt: enhanced a (voice), a (silence), or tone
harmonics (tone, XOMBE_AMP_OFF elsewhere) */
float phi[XOMBE_LMAX + 1];
uint8_t vb[8];
} xombe_set;
typedef struct {
float x1, s1, s2, y1, y2;
float gain;
} xombe_hpf;
struct xombe_dec_rules;
struct xombe_dec_ops;
/* frame logic up to the sets a frame plays, all the transcoders keep of a decoder */
typedef struct {
const struct xombe_dec_rules *rules; /* AMBE+2's, or D-STAR's (xombe__dsd_logic_init) */
xombe_pred pi;
float lambda;
float avg_f0; /* synthesis reads and updates it, here it fills the core's padding */
int eps_t, eps_1;
int prev_concealed;
unsigned hist;
int run;
int64_t frame;
int64_t mute_src;
xombe_decision decision;
xombe_set p1, p2, played, mute;
xombe_tap_fn tap;
void *tap_ctx;
} xombe_dec_core;
#if XOMBE_HAVE_DSTAR
/* D-STAR frame logic state besides the core (dstar/decoder.c) */
typedef struct {
int log; /* XOMBE_DSD_LOG_* of the last frame */
int eT, e1; /* error rule smoothing inputs for the last frame */
} xombe_dsd_logic;
#endif
struct xombe_dec {
xombe_dec_core c;
const struct xombe_dec_ops *ops; /* the codec's frame logic */
int second_half_next; /* 1 between the two half calls of a frame */
int err_t, err_1; /* error counts of the next *_bits frame, xombe_dec_set_errors or the FEC */
float tail[XOMBE_TAIL];
float pitch_phase, epoch;
float wprev[XOMBE_WT_SIZE];
float prev_f0;
int prev_voiced;
float uv_overlap[XOMBE_TAIL];
int16_t noise_hist[XOMBE_TAIL];
uint16_t lcg;
uint32_t prng;
int noise_mode;
xombe_hpf hpf;
xombe_fec fec; /* for the frame calls */
#if XOMBE_HAVE_DSTAR
xombe_dsd_logic ds;
#endif
};
#if XOMBE_HAVE_ENCODER
#define XOMBE_FRAME 160
#define XOMBE_ENC_BUF 1024 /* input history in samples, newest last */
/* frames of look-ahead beyond XOMBE_ENC_DELAY for the D-STAR tone rules (dstar/dstar_enc.h), with the D-STAR
output on the encoder codes a frame this many frames older */
#if XOMBE_HAVE_DSTAR
#define XOMBE_ENC_LOOKAHEAD 1
#else
#define XOMBE_ENC_LOOKAHEAD 0
#endif
/* unfiltered history from the frame being encoded through the newest */
#define XOMBE_ENC_RAW ((XOMBE_ENC_DELAY + 1 + XOMBE_ENC_LOOKAHEAD) * XOMBE_FRAME)
/* unfiltered samples kept before that frame: the VAD's digital-silence test reads 59, D-STAR's tone-in-noise
window 80 */
#if XOMBE_HAVE_DSTAR
#define XOMBE_ENC_RAW_LEAD 80
#else
#define XOMBE_ENC_RAW_LEAD 64
#endif
#define XOMBE_FFT 1024
#define XOMBE_SPEC_BINS (XOMBE_FFT / 2 + 1)
#define XOMBE_TONE_FFT 512 /* uses the analysis FFT's twiddles */
#define XOMBE_TONE_IDS 164
#define XOMBE_TONE_SEG 240
/* analysis window widens to XOMBE_MAX_WINDOW for long periods, its transform tabulated to XOMBE_WTAB_BINS bins:
fits read at most half a harmonic spacing away, the widest about 52.2 bins (xombe__w0[0] with +2% jitter) */
#define XOMBE_BASE_WINDOW 199
#define XOMBE_MAX_WINDOW 321
#define XOMBE_WTAB_OVERSAMPLE 16
#define XOMBE_WTAB_BINS 27
#define XOMBE_WTAB_LEN (XOMBE_WTAB_BINS * XOMBE_WTAB_OVERSAMPLE + 1)
/* pitch grid: 21, 21.5, ..., 123 samples */
#define XOMBE_PITCH_LPF_HALF 10
#define XOMBE_PITCH_HALF 150
#define XOMBE_PITCH_WIN (2 * XOMBE_PITCH_HALF + 1)
#define XOMBE_PITCH_GRID 205
#define XOMBE_VAD_HIST 300 /* half-frames of band levels for the stationarity rule */
#define XOMBE_NS_BINS 40
#include "enc/kern_state.h"
#if XOMBE_HAVE_DSTAR
/* D-STAR back end state bytes (dstar/dstar_enc.h checks its struct fits): XOMBE_ENC_DSTAR_SIZE less what the
front end's longer input history (XOMBE_ENC_LOOKAHEAD) takes, so growing one grows the other */
#define XOMBE_ENC_LOOKAHEAD_STATE 512
#define XOMBE_DS_ENC_STATE (XOMBE_ENC_DSTAR_SIZE - XOMBE_ENC_LOOKAHEAD_STATE)
#endif
/* a back end's noise-suppression gain smoothing (xombe__ns_gain): last half's gains before the floor */
typedef struct {
float prev_gain[XOMBE_NS_BINS];
int have_prev;
} xombe_ns_mem;
struct xombe_enc {
xombe_enc_cfg cfg;
float ns_strength, voicing_scale; /* cfg's, as fractions */
int calls; /* counted up to the delay */
int lookahead; /* XOMBE_ENC_LOOKAHEAD with the D-STAR output, else 0 */
int pitch_slot; /* perr/pacf slot the next pitch analysis writes */
int16_t raw[XOMBE_ENC_RAW_LEAD + XOMBE_ENC_RAW];
float xh[XOMBE_ENC_BUF];
xombe_hpf hpf;
float perr[XOMBE_ENC_DELAY][XOMBE_PITCH_GRID];
/* pitch autocorrelation per slot, float lags or int16 lags (padded by one) scaled by pacf_scale */
union {
float f[XOMBE_PITCH_WIN];
int16_t q[XOMBE_PITCH_WIN + 1];
} pacf[XOMBE_ENC_DELAY];
float pacf_scale[XOMBE_ENC_DELAY];
float pe0[XOMBE_ENC_DELAY];
int psilent[XOMBE_ENC_DELAY];
float p_prev, e_prev1, e_prev2;
float period[XOMBE_ENC_LOOKAHEAD + 1]; /* tracked periods, newest first, the frame encoded takes [lookahead] */
float base_win_sum2;
float win[XOMBE_MAX_WINDOW];
int win_len;
float win_sum2;
float wtab[XOMBE_WTAB_LEN];
float vad_nl[8], vad_smooth[8];
int16_t vad_hist[XOMBE_VAD_HIST][8]; /* log2 of the smoothed band powers, Q10 (vad.c) */
int16_t vad_hist_fl[XOMBE_VAD_HIST]; /* log2 of each half's floor, Q10 */
int64_t vad_hist_sum[8]; /* history's band powers, dequantized to Q20 and summed */
int16_t vad_above[8]; /* halves in a row with band SNR > 0 dB, up to XOMBE_VAD_HIST */
int vad_hist_n, vad_hist_pos, vad_ready, hangover;
int confident_run;
float ns_noise[XOMBE_NS_BINS], ns_floor; /* shared background estimate (xombe__ns_update) */
int ns_ready;
xombe_ns_mem ns_mem; /* AMBE+2 back end's gain smoothing */
float cn_power[XOMBE_SPEC_BINS];
int cn_ready, cn_updates;
xombe_cpx tone_spec[XOMBE_TONE_FFT / 2 + 1]; /* scratch, not carried between frames */
int tone_prev_id, tone_confirmed, tone_hold_used, tone_last_id, tone_last_ad;
uint8_t tone_req[XOMBE_ENC_DELAY + XOMBE_ENC_LOOKAHEAD + 1][2]; /* forced tone ID (0: none) and AD of each
input frame in the delay, newest first */
xombe_pred pi; /* AMBE+2 back end's prediction memory */
xombe_tap_fn tap;
void *tap_ctx;
XOMBE_KERN_STATE
#if !XOMBE_HAVE_DSTAR
/* AMBE+2 closed-loop quantizer workspace, opaque here (enc/ambe2_enc.c: A2_CQ_WS(e)) */
union {
int64_t align_i;
void *align_p;
float align_f;
unsigned char bytes[XOMBE_ENC_CQ_SIZE];
} cq;
#endif
#if XOMBE_HAVE_DSTAR
/* D-STAR back end state, opaque here (dstar/dstar_enc.h: XOMBE_DS_ENC(e)) */
union {
int64_t align_i;
void *align_p;
float align_f;
unsigned char bytes[XOMBE_DS_ENC_STATE];
} ds;
#endif
};
#endif
#endif
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
#ifndef XOMBE_CQ_Q15_TABLES_H
#define XOMBE_CQ_Q15_TABLES_H
/* int16 images of one set's PRBA codebooks for the q15 closed-loop quantizer's bounds (cquant.c), generated by
scripts/gen_cq_tables.py. entries are rounded to nearest, so each is within 1/2 unit of its exact value
r24 row i, pairs: (x0^2, x1^2), (x2^2, 2 x0 x1), (2 x0 x2, 2 x1 x2) at 2^-tm24, then (x0, x1), (x2, 0) at 2^-tx24
r58 row j, pairs: (x0^2, x1^2), (x2^2, x3^2), (2 x0 x1, 2 x0 x2), (2 x0 x3, 2 x1 x2), (2 x1 x3, 2 x2 x3) at 2^-tm58,
then (x0, x1), (x2, x3) at 2^-tx58, and a zero pair */
#include <stdint.h>
#include "../internal.h"
typedef struct {
const uint32_t (*r24)[5];
const uint32_t (*r58)[8];
int tm24, tx24, tm58, tx58;
float m24[6], x24[3]; /* max |entry| of each column over all rows, real units */
float m58[10], x58[4];
float n3, n4; /* max |x|^2 over the usable rows, rounded up */
int cnt; /* usable prba58 rows: count, sums, and sums of products */
float sx[4], sxx[4][4];
} xombe_cq_q15_tab;
extern const xombe_cq_q15_tab xombe__cq_q15_ambe2;
extern const xombe_cq_q15_tab xombe__cq_q15_dstar;
#endif
+664
View File
@@ -0,0 +1,664 @@
/* generated by scripts/gen_dsp_tables.py, do not edit */
#include "dsp_tables.h"
const float xombe__dct8[8][8] = {
{1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f},
{0.980785251f, 0.831469595f, 0.555570245f, 0.195090324f, -0.195090324f, -0.555570245f, -0.831469595f, -0.980785251f},
{0.923879504f, 0.382683426f, -0.382683426f, -0.923879504f, -0.923879504f, -0.382683426f, 0.382683426f, 0.923879504f},
{0.831469595f, -0.195090324f, -0.980785251f, -0.555570245f, 0.555570245f, 0.980785251f, 0.195090324f, -0.831469595f},
{0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f, 0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f},
{0.555570245f, -0.980785251f, 0.195090324f, 0.831469595f, -0.831469595f, -0.195090324f, 0.980785251f, -0.555570245f},
{0.382683426f, -0.923879504f, 0.923879504f, -0.382683426f, -0.382683426f, 0.923879504f, -0.923879504f, 0.382683426f},
{0.195090324f, -0.555570245f, 0.831469595f, -0.980785251f, 0.980785251f, -0.831469595f, 0.555570245f, -0.195090324f},
};
const unsigned short xombe__dct_blk_off[XOMBE_DCT_BLK_J_MAX + 1] = {
0, 0, 6, 18, 36, 60, 90, 126, 168, 216, 270, 330,
396, 468, 546, 630, 720, 816,
};
const float xombe__dct_blk[XOMBE_DCT_BLK_SIZE] = {
1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 0.707106769f, -0.707106769f, 0.0f, 0.0f,
-0.707106769f, 0.707106769f, -1.0f, -1.0f, -0.707106769f, 0.707106769f,
1.0f, 1.0f, 1.0f, 0.866025388f, 0.0f, -0.866025388f,
0.5f, -1.0f, 0.5f, 0.0f, 0.0f, 0.0f,
-0.5f, 1.0f, -0.5f, -0.866025388f, 0.0f, 0.866025388f,
1.0f, 1.0f, 1.0f, 1.0f, 0.923879504f, 0.382683426f,
-0.382683426f, -0.923879504f, 0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f,
0.382683426f, -0.923879504f, 0.923879504f, -0.382683426f, 0.0f, 0.0f,
0.0f, 0.0f, -0.382683426f, 0.923879504f, -0.923879504f, 0.382683426f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.95105654f,
0.587785244f, 0.0f, -0.587785244f, -0.95105654f, 0.809017003f, -0.309017003f,
-1.0f, -0.309017003f, 0.809017003f, 0.587785244f, -0.95105654f, 0.0f,
0.95105654f, -0.587785244f, 0.309017003f, -0.809017003f, 1.0f, -0.809017003f,
0.309017003f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
0.965925813f, 0.707106769f, 0.258819044f, -0.258819044f, -0.707106769f, -0.965925813f,
0.866025388f, 0.0f, -0.866025388f, -0.866025388f, 0.0f, 0.866025388f,
0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f, 0.707106769f, -0.707106769f,
0.5f, -1.0f, 0.5f, 0.5f, -1.0f, 0.5f,
0.258819044f, -0.707106769f, 0.965925813f, -0.965925813f, 0.707106769f, -0.258819044f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 0.974927902f, 0.781831503f, 0.433883727f, 0.0f, -0.433883727f,
-0.781831503f, -0.974927902f, 0.90096885f, 0.222520933f, -0.623489797f, -1.0f,
-0.623489797f, 0.222520933f, 0.90096885f, 0.781831503f, -0.433883727f, -0.974927902f,
0.0f, 0.974927902f, 0.433883727f, -0.781831503f, 0.623489797f, -0.90096885f,
-0.222520933f, 1.0f, -0.222520933f, -0.90096885f, 0.623489797f, 0.433883727f,
-0.974927902f, 0.781831503f, 0.0f, -0.781831503f, 0.974927902f, -0.433883727f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 0.980785251f, 0.831469595f, 0.555570245f, 0.195090324f,
-0.195090324f, -0.555570245f, -0.831469595f, -0.980785251f, 0.923879504f, 0.382683426f,
-0.382683426f, -0.923879504f, -0.923879504f, -0.382683426f, 0.382683426f, 0.923879504f,
0.831469595f, -0.195090324f, -0.980785251f, -0.555570245f, 0.555570245f, 0.980785251f,
0.195090324f, -0.831469595f, 0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f,
0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f, 0.555570245f, -0.980785251f,
0.195090324f, 0.831469595f, -0.831469595f, -0.195090324f, 0.980785251f, -0.555570245f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 0.98480773f, 0.866025388f, 0.642787635f,
0.342020154f, 0.0f, -0.342020154f, -0.642787635f, -0.866025388f, -0.98480773f,
0.939692616f, 0.5f, -0.173648179f, -0.766044438f, -1.0f, -0.766044438f,
-0.173648179f, 0.5f, 0.939692616f, 0.866025388f, 0.0f, -0.866025388f,
-0.866025388f, 0.0f, 0.866025388f, 0.866025388f, 0.0f, -0.866025388f,
0.766044438f, -0.5f, -0.939692616f, 0.173648179f, 1.0f, 0.173648179f,
-0.939692616f, -0.5f, 0.766044438f, 0.642787635f, -0.866025388f, -0.342020154f,
0.98480773f, 0.0f, -0.98480773f, 0.342020154f, 0.866025388f, -0.642787635f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.987688363f, 0.891006529f,
0.707106769f, 0.453990489f, 0.156434461f, -0.156434461f, -0.453990489f, -0.707106769f,
-0.891006529f, -0.987688363f, 0.95105654f, 0.587785244f, 0.0f, -0.587785244f,
-0.95105654f, -0.95105654f, -0.587785244f, 0.0f, 0.587785244f, 0.95105654f,
0.891006529f, 0.156434461f, -0.707106769f, -0.987688363f, -0.453990489f, 0.453990489f,
0.987688363f, 0.707106769f, -0.156434461f, -0.891006529f, 0.809017003f, -0.309017003f,
-1.0f, -0.309017003f, 0.809017003f, 0.809017003f, -0.309017003f, -1.0f,
-0.309017003f, 0.809017003f, 0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f,
0.707106769f, -0.707106769f, -0.707106769f, 0.707106769f, 0.707106769f, -0.707106769f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.989821434f,
0.909631968f, 0.755749583f, 0.540640831f, 0.281732559f, 0.0f, -0.281732559f,
-0.540640831f, -0.755749583f, -0.909631968f, -0.989821434f, 0.959492981f, 0.654860735f,
0.142314836f, -0.415415019f, -0.841253519f, -1.0f, -0.841253519f, -0.415415019f,
0.142314836f, 0.654860735f, 0.959492981f, 0.909631968f, 0.281732559f, -0.540640831f,
-0.989821434f, -0.755749583f, 0.0f, 0.755749583f, 0.989821434f, 0.540640831f,
-0.281732559f, -0.909631968f, 0.841253519f, -0.142314836f, -0.959492981f, -0.654860735f,
0.415415019f, 1.0f, 0.415415019f, -0.654860735f, -0.959492981f, -0.142314836f,
0.841253519f, 0.755749583f, -0.540640831f, -0.909631968f, 0.281732559f, 0.989821434f,
0.0f, -0.989821434f, -0.281732559f, 0.909631968f, 0.540640831f, -0.755749583f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
0.991444886f, 0.923879504f, 0.793353319f, 0.60876143f, 0.382683426f, 0.130526185f,
-0.130526185f, -0.382683426f, -0.60876143f, -0.793353319f, -0.923879504f, -0.991444886f,
0.965925813f, 0.707106769f, 0.258819044f, -0.258819044f, -0.707106769f, -0.965925813f,
-0.965925813f, -0.707106769f, -0.258819044f, 0.258819044f, 0.707106769f, 0.965925813f,
0.923879504f, 0.382683426f, -0.382683426f, -0.923879504f, -0.923879504f, -0.382683426f,
0.382683426f, 0.923879504f, 0.923879504f, 0.382683426f, -0.382683426f, -0.923879504f,
0.866025388f, 0.0f, -0.866025388f, -0.866025388f, 0.0f, 0.866025388f,
0.866025388f, 0.0f, -0.866025388f, -0.866025388f, 0.0f, 0.866025388f,
0.793353319f, -0.382683426f, -0.991444886f, -0.130526185f, 0.923879504f, 0.60876143f,
-0.60876143f, -0.923879504f, 0.130526185f, 0.991444886f, 0.382683426f, -0.793353319f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 0.992708862f, 0.935016215f, 0.822983861f, 0.663122654f, 0.46472317f,
0.239315659f, 0.0f, -0.239315659f, -0.46472317f, -0.663122654f, -0.822983861f,
-0.935016215f, -0.992708862f, 0.970941842f, 0.748510778f, 0.3546049f, -0.120536678f,
-0.568064749f, -0.885456026f, -1.0f, -0.885456026f, -0.568064749f, -0.120536678f,
0.3546049f, 0.748510778f, 0.970941842f, 0.935016215f, 0.46472317f, -0.239315659f,
-0.822983861f, -0.992708862f, -0.663122654f, 0.0f, 0.663122654f, 0.992708862f,
0.822983861f, 0.239315659f, -0.46472317f, -0.935016215f, 0.885456026f, 0.120536678f,
-0.748510778f, -0.970941842f, -0.3546049f, 0.568064749f, 1.0f, 0.568064749f,
-0.3546049f, -0.970941842f, -0.748510778f, 0.120536678f, 0.885456026f, 0.822983861f,
-0.239315659f, -0.992708862f, -0.46472317f, 0.663122654f, 0.935016215f, 0.0f,
-0.935016215f, -0.663122654f, 0.46472317f, 0.992708862f, 0.239315659f, -0.822983861f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 0.993712187f, 0.943883359f, 0.846724212f, 0.707106769f,
0.532032073f, 0.330279052f, 0.111964479f, -0.111964479f, -0.330279052f, -0.532032073f,
-0.707106769f, -0.846724212f, -0.943883359f, -0.993712187f, 0.974927902f, 0.781831503f,
0.433883727f, 0.0f, -0.433883727f, -0.781831503f, -0.974927902f, -0.974927902f,
-0.781831503f, -0.433883727f, 0.0f, 0.433883727f, 0.781831503f, 0.974927902f,
0.943883359f, 0.532032073f, -0.111964479f, -0.707106769f, -0.993712187f, -0.846724212f,
-0.330279052f, 0.330279052f, 0.846724212f, 0.993712187f, 0.707106769f, 0.111964479f,
-0.532032073f, -0.943883359f, 0.90096885f, 0.222520933f, -0.623489797f, -1.0f,
-0.623489797f, 0.222520933f, 0.90096885f, 0.90096885f, 0.222520933f, -0.623489797f,
-1.0f, -0.623489797f, 0.222520933f, 0.90096885f, 0.846724212f, -0.111964479f,
-0.943883359f, -0.707106769f, 0.330279052f, 0.993712187f, 0.532032073f, -0.532032073f,
-0.993712187f, -0.330279052f, 0.707106769f, 0.943883359f, 0.111964479f, -0.846724212f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 0.994521916f, 0.95105654f, 0.866025388f,
0.74314481f, 0.587785244f, 0.406736642f, 0.207911685f, 0.0f, -0.207911685f,
-0.406736642f, -0.587785244f, -0.74314481f, -0.866025388f, -0.95105654f, -0.994521916f,
0.978147626f, 0.809017003f, 0.5f, 0.104528464f, -0.309017003f, -0.669130623f,
-0.91354543f, -1.0f, -0.91354543f, -0.669130623f, -0.309017003f, 0.104528464f,
0.5f, 0.809017003f, 0.978147626f, 0.95105654f, 0.587785244f, 0.0f,
-0.587785244f, -0.95105654f, -0.95105654f, -0.587785244f, 0.0f, 0.587785244f,
0.95105654f, 0.95105654f, 0.587785244f, 0.0f, -0.587785244f, -0.95105654f,
0.91354543f, 0.309017003f, -0.5f, -0.978147626f, -0.809017003f, -0.104528464f,
0.669130623f, 1.0f, 0.669130623f, -0.104528464f, -0.809017003f, -0.978147626f,
-0.5f, 0.309017003f, 0.91354543f, 0.866025388f, 0.0f, -0.866025388f,
-0.866025388f, 0.0f, 0.866025388f, 0.866025388f, 0.0f, -0.866025388f,
-0.866025388f, 0.0f, 0.866025388f, 0.866025388f, 0.0f, -0.866025388f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.99518472f, 0.956940353f,
0.881921291f, 0.773010433f, 0.634393275f, 0.471396744f, 0.290284663f, 0.0980171412f,
-0.0980171412f, -0.290284663f, -0.471396744f, -0.634393275f, -0.773010433f, -0.881921291f,
-0.956940353f, -0.99518472f, 0.980785251f, 0.831469595f, 0.555570245f, 0.195090324f,
-0.195090324f, -0.555570245f, -0.831469595f, -0.980785251f, -0.980785251f, -0.831469595f,
-0.555570245f, -0.195090324f, 0.195090324f, 0.555570245f, 0.831469595f, 0.980785251f,
0.956940353f, 0.634393275f, 0.0980171412f, -0.471396744f, -0.881921291f, -0.99518472f,
-0.773010433f, -0.290284663f, 0.290284663f, 0.773010433f, 0.99518472f, 0.881921291f,
0.471396744f, -0.0980171412f, -0.634393275f, -0.956940353f, 0.923879504f, 0.382683426f,
-0.382683426f, -0.923879504f, -0.923879504f, -0.382683426f, 0.382683426f, 0.923879504f,
0.923879504f, 0.382683426f, -0.382683426f, -0.923879504f, -0.923879504f, -0.382683426f,
0.382683426f, 0.923879504f, 0.881921291f, 0.0980171412f, -0.773010433f, -0.956940353f,
-0.290284663f, 0.634393275f, 0.99518472f, 0.471396744f, -0.471396744f, -0.99518472f,
-0.634393275f, 0.290284663f, 0.956940353f, 0.773010433f, -0.0980171412f, -0.881921291f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.995734155f,
0.961825669f, 0.895163298f, 0.798017204f, 0.673695624f, 0.526432157f, 0.361241668f,
0.183749512f, 0.0f, -0.183749512f, -0.361241668f, -0.526432157f, -0.673695624f,
-0.798017204f, -0.895163298f, -0.961825669f, -0.995734155f, 0.982973099f, 0.850217164f,
0.602634609f, 0.273662984f, -0.0922683626f, -0.445738345f, -0.739008904f, -0.932472229f,
-1.0f, -0.932472229f, -0.739008904f, -0.445738345f, -0.0922683626f, 0.273662984f,
0.602634609f, 0.850217164f, 0.982973099f, 0.961825669f, 0.673695624f, 0.183749512f,
-0.361241668f, -0.798017204f, -0.995734155f, -0.895163298f, -0.526432157f, 0.0f,
0.526432157f, 0.895163298f, 0.995734155f, 0.798017204f, 0.361241668f, -0.183749512f,
-0.673695624f, -0.961825669f, 0.932472229f, 0.445738345f, -0.273662984f, -0.850217164f,
-0.982973099f, -0.602634609f, 0.0922683626f, 0.739008904f, 1.0f, 0.739008904f,
0.0922683626f, -0.602634609f, -0.982973099f, -0.850217164f, -0.273662984f, 0.445738345f,
0.932472229f, 0.895163298f, 0.183749512f, -0.673695624f, -0.995734155f, -0.526432157f,
0.361241668f, 0.961825669f, 0.798017204f, 0.0f, -0.798017204f, -0.961825669f,
-0.361241668f, 0.526432157f, 0.995734155f, 0.673695624f, -0.183749512f, -0.895163298f,
};
const float xombe__ramp_cos[XOMBE_GRAIN_RAMP] = {
1.0f, 0.980785251f, 0.923879504f, 0.831469595f, 0.707106769f, 0.555570245f,
0.382683426f, 0.195090324f, 0.0f, -0.195090324f, -0.382683426f, -0.555570245f,
-0.707106769f, -0.831469595f, -0.923879504f, -0.980785251f,
};
const float xombe__ramp_sin[XOMBE_GRAIN_RAMP] = {
0.0f, 0.195090324f, 0.382683426f, 0.555570245f, 0.707106769f, 0.831469595f,
0.923879504f, 0.980785251f, 1.0f, 0.980785251f, 0.923879504f, 0.831469595f,
0.707106769f, 0.555570245f, 0.382683426f, 0.195090324f,
};
const float xombe__sqrt_n[XOMBE_HALF_MAX + 1] = {
0.0f, 1.0f, 1.41421354f, 1.73205078f, 2.0f, 2.23606801f,
2.44948983f, 2.64575124f, 2.82842708f, 3.0f, 3.1622777f, 3.31662488f,
3.46410155f, 3.60555124f, 3.7416575f, 3.87298346f, 4.0f, 4.12310553f,
4.2426405f, 4.35889912f, 4.47213602f, 4.5825758f, 4.69041586f, 4.79583168f,
4.89897966f, 5.0f, 5.09901953f, 5.19615221f, 5.29150248f, 5.38516474f,
5.47722578f, 5.56776428f, 5.65685415f, 5.74456263f, 5.83095169f, 5.91608f,
6.0f, 6.08276272f, 6.16441393f, 6.24499798f, 6.3245554f, 6.40312433f,
6.48074055f, 6.55743837f, 6.63324976f, 6.70820379f, 6.78233004f, 6.85565472f,
6.92820311f, 7.0f, 7.07106781f, 7.14142847f, 7.21110249f, 7.28010988f,
7.34846926f, 7.41619825f, 7.48331499f, 7.54983425f, 7.6157732f, 7.68114567f,
7.74596691f, 7.81024981f, 7.8740077f, 7.93725395f, 8.0f, 8.06225777f,
8.1240387f, 8.18535233f, 8.24621105f, 8.30662346f, 8.36660004f, 8.42614937f,
8.48528099f, 8.54400349f, 8.60232544f, 8.66025448f, 8.71779823f, 8.77496433f,
8.83176041f, 8.88819408f, 8.94427204f, 9.0f, 9.05538559f, 9.11043358f,
9.1651516f,
};
const float xombe__rsqrt_half[XOMBE_HALF_MAX - XOMBE_HALF_MIN + 1] = {
0.114707865f, 0.113960579f, 0.113227703f, 0.112508789f, 0.111803398f, 0.111111112f,
0.11043153f, 0.109764263f, 0.109108947f,
};
const float xombe__half_log2[XOMBE_LMAX + 1] = {
0.0f, 0.0f, 0.5f, 0.792481244f, 1.0f, 1.16096401f,
1.2924813f, 1.40367746f, 1.5f, 1.58496249f, 1.66096401f, 1.72971582f,
1.7924813f, 1.85021985f, 1.90367746f, 1.95344532f, 2.0f, 2.04373145f,
2.08496261f, 2.12396383f, 2.16096401f, 2.19615865f, 2.22971582f, 2.26178098f,
2.29248118f, 2.32192802f, 2.35021996f, 2.37744379f, 2.40367746f, 2.4289906f,
2.4534452f, 2.47709823f, 2.5f, 2.52219701f, 2.54373145f, 2.56464148f,
2.58496261f, 2.60472679f, 2.62396383f, 2.64270115f, 2.66096401f, 2.67877603f,
2.69615865f, 2.71313238f, 2.72971582f, 2.74592662f, 2.76178098f, 2.7772944f,
2.79248118f, 2.80735493f, 2.82192802f, 2.83621264f, 2.85021996f, 2.86396027f,
2.87744379f, 2.89067984f, 2.90367746f,
};
const float xombe__w0_mid[XOMBE_B0_COUNT - 1] = {
0.0495915599f, 0.0488415845f, 0.0481036082f, 0.0473730974f, 0.0466531441f, 0.045948673f,
0.04525166f, 0.0445642062f, 0.0438907295f, 0.0432277471f, 0.0425717421f, 0.0419262908f,
0.0412927978f, 0.0406663083f, 0.0400503427f, 0.0394463614f, 0.0388523825f, 0.0382638723f,
0.0376839153f, 0.0371179469f, 0.0365574248f, 0.0360039659f, 0.0354639962f, 0.0349340104f,
0.0344074927f, 0.0338895433f, 0.033383552f, 0.0328830555f, 0.0323905833f, 0.0319081061f,
0.0313948058f, 0.0308835879f, 0.0304146204f, 0.0299551319f, 0.0294991173f, 0.0290506631f,
0.0286121704f, 0.0281796847f, 0.0277511757f, 0.0273292083f, 0.0269162189f, 0.0265072156f,
0.0261042416f, 0.0257097557f, 0.0253212638f, 0.0249367654f, 0.024558289f, 0.0241862927f,
0.0238182973f, 0.0234568212f, 0.0231018271f, 0.0227528457f, 0.0224078372f, 0.0220673606f,
0.0217343736f, 0.0214043651f, 0.0210793931f, 0.0207619015f, 0.0204489082f, 0.0201378986f,
0.0198329352f, 0.0195344314f, 0.0192394461f, 0.0189489499f, 0.0186619554f, 0.0183804743f,
0.01810297f, 0.0178299937f, 0.0175630003f, 0.0173000079f, 0.0170400087f, 0.0167835206f,
0.0165325347f, 0.0162855368f, 0.0160425529f, 0.0158040561f, 0.0155478921f, 0.0152935525f,
0.0150610572f, 0.0148330731f, 0.0146080665f, 0.014386083f, 0.0141685884f, 0.0139535898f,
0.0137410956f, 0.0135326087f, 0.0133281136f, 0.0131256115f, 0.0129266288f, 0.0127311265f,
0.0125386398f, 0.0123481303f, 0.0121601485f, 0.0119771576f, 0.0117946416f, 0.0116151711f,
0.0114401653f, 0.0112676797f, 0.0110966666f, 0.0109276846f, 0.0107626878f, 0.0105986828f,
0.0104377009f, 0.0102802003f, 0.0101257144f, 0.00997219887f, 0.00982072111f, 0.00967322104f,
0.00952621643f, 0.00938223489f, 0.00924173463f, 0.00910223462f, 0.00896423776f, 0.00882874615f,
0.0086972611f, 0.00856674556f, 0.00843776483f, 0.00831176154f, 0.00818676502f,
};
const xombe_cpx xombe__fft_tw[XOMBE_TW_N / 2] = {
{1.0f, 0.0f}, {0.999981165f, -0.00613588467f}, {0.999924719f, -0.0122715384f},
{0.999830604f, -0.0184067301f}, {0.999698818f, -0.024541229f}, {0.999529421f, -0.030674804f},
{0.999322355f, -0.0368072242f}, {0.999077737f, -0.0429382585f}, {0.99879545f, -0.0490676761f},
{0.998475552f, -0.0551952459f}, {0.998118103f, -0.061320737f}, {0.997723043f, -0.0674439222f},
{0.997290432f, -0.0735645667f}, {0.996820271f, -0.0796824396f}, {0.996312618f, -0.0857973099f},
{0.995767415f, -0.0919089541f}, {0.99518472f, -0.0980171412f}, {0.994564593f, -0.104121633f},
{0.993906975f, -0.110222206f}, {0.993211925f, -0.116318628f}, {0.992479563f, -0.122410677f},
{0.991709769f, -0.128498107f}, {0.990902662f, -0.134580702f}, {0.990058184f, -0.140658244f},
{0.989176512f, -0.146730468f}, {0.988257587f, -0.152797192f}, {0.987301409f, -0.15885815f},
{0.986308098f, -0.164913118f}, {0.985277653f, -0.170961887f}, {0.984210074f, -0.177004218f},
{0.983105481f, -0.183039889f}, {0.981963873f, -0.18906866f}, {0.980785251f, -0.195090324f},
{0.979569793f, -0.201104641f}, {0.97831738f, -0.207111374f}, {0.977028131f, -0.213110313f},
{0.975702107f, -0.219101235f}, {0.974339366f, -0.225083917f}, {0.972939968f, -0.231058106f},
{0.971503913f, -0.237023607f}, {0.970031261f, -0.242980182f}, {0.968522072f, -0.248927608f},
{0.966976464f, -0.254865646f}, {0.965394437f, -0.260794103f}, {0.963776052f, -0.266712755f},
{0.962121427f, -0.272621363f}, {0.960430503f, -0.27851969f}, {0.958703458f, -0.284407526f},
{0.956940353f, -0.290284663f}, {0.955141187f, -0.296150893f}, {0.953306019f, -0.302005947f},
{0.95143503f, -0.307849646f}, {0.949528158f, -0.313681751f}, {0.947585583f, -0.319502026f},
{0.945607305f, -0.32531029f}, {0.943593442f, -0.331106305f}, {0.941544056f, -0.336889863f},
{0.939459205f, -0.342660725f}, {0.937339008f, -0.348418683f}, {0.935183525f, -0.354163527f},
{0.932992816f, -0.359895051f}, {0.93076694f, -0.365612984f}, {0.928506076f, -0.371317208f},
{0.926210225f, -0.377007425f}, {0.923879504f, -0.382683426f}, {0.921514034f, -0.388345033f},
{0.919113874f, -0.393992037f}, {0.916679084f, -0.399624199f}, {0.914209783f, -0.405241311f},
{0.91170603f, -0.410843164f}, {0.909168005f, -0.416429549f}, {0.906595707f, -0.422000259f},
{0.903989315f, -0.427555084f}, {0.901348829f, -0.433093816f}, {0.898674488f, -0.438616246f},
{0.895966232f, -0.444122136f}, {0.893224299f, -0.449611336f}, {0.890448749f, -0.455083579f},
{0.887639642f, -0.460538715f}, {0.884797096f, -0.465976506f}, {0.881921291f, -0.471396744f},
{0.879012227f, -0.47679922f}, {0.876070082f, -0.482183784f}, {0.873094976f, -0.487550169f},
{0.870086968f, -0.492898196f}, {0.867046237f, -0.498227656f}, {0.863972843f, -0.50353837f},
{0.860866964f, -0.50883013f}, {0.857728601f, -0.514102757f}, {0.854557991f, -0.519356012f},
{0.851355195f, -0.524589658f}, {0.848120332f, -0.529803634f}, {0.84485358f, -0.534997642f},
{0.841554999f, -0.540171444f}, {0.838224709f, -0.545324981f}, {0.834862888f, -0.550457954f},
{0.831469595f, -0.555570245f}, {0.82804507f, -0.560661554f}, {0.824589312f, -0.565731823f},
{0.8211025f, -0.570780754f}, {0.817584813f, -0.575808167f}, {0.81403631f, -0.580813944f},
{0.81045717f, -0.585797846f}, {0.806847572f, -0.590759695f}, {0.803207517f, -0.59569931f},
{0.799537241f, -0.600616455f}, {0.795836926f, -0.605511069f}, {0.792106569f, -0.610382795f},
{0.78834641f, -0.615231574f}, {0.784556568f, -0.620057225f}, {0.780737221f, -0.624859512f},
{0.77688849f, -0.629638255f}, {0.773010433f, -0.634393275f}, {0.769103348f, -0.639124453f},
{0.765167236f, -0.643831551f}, {0.761202395f, -0.64851439f}, {0.757208824f, -0.653172851f},
{0.753186822f, -0.657806695f}, {0.749136388f, -0.662415802f}, {0.745057762f, -0.666999936f},
{0.740951121f, -0.671558976f}, {0.736816585f, -0.676092684f}, {0.732654274f, -0.680601001f},
{0.728464365f, -0.685083687f}, {0.724247098f, -0.689540565f}, {0.720002532f, -0.693971455f},
{0.715730846f, -0.698376238f}, {0.711432219f, -0.702754736f}, {0.707106769f, -0.707106769f},
{0.702754736f, -0.711432219f}, {0.698376238f, -0.715730846f}, {0.693971455f, -0.720002532f},
{0.689540565f, -0.724247098f}, {0.685083687f, -0.728464365f}, {0.680601001f, -0.732654274f},
{0.676092684f, -0.736816585f}, {0.671558976f, -0.740951121f}, {0.666999936f, -0.745057762f},
{0.662415802f, -0.749136388f}, {0.657806695f, -0.753186822f}, {0.653172851f, -0.757208824f},
{0.64851439f, -0.761202395f}, {0.643831551f, -0.765167236f}, {0.639124453f, -0.769103348f},
{0.634393275f, -0.773010433f}, {0.629638255f, -0.77688849f}, {0.624859512f, -0.780737221f},
{0.620057225f, -0.784556568f}, {0.615231574f, -0.78834641f}, {0.610382795f, -0.792106569f},
{0.605511069f, -0.795836926f}, {0.600616455f, -0.799537241f}, {0.59569931f, -0.803207517f},
{0.590759695f, -0.806847572f}, {0.585797846f, -0.81045717f}, {0.580813944f, -0.81403631f},
{0.575808167f, -0.817584813f}, {0.570780754f, -0.8211025f}, {0.565731823f, -0.824589312f},
{0.560661554f, -0.82804507f}, {0.555570245f, -0.831469595f}, {0.550457954f, -0.834862888f},
{0.545324981f, -0.838224709f}, {0.540171444f, -0.841554999f}, {0.534997642f, -0.84485358f},
{0.529803634f, -0.848120332f}, {0.524589658f, -0.851355195f}, {0.519356012f, -0.854557991f},
{0.514102757f, -0.857728601f}, {0.50883013f, -0.860866964f}, {0.50353837f, -0.863972843f},
{0.498227656f, -0.867046237f}, {0.492898196f, -0.870086968f}, {0.487550169f, -0.873094976f},
{0.482183784f, -0.876070082f}, {0.47679922f, -0.879012227f}, {0.471396744f, -0.881921291f},
{0.465976506f, -0.884797096f}, {0.460538715f, -0.887639642f}, {0.455083579f, -0.890448749f},
{0.449611336f, -0.893224299f}, {0.444122136f, -0.895966232f}, {0.438616246f, -0.898674488f},
{0.433093816f, -0.901348829f}, {0.427555084f, -0.903989315f}, {0.422000259f, -0.906595707f},
{0.416429549f, -0.909168005f}, {0.410843164f, -0.91170603f}, {0.405241311f, -0.914209783f},
{0.399624199f, -0.916679084f}, {0.393992037f, -0.919113874f}, {0.388345033f, -0.921514034f},
{0.382683426f, -0.923879504f}, {0.377007425f, -0.926210225f}, {0.371317208f, -0.928506076f},
{0.365612984f, -0.93076694f}, {0.359895051f, -0.932992816f}, {0.354163527f, -0.935183525f},
{0.348418683f, -0.937339008f}, {0.342660725f, -0.939459205f}, {0.336889863f, -0.941544056f},
{0.331106305f, -0.943593442f}, {0.32531029f, -0.945607305f}, {0.319502026f, -0.947585583f},
{0.313681751f, -0.949528158f}, {0.307849646f, -0.95143503f}, {0.302005947f, -0.953306019f},
{0.296150893f, -0.955141187f}, {0.290284663f, -0.956940353f}, {0.284407526f, -0.958703458f},
{0.27851969f, -0.960430503f}, {0.272621363f, -0.962121427f}, {0.266712755f, -0.963776052f},
{0.260794103f, -0.965394437f}, {0.254865646f, -0.966976464f}, {0.248927608f, -0.968522072f},
{0.242980182f, -0.970031261f}, {0.237023607f, -0.971503913f}, {0.231058106f, -0.972939968f},
{0.225083917f, -0.974339366f}, {0.219101235f, -0.975702107f}, {0.213110313f, -0.977028131f},
{0.207111374f, -0.97831738f}, {0.201104641f, -0.979569793f}, {0.195090324f, -0.980785251f},
{0.18906866f, -0.981963873f}, {0.183039889f, -0.983105481f}, {0.177004218f, -0.984210074f},
{0.170961887f, -0.985277653f}, {0.164913118f, -0.986308098f}, {0.15885815f, -0.987301409f},
{0.152797192f, -0.988257587f}, {0.146730468f, -0.989176512f}, {0.140658244f, -0.990058184f},
{0.134580702f, -0.990902662f}, {0.128498107f, -0.991709769f}, {0.122410677f, -0.992479563f},
{0.116318628f, -0.993211925f}, {0.110222206f, -0.993906975f}, {0.104121633f, -0.994564593f},
{0.0980171412f, -0.99518472f}, {0.0919089541f, -0.995767415f}, {0.0857973099f, -0.996312618f},
{0.0796824396f, -0.996820271f}, {0.0735645667f, -0.997290432f}, {0.0674439222f, -0.997723043f},
{0.061320737f, -0.998118103f}, {0.0551952459f, -0.998475552f}, {0.0490676761f, -0.99879545f},
{0.0429382585f, -0.999077737f}, {0.0368072242f, -0.999322355f}, {0.030674804f, -0.999529421f},
{0.024541229f, -0.999698818f}, {0.0184067301f, -0.999830604f}, {0.0122715384f, -0.999924719f},
{0.00613588467f, -0.999981165f}, {0.0f, -1.0f}, {-0.00613588467f, -0.999981165f},
{-0.0122715384f, -0.999924719f}, {-0.0184067301f, -0.999830604f}, {-0.024541229f, -0.999698818f},
{-0.030674804f, -0.999529421f}, {-0.0368072242f, -0.999322355f}, {-0.0429382585f, -0.999077737f},
{-0.0490676761f, -0.99879545f}, {-0.0551952459f, -0.998475552f}, {-0.061320737f, -0.998118103f},
{-0.0674439222f, -0.997723043f}, {-0.0735645667f, -0.997290432f}, {-0.0796824396f, -0.996820271f},
{-0.0857973099f, -0.996312618f}, {-0.0919089541f, -0.995767415f}, {-0.0980171412f, -0.99518472f},
{-0.104121633f, -0.994564593f}, {-0.110222206f, -0.993906975f}, {-0.116318628f, -0.993211925f},
{-0.122410677f, -0.992479563f}, {-0.128498107f, -0.991709769f}, {-0.134580702f, -0.990902662f},
{-0.140658244f, -0.990058184f}, {-0.146730468f, -0.989176512f}, {-0.152797192f, -0.988257587f},
{-0.15885815f, -0.987301409f}, {-0.164913118f, -0.986308098f}, {-0.170961887f, -0.985277653f},
{-0.177004218f, -0.984210074f}, {-0.183039889f, -0.983105481f}, {-0.18906866f, -0.981963873f},
{-0.195090324f, -0.980785251f}, {-0.201104641f, -0.979569793f}, {-0.207111374f, -0.97831738f},
{-0.213110313f, -0.977028131f}, {-0.219101235f, -0.975702107f}, {-0.225083917f, -0.974339366f},
{-0.231058106f, -0.972939968f}, {-0.237023607f, -0.971503913f}, {-0.242980182f, -0.970031261f},
{-0.248927608f, -0.968522072f}, {-0.254865646f, -0.966976464f}, {-0.260794103f, -0.965394437f},
{-0.266712755f, -0.963776052f}, {-0.272621363f, -0.962121427f}, {-0.27851969f, -0.960430503f},
{-0.284407526f, -0.958703458f}, {-0.290284663f, -0.956940353f}, {-0.296150893f, -0.955141187f},
{-0.302005947f, -0.953306019f}, {-0.307849646f, -0.95143503f}, {-0.313681751f, -0.949528158f},
{-0.319502026f, -0.947585583f}, {-0.32531029f, -0.945607305f}, {-0.331106305f, -0.943593442f},
{-0.336889863f, -0.941544056f}, {-0.342660725f, -0.939459205f}, {-0.348418683f, -0.937339008f},
{-0.354163527f, -0.935183525f}, {-0.359895051f, -0.932992816f}, {-0.365612984f, -0.93076694f},
{-0.371317208f, -0.928506076f}, {-0.377007425f, -0.926210225f}, {-0.382683426f, -0.923879504f},
{-0.388345033f, -0.921514034f}, {-0.393992037f, -0.919113874f}, {-0.399624199f, -0.916679084f},
{-0.405241311f, -0.914209783f}, {-0.410843164f, -0.91170603f}, {-0.416429549f, -0.909168005f},
{-0.422000259f, -0.906595707f}, {-0.427555084f, -0.903989315f}, {-0.433093816f, -0.901348829f},
{-0.438616246f, -0.898674488f}, {-0.444122136f, -0.895966232f}, {-0.449611336f, -0.893224299f},
{-0.455083579f, -0.890448749f}, {-0.460538715f, -0.887639642f}, {-0.465976506f, -0.884797096f},
{-0.471396744f, -0.881921291f}, {-0.47679922f, -0.879012227f}, {-0.482183784f, -0.876070082f},
{-0.487550169f, -0.873094976f}, {-0.492898196f, -0.870086968f}, {-0.498227656f, -0.867046237f},
{-0.50353837f, -0.863972843f}, {-0.50883013f, -0.860866964f}, {-0.514102757f, -0.857728601f},
{-0.519356012f, -0.854557991f}, {-0.524589658f, -0.851355195f}, {-0.529803634f, -0.848120332f},
{-0.534997642f, -0.84485358f}, {-0.540171444f, -0.841554999f}, {-0.545324981f, -0.838224709f},
{-0.550457954f, -0.834862888f}, {-0.555570245f, -0.831469595f}, {-0.560661554f, -0.82804507f},
{-0.565731823f, -0.824589312f}, {-0.570780754f, -0.8211025f}, {-0.575808167f, -0.817584813f},
{-0.580813944f, -0.81403631f}, {-0.585797846f, -0.81045717f}, {-0.590759695f, -0.806847572f},
{-0.59569931f, -0.803207517f}, {-0.600616455f, -0.799537241f}, {-0.605511069f, -0.795836926f},
{-0.610382795f, -0.792106569f}, {-0.615231574f, -0.78834641f}, {-0.620057225f, -0.784556568f},
{-0.624859512f, -0.780737221f}, {-0.629638255f, -0.77688849f}, {-0.634393275f, -0.773010433f},
{-0.639124453f, -0.769103348f}, {-0.643831551f, -0.765167236f}, {-0.64851439f, -0.761202395f},
{-0.653172851f, -0.757208824f}, {-0.657806695f, -0.753186822f}, {-0.662415802f, -0.749136388f},
{-0.666999936f, -0.745057762f}, {-0.671558976f, -0.740951121f}, {-0.676092684f, -0.736816585f},
{-0.680601001f, -0.732654274f}, {-0.685083687f, -0.728464365f}, {-0.689540565f, -0.724247098f},
{-0.693971455f, -0.720002532f}, {-0.698376238f, -0.715730846f}, {-0.702754736f, -0.711432219f},
{-0.707106769f, -0.707106769f}, {-0.711432219f, -0.702754736f}, {-0.715730846f, -0.698376238f},
{-0.720002532f, -0.693971455f}, {-0.724247098f, -0.689540565f}, {-0.728464365f, -0.685083687f},
{-0.732654274f, -0.680601001f}, {-0.736816585f, -0.676092684f}, {-0.740951121f, -0.671558976f},
{-0.745057762f, -0.666999936f}, {-0.749136388f, -0.662415802f}, {-0.753186822f, -0.657806695f},
{-0.757208824f, -0.653172851f}, {-0.761202395f, -0.64851439f}, {-0.765167236f, -0.643831551f},
{-0.769103348f, -0.639124453f}, {-0.773010433f, -0.634393275f}, {-0.77688849f, -0.629638255f},
{-0.780737221f, -0.624859512f}, {-0.784556568f, -0.620057225f}, {-0.78834641f, -0.615231574f},
{-0.792106569f, -0.610382795f}, {-0.795836926f, -0.605511069f}, {-0.799537241f, -0.600616455f},
{-0.803207517f, -0.59569931f}, {-0.806847572f, -0.590759695f}, {-0.81045717f, -0.585797846f},
{-0.81403631f, -0.580813944f}, {-0.817584813f, -0.575808167f}, {-0.8211025f, -0.570780754f},
{-0.824589312f, -0.565731823f}, {-0.82804507f, -0.560661554f}, {-0.831469595f, -0.555570245f},
{-0.834862888f, -0.550457954f}, {-0.838224709f, -0.545324981f}, {-0.841554999f, -0.540171444f},
{-0.84485358f, -0.534997642f}, {-0.848120332f, -0.529803634f}, {-0.851355195f, -0.524589658f},
{-0.854557991f, -0.519356012f}, {-0.857728601f, -0.514102757f}, {-0.860866964f, -0.50883013f},
{-0.863972843f, -0.50353837f}, {-0.867046237f, -0.498227656f}, {-0.870086968f, -0.492898196f},
{-0.873094976f, -0.487550169f}, {-0.876070082f, -0.482183784f}, {-0.879012227f, -0.47679922f},
{-0.881921291f, -0.471396744f}, {-0.884797096f, -0.465976506f}, {-0.887639642f, -0.460538715f},
{-0.890448749f, -0.455083579f}, {-0.893224299f, -0.449611336f}, {-0.895966232f, -0.444122136f},
{-0.898674488f, -0.438616246f}, {-0.901348829f, -0.433093816f}, {-0.903989315f, -0.427555084f},
{-0.906595707f, -0.422000259f}, {-0.909168005f, -0.416429549f}, {-0.91170603f, -0.410843164f},
{-0.914209783f, -0.405241311f}, {-0.916679084f, -0.399624199f}, {-0.919113874f, -0.393992037f},
{-0.921514034f, -0.388345033f}, {-0.923879504f, -0.382683426f}, {-0.926210225f, -0.377007425f},
{-0.928506076f, -0.371317208f}, {-0.93076694f, -0.365612984f}, {-0.932992816f, -0.359895051f},
{-0.935183525f, -0.354163527f}, {-0.937339008f, -0.348418683f}, {-0.939459205f, -0.342660725f},
{-0.941544056f, -0.336889863f}, {-0.943593442f, -0.331106305f}, {-0.945607305f, -0.32531029f},
{-0.947585583f, -0.319502026f}, {-0.949528158f, -0.313681751f}, {-0.95143503f, -0.307849646f},
{-0.953306019f, -0.302005947f}, {-0.955141187f, -0.296150893f}, {-0.956940353f, -0.290284663f},
{-0.958703458f, -0.284407526f}, {-0.960430503f, -0.27851969f}, {-0.962121427f, -0.272621363f},
{-0.963776052f, -0.266712755f}, {-0.965394437f, -0.260794103f}, {-0.966976464f, -0.254865646f},
{-0.968522072f, -0.248927608f}, {-0.970031261f, -0.242980182f}, {-0.971503913f, -0.237023607f},
{-0.972939968f, -0.231058106f}, {-0.974339366f, -0.225083917f}, {-0.975702107f, -0.219101235f},
{-0.977028131f, -0.213110313f}, {-0.97831738f, -0.207111374f}, {-0.979569793f, -0.201104641f},
{-0.980785251f, -0.195090324f}, {-0.981963873f, -0.18906866f}, {-0.983105481f, -0.183039889f},
{-0.984210074f, -0.177004218f}, {-0.985277653f, -0.170961887f}, {-0.986308098f, -0.164913118f},
{-0.987301409f, -0.15885815f}, {-0.988257587f, -0.152797192f}, {-0.989176512f, -0.146730468f},
{-0.990058184f, -0.140658244f}, {-0.990902662f, -0.134580702f}, {-0.991709769f, -0.128498107f},
{-0.992479563f, -0.122410677f}, {-0.993211925f, -0.116318628f}, {-0.993906975f, -0.110222206f},
{-0.994564593f, -0.104121633f}, {-0.99518472f, -0.0980171412f}, {-0.995767415f, -0.0919089541f},
{-0.996312618f, -0.0857973099f}, {-0.996820271f, -0.0796824396f}, {-0.997290432f, -0.0735645667f},
{-0.997723043f, -0.0674439222f}, {-0.998118103f, -0.061320737f}, {-0.998475552f, -0.0551952459f},
{-0.99879545f, -0.0490676761f}, {-0.999077737f, -0.0429382585f}, {-0.999322355f, -0.0368072242f},
{-0.999529421f, -0.030674804f}, {-0.999698818f, -0.024541229f}, {-0.999830604f, -0.0184067301f},
{-0.999924719f, -0.0122715384f}, {-0.999981165f, -0.00613588467f},
};
#if XOMBE_HAVE_ENCODER
const float xombe__base_win[XOMBE_BASE_WINDOW] = {
0.0799999982f, 0.0802315921f, 0.0809261277f, 0.0820829123f, 0.0837007836f, 0.0857781097f,
0.0883127972f, 0.091302298f, 0.0947435945f, 0.0986332297f, 0.102967285f, 0.107741393f,
0.11295075f, 0.118590109f, 0.124653794f, 0.131135687f, 0.138029292f, 0.145327628f,
0.153023377f, 0.161108777f, 0.169575676f, 0.178415582f, 0.187619552f, 0.197178349f,
0.207082346f, 0.217321545f, 0.227885664f, 0.238764063f, 0.249945775f, 0.261419535f,
0.273173809f, 0.285196781f, 0.297476292f, 0.310000002f, 0.322755307f, 0.335729361f,
0.34890908f, 0.362281233f, 0.375832349f, 0.389548749f, 0.403416634f, 0.417422056f,
0.43155089f, 0.44578892f, 0.46012184f, 0.474535167f, 0.489014417f, 0.503545046f,
0.518112302f, 0.532701671f, 0.547298372f, 0.561887681f, 0.576454997f, 0.590985596f,
0.605464816f, 0.619878173f, 0.634211063f, 0.648449123f, 0.662577927f, 0.67658335f,
0.690451264f, 0.704167664f, 0.71771878f, 0.731090903f, 0.744270623f, 0.757244706f,
0.769999981f, 0.782523692f, 0.794803202f, 0.806826174f, 0.818580449f, 0.830054224f,
0.841235936f, 0.85211432f, 0.862678468f, 0.872917652f, 0.88282162f, 0.892380416f,
0.901584446f, 0.910424292f, 0.918891251f, 0.926976621f, 0.934672356f, 0.941970706f,
0.948864281f, 0.955346227f, 0.961409867f, 0.967049241f, 0.972258627f, 0.977032721f,
0.981366754f, 0.985256374f, 0.988697708f, 0.991687179f, 0.994221866f, 0.996299207f,
0.997917056f, 0.999073863f, 0.999768436f, 1.0f, 0.999768436f, 0.999073863f,
0.997917056f, 0.996299207f, 0.994221866f, 0.991687179f, 0.988697708f, 0.985256374f,
0.981366754f, 0.977032721f, 0.972258627f, 0.967049241f, 0.961409867f, 0.955346227f,
0.948864281f, 0.941970706f, 0.934672356f, 0.926976621f, 0.918891251f, 0.910424292f,
0.901584446f, 0.892380416f, 0.88282162f, 0.872917652f, 0.862678468f, 0.85211432f,
0.841235936f, 0.830054224f, 0.818580449f, 0.806826174f, 0.794803202f, 0.782523692f,
0.769999981f, 0.757244706f, 0.744270623f, 0.731090903f, 0.71771878f, 0.704167664f,
0.690451264f, 0.67658335f, 0.662577927f, 0.648449123f, 0.634211063f, 0.619878173f,
0.605464816f, 0.590985596f, 0.576454997f, 0.561887681f, 0.547298372f, 0.532701671f,
0.518112302f, 0.503545046f, 0.489014417f, 0.474535167f, 0.46012184f, 0.44578892f,
0.43155089f, 0.417422056f, 0.403416634f, 0.389548749f, 0.375832349f, 0.362281233f,
0.34890908f, 0.335729361f, 0.322755307f, 0.310000002f, 0.297476292f, 0.285196781f,
0.273173809f, 0.261419535f, 0.249945775f, 0.238764063f, 0.227885664f, 0.217321545f,
0.207082346f, 0.197178349f, 0.187619552f, 0.178415582f, 0.169575676f, 0.161108777f,
0.153023377f, 0.145327628f, 0.138029292f, 0.131135687f, 0.124653794f, 0.118590109f,
0.11295075f, 0.107741393f, 0.102967285f, 0.0986332297f, 0.0947435945f, 0.091302298f,
0.0883127972f, 0.0857781097f, 0.0837007836f, 0.0820829123f, 0.0809261277f, 0.0802315921f,
0.0799999982f,
};
const float xombe__pitch_lpf[2 * XOMBE_PITCH_LPF_HALF + 1] = {
0.00253628287f, 0.00255348557f, 0.0f, -0.00863465201f, -0.0210222024f, -0.0242112093f,
0.0f, 0.0605565086f, 0.14459157f, 0.219130725f, 0.248999f, 0.219130725f,
0.14459157f, 0.0605565086f, 0.0f, -0.0242112093f, -0.0210222024f, -0.00863465201f,
0.0f, 0.00255348557f, 0.00253628287f,
};
#if XOMBE_KERNELS_Q15
const uint32_t xombe__pitch_lpf_q15[2][XOMBE_PITCH_LPF_PAIRS] = {
{
0x00890088u, 0xfe320000u, 0xfaf1fb9cu, 0x0ca60000u, 0x2dc61e34u, 0x2dc63404u,
0x0ca61e34u, 0xfaf10000u, 0xfe32fb9cu, 0x00890000u, 0x00000088u,
},
{
0x00880000u, 0x00000089u, 0xfb9cfe32u, 0x0000faf1u, 0x1e340ca6u, 0x34042dc6u,
0x1e342dc6u, 0x00000ca6u, 0xfb9cfaf1u, 0x0000fe32u, 0x00880089u,
},
};
const float xombe__pitch_lpf_q15_gain = 53477.1523f;
const uint32_t xombe__fft_tw_q15[XOMBE_FFT / 4] = {
0x00007fffu, 0xfe6e7ffeu, 0xfcdc7ff6u, 0xfb4a7feau, 0xf9b87fd9u, 0xf8277fc2u,
0xf6957fa7u, 0xf5057f87u, 0xf3747f62u, 0xf1e47f38u, 0xf0557f0au, 0xeec67ed6u,
0xed387e9du, 0xebab7e60u, 0xea1e7e1eu, 0xe8927dd6u, 0xe7077d8au, 0xe57d7d3au,
0xe3f47ce4u, 0xe26d7c89u, 0xe0e67c2au, 0xdf617bc6u, 0xdddc7b5du, 0xdc597aefu,
0xdad87a7du, 0xd9587a06u, 0xd7d9798au, 0xd65c790au, 0xd4e17885u, 0xd36777fbu,
0xd1ef776cu, 0xd07976d9u, 0xcf047642u, 0xcd9275a6u, 0xcc217505u, 0xcab27460u,
0xc94673b6u, 0xc7db7308u, 0xc6737255u, 0xc50d719eu, 0xc3a970e3u, 0xc2487023u,
0xc0e96f5fu, 0xbf8c6e97u, 0xbe326dcau, 0xbcda6cf9u, 0xbb856c24u, 0xba336b4bu,
0xb8e36a6eu, 0xb796698cu, 0xb64c68a7u, 0xb50567bdu, 0xb3c066d0u, 0xb27f65deu,
0xb14064e9u, 0xb00563efu, 0xaecc62f2u, 0xad9761f1u, 0xac6560ecu, 0xab365fe4u,
0xaa0a5ed7u, 0xa8e25dc8u, 0xa7bd5cb4u, 0xa69c5b9du, 0xa57e5a82u, 0xa4635964u,
0xa34c5843u, 0xa238571eu, 0xa12955f6u, 0xa01c54cau, 0x9f14539bu, 0x9e0f5269u,
0x9d0e5134u, 0x9c114ffbu, 0x9b174ec0u, 0x9a224d81u, 0x99304c40u, 0x98434afbu,
0x975949b4u, 0x9674486au, 0x9592471du, 0x94b545cdu, 0x93dc447bu, 0x93074326u,
0x923641ceu, 0x91694074u, 0x90a13f17u, 0x8fdd3db8u, 0x8f1d3c57u, 0x8e623af3u,
0x8dab398du, 0x8cf83825u, 0x8c4a36bau, 0x8ba0354eu, 0x8afb33dfu, 0x8a5a326eu,
0x89be30fcu, 0x89272f87u, 0x88942e11u, 0x88052c99u, 0x877b2b1fu, 0x86f629a4u,
0x86762827u, 0x85fa26a8u, 0x85832528u, 0x851123a7u, 0x84a32224u, 0x843a209fu,
0x83d61f1au, 0x83771d93u, 0x831c1c0cu, 0x82c61a83u, 0x827618f9u, 0x822a176eu,
0x81e215e2u, 0x81a01455u, 0x816312c8u, 0x812a113au, 0x80f60fabu, 0x80c80e1cu,
0x809e0c8cu, 0x80790afbu, 0x8059096bu, 0x803e07d9u, 0x80270648u, 0x801604b6u,
0x800a0324u, 0x80020192u, 0x80000000u, 0x8002fe6eu, 0x800afcdcu, 0x8016fb4au,
0x8027f9b8u, 0x803ef827u, 0x8059f695u, 0x8079f505u, 0x809ef374u, 0x80c8f1e4u,
0x80f6f055u, 0x812aeec6u, 0x8163ed38u, 0x81a0ebabu, 0x81e2ea1eu, 0x822ae892u,
0x8276e707u, 0x82c6e57du, 0x831ce3f4u, 0x8377e26du, 0x83d6e0e6u, 0x843adf61u,
0x84a3dddcu, 0x8511dc59u, 0x8583dad8u, 0x85fad958u, 0x8676d7d9u, 0x86f6d65cu,
0x877bd4e1u, 0x8805d367u, 0x8894d1efu, 0x8927d079u, 0x89becf04u, 0x8a5acd92u,
0x8afbcc21u, 0x8ba0cab2u, 0x8c4ac946u, 0x8cf8c7dbu, 0x8dabc673u, 0x8e62c50du,
0x8f1dc3a9u, 0x8fddc248u, 0x90a1c0e9u, 0x9169bf8cu, 0x9236be32u, 0x9307bcdau,
0x93dcbb85u, 0x94b5ba33u, 0x9592b8e3u, 0x9674b796u, 0x9759b64cu, 0x9843b505u,
0x9930b3c0u, 0x9a22b27fu, 0x9b17b140u, 0x9c11b005u, 0x9d0eaeccu, 0x9e0fad97u,
0x9f14ac65u, 0xa01cab36u, 0xa129aa0au, 0xa238a8e2u, 0xa34ca7bdu, 0xa463a69cu,
0xa57ea57eu, 0xa69ca463u, 0xa7bda34cu, 0xa8e2a238u, 0xaa0aa129u, 0xab36a01cu,
0xac659f14u, 0xad979e0fu, 0xaecc9d0eu, 0xb0059c11u, 0xb1409b17u, 0xb27f9a22u,
0xb3c09930u, 0xb5059843u, 0xb64c9759u, 0xb7969674u, 0xb8e39592u, 0xba3394b5u,
0xbb8593dcu, 0xbcda9307u, 0xbe329236u, 0xbf8c9169u, 0xc0e990a1u, 0xc2488fddu,
0xc3a98f1du, 0xc50d8e62u, 0xc6738dabu, 0xc7db8cf8u, 0xc9468c4au, 0xcab28ba0u,
0xcc218afbu, 0xcd928a5au, 0xcf0489beu, 0xd0798927u, 0xd1ef8894u, 0xd3678805u,
0xd4e1877bu, 0xd65c86f6u, 0xd7d98676u, 0xd95885fau, 0xdad88583u, 0xdc598511u,
0xdddc84a3u, 0xdf61843au, 0xe0e683d6u, 0xe26d8377u, 0xe3f4831cu, 0xe57d82c6u,
0xe7078276u, 0xe892822au, 0xea1e81e2u, 0xebab81a0u, 0xed388163u, 0xeec6812au,
0xf05580f6u, 0xf1e480c8u, 0xf374809eu, 0xf5058079u, 0xf6958059u, 0xf827803eu,
0xf9b88027u, 0xfb4a8016u, 0xfcdc800au, 0xfe6e8002u,
};
const uint32_t xombe__tone_tw_q15[XOMBE_TONE_FFT / 4] = {
0x00007fffu, 0xfcdc7ff6u, 0xf9b87fd9u, 0xf6957fa7u, 0xf3747f62u, 0xf0557f0au,
0xed387e9du, 0xea1e7e1eu, 0xe7077d8au, 0xe3f47ce4u, 0xe0e67c2au, 0xdddc7b5du,
0xdad87a7du, 0xd7d9798au, 0xd4e17885u, 0xd1ef776cu, 0xcf047642u, 0xcc217505u,
0xc94673b6u, 0xc6737255u, 0xc3a970e3u, 0xc0e96f5fu, 0xbe326dcau, 0xbb856c24u,
0xb8e36a6eu, 0xb64c68a7u, 0xb3c066d0u, 0xb14064e9u, 0xaecc62f2u, 0xac6560ecu,
0xaa0a5ed7u, 0xa7bd5cb4u, 0xa57e5a82u, 0xa34c5843u, 0xa12955f6u, 0x9f14539bu,
0x9d0e5134u, 0x9b174ec0u, 0x99304c40u, 0x975949b4u, 0x9592471du, 0x93dc447bu,
0x923641ceu, 0x90a13f17u, 0x8f1d3c57u, 0x8dab398du, 0x8c4a36bau, 0x8afb33dfu,
0x89be30fcu, 0x88942e11u, 0x877b2b1fu, 0x86762827u, 0x85832528u, 0x84a32224u,
0x83d61f1au, 0x831c1c0cu, 0x827618f9u, 0x81e215e2u, 0x816312c8u, 0x80f60fabu,
0x809e0c8cu, 0x8059096bu, 0x80270648u, 0x800a0324u, 0x80000000u, 0x800afcdcu,
0x8027f9b8u, 0x8059f695u, 0x809ef374u, 0x80f6f055u, 0x8163ed38u, 0x81e2ea1eu,
0x8276e707u, 0x831ce3f4u, 0x83d6e0e6u, 0x84a3dddcu, 0x8583dad8u, 0x8676d7d9u,
0x877bd4e1u, 0x8894d1efu, 0x89becf04u, 0x8afbcc21u, 0x8c4ac946u, 0x8dabc673u,
0x8f1dc3a9u, 0x90a1c0e9u, 0x9236be32u, 0x93dcbb85u, 0x9592b8e3u, 0x9759b64cu,
0x9930b3c0u, 0x9b17b140u, 0x9d0eaeccu, 0x9f14ac65u, 0xa129aa0au, 0xa34ca7bdu,
0xa57ea57eu, 0xa7bda34cu, 0xaa0aa129u, 0xac659f14u, 0xaecc9d0eu, 0xb1409b17u,
0xb3c09930u, 0xb64c9759u, 0xb8e39592u, 0xbb8593dcu, 0xbe329236u, 0xc0e990a1u,
0xc3a98f1du, 0xc6738dabu, 0xc9468c4au, 0xcc218afbu, 0xcf0489beu, 0xd1ef8894u,
0xd4e1877bu, 0xd7d98676u, 0xdad88583u, 0xdddc84a3u, 0xe0e683d6u, 0xe3f4831cu,
0xe7078276u, 0xea1e81e2u, 0xed388163u, 0xf05580f6u, 0xf374809eu, 0xf6958059u,
0xf9b88027u, 0xfcdc800au,
};
#endif
const float xombe__pitch_w2[XOMBE_PITCH_WIN] = {
5.3679385e-05f, 5.38148597e-05f, 5.42222406e-05f, 5.49044235e-05f, 5.58662214e-05f, 5.71143501e-05f,
5.86574351e-05f, 6.05059613e-05f, 6.26722685e-05f, 6.51705195e-05f, 6.80166559e-05f, 7.12283945e-05f,
7.48251405e-05f, 7.88279722e-05f, 8.32595906e-05f, 8.81442393e-05f, 9.35077042e-05f, 9.93771901e-05f,
0.000105781291f, 0.000112749927f, 0.000120314246f, 0.000128506596f, 0.000137360388f, 0.000146910053f,
0.000157190996f, 0.000168239407f, 0.000180092291f, 0.000192787295f, 0.00020636266f, 0.000220857095f,
0.000236309701f, 0.000252759899f, 0.000270247285f, 0.00028881157f, 0.000308492425f, 0.000329329428f,
0.000351361959f, 0.000374629104f, 0.000399169512f, 0.00042502131f, 0.000452222012f, 0.000480808434f,
0.000510816579f, 0.000542281428f, 0.000575237034f, 0.000609716401f, 0.000645751075f, 0.00068337156f,
0.000722606725f, 0.000763484102f, 0.000806029537f, 0.000850267243f, 0.000896219572f, 0.000943907187f,
0.000993348658f, 0.00104456081f, 0.00109755783f, 0.00115235255f, 0.00120895484f, 0.00126737263f,
0.00132761162f, 0.00138967496f, 0.00145356311f, 0.00151927443f, 0.00158680452f, 0.00165614625f,
0.00172729034f, 0.0018002243f, 0.00187493325f, 0.00195139961f, 0.00202960288f, 0.0021095199f,
0.00219112495f, 0.00227438915f, 0.00235928129f, 0.00244576694f, 0.00253380951f, 0.00262336922f,
0.0027144039f, 0.00280686794f, 0.00290071429f, 0.0029958922f, 0.00309234904f, 0.00319002918f,
0.00328887464f, 0.00338882511f, 0.00348981773f, 0.00359178754f, 0.00369466678f, 0.00379838631f,
0.00390287419f, 0.0040080566f, 0.0041138581f, 0.00422020117f, 0.00432700617f, 0.00443419209f,
0.00454167603f, 0.00464937417f, 0.0047572013f, 0.00486506987f, 0.00497289188f, 0.00508057838f,
0.00518803997f, 0.00529518444f, 0.00540192099f, 0.00550815696f, 0.00561379967f, 0.005718756f,
0.00582293281f, 0.00592623604f, 0.0060285721f, 0.00612984831f, 0.00622997107f, 0.00632884772f,
0.00642638607f, 0.0065224939f, 0.00661708089f, 0.00671005668f, 0.00680133281f, 0.0068908208f,
0.00697843451f, 0.00706408871f, 0.00714769913f, 0.0072291838f, 0.00730846263f, 0.00738545693f,
0.00746008987f, 0.00753228692f, 0.00760197546f, 0.0076690861f, 0.00773355085f, 0.00779530359f,
0.00785428286f, 0.00791042764f, 0.00796368066f, 0.00801398791f, 0.00806129724f, 0.00810555927f,
0.00814673025f, 0.00818476733f, 0.00821962953f, 0.00825128239f, 0.00827969145f, 0.00830482971f,
0.00832666829f, 0.00834518578f, 0.00836036354f, 0.00837218482f, 0.00838063657f, 0.00838571228f,
0.00838740449f, 0.00838571228f, 0.00838063657f, 0.00837218482f, 0.00836036354f, 0.00834518578f,
0.00832666829f, 0.00830482971f, 0.00827969145f, 0.00825128239f, 0.00821962953f, 0.00818476733f,
0.00814673025f, 0.00810555927f, 0.00806129724f, 0.00801398791f, 0.00796368066f, 0.00791042764f,
0.00785428286f, 0.00779530359f, 0.00773355085f, 0.0076690861f, 0.00760197546f, 0.00753228692f,
0.00746008987f, 0.00738545693f, 0.00730846263f, 0.0072291838f, 0.00714769913f, 0.00706408871f,
0.00697843451f, 0.0068908208f, 0.00680133281f, 0.00671005668f, 0.00661708089f, 0.0065224939f,
0.00642638607f, 0.00632884772f, 0.00622997107f, 0.00612984831f, 0.0060285721f, 0.00592623604f,
0.00582293281f, 0.005718756f, 0.00561379967f, 0.00550815696f, 0.00540192099f, 0.00529518444f,
0.00518803997f, 0.00508057838f, 0.00497289188f, 0.00486506987f, 0.0047572013f, 0.00464937417f,
0.00454167603f, 0.00443419209f, 0.00432700617f, 0.00422020117f, 0.0041138581f, 0.0040080566f,
0.00390287419f, 0.00379838631f, 0.00369466678f, 0.00359178754f, 0.00348981773f, 0.00338882511f,
0.00328887464f, 0.00319002918f, 0.00309234904f, 0.0029958922f, 0.00290071429f, 0.00280686794f,
0.0027144039f, 0.00262336922f, 0.00253380951f, 0.00244576694f, 0.00235928129f, 0.00227438915f,
0.00219112495f, 0.0021095199f, 0.00202960288f, 0.00195139961f, 0.00187493325f, 0.0018002243f,
0.00172729034f, 0.00165614625f, 0.00158680452f, 0.00151927443f, 0.00145356311f, 0.00138967496f,
0.00132761162f, 0.00126737263f, 0.00120895484f, 0.00115235255f, 0.00109755783f, 0.00104456081f,
0.000993348658f, 0.000943907187f, 0.000896219572f, 0.000850267243f, 0.000806029537f, 0.000763484102f,
0.000722606725f, 0.00068337156f, 0.000645751075f, 0.000609716401f, 0.000575237034f, 0.000542281428f,
0.000510816579f, 0.000480808434f, 0.000452222012f, 0.00042502131f, 0.000399169512f, 0.000374629104f,
0.000351361959f, 0.000329329428f, 0.000308492425f, 0.00028881157f, 0.000270247285f, 0.000252759899f,
0.000236309701f, 0.000220857095f, 0.00020636266f, 0.000192787295f, 0.000180092291f, 0.000168239407f,
0.000157190996f, 0.000146910053f, 0.000137360388f, 0.000128506596f, 0.000120314246f, 0.000112749927f,
0.000105781291f, 9.93771901e-05f, 9.35077042e-05f, 8.81442393e-05f, 8.32595906e-05f, 7.88279722e-05f,
7.48251405e-05f, 7.12283945e-05f, 6.80166559e-05f, 6.51705195e-05f, 6.26722685e-05f, 6.05059613e-05f,
5.86574351e-05f, 5.71143501e-05f, 5.58662214e-05f, 5.49044235e-05f, 5.42222406e-05f, 5.38148597e-05f,
5.3679385e-05f,
};
const float xombe__pitch_sum_w4 = 0.00605550827f;
#if XOMBE_KERNELS_Q15
const int16_t xombe__pitch_w2_q15[XOMBE_PITCH_HALF + 1] = {
210, 210, 212, 214, 218, 223, 229, 236, 245, 255, 266, 278,
292, 308, 325, 344, 365, 388, 413, 440, 470, 502, 537, 574,
614, 657, 704, 753, 806, 863, 923, 987, 1056, 1128, 1205, 1287,
1373, 1464, 1559, 1660, 1767, 1878, 1996, 2119, 2247, 2382, 2523, 2670,
2823, 2983, 3149, 3322, 3501, 3688, 3881, 4081, 4288, 4502, 4723, 4951,
5187, 5429, 5679, 5935, 6199, 6470, 6748, 7033, 7325, 7624, 7929, 8241,
8560, 8885, 9217, 9555, 9899, 10249, 10604, 10966, 11332, 11704, 12081, 12462,
12849, 13239, 13634, 14032, 14434, 14839, 15247, 15658, 16072, 16487, 16904, 17323,
17743, 18164, 18585, 19006, 19428, 19848, 20268, 20687, 21104, 21519, 21931, 22341,
22748, 23152, 23552, 23947, 24339, 24725, 25106, 25481, 25851, 26214, 26571, 26920,
27263, 27597, 27924, 28242, 28552, 28853, 29144, 29426, 29699, 29961, 30213, 30454,
30684, 30904, 31112, 31308, 31493, 31666, 31827, 31975, 32112, 32235, 32346, 32444,
32530, 32602, 32661, 32708, 32741, 32760, 32767,
};
const float xombe__pitch_w2_q15_gain = 3906691.25f;
#endif
const float xombe__tone_win[XOMBE_TONE_SEG] = {
0.0f, 0.00017277422f, 0.000690977438f, 0.00155425165f, 0.00276200008f, 0.00431338791f,
0.00620734366f, 0.00844255742f, 0.0110174855f, 0.0139303477f, 0.0171791315f, 0.0207615905f,
0.0246752501f, 0.0289174058f, 0.033485122f, 0.038375251f, 0.0435844027f, 0.0491089821f,
0.0549451709f, 0.0610889383f, 0.0675360337f, 0.0742820054f, 0.0813221857f, 0.0886517167f,
0.0962655246f, 0.104158357f, 0.112324752f, 0.12075907f, 0.129455477f, 0.138407975f,
0.147610351f, 0.157056287f, 0.16673921f, 0.176652446f, 0.186789155f, 0.197142333f,
0.207704797f, 0.218469277f, 0.229428321f, 0.24057436f, 0.25189966f, 0.263396442f,
0.27505675f, 0.286872506f, 0.298835546f, 0.310937643f, 0.323170364f, 0.335525304f,
0.34799391f, 0.36056757f, 0.37323758f, 0.385995209f, 0.398831606f, 0.411737949f,
0.424705267f, 0.43772465f, 0.450787038f, 0.46388346f, 0.477004826f, 0.490142077f,
0.503286183f, 0.516427994f, 0.52955842f, 0.542668462f, 0.555748999f, 0.568790972f,
0.58178544f, 0.594723403f, 0.607595861f, 0.620393991f, 0.633108914f, 0.645731866f,
0.658254087f, 0.670666933f, 0.682961822f, 0.695130289f, 0.70716387f, 0.719054282f,
0.730793357f, 0.74237287f, 0.753784895f, 0.765021563f, 0.776075065f, 0.786937773f,
0.797602117f, 0.808060884f, 0.818306684f, 0.828332543f, 0.838131487f, 0.847696722f,
0.857021689f, 0.866099894f, 0.874925137f, 0.883491218f, 0.891792297f, 0.899822593f,
0.907576561f, 0.915048897f, 0.922234356f, 0.929128051f, 0.935725152f, 0.942021132f,
0.948011637f, 0.953692496f, 0.959059834f, 0.964109898f, 0.968839228f, 0.973244548f,
0.977322817f, 0.981071174f, 0.984487116f, 0.9875682f, 0.990312338f, 0.992717624f,
0.994782388f, 0.996505201f, 0.99788487f, 0.9989205f, 0.999611259f, 0.999956787f,
0.999956787f, 0.999611259f, 0.9989205f, 0.99788487f, 0.996505201f, 0.994782388f,
0.992717624f, 0.990312338f, 0.9875682f, 0.984487116f, 0.981071174f, 0.977322817f,
0.973244548f, 0.968839228f, 0.964109898f, 0.959059834f, 0.953692496f, 0.948011637f,
0.942021132f, 0.935725152f, 0.929128051f, 0.922234356f, 0.915048897f, 0.907576561f,
0.899822593f, 0.891792297f, 0.883491218f, 0.874925137f, 0.866099894f, 0.857021689f,
0.847696722f, 0.838131487f, 0.828332543f, 0.818306684f, 0.808060884f, 0.797602117f,
0.786937773f, 0.776075065f, 0.765021563f, 0.753784895f, 0.74237287f, 0.730793357f,
0.719054282f, 0.70716387f, 0.695130289f, 0.682961822f, 0.670666933f, 0.658254087f,
0.645731866f, 0.633108914f, 0.620393991f, 0.607595861f, 0.594723403f, 0.58178544f,
0.568790972f, 0.555748999f, 0.542668462f, 0.52955842f, 0.516427994f, 0.503286183f,
0.490142077f, 0.477004826f, 0.46388346f, 0.450787038f, 0.43772465f, 0.424705267f,
0.411737949f, 0.398831606f, 0.385995209f, 0.37323758f, 0.36056757f, 0.34799391f,
0.335525304f, 0.323170364f, 0.310937643f, 0.298835546f, 0.286872506f, 0.27505675f,
0.263396442f, 0.25189966f, 0.24057436f, 0.229428321f, 0.218469277f, 0.207704797f,
0.197142333f, 0.186789155f, 0.176652446f, 0.16673921f, 0.157056287f, 0.147610351f,
0.138407975f, 0.129455477f, 0.12075907f, 0.112324752f, 0.104158357f, 0.0962655246f,
0.0886517167f, 0.0813221857f, 0.0742820054f, 0.0675360337f, 0.0610889383f, 0.0549451709f,
0.0491089821f, 0.0435844027f, 0.038375251f, 0.033485122f, 0.0289174058f, 0.0246752501f,
0.0207615905f, 0.0171791315f, 0.0139303477f, 0.0110174855f, 0.00844255742f, 0.00620734366f,
0.00431338791f, 0.00276200008f, 0.00155425165f, 0.000690977438f, 0.00017277422f, 0.0f,
};
#endif
+69
View File
@@ -0,0 +1,69 @@
#ifndef XOMBE_DSP_TABLES_H
#define XOMBE_DSP_TABLES_H
/* constant-argument trigonometry, roots, and init-time tables, generated by scripts/gen_dsp_tables.py */
#include "../state.h"
#include "tables.h"
#define XOMBE_GRAIN_RAMP 16 /* grain fade length, samples */
/* DCT-II kernels cos(pi*m*(i + 1/2)/J): 8-point one between PRBA vector and block means, and one per spectral
block length J 1..XOMBE_DCT_BLK_J_MAX for m = 0..XOMBE_DCT_BLK_ROWS - 1
block J's kernel starts at xombe__dct_blk + xombe__dct_blk_off[J], row m at offset m*J */
#define XOMBE_DCT_BLK_J_MAX 17
#define XOMBE_DCT_BLK_ROWS 6
#define XOMBE_DCT_BLK_SIZE (XOMBE_DCT_BLK_ROWS * XOMBE_DCT_BLK_J_MAX * (XOMBE_DCT_BLK_J_MAX + 1) / 2)
extern const float xombe__dct8[8][8];
extern const unsigned short xombe__dct_blk_off[XOMBE_DCT_BLK_J_MAX + 1];
extern const float xombe__dct_blk[XOMBE_DCT_BLK_SIZE];
/* cos, sin of pi*j/XOMBE_GRAIN_RAMP: grain fades at integer offsets, rotated by the grain's fractional start */
extern const float xombe__ramp_cos[XOMBE_GRAIN_RAMP];
extern const float xombe__ramp_sin[XOMBE_GRAIN_RAMP];
/* half-frame crossfades: sqrt(n/N) = xombe__sqrt_n[n] * xombe__rsqrt_half[N - XOMBE_HALF_MIN] */
extern const float xombe__sqrt_n[XOMBE_HALF_MAX + 1];
extern const float xombe__rsqrt_half[XOMBE_HALF_MAX - XOMBE_HALF_MIN + 1];
/* 1/2*log2(L), per-harmonic share of the frame gain, entry 0 unused */
extern const float xombe__half_log2[XOMBE_LMAX + 1];
/* sqrt(xombe__w0[b]*xombe__w0[b + 1]), log-scale midpoint of neighbouring pitches */
extern const float xombe__w0_mid[XOMBE_B0_COUNT - 1];
/* FFT twiddles exp(-2*pi*i*k/XOMBE_TW_N), an n-point transform takes every (XOMBE_TW_N/n)-th */
#define XOMBE_TW_N 1024
extern const xombe_cpx xombe__fft_tw[XOMBE_TW_N / 2];
#if XOMBE_HAVE_ENCODER
/* base analysis window, Hamming 0.54 - 0.46*cos(2*pi*i/(n - 1)) */
extern const float xombe__base_win[XOMBE_BASE_WINDOW];
/* pitch tracker low-pass, quarter-band sinc under a Hamming taper, unit DC gain */
extern const float xombe__pitch_lpf[2 * XOMBE_PITCH_LPF_HALF + 1];
/* pitch tracker window w^2/sum(w^2) for Hamming w of XOMBE_PITCH_WIN, and the sum of its squares */
extern const float xombe__pitch_w2[XOMBE_PITCH_WIN];
extern const float xombe__pitch_sum_w4;
#if XOMBE_KERNELS_Q15
/* xombe__pitch_w2[0..XOMBE_PITCH_HALF] * xombe__pitch_w2_q15_gain rounded (peak 32767), the rest mirrors it
(kern_q15_pitch.c) */
extern const int16_t xombe__pitch_w2_q15[XOMBE_PITCH_HALF + 1];
extern const float xombe__pitch_w2_q15_gain;
#endif
#if XOMBE_KERNELS_Q15
/* pitch low-pass taps for kern_q15_pitch.c, g[m] = h[2*XOMBE_PITCH_LPF_HALF - m] * xombe__pitch_lpf_q15_gain rounded,
as int16 pairs, row 0 (g[0], g[1]), (g[2], g[3]), ... zero-padded, row 1 one later, (0, g[0]), (g[1], g[2]), ... */
#define XOMBE_PITCH_LPF_PAIRS (XOMBE_PITCH_LPF_HALF + 1)
extern const uint32_t xombe__pitch_lpf_q15[2][XOMBE_PITCH_LPF_PAIRS];
extern const float xombe__pitch_lpf_q15_gain;
/* encoder analysis FFT twiddles for XOMBE_FFT / 2 complex points (kern_q15_spec.c), exp(-2*pi*i*j/(XOMBE_FFT / 2))
for j < XOMBE_FFT / 4, Q15 rounded and held below 1, as int16 pairs (re, im) */
extern const uint32_t xombe__fft_tw_q15[XOMBE_FFT / 4];
/* tone detector FFT twiddles for XOMBE_TONE_FFT / 2 complex points (tone_detect.c), as xombe__fft_tw_q15 */
extern const uint32_t xombe__tone_tw_q15[XOMBE_TONE_FFT / 4];
#endif
/* tone detector Hann window, 0.5 - 0.5*cos(2*pi*i/(n - 1)) */
extern const float xombe__tone_win[XOMBE_TONE_SEG];
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More