mirror of
https://github.com/ratspeak/rsLXST
synced 2026-11-23 15:30:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19ac89ec7a | ||
|
|
92baad3898 | ||
|
|
09a47976fb | ||
|
|
4370a4153a | ||
|
|
e9e053a038 | ||
|
|
fe3128964b | ||
|
|
f323457be5 | ||
|
|
f52c805d7b | ||
|
|
0a5c434fc8 | ||
|
|
d41528031f | ||
|
|
b39e23cbec | ||
|
|
2b04b62e79 | ||
|
|
7511e99bf1 | ||
|
|
c140942a13 | ||
|
|
ff602499fa | ||
|
|
7e6e962746 | ||
|
|
e8a3a67132 | ||
|
|
2a7357e0d1 | ||
|
|
ed9dfdd74b | ||
|
|
e01e28693d | ||
|
|
131b592355 | ||
|
|
958c7f7932 | ||
|
|
15a749ed48 | ||
|
|
73947604ba | ||
|
|
0b2a55aadd | ||
|
|
edc6187472 | ||
|
|
4613264079 | ||
|
|
db48665199 | ||
|
|
74b0fb8fd8 | ||
|
|
aeb400006b | ||
|
|
a2f19db8ea | ||
|
|
9f84f6e466 | ||
|
|
6394464f11 | ||
|
|
9c70a9d67e | ||
|
|
57171563b0 | ||
|
|
56da627f6b | ||
|
|
585405cb3b | ||
|
|
54f8711730 | ||
|
|
f4d6daab25 | ||
|
|
cd66bad49a | ||
|
|
1c037655b2 | ||
|
|
cb857c69d0 | ||
|
|
dff93e73af | ||
|
|
b6d7d921f5 | ||
|
|
65c21b6e94 | ||
|
|
c95af2b0ae | ||
|
|
2c680d8028 | ||
|
|
8f8e664427 | ||
|
|
9d685e4c60 | ||
|
|
34545cf49b | ||
|
|
c1c877618f | ||
|
|
63670e3bd6 | ||
|
|
20387ae908 | ||
|
|
ead1652fda | ||
|
|
07ab7d7955 | ||
|
|
2e7a616498 | ||
|
|
37a578d525 | ||
|
|
4cf9812c36 | ||
|
|
abbe8d793f | ||
|
|
81cc0c1681 | ||
|
|
df41edab47 | ||
|
|
5638cf7cf0 | ||
|
|
855d44c930 | ||
|
|
8acab49832 | ||
|
|
3e9f2ca8f3 | ||
|
|
ae538650b9 | ||
|
|
208560655f | ||
|
|
5c9c945300 | ||
|
|
7dfb98e1c8 | ||
|
|
7a01ece94f | ||
|
|
87dd25958f | ||
|
|
df9228e744 | ||
|
|
d9d62f3c7f | ||
|
|
b1e6a3f6f8 | ||
|
|
fe1f1ada43 | ||
|
|
6f7b608a17 | ||
|
|
e8c1a8d85a | ||
|
|
f9c97a011f | ||
|
|
ba573034d4 | ||
|
|
49d6607eed | ||
|
|
5a0645568f | ||
|
|
7d3e17c71d | ||
|
|
f301dfbda6 | ||
|
|
f55a969161 | ||
|
|
d65e26bf57 | ||
|
|
b1b87860c4 | ||
|
|
719ec1edb6 | ||
|
|
9ee2807e02 | ||
|
|
2c840613d6 | ||
|
|
22ad7c89b8 | ||
|
|
34960adc61 | ||
|
|
9252821447 | ||
|
|
6bd80b8fcf | ||
|
|
31c2057e53 | ||
|
|
65b6961a5c | ||
|
|
8bbc037d86 | ||
|
|
c149dbab3c | ||
|
|
a3dd7c4e2b | ||
|
|
f45e119bed | ||
|
|
f228e2e1b1 | ||
|
|
2e4e4409a3 | ||
|
|
2e92c69b0e | ||
|
|
e776d68b9b | ||
|
|
0df9569249 | ||
|
|
3b35564c63 | ||
|
|
ac541ed227 | ||
|
|
5bc258208d | ||
|
|
68df322377 | ||
|
|
9ef5fb3a4d | ||
|
|
21a54b7784 | ||
|
|
af89a03094 | ||
|
|
43207705af | ||
|
|
5458202e34 | ||
|
|
8d5618252d | ||
|
|
0a8735be87 | ||
|
|
63c0f413b0 | ||
|
|
3205cb73b9 | ||
|
|
c53c634dfe | ||
|
|
262c883d20 | ||
|
|
86dfa3d012 | ||
|
|
77fc059448 | ||
|
|
3bc4d9d8ec | ||
|
|
260e41ada6 | ||
|
|
18ed05d239 | ||
|
|
9f06e3371b | ||
|
|
fd81d7155c | ||
|
|
47827c9e2a | ||
|
|
a381eab55c | ||
|
|
1457a03750 | ||
|
|
cba6a32706 | ||
|
|
7bf08ebd32 | ||
|
|
f01978c115 | ||
|
|
25a0344516 | ||
|
|
e3f80815bc | ||
|
|
65ecb0733f |
No files matched your search
+187
-30
@@ -9,32 +9,79 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
RSLXST_RSRETICULUM_VERSION: 1.5.1
|
||||
RSLXST_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
|
||||
RSLXST_PYTHON_LXST_COMMIT: 6a329bf6d956ca8b15077d4c470afe4cb7c669cc
|
||||
RSLXST_PYTHON_RNS_COMMIT: cff4d03fdbd6bfb63b765280cd944756ac5cce8d
|
||||
|
||||
jobs:
|
||||
api-compat:
|
||||
name: Public API baseline
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
path: rsLXST
|
||||
fetch-depth: 0
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: ${{ github.repository_owner }}/rsReticulum
|
||||
ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}
|
||||
path: rsReticulum
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772
|
||||
with:
|
||||
toolchain: nightly-2026-08-01
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
workspaces: rsLXST -> target
|
||||
cache-bin: true
|
||||
- name: Install API snapshot tool
|
||||
run: cargo install cargo-public-api --version 0.52.0 --locked
|
||||
- name: Check reviewed public API baseline
|
||||
run: python3 tools/check-api-baseline.py
|
||||
working-directory: rsLXST
|
||||
- name: Check manifest and feature contract
|
||||
run: python3 tools/check-api-manifest.py
|
||||
working-directory: rsLXST
|
||||
- name: Check additions-only compatibility floor
|
||||
run: python3 tools/check-api-compatibility.py
|
||||
working-directory: rsLXST
|
||||
- name: Check canonical and retained external consumers
|
||||
run: cargo check --manifest-path api/fixtures/Cargo.toml --locked
|
||||
working-directory: rsLXST
|
||||
|
||||
lint:
|
||||
name: Lint and Docs
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
path: rsLXST
|
||||
- uses: actions/checkout@v5
|
||||
fetch-depth: 0
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: ${{ github.repository_owner }}/rsReticulum
|
||||
ref: main
|
||||
ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}
|
||||
path: rsReticulum
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: markqvist/LXST
|
||||
ref: ${{ env.RSLXST_PYTHON_LXST_COMMIT }}
|
||||
path: upstream/LXST
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: markqvist/Reticulum
|
||||
ref: ${{ env.RSLXST_PYTHON_RNS_COMMIT }}
|
||||
path: upstream/Reticulum
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772
|
||||
with:
|
||||
toolchain: 1.96.0
|
||||
components: clippy, rustfmt
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
workspaces: rsLXST -> target
|
||||
cache-bin: false
|
||||
@@ -42,9 +89,15 @@ jobs:
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config libopus0 libogg0
|
||||
- run: cargo fmt --all -- --check
|
||||
working-directory: rsLXST
|
||||
- run: cargo clippy --workspace -- -D warnings
|
||||
- name: Check source-release contract
|
||||
run: python3 tools/check-source-release.py
|
||||
working-directory: rsLXST
|
||||
- run: cargo doc --workspace --no-deps
|
||||
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
working-directory: rsLXST
|
||||
- name: Build embedding examples
|
||||
run: cargo build -p lxst-telephony --examples --locked
|
||||
working-directory: rsLXST
|
||||
- run: cargo doc --workspace --no-deps --locked
|
||||
working-directory: rsLXST
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
@@ -58,27 +111,31 @@ jobs:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
path: rsLXST
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: ${{ github.repository_owner }}/rsReticulum
|
||||
ref: main
|
||||
ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}
|
||||
path: rsReticulum
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: markqvist/LXST
|
||||
ref: ${{ env.RSLXST_PYTHON_LXST_COMMIT }}
|
||||
path: upstream/LXST
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: markqvist/Reticulum
|
||||
ref: ${{ env.RSLXST_PYTHON_RNS_COMMIT }}
|
||||
path: upstream/Reticulum
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/setup-python@v6
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772
|
||||
with:
|
||||
toolchain: 1.96.0
|
||||
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
workspaces: rsLXST -> target
|
||||
cache-bin: false
|
||||
@@ -90,11 +147,71 @@ jobs:
|
||||
run: brew install opus libogg
|
||||
- name: Install Python interop deps
|
||||
run: python -m pip install --upgrade pip && python -m pip install numpy cryptography pyserial cffi "audioop-lts; python_version >= '3.13'"
|
||||
- run: cargo test --workspace
|
||||
# The voice relay interop tests run an rnsd-rs transport node.
|
||||
- run: cargo build -p rns-tools --bin rnsd-rs --locked
|
||||
working-directory: rsReticulum
|
||||
- run: cargo test --workspace --locked
|
||||
working-directory: rsLXST
|
||||
|
||||
embedded-msrv:
|
||||
name: Embedded Rust 1.87 MSRV
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09
|
||||
with:
|
||||
path: rsLXST
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09
|
||||
with:
|
||||
repository: ${{ github.repository_owner }}/rsReticulum
|
||||
ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}
|
||||
path: rsReticulum
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772
|
||||
with:
|
||||
toolchain: 1.87.0
|
||||
- name: Check no_std MCU libraries at their independent compiler floor
|
||||
working-directory: rsLXST
|
||||
run: cargo check -p lxst-codec2 -p lxst-embedded --lib --locked
|
||||
|
||||
msrv:
|
||||
name: Rust 1.89 MSRV
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
path: rsLXST
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: ${{ github.repository_owner }}/rsReticulum
|
||||
ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}
|
||||
path: rsReticulum
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: markqvist/LXST
|
||||
ref: ${{ env.RSLXST_PYTHON_LXST_COMMIT }}
|
||||
path: upstream/LXST
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: markqvist/Reticulum
|
||||
ref: ${{ env.RSLXST_PYTHON_RNS_COMMIT }}
|
||||
path: upstream/Reticulum
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
workspaces: rsLXST -> target
|
||||
cache-bin: false
|
||||
- name: Install Linux system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config libopus0 libogg0
|
||||
- name: Clippy (all targets and features)
|
||||
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
working-directory: rsLXST
|
||||
|
||||
mobile-check:
|
||||
name: Check (${{ matrix.target }})
|
||||
name: Clippy (${{ matrix.target }}, ${{ matrix.toolchain }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -103,40 +220,80 @@ jobs:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
target: aarch64-linux-android
|
||||
toolchain: 1.96.0
|
||||
- os: ubuntu-latest
|
||||
target: armv7-linux-androideabi
|
||||
toolchain: 1.96.0
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-linux-android
|
||||
toolchain: 1.96.0
|
||||
- os: macos-latest
|
||||
target: aarch64-apple-ios
|
||||
toolchain: 1.96.0
|
||||
- os: ubuntu-latest
|
||||
target: aarch64-linux-android
|
||||
toolchain: 1.89.0
|
||||
- os: ubuntu-latest
|
||||
target: armv7-linux-androideabi
|
||||
toolchain: 1.89.0
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-linux-android
|
||||
toolchain: 1.89.0
|
||||
- os: macos-latest
|
||||
target: aarch64-apple-ios
|
||||
toolchain: 1.89.0
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
path: rsLXST
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
repository: ${{ github.repository_owner }}/rsReticulum
|
||||
ref: main
|
||||
ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}
|
||||
path: rsReticulum
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772
|
||||
with:
|
||||
toolchain: ${{ matrix.toolchain }}
|
||||
targets: ${{ matrix.target }}
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
workspaces: rsLXST -> target
|
||||
cache-bin: false
|
||||
- uses: nttld/setup-ndk@v1
|
||||
if: matrix.target == 'aarch64-linux-android'
|
||||
- uses: nttld/setup-ndk@ed92fe6cadad69be94a966a7ee3271275e62f779 # v1
|
||||
if: contains(matrix.target, 'android')
|
||||
id: setup-ndk
|
||||
with:
|
||||
ndk-version: r27d
|
||||
add-to-path: false
|
||||
- name: Check Android
|
||||
- name: Clippy Android
|
||||
if: matrix.target == 'aarch64-linux-android'
|
||||
env:
|
||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
AR_aarch64_linux_android: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar
|
||||
CC_aarch64_linux_android: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android24-clang
|
||||
CXX_aarch64_linux_android: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android24-clang++
|
||||
run: cargo check --workspace --target ${{ matrix.target }}
|
||||
run: cargo clippy --workspace --all-targets --all-features --target ${{ matrix.target }} --locked -- -D warnings
|
||||
working-directory: rsLXST
|
||||
- name: Check iOS
|
||||
- name: Clippy Android ARMv7
|
||||
if: matrix.target == 'armv7-linux-androideabi'
|
||||
env:
|
||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
AR_armv7_linux_androideabi: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar
|
||||
CC_armv7_linux_androideabi: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi24-clang
|
||||
CXX_armv7_linux_androideabi: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi24-clang++
|
||||
run: cargo clippy --workspace --all-targets --all-features --target ${{ matrix.target }} --locked -- -D warnings
|
||||
working-directory: rsLXST
|
||||
- name: Clippy Android x86_64
|
||||
if: matrix.target == 'x86_64-linux-android'
|
||||
env:
|
||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
AR_x86_64_linux_android: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar
|
||||
CC_x86_64_linux_android: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android24-clang
|
||||
CXX_x86_64_linux_android: ${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android24-clang++
|
||||
run: cargo clippy --workspace --all-targets --all-features --target ${{ matrix.target }} --locked -- -D warnings
|
||||
working-directory: rsLXST
|
||||
- name: Clippy iOS
|
||||
if: matrix.target == 'aarch64-apple-ios'
|
||||
run: cargo check --workspace --target ${{ matrix.target }}
|
||||
run: cargo clippy --workspace --all-targets --all-features --target ${{ matrix.target }} --locked -- -D warnings
|
||||
working-directory: rsLXST
|
||||
@@ -1,5 +1,6 @@
|
||||
.DS_Store
|
||||
target/
|
||||
api/fixtures/target/
|
||||
|
||||
# Runtime data and local identities
|
||||
.reticulum/
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 0.4.0 - 2026-11-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Call modes**: calls can be full or half duplex, as in LXST 0.6.0, and switch during a call. `TelephonyControl::Call` takes a `mode`; `None` is full duplex.
|
||||
- **Stamped calls**: call announces and link requests carry stamps when Reticulum's `[stamps]` settings ask for them, and call links use Link MTU discovery.
|
||||
|
||||
### Fixed and improved
|
||||
|
||||
- Calls connect as in LXST 0.6.0: the callee is established as soon as it answers, and a lost setup packet no longer ends a call. Check `audio_started` to know when audio is running.
|
||||
- An outgoing call ends if the callee doesn't ring within `connect_timeout` (5 seconds by default), and the line is busy while a call looks for its path.
|
||||
- `lxst-embedded` sessions use LXST 0.6.0's ring, wait, and connect times; change them with `SessionConfig::times`.
|
||||
- The first announce goes out 5 seconds after start, with no startup burst by default.
|
||||
- `opus-rs` 0.1.42 fixes a decoder crash on a crafted packet, and a damaged frame is now skipped instead of dropping its whole packet.
|
||||
|
||||
### Build and compatibility
|
||||
|
||||
- rsLXST now uses rsReticulum `~1.5.0`, whose default storage builds a bundled SQLite and needs a C compiler.
|
||||
- API changes, including the removed answer retry, call modes, and async outgoing link calls, are listed in the [migration guide](api/migrations/next.md).
|
||||
|
||||
## 0.3.1 - 2026-11-08
|
||||
|
||||
- Telephony wakes on Link events instead of polling, polls once a second when
|
||||
idle, and sends announces on their own deadline instead of the idle tick.
|
||||
- Replaced the AGPL license text with the LXST license.
|
||||
- Uses the rsReticulum `~1.4.0` dependency line; the `v0.3.0` release used
|
||||
`~1.3.0`.
|
||||
- Retire outgoing calls when Link-request dispatch or handshake queue admission
|
||||
fails, and keep established traffic bound to the original interface owner.
|
||||
|
||||
## 0.3.0 - 2026-10-12
|
||||
|
||||
### Added
|
||||
|
||||
- Added native Codec2 telephony streams and revocable push-to-talk input leases, with explicit audio reconfiguration and completion events.
|
||||
|
||||
### Embedded sessions
|
||||
|
||||
- Reduce 700C encoding work on constrained devices while preserving bit-exact output.
|
||||
|
||||
- Implement bounded native Codec2 700C and advertise standard ULBW alongside
|
||||
VLBW/LBW, with C-oracle fixtures and bidirectional Python/Rust interoperability.
|
||||
Device CPU, stack, acoustic quality and RF usability still require qualification.
|
||||
|
||||
- Add a no_std LXST boundary with fixed parser/queue limits and authenticated,
|
||||
accepted, audio-ready PTT gating. Share profile IDs, codec aggregation and
|
||||
call transitions with the host API. Bound profile fallback and answer retries;
|
||||
fence audio reconfiguration completions and require release after a Talk timeout.
|
||||
|
||||
### Codec foundations
|
||||
|
||||
- Add an opt-in, allocation-free `no_std` native Rust Codec2 crate for 1600/3200
|
||||
bit/s. Initialize in caller-owned storage; isolate decoder randomness; use the
|
||||
same Rust math on host and MCU; reject wrong native frame sizes. Correct the
|
||||
inherited real-FFT input-copy truncation. Preserve upstream source/license
|
||||
provenance. Target audio, CPU/stack and live integration remain separate gates.
|
||||
|
||||
- Add a fixed-profile Codec2 packet adapter over caller-owned PCM16/output
|
||||
buffers and an application-supplied native backend. Reject malformed lengths,
|
||||
unexpected modes and insufficient capacity before codec processing; stop
|
||||
further processing after a backend failure. Preserve native 700C frame padding.
|
||||
Native Codec2 telephony streams use this adapter boundary.
|
||||
|
||||
### Build and compatibility
|
||||
|
||||
- Raised the host source-build minimum to Rust 1.89 and qualified the corresponding protocol dependency update.
|
||||
- Kept the standalone `lxst-codec2` and `lxst-embedded` minimum at Rust 1.87, with an independent MCU library check.
|
||||
- Added variants to the experimental telephony event, control, and error enums; downstream exhaustive matches must handle the new cases.
|
||||
|
||||
- Migrated rsReticulum compatibility to the explicit `~1.3.0` line for nullable
|
||||
interface discovery and bounded RNode announce admission. Codec dependencies,
|
||||
telephony APIs and the standalone embedded compiler minimum are unchanged.
|
||||
|
||||
|
||||
## 0.2.0 - 2026-08-17
|
||||
|
||||
- Document the existing registered `TelephonyService` seam as the canonical
|
||||
experimental embedding boundary, with compiled canonical/retained consumer
|
||||
contracts and no public API or runtime behavior change.
|
||||
|
||||
- Classified all three pre-1.0 packages as experimental and added pinned,
|
||||
CI-enforced public API snapshots without changing visibility or signatures.
|
||||
- Replace the locally modified Opus 0.1.19 snapshot with exact upstream
|
||||
`opus-rs` 0.1.29 using heap-backed codec state, raise the unified stack MSRV
|
||||
to Rust 1.87, retain Android ARMv7 support, and explicitly exclude Android
|
||||
i686 from the supported artifact matrix.
|
||||
- Record the exact vendored `opus-rs` lineage and local patch ledger, and add a
|
||||
locked, CI-checked production dependency license inventory.
|
||||
|
||||
- Replaced finite telephony announce handlers with validated destination
|
||||
recall and one deadline-bound path request, while preserving cached-path
|
||||
refresh, stale-path removal, final path confirmation, and hop refresh.
|
||||
- Pinned every established telephony Link to the immutable interface that
|
||||
completed its handshake; wrong-interface traffic is rejected before crypto,
|
||||
accounting, or audio processing, and interface loss closes the call.
|
||||
- Moved signalling, identification, keepalives, and close packets to ordered
|
||||
typed Link endpoint delivery. Final teardown now drains before atomic endpoint
|
||||
and temporary-destination removal.
|
||||
- Kept realtime media bounded and receipt-free with exact-interface
|
||||
best-effort delivery and explicit backpressure drop accounting.
|
||||
- Made live Python Telephone/TCP interoperability tests opt-in so the ordinary
|
||||
locked workspace test gate remains local and non-live.
|
||||
- Advanced the experimental source boundary to 0.2 for the current telephony,
|
||||
exact-Link, Opus, and rsReticulum 1.2 integration APIs.
|
||||
|
||||
## 0.1.2 - 2026-07-26
|
||||
|
||||
- Updated the Reticulum dependency baseline to rsReticulum 1.1.0.
|
||||
- Aligned telephony compatibility fixtures with current interface and
|
||||
responder Link registration behaviour.
|
||||
Generated
+161
-39
@@ -11,6 +11,19 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -70,15 +83,6 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.11.1"
|
||||
@@ -103,6 +107,16 @@ dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cesu8"
|
||||
version = "1.1.0"
|
||||
@@ -129,6 +143,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -261,6 +276,18 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.4.1"
|
||||
@@ -273,6 +300,12 @@ version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -377,6 +410,15 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
@@ -392,6 +434,15 @@ version = "0.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
|
||||
dependencies = [
|
||||
"hashbrown 0.14.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
@@ -526,6 +577,23 @@ version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.30.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@@ -547,9 +615,16 @@ version = "0.4.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "lxst-codec2"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lxst-core"
|
||||
version = "0.1.1"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"half",
|
||||
"hex",
|
||||
@@ -560,9 +635,18 @@ dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lxst-embedded"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"lxst-codec2",
|
||||
"lxst-core",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lxst-rns"
|
||||
version = "0.1.1"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"lxst-core",
|
||||
@@ -576,10 +660,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lxst-telephony"
|
||||
version = "0.1.1"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
"lxst-codec2",
|
||||
"lxst-core",
|
||||
"lxst-rns",
|
||||
"rns-crypto",
|
||||
@@ -613,9 +698,9 @@ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.0"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
|
||||
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
@@ -643,29 +728,21 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
@@ -678,13 +755,11 @@ checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"block2",
|
||||
"libc",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
@@ -696,7 +771,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "opus-rs"
|
||||
version = "0.1.19"
|
||||
version = "0.1.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bafbcaf2ed381cdf68ced4ed8d16517de90ffd7424e36f0b9e45d67fbe30b1f9"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
@@ -737,6 +814,12 @@ dependencies = [
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
@@ -926,7 +1009,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -944,34 +1027,41 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
"rand 0.8.6",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"rns-crypto",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
"if-addrs",
|
||||
"jni",
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand 0.8.6",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
"rns-transport",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
@@ -985,9 +1075,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
"rand 0.8.6",
|
||||
"rmpv",
|
||||
"rns-crypto",
|
||||
@@ -995,12 +1086,13 @@ dependencies = [
|
||||
"rns-wire",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1009,6 +1101,7 @@ dependencies = [
|
||||
"rns-crypto",
|
||||
"rns-link",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -1016,7 +1109,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1035,14 +1128,16 @@ dependencies = [
|
||||
"serde",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1052,6 +1147,7 @@ dependencies = [
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
"rns-wire",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"subtle",
|
||||
"thiserror 2.0.18",
|
||||
@@ -1061,13 +1157,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "1.0.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"rns-crypto",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.32.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
@@ -1228,6 +1338,12 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
@@ -1442,6 +1558,12 @@ version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
|
||||
+16
-13
@@ -2,15 +2,18 @@
|
||||
resolver = "2"
|
||||
members = [
|
||||
"crates/lxst-core",
|
||||
"crates/lxst-codec2",
|
||||
"crates/lxst-embedded",
|
||||
"crates/lxst-rns",
|
||||
"crates/lxst-telephony",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.1"
|
||||
version = "0.4.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
license-file = "LICENSE"
|
||||
rust-version = "1.89"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
rmpv = "1"
|
||||
@@ -21,16 +24,16 @@ bytes = "1"
|
||||
tokio = { version = "1", features = ["sync", "time", "rt", "macros"] }
|
||||
half = "2"
|
||||
proptest = "1"
|
||||
opus-rs = { path = "vendor/opus-rs" }
|
||||
opus-rs = { version = "=0.1.42", default-features = false, features = ["heap"] }
|
||||
serial_test = "3"
|
||||
|
||||
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.0.0" }
|
||||
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.0.0" }
|
||||
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.0.0" }
|
||||
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.0.0" }
|
||||
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.0.0" }
|
||||
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.0.0" }
|
||||
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.0.0" }
|
||||
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.5.1" }
|
||||
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.5.1" }
|
||||
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.5.1" }
|
||||
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.5.1" }
|
||||
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.5.1" }
|
||||
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.5.1" }
|
||||
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.5.1" }
|
||||
|
||||
lxst-core = { path = "crates/lxst-core", version = "0.1.1" }
|
||||
lxst-rns = { path = "crates/lxst-rns", version = "0.1.1" }
|
||||
lxst-core = { path = "crates/lxst-core", version = "0.4.0" }
|
||||
lxst-rns = { path = "crates/lxst-rns", version = "0.4.0" }
|
||||
@@ -1,661 +1,7 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
LXST Copyright 2026 Mark Qvist.
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
This implementation of LXST is derived from the LXST reference implementation,
|
||||
and used under license for Ratspeak, for non-commercial use only.
|
||||
No derivatives or use outside Ratspeak is permitted.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
For commercial licensing inquiries, contact license@unsigned.io
|
||||
@@ -4,10 +4,10 @@
|
||||
|
||||
**Rust LXST telephony and media streaming for Reticulum.**
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://github.com/markqvist/LXST)
|
||||
[](#feature-status)
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://github.com/markqvist/LXST)
|
||||
[](#release-scope)
|
||||
|
||||
[rsLXMF](https://github.com/ratspeak/rsLXMF) |
|
||||
[Ratspeak](https://github.com/ratspeak/Ratspeak) |
|
||||
@@ -18,19 +18,15 @@
|
||||
|
||||
---
|
||||
|
||||
rsLXST is a Rust implementation of [LXST](https://github.com/markqvist/LXST), the Lightweight Extensible Signal
|
||||
Transport used for real-time voice calls and other media streams over Reticulum. This is not a
|
||||
fork of LXST; it is LXST written in a different language with interoperability
|
||||
as the primary focus. Python LXST remains the source-of-truth
|
||||
implementation, do not treat this repository as one.
|
||||
rsLXST is a Rust port of [LXST](https://github.com/markqvist/LXST), Mark Qvist's
|
||||
Lightweight Extensible Signal Transport for real-time voice calls and other
|
||||
media streams over Reticulum. It was written from the reference source with
|
||||
interoperability as the primary focus.
|
||||
|
||||
The current rsLXST is experimental and incomplete. It provides LXST wire codecs,
|
||||
Reticulum link media packet boundaries, a telephony runtime, and Opus stream
|
||||
integration for applications (such as Ratspeak).
|
||||
|
||||
The first public target is interoperable Opus
|
||||
telephony, not complete feature parity with
|
||||
the reference implementation LXST.
|
||||
rsLXST is Ratspeak's voice component. The LXST author licenses this port for
|
||||
use in Ratspeak only, for non-commercial use, with no derivatives or use outside
|
||||
Ratspeak; see [License](#license). The build, test, and API notes below document
|
||||
the code for Ratspeak development.
|
||||
|
||||
## Contents
|
||||
|
||||
@@ -39,20 +35,17 @@ the reference implementation LXST.
|
||||
- [Test It](#test-it)
|
||||
- [Crate Layout](#crate-layout)
|
||||
- [Using Telephony](#using-telephony)
|
||||
- [Contributing](#contributing)
|
||||
- [Rust API](api/README.md)
|
||||
- [License](#license)
|
||||
- [Third-party licenses](#third-party-licenses)
|
||||
|
||||
## Release Scope
|
||||
|
||||
The experimental release is to cover basic voice calls, with several features still unsupported:
|
||||
|
||||
- `rnphone` parity and `rnphone-rs` usage.
|
||||
- Full Codec2 support.
|
||||
- Deeper audio support: microphone/source backends, filters, AGC, etc.
|
||||
- Broadcast, stream, and non-telephony LXST primitives.
|
||||
|
||||
Those are expected future work. They should not be implied by the first public
|
||||
Opus telephony release.
|
||||
The implemented application path covers telephony signalling, full- and
|
||||
half-duplex call modes, and negotiated Opus or native Codec2 media over
|
||||
Reticulum Links. It does not provide a
|
||||
`rnphone-rs` client, a general platform microphone/speaker backend, or LXST's
|
||||
non-telephony features.
|
||||
|
||||
## Build It
|
||||
|
||||
@@ -72,9 +65,13 @@ mkdir ratspeak-src
|
||||
cd ratspeak-src
|
||||
git clone https://github.com/ratspeak/rsReticulum
|
||||
git clone https://github.com/ratspeak/rsLXST
|
||||
git -C rsReticulum checkout --detach v1.5.0
|
||||
git -C rsLXST checkout --detach v0.4.0
|
||||
cd rsLXST
|
||||
```
|
||||
|
||||
The commands below run from that `rsLXST` directory.
|
||||
|
||||
### macOS
|
||||
|
||||
Install Rust with `rustup`, then install Apple's command-line build tools:
|
||||
@@ -86,8 +83,7 @@ xcode-select --install
|
||||
Build the workspace:
|
||||
|
||||
```bash
|
||||
cd rsLXST
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
### Linux / Raspberry Pi
|
||||
@@ -116,8 +112,7 @@ sudo pacman -S --needed base-devel pkgconf
|
||||
Build the workspace:
|
||||
|
||||
```bash
|
||||
cd rsLXST
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
### Windows
|
||||
@@ -128,8 +123,7 @@ Build Tools, install the "Desktop development with C++" workload.
|
||||
Build from PowerShell:
|
||||
|
||||
```powershell
|
||||
cd rsLXST
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
## Test It
|
||||
@@ -137,46 +131,57 @@ cargo build --release
|
||||
Run the workspace test gate:
|
||||
|
||||
```bash
|
||||
cargo test --workspace
|
||||
cargo test --workspace --locked
|
||||
```
|
||||
|
||||
Run the local CI gate:
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace -- -D warnings
|
||||
cargo test --workspace
|
||||
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
cargo test --workspace --locked
|
||||
```
|
||||
|
||||
The test gate covers wire codecs, telephony state, profile metadata, Opus
|
||||
stream boundaries, malformed-input handling, the local service runtime, Python
|
||||
LXST wire parity, Reticulum destination parity, and live headless LXST
|
||||
Telephone interop. The Python tests expect upstream LXST at `../upstream/LXST`
|
||||
or `LXST_UPSTREAM_DIR`, and upstream Reticulum at `../upstream/Reticulum`,
|
||||
`RETICULUM_UPSTREAM_DIR`, or sibling `../rsReticulum`.
|
||||
|
||||
For full Python Opus media interop, install a native Opus runtime as well as
|
||||
the Python reference dependencies:
|
||||
The live call tests against Python LXST are not part of ordinary runs. Run
|
||||
them explicitly with:
|
||||
|
||||
```bash
|
||||
python -m pip install numpy cryptography pyserial cffi
|
||||
cargo test -p lxst-telephony --test python_telephone_live_interop -- --ignored
|
||||
```
|
||||
|
||||
Python/reference tests additionally need the reference source checkouts. They
|
||||
expect upstream LXST at `../upstream/LXST` or
|
||||
`LXST_UPSTREAM_DIR`, and upstream Reticulum at `../upstream/Reticulum`,
|
||||
`RETICULUM_UPSTREAM_DIR`, or sibling `../rsReticulum`.
|
||||
|
||||
For full Python Opus media interop, install a native Opus runtime and activate
|
||||
a Python virtual environment. Then install the reference dependencies; Python
|
||||
3.13 and newer also need the `audioop` compatibility package:
|
||||
|
||||
```bash
|
||||
python -m pip install numpy cryptography pyserial cffi "audioop-lts; python_version >= '3.13'"
|
||||
```
|
||||
|
||||
## Crate Layout
|
||||
|
||||
| Crate | Purpose |
|
||||
| --- | --- |
|
||||
| `lxst-codec2` | Allocation-free native Codec2 700C/1600/3200 processing. |
|
||||
| `lxst-embedded` | Bounded `no_std` framing, session/PTT policy and Codec2 integration for Ratspeak's constrained devices. |
|
||||
| `lxst-core` | LXST constants, telephony profiles, signalling values, codec IDs, MessagePack packets, Raw audio frames, Opus encode/decode state, stream packetization, synthetic sources, and jitter buffers. This crate has no Reticulum runtime dependency. |
|
||||
| `lxst-rns` | The Reticulum link-packet boundary for no-receipt LXST signalling and media over active links. It packs outbound LXST packets and decodes inbound link plaintext into typed LXST packet/frame events. |
|
||||
| `lxst-telephony` | The telephony runtime and service layer. It owns call state, caller policy, Reticulum destination registration, announce discovery, outgoing link establishment, typed control/event channels, Opus transmit/receive stream boundaries, timeout handling, and shutdown teardown. |
|
||||
|
||||
## Using Telephony
|
||||
|
||||
Applications normally use `lxst-telephony` through `TelephonyService`, not by
|
||||
Ratspeak uses `lxst-telephony` through `TelephonyService`, not by
|
||||
manually translating Reticulum events. The service registers the local
|
||||
`lxst.telephony` destination, emits startup/periodic announces, owns the call
|
||||
runtime, and exposes typed control and event channels.
|
||||
|
||||
This fragment assumes an initialized Reticulum transport, local identity and
|
||||
remote identity inside an async application:
|
||||
|
||||
```rust
|
||||
use lxst_core::Profile;
|
||||
use lxst_telephony::{TelephonyControl, TelephonyService};
|
||||
@@ -192,6 +197,7 @@ control_tx
|
||||
.send(TelephonyControl::Call {
|
||||
remote_identity,
|
||||
profile: Some(Profile::QualityMedium),
|
||||
mode: None,
|
||||
discovery_timeout: Duration::from_secs(8),
|
||||
})
|
||||
.await?;
|
||||
@@ -205,12 +211,16 @@ traffic. Outgoing announce/path discovery runs asynchronously inside the
|
||||
service, so an unreachable or non-LXST peer does not block hangup, announce,
|
||||
media, or shutdown controls while discovery times out.
|
||||
|
||||
For Opus calls, applications supply and receive `RawAudioFrame` values through
|
||||
The compiled [`service` example](crates/lxst-telephony/examples/service.rs)
|
||||
checks construction and types. It does not run a transport or place a call. The lower-level endpoint and runtime types remain
|
||||
available for compatible specialist use, but are experimental SPI.
|
||||
|
||||
For Opus calls, the host app supplies and receives `RawAudioFrame` values through
|
||||
`StartOpusStream` and `StartOpusReceiveStream`. rsLXST enforces the negotiated
|
||||
LXST profile and reports profile changes, source/sink closure, frame drops, and
|
||||
call-end stream shutdown explicitly.
|
||||
|
||||
Applications still own platform integration:
|
||||
The host app still owns platform integration:
|
||||
|
||||
- contact or peer lookup
|
||||
- UI and call controls
|
||||
@@ -223,14 +233,48 @@ Applications still own platform integration:
|
||||
|
||||
Ratspeak uses this boundary for its native voice-call feature.
|
||||
|
||||
## Contributing
|
||||
## Embedded protocol boundary
|
||||
|
||||
If the issue or contribution belongs upstream as well, start there. Python LXST
|
||||
and Reticulum remain the reference implementations.
|
||||
[`lxst-embedded`](crates/lxst-embedded/README.md) shares the trusted host profile
|
||||
and transition sources, with bounded borrowed MessagePack parsing, fixed media
|
||||
queues and explicit authenticated-session/PTT gates. It is a no_std embedding
|
||||
boundary; board drivers, transport ownership and product integration remain
|
||||
application responsibilities.
|
||||
|
||||
PRs are closed for now until I have time to catch up on everything.
|
||||
## Embedded Codec2 backend
|
||||
|
||||
[`lxst-codec2`](crates/lxst-codec2/README.md) supplies bounded native Rust
|
||||
Codec2 700C, 1600 and 3200 encode/decode with in-place initialization and no
|
||||
allocator. The host telephony and embedded boundaries accept standard ULBW,
|
||||
VLBW and LBW profiles. Device timing, stack and audio qualification remain
|
||||
required before use on hardware. This backend does not implement Opus voice
|
||||
memo containers.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the GNU Affero General
|
||||
Public License v3.0 or later. See [LICENSE](LICENSE).
|
||||
rsLXST is used under the license in [LICENSE](LICENSE), reproduced here:
|
||||
|
||||
```
|
||||
LXST Copyright 2026 Mark Qvist.
|
||||
|
||||
This implementation of LXST is derived from the LXST reference implementation,
|
||||
and used under license for Ratspeak, for non-commercial use only.
|
||||
No derivatives or use outside Ratspeak is permitted.
|
||||
|
||||
For commercial licensing inquiries, contact license@unsigned.io
|
||||
```
|
||||
|
||||
The adapted `lxst-codec2` crate retains its own [NOTICE](crates/lxst-codec2/NOTICE)
|
||||
and upstream license files.
|
||||
|
||||
## Third-party licenses
|
||||
|
||||
Third-party components retain their own licenses. The locked production
|
||||
dependency inventory, including the exact upstream BSD-3-Clause Opus package,
|
||||
checksum, source commit, and preserved notice, is documented in
|
||||
[THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
The host workspace requires Rust 1.89 or later. The `lxst-codec2` and
|
||||
`lxst-embedded` crates retain Rust 1.87 compatibility for Ratspeak's constrained
|
||||
targets; CI checks that independent minimum without the host-only development
|
||||
tests.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
# Third-party licenses
|
||||
|
||||
rsLXST is used under the license in [LICENSE](LICENSE), reproduced here:
|
||||
|
||||
```
|
||||
LXST Copyright 2026 Mark Qvist.
|
||||
|
||||
This implementation of LXST is derived from the LXST reference implementation,
|
||||
and used under license for Ratspeak, for non-commercial use only.
|
||||
No derivatives or use outside Ratspeak is permitted.
|
||||
|
||||
For commercial licensing inquiries, contact license@unsigned.io
|
||||
```
|
||||
|
||||
The adapted `lxst-codec2` crate retains the separate terms described below.
|
||||
Third-party components retain their own licenses; the rsLXST license does not
|
||||
replace those terms or notices.
|
||||
|
||||
[`THIRD_PARTY_LICENSES.json`](THIRD_PARTY_LICENSES.json) is the complete,
|
||||
CI-checked inventory of adapted Codec2 and registry third-party normal/build
|
||||
dependencies reachable from the locked workspace across declared targets. It
|
||||
excludes dev-only packages and first-party path packages. The inventory is
|
||||
generated from Cargo metadata and `Cargo.lock` with:
|
||||
|
||||
```sh
|
||||
python3 tools/check-third-party-licenses.py --write
|
||||
```
|
||||
|
||||
Review changes before committing them. Ordinary qualification uses the script
|
||||
without `--write` and fails if the lockfile, dependency graph, declared license,
|
||||
repository, or source changes.
|
||||
|
||||
## Upstream Opus implementation
|
||||
|
||||
rsLXST consumes the exact crates.io package `opus-rs` 0.1.42 from
|
||||
[`restsend/opus-rs`](https://github.com/restsend/opus-rs), associated with
|
||||
upstream commit `5d8230f362b2618b9e730e6201c0d8f98961dfe1` and locked crate
|
||||
checksum `bafbcaf2ed381cdf68ced4ed8d16517de90ffd7424e36f0b9e45d67fbe30b1f9`.
|
||||
It is BSD-3-Clause, is not locally modified, and is configured with explicit
|
||||
heap-backed codec state. The preserved license and Opus patent notice are in
|
||||
[`third_party/opus-rs-0.1.42-COPYING`](third_party/opus-rs-0.1.42-COPYING).
|
||||
|
||||
This inventory records source and license evidence; it is not legal advice and
|
||||
does not by itself replace any third-party notice required for a distributed
|
||||
binary or source bundle.
|
||||
|
||||
## Adapted Codec2 implementation
|
||||
|
||||
`crates/lxst-codec2` retains the pure-Rust codec2 0.3.1 implementation's
|
||||
LGPL-2.1-only AND MIT declaration and embedded KISS FFT BSD-3-Clause notice.
|
||||
Its [NOTICE](crates/lxst-codec2/NOTICE) and
|
||||
[immutable provenance](crates/lxst-codec2/UPSTREAM.json) describe the bounded
|
||||
storage, math and state-ownership modifications. This path dependency is
|
||||
explicitly inventoried; it is not treated as original first-party DSP.
|
||||
@@ -0,0 +1,79 @@
|
||||
# Rust API
|
||||
|
||||
rsLXST is experimental and remains below 1.0. The service boundary Ratspeak uses
|
||||
for telephony is the existing `lxst_telephony::TelephonyService` service seam:
|
||||
|
||||
- construct it with `TelephonyService::registered` or
|
||||
`TelephonyService::registered_with_config`;
|
||||
- retain the `TelephonyServiceParts::control_tx` and `event_rx` handles;
|
||||
- drive the owned service with `TelephonyService::run`; and
|
||||
- use `TelephonyControl`, `request_answer`, and `TelephonyServiceEvent` without
|
||||
translating raw Reticulum events in the application.
|
||||
|
||||
The compiled `lxst-telephony` `service` example checks construction and handle
|
||||
types. It does not run the service or demonstrate an end-to-end call.
|
||||
|
||||
## Stability
|
||||
|
||||
All workspace packages are experimental:
|
||||
|
||||
- `lxst-core` contains codec, profile, stream, signalling, and wire concepts;
|
||||
- `lxst-rns` binds media packets to Reticulum Links;
|
||||
- `lxst-telephony` contains the service boundary plus extensive runtime and
|
||||
state-machine machinery;
|
||||
- `lxst-codec2` provides bounded native Codec2 processing; and
|
||||
- `lxst-embedded` provides the bounded `no_std` framing and session boundary.
|
||||
|
||||
Selecting `TelephonyService` does not stabilize the whole package or change
|
||||
channel capacities, backpressure, event ordering, cancellation, timeouts,
|
||||
media, exact-Link, or shutdown behavior. `TelephonyRnsEndpoint`,
|
||||
`TelephonyRuntimeCore`, `TelephonyCommand`, `TelephonyDriveStep`,
|
||||
`TelephonyService::new`, and `TelephonyService::with_config` remain available
|
||||
for compatibility and specialist testing, but are implementation-level APIs
|
||||
rather than the recommended application construction path.
|
||||
|
||||
## Compatibility checks
|
||||
|
||||
The `api/` directory contains the evidence used by CI:
|
||||
|
||||
- `stability.json` records package tiers, compatibility baselines, and snapshot
|
||||
hashes;
|
||||
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
|
||||
manifest, feature, dependency, target, and MSRV contract; and
|
||||
- `fixtures/` compiles the recommended and retained paths as an external
|
||||
consumer.
|
||||
|
||||
These checks catch accidental changes, but they do not replace Android and
|
||||
Apple target builds, media tests, Python Telephone interoperability, or manual
|
||||
review. The API snapshot omits auto-derived, auto-trait, and blanket
|
||||
implementations and is not by itself a complete SemVer verdict.
|
||||
|
||||
Run the checks with:
|
||||
|
||||
```sh
|
||||
python3 tools/check-api-baseline.py
|
||||
python3 tools/check-api-manifest.py
|
||||
python3 tools/check-api-compatibility.py
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --locked
|
||||
```
|
||||
|
||||
After reviewing an API change, run
|
||||
`python3 tools/check-api-baseline.py --update` and commit the source and snapshot
|
||||
changes together. CI compares snapshots with the current source; compatibility
|
||||
checks retain the historical baseline.
|
||||
|
||||
## Live audio and constrained peers
|
||||
|
||||
`SendAudioFrames`, `StartAudioStream` and the corresponding receive/stop controls
|
||||
accept negotiated Opus and native Codec2 700C/1600/3200 profiles. Original Opus
|
||||
controls remain available. Codec2 media emits `Audio*` service events; the
|
||||
existing Opus event stream is unchanged. Standard ULBW uses ten four-byte 700C frames per 400 ms packet.
|
||||
|
||||
`StartAudioStream` binds the exact active Link and optionally shares an
|
||||
`AudioTransmitGate` with the local input owner. Renew one press serial while
|
||||
held, use a newer serial on release, and close the gate when its owner retires.
|
||||
Expired, cancelled or superseded input cannot admit queued PCM; new edges clear
|
||||
pending PCM. The gate times out after 750 ms without renewal and after a ten
|
||||
second burst. This is local PTT policy, not a remote floor-control extension.
|
||||
Applications must still bind UI events to the current call and stop on lost
|
||||
focus, suspension and release. No memo/container format is changed.
|
||||
Generated
+1541
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "lxst-telephony-api-fixture"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
lxst-embedded = { path = "../../crates/lxst-embedded" }
|
||||
lxst-codec2 = { path = "../../crates/lxst-codec2" }
|
||||
lxst-core = { path = "../../crates/lxst-core" }
|
||||
lxst-telephony = { path = "../../crates/lxst-telephony" }
|
||||
rns-identity = { path = "../../../rsReticulum/crates/rns-identity" }
|
||||
rns-transport = { path = "../../../rsReticulum/crates/rns-transport" }
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
@@ -0,0 +1,106 @@
|
||||
//! External-consumer compile contract for selected and retained LXST paths.
|
||||
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub mod canonical {
|
||||
use super::*;
|
||||
use lxst_telephony::{Error, TelephonyService, TelephonyServiceParts};
|
||||
|
||||
pub fn register(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: &Identity,
|
||||
) -> Result<TelephonyServiceParts, Error> {
|
||||
TelephonyService::registered(transport_tx, identity)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod retained {
|
||||
use lxst_telephony::{TelephonyRnsEndpoint, TelephonyRuntimeCore};
|
||||
|
||||
pub fn raw_assembly_types(
|
||||
endpoint: TelephonyRnsEndpoint,
|
||||
runtime: TelephonyRuntimeCore,
|
||||
) -> (TelephonyRnsEndpoint, TelephonyRuntimeCore) {
|
||||
(endpoint, runtime)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod codec2 {
|
||||
use lxst_core::{Codec2Backend, Codec2PacketCodec, Codec2PacketError, Profile};
|
||||
|
||||
pub fn construct<B: Codec2Backend>(
|
||||
profile: Profile,
|
||||
backend: B,
|
||||
) -> Result<Codec2PacketCodec<B>, Codec2PacketError<B::Error>> {
|
||||
Codec2PacketCodec::new(profile, backend)
|
||||
}
|
||||
|
||||
pub fn encode<B: Codec2Backend>(
|
||||
codec: &mut Codec2PacketCodec<B>,
|
||||
pcm: &[i16],
|
||||
output: &mut [u8],
|
||||
) -> Result<usize, Codec2PacketError<B::Error>> {
|
||||
codec.encode_into(pcm, output)
|
||||
}
|
||||
|
||||
pub fn decode<B: Codec2Backend>(
|
||||
codec: &mut Codec2PacketCodec<B>,
|
||||
packet: &[u8],
|
||||
output: &mut [i16],
|
||||
) -> Result<usize, Codec2PacketError<B::Error>> {
|
||||
codec.decode_into(packet, output)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod bounded_codec2 {
|
||||
use lxst_codec2::{Codec, Error, Mode};
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
pub fn initialise(storage: &mut MaybeUninit<Codec>, mode: Mode) -> &mut Codec {
|
||||
Codec::initialise(storage, mode)
|
||||
}
|
||||
pub fn roundtrip(
|
||||
codec: &mut Codec,
|
||||
pcm: &[i16],
|
||||
packet: &mut [u8],
|
||||
output: &mut [i16],
|
||||
) -> Result<(), Error> {
|
||||
codec.encode(pcm, packet)?;
|
||||
codec.decode(packet, output)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod embedded {
|
||||
use lxst_embedded::{CallRole, ConfigError, Session, SessionConfig};
|
||||
pub fn construct(role: CallRole, config: SessionConfig) -> Result<Session, ConfigError> {
|
||||
Session::new(role, config, 0)
|
||||
}
|
||||
pub fn parse(
|
||||
bytes: &[u8],
|
||||
) -> Result<lxst_embedded::wire::Packet<'_>, lxst_embedded::wire::Error> {
|
||||
lxst_embedded::wire::Packet::decode(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod live_audio {
|
||||
use lxst_core::{Profile, RawAudioFrame};
|
||||
use lxst_telephony::{AudioTransmitGate, LinkId, TelephonyControl};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
pub fn stream(
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
frames: mpsc::Receiver<RawAudioFrame>,
|
||||
) -> (Arc<AudioTransmitGate>, TelephonyControl) {
|
||||
let gate = Arc::new(AudioTransmitGate::new());
|
||||
let command = TelephonyControl::StartAudioStream {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
gate: Some(gate.clone()),
|
||||
};
|
||||
(gate, command)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
# Migrating to rsLXST 0.4 (draft)
|
||||
|
||||
This draft covers source and behaviour changes since rsLXST 0.3.1. Telephony
|
||||
now follows LXST 0.6.0 signalling, and rsLXST 0.4 runs on rsReticulum 1.5,
|
||||
which follows Reticulum 1.6.0.
|
||||
|
||||
Move rsReticulum dependencies to `~1.5.0` together with rsLXST 0.4; types from
|
||||
two rsReticulum lines do not mix. rsReticulum types that appear in rsLXST
|
||||
signatures (`TransportMessage`, `Link`, `LinkManager`, and `Identity`) change
|
||||
in 1.5; rsReticulum's own migration guide covers them.
|
||||
|
||||
## Telephony: answering
|
||||
|
||||
LXST 0.6.0 establishes the callee as soon as it answers: CONNECTING and
|
||||
ESTABLISHED are sent once, with no retry and no wait for the caller's echo.
|
||||
|
||||
| Old | New |
|
||||
| --- | --- |
|
||||
| `lxst_core::TelephonyCall::retry_answer()` | removed; `answer()` returns the whole answer and ends with `StartAudioPipelines` |
|
||||
| `lxst_embedded::CallState::retry_answer()` | removed; as above |
|
||||
| `TelephonyServiceConfig::answer_retry_interval` | removed; delete the field |
|
||||
| `TelephonyServiceConfig::answer_timeout` | removed; delete the field |
|
||||
| (none) | `TelephonyServiceConfig::connect_timeout`; a literal without `..TelephonyServiceConfig::default()` must set it |
|
||||
|
||||
`request_answer` and `TelephonyControl::Answer` now reply with an ESTABLISHED
|
||||
snapshot where they replied with CONNECTING.
|
||||
|
||||
A caller is ESTABLISHED once it has handled CONNECTING, so a lost ESTABLISHED
|
||||
no longer ends the call. Its audio still starts only on the callee's
|
||||
ESTABLISHED, so `status()` no longer shows that audio is running: check
|
||||
`audio_started()` (`TelephonyCall`, `CallState`) or wait for
|
||||
`StartAudioPipelines`.
|
||||
|
||||
## Telephony: call modes
|
||||
|
||||
Full and half duplex are signalled with the profile when the callee rings.
|
||||
|
||||
```rust
|
||||
// old
|
||||
TelephonyControl::Call { remote_identity, profile, discovery_timeout }
|
||||
// new; `None` is full duplex
|
||||
TelephonyControl::Call { remote_identity, profile, mode: None, discovery_timeout }
|
||||
```
|
||||
|
||||
These types gain variants or fields, so exhaustive matches need new arms and
|
||||
struct literals need the new fields:
|
||||
|
||||
| Type | Added |
|
||||
| --- | --- |
|
||||
| `Signal` (`lxst-core`, `lxst-embedded`) | `PreferredMode(u8)`; wire values `0xF0` to `0xFE` decode to it, not to `Raw` |
|
||||
| `TelephonyAction` (`lxst-core`, `lxst-embedded`) | `SendSignalPair`, `SelectMode`, `SwitchMode` |
|
||||
| `TelephonyCommand` | `SendSignalPair`, `SelectMode`, `SwitchMode` |
|
||||
| `TelephonyControl` | `SwitchMode`, `SquelchTransmit`, `DisableRemoteModeFollow` |
|
||||
| `ActiveCallSnapshot` | `mode`, `transmit_squelched` |
|
||||
|
||||
A caller that sees RINGING now emits one `SendSignalPair(profile, mode)` where
|
||||
it emitted `SendSignal(profile)`. Both signals travel in one packet:
|
||||
`TelephonyCommand::signal()` returns `None` for the pair, so build the packet
|
||||
with `TelephonyCommand::to_lxst_packet()`.
|
||||
|
||||
## Telephony: outgoing call links
|
||||
|
||||
LXST 0.6.0 opens the call with a plain `RNS.Link(call_destination, ...)`
|
||||
(`LXST/Primitives/Telephony.py:840-842`). On Reticulum 1.6.0 that link request
|
||||
carries a stamp at the link cost the destination announced
|
||||
(`RNS/Link.py:363`). Generating that stamp is CPU work, so building the link
|
||||
request is now async:
|
||||
|
||||
| Old | New |
|
||||
| --- | --- |
|
||||
| `fn TelephonyRnsEndpoint::begin_outgoing_link_with_remote_pubkey(..) -> Result<LinkId, Error>` | `async fn`; add `.await` |
|
||||
| (none) | `async fn TelephonyRnsEndpoint::begin_outgoing_link_with_mode(..)`, the same call with an `Option<CallMode>` |
|
||||
|
||||
```rust
|
||||
// old
|
||||
let link_id = endpoint.begin_outgoing_link_with_remote_pubkey(&mut core, identity, pubkey, profile, hops)?;
|
||||
// new
|
||||
let link_id = endpoint.begin_outgoing_link_with_remote_pubkey(&mut core, identity, pubkey, profile, hops).await?;
|
||||
```
|
||||
|
||||
`begin_outgoing_link_with_remote_pubkey` no longer sends a path request, and
|
||||
the new calls send none. When no path is known, call
|
||||
`request_path_to_identity` first, or use `begin_outgoing_link`, which discovers
|
||||
the peer and its path.
|
||||
|
||||
To stamp off the caller's task, call
|
||||
`prepare_outgoing_link_request(&transport_tx, identity, hops).await?` and pass
|
||||
its `OutgoingLinkRequest` to the synchronous
|
||||
`TelephonyRnsEndpoint::begin_prepared_outgoing_link`.
|
||||
|
||||
`Error` gains `LinkStamp(rns_link::stamp::LinkStampError)`, so exhaustive
|
||||
matches on `lxst_telephony::Error` need a new arm.
|
||||
|
||||
## Embedded sessions
|
||||
|
||||
`SessionConfig` gains `times: CallTimes`; add `times: CallTimes::DEFAULT` to
|
||||
struct literals. The defaults are LXST 0.6.0's: an incoming call rings for
|
||||
60 seconds (was 90), and an outgoing call ends unless the callee rings within
|
||||
5 seconds and the call is established within 70 seconds of the session start.
|
||||
The 10 second answer deadline and its three retries are gone.
|
||||
|
||||
## Behaviour an operator sees
|
||||
|
||||
- Outgoing calls end unless the callee rings within `connect_timeout`
|
||||
(5 seconds by default) of the call request. The 70 second
|
||||
`outgoing_call_timeout` also runs from the call request, path discovery
|
||||
included.
|
||||
- The line is busy while an outgoing call discovers its path.
|
||||
- The first announce follows 5 seconds after the service starts, and
|
||||
`startup_announce_retries` defaults to 0.
|
||||
- The telephony destination announces through the stamped announce builder.
|
||||
Calls stamp and check link requests according to the Reticulum `[stamps]`
|
||||
settings, as upstream does.
|
||||
- Call links signal the next hop's MTU when Reticulum's `link_mtu_discovery`
|
||||
is on (`RNS/Link.py:392-397`).
|
||||
- Received audio is decoded by the codec of each frame. A frame that fails to
|
||||
decode is reported and skipped; the rest of its packet still plays.
|
||||
- Raw frames at `RawBitDepth::Float128` carry IEEE binary128 samples, as
|
||||
numpy's `float128` does on Linux aarch64. rsLXST 0.3.1 wrote an `f64`
|
||||
padded to 16 bytes.
|
||||
- The Medium voice profile still encodes wideband SILK at its 8 kbps ceiling.
|
||||
- `opus-rs` is pinned at 0.1.42 (was 0.1.29). A peer packet that panics the
|
||||
Opus decoder is rejected, and the decoder is reset.
|
||||
@@ -0,0 +1,18 @@
|
||||
pub mod lxst_codec2
|
||||
pub enum lxst_codec2::Error
|
||||
pub lxst_codec2::Error::EncodedLength
|
||||
pub lxst_codec2::Error::PcmLength
|
||||
pub enum lxst_codec2::Mode
|
||||
pub lxst_codec2::Mode::Rate1600
|
||||
pub lxst_codec2::Mode::Rate3200
|
||||
pub lxst_codec2::Mode::Rate700C
|
||||
impl lxst_codec2::Mode
|
||||
pub const fn lxst_codec2::Mode::bytes(self) -> usize
|
||||
pub const fn lxst_codec2::Mode::samples(self) -> usize
|
||||
pub struct lxst_codec2::Codec
|
||||
impl lxst_codec2::Codec
|
||||
pub fn lxst_codec2::Codec::decode(&mut self, &[u8], &mut [i16]) -> core::result::Result<(), lxst_codec2::Error>
|
||||
pub fn lxst_codec2::Codec::encode(&mut self, &[i16], &mut [u8]) -> core::result::Result<(), lxst_codec2::Error>
|
||||
pub fn lxst_codec2::Codec::initialise(&mut core::mem::maybe_uninit::MaybeUninit<Self>, lxst_codec2::Mode) -> &mut Self
|
||||
pub fn lxst_codec2::Codec::mode(&self) -> lxst_codec2::Mode
|
||||
pub fn lxst_codec2::Codec::reset(&mut self, lxst_codec2::Mode)
|
||||
@@ -0,0 +1,397 @@
|
||||
pub mod lxst_core
|
||||
pub enum lxst_core::AudioCodec
|
||||
pub lxst_core::AudioCodec::Codec2(lxst_core::Codec2Mode)
|
||||
pub lxst_core::AudioCodec::Opus(lxst_core::OpusProfile)
|
||||
impl lxst_core::AudioCodec
|
||||
pub const fn lxst_core::AudioCodec::channels(self) -> u8
|
||||
pub const fn lxst_core::AudioCodec::codec_kind(self) -> lxst_core::CodecKind
|
||||
pub const fn lxst_core::AudioCodec::sample_rate_hz(self) -> u32
|
||||
#[repr(u8)] pub enum lxst_core::CallMode
|
||||
pub lxst_core::CallMode::FullDuplex = 1
|
||||
pub lxst_core::CallMode::HalfDuplex = 2
|
||||
impl lxst_core::CallMode
|
||||
pub const lxst_core::CallMode::AVAILABLE: [Self; 2]
|
||||
pub const lxst_core::CallMode::DEFAULT: Self
|
||||
pub const fn lxst_core::CallMode::abbreviation(self) -> &'static str
|
||||
pub const fn lxst_core::CallMode::from_wire(u8) -> core::option::Option<Self>
|
||||
pub const fn lxst_core::CallMode::name(self) -> &'static str
|
||||
pub const fn lxst_core::CallMode::wire_value(self) -> u8
|
||||
impl core::convert::From<lxst_core::CallMode> for lxst_core::Signal
|
||||
pub fn lxst_core::Signal::from(lxst_core::CallMode) -> Self
|
||||
pub enum lxst_core::CallRole
|
||||
pub lxst_core::CallRole::Incoming
|
||||
pub lxst_core::CallRole::Outgoing
|
||||
#[repr(u8)] pub enum lxst_core::Codec2Mode
|
||||
pub lxst_core::Codec2Mode::Mode1200 = 1
|
||||
pub lxst_core::Codec2Mode::Mode1300 = 2
|
||||
pub lxst_core::Codec2Mode::Mode1400 = 3
|
||||
pub lxst_core::Codec2Mode::Mode1600 = 4
|
||||
pub lxst_core::Codec2Mode::Mode2400 = 5
|
||||
pub lxst_core::Codec2Mode::Mode3200 = 6
|
||||
pub lxst_core::Codec2Mode::Mode700C = 0
|
||||
impl lxst_core::Codec2Mode
|
||||
pub const fn lxst_core::Codec2Mode::bitrate(self) -> u16
|
||||
pub const fn lxst_core::Codec2Mode::from_header(u8) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub const fn lxst_core::Codec2Mode::header(self) -> u8
|
||||
pub enum lxst_core::Codec2PacketError<E>
|
||||
pub lxst_core::Codec2PacketError::Backend(E)
|
||||
pub lxst_core::Codec2PacketError::BackendModeMismatch
|
||||
pub lxst_core::Codec2PacketError::BackendModeMismatch::actual: lxst_core::Codec2Mode
|
||||
pub lxst_core::Codec2PacketError::BackendModeMismatch::expected: lxst_core::Codec2Mode
|
||||
pub lxst_core::Codec2PacketError::Failed
|
||||
pub lxst_core::Codec2PacketError::ModeHeader
|
||||
pub lxst_core::Codec2PacketError::ModeHeader::actual: u8
|
||||
pub lxst_core::Codec2PacketError::ModeHeader::expected: u8
|
||||
pub lxst_core::Codec2PacketError::NonCodec2Profile(lxst_core::Profile)
|
||||
pub lxst_core::Codec2PacketError::OutputCapacity
|
||||
pub lxst_core::Codec2PacketError::OutputCapacity::actual: usize
|
||||
pub lxst_core::Codec2PacketError::OutputCapacity::required: usize
|
||||
pub lxst_core::Codec2PacketError::PayloadLength
|
||||
pub lxst_core::Codec2PacketError::PayloadLength::actual: usize
|
||||
pub lxst_core::Codec2PacketError::PayloadLength::expected: usize
|
||||
pub lxst_core::Codec2PacketError::SampleCount
|
||||
pub lxst_core::Codec2PacketError::SampleCount::actual: usize
|
||||
pub lxst_core::Codec2PacketError::SampleCount::expected: usize
|
||||
#[repr(u8)] pub enum lxst_core::CodecKind
|
||||
pub lxst_core::CodecKind::Codec2 = 2
|
||||
pub lxst_core::CodecKind::Null = 255
|
||||
pub lxst_core::CodecKind::Opus = 1
|
||||
pub lxst_core::CodecKind::Raw = 0
|
||||
impl lxst_core::CodecKind
|
||||
pub const fn lxst_core::CodecKind::from_wire(u8) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub const fn lxst_core::CodecKind::is_transmittable(self) -> bool
|
||||
pub const fn lxst_core::CodecKind::wire_id(self) -> u8
|
||||
pub enum lxst_core::DropPolicy
|
||||
pub lxst_core::DropPolicy::DropNewest
|
||||
pub lxst_core::DropPolicy::DropOldest
|
||||
pub enum lxst_core::Error
|
||||
pub lxst_core::Error::Decode(alloc::string::String)
|
||||
pub lxst_core::Error::EmptyFrame
|
||||
pub lxst_core::Error::EmptyRawPayload
|
||||
pub lxst_core::Error::Encode(alloc::string::String)
|
||||
pub lxst_core::Error::InvalidFieldKey
|
||||
pub lxst_core::Error::InvalidFieldType
|
||||
pub lxst_core::Error::InvalidFieldType::field: u8
|
||||
pub lxst_core::Error::InvalidRawChannels(u8)
|
||||
pub lxst_core::Error::InvalidRawFrameCodec(lxst_core::CodecKind)
|
||||
pub lxst_core::Error::InvalidRawSampleBytes
|
||||
pub lxst_core::Error::InvalidRawSampleBytes::bytes_per_sample: usize
|
||||
pub lxst_core::Error::InvalidRawSampleCount
|
||||
pub lxst_core::Error::InvalidRawSampleCount::channels: u8
|
||||
pub lxst_core::Error::InvalidRawSampleCount::samples: usize
|
||||
pub lxst_core::Error::InvalidSignal
|
||||
pub lxst_core::Error::NonTransmittableCodec(lxst_core::CodecKind)
|
||||
pub lxst_core::Error::RootNotMap
|
||||
pub lxst_core::Error::UnknownCodec(u8)
|
||||
pub lxst_core::Error::UnknownCodec2Mode(u8)
|
||||
pub lxst_core::Error::UnknownRawBitDepth(u8)
|
||||
pub enum lxst_core::FrameStreamEvent
|
||||
pub lxst_core::FrameStreamEvent::CodecChanged
|
||||
pub lxst_core::FrameStreamEvent::CodecChanged::from: core::option::Option<lxst_core::CodecKind>
|
||||
pub lxst_core::FrameStreamEvent::CodecChanged::to: lxst_core::CodecKind
|
||||
pub lxst_core::FrameStreamEvent::Frame(lxst_core::Frame)
|
||||
pub enum lxst_core::JitterPush<T>
|
||||
pub lxst_core::JitterPush::Accepted
|
||||
pub lxst_core::JitterPush::DroppedIncoming(T)
|
||||
pub lxst_core::JitterPush::DroppedOldest(T)
|
||||
pub enum lxst_core::OpusApplication
|
||||
pub lxst_core::OpusApplication::Audio
|
||||
pub lxst_core::OpusApplication::Voip
|
||||
pub enum lxst_core::OpusCodecError
|
||||
pub lxst_core::OpusCodecError::ChannelMismatch
|
||||
pub lxst_core::OpusCodecError::ChannelMismatch::actual: u8
|
||||
pub lxst_core::OpusCodecError::ChannelMismatch::expected: u8
|
||||
pub lxst_core::OpusCodecError::Codec(alloc::string::String)
|
||||
pub lxst_core::OpusCodecError::DecodedPacketDurationMismatch
|
||||
pub lxst_core::OpusCodecError::DecodedPacketDurationMismatch::actual: usize
|
||||
pub lxst_core::OpusCodecError::DecodedPacketDurationMismatch::expected: usize
|
||||
pub lxst_core::OpusCodecError::EncodedFrameTooLarge
|
||||
pub lxst_core::OpusCodecError::EncodedFrameTooLarge::actual: usize
|
||||
pub lxst_core::OpusCodecError::EncodedFrameTooLarge::index: usize
|
||||
pub lxst_core::OpusCodecError::EncodedFrameTooLarge::maximum: usize
|
||||
pub lxst_core::OpusCodecError::EncodedPacketTooLarge
|
||||
pub lxst_core::OpusCodecError::EncodedPacketTooLarge::actual: usize
|
||||
pub lxst_core::OpusCodecError::EncodedPacketTooLarge::maximum: usize
|
||||
pub lxst_core::OpusCodecError::InvalidFrameCodec(lxst_core::CodecKind)
|
||||
pub lxst_core::OpusCodecError::MalformedPacket(&'static str)
|
||||
pub lxst_core::OpusCodecError::NonOpusProfile(lxst_core::Profile)
|
||||
pub lxst_core::OpusCodecError::SampleFrameMismatch
|
||||
pub lxst_core::OpusCodecError::SampleFrameMismatch::actual: usize
|
||||
pub lxst_core::OpusCodecError::SampleFrameMismatch::expected: usize
|
||||
pub lxst_core::OpusCodecError::UnsupportedFrameDuration
|
||||
pub lxst_core::OpusCodecError::UnsupportedFrameDuration::sample_frames: usize
|
||||
pub lxst_core::OpusCodecError::UnsupportedFrameDuration::sample_rate_hz: u32
|
||||
pub lxst_core::OpusCodecError::UnsupportedPacketDuration
|
||||
pub lxst_core::OpusCodecError::UnsupportedPacketDuration::samples_48k: usize
|
||||
pub lxst_core::OpusCodecError::UnsupportedSubframePayloadLength(usize)
|
||||
pub lxst_core::OpusCodecError::UnsupportedSubpacketLayout
|
||||
pub lxst_core::OpusCodecError::Wire(lxst_core::Error)
|
||||
#[repr(u8)] pub enum lxst_core::OpusProfile
|
||||
pub lxst_core::OpusProfile::AudioHigh = 7
|
||||
pub lxst_core::OpusProfile::AudioLow = 5
|
||||
pub lxst_core::OpusProfile::AudioMax = 8
|
||||
pub lxst_core::OpusProfile::AudioMedium = 6
|
||||
pub lxst_core::OpusProfile::AudioMin = 4
|
||||
pub lxst_core::OpusProfile::VoiceHigh = 2
|
||||
pub lxst_core::OpusProfile::VoiceLow = 0
|
||||
pub lxst_core::OpusProfile::VoiceMax = 3
|
||||
pub lxst_core::OpusProfile::VoiceMedium = 1
|
||||
impl lxst_core::OpusProfile
|
||||
pub const lxst_core::OpusProfile::FRAME_MAX_MS: f32
|
||||
pub const lxst_core::OpusProfile::FRAME_QUANTA_MS: f32
|
||||
pub const lxst_core::OpusProfile::VALID_FRAME_MS: [f32; 6]
|
||||
pub const fn lxst_core::OpusProfile::application(self) -> lxst_core::OpusApplication
|
||||
pub const fn lxst_core::OpusProfile::bitrate_ceiling(self) -> u32
|
||||
pub const fn lxst_core::OpusProfile::channels(self) -> u8
|
||||
pub const fn lxst_core::OpusProfile::max_bytes_per_frame_ms(self, u16) -> usize
|
||||
pub const fn lxst_core::OpusProfile::sample_rate(self) -> u32
|
||||
#[repr(u32)] pub enum lxst_core::Profile
|
||||
pub lxst_core::Profile::BandwidthLow = 48
|
||||
pub lxst_core::Profile::BandwidthUltraLow = 16
|
||||
pub lxst_core::Profile::BandwidthVeryLow = 32
|
||||
pub lxst_core::Profile::LatencyLow = 128
|
||||
pub lxst_core::Profile::LatencyUltraLow = 112
|
||||
pub lxst_core::Profile::QualityHigh = 80
|
||||
pub lxst_core::Profile::QualityMax = 96
|
||||
pub lxst_core::Profile::QualityMedium = 64
|
||||
impl lxst_core::Profile
|
||||
pub const lxst_core::Profile::DEFAULT: Self
|
||||
pub const lxst_core::Profile::ORDER: [Self; 8]
|
||||
pub const fn lxst_core::Profile::abbreviation(self) -> &'static str
|
||||
pub const fn lxst_core::Profile::audio_codec(self) -> lxst_core::AudioCodec
|
||||
pub const fn lxst_core::Profile::buffer_frames(self) -> u8
|
||||
pub const fn lxst_core::Profile::channels(self) -> u8
|
||||
pub const fn lxst_core::Profile::frame_time_ms(self) -> u16
|
||||
pub const fn lxst_core::Profile::from_wire(u32) -> core::option::Option<Self>
|
||||
pub const fn lxst_core::Profile::name(self) -> &'static str
|
||||
pub fn lxst_core::Profile::next(self) -> Self
|
||||
pub const fn lxst_core::Profile::opus_payload_ceiling_bytes(self) -> core::option::Option<usize>
|
||||
pub const fn lxst_core::Profile::sample_frames_per_packet(self) -> usize
|
||||
pub const fn lxst_core::Profile::sample_rate_hz(self) -> u32
|
||||
pub const fn lxst_core::Profile::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_core::Profile> for lxst_core::Signal
|
||||
pub fn lxst_core::Signal::from(lxst_core::Profile) -> Self
|
||||
#[repr(u8)] pub enum lxst_core::RawBitDepth
|
||||
pub lxst_core::RawBitDepth::Float128 = 3
|
||||
pub lxst_core::RawBitDepth::Float16 = 0
|
||||
pub lxst_core::RawBitDepth::Float32 = 1
|
||||
pub lxst_core::RawBitDepth::Float64 = 2
|
||||
impl lxst_core::RawBitDepth
|
||||
pub const fn lxst_core::RawBitDepth::bits(self) -> u16
|
||||
pub const fn lxst_core::RawBitDepth::bytes_per_sample(self) -> usize
|
||||
pub const fn lxst_core::RawBitDepth::from_header_bits(u8) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub const fn lxst_core::RawBitDepth::numpy_dtype(self) -> &'static str
|
||||
pub enum lxst_core::Signal
|
||||
pub lxst_core::Signal::PreferredMode(u8)
|
||||
pub lxst_core::Signal::PreferredProfile(lxst_core::Profile)
|
||||
pub lxst_core::Signal::Raw(u32)
|
||||
pub lxst_core::Signal::Status(lxst_core::SignallingStatus)
|
||||
impl lxst_core::Signal
|
||||
pub const fn lxst_core::Signal::from_wire(u32) -> Self
|
||||
pub const fn lxst_core::Signal::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_core::CallMode> for lxst_core::Signal
|
||||
pub fn lxst_core::Signal::from(lxst_core::CallMode) -> Self
|
||||
impl core::convert::From<lxst_core::Profile> for lxst_core::Signal
|
||||
pub fn lxst_core::Signal::from(lxst_core::Profile) -> Self
|
||||
impl core::convert::From<lxst_core::SignallingStatus> for lxst_core::Signal
|
||||
pub fn lxst_core::Signal::from(lxst_core::SignallingStatus) -> Self
|
||||
#[repr(u32)] pub enum lxst_core::SignallingStatus
|
||||
pub lxst_core::SignallingStatus::Available = 3
|
||||
pub lxst_core::SignallingStatus::Busy = 0
|
||||
pub lxst_core::SignallingStatus::Calling = 2
|
||||
pub lxst_core::SignallingStatus::Connecting = 5
|
||||
pub lxst_core::SignallingStatus::Established = 6
|
||||
pub lxst_core::SignallingStatus::Rejected = 1
|
||||
pub lxst_core::SignallingStatus::Ringing = 4
|
||||
impl lxst_core::SignallingStatus
|
||||
pub const lxst_core::SignallingStatus::AUTO_STATUS_CODES: [Self; 5]
|
||||
pub const fn lxst_core::SignallingStatus::from_wire(u32) -> core::option::Option<Self>
|
||||
pub fn lxst_core::SignallingStatus::is_auto_status(self) -> bool
|
||||
pub const fn lxst_core::SignallingStatus::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_core::SignallingStatus> for lxst_core::Signal
|
||||
pub fn lxst_core::Signal::from(lxst_core::SignallingStatus) -> Self
|
||||
pub enum lxst_core::StreamError
|
||||
pub lxst_core::StreamError::InvalidBatchSize
|
||||
pub lxst_core::StreamError::InvalidJitterCapacity
|
||||
pub enum lxst_core::SyntheticError
|
||||
pub lxst_core::SyntheticError::InvalidFrameSamples
|
||||
pub lxst_core::SyntheticError::InvalidSampleRate
|
||||
pub lxst_core::SyntheticError::NonFiniteParameter
|
||||
pub lxst_core::SyntheticError::Raw(lxst_core::Error)
|
||||
pub enum lxst_core::SyntheticSourceKind
|
||||
pub lxst_core::SyntheticSourceKind::Ramp
|
||||
pub lxst_core::SyntheticSourceKind::Ramp::start: f32
|
||||
pub lxst_core::SyntheticSourceKind::Ramp::step: f32
|
||||
pub lxst_core::SyntheticSourceKind::Silence
|
||||
pub lxst_core::SyntheticSourceKind::Sine
|
||||
pub lxst_core::SyntheticSourceKind::Sine::amplitude: f32
|
||||
pub lxst_core::SyntheticSourceKind::Sine::frequency_hz: f32
|
||||
pub enum lxst_core::TelephonyAction
|
||||
pub lxst_core::TelephonyAction::IdentifyLocalIdentity
|
||||
pub lxst_core::TelephonyAction::IgnoreSignal(lxst_core::Signal)
|
||||
pub lxst_core::TelephonyAction::OpenAudioPipelines
|
||||
pub lxst_core::TelephonyAction::PrepareDialingPipelines
|
||||
pub lxst_core::TelephonyAction::ResetDialingPipelines
|
||||
pub lxst_core::TelephonyAction::RingIncomingCall
|
||||
pub lxst_core::TelephonyAction::SelectMode(lxst_core::CallMode)
|
||||
pub lxst_core::TelephonyAction::SelectProfile(lxst_core::Profile)
|
||||
pub lxst_core::TelephonyAction::SendSignal(lxst_core::Signal)
|
||||
pub lxst_core::TelephonyAction::SendSignalPair(lxst_core::Signal, lxst_core::Signal)
|
||||
pub lxst_core::TelephonyAction::StartAudioPipelines
|
||||
pub lxst_core::TelephonyAction::StartDialTone
|
||||
pub lxst_core::TelephonyAction::SwitchMode(lxst_core::CallMode)
|
||||
pub lxst_core::TelephonyAction::SwitchProfile(lxst_core::Profile)
|
||||
pub lxst_core::TelephonyAction::TeardownLink
|
||||
pub lxst_core::TelephonyAction::Terminate(core::option::Option<lxst_core::SignallingStatus>)
|
||||
pub struct lxst_core::Codec2PacketCodec<B>
|
||||
impl<B: lxst_core::Codec2Backend> lxst_core::Codec2PacketCodec<B>
|
||||
pub fn lxst_core::Codec2PacketCodec<B>::decode_into(&mut self, &[u8], &mut [i16]) -> core::result::Result<usize, lxst_core::Codec2PacketError<<B as lxst_core::Codec2Backend>::Error>>
|
||||
pub fn lxst_core::Codec2PacketCodec<B>::encode_into(&mut self, &[i16], &mut [u8]) -> core::result::Result<usize, lxst_core::Codec2PacketError<<B as lxst_core::Codec2Backend>::Error>>
|
||||
pub const fn lxst_core::Codec2PacketCodec<B>::mode(&self) -> lxst_core::Codec2Mode
|
||||
pub fn lxst_core::Codec2PacketCodec<B>::new(lxst_core::Profile, B) -> core::result::Result<Self, lxst_core::Codec2PacketError<<B as lxst_core::Codec2Backend>::Error>>
|
||||
pub const fn lxst_core::Codec2PacketCodec<B>::payload_bytes(&self) -> usize
|
||||
pub const fn lxst_core::Codec2PacketCodec<B>::profile(&self) -> lxst_core::Profile
|
||||
pub const fn lxst_core::Codec2PacketCodec<B>::sample_frames(&self) -> usize
|
||||
pub struct lxst_core::Frame
|
||||
pub lxst_core::Frame::codec: lxst_core::CodecKind
|
||||
pub lxst_core::Frame::payload: alloc::vec::Vec<u8>
|
||||
impl lxst_core::Frame
|
||||
pub fn lxst_core::Frame::from_wire_bytes(&[u8]) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub fn lxst_core::Frame::new(lxst_core::CodecKind, impl core::convert::Into<alloc::vec::Vec<u8>>) -> Self
|
||||
pub fn lxst_core::Frame::to_wire_bytes(&self) -> core::result::Result<alloc::vec::Vec<u8>, lxst_core::Error>
|
||||
pub struct lxst_core::FramePacketizer
|
||||
impl lxst_core::FramePacketizer
|
||||
pub const lxst_core::FramePacketizer::PYTHON_COMPATIBLE: Self
|
||||
pub const fn lxst_core::FramePacketizer::frames_per_packet(self) -> usize
|
||||
pub fn lxst_core::FramePacketizer::new(usize) -> core::result::Result<Self, lxst_core::StreamError>
|
||||
pub fn lxst_core::FramePacketizer::packetize(self, impl core::iter::traits::collect::IntoIterator<Item = lxst_core::Frame>) -> alloc::vec::Vec<lxst_core::LxstPacket>
|
||||
pub fn lxst_core::FramePacketizer::packetize_one(self, lxst_core::Frame) -> lxst_core::LxstPacket
|
||||
pub struct lxst_core::FrameStreamState
|
||||
impl lxst_core::FrameStreamState
|
||||
pub fn lxst_core::FrameStreamState::accept_packet(&mut self, lxst_core::LxstPacket) -> alloc::vec::Vec<lxst_core::FrameStreamEvent>
|
||||
pub const fn lxst_core::FrameStreamState::current_codec(&self) -> core::option::Option<lxst_core::CodecKind>
|
||||
pub fn lxst_core::FrameStreamState::new() -> Self
|
||||
pub struct lxst_core::JitterBuffer<T>
|
||||
impl<T> lxst_core::JitterBuffer<T>
|
||||
pub const fn lxst_core::JitterBuffer<T>::capacity(&self) -> usize
|
||||
pub fn lxst_core::JitterBuffer<T>::clear(&mut self)
|
||||
pub const fn lxst_core::JitterBuffer<T>::drop_policy(&self) -> lxst_core::DropPolicy
|
||||
pub fn lxst_core::JitterBuffer<T>::is_empty(&self) -> bool
|
||||
pub fn lxst_core::JitterBuffer<T>::len(&self) -> usize
|
||||
pub fn lxst_core::JitterBuffer<T>::new(usize, lxst_core::DropPolicy) -> core::result::Result<Self, lxst_core::StreamError>
|
||||
pub fn lxst_core::JitterBuffer<T>::pop(&mut self) -> core::option::Option<T>
|
||||
pub fn lxst_core::JitterBuffer<T>::push(&mut self, T) -> lxst_core::JitterPush<T>
|
||||
pub const fn lxst_core::JitterBuffer<T>::stats(&self) -> lxst_core::JitterStats
|
||||
pub struct lxst_core::JitterStats
|
||||
pub lxst_core::JitterStats::dropped_newest: u64
|
||||
pub lxst_core::JitterStats::dropped_oldest: u64
|
||||
pub lxst_core::JitterStats::popped: u64
|
||||
pub lxst_core::JitterStats::pushed: u64
|
||||
pub lxst_core::JitterStats::underruns: u64
|
||||
pub struct lxst_core::LxstPacket
|
||||
pub lxst_core::LxstPacket::frames: alloc::vec::Vec<lxst_core::Frame>
|
||||
pub lxst_core::LxstPacket::signals: alloc::vec::Vec<lxst_core::Signal>
|
||||
impl lxst_core::LxstPacket
|
||||
pub fn lxst_core::LxstPacket::decode(&[u8]) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub fn lxst_core::LxstPacket::encode(&self) -> core::result::Result<alloc::vec::Vec<u8>, lxst_core::Error>
|
||||
pub fn lxst_core::LxstPacket::frame(lxst_core::Frame) -> Self
|
||||
pub fn lxst_core::LxstPacket::new() -> Self
|
||||
pub fn lxst_core::LxstPacket::signalling(impl core::iter::traits::collect::IntoIterator<Item = lxst_core::Signal>) -> Self
|
||||
pub struct lxst_core::OpusDecoderState
|
||||
impl lxst_core::OpusDecoderState
|
||||
pub fn lxst_core::OpusDecoderState::decode_frame(&mut self, &lxst_core::Frame) -> core::result::Result<lxst_core::RawAudioFrame, lxst_core::OpusCodecError>
|
||||
pub fn lxst_core::OpusDecoderState::new(lxst_core::Profile) -> core::result::Result<Self, lxst_core::OpusCodecError>
|
||||
pub const fn lxst_core::OpusDecoderState::profile(&self) -> lxst_core::Profile
|
||||
pub const fn lxst_core::OpusDecoderState::subframe_count(&self) -> usize
|
||||
pub const fn lxst_core::OpusDecoderState::subframe_sample_frames(&self) -> usize
|
||||
pub struct lxst_core::OpusEncoderState
|
||||
impl lxst_core::OpusEncoderState
|
||||
pub const fn lxst_core::OpusEncoderState::channels(&self) -> u8
|
||||
pub fn lxst_core::OpusEncoderState::encode_frame(&mut self, &lxst_core::RawAudioFrame) -> core::result::Result<lxst_core::Frame, lxst_core::OpusCodecError>
|
||||
pub const fn lxst_core::OpusEncoderState::max_payload_bytes(&self) -> usize
|
||||
pub fn lxst_core::OpusEncoderState::new(lxst_core::Profile) -> core::result::Result<Self, lxst_core::OpusCodecError>
|
||||
pub const fn lxst_core::OpusEncoderState::profile(&self) -> lxst_core::Profile
|
||||
pub const fn lxst_core::OpusEncoderState::sample_frames(&self) -> usize
|
||||
pub const fn lxst_core::OpusEncoderState::subframe_count(&self) -> usize
|
||||
pub const fn lxst_core::OpusEncoderState::subframe_sample_frames(&self) -> usize
|
||||
pub struct lxst_core::OpusMonoDecoder
|
||||
impl lxst_core::OpusMonoDecoder
|
||||
pub const fn lxst_core::OpusMonoDecoder::channels(&self) -> u8
|
||||
pub fn lxst_core::OpusMonoDecoder::decode_packet(&mut self, &[u8]) -> core::result::Result<lxst_core::RawAudioFrame, lxst_core::OpusCodecError>
|
||||
pub fn lxst_core::OpusMonoDecoder::new() -> core::result::Result<Self, lxst_core::OpusCodecError>
|
||||
pub const fn lxst_core::OpusMonoDecoder::sample_rate_hz(&self) -> u32
|
||||
pub struct lxst_core::OpusPacketDecoder
|
||||
impl lxst_core::OpusPacketDecoder
|
||||
pub const fn lxst_core::OpusPacketDecoder::channels(&self) -> u8
|
||||
pub fn lxst_core::OpusPacketDecoder::decode_packet(&mut self, &[u8]) -> core::result::Result<lxst_core::RawAudioFrame, lxst_core::OpusCodecError>
|
||||
pub fn lxst_core::OpusPacketDecoder::new(u32, u8) -> core::result::Result<Self, lxst_core::OpusCodecError>
|
||||
pub const fn lxst_core::OpusPacketDecoder::sample_rate_hz(&self) -> u32
|
||||
pub struct lxst_core::RawAudioFrame
|
||||
pub lxst_core::RawAudioFrame::channels: u8
|
||||
pub lxst_core::RawAudioFrame::samples: alloc::vec::Vec<f32>
|
||||
impl lxst_core::RawAudioFrame
|
||||
pub fn lxst_core::RawAudioFrame::from_frame(&lxst_core::Frame) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub fn lxst_core::RawAudioFrame::from_payload(&[u8]) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub fn lxst_core::RawAudioFrame::new(u8, impl core::convert::Into<alloc::vec::Vec<f32>>) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub fn lxst_core::RawAudioFrame::resampled(&self, u32, u32) -> Self
|
||||
pub fn lxst_core::RawAudioFrame::sample_frames(&self) -> usize
|
||||
pub fn lxst_core::RawAudioFrame::to_frame(&self, lxst_core::RawBitDepth) -> core::result::Result<lxst_core::Frame, lxst_core::Error>
|
||||
pub fn lxst_core::RawAudioFrame::to_payload(&self, lxst_core::RawBitDepth) -> core::result::Result<alloc::vec::Vec<u8>, lxst_core::Error>
|
||||
pub fn lxst_core::RawAudioFrame::with_channels(self, u8) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub struct lxst_core::RawFrameCollector
|
||||
impl lxst_core::RawFrameCollector
|
||||
pub fn lxst_core::RawFrameCollector::frames(&self) -> &[lxst_core::RawAudioFrame]
|
||||
pub fn lxst_core::RawFrameCollector::into_frames(self) -> alloc::vec::Vec<lxst_core::RawAudioFrame>
|
||||
pub fn lxst_core::RawFrameCollector::new() -> Self
|
||||
pub fn lxst_core::RawFrameCollector::push(&mut self, lxst_core::RawAudioFrame)
|
||||
pub const fn lxst_core::RawFrameCollector::sample_frames(&self) -> usize
|
||||
pub struct lxst_core::RawFrameHeader
|
||||
pub lxst_core::RawFrameHeader::bit_depth: lxst_core::RawBitDepth
|
||||
pub lxst_core::RawFrameHeader::channels: u8
|
||||
impl lxst_core::RawFrameHeader
|
||||
pub const fn lxst_core::RawFrameHeader::encode(self) -> u8
|
||||
pub const fn lxst_core::RawFrameHeader::new(u8, lxst_core::RawBitDepth) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub fn lxst_core::RawFrameHeader::parse(u8) -> core::result::Result<Self, lxst_core::Error>
|
||||
pub struct lxst_core::SyntheticSource
|
||||
impl lxst_core::SyntheticSource
|
||||
pub const fn lxst_core::SyntheticSource::channels(&self) -> u8
|
||||
pub const fn lxst_core::SyntheticSource::cursor_samples(&self) -> u64
|
||||
pub const fn lxst_core::SyntheticSource::frame_samples(&self) -> usize
|
||||
pub fn lxst_core::SyntheticSource::new(u8, u32, usize, lxst_core::SyntheticSourceKind) -> core::result::Result<Self, lxst_core::SyntheticError>
|
||||
pub fn lxst_core::SyntheticSource::next_raw_frame(&mut self) -> core::result::Result<lxst_core::RawAudioFrame, lxst_core::SyntheticError>
|
||||
pub const fn lxst_core::SyntheticSource::sample_rate_hz(&self) -> u32
|
||||
pub struct lxst_core::TelephonyCall
|
||||
impl lxst_core::TelephonyCall
|
||||
pub fn lxst_core::TelephonyCall::answer(&mut self) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub const fn lxst_core::TelephonyCall::answered(&self) -> bool
|
||||
pub const fn lxst_core::TelephonyCall::audio_started(&self) -> bool
|
||||
pub fn lxst_core::TelephonyCall::caller_identified(&mut self, bool, bool) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub fn lxst_core::TelephonyCall::disable_remote_mode_follow(&mut self)
|
||||
pub fn lxst_core::TelephonyCall::hangup(&mut self, bool) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub fn lxst_core::TelephonyCall::incoming() -> Self
|
||||
pub fn lxst_core::TelephonyCall::incoming_link_established(bool) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub const fn lxst_core::TelephonyCall::mode(&self) -> core::option::Option<lxst_core::CallMode>
|
||||
pub fn lxst_core::TelephonyCall::outgoing(core::option::Option<lxst_core::Profile>) -> Self
|
||||
pub fn lxst_core::TelephonyCall::outgoing_with_mode(core::option::Option<lxst_core::Profile>, core::option::Option<lxst_core::CallMode>) -> Self
|
||||
pub const fn lxst_core::TelephonyCall::profile(&self) -> core::option::Option<lxst_core::Profile>
|
||||
pub fn lxst_core::TelephonyCall::receive_signal(&mut self, lxst_core::Signal) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub const fn lxst_core::TelephonyCall::role(&self) -> lxst_core::CallRole
|
||||
pub fn lxst_core::TelephonyCall::set_transmit_squelched(&mut self, bool)
|
||||
pub const fn lxst_core::TelephonyCall::status(&self) -> lxst_core::SignallingStatus
|
||||
pub fn lxst_core::TelephonyCall::switch_mode(&mut self, lxst_core::CallMode) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub fn lxst_core::TelephonyCall::switch_profile(&mut self, lxst_core::Profile) -> alloc::vec::Vec<lxst_core::TelephonyAction>
|
||||
pub const fn lxst_core::TelephonyCall::transmit_squelched(&self) -> bool
|
||||
pub const lxst_core::APP_NAME: &str
|
||||
pub const lxst_core::FIELD_FRAMES: u8
|
||||
pub const lxst_core::FIELD_SIGNALLING: u8
|
||||
pub const lxst_core::OPUS_ENCODED_FRAME_MAX_BYTES: usize
|
||||
pub const lxst_core::OPUS_ENCODED_PACKET_MAX_BYTES: usize
|
||||
pub const lxst_core::OPUS_MONO_DECODE_SAMPLE_RATE_HZ: u32
|
||||
pub const lxst_core::TELEPHONY_DESTINATION_NAME: &str
|
||||
pub const lxst_core::TELEPHONY_PRIMITIVE_NAME: &str
|
||||
pub trait lxst_core::Codec2Backend
|
||||
pub type lxst_core::Codec2Backend::Error
|
||||
pub fn lxst_core::Codec2Backend::decode_native(&mut self, &[u8], &mut [i16]) -> core::result::Result<(), Self::Error>
|
||||
pub fn lxst_core::Codec2Backend::encode_native(&mut self, &[i16], &mut [u8]) -> core::result::Result<(), Self::Error>
|
||||
pub fn lxst_core::Codec2Backend::mode(&self) -> lxst_core::Codec2Mode
|
||||
pub fn lxst_core::opus_packet_duration_samples_48k(&[u8]) -> core::result::Result<usize, lxst_core::OpusCodecError>
|
||||
@@ -0,0 +1,337 @@
|
||||
pub mod lxst_embedded
|
||||
pub mod lxst_embedded::wire
|
||||
#[repr(u8)] pub enum lxst_embedded::wire::Codec2Mode
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode1200 = 1
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode1300 = 2
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode1400 = 3
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode1600 = 4
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode2400 = 5
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode3200 = 6
|
||||
pub lxst_embedded::wire::Codec2Mode::Mode700C = 0
|
||||
impl lxst_embedded::wire::Codec2Mode
|
||||
pub const fn lxst_embedded::wire::Codec2Mode::bitrate(self) -> u16
|
||||
pub const fn lxst_embedded::wire::Codec2Mode::from_header(u8) -> core::result::Result<Self, lxst_embedded::wire::Error>
|
||||
pub const fn lxst_embedded::wire::Codec2Mode::header(self) -> u8
|
||||
#[repr(u8)] pub enum lxst_embedded::wire::CodecKind
|
||||
pub lxst_embedded::wire::CodecKind::Codec2 = 2
|
||||
pub lxst_embedded::wire::CodecKind::Null = 255
|
||||
pub lxst_embedded::wire::CodecKind::Opus = 1
|
||||
pub lxst_embedded::wire::CodecKind::Raw = 0
|
||||
impl lxst_embedded::wire::CodecKind
|
||||
pub const fn lxst_embedded::wire::CodecKind::from_wire(u8) -> core::result::Result<Self, lxst_embedded::wire::Error>
|
||||
pub const fn lxst_embedded::wire::CodecKind::is_transmittable(self) -> bool
|
||||
pub const fn lxst_embedded::wire::CodecKind::wire_id(self) -> u8
|
||||
pub enum lxst_embedded::wire::Error
|
||||
pub lxst_embedded::wire::Error::DuplicateField
|
||||
pub lxst_embedded::wire::Error::EmptyFrame
|
||||
pub lxst_embedded::wire::Error::Limit
|
||||
pub lxst_embedded::wire::Error::NonTransmittableCodec(lxst_embedded::wire::CodecKind)
|
||||
pub lxst_embedded::wire::Error::OutputCapacity
|
||||
pub lxst_embedded::wire::Error::Shape
|
||||
pub lxst_embedded::wire::Error::TrailingData
|
||||
pub lxst_embedded::wire::Error::Truncated
|
||||
pub lxst_embedded::wire::Error::UnknownCodec(u8)
|
||||
pub lxst_embedded::wire::Error::UnknownCodec2Mode(u8)
|
||||
pub enum lxst_embedded::wire::Signal
|
||||
pub lxst_embedded::wire::Signal::PreferredMode(u8)
|
||||
pub lxst_embedded::wire::Signal::PreferredProfile(lxst_embedded::Profile)
|
||||
pub lxst_embedded::wire::Signal::Raw(u32)
|
||||
pub lxst_embedded::wire::Signal::Status(lxst_embedded::SignallingStatus)
|
||||
impl lxst_embedded::wire::Signal
|
||||
pub const fn lxst_embedded::wire::Signal::from_wire(u32) -> Self
|
||||
pub const fn lxst_embedded::wire::Signal::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_embedded::CallMode> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self
|
||||
impl core::convert::From<lxst_embedded::Profile> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self
|
||||
impl core::convert::From<lxst_embedded::SignallingStatus> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::SignallingStatus) -> Self
|
||||
pub struct lxst_embedded::wire::Frame<'a>
|
||||
pub lxst_embedded::wire::Frame::codec: lxst_embedded::wire::CodecKind
|
||||
pub lxst_embedded::wire::Frame::payload: &'a [u8]
|
||||
pub struct lxst_embedded::wire::Packet<'a>
|
||||
impl<'a> lxst_embedded::wire::Packet<'a>
|
||||
pub fn lxst_embedded::wire::Packet<'a>::decode(&'a [u8]) -> core::result::Result<Self, lxst_embedded::wire::Error>
|
||||
pub fn lxst_embedded::wire::Packet<'a>::frames(&self) -> &[lxst_embedded::wire::Frame<'a>]
|
||||
pub fn lxst_embedded::wire::Packet<'a>::signals(&self) -> &[lxst_embedded::wire::Signal]
|
||||
pub const lxst_embedded::wire::MAX_FRAMES: usize
|
||||
pub const lxst_embedded::wire::MAX_FRAME_BYTES: usize
|
||||
pub const lxst_embedded::wire::MAX_PACKET_BYTES: usize
|
||||
pub const lxst_embedded::wire::MAX_SIGNALS: usize
|
||||
pub fn lxst_embedded::wire::encode(&[lxst_embedded::wire::Signal], &[lxst_embedded::wire::Frame<'_>], &mut [u8]) -> core::result::Result<usize, lxst_embedded::wire::Error>
|
||||
pub enum lxst_embedded::AudioCodec
|
||||
pub lxst_embedded::AudioCodec::Codec2(lxst_embedded::wire::Codec2Mode)
|
||||
pub lxst_embedded::AudioCodec::Opus(lxst_embedded::OpusProfile)
|
||||
impl lxst_embedded::AudioCodec
|
||||
pub const fn lxst_embedded::AudioCodec::channels(self) -> u8
|
||||
pub const fn lxst_embedded::AudioCodec::codec_kind(self) -> lxst_embedded::wire::CodecKind
|
||||
pub const fn lxst_embedded::AudioCodec::sample_rate_hz(self) -> u32
|
||||
#[repr(u8)] pub enum lxst_embedded::CallMode
|
||||
pub lxst_embedded::CallMode::FullDuplex = 1
|
||||
pub lxst_embedded::CallMode::HalfDuplex = 2
|
||||
impl lxst_embedded::CallMode
|
||||
pub const lxst_embedded::CallMode::AVAILABLE: [Self; 2]
|
||||
pub const lxst_embedded::CallMode::DEFAULT: Self
|
||||
pub const fn lxst_embedded::CallMode::abbreviation(self) -> &'static str
|
||||
pub const fn lxst_embedded::CallMode::from_wire(u8) -> core::option::Option<Self>
|
||||
pub const fn lxst_embedded::CallMode::name(self) -> &'static str
|
||||
pub const fn lxst_embedded::CallMode::wire_value(self) -> u8
|
||||
impl core::convert::From<lxst_embedded::CallMode> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self
|
||||
pub enum lxst_embedded::CallRole
|
||||
pub lxst_embedded::CallRole::Incoming
|
||||
pub lxst_embedded::CallRole::Outgoing
|
||||
#[repr(u8)] pub enum lxst_embedded::Codec2Mode
|
||||
pub lxst_embedded::Codec2Mode::Mode1200 = 1
|
||||
pub lxst_embedded::Codec2Mode::Mode1300 = 2
|
||||
pub lxst_embedded::Codec2Mode::Mode1400 = 3
|
||||
pub lxst_embedded::Codec2Mode::Mode1600 = 4
|
||||
pub lxst_embedded::Codec2Mode::Mode2400 = 5
|
||||
pub lxst_embedded::Codec2Mode::Mode3200 = 6
|
||||
pub lxst_embedded::Codec2Mode::Mode700C = 0
|
||||
impl lxst_embedded::wire::Codec2Mode
|
||||
pub const fn lxst_embedded::wire::Codec2Mode::bitrate(self) -> u16
|
||||
pub const fn lxst_embedded::wire::Codec2Mode::from_header(u8) -> core::result::Result<Self, lxst_embedded::wire::Error>
|
||||
pub const fn lxst_embedded::wire::Codec2Mode::header(self) -> u8
|
||||
pub enum lxst_embedded::Codec2PacketError<E>
|
||||
pub lxst_embedded::Codec2PacketError::Backend(E)
|
||||
pub lxst_embedded::Codec2PacketError::BackendModeMismatch
|
||||
pub lxst_embedded::Codec2PacketError::BackendModeMismatch::actual: lxst_embedded::wire::Codec2Mode
|
||||
pub lxst_embedded::Codec2PacketError::BackendModeMismatch::expected: lxst_embedded::wire::Codec2Mode
|
||||
pub lxst_embedded::Codec2PacketError::Failed
|
||||
pub lxst_embedded::Codec2PacketError::ModeHeader
|
||||
pub lxst_embedded::Codec2PacketError::ModeHeader::actual: u8
|
||||
pub lxst_embedded::Codec2PacketError::ModeHeader::expected: u8
|
||||
pub lxst_embedded::Codec2PacketError::NonCodec2Profile(lxst_embedded::Profile)
|
||||
pub lxst_embedded::Codec2PacketError::OutputCapacity
|
||||
pub lxst_embedded::Codec2PacketError::OutputCapacity::actual: usize
|
||||
pub lxst_embedded::Codec2PacketError::OutputCapacity::required: usize
|
||||
pub lxst_embedded::Codec2PacketError::PayloadLength
|
||||
pub lxst_embedded::Codec2PacketError::PayloadLength::actual: usize
|
||||
pub lxst_embedded::Codec2PacketError::PayloadLength::expected: usize
|
||||
pub lxst_embedded::Codec2PacketError::SampleCount
|
||||
pub lxst_embedded::Codec2PacketError::SampleCount::actual: usize
|
||||
pub lxst_embedded::Codec2PacketError::SampleCount::expected: usize
|
||||
#[repr(u8)] pub enum lxst_embedded::CodecKind
|
||||
pub lxst_embedded::CodecKind::Codec2 = 2
|
||||
pub lxst_embedded::CodecKind::Null = 255
|
||||
pub lxst_embedded::CodecKind::Opus = 1
|
||||
pub lxst_embedded::CodecKind::Raw = 0
|
||||
impl lxst_embedded::wire::CodecKind
|
||||
pub const fn lxst_embedded::wire::CodecKind::from_wire(u8) -> core::result::Result<Self, lxst_embedded::wire::Error>
|
||||
pub const fn lxst_embedded::wire::CodecKind::is_transmittable(self) -> bool
|
||||
pub const fn lxst_embedded::wire::CodecKind::wire_id(self) -> u8
|
||||
pub enum lxst_embedded::ConfigError
|
||||
pub lxst_embedded::ConfigError::NoAudioDirection
|
||||
pub lxst_embedded::ConfigError::UnsupportedPreferredProfile
|
||||
pub enum lxst_embedded::EndReason
|
||||
pub lxst_embedded::EndReason::AudioUnavailable
|
||||
pub lxst_embedded::EndReason::Busy
|
||||
pub lxst_embedded::EndReason::Local
|
||||
pub lxst_embedded::EndReason::ProfileUnsupported
|
||||
pub lxst_embedded::EndReason::Rejected
|
||||
pub lxst_embedded::EndReason::Remote
|
||||
pub lxst_embedded::EndReason::RouteLost
|
||||
pub lxst_embedded::EndReason::Timeout
|
||||
pub enum lxst_embedded::Event
|
||||
pub lxst_embedded::Event::Capture(bool)
|
||||
pub lxst_embedded::Event::Ended(lxst_embedded::EndReason)
|
||||
pub lxst_embedded::Event::FlushMedia
|
||||
pub lxst_embedded::Event::Transition(lxst_embedded::TelephonyAction)
|
||||
pub enum lxst_embedded::OpusApplication
|
||||
pub lxst_embedded::OpusApplication::Audio
|
||||
pub lxst_embedded::OpusApplication::Voip
|
||||
#[repr(u8)] pub enum lxst_embedded::OpusProfile
|
||||
pub lxst_embedded::OpusProfile::AudioHigh = 7
|
||||
pub lxst_embedded::OpusProfile::AudioLow = 5
|
||||
pub lxst_embedded::OpusProfile::AudioMax = 8
|
||||
pub lxst_embedded::OpusProfile::AudioMedium = 6
|
||||
pub lxst_embedded::OpusProfile::AudioMin = 4
|
||||
pub lxst_embedded::OpusProfile::VoiceHigh = 2
|
||||
pub lxst_embedded::OpusProfile::VoiceLow = 0
|
||||
pub lxst_embedded::OpusProfile::VoiceMax = 3
|
||||
pub lxst_embedded::OpusProfile::VoiceMedium = 1
|
||||
impl lxst_embedded::OpusProfile
|
||||
pub const lxst_embedded::OpusProfile::FRAME_MAX_MS: f32
|
||||
pub const lxst_embedded::OpusProfile::FRAME_QUANTA_MS: f32
|
||||
pub const lxst_embedded::OpusProfile::VALID_FRAME_MS: [f32; 6]
|
||||
pub const fn lxst_embedded::OpusProfile::application(self) -> lxst_embedded::OpusApplication
|
||||
pub const fn lxst_embedded::OpusProfile::bitrate_ceiling(self) -> u32
|
||||
pub const fn lxst_embedded::OpusProfile::channels(self) -> u8
|
||||
pub const fn lxst_embedded::OpusProfile::max_bytes_per_frame_ms(self, u16) -> usize
|
||||
pub const fn lxst_embedded::OpusProfile::sample_rate(self) -> u32
|
||||
#[repr(u32)] pub enum lxst_embedded::Profile
|
||||
pub lxst_embedded::Profile::BandwidthLow = 48
|
||||
pub lxst_embedded::Profile::BandwidthUltraLow = 16
|
||||
pub lxst_embedded::Profile::BandwidthVeryLow = 32
|
||||
pub lxst_embedded::Profile::LatencyLow = 128
|
||||
pub lxst_embedded::Profile::LatencyUltraLow = 112
|
||||
pub lxst_embedded::Profile::QualityHigh = 80
|
||||
pub lxst_embedded::Profile::QualityMax = 96
|
||||
pub lxst_embedded::Profile::QualityMedium = 64
|
||||
impl lxst_embedded::Profile
|
||||
pub const lxst_embedded::Profile::DEFAULT: Self
|
||||
pub const lxst_embedded::Profile::ORDER: [Self; 8]
|
||||
pub const fn lxst_embedded::Profile::abbreviation(self) -> &'static str
|
||||
pub const fn lxst_embedded::Profile::audio_codec(self) -> lxst_embedded::AudioCodec
|
||||
pub const fn lxst_embedded::Profile::buffer_frames(self) -> u8
|
||||
pub const fn lxst_embedded::Profile::channels(self) -> u8
|
||||
pub const fn lxst_embedded::Profile::frame_time_ms(self) -> u16
|
||||
pub const fn lxst_embedded::Profile::from_wire(u32) -> core::option::Option<Self>
|
||||
pub const fn lxst_embedded::Profile::name(self) -> &'static str
|
||||
pub fn lxst_embedded::Profile::next(self) -> Self
|
||||
pub const fn lxst_embedded::Profile::opus_payload_ceiling_bytes(self) -> core::option::Option<usize>
|
||||
pub const fn lxst_embedded::Profile::sample_frames_per_packet(self) -> usize
|
||||
pub const fn lxst_embedded::Profile::sample_rate_hz(self) -> u32
|
||||
pub const fn lxst_embedded::Profile::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_embedded::Profile> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self
|
||||
pub enum lxst_embedded::QueueError
|
||||
pub lxst_embedded::QueueError::EmptyPayload
|
||||
pub lxst_embedded::QueueError::Expired
|
||||
pub lxst_embedded::QueueError::OutputCapacity
|
||||
pub lxst_embedded::QueueError::PayloadTooLarge
|
||||
pub enum lxst_embedded::Signal
|
||||
pub lxst_embedded::Signal::PreferredMode(u8)
|
||||
pub lxst_embedded::Signal::PreferredProfile(lxst_embedded::Profile)
|
||||
pub lxst_embedded::Signal::Raw(u32)
|
||||
pub lxst_embedded::Signal::Status(lxst_embedded::SignallingStatus)
|
||||
impl lxst_embedded::wire::Signal
|
||||
pub const fn lxst_embedded::wire::Signal::from_wire(u32) -> Self
|
||||
pub const fn lxst_embedded::wire::Signal::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_embedded::CallMode> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self
|
||||
impl core::convert::From<lxst_embedded::Profile> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self
|
||||
impl core::convert::From<lxst_embedded::SignallingStatus> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::SignallingStatus) -> Self
|
||||
#[repr(u32)] pub enum lxst_embedded::SignallingStatus
|
||||
pub lxst_embedded::SignallingStatus::Available = 3
|
||||
pub lxst_embedded::SignallingStatus::Busy = 0
|
||||
pub lxst_embedded::SignallingStatus::Calling = 2
|
||||
pub lxst_embedded::SignallingStatus::Connecting = 5
|
||||
pub lxst_embedded::SignallingStatus::Established = 6
|
||||
pub lxst_embedded::SignallingStatus::Rejected = 1
|
||||
pub lxst_embedded::SignallingStatus::Ringing = 4
|
||||
impl lxst_embedded::SignallingStatus
|
||||
pub const lxst_embedded::SignallingStatus::AUTO_STATUS_CODES: [Self; 5]
|
||||
pub const fn lxst_embedded::SignallingStatus::from_wire(u32) -> core::option::Option<Self>
|
||||
pub fn lxst_embedded::SignallingStatus::is_auto_status(self) -> bool
|
||||
pub const fn lxst_embedded::SignallingStatus::wire_value(self) -> u32
|
||||
impl core::convert::From<lxst_embedded::SignallingStatus> for lxst_embedded::wire::Signal
|
||||
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::SignallingStatus) -> Self
|
||||
pub enum lxst_embedded::TelephonyAction
|
||||
pub lxst_embedded::TelephonyAction::IdentifyLocalIdentity
|
||||
pub lxst_embedded::TelephonyAction::IgnoreSignal(lxst_embedded::wire::Signal)
|
||||
pub lxst_embedded::TelephonyAction::OpenAudioPipelines
|
||||
pub lxst_embedded::TelephonyAction::PrepareDialingPipelines
|
||||
pub lxst_embedded::TelephonyAction::ResetDialingPipelines
|
||||
pub lxst_embedded::TelephonyAction::RingIncomingCall
|
||||
pub lxst_embedded::TelephonyAction::SelectMode(lxst_embedded::CallMode)
|
||||
pub lxst_embedded::TelephonyAction::SelectProfile(lxst_embedded::Profile)
|
||||
pub lxst_embedded::TelephonyAction::SendSignal(lxst_embedded::wire::Signal)
|
||||
pub lxst_embedded::TelephonyAction::SendSignalPair(lxst_embedded::wire::Signal, lxst_embedded::wire::Signal)
|
||||
pub lxst_embedded::TelephonyAction::StartAudioPipelines
|
||||
pub lxst_embedded::TelephonyAction::StartDialTone
|
||||
pub lxst_embedded::TelephonyAction::SwitchMode(lxst_embedded::CallMode)
|
||||
pub lxst_embedded::TelephonyAction::SwitchProfile(lxst_embedded::Profile)
|
||||
pub lxst_embedded::TelephonyAction::TeardownLink
|
||||
pub lxst_embedded::TelephonyAction::Terminate(core::option::Option<lxst_embedded::SignallingStatus>)
|
||||
pub struct lxst_embedded::Actions
|
||||
impl lxst_embedded::Actions
|
||||
pub fn lxst_embedded::Actions::as_slice(&self) -> &[lxst_embedded::TelephonyAction]
|
||||
pub struct lxst_embedded::CallState
|
||||
impl lxst_embedded::CallState
|
||||
pub fn lxst_embedded::CallState::answer(&mut self) -> lxst_embedded::Actions
|
||||
pub const fn lxst_embedded::CallState::answered(&self) -> bool
|
||||
pub const fn lxst_embedded::CallState::audio_started(&self) -> bool
|
||||
pub fn lxst_embedded::CallState::caller_identified(&mut self, bool, bool) -> lxst_embedded::Actions
|
||||
pub fn lxst_embedded::CallState::disable_remote_mode_follow(&mut self)
|
||||
pub fn lxst_embedded::CallState::hangup(&mut self, bool) -> lxst_embedded::Actions
|
||||
pub fn lxst_embedded::CallState::incoming() -> Self
|
||||
pub fn lxst_embedded::CallState::incoming_link_established(bool) -> lxst_embedded::Actions
|
||||
pub const fn lxst_embedded::CallState::mode(&self) -> core::option::Option<lxst_embedded::CallMode>
|
||||
pub fn lxst_embedded::CallState::outgoing(core::option::Option<lxst_embedded::Profile>) -> Self
|
||||
pub fn lxst_embedded::CallState::outgoing_with_mode(core::option::Option<lxst_embedded::Profile>, core::option::Option<lxst_embedded::CallMode>) -> Self
|
||||
pub const fn lxst_embedded::CallState::profile(&self) -> core::option::Option<lxst_embedded::Profile>
|
||||
pub fn lxst_embedded::CallState::receive_signal(&mut self, lxst_embedded::wire::Signal) -> lxst_embedded::Actions
|
||||
pub const fn lxst_embedded::CallState::role(&self) -> lxst_embedded::CallRole
|
||||
pub fn lxst_embedded::CallState::set_transmit_squelched(&mut self, bool)
|
||||
pub const fn lxst_embedded::CallState::status(&self) -> lxst_embedded::SignallingStatus
|
||||
pub fn lxst_embedded::CallState::switch_mode(&mut self, lxst_embedded::CallMode) -> lxst_embedded::Actions
|
||||
pub fn lxst_embedded::CallState::switch_profile(&mut self, lxst_embedded::Profile) -> lxst_embedded::Actions
|
||||
pub const fn lxst_embedded::CallState::transmit_squelched(&self) -> bool
|
||||
pub struct lxst_embedded::CallTimes
|
||||
pub lxst_embedded::CallTimes::connect_ms: u64
|
||||
pub lxst_embedded::CallTimes::ring_ms: u64
|
||||
pub lxst_embedded::CallTimes::wait_ms: u64
|
||||
impl lxst_embedded::CallTimes
|
||||
pub const lxst_embedded::CallTimes::DEFAULT: Self
|
||||
impl core::default::Default for lxst_embedded::CallTimes
|
||||
pub fn lxst_embedded::CallTimes::default() -> Self
|
||||
pub struct lxst_embedded::Codec2PacketCodec<B>
|
||||
impl<B: lxst_embedded::Codec2Backend> lxst_embedded::Codec2PacketCodec<B>
|
||||
pub fn lxst_embedded::Codec2PacketCodec<B>::decode_into(&mut self, &[u8], &mut [i16]) -> core::result::Result<usize, lxst_embedded::Codec2PacketError<<B as lxst_embedded::Codec2Backend>::Error>>
|
||||
pub fn lxst_embedded::Codec2PacketCodec<B>::encode_into(&mut self, &[i16], &mut [u8]) -> core::result::Result<usize, lxst_embedded::Codec2PacketError<<B as lxst_embedded::Codec2Backend>::Error>>
|
||||
pub const fn lxst_embedded::Codec2PacketCodec<B>::mode(&self) -> lxst_embedded::wire::Codec2Mode
|
||||
pub fn lxst_embedded::Codec2PacketCodec<B>::new(lxst_embedded::Profile, B) -> core::result::Result<Self, lxst_embedded::Codec2PacketError<<B as lxst_embedded::Codec2Backend>::Error>>
|
||||
pub const fn lxst_embedded::Codec2PacketCodec<B>::payload_bytes(&self) -> usize
|
||||
pub const fn lxst_embedded::Codec2PacketCodec<B>::profile(&self) -> lxst_embedded::Profile
|
||||
pub const fn lxst_embedded::Codec2PacketCodec<B>::sample_frames(&self) -> usize
|
||||
pub struct lxst_embedded::Events
|
||||
impl lxst_embedded::Events
|
||||
pub fn lxst_embedded::Events::as_slice(&self) -> &[lxst_embedded::Event]
|
||||
pub struct lxst_embedded::MediaQueue
|
||||
impl lxst_embedded::MediaQueue
|
||||
pub fn lxst_embedded::MediaQueue::clear(&mut self)
|
||||
pub const fn lxst_embedded::MediaQueue::dropped(&self) -> u64
|
||||
pub const fn lxst_embedded::MediaQueue::is_empty(&self) -> bool
|
||||
pub const fn lxst_embedded::MediaQueue::len(&self) -> usize
|
||||
pub const fn lxst_embedded::MediaQueue::new() -> Self
|
||||
pub fn lxst_embedded::MediaQueue::pop(&mut self, u64, u32, &mut [u8]) -> core::result::Result<core::option::Option<usize>, lxst_embedded::QueueError>
|
||||
pub fn lxst_embedded::MediaQueue::push(&mut self, &[u8], u32, u64, u64) -> core::result::Result<(), lxst_embedded::QueueError>
|
||||
impl core::default::Default for lxst_embedded::MediaQueue
|
||||
pub fn lxst_embedded::MediaQueue::default() -> Self
|
||||
pub struct lxst_embedded::ProfileSet(_)
|
||||
impl lxst_embedded::ProfileSet
|
||||
pub const lxst_embedded::ProfileSet::CODEC2: Self
|
||||
pub const lxst_embedded::ProfileSet::OPUS_MEDIUM: Self
|
||||
pub const fn lxst_embedded::ProfileSet::contains(self, lxst_embedded::Profile) -> bool
|
||||
pub const fn lxst_embedded::ProfileSet::only(lxst_embedded::Profile) -> Self
|
||||
pub const fn lxst_embedded::ProfileSet::union(self, Self) -> Self
|
||||
pub struct lxst_embedded::Session
|
||||
impl lxst_embedded::Session
|
||||
pub fn lxst_embedded::Session::answer(&mut self, u64) -> lxst_embedded::Events
|
||||
pub const fn lxst_embedded::Session::audio_generation(&self) -> u32
|
||||
pub fn lxst_embedded::Session::audio_ready(&mut self, u32, bool) -> lxst_embedded::Events
|
||||
pub fn lxst_embedded::Session::end(&mut self, lxst_embedded::EndReason) -> lxst_embedded::Events
|
||||
pub const fn lxst_embedded::Session::ended(&self) -> core::option::Option<lxst_embedded::EndReason>
|
||||
pub fn lxst_embedded::Session::link_established(&mut self) -> lxst_embedded::Events
|
||||
pub fn lxst_embedded::Session::media_ready(&self) -> bool
|
||||
pub const fn lxst_embedded::Session::mode(&self) -> core::option::Option<lxst_embedded::CallMode>
|
||||
pub fn lxst_embedded::Session::new(lxst_embedded::CallRole, lxst_embedded::SessionConfig, u64) -> core::result::Result<Self, lxst_embedded::ConfigError>
|
||||
pub fn lxst_embedded::Session::peer_verified(&mut self, u64) -> lxst_embedded::Events
|
||||
pub fn lxst_embedded::Session::playback_allowed(&self) -> bool
|
||||
pub const fn lxst_embedded::Session::profile(&self) -> core::option::Option<lxst_embedded::Profile>
|
||||
pub fn lxst_embedded::Session::receive_profile_media(&mut self, lxst_embedded::Profile, u64) -> lxst_embedded::Events
|
||||
pub fn lxst_embedded::Session::receive_signal(&mut self, lxst_embedded::wire::Signal, u64) -> lxst_embedded::Events
|
||||
pub fn lxst_embedded::Session::set_transmitting(&mut self, bool, u64) -> lxst_embedded::Events
|
||||
pub const fn lxst_embedded::Session::status(&self) -> lxst_embedded::SignallingStatus
|
||||
pub fn lxst_embedded::Session::tick(&mut self, u64) -> lxst_embedded::Events
|
||||
pub const fn lxst_embedded::Session::transmitting(&self) -> bool
|
||||
pub struct lxst_embedded::SessionConfig
|
||||
pub lxst_embedded::SessionConfig::allowed: lxst_embedded::ProfileSet
|
||||
pub lxst_embedded::SessionConfig::capture: bool
|
||||
pub lxst_embedded::SessionConfig::playback: bool
|
||||
pub lxst_embedded::SessionConfig::preferred: lxst_embedded::Profile
|
||||
pub lxst_embedded::SessionConfig::times: lxst_embedded::CallTimes
|
||||
pub trait lxst_embedded::Codec2Backend
|
||||
pub type lxst_embedded::Codec2Backend::Error
|
||||
pub fn lxst_embedded::Codec2Backend::decode_native(&mut self, &[u8], &mut [i16]) -> core::result::Result<(), Self::Error>
|
||||
pub fn lxst_embedded::Codec2Backend::encode_native(&mut self, &[i16], &mut [u8]) -> core::result::Result<(), Self::Error>
|
||||
pub fn lxst_embedded::Codec2Backend::mode(&self) -> lxst_embedded::wire::Codec2Mode
|
||||
impl lxst_embedded::Codec2Backend for &mut lxst_codec2::Codec
|
||||
pub type &mut lxst_codec2::Codec::Error = lxst_codec2::Error
|
||||
pub fn &mut lxst_codec2::Codec::decode_native(&mut self, &[u8], &mut [i16]) -> core::result::Result<(), Self::Error>
|
||||
pub fn &mut lxst_codec2::Codec::encode_native(&mut self, &[i16], &mut [u8]) -> core::result::Result<(), Self::Error>
|
||||
pub fn &mut lxst_codec2::Codec::mode(&self) -> lxst_embedded::wire::Codec2Mode
|
||||
@@ -0,0 +1,54 @@
|
||||
pub mod lxst_rns
|
||||
pub enum lxst_rns::Error
|
||||
pub lxst_rns::Error::LinkEncrypt(alloc::string::String)
|
||||
pub lxst_rns::Error::LinkNotActive(rns_link::link::LinkState)
|
||||
pub lxst_rns::Error::Lxst(lxst_core::wire::Error)
|
||||
pub lxst_rns::Error::Opus(lxst_core::opus::OpusCodecError)
|
||||
pub lxst_rns::Error::PayloadExceedsMdu
|
||||
pub lxst_rns::Error::PayloadExceedsMdu::mdu: usize
|
||||
pub lxst_rns::Error::PayloadExceedsMdu::payload_len: usize
|
||||
pub lxst_rns::Error::Stream(lxst_core::stream::StreamError)
|
||||
pub struct lxst_rns::InboundLxstPacket
|
||||
pub lxst_rns::InboundLxstPacket::frame_events: alloc::vec::Vec<lxst_core::stream::FrameStreamEvent>
|
||||
pub lxst_rns::InboundLxstPacket::link_id: [u8; 16]
|
||||
pub lxst_rns::InboundLxstPacket::packet: lxst_core::wire::LxstPacket
|
||||
pub struct lxst_rns::LxstLinkIngress
|
||||
impl lxst_rns::LxstLinkIngress
|
||||
pub fn lxst_rns::LxstLinkIngress::accept_plaintext(&mut self, [u8; 16], &[u8]) -> core::result::Result<lxst_rns::InboundLxstPacket, lxst_rns::Error>
|
||||
pub const fn lxst_rns::LxstLinkIngress::current_codec(&self) -> core::option::Option<lxst_core::wire::CodecKind>
|
||||
pub fn lxst_rns::LxstLinkIngress::new() -> Self
|
||||
pub struct lxst_rns::LxstMediaEgress
|
||||
impl lxst_rns::LxstMediaEgress
|
||||
pub const lxst_rns::LxstMediaEgress::PYTHON_COMPATIBLE: Self
|
||||
pub fn lxst_rns::LxstMediaEgress::new(usize) -> core::result::Result<Self, lxst_rns::Error>
|
||||
pub fn lxst_rns::LxstMediaEgress::pack_frames(self, &rns_link::link::Link, impl core::iter::traits::collect::IntoIterator<Item = lxst_core::wire::Frame>) -> core::result::Result<alloc::vec::Vec<lxst_rns::PackedLinkPacket>, lxst_rns::Error>
|
||||
pub fn lxst_rns::LxstMediaEgress::pack_raw_frames(self, &rns_link::link::Link, lxst_core::wire::RawBitDepth, impl core::iter::traits::collect::IntoIterator<Item = lxst_core::raw::RawAudioFrame>) -> core::result::Result<alloc::vec::Vec<lxst_rns::PackedLinkPacket>, lxst_rns::Error>
|
||||
pub const fn lxst_rns::LxstMediaEgress::packetizer(&self) -> lxst_core::stream::FramePacketizer
|
||||
pub struct lxst_rns::LxstMediaIngress
|
||||
impl lxst_rns::LxstMediaIngress
|
||||
pub fn lxst_rns::LxstMediaIngress::accept_plaintext(&mut self, [u8; 16], &[u8]) -> core::result::Result<lxst_rns::MediaIngressResult, lxst_rns::Error>
|
||||
pub const fn lxst_rns::LxstMediaIngress::current_codec(&self) -> core::option::Option<lxst_core::wire::CodecKind>
|
||||
pub fn lxst_rns::LxstMediaIngress::jitter_len(&self) -> usize
|
||||
pub const fn lxst_rns::LxstMediaIngress::jitter_stats(&self) -> lxst_core::stream::JitterStats
|
||||
pub fn lxst_rns::LxstMediaIngress::new(usize, lxst_core::stream::DropPolicy) -> core::result::Result<Self, lxst_rns::Error>
|
||||
pub fn lxst_rns::LxstMediaIngress::pop_frame(&mut self) -> core::option::Option<lxst_core::wire::Frame>
|
||||
pub fn lxst_rns::LxstMediaIngress::pop_opus_frame(&mut self, &mut lxst_core::opus::OpusDecoderState) -> core::result::Result<core::option::Option<lxst_core::raw::RawAudioFrame>, lxst_rns::Error>
|
||||
pub fn lxst_rns::LxstMediaIngress::pop_raw_frame(&mut self) -> core::result::Result<core::option::Option<lxst_core::raw::RawAudioFrame>, lxst_rns::Error>
|
||||
pub struct lxst_rns::MediaIngressResult
|
||||
pub lxst_rns::MediaIngressResult::inbound: lxst_rns::InboundLxstPacket
|
||||
pub lxst_rns::MediaIngressResult::jitter_pushes: alloc::vec::Vec<lxst_core::stream::JitterPush<lxst_core::wire::Frame>>
|
||||
pub struct lxst_rns::PackedLinkPacket
|
||||
pub lxst_rns::PackedLinkPacket::destination_hash: [u8; 16]
|
||||
pub lxst_rns::PackedLinkPacket::packet_hash: [u8; 32]
|
||||
pub lxst_rns::PackedLinkPacket::raw: bytes::bytes::Bytes
|
||||
pub struct lxst_rns::PreparedLinkEndpointSend
|
||||
pub lxst_rns::PreparedLinkEndpointSend::message: rns_transport::messages::TransportMessage
|
||||
pub lxst_rns::PreparedLinkEndpointSend::packet: lxst_rns::PackedLinkPacket
|
||||
pub lxst_rns::PreparedLinkEndpointSend::result_rx: tokio::sync::oneshot::Receiver<rns_transport::messages::LinkEndpointSendResult>
|
||||
pub fn lxst_rns::pack_link_payload(&rns_link::link::Link, &[u8]) -> core::result::Result<lxst_rns::PackedLinkPacket, lxst_rns::Error>
|
||||
pub fn lxst_rns::pack_lxst_link_packet(&rns_link::link::Link, &lxst_core::wire::LxstPacket) -> core::result::Result<lxst_rns::PackedLinkPacket, lxst_rns::Error>
|
||||
pub fn lxst_rns::prepare_link_payload_send(&rns_link::link::Link, rns_transport::messages::LinkEndpointRole, &[u8]) -> core::result::Result<lxst_rns::PreparedLinkEndpointSend, lxst_rns::Error>
|
||||
pub fn lxst_rns::prepare_lxst_link_packet_send(&rns_link::link::Link, rns_transport::messages::LinkEndpointRole, &lxst_core::wire::LxstPacket) -> core::result::Result<lxst_rns::PreparedLinkEndpointSend, lxst_rns::Error>
|
||||
pub fn lxst_rns::prepare_packed_link_endpoint_best_effort_send(lxst_rns::PackedLinkPacket, rns_transport::messages::LinkEndpointRole) -> lxst_rns::PreparedLinkEndpointSend
|
||||
pub fn lxst_rns::prepare_packed_link_endpoint_final_send(lxst_rns::PackedLinkPacket, rns_transport::messages::LinkEndpointRole) -> lxst_rns::PreparedLinkEndpointSend
|
||||
pub fn lxst_rns::prepare_packed_link_endpoint_send(lxst_rns::PackedLinkPacket, rns_transport::messages::LinkEndpointRole) -> lxst_rns::PreparedLinkEndpointSend
|
||||
@@ -0,0 +1,391 @@
|
||||
pub mod lxst_telephony
|
||||
pub enum lxst_telephony::CallerAllowPolicy
|
||||
pub lxst_telephony::CallerAllowPolicy::All
|
||||
pub lxst_telephony::CallerAllowPolicy::List(alloc::vec::Vec<lxst_telephony::IdentityHash>)
|
||||
pub lxst_telephony::CallerAllowPolicy::None
|
||||
pub enum lxst_telephony::Error
|
||||
pub lxst_telephony::Error::Audio(alloc::string::String)
|
||||
pub lxst_telephony::Error::CallNotAnswerable
|
||||
pub lxst_telephony::Error::CallNotEstablished
|
||||
pub lxst_telephony::Error::Destination(rns_identity::destination::DestinationError)
|
||||
pub lxst_telephony::Error::LineBusy
|
||||
pub lxst_telephony::Error::LinkDestinationClosed
|
||||
pub lxst_telephony::Error::LinkOperation(alloc::string::String)
|
||||
pub lxst_telephony::Error::LinkProofInvalid(alloc::string::String)
|
||||
pub lxst_telephony::Error::LinkStamp(rns_link::stamp::LinkStampError)
|
||||
pub lxst_telephony::Error::MediaProfileMismatch
|
||||
pub lxst_telephony::Error::MediaProfileMismatch::active: lxst_core::profile::Profile
|
||||
pub lxst_telephony::Error::MediaProfileMismatch::requested: lxst_core::profile::Profile
|
||||
pub lxst_telephony::Error::NoActiveCall
|
||||
pub lxst_telephony::Error::NoSigningKey
|
||||
pub lxst_telephony::Error::Opus(lxst_core::opus::OpusCodecError)
|
||||
pub lxst_telephony::Error::RemotePathNotDiscovered
|
||||
pub lxst_telephony::Error::RemotePublicKeyMissing
|
||||
pub lxst_telephony::Error::RemoteTelephonyPeerNotDiscovered
|
||||
pub lxst_telephony::Error::Rns(lxst_rns::Error)
|
||||
pub lxst_telephony::Error::ServiceControlClosed
|
||||
pub lxst_telephony::Error::ServiceEventClosed
|
||||
pub lxst_telephony::Error::ServiceEventFull
|
||||
pub lxst_telephony::Error::TransportClosed
|
||||
pub lxst_telephony::Error::TransportFull
|
||||
pub lxst_telephony::Error::TransportQueryClosed
|
||||
pub lxst_telephony::Error::UnexpectedLinkEvent
|
||||
pub lxst_telephony::Error::UnexpectedTransportQueryResponse
|
||||
pub lxst_telephony::Error::UnknownLink
|
||||
pub lxst_telephony::Error::WrongActiveLink
|
||||
pub enum lxst_telephony::OpusReceiveStreamStopReason
|
||||
pub lxst_telephony::OpusReceiveStreamStopReason::CallEnded
|
||||
pub lxst_telephony::OpusReceiveStreamStopReason::ProfileChanged
|
||||
pub lxst_telephony::OpusReceiveStreamStopReason::Replaced
|
||||
pub lxst_telephony::OpusReceiveStreamStopReason::Requested
|
||||
pub lxst_telephony::OpusReceiveStreamStopReason::SinkClosed
|
||||
pub enum lxst_telephony::OpusTransmitStreamStopReason
|
||||
pub lxst_telephony::OpusTransmitStreamStopReason::CallEnded
|
||||
pub lxst_telephony::OpusTransmitStreamStopReason::ProfileChanged
|
||||
pub lxst_telephony::OpusTransmitStreamStopReason::Replaced
|
||||
pub lxst_telephony::OpusTransmitStreamStopReason::Requested
|
||||
pub lxst_telephony::OpusTransmitStreamStopReason::SourceClosed
|
||||
pub enum lxst_telephony::QueuedLinkPacketKind
|
||||
pub lxst_telephony::QueuedLinkPacketKind::LinkClose
|
||||
pub lxst_telephony::QueuedLinkPacketKind::LinkIdentify
|
||||
pub lxst_telephony::QueuedLinkPacketKind::LxstData
|
||||
pub enum lxst_telephony::TelephonyCommand
|
||||
pub lxst_telephony::TelephonyCommand::CallTerminated
|
||||
pub lxst_telephony::TelephonyCommand::CallTerminated::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::CallTerminated::reason: core::option::Option<lxst_core::profile::SignallingStatus>
|
||||
pub lxst_telephony::TelephonyCommand::IdentifyLocalIdentity
|
||||
pub lxst_telephony::TelephonyCommand::IdentifyLocalIdentity::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::IgnoredSignal
|
||||
pub lxst_telephony::TelephonyCommand::IgnoredSignal::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::IgnoredSignal::signal: lxst_core::wire::Signal
|
||||
pub lxst_telephony::TelephonyCommand::OpenAudioPipelines
|
||||
pub lxst_telephony::TelephonyCommand::OpenAudioPipelines::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::PrepareDialingPipelines
|
||||
pub lxst_telephony::TelephonyCommand::PrepareDialingPipelines::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::ResetDialingPipelines
|
||||
pub lxst_telephony::TelephonyCommand::ResetDialingPipelines::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::RingIncomingCall
|
||||
pub lxst_telephony::TelephonyCommand::RingIncomingCall::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::RingIncomingCall::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::TelephonyCommand::SelectMode
|
||||
pub lxst_telephony::TelephonyCommand::SelectMode::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SelectMode::mode: lxst_core::profile::CallMode
|
||||
pub lxst_telephony::TelephonyCommand::SelectProfile
|
||||
pub lxst_telephony::TelephonyCommand::SelectProfile::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SelectProfile::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyCommand::SendSignal
|
||||
pub lxst_telephony::TelephonyCommand::SendSignal::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SendSignal::signal: lxst_core::wire::Signal
|
||||
pub lxst_telephony::TelephonyCommand::SendSignalPair
|
||||
pub lxst_telephony::TelephonyCommand::SendSignalPair::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SendSignalPair::signals: [lxst_core::wire::Signal; 2]
|
||||
pub lxst_telephony::TelephonyCommand::StartAudioPipelines
|
||||
pub lxst_telephony::TelephonyCommand::StartAudioPipelines::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::StartDialTone
|
||||
pub lxst_telephony::TelephonyCommand::StartDialTone::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::StopAudioPipelines
|
||||
pub lxst_telephony::TelephonyCommand::StopAudioPipelines::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SwitchMode
|
||||
pub lxst_telephony::TelephonyCommand::SwitchMode::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SwitchMode::mode: lxst_core::profile::CallMode
|
||||
pub lxst_telephony::TelephonyCommand::SwitchProfile
|
||||
pub lxst_telephony::TelephonyCommand::SwitchProfile::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyCommand::SwitchProfile::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyCommand::TeardownLink
|
||||
pub lxst_telephony::TelephonyCommand::TeardownLink::link_id: lxst_telephony::LinkId
|
||||
impl lxst_telephony::TelephonyCommand
|
||||
pub const fn lxst_telephony::TelephonyCommand::link_id(&self) -> lxst_telephony::LinkId
|
||||
pub const fn lxst_telephony::TelephonyCommand::signal(&self) -> core::option::Option<lxst_core::wire::Signal>
|
||||
pub fn lxst_telephony::TelephonyCommand::to_lxst_packet(&self) -> core::option::Option<lxst_core::wire::LxstPacket>
|
||||
pub enum lxst_telephony::TelephonyCommandEffect
|
||||
pub lxst_telephony::TelephonyCommandEffect::Noop
|
||||
pub lxst_telephony::TelephonyCommandEffect::QueuedLinkPacket
|
||||
pub lxst_telephony::TelephonyCommandEffect::QueuedLinkPacket::kind: lxst_telephony::QueuedLinkPacketKind
|
||||
pub lxst_telephony::TelephonyCommandEffect::QueuedLinkPacket::link_id: lxst_telephony::LinkId
|
||||
pub enum lxst_telephony::TelephonyControl
|
||||
pub lxst_telephony::TelephonyControl::Announce
|
||||
pub lxst_telephony::TelephonyControl::Answer
|
||||
pub lxst_telephony::TelephonyControl::Answer::expected_link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyControl::Answer::reply: tokio::sync::oneshot::Sender<core::result::Result<lxst_telephony::ActiveCallSnapshot, lxst_telephony::Error>>
|
||||
pub lxst_telephony::TelephonyControl::Call
|
||||
pub lxst_telephony::TelephonyControl::Call::discovery_timeout: core::time::Duration
|
||||
pub lxst_telephony::TelephonyControl::Call::mode: core::option::Option<lxst_core::profile::CallMode>
|
||||
pub lxst_telephony::TelephonyControl::Call::profile: core::option::Option<lxst_core::profile::Profile>
|
||||
pub lxst_telephony::TelephonyControl::Call::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::TelephonyControl::DisableRemoteModeFollow
|
||||
pub lxst_telephony::TelephonyControl::Hangup
|
||||
pub lxst_telephony::TelephonyControl::Hangup::ring_timeout: bool
|
||||
pub lxst_telephony::TelephonyControl::SendAudioFrames
|
||||
pub lxst_telephony::TelephonyControl::SendAudioFrames::frames: alloc::vec::Vec<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::SendAudioFrames::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyControl::SendOpusFrames
|
||||
pub lxst_telephony::TelephonyControl::SendOpusFrames::frames: alloc::vec::Vec<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::SendOpusFrames::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyControl::SendRawFrames
|
||||
pub lxst_telephony::TelephonyControl::SendRawFrames::bit_depth: lxst_core::wire::RawBitDepth
|
||||
pub lxst_telephony::TelephonyControl::SendRawFrames::frames: alloc::vec::Vec<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::SetAccessPolicy(lxst_telephony::CallerAccessPolicy)
|
||||
pub lxst_telephony::TelephonyControl::SetExternalBusy(bool)
|
||||
pub lxst_telephony::TelephonyControl::Shutdown
|
||||
pub lxst_telephony::TelephonyControl::SquelchTransmit(bool)
|
||||
pub lxst_telephony::TelephonyControl::StartAudioReceiveStream
|
||||
pub lxst_telephony::TelephonyControl::StartAudioReceiveStream::frames: tokio::sync::mpsc::bounded::Sender<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::StartAudioStream
|
||||
pub lxst_telephony::TelephonyControl::StartAudioStream::frames: tokio::sync::mpsc::bounded::Receiver<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::StartAudioStream::gate: core::option::Option<alloc::sync::Arc<lxst_telephony::AudioTransmitGate>>
|
||||
pub lxst_telephony::TelephonyControl::StartAudioStream::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyControl::StartAudioStream::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyControl::StartOpusReceiveStream
|
||||
pub lxst_telephony::TelephonyControl::StartOpusReceiveStream::frames: tokio::sync::mpsc::bounded::Sender<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::StartOpusStream
|
||||
pub lxst_telephony::TelephonyControl::StartOpusStream::frames: tokio::sync::mpsc::bounded::Receiver<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyControl::StartOpusStream::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyControl::StopAudioReceiveStream
|
||||
pub lxst_telephony::TelephonyControl::StopAudioStream
|
||||
pub lxst_telephony::TelephonyControl::StopOpusReceiveStream
|
||||
pub lxst_telephony::TelephonyControl::StopOpusStream
|
||||
pub lxst_telephony::TelephonyControl::SwitchMode
|
||||
pub lxst_telephony::TelephonyControl::SwitchMode::mode: lxst_core::profile::CallMode
|
||||
pub lxst_telephony::TelephonyControl::SwitchProfile
|
||||
pub lxst_telephony::TelephonyControl::SwitchProfile::profile: lxst_core::profile::Profile
|
||||
pub enum lxst_telephony::TelephonyLinkEvent
|
||||
pub lxst_telephony::TelephonyLinkEvent::IncomingLinkEstablished
|
||||
pub lxst_telephony::TelephonyLinkEvent::IncomingLinkEstablished::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkClosed
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkClosed::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkEstablished
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkEstablished::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkPacket
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkPacket::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyLinkEvent::LinkPacket::plaintext: alloc::vec::Vec<u8>
|
||||
pub lxst_telephony::TelephonyLinkEvent::OutgoingLinkEstablished
|
||||
pub lxst_telephony::TelephonyLinkEvent::OutgoingLinkEstablished::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyLinkEvent::RemoteIdentified
|
||||
pub lxst_telephony::TelephonyLinkEvent::RemoteIdentified::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyLinkEvent::RemoteIdentified::remote_identity: lxst_telephony::IdentityHash
|
||||
pub enum lxst_telephony::TelephonyServiceEvent
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioFramesReceived
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioFramesReceived::frames: alloc::vec::Vec<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioFramesReceived::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioFramesReceived::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamFrames
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamFrames::dropped: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamFrames::frames: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamFrames::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamFrames::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStarted
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStarted::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStarted::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStopped
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStopped::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStopped::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioReceiveStreamStopped::reason: lxst_telephony::OpusReceiveStreamStopReason
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStarted
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStarted::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStarted::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStopped
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStopped::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStopped::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::AudioTransmitStreamStopped::reason: lxst_telephony::OpusTransmitStreamStopReason
|
||||
pub lxst_telephony::TelephonyServiceEvent::CallTerminated
|
||||
pub lxst_telephony::TelephonyServiceEvent::CallTerminated::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::CallTerminated::reason: core::option::Option<lxst_core::profile::SignallingStatus>
|
||||
pub lxst_telephony::TelephonyServiceEvent::Drive(lxst_telephony::TelephonyDriveStep)
|
||||
pub lxst_telephony::TelephonyServiceEvent::Error
|
||||
pub lxst_telephony::TelephonyServiceEvent::Error::message: alloc::string::String
|
||||
pub lxst_telephony::TelephonyServiceEvent::IncomingCall
|
||||
pub lxst_telephony::TelephonyServiceEvent::IncomingCall::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::IncomingCall::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaReceived
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaReceived::frames: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaReceived::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaSent
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaSent::frames: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaSent::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::MediaSent::packets: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusFramesReceived
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusFramesReceived::frames: alloc::vec::Vec<lxst_core::raw::RawAudioFrame>
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusFramesReceived::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusFramesReceived::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamFrames
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamFrames::dropped: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamFrames::frames: usize
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamFrames::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamFrames::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStarted
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStarted::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStarted::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStopped
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStopped::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStopped::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusReceiveStreamStopped::reason: lxst_telephony::OpusReceiveStreamStopReason
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStarted
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStarted::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStarted::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStopped
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStopped::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStopped::profile: lxst_core::profile::Profile
|
||||
pub lxst_telephony::TelephonyServiceEvent::OpusTransmitStreamStopped::reason: lxst_telephony::OpusTransmitStreamStopReason
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallFailed
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallFailed::message: alloc::string::String
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallFailed::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallPending
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallPending::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallStarted
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallStarted::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::TelephonyServiceEvent::OutgoingCallStarted::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::TelephonyServiceEvent::Snapshot(lxst_telephony::TelephonyRuntimeSnapshot)
|
||||
pub lxst_telephony::TelephonyServiceEvent::Stopped
|
||||
pub struct lxst_telephony::ActiveCall
|
||||
pub lxst_telephony::ActiveCall::call: lxst_core::telephony::TelephonyCall
|
||||
pub lxst_telephony::ActiveCall::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::ActiveCall::remote_identity: lxst_telephony::IdentityHash
|
||||
pub struct lxst_telephony::ActiveCallSnapshot
|
||||
pub lxst_telephony::ActiveCallSnapshot::answered: bool
|
||||
pub lxst_telephony::ActiveCallSnapshot::link_id: lxst_telephony::LinkId
|
||||
pub lxst_telephony::ActiveCallSnapshot::mode: core::option::Option<lxst_core::profile::CallMode>
|
||||
pub lxst_telephony::ActiveCallSnapshot::profile: core::option::Option<lxst_core::profile::Profile>
|
||||
pub lxst_telephony::ActiveCallSnapshot::remote_identity: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::ActiveCallSnapshot::role: lxst_core::telephony::CallRole
|
||||
pub lxst_telephony::ActiveCallSnapshot::status: lxst_core::profile::SignallingStatus
|
||||
pub lxst_telephony::ActiveCallSnapshot::transmit_squelched: bool
|
||||
pub struct lxst_telephony::AudioTransmitGate
|
||||
impl lxst_telephony::AudioTransmitGate
|
||||
pub fn lxst_telephony::AudioTransmitGate::allows(&self) -> bool
|
||||
pub fn lxst_telephony::AudioTransmitGate::close(&self)
|
||||
pub fn lxst_telephony::AudioTransmitGate::new() -> Self
|
||||
pub fn lxst_telephony::AudioTransmitGate::serial(&self) -> u64
|
||||
pub fn lxst_telephony::AudioTransmitGate::update(&self, u64, bool) -> bool
|
||||
pub struct lxst_telephony::CallerAccessPolicy
|
||||
pub lxst_telephony::CallerAccessPolicy::allowed: lxst_telephony::CallerAllowPolicy
|
||||
pub lxst_telephony::CallerAccessPolicy::blocked: alloc::vec::Vec<lxst_telephony::IdentityHash>
|
||||
impl lxst_telephony::CallerAccessPolicy
|
||||
pub fn lxst_telephony::CallerAccessPolicy::is_allowed(&self, &lxst_telephony::IdentityHash) -> bool
|
||||
impl core::default::Default for lxst_telephony::CallerAccessPolicy
|
||||
pub fn lxst_telephony::CallerAccessPolicy::default() -> Self
|
||||
pub struct lxst_telephony::OutgoingLinkRequest
|
||||
impl core::fmt::Debug for lxst_telephony::OutgoingLinkRequest
|
||||
pub fn lxst_telephony::OutgoingLinkRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct lxst_telephony::RemoteTelephonyPeer
|
||||
pub lxst_telephony::RemoteTelephonyPeer::destination_hash: [u8; 16]
|
||||
pub lxst_telephony::RemoteTelephonyPeer::hops: u8
|
||||
pub lxst_telephony::RemoteTelephonyPeer::identity_hash: lxst_telephony::IdentityHash
|
||||
pub lxst_telephony::RemoteTelephonyPeer::public_key: [u8; 64]
|
||||
pub struct lxst_telephony::TelephonyDriveStep
|
||||
pub lxst_telephony::TelephonyDriveStep::effects: alloc::vec::Vec<lxst_telephony::TelephonyCommandEffect>
|
||||
pub lxst_telephony::TelephonyDriveStep::step: lxst_telephony::TelephonyStep
|
||||
pub struct lxst_telephony::TelephonyRnsEndpoint
|
||||
pub lxst_telephony::TelephonyRnsEndpoint::destination_hash: [u8; 16]
|
||||
pub lxst_telephony::TelephonyRnsEndpoint::link_closed_rx: tokio::sync::mpsc::bounded::Receiver<lxst_telephony::LinkId>
|
||||
pub lxst_telephony::TelephonyRnsEndpoint::link_established_rx: tokio::sync::mpsc::bounded::Receiver<lxst_telephony::LinkId>
|
||||
pub lxst_telephony::TelephonyRnsEndpoint::link_identified_rx: tokio::sync::mpsc::bounded::Receiver<(lxst_telephony::LinkId, lxst_telephony::IdentityHash)>
|
||||
pub lxst_telephony::TelephonyRnsEndpoint::link_packet_rx: tokio::sync::mpsc::unbounded::UnboundedReceiver<(alloc::vec::Vec<u8>, lxst_telephony::LinkId)>
|
||||
pub lxst_telephony::TelephonyRnsEndpoint::manager: rns_runtime::link_manager::LinkManager
|
||||
impl lxst_telephony::TelephonyRnsEndpoint
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::announce(&self) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::await_path_to_identity(&self, lxst_telephony::IdentityHash, core::time::Duration) -> impl core::future::future::Future<Output = core::result::Result<(), lxst_telephony::Error>> + core::marker::Send + 'static
|
||||
pub async fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, core::option::Option<lxst_core::profile::Profile>, core::time::Duration) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link_with_mode(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, [u8; 64], core::option::Option<lxst_core::profile::Profile>, core::option::Option<lxst_core::profile::CallMode>, u8) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link_with_remote_pubkey(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, [u8; 64], core::option::Option<lxst_core::profile::Profile>, u8) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::begin_prepared_outgoing_link(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, [u8; 64], core::option::Option<lxst_core::profile::Profile>, core::option::Option<lxst_core::profile::CallMode>, lxst_telephony::OutgoingLinkRequest) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::deregister_destination(&self) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::deregister_link_destination(&self, lxst_telephony::LinkId) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::discover_remote_telephony_peer(&self, lxst_telephony::IdentityHash, core::time::Duration) -> impl core::future::future::Future<Output = core::result::Result<lxst_telephony::RemoteTelephonyPeer, lxst_telephony::Error>> + core::marker::Send + 'static
|
||||
pub async fn lxst_telephony::TelephonyRnsEndpoint::drive_once(&mut self, &mut lxst_telephony::TelephonyRuntimeCore) -> core::result::Result<core::option::Option<lxst_telephony::TelephonyDriveStep>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::execute_command(&mut self, &lxst_telephony::TelephonyCommand) -> core::result::Result<lxst_telephony::TelephonyCommandEffect, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::execute_commands(&mut self, &[lxst_telephony::TelephonyCommand]) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommandEffect>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::media_drop_count(&self, lxst_telephony::LinkId) -> u64
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::queue_frames(&mut self, lxst_telephony::LinkId, impl core::iter::traits::collect::IntoIterator<Item = lxst_core::wire::Frame>) -> core::result::Result<usize, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::queue_raw_frames(&mut self, lxst_telephony::LinkId, lxst_core::wire::RawBitDepth, impl core::iter::traits::collect::IntoIterator<Item = lxst_core::raw::RawAudioFrame>) -> core::result::Result<usize, lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::TelephonyRnsEndpoint::recv_link_event(&mut self) -> core::result::Result<core::option::Option<lxst_telephony::TelephonyLinkEvent>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::register(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, &rns_identity::identity::Identity) -> core::result::Result<Self, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::request_path_to_identity(&self, &lxst_telephony::IdentityHash) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::TelephonyRnsEndpoint::step(&mut self, &mut lxst_telephony::TelephonyRuntimeCore) -> core::result::Result<core::option::Option<lxst_telephony::TelephonyStep>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::tick_reticulum(&mut self)
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::try_drive_once(&mut self, &mut lxst_telephony::TelephonyRuntimeCore) -> core::result::Result<core::option::Option<lxst_telephony::TelephonyDriveStep>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::try_drive_ready(&mut self, &mut lxst_telephony::TelephonyRuntimeCore) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyDriveStep>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::try_pump_reticulum(&mut self) -> bool
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::try_recv_link_event(&mut self) -> core::result::Result<core::option::Option<lxst_telephony::TelephonyLinkEvent>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRnsEndpoint::try_step(&mut self, &mut lxst_telephony::TelephonyRuntimeCore) -> core::result::Result<core::option::Option<lxst_telephony::TelephonyStep>, lxst_telephony::Error>
|
||||
pub struct lxst_telephony::TelephonyRuntimeCore
|
||||
impl lxst_telephony::TelephonyRuntimeCore
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::accept_link_event(&mut self, lxst_telephony::TelephonyLinkEvent) -> core::result::Result<lxst_telephony::TelephonyStep, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::accept_lxst_plaintext(&mut self, lxst_telephony::LinkId, &[u8]) -> core::result::Result<lxst_telephony::TelephonyStep, lxst_telephony::Error>
|
||||
pub const fn lxst_telephony::TelephonyRuntimeCore::access_policy(&self) -> &lxst_telephony::CallerAccessPolicy
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::active_call(&self) -> core::option::Option<&lxst_telephony::ActiveCall>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::answer_active(&mut self, lxst_telephony::LinkId) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::caller_identified(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
|
||||
pub const fn lxst_telephony::TelephonyRuntimeCore::dialling(&self) -> bool
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::disable_remote_mode_follow(&mut self) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub const fn lxst_telephony::TelephonyRuntimeCore::external_busy(&self) -> bool
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::hangup_active(&mut self, bool) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::incoming_link_established(&mut self, lxst_telephony::LinkId) -> alloc::vec::Vec<lxst_telephony::TelephonyCommand>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::line_busy(&self) -> bool
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::link_closed(&mut self, lxst_telephony::LinkId) -> alloc::vec::Vec<lxst_telephony::TelephonyCommand>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::new() -> Self
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::outgoing_link_established(&mut self, lxst_telephony::LinkId) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::pending_link_count(&self) -> usize
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::receive_signal(&mut self, lxst_telephony::LinkId, lxst_core::wire::Signal) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::set_access_policy(&mut self, lxst_telephony::CallerAccessPolicy)
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::set_active_transmit_squelched(&mut self, bool) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::set_external_busy(&mut self, bool)
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::shutdown(&mut self) -> alloc::vec::Vec<lxst_telephony::TelephonyCommand>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::snapshot(&self) -> lxst_telephony::TelephonyRuntimeSnapshot
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::start_outgoing_call(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash, core::option::Option<lxst_core::profile::Profile>) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::start_outgoing_call_with_mode(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash, core::option::Option<lxst_core::profile::Profile>, core::option::Option<lxst_core::profile::CallMode>) -> core::result::Result<(), lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::switch_active_mode(&mut self, lxst_core::profile::CallMode) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::switch_active_profile(&mut self, lxst_core::profile::Profile) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyRuntimeCore::with_access_policy(lxst_telephony::CallerAccessPolicy) -> Self
|
||||
pub struct lxst_telephony::TelephonyRuntimeSnapshot
|
||||
pub lxst_telephony::TelephonyRuntimeSnapshot::active_call: core::option::Option<lxst_telephony::ActiveCallSnapshot>
|
||||
pub lxst_telephony::TelephonyRuntimeSnapshot::external_busy: bool
|
||||
pub lxst_telephony::TelephonyRuntimeSnapshot::pending_link_count: usize
|
||||
pub struct lxst_telephony::TelephonyService
|
||||
impl lxst_telephony::TelephonyService
|
||||
pub fn lxst_telephony::TelephonyService::new(lxst_telephony::TelephonyRnsEndpoint, lxst_telephony::TelephonyRuntimeCore, tokio::sync::mpsc::bounded::Receiver<lxst_telephony::TelephonyControl>, tokio::sync::mpsc::bounded::Sender<lxst_telephony::TelephonyServiceEvent>) -> Self
|
||||
pub fn lxst_telephony::TelephonyService::registered(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, &rns_identity::identity::Identity) -> core::result::Result<lxst_telephony::TelephonyServiceParts, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::TelephonyService::registered_with_config(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, &rns_identity::identity::Identity, lxst_telephony::TelephonyServiceConfig, lxst_telephony::TelephonyServiceChannelConfig) -> core::result::Result<lxst_telephony::TelephonyServiceParts, lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::TelephonyService::run(self)
|
||||
pub fn lxst_telephony::TelephonyService::with_config(lxst_telephony::TelephonyRnsEndpoint, lxst_telephony::TelephonyRuntimeCore, tokio::sync::mpsc::bounded::Receiver<lxst_telephony::TelephonyControl>, tokio::sync::mpsc::bounded::Sender<lxst_telephony::TelephonyServiceEvent>, lxst_telephony::TelephonyServiceConfig) -> Self
|
||||
pub struct lxst_telephony::TelephonyServiceChannelConfig
|
||||
pub lxst_telephony::TelephonyServiceChannelConfig::control_capacity: usize
|
||||
pub lxst_telephony::TelephonyServiceChannelConfig::event_capacity: usize
|
||||
impl core::default::Default for lxst_telephony::TelephonyServiceChannelConfig
|
||||
pub fn lxst_telephony::TelephonyServiceChannelConfig::default() -> Self
|
||||
pub struct lxst_telephony::TelephonyServiceConfig
|
||||
pub lxst_telephony::TelephonyServiceConfig::announce_interval: core::option::Option<core::time::Duration>
|
||||
pub lxst_telephony::TelephonyServiceConfig::announce_on_start: bool
|
||||
pub lxst_telephony::TelephonyServiceConfig::connect_timeout: core::option::Option<core::time::Duration>
|
||||
pub lxst_telephony::TelephonyServiceConfig::incoming_ring_timeout: core::option::Option<core::time::Duration>
|
||||
pub lxst_telephony::TelephonyServiceConfig::media_frames_per_tick: usize
|
||||
pub lxst_telephony::TelephonyServiceConfig::outgoing_call_timeout: core::option::Option<core::time::Duration>
|
||||
pub lxst_telephony::TelephonyServiceConfig::poll_interval: core::time::Duration
|
||||
pub lxst_telephony::TelephonyServiceConfig::startup_announce_retries: u8
|
||||
pub lxst_telephony::TelephonyServiceConfig::startup_announce_retry_interval: core::option::Option<core::time::Duration>
|
||||
impl core::default::Default for lxst_telephony::TelephonyServiceConfig
|
||||
pub fn lxst_telephony::TelephonyServiceConfig::default() -> Self
|
||||
pub struct lxst_telephony::TelephonyServiceParts
|
||||
pub lxst_telephony::TelephonyServiceParts::control_tx: tokio::sync::mpsc::bounded::Sender<lxst_telephony::TelephonyControl>
|
||||
pub lxst_telephony::TelephonyServiceParts::event_rx: tokio::sync::mpsc::bounded::Receiver<lxst_telephony::TelephonyServiceEvent>
|
||||
pub lxst_telephony::TelephonyServiceParts::service: lxst_telephony::TelephonyService
|
||||
pub struct lxst_telephony::TelephonyStep
|
||||
pub lxst_telephony::TelephonyStep::commands: alloc::vec::Vec<lxst_telephony::TelephonyCommand>
|
||||
pub lxst_telephony::TelephonyStep::inbound: core::option::Option<lxst_rns::InboundLxstPacket>
|
||||
impl lxst_telephony::TelephonyStep
|
||||
pub fn lxst_telephony::TelephonyStep::commands(alloc::vec::Vec<lxst_telephony::TelephonyCommand>) -> Self
|
||||
pub const lxst_telephony::TELEPHONY_ANNOUNCE_INTERVAL: core::time::Duration
|
||||
pub const lxst_telephony::TELEPHONY_CONNECT_TIME: core::time::Duration
|
||||
pub const lxst_telephony::TELEPHONY_JOB_INTERVAL: core::time::Duration
|
||||
pub const lxst_telephony::TELEPHONY_RING_TIME: core::time::Duration
|
||||
pub const lxst_telephony::TELEPHONY_STARTUP_ANNOUNCE_RETRIES: u8
|
||||
pub const lxst_telephony::TELEPHONY_STARTUP_ANNOUNCE_RETRY_INTERVAL: core::time::Duration
|
||||
pub const lxst_telephony::TELEPHONY_WAIT_TIME: core::time::Duration
|
||||
pub fn lxst_telephony::execute_command_with_link(&tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, &[u8; 64], &rns_identity::identity::Identity, &mut rns_link::link::Link, &lxst_telephony::TelephonyCommand) -> core::result::Result<lxst_telephony::TelephonyCommandEffect, lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::prepare_outgoing_link_request(&tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, lxst_telephony::IdentityHash, u8) -> core::result::Result<lxst_telephony::OutgoingLinkRequest, lxst_telephony::Error>
|
||||
pub async fn lxst_telephony::request_answer(&tokio::sync::mpsc::bounded::Sender<lxst_telephony::TelephonyControl>, lxst_telephony::LinkId) -> core::result::Result<lxst_telephony::ActiveCallSnapshot, lxst_telephony::Error>
|
||||
pub fn lxst_telephony::signalling_packet(lxst_core::wire::Signal) -> lxst_core::wire::LxstPacket
|
||||
pub fn lxst_telephony::signalling_packets_from_commands(&[lxst_telephony::TelephonyCommand]) -> alloc::vec::Vec<(lxst_telephony::LinkId, lxst_core::wire::LxstPacket)>
|
||||
pub fn lxst_telephony::telephony_destination_hash(&lxst_telephony::IdentityHash) -> [u8; 16]
|
||||
pub fn lxst_telephony::telephony_inbound_destination(&rns_identity::identity::Identity) -> core::result::Result<rns_identity::destination::Destination, lxst_telephony::Error>
|
||||
pub type lxst_telephony::IdentityHash = [u8; 16]
|
||||
pub type lxst_telephony::LinkId = [u8; 16]
|
||||
@@ -0,0 +1,409 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
|
||||
"packages": [
|
||||
{
|
||||
"name": "lxst-codec2",
|
||||
"version": "0.4.0",
|
||||
"rustVersion": "1.87",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
"targets": [
|
||||
{
|
||||
"name": "lxst_codec2",
|
||||
"kind": [
|
||||
"lib"
|
||||
],
|
||||
"crateTypes": [
|
||||
"lib"
|
||||
],
|
||||
"requiredFeatures": []
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"name": "libm",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "=0.2.16",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lxst-core",
|
||||
"version": "0.4.0",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
"targets": [
|
||||
{
|
||||
"name": "lxst_core",
|
||||
"kind": [
|
||||
"lib"
|
||||
],
|
||||
"crateTypes": [
|
||||
"lib"
|
||||
],
|
||||
"requiredFeatures": []
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"name": "half",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^2",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "opus-rs",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "=0.1.42",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"heap"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "rmpv",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "thiserror",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^2",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lxst-embedded",
|
||||
"version": "0.4.0",
|
||||
"rustVersion": "1.87",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
"targets": [
|
||||
{
|
||||
"name": "lxst_embedded",
|
||||
"kind": [
|
||||
"lib"
|
||||
],
|
||||
"crateTypes": [
|
||||
"lib"
|
||||
],
|
||||
"requiredFeatures": []
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"name": "lxst-codec2",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^0.4.0",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "thiserror",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^2",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lxst-rns",
|
||||
"version": "0.4.0",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
"targets": [
|
||||
{
|
||||
"name": "lxst_rns",
|
||||
"kind": [
|
||||
"lib"
|
||||
],
|
||||
"crateTypes": [
|
||||
"lib"
|
||||
],
|
||||
"requiredFeatures": []
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"name": "bytes",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "lxst-core",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^0.4.0",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-transport",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-wire",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "thiserror",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^2",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "tokio",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [
|
||||
"macros",
|
||||
"rt",
|
||||
"sync",
|
||||
"time"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lxst-telephony",
|
||||
"version": "0.4.0",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
"targets": [
|
||||
{
|
||||
"name": "lxst_telephony",
|
||||
"kind": [
|
||||
"lib"
|
||||
],
|
||||
"crateTypes": [
|
||||
"lib"
|
||||
],
|
||||
"requiredFeatures": []
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"name": "bytes",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "lxst-codec2",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^0.4.0",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "lxst-core",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^0.4.0",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "lxst-rns",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^0.4.0",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-crypto",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-identity",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-runtime",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-transport",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "rns-wire",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "thiserror",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^2",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "tokio",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [
|
||||
"macros",
|
||||
"rt",
|
||||
"sync",
|
||||
"time"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"tool": {
|
||||
"name": "cargo-public-api",
|
||||
"version": "0.52.0",
|
||||
"rustdocToolchain": "nightly-2026-08-01",
|
||||
"target": "aarch64-apple-darwin",
|
||||
"arguments": [
|
||||
"--all-features",
|
||||
"-sss"
|
||||
]
|
||||
},
|
||||
"baseline": {
|
||||
"commit": "af89a03094605dbdf7264d06fdc546526ec6980b"
|
||||
},
|
||||
"compatibilityFloor": {
|
||||
"evidenceCommit": "aeb400006bdd550f42e494bfc823f66acce0669e",
|
||||
"sourceCommit": "aeb400006bdd550f42e494bfc823f66acce0669e"
|
||||
},
|
||||
"packages": [
|
||||
{
|
||||
"name": "lxst-codec2",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/lxst-codec2.txt",
|
||||
"itemCount": 18,
|
||||
"sha256": "634ee1223c894a72833b25e0f56b4c54b8bddbd382a84665723dfcca8d8e289f"
|
||||
},
|
||||
{
|
||||
"name": "lxst-embedded",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/lxst-embedded.txt",
|
||||
"itemCount": 337,
|
||||
"sha256": "e4a86f580d90b6b5589fa0e91ac6d426b7df5d7f10e753683061d7184f64d425"
|
||||
},
|
||||
{
|
||||
"name": "lxst-core",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/lxst-core.txt",
|
||||
"itemCount": 397,
|
||||
"sha256": "7edc5748c8b212d551756681cbc0815da6102accb5a59126b43d3b23233096cd"
|
||||
},
|
||||
{
|
||||
"name": "lxst-rns",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/lxst-rns.txt",
|
||||
"itemCount": 54,
|
||||
"sha256": "6be5ba72d749f51d4f09816dce771540491cc3747bd531b307f94cef3297d463"
|
||||
},
|
||||
{
|
||||
"name": "lxst-telephony",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/lxst-telephony.txt",
|
||||
"itemCount": 391,
|
||||
"sha256": "f36724579b879506b8cd4fd3e4378f9b594bf97f169764f1461dd64401679b7a"
|
||||
}
|
||||
],
|
||||
"newPackages": []
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
|
||||
msrv = "1.89"
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "lxst-codec2"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version = "1.87"
|
||||
publish.workspace = true
|
||||
license = "LGPL-2.1-only AND MIT AND BSD-3-Clause"
|
||||
description = "Bounded no_std Codec2 speech backend for LXST"
|
||||
|
||||
[dependencies]
|
||||
libm = { version = "=0.2.16", default-features = false }
|
||||
|
||||
[[test]]
|
||||
name = "contract"
|
||||
harness = false
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
This is a modified version of the pure-Rust codec2 0.3.1 implementation by
|
||||
David Rowe and Matt Weeks, https://github.com/scriptjunkie/codec2.
|
||||
The original manifest declares LGPL-2.1-only AND MIT. The original package
|
||||
and pinned repository have no separate MIT license file; the original manifest
|
||||
and README are retained under licenses/. Do not erase the upstream declaration.
|
||||
Codec2's LGPL-2.1 text and the embedded KISS FFT BSD-3-Clause notice are retained
|
||||
there as well. Original author/function notices remain in the adapted sources.
|
||||
|
||||
Modified for rsLXST on 2026-10-01: bounded storage and scratch; in-place state
|
||||
initialisation; per-instance synthesis RNG; exact libm math on all targets;
|
||||
checked public frame shapes; corrected real-FFT input copying; shared the
|
||||
identical forward FFT plan and removed unreachable mode/rate storage; separated
|
||||
phase scratch lifetime from inverse FFT scratch for the MCU stack. The public API
|
||||
exposes native 700C/1600/3200 modes at 8 kHz mono. Other private upstream modes
|
||||
are not a supported API. See UPSTREAM.json for immutable original provenance.
|
||||
|
||||
The native 700C implementation and immutable codebooks additionally adapt
|
||||
David Rowe's Codec2 C implementation, Copyright 2017, under LGPL-2.1-only:
|
||||
https://github.com/drowe67/codec2 at commit
|
||||
310777b1c6f1af0bc7c72f5b32f80f6fd9136962. Source/codebook hashes are recorded in
|
||||
UPSTREAM.json. Modified for rsLXST on 2026-10-01: Rust newamp1 spectral
|
||||
quantization and phase reconstruction, fixed M-best scratch and FFT plans,
|
||||
streamed synthesis models, explicit mode identity, and default 700C settings.
|
||||
Shared analysis and synthesis preserve reference scalar promotions in pitch,
|
||||
windows, FFT twiddles, notch filtering and phase arithmetic. KISS FFT changes
|
||||
retain its BSD-3-Clause attribution. Corrected inherited
|
||||
background-estimator voicing and pitch-search endpoint/history-bin behavior.
|
||||
|
||||
New wrapper, tests and storage adaptation are provided under LGPL-2.1-only.
|
||||
Third-party libm retains its own MIT license and appears in the workspace's
|
||||
locked third-party inventory. Packaging must retain the applicable notices and
|
||||
provide the corresponding modified Codec2 source and relinking materials.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Bounded Rust Codec2
|
||||
|
||||
Allocation-free `no_std` native 700C/1600/3200 speech at mono 8 kHz PCM16.
|
||||
This is the pinned Rust Codec2 port with fixed storage, per-instance synthesis
|
||||
randomness and pure-Rust `libm` math. It has no allocator dependency.
|
||||
|
||||
Allocate `MaybeUninit<Codec>` in final aligned storage, then call
|
||||
`Codec::initialise`. Do not construct a codec temporary on a small task stack.
|
||||
One serialized owner can alternate encoding and decoding; predictor histories
|
||||
are independent. Independent sessions require separate states. `reset` erases
|
||||
histories in place. Native input/output frame lengths must match `Mode` exactly;
|
||||
length errors do not advance state or modify output.
|
||||
|
||||
700C uses 320 PCM samples and four encoded bytes per native frame (28 bits plus
|
||||
four zero padding bits). Its default spectral postfilter is enabled and front
|
||||
EQ is disabled, matching the pinned C reference. Mode identity is explicit;
|
||||
700C and 1600 have equal sample counts but different bitstreams.
|
||||
|
||||
LXST framing and negotiation belong to `lxst-core`, not this backend.
|
||||
Opus, memo containers, audio drivers and real-time target qualification are not
|
||||
provided here. Codec state plus worst-case nested DSP stack and I/O buffers must
|
||||
fit the selected device budget. A target build is not a timing/stack measurement.
|
||||
|
||||
`cargo test -p lxst-codec2 --release` checks allocation-free initialization,
|
||||
reset and streaming; rejected inputs; independent duplex histories; hostile
|
||||
correctly-sized decoder frames; padding; and FFT, pitch-search and background
|
||||
estimator regressions. 700C codebooks can be reproduced from the pinned C source
|
||||
using `tools/generate-codec2-700c-codebooks.py SOURCE --check`. Numerical
|
||||
comparison uses the pinned C reference with compiler FMA contraction disabled
|
||||
to match Rust scalar operations; default compiler contraction may accumulate
|
||||
phase differences. Native-frame compatibility and live peer interoperability
|
||||
are distinct qualification gates.
|
||||
|
||||
See [NOTICE](NOTICE), [UPSTREAM.json](UPSTREAM.json) and [licenses](licenses/)
|
||||
for source provenance, modifications and original license notices.
|
||||
|
||||
FFT coefficient tables are shared read-only data, generated using the pinned
|
||||
`libm` and the original native initialisation formulas. Per-stream state keeps
|
||||
only integer selectors; encoder/decoder histories and mutable FFT scratch remain
|
||||
independent. A bit-for-bit table test covers every supported size and direction.
|
||||
Generate coefficients into a temporary file and compare them with the checked-in table:
|
||||
|
||||
```sh
|
||||
coefficients=$(mktemp)
|
||||
cargo run -p lxst-codec2 --example generate_fft_tables --locked --offline > "$coefficients"
|
||||
diff -u crates/lxst-codec2/src/native/fft_coefficients.rs "$coefficients"
|
||||
```
|
||||
|
||||
These comparison commands are for a POSIX shell. Inspect the generated file and
|
||||
diff before replacing checked-in coefficients; redirecting straight to the
|
||||
source would truncate it before Cargo has compiled the generator. `--offline`
|
||||
requires the pinned dependencies to be available in the Cargo cache.
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"upstream_crate": "codec2",
|
||||
"version": "0.3.1",
|
||||
"repository": "https://github.com/scriptjunkie/codec2",
|
||||
"commit": "24ec3b7c5b9892c268e180802ee3a5ce7737f214",
|
||||
"crate_sha256": "3c3c8ba70382a99c0b5ebadf6ad50e7d98fb6eb9bcc4c0e30d422f6321798d99",
|
||||
"declared_license": "LGPL-2.1-only AND MIT",
|
||||
"additional_embedded_notice": "BSD-3-Clause KISS FFT notice preserved in src/native/kiss_fft.rs",
|
||||
"original_source_sha256": {
|
||||
"kiss_fft.rs": "33f9a3f1c2caddaa8e7536d655fd0c20f85d9dd78224f5e117a2c5bec1ca5671",
|
||||
"codebookd.rs": "5527f6217500f303a551a6e6f2425cf7ea1abe95e43093f73eea467a45c7ba08",
|
||||
"codebook.rs": "8de6ea51a391982d26a724c3b7e8ef2e6fefed066f295e7f4a745a6aceb0a6d2",
|
||||
"lib.rs": "5a468ed1b26854be5f1992a215959151e7d3435fe154d212b2c468e4f10744bb",
|
||||
"codebookge.rs": "0d36228e468f74eb65bbcbbadb9cb66a599466f347f1b7ee436abdb29d4c4378",
|
||||
"quantise.rs": "f1e831fddee5a657e4139ac0808339cede5f5a8b6e9784eda600f3a714bb81bb",
|
||||
"codebookjvm.rs": "6a5aba7b9be606b2d7b16054e897d8862f3bd4ec24fa3f78ff5659b361bd7266",
|
||||
"nlp.rs": "d86f14abc7ce709d1a36a5b4dce3a2bab30ed5999a04548b61548c433897a0c6"
|
||||
},
|
||||
"codec2_700c": {
|
||||
"repository": "https://github.com/drowe67/codec2",
|
||||
"commit": "310777b1c6f1af0bc7c72f5b32f80f6fd9136962",
|
||||
"license": "LGPL-2.1-only",
|
||||
"source_sha256": {
|
||||
"src/codec2.c": "57dcb29bd9376bb32f9ea5d6f16e36a4b635ddf976683f0c0c46fd4989550bf5",
|
||||
"src/newamp1.c": "8df144b2ef72abdf2fc3ff66ec5c682694bdb4e940a668d1c13b3f4335168c93",
|
||||
"src/newamp1.h": "457f8357a8ca2f064f77cb68abebfe1acf4fb6be82802b43244d7c926d356423",
|
||||
"src/mbest.c": "91e0126fc7a001d9a019cea49545263ed0c58dc4418eea871549505bc5b935fc",
|
||||
"src/phase.c": "751d3123d070c42fcb235affe154219f3326fb0e8a13335f4b9e1389ab295eb2",
|
||||
"src/quantise.c": "a9b6dbadfee5c79b5ba346e606152c735d1096c2f3552a3da3b39c024469732f",
|
||||
"src/codebook/train_120_1.txt": "a3aa8da88db8b4a9168023c2269a4f4f9555aec20ed81a44752cce86c9d1d6f4",
|
||||
"src/codebook/train_120_2.txt": "2e57e1f514d9e1ff165f3a6dd1f689af2565de6195300ce0d468af9b7f2120b3",
|
||||
"src/codebook/newamp1_energy_q.txt": "ae75dc2e0fbd38bd2341795f00162a677251ec66deff6015015e19168d7bfee2",
|
||||
"src/sine.c": "9d286a353734f6968e6fd6502d089a95d46a226757a16346fa9b27169b958252",
|
||||
"src/nlp.c": "5c35a44bc3093bd74fe7411e48214ed38afd59b0b84206d73b1751343f27c3ba",
|
||||
"src/postfilter.c": "52fd7d3131e947b71644851224d09351fd53974c6f4abb2c25a1d0f8d12a0d07",
|
||||
"src/kiss_fft.c": "f16ca65e00a766c8c17bbd8c068168e9615c9b9e493fda2acf2822d743cc40c8",
|
||||
"src/kiss_fftr.c": "fcd5fb59beae112c91a53832e4ff24242ef3192fa57f0845dd8dcbf11e46c16d",
|
||||
"src/_kiss_fft_guts.h": "25fbd1b559e52dd255bc0129806c84c863f21bbafe652c83e169438cff517a9e",
|
||||
"src/defines.h": "2b0c3f83f38a8bb7f49b3fad6634e4acbb946216b2bba634264d3cb4440243f0"
|
||||
},
|
||||
"adaptation_notes": [
|
||||
"Fixed-storage newamp1 and 128-point phase FFTs; default postfilter on, front EQ off",
|
||||
"One 10 ms synthesis model at a time; per-instance random and predictor histories",
|
||||
"Shared analysis preserves C scalar precision and pitch-refinement accumulation order",
|
||||
"Corrected inherited background-estimator voicing condition and pitch-search inclusive endpoint/integer history bin",
|
||||
"Reference scalar promotions retained for windows, twiddles, notch filter and phase synthesis; numerical oracle disables compiler FMA contraction to match Rust scalar operations"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# Keep lint suggestions compatible with the standalone MCU compiler floor.
|
||||
msrv = "1.87"
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Regenerate with cargo run -p lxst-codec2 --example generate_fft_tables --locked --offline.
|
||||
//! Preserve the native initialiser's floating-point operation order exactly.
|
||||
fn complex(name: &str, phases: impl Iterator<Item = f32>, length: usize) {
|
||||
println!("pub(super) static {name}: [kiss_fft_cpx; {length}] = [");
|
||||
for phase in phases {
|
||||
println!(
|
||||
" kiss_fft_cpx {{ r: f32::from_bits(0x{:08x}), i: f32::from_bits(0x{:08x}) }},",
|
||||
libm::cosf(phase).to_bits(),
|
||||
libm::sinf(phase).to_bits()
|
||||
);
|
||||
}
|
||||
println!("];\n");
|
||||
}
|
||||
fn main() {
|
||||
println!(
|
||||
"// Generated by examples/generate_fft_tables.rs with pinned libm 0.2.16.\n// Immutable native FFT coefficients; no approximation or host trigonometry.\nuse super::inner::kiss_fft_cpx;\n"
|
||||
);
|
||||
for n in [128, 256, 512] {
|
||||
for inverse in [false, true] {
|
||||
complex(
|
||||
&format!(
|
||||
"COMPLEX_{n}_{}",
|
||||
if inverse { "INVERSE" } else { "FORWARD" }
|
||||
),
|
||||
(0..n).map(|i| {
|
||||
let mut phase = -2.0 * core::f64::consts::PI * i as f64 / n as f64;
|
||||
if inverse {
|
||||
phase *= -1.0;
|
||||
}
|
||||
phase as f32
|
||||
}),
|
||||
n,
|
||||
);
|
||||
}
|
||||
}
|
||||
for n in [128, 256] {
|
||||
for inverse in [false, true] {
|
||||
complex(
|
||||
&format!("REAL_{n}_{}", if inverse { "INVERSE" } else { "FORWARD" }),
|
||||
(0..n / 2).map(|i| {
|
||||
let mut phase = (-core::f64::consts::PI
|
||||
* (f64::from((i + 1) as f32 / n as f32) + 0.5))
|
||||
as f32;
|
||||
if inverse {
|
||||
phase *= -1.0;
|
||||
}
|
||||
phase
|
||||
}),
|
||||
n / 2,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
Copyright (c) 2003-2010, Mark Borgerding
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,502 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "codec2"
|
||||
version = "0.3.1"
|
||||
description = "A pure-Rust implementation of the Codec2 low-bitrate speech compression codec"
|
||||
authors = ["David Rowe", "Matt Weeks <scriptjunkie@scriptjunkie.us>"]
|
||||
license = "LGPL-2.1-only AND MIT"
|
||||
edition = "2018"
|
||||
repository = "https://github.com/scriptjunkie/codec2"
|
||||
keywords = ["audio", "speech", "compression", "codec"]
|
||||
categories = ["compression", "multimedia::audio", "multimedia::encoding", "algorithms"]
|
||||
readme = "README.md"
|
||||
|
||||
[dependencies]
|
||||
micromath = {version = "2.1.0", optional = true}
|
||||
|
||||
[dev-dependencies]
|
||||
zerocopy = "0.3.0"
|
||||
|
||||
[features]
|
||||
micromath = ["dep:micromath"]
|
||||
@@ -0,0 +1,61 @@
|
||||
# Codec2
|
||||
|
||||
Add this to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
codec2 = "0.3"
|
||||
```
|
||||
|
||||
## Usage
|
||||
Currently 3200, 2400, 1600, 1400, 1300 and 1200 bitrates encoding and decoding are implemented.
|
||||
|
||||
Create a Codec2 object e.g. `Codec2::new(Codec2Mode::MODE_3200)` then repeatedly obtain raw 8khz
|
||||
16-bit audio samples and call `encode` to encode blocks of `samples_per_frame()` samples into
|
||||
`bits_per_frame()` compressed bits, in order. On the receiving end, create a Codec2 object and
|
||||
repeatedly call `decode` to decompress each chunk of received bytes into the next samples.
|
||||
|
||||
Complete example below. This example uses zerocopy to interpret the `&[i16]` slices as `&[u8]` for
|
||||
I/O.
|
||||
|
||||
Cargo.toml:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
zerocopy = "0.3.0"
|
||||
codec2 = "0"
|
||||
```
|
||||
|
||||
main.rs:
|
||||
|
||||
```rust
|
||||
use codec2::*;
|
||||
use std::env::args;
|
||||
use std::io::prelude::*;
|
||||
use zerocopy::AsBytes;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
if args().len() != 4 || (args().nth(1).unwrap() != "enc" && args().nth(1).unwrap() != "dec") {
|
||||
eprintln!("Usage: {} (enc|dec) inputfile outputfilename", args().nth(0).unwrap());
|
||||
eprintln!("Files should be raw 16-bit signed 8khz audio");
|
||||
return Ok(());
|
||||
}
|
||||
let mut fin = std::fs::File::open(args().nth(2).unwrap())?;
|
||||
let mut fout = std::fs::File::create(args().nth(3).unwrap())?;
|
||||
let mut c2 = Codec2::new(Codec2Mode::MODE_3200);
|
||||
let mut samps = vec![0; c2.samples_per_frame()]; //i16 I/O buffer
|
||||
let mut packed = vec![0; (c2.bits_per_frame() + 7) / 8]; //u8 I/O buffer for encoded bits
|
||||
if args().nth(1).unwrap() == "enc" {
|
||||
while fin.read_exact(samps.as_bytes_mut()).is_ok() {
|
||||
c2.encode(&mut packed, &samps[..]);
|
||||
fout.write_all(&packed)?;
|
||||
}
|
||||
} else {
|
||||
while fin.read_exact(&mut packed).is_ok() {
|
||||
c2.decode(&mut samps[..], &packed);
|
||||
fout.write_all(samps.as_bytes())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
use core::ops::{Deref, DerefMut};
|
||||
|
||||
/// Private fixed storage preserving the upstream DSP's slice lengths.
|
||||
/// Zero initialisation is valid: a zero length exposes no uninitialised data.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Buffer<T: Copy, const N: usize> {
|
||||
length: usize,
|
||||
values: [T; N],
|
||||
}
|
||||
|
||||
impl<T: Copy, const N: usize> Buffer<T, N> {
|
||||
pub(crate) fn filled(length: usize, value: T) -> Self {
|
||||
assert!(length <= N);
|
||||
Self {
|
||||
length,
|
||||
values: [value; N],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn initialise(&mut self, length: usize, value: T) {
|
||||
assert!(length <= N);
|
||||
self.length = length;
|
||||
self.values[..length].fill(value);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, const N: usize> Deref for Buffer<T, N> {
|
||||
type Target = [T];
|
||||
fn deref(&self) -> &[T] {
|
||||
&self.values[..self.length]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, const N: usize> DerefMut for Buffer<T, N> {
|
||||
fn deref_mut(&mut self) -> &mut [T] {
|
||||
&mut self.values[..self.length]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Fixed-storage, allocation-free Codec2 at 8 kHz mono PCM16.
|
||||
//!
|
||||
//! Adapted from the pinned pure-Rust Codec2 port recorded in `UPSTREAM.json`.
|
||||
//! Initialise directly in caller-owned storage; the state is too large to create
|
||||
//! as a temporary on an MCU task stack. Encoding/decoding and reset never allocate.
|
||||
//! Immutable FFT coefficients are shared in read-only storage; stream histories
|
||||
//! and mutable transform scratch remain independently owned.
|
||||
#![no_std]
|
||||
|
||||
mod buffer;
|
||||
mod math;
|
||||
use buffer::Buffer;
|
||||
use math::FloatMath;
|
||||
|
||||
// Preserve the upstream DSP's names, numeric constants and indexing style so
|
||||
// algorithm changes remain reviewable separately from the storage adaptation.
|
||||
#[allow(
|
||||
non_snake_case,
|
||||
non_camel_case_types,
|
||||
non_upper_case_globals,
|
||||
dead_code
|
||||
)]
|
||||
#[allow(clippy::all)]
|
||||
mod native;
|
||||
|
||||
use core::mem::MaybeUninit;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Rate1600,
|
||||
Rate3200,
|
||||
Rate700C,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
pub const fn samples(self) -> usize {
|
||||
match self {
|
||||
Self::Rate1600 | Self::Rate700C => 320,
|
||||
Self::Rate3200 => 160,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn bytes(self) -> usize {
|
||||
match self {
|
||||
Self::Rate700C => 4,
|
||||
Self::Rate1600 | Self::Rate3200 => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
PcmLength,
|
||||
EncodedLength,
|
||||
}
|
||||
|
||||
/// Independent encoder and decoder histories at one native mode.
|
||||
///
|
||||
/// One serialized audio owner may alternate transmit and receive with this
|
||||
/// instance; FFT scratch is reused and the histories remain independent. It
|
||||
/// must never be accessed concurrently. Independent sessions need independent
|
||||
/// instances. `Mode` is a codec configuration, not an LXST/LXMF wire identifier.
|
||||
pub struct Codec {
|
||||
native: native::Codec2,
|
||||
}
|
||||
|
||||
impl Codec {
|
||||
/// Initialise in final, aligned caller storage without a whole-state copy.
|
||||
pub fn initialise(storage: &mut MaybeUninit<Self>, mode: Mode) -> &mut Self {
|
||||
// SAFETY: all native fields are integers, floats, booleans, arrays, fixed buffers
|
||||
// (zero length is valid), or Codec2Mode (repr(u8), first variant is 0).
|
||||
// There are no references, pointers, heap owners or Drop implementations.
|
||||
// Thus zero bytes form a valid value. We finish logical initialisation
|
||||
// before publishing it. The exclusive borrow prevents concurrent access.
|
||||
let value = unsafe {
|
||||
storage.as_mut_ptr().write_bytes(0, 1);
|
||||
storage.assume_init_mut()
|
||||
};
|
||||
value.initialise_native(mode);
|
||||
value
|
||||
}
|
||||
|
||||
fn initialise_native(&mut self, mode: Mode) {
|
||||
self.native.initialise(match mode {
|
||||
Mode::Rate1600 => native::Codec2Mode::MODE_1600,
|
||||
Mode::Rate3200 => native::Codec2Mode::MODE_3200,
|
||||
Mode::Rate700C => native::Codec2Mode::MODE_700C,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn reset(&mut self, mode: Mode) {
|
||||
// SAFETY: same zero-valid representation as initialise; this type owns
|
||||
// no resources requiring Drop and self is exclusively borrowed.
|
||||
unsafe { core::ptr::write_bytes(self, 0, 1) };
|
||||
self.initialise_native(mode);
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> Mode {
|
||||
match self.native.mode() {
|
||||
native::Codec2Mode::MODE_1600 => Mode::Rate1600,
|
||||
native::Codec2Mode::MODE_3200 => Mode::Rate3200,
|
||||
native::Codec2Mode::MODE_700C => Mode::Rate700C,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(&mut self, pcm: &[i16], output: &mut [u8]) -> Result<(), Error> {
|
||||
if pcm.len() != self.mode().samples() {
|
||||
return Err(Error::PcmLength);
|
||||
}
|
||||
if output.len() != self.mode().bytes() {
|
||||
return Err(Error::EncodedLength);
|
||||
}
|
||||
self.native.encode(output, pcm);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn decode(&mut self, encoded: &[u8], output: &mut [i16]) -> Result<(), Error> {
|
||||
if encoded.len() != self.mode().bytes() {
|
||||
return Err(Error::EncodedLength);
|
||||
}
|
||||
if output.len() != self.mode().samples() {
|
||||
return Err(Error::PcmLength);
|
||||
}
|
||||
self.native.decode(output, encoded);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Same pure-Rust libm functions on host and MCU. Do not replace with approximate
|
||||
// intrinsics without comparing stateful speech and target execution budgets.
|
||||
pub(crate) trait FloatMath {
|
||||
fn dsp_acos(self) -> Self;
|
||||
fn dsp_atan2(self, other: Self) -> Self;
|
||||
fn dsp_ceil(self) -> Self;
|
||||
fn dsp_cos(self) -> Self;
|
||||
fn dsp_floor(self) -> Self;
|
||||
fn dsp_log10(self) -> Self;
|
||||
fn dsp_powf(self, other: Self) -> Self;
|
||||
fn dsp_round(self) -> Self;
|
||||
fn dsp_sin(self) -> Self;
|
||||
fn dsp_sqrt(self) -> Self;
|
||||
}
|
||||
|
||||
impl FloatMath for f32 {
|
||||
fn dsp_acos(self) -> Self {
|
||||
libm::acosf(self)
|
||||
}
|
||||
fn dsp_atan2(self, other: Self) -> Self {
|
||||
libm::atan2f(self, other)
|
||||
}
|
||||
fn dsp_ceil(self) -> Self {
|
||||
libm::ceilf(self)
|
||||
}
|
||||
fn dsp_cos(self) -> Self {
|
||||
libm::cosf(self)
|
||||
}
|
||||
fn dsp_floor(self) -> Self {
|
||||
libm::floorf(self)
|
||||
}
|
||||
fn dsp_log10(self) -> Self {
|
||||
libm::log10f(self)
|
||||
}
|
||||
fn dsp_powf(self, other: Self) -> Self {
|
||||
libm::powf(self, other)
|
||||
}
|
||||
fn dsp_round(self) -> Self {
|
||||
libm::roundf(self)
|
||||
}
|
||||
fn dsp_sin(self) -> Self {
|
||||
libm::sinf(self)
|
||||
}
|
||||
fn dsp_sqrt(self) -> Self {
|
||||
libm::sqrtf(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use super::*;
|
||||
|
||||
/* THIS IS A GENERATED FILE. Edit generate_codebook.c and its input */
|
||||
|
||||
/*
|
||||
* This intermediary file and the files that used to create it are under
|
||||
* The LGPL. See the file COPYING.
|
||||
*/
|
||||
|
||||
/* codebook/lsp1.txt */
|
||||
const codes0: [f32; 16] = [
|
||||
225.0, 250.0, 275.0, 300.0, 325.0, 350.0, 375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0,
|
||||
550.0, 575.0, 600.0,
|
||||
];
|
||||
/* codebook/lsp2.txt */
|
||||
const codes1: [f32; 16] = [
|
||||
325.0, 350.0, 375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0,
|
||||
650.0, 675.0, 700.0,
|
||||
];
|
||||
/* codebook/lsp3.txt */
|
||||
const codes2: [f32; 16] = [
|
||||
500.0, 550.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 950.0, 1000.0, 1050.0, 1100.0,
|
||||
1150.0, 1200.0, 1250.0,
|
||||
];
|
||||
/* codebook/lsp4.txt */
|
||||
const codes3: [f32; 16] = [
|
||||
700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
|
||||
1900.0, 2000.0, 2100.0, 2200.0,
|
||||
];
|
||||
/* codebook/lsp5.txt */
|
||||
const codes4: [f32; 16] = [
|
||||
950.0, 1050.0, 1150.0, 1250.0, 1350.0, 1450.0, 1550.0, 1650.0, 1750.0, 1850.0, 1950.0, 2050.0,
|
||||
2150.0, 2250.0, 2350.0, 2450.0,
|
||||
];
|
||||
/* codebook/lsp6.txt */
|
||||
const codes5: [f32; 16] = [
|
||||
1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2100.0, 2200.0,
|
||||
2300.0, 2400.0, 2500.0, 2600.0,
|
||||
];
|
||||
/* codebook/lsp7.txt */
|
||||
const codes6: [f32; 16] = [
|
||||
1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0,
|
||||
2700.0, 2800.0, 2900.0, 3000.0,
|
||||
];
|
||||
/* codebook/lsp8.txt */
|
||||
const codes7: [f32; 8] = [
|
||||
2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0,
|
||||
];
|
||||
/* codebook/lsp9.txt */
|
||||
const codes8: [f32; 8] = [
|
||||
2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3200.0,
|
||||
];
|
||||
/* codebook/lsp10.txt */
|
||||
const codes9: [f32; 4] = [2900.0, 3100.0, 3300.0, 3500.0];
|
||||
|
||||
pub const lsp_cb: [lsp_codebook; 10] = [
|
||||
/* codebook/lsp1.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes0,
|
||||
},
|
||||
/* codebook/lsp2.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes1,
|
||||
},
|
||||
/* codebook/lsp3.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes2,
|
||||
},
|
||||
/* codebook/lsp4.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes3,
|
||||
},
|
||||
/* codebook/lsp5.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes4,
|
||||
},
|
||||
/* codebook/lsp6.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes5,
|
||||
},
|
||||
/* codebook/lsp7.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 4,
|
||||
m: 16,
|
||||
cb: &codes6,
|
||||
},
|
||||
/* codebook/lsp8.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 3,
|
||||
m: 8,
|
||||
cb: &codes7,
|
||||
},
|
||||
/* codebook/lsp9.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 3,
|
||||
m: 8,
|
||||
cb: &codes8,
|
||||
},
|
||||
/* codebook/lsp10.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 2,
|
||||
m: 4,
|
||||
cb: &codes9,
|
||||
},
|
||||
];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
/* codebook/dlsp1.txt */
|
||||
const codes0: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
/* codebook/dlsp2.txt */
|
||||
const codes1: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
/* codebook/dlsp3.txt */
|
||||
const codes2: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
/* codebook/dlsp4.txt */
|
||||
const codes3: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 250.0, 300.0, 350.0, 400.0, 450.0, 500.0,
|
||||
550.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 950.0, 1000.0, 1050.0, 1100.0, 1150.0,
|
||||
1200.0, 1250.0, 1300.0, 1350.0, 1400.0,
|
||||
];
|
||||
/* codebook/dlsp5.txt */
|
||||
const codes4: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 250.0, 300.0, 350.0, 400.0, 450.0, 500.0,
|
||||
550.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 950.0, 1000.0, 1050.0, 1100.0, 1150.0,
|
||||
1200.0, 1250.0, 1300.0, 1350.0, 1400.0,
|
||||
];
|
||||
/* codebook/dlsp6.txt */
|
||||
const codes5: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 250.0, 300.0, 350.0, 400.0, 450.0, 500.0,
|
||||
550.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 950.0, 1000.0, 1050.0, 1100.0, 1150.0,
|
||||
1200.0, 1250.0, 1300.0, 1350.0, 1400.0,
|
||||
];
|
||||
/* codebook/dlsp7.txt */
|
||||
const codes6: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
/* codebook/dlsp8.txt */
|
||||
const codes7: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
/* codebook/dlsp9.txt */
|
||||
const codes8: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
/* codebook/dlsp10.txt */
|
||||
const codes9: [f32; 32] = [
|
||||
25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0,
|
||||
375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0,
|
||||
700.0, 725.0, 750.0, 775.0, 800.0,
|
||||
];
|
||||
|
||||
const codesnone: [f32; 0] = [];
|
||||
|
||||
pub const lsp_cbd: [lsp_codebook; 11] = [
|
||||
/* codebook/dlsp1.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes0,
|
||||
},
|
||||
/* codebook/dlsp2.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes1,
|
||||
},
|
||||
/* codebook/dlsp3.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes2,
|
||||
},
|
||||
/* codebook/dlsp4.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes3,
|
||||
},
|
||||
/* codebook/dlsp5.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes4,
|
||||
},
|
||||
/* codebook/dlsp6.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes5,
|
||||
},
|
||||
/* codebook/dlsp7.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes6,
|
||||
},
|
||||
/* codebook/dlsp8.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes7,
|
||||
},
|
||||
/* codebook/dlsp9.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes8,
|
||||
},
|
||||
/* codebook/dlsp10.txt */
|
||||
lsp_codebook {
|
||||
k: 1,
|
||||
log2m: 5,
|
||||
m: 32,
|
||||
cb: &codes9,
|
||||
},
|
||||
lsp_codebook {
|
||||
k: 0,
|
||||
log2m: 0,
|
||||
m: 0,
|
||||
cb: &codesnone,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,72 @@
|
||||
/* THIS IS A GENERATED FILE. Edit generate_codebook.c and its input */
|
||||
|
||||
/*
|
||||
* This intermediary file and the files that used to create it are under
|
||||
* The LGPL. See the file COPYING.
|
||||
*/
|
||||
use super::*;
|
||||
|
||||
// codebook/gecb.txt
|
||||
const codes0: [f32; 512] = [
|
||||
2.71, 12.0184, 0.04675, -2.73881, 0.120993, 8.38895, -1.58028, -0.892307, 1.19307, -1.91561,
|
||||
0.187101, -3.27679, 0.332251, -7.66455, -1.47944, 31.2461, 1.52761, 27.7095, -0.524379,
|
||||
5.25012, 0.55333, 7.4388, -0.843451, -1.95299, 2.26389, 8.61029, 0.143143, 2.36549, 0.616506,
|
||||
1.28427, -1.71133, 22.0967, 1.00813, 17.3965, -0.106718, 1.41891, -0.136246, 14.2736, -1.70909,
|
||||
-20.5319, 1.65787, -3.39107, 0.138049, -4.95785, 0.536729, -1.94375, 0.196307, 36.8519,
|
||||
1.27248, 22.5565, -0.670219, -1.90604, 0.382092, 6.40113, -0.756911, -4.90102, 1.82931, 4.6138,
|
||||
0.318794, 0.73683, 0.612815, -2.07505, -0.410151, 24.7871, 1.77602, 13.1909, 0.106457,
|
||||
-0.104492, 0.192206, 10.1838, -1.82442, -7.71565, 0.931346, 4.34835, 0.308813, -4.086,
|
||||
0.397143, -11.8089, -0.048715, 41.2273, 0.877342, 35.8503, -0.759794, 0.476634, 0.978593,
|
||||
7.67467, -1.19506, 3.03883, 2.63989, -3.41106, 0.191127, 3.60351, 0.402932, 1.0843, -2.15202,
|
||||
18.1076, 1.5468, 8.32271, -0.143089, -4.07592, -0.150142, 5.86674, -1.40844, -3.2507, 1.56615,
|
||||
-10.4132, 0.178171, -10.2267, 0.362164, -0.028556, -0.070125, 24.3907, 0.594752, 17.4828,
|
||||
-0.28698, -6.90407, 0.464818, 10.2055, -1.00684, -14.3572, 2.32957, -3.69161, 0.335745,
|
||||
2.40714, 1.01966, -3.15565, -1.25945, 7.9919, 2.38369, 19.6806, -0.094947, -2.41374, 0.20933,
|
||||
6.66477, -2.22103, 1.37986, 1.29239, 2.04633, 0.243626, -0.890741, 0.428773, -7.19366,
|
||||
-1.11374, 41.3414, 2.6098, 31.1405, -0.446468, 2.53419, 0.490104, 4.62757, -1.11723, -3.24174,
|
||||
1.79156, 8.41493, 0.156012, 0.183336, 0.532447, 3.15455, -0.764484, 18.514, 0.952395, 11.7713,
|
||||
-0.332567, 0.346987, 0.202165, 14.7168, -2.12924, -15.559, 1.35358, -1.92679, -0.010963,
|
||||
-16.3364, 0.399053, -2.79057, 0.750657, 31.1483, 0.655743, 24.4819, -0.45321, -0.735879,
|
||||
0.2869, 6.5467, -0.715673, -12.3578, 1.54849, 3.87217, 0.271874, 0.802339, 0.502073, -4.85485,
|
||||
-0.497037, 17.7619, 1.19116, 13.9544, 0.01563, 1.33157, 0.341867, 8.93537, -2.31601, -5.39506,
|
||||
0.75861, 1.9645, 0.24132, -3.23769, 0.267151, -11.2344, -0.273126, 32.6248, 1.75352, 40.432,
|
||||
-0.784011, 3.04576, 0.705987, 5.66118, -1.3864, 1.35356, 2.37646, 1.67485, 0.242973, 4.73218,
|
||||
0.491227, 0.354061, -1.60676, 8.65895, 1.16711, 5.9871, -0.137601, -12.0417, -0.251375,
|
||||
10.3972, -1.43151, -8.90411, 0.98828, -13.209, 0.261484, -6.35497, 0.395932, -0.702529,
|
||||
0.283704, 26.8996, 0.420959, 15.4418, -0.355804, -13.7278, 0.527372, 12.3985, -1.16956,
|
||||
-15.9985, 1.90669, -5.81605, 0.354492, 3.85157, 0.82576, -4.16264, -0.49019, 13.0572, 2.25577,
|
||||
13.5264, -0.004956, -3.23713, 0.026709, 7.86645, -1.81037, -0.451183, 1.08383, -0.18362,
|
||||
0.135836, -2.26658, 0.375812, -5.51225, -1.96644, 38.6829, 1.97799, 24.5655, -0.704656,
|
||||
6.35881, 0.480786, 7.05175, -0.976417, -2.42273, 2.50215, 6.75935, 0.083588, 3.2588, 0.543629,
|
||||
0.910013, -1.23196, 23.0915, 0.785492, 14.807, -0.213554, 1.688, 0.004748, 18.1718, -1.54719,
|
||||
-16.1168, 1.50104, -3.28114, 0.080133, -4.63472, 0.476592, -2.18093, 0.44247, 40.304, 1.07277,
|
||||
27.592, -0.594738, -4.16681, 0.42248, 7.61609, -0.927521, -7.27441, 1.99162, 1.29636, 0.291307,
|
||||
2.39878, 0.721081, -1.95062, -0.804256, 24.9295, 1.64839, 19.1197, 0.060852, -0.590639,
|
||||
0.266085, 9.10325, -1.9574, -2.88461, 1.11693, 2.6724, 0.35458, -2.74854, 0.330733, -14.1561,
|
||||
-0.527851, 39.5756, 0.991152, 43.195, -0.589619, 1.26919, 0.787401, 8.73071, -1.0138, 1.02507,
|
||||
2.8254, 1.89538, 0.24089, 2.74557, 0.427195, 2.54446, -1.95311, 12.244, 1.44862, 12.0607,
|
||||
-0.210492, -3.37906, -0.056713, 10.204, -1.65237, -5.10274, 1.29475, -12.2708, 0.111608,
|
||||
-8.67592, 0.326634, -1.16763, 0.021781, 31.1258, 0.455335, 21.4684, -0.37544, -3.37121,
|
||||
0.39362, 11.302, -0.851456, -19.4149, 2.10703, -2.22886, 0.373233, 1.92406, 0.884438, -1.72058,
|
||||
-0.975127, 9.84013, 2.0033, 17.3954, -0.036915, -1.11137, 0.148456, 5.39997, -1.91441, 4.77382,
|
||||
1.44791, 0.537122, 0.194979, -1.03818, 0.495771, -9.95502, -1.05899, 32.9471, 2.01122, 32.4544,
|
||||
-0.30965, 4.71911, 0.436082, 4.63552, -1.23711, -1.25428, 2.02274, 9.42834, 0.190342, 1.46077,
|
||||
0.479017, 2.48479, -1.07848, 16.2217, 1.20764, 9.65421, -0.258087, -1.67236, 0.071852, 13.416,
|
||||
-1.87723, -16.072, 1.28957, -4.87118, 0.067713, -13.4427, 0.435551, -4.1655, 0.46614, 30.5895,
|
||||
0.904895, 21.598, -0.518369, -2.53205, 0.337363, 5.63726, -0.554975, -17.4005, 1.69188,
|
||||
1.14574, 0.227934, 0.889297, 0.587303, -5.72973, -0.262133, 18.6666, 1.39505, 17.0029,
|
||||
-0.01909, 4.30838, 0.304235, 12.6699, -2.07406, -6.46084, 0.920546, 1.21296, 0.284927,
|
||||
-1.78547, 0.209724, -16.024, -0.636067, 31.5768, 1.34989, 34.6775, -0.971625, 5.30086,
|
||||
0.590249, 4.44971, -1.56787, 3.60239, 2.1455, 4.51666, 0.296022, 4.12017, 0.445299, 0.868772,
|
||||
-1.44193, 14.1284, 1.35575, 6.0074, -0.012814, -7.49657, -0.43, 8.50012, -1.20469, -7.11326,
|
||||
1.10102, -6.83682, 0.196463, -6.234, 0.436747, -1.12979, 0.141052, 22.8549, 0.290821, 18.8114,
|
||||
-0.529536, -7.73251, 0.63428, 10.7898, -1.33472, -20.3258, 1.81564, -1.90332, 0.394778,
|
||||
3.79758, 0.732682, -8.18382, -0.741244, 11.7683,
|
||||
];
|
||||
|
||||
pub const ge_cb: [lsp_codebook; 1] = [lsp_codebook {
|
||||
k: 2,
|
||||
log2m: 8,
|
||||
m: 256,
|
||||
cb: &codes0,
|
||||
}];
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,113 @@
|
||||
// FFT coefficients depend only on transform size/direction. Keep them in
|
||||
// read-only flash; each stream retains just zero-valid integer selectors.
|
||||
// Histories and transform scratch remain private to their Codec instance.
|
||||
use super::{fft_coefficients::*, inner::kiss_fft_cpx};
|
||||
use core::ops::Deref;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct ComplexTable {
|
||||
length: usize,
|
||||
inverse: bool,
|
||||
}
|
||||
impl ComplexTable {
|
||||
pub(super) fn initialise(&mut self, length: usize, inverse: bool) {
|
||||
assert!(matches!(length, 128 | 256 | 512));
|
||||
self.length = length;
|
||||
self.inverse = inverse;
|
||||
}
|
||||
}
|
||||
impl Deref for ComplexTable {
|
||||
type Target = [kiss_fft_cpx];
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match (self.length, self.inverse) {
|
||||
(0, _) => &[],
|
||||
(128, false) => &COMPLEX_128_FORWARD,
|
||||
(128, true) => &COMPLEX_128_INVERSE,
|
||||
(256, false) => &COMPLEX_256_FORWARD,
|
||||
(256, true) => &COMPLEX_256_INVERSE,
|
||||
(512, false) => &COMPLEX_512_FORWARD,
|
||||
(512, true) => &COMPLEX_512_INVERSE,
|
||||
_ => unreachable!("invalid fixed FFT table"),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct RealTable {
|
||||
nfft: usize,
|
||||
inverse: bool,
|
||||
}
|
||||
impl RealTable {
|
||||
pub(super) fn initialise(&mut self, nfft: usize, inverse: bool) {
|
||||
assert!(matches!(nfft, 128 | 256));
|
||||
self.nfft = nfft;
|
||||
self.inverse = inverse;
|
||||
}
|
||||
}
|
||||
impl Deref for RealTable {
|
||||
type Target = [kiss_fft_cpx];
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match (self.nfft, self.inverse) {
|
||||
(0, _) => &[],
|
||||
(128, false) => &REAL_128_FORWARD,
|
||||
(128, true) => &REAL_128_INVERSE,
|
||||
(256, false) => &REAL_256_FORWARD,
|
||||
(256, true) => &REAL_256_INVERSE,
|
||||
_ => unreachable!("invalid fixed real FFT table"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
// Compare every stored bit to the original runtime initialiser, including
|
||||
// signed zero and forward/inverse phase operation order. No approximations.
|
||||
#[test]
|
||||
fn flash_tables_match_native_initialisation() {
|
||||
for inverse in [false, true] {
|
||||
for nfft in [128, 256, 512] {
|
||||
let mut table = ComplexTable {
|
||||
length: 0,
|
||||
inverse: false,
|
||||
};
|
||||
assert!(table.is_empty());
|
||||
table.initialise(nfft, inverse);
|
||||
assert_eq!(table.len(), nfft);
|
||||
for (i, value) in table.iter().enumerate() {
|
||||
let mut phase = -2.0 * core::f64::consts::PI * i as f64 / nfft as f64;
|
||||
if inverse {
|
||||
phase *= -1.0;
|
||||
}
|
||||
let original = kiss_fft_cpx::kf_cexp(phase as f32);
|
||||
assert_eq!(
|
||||
(value.r.to_bits(), value.i.to_bits()),
|
||||
(original.r.to_bits(), original.i.to_bits())
|
||||
);
|
||||
}
|
||||
}
|
||||
for nfft in [128, 256] {
|
||||
let mut table = RealTable {
|
||||
nfft: 0,
|
||||
inverse: false,
|
||||
};
|
||||
assert!(table.is_empty());
|
||||
table.initialise(nfft, inverse);
|
||||
assert_eq!(table.len(), nfft / 2);
|
||||
for (i, value) in table.iter().enumerate() {
|
||||
let mut phase = (-core::f64::consts::PI
|
||||
* (f64::from((i + 1) as f32 / nfft as f32) + 0.5))
|
||||
as f32;
|
||||
if inverse {
|
||||
phase *= -1.0;
|
||||
}
|
||||
let original = kiss_fft_cpx::kf_cexp(phase);
|
||||
assert_eq!(
|
||||
(value.r.to_bits(), value.i.to_bits()),
|
||||
(original.r.to_bits(), original.i.to_bits())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(core::mem::size_of::<crate::Codec>() < 17000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
/*
|
||||
Copyright (c) 2003-2010, Mark Borgerding
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
use super::*;
|
||||
|
||||
/*
|
||||
Explanation of functions dealing with complex math:
|
||||
|
||||
C_MUL(m,a,b) : m = a*b
|
||||
C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise
|
||||
C_SUB( res, a,b) : res = a - b
|
||||
C_SUBFROM( res , a) : res -= a
|
||||
C_ADDTO( res , a) : res += a
|
||||
* */
|
||||
|
||||
fn C_MUL(a: &kiss_fft_cpx, b: &kiss_fft_cpx) -> kiss_fft_cpx {
|
||||
kiss_fft_cpx {
|
||||
r: a.r * b.r - a.i * b.i,
|
||||
i: a.r * b.i + a.i * b.r,
|
||||
}
|
||||
}
|
||||
//# define C_FIXDIV(c,div) /* NOOP */
|
||||
fn C_MULBYSCALAR(c: &mut kiss_fft_cpx, s: f32) {
|
||||
c.r *= s;
|
||||
c.i *= s;
|
||||
}
|
||||
/*#ifndef CHECK_OVERFLOW_OP
|
||||
# define CHECK_OVERFLOW_OP(a,op,b) /* noop */
|
||||
#endif*/
|
||||
|
||||
fn C_ADD(a: &kiss_fft_cpx, b: &kiss_fft_cpx) -> kiss_fft_cpx {
|
||||
kiss_fft_cpx {
|
||||
r: a.r + b.r,
|
||||
i: a.i + b.i,
|
||||
}
|
||||
}
|
||||
fn C_SUB(a: &kiss_fft_cpx, b: &kiss_fft_cpx) -> kiss_fft_cpx {
|
||||
kiss_fft_cpx {
|
||||
r: a.r - b.r,
|
||||
i: a.i - b.i,
|
||||
}
|
||||
}
|
||||
fn C_ADDTO(res: &mut kiss_fft_cpx, a: &kiss_fft_cpx) {
|
||||
res.r += a.r;
|
||||
res.i += a.i;
|
||||
}
|
||||
|
||||
fn HALF_OF(x: f32) -> f32 {
|
||||
x / 2.0
|
||||
}
|
||||
|
||||
fn kf_bfly2<const N: usize>(
|
||||
Fout: &mut [kiss_fft_cpx],
|
||||
fstride: usize,
|
||||
st: &kiss_fft_state<N>,
|
||||
mut m: usize,
|
||||
) {
|
||||
let mut tw1 = &st.twiddles[..];
|
||||
let (mut Fout, mut Fout2) = Fout.split_at_mut(m);
|
||||
while m > 0 {
|
||||
//C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2);
|
||||
|
||||
let t = C_MUL(&Fout2[0], &tw1[0]);
|
||||
tw1 = &tw1[fstride..];
|
||||
Fout2[0] = C_SUB(&Fout[0], &t);
|
||||
C_ADDTO(&mut Fout[0], &t);
|
||||
Fout2 = &mut Fout2[1..];
|
||||
Fout = &mut Fout[1..];
|
||||
m = m - 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn kf_bfly4<const N: usize>(
|
||||
mut Fout: &mut [kiss_fft_cpx],
|
||||
fstride: usize,
|
||||
st: &kiss_fft_state<N>,
|
||||
m: usize,
|
||||
) {
|
||||
let mut scratch = [kiss_fft_cpx::new(); 6];
|
||||
let mut k = m;
|
||||
let m2 = 2 * m;
|
||||
let m3 = 3 * m;
|
||||
|
||||
let mut tw1 = &st.twiddles[..];
|
||||
let mut tw2 = &st.twiddles[..];
|
||||
let mut tw3 = &st.twiddles[..];
|
||||
|
||||
loop {
|
||||
// C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4);
|
||||
|
||||
scratch[0] = C_MUL(&Fout[m], &tw1[0]);
|
||||
scratch[1] = C_MUL(&Fout[m2], &tw2[0]);
|
||||
scratch[2] = C_MUL(&Fout[m3], &tw3[0]);
|
||||
|
||||
scratch[5] = C_SUB(&Fout[0], &scratch[1]);
|
||||
C_ADDTO(&mut Fout[0], &scratch[1]);
|
||||
scratch[3] = C_ADD(&scratch[0], &scratch[2]);
|
||||
scratch[4] = C_SUB(&scratch[0], &scratch[2]);
|
||||
Fout[m2] = C_SUB(&Fout[0], &scratch[3]);
|
||||
tw1 = &tw1[fstride..];
|
||||
tw2 = &tw2[fstride * 2..];
|
||||
tw3 = &tw3[fstride * 3..];
|
||||
C_ADDTO(&mut Fout[0], &scratch[3]);
|
||||
|
||||
if st.inverse != 0 {
|
||||
Fout[m].r = scratch[5].r - scratch[4].i;
|
||||
Fout[m].i = scratch[5].i + scratch[4].r;
|
||||
Fout[m3].r = scratch[5].r + scratch[4].i;
|
||||
Fout[m3].i = scratch[5].i - scratch[4].r;
|
||||
} else {
|
||||
Fout[m].r = scratch[5].r + scratch[4].i;
|
||||
Fout[m].i = scratch[5].i - scratch[4].r;
|
||||
Fout[m3].r = scratch[5].r - scratch[4].i;
|
||||
Fout[m3].i = scratch[5].i + scratch[4].r;
|
||||
}
|
||||
Fout = &mut Fout[1..];
|
||||
k -= 1;
|
||||
if k == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kf_bfly3<const N: usize>(
|
||||
mut Fout: &mut [kiss_fft_cpx],
|
||||
fstride: usize,
|
||||
st: &kiss_fft_state<N>,
|
||||
m: usize,
|
||||
) {
|
||||
let mut k = m;
|
||||
let m2 = 2 * m;
|
||||
let mut scratch = [kiss_fft_cpx::new(); 5];
|
||||
let epi3 = st.twiddles[fstride * m];
|
||||
|
||||
let mut tw1 = 0;
|
||||
let mut tw2 = 0;
|
||||
|
||||
while k > 0 {
|
||||
// C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
|
||||
|
||||
scratch[1] = C_MUL(&Fout[m], &st.twiddles[tw1]);
|
||||
scratch[2] = C_MUL(&Fout[m2], &st.twiddles[tw2]);
|
||||
scratch[3] = C_ADD(&scratch[1], &scratch[2]);
|
||||
scratch[0] = C_SUB(&scratch[1], &scratch[2]);
|
||||
tw1 += fstride;
|
||||
tw2 += fstride * 2;
|
||||
|
||||
Fout[m].r = Fout[0].r - (scratch[3].r / 2.0);
|
||||
Fout[m].i = Fout[0].i - (scratch[3].i / 2.0);
|
||||
|
||||
C_MULBYSCALAR(&mut scratch[0], epi3.i);
|
||||
|
||||
C_ADDTO(&mut Fout[0], &scratch[3]);
|
||||
|
||||
Fout[m2].r = Fout[m].r + scratch[0].i;
|
||||
Fout[m2].i = Fout[m].i - scratch[0].r;
|
||||
|
||||
Fout[m].r -= scratch[0].i;
|
||||
Fout[m].i += scratch[0].r;
|
||||
|
||||
Fout = &mut Fout[1..];
|
||||
k -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn kf_bfly5<const N: usize>(
|
||||
Fout: &mut [kiss_fft_cpx],
|
||||
fstride: usize,
|
||||
st: &kiss_fft_state<N>,
|
||||
m: usize,
|
||||
) {
|
||||
let mut scratch = [kiss_fft_cpx::new(); 13];
|
||||
let ya = st.twiddles[fstride * m];
|
||||
let yb = st.twiddles[fstride * 2 * m];
|
||||
|
||||
let (mut Fout0, Fout1) = Fout.split_at_mut(m);
|
||||
let (mut Fout1, Fout2) = Fout1.split_at_mut(m);
|
||||
let (mut Fout2, Fout3) = Fout2.split_at_mut(m);
|
||||
let (mut Fout3, mut Fout4) = Fout3.split_at_mut(m);
|
||||
|
||||
let tw = &st.twiddles[..];
|
||||
for u in 0..m {
|
||||
// C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
|
||||
scratch[0] = Fout0[0];
|
||||
|
||||
scratch[1] = C_MUL(&Fout1[0], &tw[u * fstride]);
|
||||
scratch[2] = C_MUL(&Fout2[0], &tw[2 * u * fstride]);
|
||||
scratch[3] = C_MUL(&Fout3[0], &tw[3 * u * fstride]);
|
||||
scratch[4] = C_MUL(&Fout4[0], &tw[4 * u * fstride]);
|
||||
|
||||
scratch[7] = C_ADD(&scratch[1], &scratch[4]);
|
||||
scratch[10] = C_SUB(&scratch[1], &scratch[4]);
|
||||
scratch[8] = C_ADD(&scratch[2], &scratch[3]);
|
||||
scratch[9] = C_SUB(&scratch[2], &scratch[3]);
|
||||
|
||||
Fout0[0].r += scratch[7].r + scratch[8].r;
|
||||
Fout0[0].i += scratch[7].i + scratch[8].i;
|
||||
|
||||
scratch[5].r = scratch[0].r + (scratch[7].r * ya.r) + (scratch[8].r * yb.r);
|
||||
scratch[5].i = scratch[0].i + (scratch[7].i * ya.r) + (scratch[8].i * yb.r);
|
||||
|
||||
scratch[6].r = (scratch[10].i * ya.i) + (scratch[9].i * yb.i);
|
||||
scratch[6].i = -(scratch[10].r * ya.i) - (scratch[9].r * yb.i);
|
||||
|
||||
Fout1[0] = C_SUB(&scratch[5], &scratch[6]);
|
||||
Fout4[0] = C_ADD(&scratch[5], &scratch[6]);
|
||||
|
||||
scratch[11].r = scratch[0].r + (scratch[7].r * yb.r) + (scratch[8].r * ya.r);
|
||||
scratch[11].i = scratch[0].i + (scratch[7].i * yb.r) + (scratch[8].i * ya.r);
|
||||
scratch[12].r = -(scratch[10].i * yb.i) + (scratch[9].i * ya.i);
|
||||
scratch[12].i = (scratch[10].r * yb.i) - (scratch[9].r * ya.i);
|
||||
|
||||
Fout2[0] = C_ADD(&scratch[11], &scratch[12]);
|
||||
Fout3[0] = C_SUB(&scratch[11], &scratch[12]);
|
||||
|
||||
Fout0 = &mut Fout0[1..];
|
||||
Fout1 = &mut Fout1[1..];
|
||||
Fout2 = &mut Fout2[1..];
|
||||
Fout3 = &mut Fout3[1..];
|
||||
Fout4 = &mut Fout4[1..];
|
||||
}
|
||||
}
|
||||
|
||||
/* perform the butterfly for one stage of a mixed radix FFT */
|
||||
fn kf_bfly_generic<const N: usize>(
|
||||
Fout: &mut [kiss_fft_cpx],
|
||||
fstride: usize,
|
||||
st: &kiss_fft_state<N>,
|
||||
m: usize,
|
||||
p: usize,
|
||||
) {
|
||||
let Norig = st.nfft;
|
||||
|
||||
let mut scratch = Buffer::<kiss_fft_cpx, 5>::filled(p, kiss_fft_cpx::new());
|
||||
|
||||
for u in 0..m {
|
||||
let mut k = u;
|
||||
for q1 in 0..p {
|
||||
scratch[q1] = Fout[k];
|
||||
// C_FIXDIV(scratch[q1],p);
|
||||
k += m;
|
||||
}
|
||||
|
||||
k = u;
|
||||
for _q1 in 0..p {
|
||||
let mut twidx = 0;
|
||||
Fout[k] = scratch[0];
|
||||
for q in 1..p {
|
||||
twidx += fstride * k;
|
||||
if twidx >= Norig {
|
||||
twidx -= Norig;
|
||||
}
|
||||
let t = C_MUL(&scratch[q], &st.twiddles[twidx]);
|
||||
C_ADDTO(&mut Fout[k], &t);
|
||||
}
|
||||
k += m;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kf_work<const N: usize>(
|
||||
Fout: &mut [kiss_fft_cpx],
|
||||
mut f: &[kiss_fft_cpx],
|
||||
fstride: usize,
|
||||
in_stride: i32,
|
||||
factors: &[usize],
|
||||
st: &kiss_fft_state<N>,
|
||||
) {
|
||||
let p = factors[0]; /* the radix */
|
||||
let m = factors[1]; /* stage's fft length/p */
|
||||
if m == 1 {
|
||||
for fout_idx in 0..p * m {
|
||||
Fout[fout_idx] = f[0];
|
||||
f = &f[(fstride * in_stride as usize).min(f.len())..];
|
||||
}
|
||||
} else {
|
||||
for fout_idx in (0..p * m).step_by(m) {
|
||||
// recursive call:
|
||||
// DFT of size m*p performed by doing
|
||||
// p instances of smaller DFTs of size m,
|
||||
// each one takes a decimated version of the input
|
||||
kf_work(
|
||||
&mut Fout[fout_idx..],
|
||||
f,
|
||||
fstride * p,
|
||||
in_stride,
|
||||
&factors[2..],
|
||||
st,
|
||||
);
|
||||
f = &f[(fstride * in_stride as usize).min(f.len())..];
|
||||
}
|
||||
}
|
||||
|
||||
// recombine the p smaller DFTs
|
||||
match p {
|
||||
2 => {
|
||||
kf_bfly2(Fout, fstride, st, m);
|
||||
}
|
||||
3 => {
|
||||
kf_bfly3(Fout, fstride, st, m);
|
||||
}
|
||||
4 => {
|
||||
kf_bfly4(Fout, fstride, st, m);
|
||||
}
|
||||
5 => {
|
||||
kf_bfly5(Fout, fstride, st, m);
|
||||
}
|
||||
_ => {
|
||||
kf_bfly_generic(Fout, fstride, st, m, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kiss_fft_stride<const N: usize>(
|
||||
st: &kiss_fft_state<N>,
|
||||
fin: &[kiss_fft_cpx],
|
||||
fout: &mut [kiss_fft_cpx],
|
||||
in_stride: i32,
|
||||
) {
|
||||
kf_work(fout, fin, 1, in_stride, &st.factors[..], st);
|
||||
}
|
||||
|
||||
pub fn kiss_fft<const N: usize>(
|
||||
cfg: &kiss_fft_state<N>,
|
||||
fin: &[kiss_fft_cpx],
|
||||
fout: &mut [kiss_fft_cpx],
|
||||
) {
|
||||
kiss_fft_stride(cfg, fin, fout, 1);
|
||||
}
|
||||
|
||||
pub fn kiss_fftr(st: &mut kiss_fftr_cfg, timedata: &[f32], freqdata: &mut [kiss_fft_cpx]) {
|
||||
/* input buffer timedata is stored row-wise */
|
||||
// assert(st.substate.inverse==0);
|
||||
|
||||
let ncfft = st.substate.nfft;
|
||||
|
||||
/*perform the parallel fft of two real signals packed in real,imag*/
|
||||
//could transmute this but UGH so we copy
|
||||
let mut timedatac =
|
||||
Buffer::<kiss_fft_cpx, 256>::filled(timedata.len() / 2, kiss_fft_cpx::new());
|
||||
for i in 0..timedatac.len() {
|
||||
timedatac[i] = kiss_fft_cpx {
|
||||
r: timedata[i * 2],
|
||||
i: timedata[i * 2 + 1],
|
||||
};
|
||||
}
|
||||
kiss_fft(&st.substate, &timedatac, &mut st.tmpbuf);
|
||||
|
||||
/* The real part of the DC element of the frequency spectrum in st.tmpbuf
|
||||
* contains the sum of the even-numbered elements of the input time sequence
|
||||
* The imag part is the sum of the odd-numbered elements
|
||||
*
|
||||
* The sum of tdc.r and tdc.i is the sum of the input time sequence.
|
||||
* yielding DC of input time sequence
|
||||
* The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1...
|
||||
* yielding Nyquist bin of input time sequence
|
||||
*/
|
||||
let mut tdc = kiss_fft_cpx::new();
|
||||
tdc.r = st.tmpbuf[0].r;
|
||||
tdc.i = st.tmpbuf[0].i;
|
||||
// C_FIXDIV(tdc,2);
|
||||
// CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i);
|
||||
// CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i);
|
||||
freqdata[0].r = tdc.r + tdc.i;
|
||||
freqdata[ncfft].r = tdc.r - tdc.i;
|
||||
freqdata[ncfft].i = 0.0;
|
||||
freqdata[0].i = 0.0;
|
||||
|
||||
for k in 1..ncfft / 2 + 1 {
|
||||
let fpk = st.tmpbuf[k];
|
||||
let mut fpnk = kiss_fft_cpx::new();
|
||||
fpnk.r = st.tmpbuf[ncfft - k].r;
|
||||
fpnk.i = 0.0 - st.tmpbuf[ncfft - k].i;
|
||||
// C_FIXDIV(fpk,2);
|
||||
// C_FIXDIV(fpnk,2);
|
||||
|
||||
let f1k = C_ADD(&fpk, &fpnk);
|
||||
let f2k = C_SUB(&fpk, &fpnk);
|
||||
let tw = C_MUL(&f2k, &st.super_twiddles[k - 1]);
|
||||
|
||||
freqdata[k].r = HALF_OF(f1k.r + tw.r);
|
||||
freqdata[k].i = HALF_OF(f1k.i + tw.i);
|
||||
freqdata[ncfft - k].r = HALF_OF(f1k.r - tw.r);
|
||||
freqdata[ncfft - k].i = HALF_OF(tw.i - f1k.i);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kiss_fftri(st: &mut kiss_fftr_cfg, freqdata: &[kiss_fft_cpx], timedata: &mut [f32]) {
|
||||
/* input buffer timedata is stored row-wise */
|
||||
// assert(st.substate.inverse == 1);
|
||||
|
||||
let ncfft = st.substate.nfft;
|
||||
|
||||
st.tmpbuf[0].r = freqdata[0].r + freqdata[ncfft].r;
|
||||
st.tmpbuf[0].i = freqdata[0].r - freqdata[ncfft].r;
|
||||
// C_FIXDIV(st.tmpbuf[0],2);
|
||||
|
||||
for k in 1..ncfft / 2 + 1 {
|
||||
let fk = freqdata[k];
|
||||
let mut fnkc = kiss_fft_cpx::new();
|
||||
fnkc.r = freqdata[ncfft - k].r;
|
||||
fnkc.i = 0.0 - freqdata[ncfft - k].i;
|
||||
// C_FIXDIV( fk , 2 );
|
||||
// C_FIXDIV( fnkc , 2 );
|
||||
|
||||
let fek = C_ADD(&fk, &fnkc);
|
||||
let tmp = C_SUB(&fk, &fnkc);
|
||||
let fok = C_MUL(&tmp, &st.super_twiddles[k - 1]);
|
||||
st.tmpbuf[k] = C_ADD(&fek, &fok);
|
||||
st.tmpbuf[ncfft - k] = C_SUB(&fek, &fok);
|
||||
st.tmpbuf[ncfft - k].i *= -1.0;
|
||||
}
|
||||
//could transmute this but UGH so we copy
|
||||
let mut timedatac =
|
||||
Buffer::<kiss_fft_cpx, 256>::filled(timedata.len() / 2, kiss_fft_cpx::new());
|
||||
kiss_fft(&st.substate, &st.tmpbuf, &mut timedatac);
|
||||
for i in 0..timedatac.len() {
|
||||
timedata[i * 2] = timedatac[i].r;
|
||||
timedata[i * 2 + 1] = timedatac[i].i;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,433 @@
|
||||
// Codec2 700C/newamp1, adapted to fixed-storage Rust from David Rowe's
|
||||
// codec2.c, newamp1.c, mbest.c, phase.c and quantise.c (Copyright 2017).
|
||||
// Source commit and hashes: ../../UPSTREAM.json. LGPL-2.1-only; see NOTICE
|
||||
// and licenses/LGPL-2.1.txt. No C code or allocator is linked at runtime.
|
||||
use super::{codebook700c::*, *};
|
||||
|
||||
const K: usize = 20;
|
||||
const NFFT: usize = 128;
|
||||
const NS: usize = NFFT / 2 + 1;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct State {
|
||||
frequencies: [f32; K],
|
||||
previous: [f32; K],
|
||||
wo_left: f32,
|
||||
voiced_left: i32,
|
||||
forward: kiss_fft_state<NFFT>,
|
||||
inverse: kiss_fft_state<NFFT>,
|
||||
}
|
||||
|
||||
// Match the portable upstream POW10F configuration used by the pinned oracle.
|
||||
fn pow10(value: f32) -> f32 {
|
||||
libm::expf(2.302585092994046_f32 * value)
|
||||
}
|
||||
|
||||
// Double-expression variant preserves the C macro promotion before expf.
|
||||
fn pow10_double(value: f64) -> f32 {
|
||||
libm::expf((f64::from(2.302585092994046_f32) * value) as f32)
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub(super) fn initialise(&mut self) {
|
||||
fn mel(hz: f32) -> f32 {
|
||||
libm::floorf(
|
||||
(2595.0 * f64::from(libm::log10f((1.0 + f64::from(hz) / 700.0) as f32)) + 0.5)
|
||||
as f32,
|
||||
)
|
||||
}
|
||||
let start = mel(200.0);
|
||||
let step = (mel(3700.0) - start) / (K - 1) as f32;
|
||||
let mut value = start;
|
||||
for frequency in &mut self.frequencies {
|
||||
*frequency = (0.7 * (f64::from(pow10_double(f64::from(value) / 2595.0)) - 1.0)) as f32;
|
||||
value += step;
|
||||
}
|
||||
self.previous.fill(0.0);
|
||||
self.wo_left = 0.0;
|
||||
self.voiced_left = 0;
|
||||
self.forward.initialise(NFFT, 0);
|
||||
self.inverse.initialise(NFFT, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve upstream's parabolic interpolation and strict tie ordering. All
|
||||
// callers have monotonically increasing frequency axes with at least 3 points.
|
||||
fn interpolate(y: &mut [f32], xp: &[f32], yp: &[f32], x: &[f32]) {
|
||||
debug_assert!(xp.len() >= 3 && xp.len() == yp.len() && y.len() == x.len());
|
||||
let mut k = 0;
|
||||
for (yi, &xi) in y.iter_mut().zip(x) {
|
||||
while xp[k + 1] < xi && k < xp.len() - 3 {
|
||||
k += 1;
|
||||
}
|
||||
let (x1, x2, x3) = (xp[k], xp[k + 1], xp[k + 2]);
|
||||
let (y1, y2, y3) = (yp[k], yp[k + 1], yp[k + 2]);
|
||||
let a = ((y3 - y2) / (x3 - x2) - (y2 - y1) / (x2 - x1)) / (x3 - x1);
|
||||
let b = ((y3 - y2) / (x3 - x2) * (x2 - x1) + (y2 - y1) / (x2 - x1) * (x3 - x2)) / (x3 - x1);
|
||||
*yi = a * (xi - x2) * (xi - x2) + b * (xi - x2) + y2;
|
||||
}
|
||||
}
|
||||
|
||||
fn harmonic_frequency(model: &MODEL, m: usize) -> f32 {
|
||||
(f64::from(m as f32 * model.Wo) * 4.0 / core::f64::consts::PI) as f32
|
||||
}
|
||||
|
||||
fn rate_k(model: &MODEL, frequencies: &[f32; K]) -> [f32; K] {
|
||||
let mut amplitudes = [0.0_f32; MAX_AMP + 1];
|
||||
let mut harmonics = [0.0_f32; MAX_AMP + 1];
|
||||
let mut peak = -100.0_f32;
|
||||
for m in 1..=model.L {
|
||||
amplitudes[m] = 20.0 * libm::log10f((f64::from(model.A[m]) + 1e-16) as f32);
|
||||
peak = peak.max(amplitudes[m]);
|
||||
harmonics[m] = harmonic_frequency(model, m);
|
||||
}
|
||||
for amplitude in &mut amplitudes[1..=model.L] {
|
||||
*amplitude = amplitude.max(peak - 50.0);
|
||||
}
|
||||
let mut result = [0.0; K];
|
||||
interpolate(
|
||||
&mut result,
|
||||
&harmonics[1..=model.L],
|
||||
&litudes[1..=model.L],
|
||||
frequencies,
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
// Fixed five-candidate M-best search. Strict < preserves the first codebook
|
||||
// entry on ties, including ties crossing the two-stage search order.
|
||||
#[inline]
|
||||
fn squared_error(vector: &[f32], target: &[f32; K], limit: f32) -> f32 {
|
||||
let mut error = 0.0;
|
||||
// Squared distances only increase. Reject a candidate once it cannot beat
|
||||
// the current cutoff, preserving both scalar addition order and ties.
|
||||
// Check in groups to avoid a branch for every DSP multiply/add.
|
||||
for start in (0..K).step_by(4) {
|
||||
for k in start..start + 4 {
|
||||
let difference = vector[k] - target[k];
|
||||
error += difference * difference;
|
||||
}
|
||||
if error >= limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
fn quantize(target: &[f32; K]) -> (usize, usize) {
|
||||
let mut best = [(1e32_f32, 0_usize); 5];
|
||||
for (index, vector) in VQ1.chunks_exact(K).enumerate() {
|
||||
let error = squared_error(vector, target, best[best.len() - 1].0);
|
||||
if let Some(position) = best.iter().position(|entry| error < entry.0) {
|
||||
for n in (position + 1..best.len()).rev() {
|
||||
best[n] = best[n - 1];
|
||||
}
|
||||
best[position] = (error, index);
|
||||
}
|
||||
}
|
||||
// Visit the flash-resident second codebook once, using each vector for all
|
||||
// five candidates while it is cached. Keep one winner per candidate, then
|
||||
// select in the original candidate order to preserve strict tie behavior.
|
||||
let mut residuals = [[0.0; K]; 5];
|
||||
let mut winners = [(1e32_f32, 0_usize); 5];
|
||||
for (rank, (_, first)) in best.iter().copied().enumerate() {
|
||||
for k in 0..K {
|
||||
residuals[rank][k] = target[k] - VQ1[first * K + k];
|
||||
}
|
||||
}
|
||||
for (second, vector) in VQ2.chunks_exact(K).enumerate() {
|
||||
for (residual, winner) in residuals.iter().zip(&mut winners) {
|
||||
let error = squared_error(vector, residual, winner.0);
|
||||
if error < winner.0 {
|
||||
*winner = (error, second);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut result = (1e32_f32, 0, 0);
|
||||
for ((_, first), (error, second)) in best.into_iter().zip(winners) {
|
||||
if error < result.0 {
|
||||
result = (error, first, second);
|
||||
}
|
||||
}
|
||||
(result.1, result.2)
|
||||
}
|
||||
|
||||
fn encode_model(model: &MODEL, state: &State, constants: &C2const) -> [i32; 4] {
|
||||
let mut vector = rate_k(model, &state.frequencies);
|
||||
let mut sum = 0.0;
|
||||
for value in vector {
|
||||
sum += value;
|
||||
}
|
||||
let mean = sum / K as f32;
|
||||
for value in &mut vector {
|
||||
*value -= mean;
|
||||
}
|
||||
// The pinned default disables front EQ. Its unused diagnostic/EQ history
|
||||
// has no effect on the wire data and is not retained in the bounded backend.
|
||||
let (first, second) = quantize(&vector);
|
||||
let mut energy = 0;
|
||||
let mut error = f32::MAX;
|
||||
for (index, value) in ENERGY.iter().enumerate() {
|
||||
let difference = value - mean;
|
||||
let candidate = difference * difference;
|
||||
if candidate < error {
|
||||
error = candidate;
|
||||
energy = index;
|
||||
}
|
||||
}
|
||||
let pitch = if model.voiced != 0 {
|
||||
let min = constants.Wo_min.dsp_log10();
|
||||
let max = constants.Wo_max.dsp_log10();
|
||||
let normal = (model.Wo.dsp_log10() - min) / (max - min);
|
||||
(64.0 * normal + 0.5).dsp_floor().clamp(1.0, 63.0) as i32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
[first as i32, second as i32, energy as i32, pitch]
|
||||
}
|
||||
|
||||
fn decode_vector(indexes: &[i32; 4], frequencies: &[f32; K]) -> [f32; K] {
|
||||
let mut result = [0.0; K];
|
||||
let mut pre = [0.0; K];
|
||||
let (mut before, mut after) = (0.0, 0.0);
|
||||
for k in 0..K {
|
||||
result[k] = VQ1[indexes[0] as usize * K + k] + VQ2[indexes[1] as usize * K + k];
|
||||
pre[k] = 20.0 * libm::log10f((f64::from(frequencies[k]) / 0.3) as f32);
|
||||
result[k] += pre[k];
|
||||
before += pow10_double(f64::from(result[k]) / 10.0);
|
||||
result[k] *= 1.5;
|
||||
after += pow10_double(f64::from(result[k]) / 10.0);
|
||||
}
|
||||
let gain = 10.0 * (after / before).dsp_log10();
|
||||
for k in 0..K {
|
||||
result[k] -= gain;
|
||||
result[k] -= pre[k];
|
||||
result[k] += ENERGY[indexes[2] as usize];
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn rate_l(model: &mut MODEL, vector: &[f32; K], frequencies: &[f32; K]) {
|
||||
let mut levels = [0.0; K + 2];
|
||||
let mut axis = [0.0; K + 2];
|
||||
levels[1..=K].copy_from_slice(vector);
|
||||
axis[1..=K].copy_from_slice(frequencies);
|
||||
axis[K + 1] = 4.0;
|
||||
let mut harmonics = [0.0; MAX_AMP + 1];
|
||||
let mut amplitudes = [0.0; MAX_AMP + 1];
|
||||
for m in 1..=model.L {
|
||||
harmonics[m] = harmonic_frequency(model, m);
|
||||
}
|
||||
interpolate(
|
||||
&mut amplitudes[1..=model.L],
|
||||
&axis,
|
||||
&levels,
|
||||
&harmonics[1..=model.L],
|
||||
);
|
||||
for m in 1..=model.L {
|
||||
model.A[m] = pow10_double(f64::from(amplitudes[m]) / 20.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the cepstral FFT scratch lifetime separate from synthesis. One 10 ms
|
||||
// model is reconstructed at a time instead of retaining four models and H[].
|
||||
#[inline(never)]
|
||||
fn determine_phase(model: &MODEL, state: &State, h: &mut [COMP; MAX_AMP + 1]) {
|
||||
let mut amplitudes = [0.0; MAX_AMP + 1];
|
||||
let mut harmonics = [0.0; MAX_AMP + 1];
|
||||
for m in 1..=model.L {
|
||||
amplitudes[m] = 20.0 * model.A[m].dsp_log10();
|
||||
harmonics[m] = harmonic_frequency(model, m);
|
||||
}
|
||||
let mut spectrum = [0.0; NS];
|
||||
let mut frequencies = [0.0; NS];
|
||||
for (i, frequency) in frequencies.iter_mut().enumerate() {
|
||||
*frequency = 8.0 * i as f32 / NFFT as f32;
|
||||
}
|
||||
interpolate(
|
||||
&mut spectrum,
|
||||
&harmonics[1..=model.L],
|
||||
&litudes[1..=model.L],
|
||||
&frequencies,
|
||||
);
|
||||
let mut input = [COMP::new(); NFFT];
|
||||
let mut output = [COMP::new(); NFFT];
|
||||
input[0].r = spectrum[0];
|
||||
for i in 1..NS {
|
||||
input[i].r = spectrum[i];
|
||||
input[NFFT - i].r = spectrum[i];
|
||||
}
|
||||
kiss_fft::kiss_fft(&state.inverse, &input, &mut output);
|
||||
for value in &mut output {
|
||||
value.r /= NFFT as f32;
|
||||
value.i /= NFFT as f32;
|
||||
}
|
||||
input.fill(COMP::new());
|
||||
input[0] = output[0];
|
||||
input[NS - 1] = output[NS - 1];
|
||||
for i in 1..NS - 1 {
|
||||
input[i].r = output[i].r + output[NFFT - i].r;
|
||||
input[i].i = output[i].i + output[NFFT - i].i;
|
||||
}
|
||||
kiss_fft::kiss_fft(&state.forward, &input, &mut output);
|
||||
let scale = (20.0 / f64::from(libm::logf(10.0))) as f32;
|
||||
for m in 1..=model.L {
|
||||
let bin = libm::floorf(
|
||||
(0.5 + f64::from(m as f32 * model.Wo * NFFT as f32) / (2.0 * core::f64::consts::PI))
|
||||
as f32,
|
||||
) as usize;
|
||||
debug_assert!(bin < NS);
|
||||
let phase = output[bin].i / scale;
|
||||
h[m].r = phase.dsp_cos();
|
||||
h[m].i = phase.dsp_sin();
|
||||
}
|
||||
}
|
||||
|
||||
impl Codec2 {
|
||||
pub(super) fn codec2_encode_700c(&mut self, bits: &mut [u8], speech: &[i16]) {
|
||||
let mut model = MODEL::new(self.internal.c2const.p_max as f32);
|
||||
for frame in speech.chunks_exact(80) {
|
||||
self.analyse_one_frame(&mut model, frame);
|
||||
}
|
||||
let indexes = encode_model(&model, &self.internal.newamp, &self.internal.c2const);
|
||||
bits.fill(0);
|
||||
let mut offset = 0;
|
||||
for (value, width) in indexes.into_iter().zip([9, 9, 4, 6]) {
|
||||
pack_natural_or_gray(bits, &mut offset, value, width, 0);
|
||||
}
|
||||
debug_assert_eq!(offset, 28);
|
||||
}
|
||||
|
||||
pub(super) fn codec2_decode_700c(&mut self, speech: &mut [i16], bits: &[u8]) {
|
||||
let mut offset = 0;
|
||||
let mut indexes = [0; 4];
|
||||
for (value, width) in indexes.iter_mut().zip([9, 9, 4, 6]) {
|
||||
*value = unpack_natural_or_gray(bits, &mut offset, width, 0);
|
||||
}
|
||||
let right = decode_vector(&indexes, &self.internal.newamp.frequencies);
|
||||
let unvoiced_wo = (2.0 * core::f64::consts::PI / 100.0) as f32;
|
||||
let voiced_right = i32::from(indexes[3] != 0);
|
||||
let wo_right = if voiced_right != 0 {
|
||||
let min = self.internal.c2const.Wo_min.dsp_log10();
|
||||
let step = (self.internal.c2const.Wo_max.dsp_log10() - min) / 64.0;
|
||||
pow10(min + step * indexes[3] as f32)
|
||||
} else {
|
||||
unvoiced_wo
|
||||
};
|
||||
for frame in 0..4 {
|
||||
let mut model = MODEL::new(self.internal.c2const.p_max as f32);
|
||||
let c = 1.0 - frame as f32 / 4.0;
|
||||
let left = &self.internal.newamp;
|
||||
match (left.voiced_left != 0, voiced_right != 0) {
|
||||
(true, true) => {
|
||||
model.Wo = (f64::from(left.wo_left * c)
|
||||
+ f64::from(wo_right) * (1.0 - f64::from(c)))
|
||||
as f32;
|
||||
model.voiced = 1;
|
||||
}
|
||||
(true, false) if frame < 2 => {
|
||||
model.Wo = left.wo_left;
|
||||
model.voiced = 1;
|
||||
}
|
||||
(false, true) if frame >= 2 => {
|
||||
model.Wo = wo_right;
|
||||
model.voiced = 1;
|
||||
}
|
||||
_ => {
|
||||
model.Wo = unvoiced_wo;
|
||||
model.voiced = 0;
|
||||
}
|
||||
}
|
||||
model.L = libm::floorf((core::f64::consts::PI / f64::from(model.Wo)) as f32) as usize;
|
||||
let mut vector = [0.0; K];
|
||||
for k in 0..K {
|
||||
vector[k] = (f64::from(left.previous[k] * c)
|
||||
+ f64::from(right[k]) * (1.0 - f64::from(c)))
|
||||
as f32;
|
||||
}
|
||||
rate_l(&mut model, &vector, &left.frequencies);
|
||||
let mut h = [COMP::new(); MAX_AMP + 1];
|
||||
determine_phase(&model, left, &mut h);
|
||||
self.synthesise_one_frame(
|
||||
&mut speech[80 * frame..80 * (frame + 1)],
|
||||
&mut model,
|
||||
&h,
|
||||
1.5,
|
||||
);
|
||||
}
|
||||
self.internal.newamp.previous = right;
|
||||
self.internal.newamp.wo_left = wo_right;
|
||||
self.internal.newamp.voiced_left = voiced_right;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Exhaustive pre-optimization search is an independent ordering oracle.
|
||||
fn exhaustive(target: &[f32; K]) -> (usize, usize) {
|
||||
let mut best = [(1e32_f32, 0_usize); 5];
|
||||
for (index, vector) in VQ1.chunks_exact(K).enumerate() {
|
||||
let error = vector.iter().zip(target).fold(0.0, |sum, (a, b)| {
|
||||
let d = a - b;
|
||||
sum + d * d
|
||||
});
|
||||
if let Some(position) = best.iter().position(|entry| error < entry.0) {
|
||||
for n in (position + 1..best.len()).rev() {
|
||||
best[n] = best[n - 1];
|
||||
}
|
||||
best[position] = (error, index);
|
||||
}
|
||||
}
|
||||
let mut result = (1e32_f32, 0, 0);
|
||||
for (_, first) in best {
|
||||
let mut residual = [0.0; K];
|
||||
for k in 0..K {
|
||||
residual[k] = target[k] - VQ1[first * K + k];
|
||||
}
|
||||
for (second, vector) in VQ2.chunks_exact(K).enumerate() {
|
||||
let error = vector.iter().zip(residual).fold(0.0, |sum, (a, b)| {
|
||||
let d = a - b;
|
||||
sum + d * d
|
||||
});
|
||||
if error < result.0 {
|
||||
result = (error, first, second);
|
||||
}
|
||||
}
|
||||
}
|
||||
(result.1, result.2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_search_preserves_exhaustive_winners() {
|
||||
let mut random = 71_u32;
|
||||
for case in 0..4096 {
|
||||
let mut target = [0.0; K];
|
||||
for (k, value) in target.iter_mut().enumerate() {
|
||||
random = random.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
*value = match case % 8 {
|
||||
0 => 0.0,
|
||||
1 => VQ1[(case / 8 % 512) * K + k],
|
||||
2 => VQ2[(case / 8 % 512) * K + k],
|
||||
3 => VQ1[(case / 8 % 512) * K + k] + VQ2[((case / 8 * 17) % 512) * K + k],
|
||||
_ => ((random >> 16) as i16) as f32 / (1 << (case % 12)) as f32,
|
||||
};
|
||||
}
|
||||
assert_eq!(quantize(&target), exhaustive(&target), "case {case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_distance_preserves_winning_arithmetic_and_ties() {
|
||||
let target = [0.0; K];
|
||||
let vector = [1.0; K];
|
||||
assert_eq!(
|
||||
squared_error(&vector, &target, 21.0).to_bits(),
|
||||
20.0_f32.to_bits()
|
||||
);
|
||||
assert_eq!(squared_error(&vector, &target, 20.0), 20.0);
|
||||
assert_eq!(squared_error(&vector, &target, 4.0), 4.0);
|
||||
assert_eq!(squared_error(&vector, &target, 5.0), 8.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
use super::*;
|
||||
const fdmdv_os_filter: [f32; 48] = [
|
||||
-0.0008215855034550382,
|
||||
-0.0007833023901802921,
|
||||
0.001075563790768233,
|
||||
0.001199092367787555,
|
||||
-0.001765309502928316,
|
||||
-0.002055372115328064,
|
||||
0.002986877604154257,
|
||||
0.003462567920638414,
|
||||
-0.004856570111126334,
|
||||
-0.005563143845031497,
|
||||
0.007533613299748122,
|
||||
0.008563932468880897,
|
||||
-0.01126857129039911,
|
||||
-0.01280782411693687,
|
||||
0.01651443896361847,
|
||||
0.01894875110322284,
|
||||
-0.02421604439474981,
|
||||
-0.02845107338464062,
|
||||
0.03672973563400258,
|
||||
0.04542046150312214,
|
||||
-0.06189165826716491,
|
||||
-0.08721876380763803,
|
||||
0.1496157094199961,
|
||||
0.4497962274137046,
|
||||
0.4497962274137046,
|
||||
0.1496157094199961,
|
||||
-0.08721876380763803,
|
||||
-0.0618916582671649,
|
||||
0.04542046150312216,
|
||||
0.03672973563400257,
|
||||
-0.02845107338464062,
|
||||
-0.02421604439474984,
|
||||
0.01894875110322284,
|
||||
0.01651443896361848,
|
||||
-0.01280782411693687,
|
||||
-0.0112685712903991,
|
||||
0.008563932468880899,
|
||||
0.007533613299748123,
|
||||
-0.005563143845031501,
|
||||
-0.004856570111126346,
|
||||
0.003462567920638419,
|
||||
0.002986877604154259,
|
||||
-0.002055372115328063,
|
||||
-0.001765309502928318,
|
||||
0.001199092367787557,
|
||||
0.001075563790768233,
|
||||
-0.0007833023901802925,
|
||||
-0.0008215855034550383,
|
||||
];
|
||||
|
||||
const nlp_fir: [f32; 48] = [
|
||||
-1.0818124e-03,
|
||||
-1.1008344e-03,
|
||||
-9.2768838e-04,
|
||||
-4.2289438e-04,
|
||||
5.5034190e-04,
|
||||
2.0029849e-03,
|
||||
3.7058509e-03,
|
||||
5.1449415e-03,
|
||||
5.5924666e-03,
|
||||
4.3036754e-03,
|
||||
8.0284511e-04,
|
||||
-4.8204610e-03,
|
||||
-1.1705810e-02,
|
||||
-1.8199275e-02,
|
||||
-2.2065282e-02,
|
||||
-2.0920610e-02,
|
||||
-1.2808831e-02,
|
||||
3.2204775e-03,
|
||||
2.6683811e-02,
|
||||
5.5520624e-02,
|
||||
8.6305944e-02,
|
||||
1.1480192e-01,
|
||||
1.3674206e-01,
|
||||
1.4867556e-01,
|
||||
1.4867556e-01,
|
||||
1.3674206e-01,
|
||||
1.1480192e-01,
|
||||
8.6305944e-02,
|
||||
5.5520624e-02,
|
||||
2.6683811e-02,
|
||||
3.2204775e-03,
|
||||
-1.2808831e-02,
|
||||
-2.0920610e-02,
|
||||
-2.2065282e-02,
|
||||
-1.8199275e-02,
|
||||
-1.1705810e-02,
|
||||
-4.8204610e-03,
|
||||
8.0284511e-04,
|
||||
4.3036754e-03,
|
||||
5.5924666e-03,
|
||||
5.1449415e-03,
|
||||
3.7058509e-03,
|
||||
2.0029849e-03,
|
||||
5.5034190e-04,
|
||||
-4.2289438e-04,
|
||||
-9.2768838e-04,
|
||||
-1.1008344e-03,
|
||||
-1.0818124e-03,
|
||||
];
|
||||
|
||||
//const PMAX_M: i32 = 320; /* maximum NLP analysis window size */
|
||||
const COEFF: f64 = 0.95; /* notch filter parameter */
|
||||
const PE_FFT_SIZE: i32 = 512; /* DFT size for pitch estimation */
|
||||
const DEC: i32 = 5; /* decimation factor */
|
||||
const SAMPLE_RATE: i32 = 8000;
|
||||
//const PI: f32 = 3.141592654; /* mathematical constant */
|
||||
//const T: f32 = 0.1; /* threshold for local minima candidate */
|
||||
//const F0_MAX: i32 = 500;
|
||||
const CNLP: f32 = 0.3; /* post processor constant */
|
||||
const NLP_NTAP: i32 = 48; /* Decimation LPF order */
|
||||
const FDMDV_OS: i32 = 2; /* oversampling rate */
|
||||
pub const FDMDV_OS_TAPS_16K: i32 = 48; /* number of OS filter taps at 16kHz */
|
||||
//const FDMDV_OS_TAPS_8K: i32 = FDMDV_OS_TAPS_16K / FDMDV_OS; /* number of OS filter taps at 8kHz */
|
||||
/*---------------------------------------------------------------------------*\
|
||||
|
||||
post_process_sub_multiples()
|
||||
|
||||
Given the global maximma of Fw[] we search integer submultiples for
|
||||
local maxima. If local maxima exist and they are above an
|
||||
experimentally derived threshold (OK a magic number I pulled out of
|
||||
the air) we choose the submultiple as the F0 estimate.
|
||||
|
||||
The rational for this is that the lowest frequency peak of Fw[]
|
||||
should be F0, as Fw[] can be considered the autocorrelation function
|
||||
of Sw[] (the speech spectrum). However sometimes due to phase
|
||||
effects the lowest frequency maxima may not be the global maxima.
|
||||
|
||||
This works OK in practice and favours low F0 values in the presence
|
||||
of background noise which means the sinusoidal codec does an OK job
|
||||
of synthesising the background noise. High F0 in background noise
|
||||
tends to sound more periodic introducing annoying artifacts.
|
||||
|
||||
\*---------------------------------------------------------------------------*/
|
||||
|
||||
fn post_process_sub_multiples(
|
||||
Fw: &[COMP],
|
||||
_pmin: i32,
|
||||
pmax: i32,
|
||||
gmax: f32,
|
||||
gmax_bin: i32,
|
||||
prev_f0: &f32,
|
||||
) -> f32 {
|
||||
/* post process estimate by searching submultiples */
|
||||
|
||||
let mut mult = 2;
|
||||
let min_bin = PE_FFT_SIZE * DEC / pmax;
|
||||
let mut cmax_bin = gmax_bin;
|
||||
let prev_f0_bin = ((*prev_f0) * ((PE_FFT_SIZE * DEC) as f32) / (SAMPLE_RATE as f32)) as i32;
|
||||
|
||||
while gmax_bin / mult >= min_bin {
|
||||
let b = gmax_bin / mult; /* determine search interval */
|
||||
let mut bmin = (0.8 * (b as f32)) as usize;
|
||||
let bmax = (1.2 * (b as f32)) as usize;
|
||||
if bmin < min_bin as usize {
|
||||
bmin = min_bin as usize;
|
||||
}
|
||||
/* lower threshold to favour previous frames pitch estimate,
|
||||
this is a form of pitch tracking */
|
||||
|
||||
let thresh = if (prev_f0_bin > bmin as i32) && (prev_f0_bin < bmax as i32) {
|
||||
CNLP * 0.5 * gmax
|
||||
} else {
|
||||
CNLP * gmax
|
||||
};
|
||||
let mut lmax = 0.0;
|
||||
let mut lmax_bin = bmin;
|
||||
for b in bmin..=bmax {
|
||||
/* look for maximum in interval */
|
||||
if Fw[b].r > lmax {
|
||||
lmax = Fw[b].r;
|
||||
lmax_bin = b;
|
||||
}
|
||||
}
|
||||
|
||||
if lmax > thresh {
|
||||
if (lmax > Fw[lmax_bin - 1].r) && (lmax > Fw[lmax_bin + 1].r) {
|
||||
cmax_bin = lmax_bin as i32;
|
||||
}
|
||||
}
|
||||
mult += 1;
|
||||
}
|
||||
|
||||
cmax_bin as f32 * SAMPLE_RATE as f32 / (PE_FFT_SIZE as f32 * DEC as f32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn submultiple_search_includes_upper_interval_endpoint() {
|
||||
let mut spectrum = [COMP::new(); PE_FFT_SIZE as usize];
|
||||
spectrum[80].r = 100.0;
|
||||
spectrum[48].r = 50.0; // Upper endpoint of the 80/2 search interval.
|
||||
assert_eq!(
|
||||
post_process_sub_multiples(&spectrum, 20, 160, 100.0, 80, &50.0),
|
||||
150.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pitch_history_uses_an_integer_bin_before_threshold_comparison() {
|
||||
let mut spectrum = [COMP::new(); PE_FFT_SIZE as usize];
|
||||
spectrum[80].r = 100.0;
|
||||
spectrum[40].r = 20.0; // Above tracking threshold, below normal threshold.
|
||||
let previous = 32.5 * SAMPLE_RATE as f32 / (PE_FFT_SIZE * DEC) as f32;
|
||||
assert_eq!(
|
||||
post_process_sub_multiples(&spectrum, 20, 160, 100.0, 80, &previous),
|
||||
250.0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/*---------------------------------------------------------------------------*\
|
||||
|
||||
FUNCTION....: fdmdv_16_to_8()
|
||||
AUTHOR......: David Rowe, conversion by Matt Weeks
|
||||
DATE CREATED: 9 May 2012
|
||||
|
||||
Changes the sample rate of a signal from 16 to 8 kHz.
|
||||
|
||||
n is the number of samples at the 8 kHz rate, there are FDMDV_OS*n
|
||||
samples at the 48 kHz rate. As above however a memory of
|
||||
FDMDV_OS_TAPS samples is reqd for in16k[] (see t16_8.c unit test as example).
|
||||
|
||||
Low pass filter the 16 kHz signal at 4 kHz using the same filter as
|
||||
the upsampler, then just output every FDMDV_OS-th filtered sample.
|
||||
|
||||
Note: this function copied from fdmdv.c, included in nlp.c as a convenience
|
||||
to avoid linking with another source file.
|
||||
|
||||
\*---------------------------------------------------------------------------*/
|
||||
|
||||
fn fdmdv_16_to_8(out8k: &mut [f32], in16k: &mut [f32], in16koff: usize, n: i32) {
|
||||
let mut i = 0;
|
||||
for k in 0..n as usize {
|
||||
let mut acc = 0.0;
|
||||
for j in 0..FDMDV_OS_TAPS_16K as usize {
|
||||
acc += fdmdv_os_filter[j] * in16k[in16koff + i - j];
|
||||
}
|
||||
out8k[k] = acc;
|
||||
i += FDMDV_OS as usize;
|
||||
}
|
||||
|
||||
/* update filter memory */
|
||||
|
||||
for i in -FDMDV_OS_TAPS_16K..0 {
|
||||
in16k[(in16koff as i32 + i) as usize] =
|
||||
in16k[(in16koff as isize + i as isize + n as isize * FDMDV_OS as isize) as usize];
|
||||
}
|
||||
}
|
||||
/*---------------------------------------------------------------------------*\
|
||||
|
||||
nlp()
|
||||
|
||||
Determines the pitch in samples using the Non Linear Pitch (NLP)
|
||||
algorithm [1]. Returns the fundamental in Hz. Note that the actual
|
||||
pitch estimate is for the centre of the M sample Sn[] vector, not
|
||||
the current N sample input vector. This is (I think) a delay of 2.5
|
||||
frames with N=80 samples. You should align further analysis using
|
||||
this pitch estimate to be centred on the middle of Sn[].
|
||||
|
||||
Two post processors have been tried, the MBE version (as discussed
|
||||
in [1]), and a post processor that checks sub-multiples. Both
|
||||
suffer occasional gross pitch errors (i.e. neither are perfect). In
|
||||
the presence of background noise the sub-multiple algorithm tends
|
||||
towards low F0 which leads to better sounding background noise than
|
||||
the MBE post processor.
|
||||
|
||||
A good way to test and develop the NLP pitch estimator is using the
|
||||
tnlp (codec2/unittest) and the codec2/octave/plnlp.m Octave script.
|
||||
|
||||
A pitch tracker searching a few frames forward and backward in time
|
||||
would be a useful addition.
|
||||
|
||||
References:
|
||||
|
||||
[1] http://rowetel.com/downloads/1997_rowe_phd_thesis.pdf Chapter 4
|
||||
|
||||
\*---------------------------------------------------------------------------*/
|
||||
|
||||
pub fn nlp(
|
||||
nlp: &mut NLP,
|
||||
fft_cfg: &codec2_fft_cfg,
|
||||
Sn: &[f32], /* input speech vector */
|
||||
n: usize, /* frames shift (no. new samples in Sn[]) */
|
||||
pitch: &mut f32, /* estimated pitch period in samples at current Fs */
|
||||
_Sw: &[COMP], /* Freq domain version of Sn[] */
|
||||
_W: &[f32], /* Freq domain window */
|
||||
prev_f0: &mut f32, /* previous pitch f0 in Hz, memory for pitch tracking */
|
||||
) -> f32 {
|
||||
// notch: f32; /* current notch filter output */
|
||||
// let mut Fw[PE_FFT_SIZE]; /* DFT of squared signal (input/output) */
|
||||
// PROFILE_VAR(start, tnotch, filter, peakpick, window, fft, magsq, shiftmem);
|
||||
// assert(nlp_state != NULL);
|
||||
// nlp = (NLP*)nlp_state;
|
||||
let m = nlp.m;
|
||||
|
||||
/* Square, notch filter at DC, and LP filter vector */
|
||||
|
||||
/* If running at 16 kHz decimate to 8 kHz, as NLP ws designed for
|
||||
Fs = 8kHz. The decimating filter introduces about 3ms of delay,
|
||||
that shouldn't be a problem as pitch changes slowly. */
|
||||
|
||||
// This backend admits 8 kHz only; no 16 kHz resampling owner is retained.
|
||||
for i in m - n..m {
|
||||
nlp.sq[i] = Sn[i] * Sn[i];
|
||||
}
|
||||
//fprintf(stderr, "n: %d m: %d\n", n, m);
|
||||
|
||||
// PROFILE_SAMPLE(start);
|
||||
for i in m - n..m {
|
||||
/* notch filter at DC */
|
||||
let mut notch = nlp.sq[i] - nlp.mem_x;
|
||||
notch = (f64::from(notch) + COEFF * f64::from(nlp.mem_y)) as f32;
|
||||
nlp.mem_x = nlp.sq[i];
|
||||
nlp.mem_y = notch;
|
||||
nlp.sq[i] = notch + 1.0; /* With 0 input vectors to codec,
|
||||
kiss_fft() would take a long
|
||||
time to execute when running in
|
||||
real time. Problem was traced
|
||||
to kiss_fft function call in
|
||||
this function. Adding this small
|
||||
constant fixed problem. Not
|
||||
exactly sure why. */
|
||||
}
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG(tnotch, start, " square and notch");
|
||||
|
||||
for i in m - n..m {
|
||||
/* FIR filter vector */
|
||||
|
||||
for j in 0..NLP_NTAP as usize - 1 {
|
||||
nlp.mem_fir[j] = nlp.mem_fir[j + 1];
|
||||
}
|
||||
nlp.mem_fir[NLP_NTAP as usize - 1] = nlp.sq[i];
|
||||
|
||||
nlp.sq[i] = 0.0;
|
||||
for j in 0..NLP_NTAP as usize {
|
||||
nlp.sq[i] += nlp.mem_fir[j] * nlp_fir[j];
|
||||
}
|
||||
}
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG(filter, tnotch, " filter");
|
||||
|
||||
/* Decimate and DFT */
|
||||
|
||||
let mut Fw = [COMP::new(); PE_FFT_SIZE as usize];
|
||||
for i in 0..m / DEC as usize {
|
||||
Fw[i].r = nlp.sq[i * DEC as usize] * nlp.w[i];
|
||||
}
|
||||
// PROFILE_SAMPLE_AND_LOG(window, filter, " window");
|
||||
// #ifdef DUMP
|
||||
// dump_dec(Fw);
|
||||
// #endif
|
||||
|
||||
// FIXME: check if this can be converted to a real fft
|
||||
// since all imag inputs are 0
|
||||
super::codec2_fft_inplace(fft_cfg, &mut Fw);
|
||||
// PROFILE_SAMPLE_AND_LOG(fft, window, " fft");
|
||||
|
||||
for i in 0..PE_FFT_SIZE as usize {
|
||||
Fw[i].r = Fw[i].r * Fw[i].r + Fw[i].i * Fw[i].i;
|
||||
}
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG(magsq, fft, " mag sq");
|
||||
// #ifdef DUMP
|
||||
// dump_sq(m, nlp.sq);
|
||||
// dump_Fw(Fw);
|
||||
// #endif
|
||||
|
||||
/* todo: express everything in f0, as pitch in samples is dep on Fs */
|
||||
|
||||
let pmin = (SAMPLE_RATE as f32 * P_MIN_S).dsp_floor() as i32;
|
||||
let pmax = (SAMPLE_RATE as f32 * P_MAX_S).dsp_floor() as i32;
|
||||
|
||||
/* find global peak */
|
||||
|
||||
let mut gmax = 0.0;
|
||||
let mut gmax_bin = PE_FFT_SIZE * DEC / pmax;
|
||||
for i in (PE_FFT_SIZE * DEC / pmax) as usize..(PE_FFT_SIZE * DEC / pmin) as usize + 1 {
|
||||
if Fw[i].r > gmax {
|
||||
gmax = Fw[i].r;
|
||||
gmax_bin = i as i32;
|
||||
}
|
||||
}
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG(peakpick, magsq, " peak pick");
|
||||
|
||||
let best_f0 = post_process_sub_multiples(&Fw, pmin, pmax, gmax, gmax_bin, prev_f0);
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG(shiftmem, peakpick, " post process");
|
||||
|
||||
/* Shift samples in buffer to make room for new samples */
|
||||
|
||||
for i in 0..m - n {
|
||||
nlp.sq[i] = nlp.sq[i + n];
|
||||
}
|
||||
|
||||
/* return pitch period in samples and F0 estimate */
|
||||
|
||||
*pitch = nlp.Fs as f32 / best_f0;
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG2(shiftmem, " shift mem");
|
||||
|
||||
// PROFILE_SAMPLE_AND_LOG2(start, " nlp int");
|
||||
|
||||
*prev_f0 = best_f0;
|
||||
|
||||
best_f0
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,144 @@
|
||||
use lxst_codec2::{Codec, Error, Mode};
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
struct Meter;
|
||||
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
unsafe impl GlobalAlloc for Meter {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Relaxed);
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: Meter = Meter;
|
||||
|
||||
// One process/thread: unrelated parallel test allocations cannot contaminate
|
||||
// the count. Large states are allocated before measurement and initialised in place.
|
||||
fn main() {
|
||||
for mode in [Mode::Rate1600, Mode::Rate3200, Mode::Rate700C] {
|
||||
let mut duplex_storage = Box::<Codec>::new_uninit();
|
||||
let mut encoder_storage = Box::<Codec>::new_uninit();
|
||||
let mut decoder_storage = Box::<Codec>::new_uninit();
|
||||
let before = ALLOCATIONS.load(Relaxed);
|
||||
let duplex = Codec::initialise(&mut duplex_storage, mode);
|
||||
let encoder = Codec::initialise(&mut encoder_storage, mode);
|
||||
let decoder = Codec::initialise(&mut decoder_storage, mode);
|
||||
let samples = mode.samples();
|
||||
let bytes = mode.bytes();
|
||||
let mut input = [0_i16; 320];
|
||||
let mut expected = [0_i16; 320];
|
||||
let mut actual = [0_i16; 320];
|
||||
let mut encoded = [0_u8; 8];
|
||||
let mut same = [0_u8; 8];
|
||||
let mut rng = 71_u32;
|
||||
for frame in 0..1000 {
|
||||
for sample in &mut input[..samples] {
|
||||
rng = rng.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
*sample = match frame % 5 {
|
||||
0 => 0,
|
||||
1 => (rng >> 16) as i16,
|
||||
2 => {
|
||||
if rng & 1 == 0 {
|
||||
i16::MIN
|
||||
} else {
|
||||
i16::MAX
|
||||
}
|
||||
}
|
||||
_ => ((rng >> 16) as i16) / 4,
|
||||
};
|
||||
}
|
||||
// Rejected input cannot alter state or caller outputs.
|
||||
same.fill(0xA5);
|
||||
assert_eq!(
|
||||
duplex.encode(&input[..samples - 1], &mut same),
|
||||
Err(Error::PcmLength)
|
||||
);
|
||||
assert_eq!(same, [0xA5; 8]);
|
||||
assert_eq!(
|
||||
duplex.encode(&input[..samples], &mut same[..bytes - 1]),
|
||||
Err(Error::EncodedLength)
|
||||
);
|
||||
actual.fill(123);
|
||||
assert_eq!(
|
||||
duplex.decode(&encoded[..bytes - 1], &mut actual[..samples]),
|
||||
Err(Error::EncodedLength)
|
||||
);
|
||||
assert_eq!(
|
||||
duplex.decode(&encoded[..bytes], &mut actual[..samples - 1]),
|
||||
Err(Error::PcmLength)
|
||||
);
|
||||
assert!(actual.iter().all(|v| *v == 123));
|
||||
encoder
|
||||
.encode(&input[..samples], &mut encoded[..bytes])
|
||||
.unwrap();
|
||||
duplex
|
||||
.encode(&input[..samples], &mut same[..bytes])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
encoded[..bytes],
|
||||
same[..bytes],
|
||||
"receive activity changed encoder history"
|
||||
);
|
||||
assert!(same[bytes..].iter().all(|byte| *byte == 0xA5));
|
||||
if mode == Mode::Rate700C {
|
||||
assert_eq!(encoded[3] & 0x0f, 0, "700C native padding");
|
||||
}
|
||||
decoder
|
||||
.decode(&encoded[..bytes], &mut expected[..samples])
|
||||
.unwrap();
|
||||
duplex
|
||||
.decode(&encoded[..bytes], &mut actual[..samples])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
expected[..samples],
|
||||
actual[..samples],
|
||||
"another decoder changed random/history state"
|
||||
);
|
||||
if frame % 127 == 0 {
|
||||
duplex.reset(mode);
|
||||
encoder.reset(mode);
|
||||
decoder.reset(mode);
|
||||
}
|
||||
}
|
||||
// Every correctly-sized payload is valid codec data. Exercise decoder indices on
|
||||
// hostile but correctly-sized frames, including both extrema.
|
||||
for frame in 0..10000 {
|
||||
for byte in &mut encoded {
|
||||
rng = rng.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
*byte = match frame % 10 {
|
||||
0 => 0,
|
||||
1 => 255,
|
||||
_ => (rng >> 24) as u8,
|
||||
};
|
||||
}
|
||||
duplex
|
||||
.decode(&encoded[..bytes], &mut actual[..samples])
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
ALLOCATIONS.load(Relaxed),
|
||||
before,
|
||||
"initialisation/reset/stream allocated"
|
||||
);
|
||||
let other = match mode {
|
||||
Mode::Rate1600 => Mode::Rate3200,
|
||||
Mode::Rate3200 => Mode::Rate700C,
|
||||
Mode::Rate700C => Mode::Rate1600,
|
||||
};
|
||||
duplex.reset(other);
|
||||
assert_eq!(duplex.mode(), other);
|
||||
assert_eq!(ALLOCATIONS.load(Relaxed), before);
|
||||
println!(
|
||||
"{mode:?}: allocation-free construction/reset; isolated duplex histories; 1000 stream pairs; 10000 arbitrary decoder frames PASS"
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"codec fixed storage: {} bytes, alignment {}",
|
||||
size_of::<Codec>(),
|
||||
align_of::<Codec>()
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
name = "lxst-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
half.workspace = true
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
include!("shared/codec2.rs");
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,215 @@
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
struct Backend {
|
||||
mode: Codec2Mode,
|
||||
calls: Rc<Cell<usize>>,
|
||||
fail_at: Option<usize>,
|
||||
}
|
||||
|
||||
impl Codec2Backend for Backend {
|
||||
type Error = &'static str;
|
||||
|
||||
fn mode(&self) -> Codec2Mode {
|
||||
self.mode
|
||||
}
|
||||
|
||||
fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error> {
|
||||
let count = self.calls.get() + 1;
|
||||
self.calls.set(count);
|
||||
assert_eq!(
|
||||
pcm.len(),
|
||||
if self.mode == Codec2Mode::Mode3200 {
|
||||
160
|
||||
} else {
|
||||
320
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
encoded.len(),
|
||||
if self.mode == Codec2Mode::Mode700C {
|
||||
4
|
||||
} else {
|
||||
8
|
||||
}
|
||||
);
|
||||
if self.fail_at == Some(count) {
|
||||
return Err("injected codec failure");
|
||||
}
|
||||
encoded.fill(count as u8);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error> {
|
||||
let mut scratch = [0; 8];
|
||||
self.encode_native(pcm, &mut scratch[..encoded.len()])?;
|
||||
pcm.fill(i16::from(encoded[0]));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn codec(
|
||||
profile: Profile,
|
||||
fail_at: Option<usize>,
|
||||
) -> (Codec2PacketCodec<Backend>, Rc<Cell<usize>>) {
|
||||
let AudioCodec::Codec2(mode) = profile.audio_codec() else {
|
||||
panic!("test profile")
|
||||
};
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let backend = Backend {
|
||||
mode,
|
||||
calls: calls.clone(),
|
||||
fail_at,
|
||||
};
|
||||
(Codec2PacketCodec::new(profile, backend).unwrap(), calls)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_packets_preserve_native_frame_padding_and_output_tails() {
|
||||
for (profile, samples, bytes, count) in [
|
||||
(Profile::BandwidthUltraLow, 3200, 41, 10),
|
||||
(Profile::BandwidthVeryLow, 2560, 65, 8),
|
||||
(Profile::BandwidthLow, 1600, 81, 10),
|
||||
] {
|
||||
let (mut encoder, calls) = codec(profile, None);
|
||||
assert_eq!(encoder.profile(), profile);
|
||||
assert_eq!(encoder.sample_frames(), samples);
|
||||
assert_eq!(encoder.payload_bytes(), bytes);
|
||||
let pcm = vec![100; samples];
|
||||
let mut payload = [0xED; 96];
|
||||
assert_eq!(encoder.encode_into(&pcm, &mut payload).unwrap(), bytes);
|
||||
assert_eq!(calls.get(), count);
|
||||
assert_eq!(payload[0], encoder.mode().header());
|
||||
assert!(payload[bytes..].iter().all(|x| *x == 0xED));
|
||||
for (i, frame) in payload[1..bytes]
|
||||
.chunks_exact((bytes - 1) / count)
|
||||
.enumerate()
|
||||
{
|
||||
assert!(frame.iter().all(|x| usize::from(*x) == i + 1));
|
||||
}
|
||||
let (mut decoder, calls) = codec(profile, None);
|
||||
let mut decoded = vec![-123; samples + 8];
|
||||
assert_eq!(
|
||||
decoder
|
||||
.decode_into(&payload[..bytes], &mut decoded)
|
||||
.unwrap(),
|
||||
samples
|
||||
);
|
||||
assert_eq!(calls.get(), count);
|
||||
assert!(decoded[samples..].iter().all(|x| *x == -123));
|
||||
for (i, frame) in decoded[..samples].chunks_exact(samples / count).enumerate() {
|
||||
assert!(frame.iter().all(|x| *x == (i + 1) as i16));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_non_codec2_profiles_and_backend_mode_mismatch() {
|
||||
for profile in Profile::ORDER {
|
||||
let backend = Backend {
|
||||
mode: Codec2Mode::Mode1600,
|
||||
calls: Rc::new(Cell::new(0)),
|
||||
fail_at: None,
|
||||
};
|
||||
let result = Codec2PacketCodec::new(profile, backend);
|
||||
match profile.audio_codec() {
|
||||
AudioCodec::Opus(_) => assert!(
|
||||
matches!(result, Err(Codec2PacketError::NonCodec2Profile(p)) if p == profile)
|
||||
),
|
||||
AudioCodec::Codec2(Codec2Mode::Mode1600) => assert!(result.is_ok()),
|
||||
AudioCodec::Codec2(_) => assert!(matches!(
|
||||
result,
|
||||
Err(Codec2PacketError::BackendModeMismatch { .. })
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_malformed_lengths_headers_and_capacities_fail_before_backend_or_output_mutation() {
|
||||
for profile in [
|
||||
Profile::BandwidthUltraLow,
|
||||
Profile::BandwidthVeryLow,
|
||||
Profile::BandwidthLow,
|
||||
] {
|
||||
let (mut codec, calls) = codec(profile, None);
|
||||
let mut payload = vec![0; codec.payload_bytes() + 1];
|
||||
payload[0] = codec.mode().header();
|
||||
let mut output = vec![-123; codec.sample_frames()];
|
||||
for length in 0..=payload.len() {
|
||||
if length == codec.payload_bytes() {
|
||||
continue;
|
||||
}
|
||||
assert!(matches!(
|
||||
codec.decode_into(&payload[..length], &mut output),
|
||||
Err(Codec2PacketError::PayloadLength { .. })
|
||||
));
|
||||
}
|
||||
payload.pop();
|
||||
for header in 0..=255 {
|
||||
if header == codec.mode().header() {
|
||||
continue;
|
||||
}
|
||||
payload[0] = header;
|
||||
assert!(matches!(
|
||||
codec.decode_into(&payload, &mut output),
|
||||
Err(Codec2PacketError::ModeHeader { .. })
|
||||
));
|
||||
}
|
||||
payload[0] = codec.mode().header();
|
||||
for capacity in [0, 1, codec.sample_frames() - 1] {
|
||||
assert!(matches!(
|
||||
codec.decode_into(&payload, &mut output[..capacity]),
|
||||
Err(Codec2PacketError::OutputCapacity { .. })
|
||||
));
|
||||
}
|
||||
assert!(output.iter().all(|x| *x == -123));
|
||||
payload.fill(0xEA);
|
||||
for samples in [0, 1, codec.sample_frames() - 1, codec.sample_frames() + 1] {
|
||||
assert!(matches!(
|
||||
codec.encode_into(&vec![0; samples], &mut payload),
|
||||
Err(Codec2PacketError::SampleCount { .. })
|
||||
));
|
||||
}
|
||||
for capacity in [0, 1, codec.payload_bytes() - 1] {
|
||||
assert!(matches!(
|
||||
codec.encode_into(&output, &mut payload[..capacity]),
|
||||
Err(Codec2PacketError::OutputCapacity { .. })
|
||||
));
|
||||
}
|
||||
assert!(payload.iter().all(|x| *x == 0xEA));
|
||||
assert_eq!(calls.get(), 0);
|
||||
// A rejected input must not poison a valid stream.
|
||||
assert!(codec.encode_into(&output, &mut payload).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_failure_latches_both_directions_until_replacement() {
|
||||
for encode_first in [true, false] {
|
||||
let (mut codec, calls) = codec(Profile::BandwidthVeryLow, Some(3));
|
||||
let mut payload = [0; 65];
|
||||
payload[0] = Codec2Mode::Mode1600.header();
|
||||
let mut pcm = [0; 2560];
|
||||
let result = if encode_first {
|
||||
codec.encode_into(&pcm, &mut payload)
|
||||
} else {
|
||||
codec.decode_into(&payload, &mut pcm)
|
||||
};
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(Codec2PacketError::Backend("injected codec failure"))
|
||||
);
|
||||
assert_eq!(calls.get(), 3);
|
||||
assert_eq!(
|
||||
codec.encode_into(&pcm, &mut payload),
|
||||
Err(Codec2PacketError::Failed)
|
||||
);
|
||||
assert_eq!(
|
||||
codec.decode_into(&payload, &mut pcm),
|
||||
Err(Codec2PacketError::Failed)
|
||||
);
|
||||
assert_eq!(calls.get(), 3);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
//! Core LXST wire types.
|
||||
//!
|
||||
//! This crate owns the byte-level contract with Python LXST. It deliberately
|
||||
//! avoids audio and Reticulum runtime dependencies so packet/profile parity can
|
||||
//! be tested in isolation.
|
||||
//! This crate provides LXST packet/profile types, call transitions and audio
|
||||
//! codec helpers. It has no Reticulum runtime dependency and does not open
|
||||
//! audio devices; callers supply and consume PCM frames.
|
||||
|
||||
#[path = "shared/actions.rs"]
|
||||
mod actions;
|
||||
#[path = "shared/telephony.rs"]
|
||||
mod call_state;
|
||||
mod codec2;
|
||||
mod opus;
|
||||
#[path = "shared/profile.rs"]
|
||||
mod profile;
|
||||
mod raw;
|
||||
mod stream;
|
||||
@@ -12,8 +18,13 @@ mod synthetic;
|
||||
mod telephony;
|
||||
mod wire;
|
||||
|
||||
pub use opus::{OpusCodecError, OpusDecoderState, OpusEncoderState};
|
||||
pub use profile::{AudioCodec, OpusApplication, OpusProfile, Profile, SignallingStatus};
|
||||
pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError};
|
||||
pub use opus::{
|
||||
OPUS_ENCODED_FRAME_MAX_BYTES, OPUS_ENCODED_PACKET_MAX_BYTES, OPUS_MONO_DECODE_SAMPLE_RATE_HZ,
|
||||
OpusCodecError, OpusDecoderState, OpusEncoderState, OpusMonoDecoder, OpusPacketDecoder,
|
||||
opus_packet_duration_samples_48k,
|
||||
};
|
||||
pub use profile::{AudioCodec, CallMode, OpusApplication, OpusProfile, Profile, SignallingStatus};
|
||||
pub use raw::RawAudioFrame;
|
||||
pub use stream::{
|
||||
DropPolicy, FramePacketizer, FrameStreamEvent, FrameStreamState, JitterBuffer, JitterPush,
|
||||
|
||||
+782
-92
@@ -1,8 +1,24 @@
|
||||
use opus_rs::{Application, OpusDecoder, OpusEncoder};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
use opus_rs::{Application, Bandwidth, OpusDecoder, OpusEncoder};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{AudioCodec, CodecKind, Frame, OpusApplication, OpusProfile, Profile, RawAudioFrame};
|
||||
|
||||
/// The fixed output clock used by the interoperable Opus packet decoder.
|
||||
pub const OPUS_MONO_DECODE_SAMPLE_RATE_HZ: u32 = 48_000;
|
||||
|
||||
/// The maximum encoded size of one frame contained in an Opus packet.
|
||||
pub const OPUS_ENCODED_FRAME_MAX_BYTES: usize = 1_275;
|
||||
|
||||
/// The maximum encoded Opus packet accepted by the interoperable decoder.
|
||||
///
|
||||
/// This implementation uses the 61,440-byte processing limit recommended by
|
||||
/// [RFC 7845, section 6](https://www.rfc-editor.org/rfc/rfc7845.html#section-6).
|
||||
/// Valid padded Opus packets can be larger. This is separate from the
|
||||
/// 1,275-byte per-frame limit and the decoded PCM allocation.
|
||||
pub const OPUS_ENCODED_PACKET_MAX_BYTES: usize = 61_440;
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum OpusCodecError {
|
||||
#[error("profile {0:?} does not use Opus")]
|
||||
@@ -26,6 +42,20 @@ pub enum OpusCodecError {
|
||||
UnsupportedSubpacketLayout,
|
||||
#[error("malformed Opus packet: {0}")]
|
||||
MalformedPacket(&'static str),
|
||||
#[error("encoded Opus packet length {actual} exceeds the {maximum}-byte ceiling")]
|
||||
EncodedPacketTooLarge { actual: usize, maximum: usize },
|
||||
#[error("encoded Opus frame {index} length {actual} exceeds the {maximum}-byte ceiling")]
|
||||
EncodedFrameTooLarge {
|
||||
index: usize,
|
||||
actual: usize,
|
||||
maximum: usize,
|
||||
},
|
||||
#[error("unsupported Opus packet duration: {samples_48k} samples at 48 kHz")]
|
||||
UnsupportedPacketDuration { samples_48k: usize },
|
||||
#[error(
|
||||
"Opus decoder returned {actual} sample frames for a packet frame containing {expected}"
|
||||
)]
|
||||
DecodedPacketDurationMismatch { expected: usize, actual: usize },
|
||||
#[error("Opus codec error: {0}")]
|
||||
Codec(String),
|
||||
#[error("LXST wire error: {0}")]
|
||||
@@ -38,8 +68,6 @@ pub struct OpusEncoderState {
|
||||
sample_frames: usize,
|
||||
subframe_count: usize,
|
||||
subframe_sample_frames: usize,
|
||||
encode_sample_frames: usize,
|
||||
encode_subframe_sample_frames: usize,
|
||||
max_payload_bytes: usize,
|
||||
encoder: OpusEncoder,
|
||||
}
|
||||
@@ -52,35 +80,28 @@ impl OpusEncoderState {
|
||||
};
|
||||
let channels = opus_profile.channels();
|
||||
let sample_rate = opus_profile.sample_rate();
|
||||
let encode_sample_rate = encode_sample_rate(opus_profile);
|
||||
let sample_frames = profile.sample_frames_per_packet();
|
||||
let encode_sample_frames =
|
||||
scale_sample_frames(sample_frames, sample_rate, encode_sample_rate)?;
|
||||
let packet_layout = PacketLayout::new(encode_sample_rate, encode_sample_frames)?;
|
||||
let subframe_sample_frames = sample_frames
|
||||
.checked_div(packet_layout.subframe_count)
|
||||
.filter(|frames| frames * packet_layout.subframe_count == sample_frames)
|
||||
.ok_or(OpusCodecError::UnsupportedFrameDuration {
|
||||
sample_rate_hz: sample_rate,
|
||||
sample_frames,
|
||||
})?;
|
||||
let packet_layout = PacketLayout::new(sample_rate, sample_frames)?;
|
||||
let mut encoder = OpusEncoder::new(
|
||||
encode_sample_rate as i32,
|
||||
sample_rate as i32,
|
||||
usize::from(channels),
|
||||
opus_application(opus_profile.application()),
|
||||
)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
encoder.bitrate_bps = opus_profile.bitrate_ceiling() as i32;
|
||||
encoder.use_cbr = false;
|
||||
if matches!(opus_profile, OpusProfile::VoiceMedium) {
|
||||
// At 8 kbps libopus builds disagree (1.5 wideband, 1.6 narrowband); wideband is
|
||||
// what this profile has always sent.
|
||||
encoder.set_bandwidth(Bandwidth::Wideband);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
profile,
|
||||
channels,
|
||||
sample_frames,
|
||||
subframe_count: packet_layout.subframe_count,
|
||||
subframe_sample_frames,
|
||||
encode_sample_frames,
|
||||
encode_subframe_sample_frames: packet_layout.subframe_sample_frames,
|
||||
subframe_sample_frames: packet_layout.subframe_sample_frames,
|
||||
max_payload_bytes: opus_profile.max_bytes_per_frame_ms(profile.frame_time_ms()),
|
||||
encoder,
|
||||
})
|
||||
@@ -116,22 +137,10 @@ impl OpusEncoderState {
|
||||
return self.encode_multi_subframe_packet(frame);
|
||||
}
|
||||
|
||||
let resampled;
|
||||
let input = if self.encode_sample_frames == self.sample_frames {
|
||||
&frame.samples
|
||||
} else {
|
||||
resampled = resample_interleaved_linear(
|
||||
&frame.samples,
|
||||
self.sample_frames,
|
||||
self.encode_sample_frames,
|
||||
usize::from(self.channels),
|
||||
);
|
||||
&resampled
|
||||
};
|
||||
let mut encoded = vec![0u8; self.max_payload_bytes];
|
||||
let written = self
|
||||
.encoder
|
||||
.encode(input, self.encode_sample_frames, &mut encoded)
|
||||
.encode(&frame.samples, self.sample_frames, &mut encoded)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
encoded.truncate(written);
|
||||
Ok(Frame::new(CodecKind::Opus, encoded))
|
||||
@@ -148,22 +157,14 @@ impl OpusEncoderState {
|
||||
for (subframe_index, payload_budget) in budgets.into_iter().enumerate() {
|
||||
let start = subframe_index * self.subframe_sample_frames * channels;
|
||||
let end = start + self.subframe_sample_frames * channels;
|
||||
let resampled;
|
||||
let input = if self.encode_subframe_sample_frames == self.subframe_sample_frames {
|
||||
&frame.samples[start..end]
|
||||
} else {
|
||||
resampled = resample_interleaved_linear(
|
||||
&frame.samples[start..end],
|
||||
self.subframe_sample_frames,
|
||||
self.encode_subframe_sample_frames,
|
||||
channels,
|
||||
);
|
||||
&resampled
|
||||
};
|
||||
let mut encoded = vec![0u8; payload_budget + 1];
|
||||
let written = self
|
||||
.encoder
|
||||
.encode(input, self.encode_subframe_sample_frames, &mut encoded)
|
||||
.encode(
|
||||
&frame.samples[start..end],
|
||||
self.subframe_sample_frames,
|
||||
&mut encoded,
|
||||
)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
encoded.truncate(written);
|
||||
if encoded.first().is_none_or(|toc| toc & 0x03 != 0) {
|
||||
@@ -219,6 +220,7 @@ impl OpusEncoderState {
|
||||
|
||||
pub struct OpusDecoderState {
|
||||
profile: Profile,
|
||||
sample_rate_hz: u32,
|
||||
channels: u8,
|
||||
sample_frames: usize,
|
||||
subframe_count: usize,
|
||||
@@ -241,6 +243,7 @@ impl OpusDecoderState {
|
||||
|
||||
Ok(Self {
|
||||
profile,
|
||||
sample_rate_hz: sample_rate,
|
||||
channels,
|
||||
sample_frames,
|
||||
subframe_count: packet_layout.subframe_count,
|
||||
@@ -274,10 +277,14 @@ impl OpusDecoderState {
|
||||
|
||||
fn decode_direct_packet(&mut self, frame: &Frame) -> Result<RawAudioFrame, OpusCodecError> {
|
||||
let mut samples = vec![0.0f32; self.sample_frames * usize::from(self.channels)];
|
||||
let decoded = self
|
||||
.decoder
|
||||
.decode(&frame.payload, self.sample_frames, &mut samples)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
let decoded = decode_guarded(
|
||||
&mut self.decoder,
|
||||
self.sample_rate_hz,
|
||||
usize::from(self.channels),
|
||||
&frame.payload,
|
||||
self.sample_frames,
|
||||
&mut samples,
|
||||
)?;
|
||||
samples.truncate(decoded * usize::from(self.channels));
|
||||
Ok(RawAudioFrame::new(self.channels, samples)?)
|
||||
}
|
||||
@@ -297,19 +304,394 @@ impl OpusDecoderState {
|
||||
let mut subpacket = Vec::with_capacity(subpayload.len() + 1);
|
||||
subpacket.push(toc);
|
||||
subpacket.extend_from_slice(subpayload);
|
||||
self.decoder
|
||||
.decode(
|
||||
&subpacket,
|
||||
self.subframe_sample_frames,
|
||||
&mut samples[start..end],
|
||||
)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
decode_guarded(
|
||||
&mut self.decoder,
|
||||
self.sample_rate_hz,
|
||||
channels,
|
||||
&subpacket,
|
||||
self.subframe_sample_frames,
|
||||
&mut samples[start..end],
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(RawAudioFrame::new(self.channels, samples)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// A stateful decoder for interoperable mono Opus packets at the Opus 48 kHz clock.
|
||||
///
|
||||
/// Unlike [`OpusDecoderState`], this decoder is not tied to an LXST call profile. It accepts
|
||||
/// every structurally legal packet duration from 2.5 through 120 milliseconds and preserves
|
||||
/// decoder state across calls. The returned [`RawAudioFrame`] is always mono at 48 kHz.
|
||||
pub struct OpusMonoDecoder {
|
||||
decoder: OpusDecoder,
|
||||
}
|
||||
|
||||
impl OpusMonoDecoder {
|
||||
pub fn new() -> Result<Self, OpusCodecError> {
|
||||
let decoder = OpusDecoder::new(OPUS_MONO_DECODE_SAMPLE_RATE_HZ as i32, 1)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
Ok(Self { decoder })
|
||||
}
|
||||
|
||||
pub const fn sample_rate_hz(&self) -> u32 {
|
||||
OPUS_MONO_DECODE_SAMPLE_RATE_HZ
|
||||
}
|
||||
|
||||
pub const fn channels(&self) -> u8 {
|
||||
1
|
||||
}
|
||||
|
||||
/// Decode one complete mono Opus packet to PCM at 48 kHz.
|
||||
/// Stereo packets are rejected, as are packets exceeding
|
||||
/// [`OPUS_ENCODED_PACKET_MAX_BYTES`] or the per-frame size/duration limits.
|
||||
pub fn decode_packet(&mut self, packet: &[u8]) -> Result<RawAudioFrame, OpusCodecError> {
|
||||
let inspected = inspect_opus_packet(packet)?;
|
||||
if inspected.channels != 1 {
|
||||
return Err(OpusCodecError::ChannelMismatch {
|
||||
expected: 1,
|
||||
actual: inspected.channels,
|
||||
});
|
||||
}
|
||||
|
||||
let mut samples = Vec::with_capacity(inspected.duration_samples_48k);
|
||||
let direct_toc = inspected.toc & !0x03;
|
||||
for payload in inspected.frames {
|
||||
let mut direct_packet = Vec::with_capacity(payload.len() + 1);
|
||||
direct_packet.push(direct_toc);
|
||||
direct_packet.extend_from_slice(payload);
|
||||
|
||||
let output_start = samples.len();
|
||||
samples.resize(output_start + inspected.samples_per_frame_48k, 0.0);
|
||||
let decoded = decode_guarded(
|
||||
&mut self.decoder,
|
||||
OPUS_MONO_DECODE_SAMPLE_RATE_HZ,
|
||||
1,
|
||||
&direct_packet,
|
||||
inspected.samples_per_frame_48k,
|
||||
&mut samples[output_start..],
|
||||
)?;
|
||||
if decoded != inspected.samples_per_frame_48k {
|
||||
return Err(OpusCodecError::DecodedPacketDurationMismatch {
|
||||
expected: inspected.samples_per_frame_48k,
|
||||
actual: decoded,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
debug_assert_eq!(samples.len(), inspected.duration_samples_48k);
|
||||
Ok(RawAudioFrame::new(1, samples)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes any legal Opus packet (2.5 to 120 ms, mono or stereo) to a fixed sample rate
|
||||
/// and channel count, as Python's libopus decoder does whatever the local profile is.
|
||||
pub struct OpusPacketDecoder {
|
||||
sample_rate_hz: u32,
|
||||
channels: u8,
|
||||
decoders: [Option<OpusDecoder>; 2],
|
||||
}
|
||||
|
||||
impl OpusPacketDecoder {
|
||||
pub fn new(sample_rate_hz: u32, channels: u8) -> Result<Self, OpusCodecError> {
|
||||
if !matches!(sample_rate_hz, 8_000 | 12_000 | 16_000 | 24_000 | 48_000) {
|
||||
return Err(OpusCodecError::UnsupportedFrameDuration {
|
||||
sample_rate_hz,
|
||||
sample_frames: 0,
|
||||
});
|
||||
}
|
||||
if !matches!(channels, 1 | 2) {
|
||||
return Err(OpusCodecError::ChannelMismatch {
|
||||
expected: 2,
|
||||
actual: channels,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
sample_rate_hz,
|
||||
channels,
|
||||
decoders: [None, None],
|
||||
})
|
||||
}
|
||||
|
||||
pub const fn sample_rate_hz(&self) -> u32 {
|
||||
self.sample_rate_hz
|
||||
}
|
||||
|
||||
pub const fn channels(&self) -> u8 {
|
||||
self.channels
|
||||
}
|
||||
|
||||
pub fn decode_packet(&mut self, packet: &[u8]) -> Result<RawAudioFrame, OpusCodecError> {
|
||||
let inspected = inspect_opus_packet(packet)?;
|
||||
let packet_channels = usize::from(inspected.channels);
|
||||
let samples_per_frame =
|
||||
inspected.samples_per_frame_48k * self.sample_rate_hz as usize / 48_000;
|
||||
let slot = &mut self.decoders[packet_channels - 1];
|
||||
if slot.is_none() {
|
||||
*slot = Some(
|
||||
OpusDecoder::new(self.sample_rate_hz as i32, packet_channels)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?,
|
||||
);
|
||||
}
|
||||
let decoder = slot.as_mut().expect("decoder exists after creation");
|
||||
|
||||
let mut samples =
|
||||
Vec::with_capacity(samples_per_frame * inspected.frames.len() * packet_channels);
|
||||
let direct_toc = inspected.toc & !0x03;
|
||||
for payload in inspected.frames {
|
||||
let mut direct_packet = Vec::with_capacity(payload.len() + 1);
|
||||
direct_packet.push(direct_toc);
|
||||
direct_packet.extend_from_slice(payload);
|
||||
|
||||
let output_start = samples.len();
|
||||
samples.resize(output_start + samples_per_frame * packet_channels, 0.0);
|
||||
let decoded = decode_guarded(
|
||||
decoder,
|
||||
self.sample_rate_hz,
|
||||
packet_channels,
|
||||
&direct_packet,
|
||||
samples_per_frame,
|
||||
&mut samples[output_start..],
|
||||
)?;
|
||||
if decoded != samples_per_frame {
|
||||
return Err(OpusCodecError::DecodedPacketDurationMismatch {
|
||||
expected: samples_per_frame,
|
||||
actual: decoded,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let frame = RawAudioFrame::new(inspected.channels, samples)?;
|
||||
Ok(frame.with_channels(self.channels)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Peer packets reach opus-rs, which has panicked on hostile input (0.1.29: negative SILK LTP
|
||||
/// start index, fixed in 0.1.42). A panicked decoder's state is undefined, so it is replaced
|
||||
/// and the packet rejected. Remove once the pinned opus-rs passes a decoder fuzz campaign.
|
||||
fn decode_guarded(
|
||||
decoder: &mut OpusDecoder,
|
||||
sample_rate_hz: u32,
|
||||
channels: usize,
|
||||
packet: &[u8],
|
||||
frame_size: usize,
|
||||
output: &mut [f32],
|
||||
) -> Result<usize, OpusCodecError> {
|
||||
match catch_unwind(AssertUnwindSafe(|| {
|
||||
decoder.decode(packet, frame_size, output)
|
||||
})) {
|
||||
Ok(result) => result.map_err(|err| OpusCodecError::Codec(err.to_string())),
|
||||
Err(_) => {
|
||||
*decoder = OpusDecoder::new(sample_rate_hz as i32, channels)
|
||||
.map_err(|err| OpusCodecError::Codec(err.to_string()))?;
|
||||
Err(OpusCodecError::MalformedPacket(
|
||||
"Opus decoder rejected the packet",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a supported packet's total duration in samples at the Opus 48 kHz clock.
|
||||
///
|
||||
/// The packet is structurally inspected using the framing rules from RFC 6716. Every legal
|
||||
/// duration from 2.5 through 120 milliseconds is accepted in 2.5 millisecond increments.
|
||||
pub fn opus_packet_duration_samples_48k(packet: &[u8]) -> Result<usize, OpusCodecError> {
|
||||
Ok(inspect_opus_packet(packet)?.duration_samples_48k)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InspectedOpusPacket<'a> {
|
||||
toc: u8,
|
||||
channels: u8,
|
||||
samples_per_frame_48k: usize,
|
||||
duration_samples_48k: usize,
|
||||
frames: Vec<&'a [u8]>,
|
||||
}
|
||||
|
||||
fn inspect_opus_packet(packet: &[u8]) -> Result<InspectedOpusPacket<'_>, OpusCodecError> {
|
||||
if packet.is_empty() {
|
||||
return Err(OpusCodecError::MalformedPacket("packet is empty"));
|
||||
}
|
||||
if packet.len() > OPUS_ENCODED_PACKET_MAX_BYTES {
|
||||
return Err(OpusCodecError::EncodedPacketTooLarge {
|
||||
actual: packet.len(),
|
||||
maximum: OPUS_ENCODED_PACKET_MAX_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
let toc = packet[0];
|
||||
let samples_per_frame_48k = opus_samples_per_frame_48k(toc);
|
||||
let frames = parse_opus_packet_frames(packet)?;
|
||||
for (index, frame) in frames.iter().enumerate() {
|
||||
if frame.len() > OPUS_ENCODED_FRAME_MAX_BYTES {
|
||||
return Err(OpusCodecError::EncodedFrameTooLarge {
|
||||
index,
|
||||
actual: frame.len(),
|
||||
maximum: OPUS_ENCODED_FRAME_MAX_BYTES,
|
||||
});
|
||||
}
|
||||
}
|
||||
let duration_samples_48k = samples_per_frame_48k
|
||||
.checked_mul(frames.len())
|
||||
.ok_or(OpusCodecError::MalformedPacket("packet duration overflows"))?;
|
||||
if duration_samples_48k > 5_760 {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"packet duration exceeds 120 milliseconds",
|
||||
));
|
||||
}
|
||||
if duration_samples_48k == 0 || !duration_samples_48k.is_multiple_of(120) {
|
||||
return Err(OpusCodecError::UnsupportedPacketDuration {
|
||||
samples_48k: duration_samples_48k,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(InspectedOpusPacket {
|
||||
toc,
|
||||
channels: if toc & 0x04 == 0 { 1 } else { 2 },
|
||||
samples_per_frame_48k,
|
||||
duration_samples_48k,
|
||||
frames,
|
||||
})
|
||||
}
|
||||
|
||||
// Straight from libopus opus_packet_get_samples_per_frame() for the fixed 48 kHz clock.
|
||||
fn opus_samples_per_frame_48k(toc: u8) -> usize {
|
||||
if toc & 0x80 != 0 {
|
||||
let config = usize::from((toc >> 3) & 0x03);
|
||||
((OPUS_MONO_DECODE_SAMPLE_RATE_HZ as usize) << config) / 400
|
||||
} else if toc & 0x60 == 0x60 {
|
||||
if toc & 0x08 != 0 { 960 } else { 480 }
|
||||
} else {
|
||||
let config = usize::from((toc >> 3) & 0x03);
|
||||
if config == 3 {
|
||||
2_880
|
||||
} else {
|
||||
((OPUS_MONO_DECODE_SAMPLE_RATE_HZ as usize) << config) / 100
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_opus_packet_frames(packet: &[u8]) -> Result<Vec<&[u8]>, OpusCodecError> {
|
||||
let toc = packet[0];
|
||||
let body = &packet[1..];
|
||||
match toc & 0x03 {
|
||||
0 => Ok(vec![body]),
|
||||
1 => {
|
||||
if !body.len().is_multiple_of(2) {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 1 CBR payload has odd length",
|
||||
));
|
||||
}
|
||||
let frame_len = body.len() / 2;
|
||||
Ok(vec![&body[..frame_len], &body[frame_len..]])
|
||||
}
|
||||
2 => {
|
||||
let (first_len, length_bytes) = read_subframe_payload_len(body)?;
|
||||
let payload = &body[length_bytes..];
|
||||
if first_len > payload.len() {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 2 first frame exceeds packet payload",
|
||||
));
|
||||
}
|
||||
Ok(vec![&payload[..first_len], &payload[first_len..]])
|
||||
}
|
||||
3 => parse_code3_packet_frames(packet),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_code3_packet_frames(packet: &[u8]) -> Result<Vec<&[u8]>, OpusCodecError> {
|
||||
let count_byte = *packet.get(1).ok_or(OpusCodecError::MalformedPacket(
|
||||
"code 3 packet is too short",
|
||||
))?;
|
||||
let frame_count = usize::from(count_byte & 0x3F);
|
||||
if frame_count == 0 {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 3 frame count is zero",
|
||||
));
|
||||
}
|
||||
if frame_count > 48 {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 3 frame count exceeds 48",
|
||||
));
|
||||
}
|
||||
|
||||
let mut cursor = 2usize;
|
||||
let mut payload_end = packet.len();
|
||||
if count_byte & 0x40 != 0 {
|
||||
let mut padding = 0usize;
|
||||
loop {
|
||||
let byte = usize::from(*packet.get(cursor).ok_or(OpusCodecError::MalformedPacket(
|
||||
"code 3 padding exceeds packet",
|
||||
))?);
|
||||
cursor += 1;
|
||||
padding = padding
|
||||
.checked_add(if byte == 255 { 254 } else { byte })
|
||||
.ok_or(OpusCodecError::MalformedPacket(
|
||||
"code 3 padding length overflows",
|
||||
))?;
|
||||
if byte != 255 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
payload_end = packet
|
||||
.len()
|
||||
.checked_sub(padding)
|
||||
.ok_or(OpusCodecError::MalformedPacket(
|
||||
"code 3 padding exceeds packet",
|
||||
))?;
|
||||
if cursor > payload_end {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 3 padding exceeds payload",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if count_byte & 0x80 == 0 {
|
||||
let payload = &packet[cursor..payload_end];
|
||||
if !payload.len().is_multiple_of(frame_count) {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 3 CBR payload is not evenly divisible",
|
||||
));
|
||||
}
|
||||
let frame_len = payload.len() / frame_count;
|
||||
return Ok((0..frame_count)
|
||||
.map(|index| {
|
||||
let start = index * frame_len;
|
||||
&payload[start..start + frame_len]
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
|
||||
let mut lengths = Vec::with_capacity(frame_count);
|
||||
for _ in 0..frame_count - 1 {
|
||||
let (frame_len, length_bytes) = read_subframe_payload_len(&packet[cursor..payload_end])?;
|
||||
cursor += length_bytes;
|
||||
lengths.push(frame_len);
|
||||
}
|
||||
let declared = lengths.iter().sum::<usize>();
|
||||
let remaining = payload_end
|
||||
.checked_sub(cursor)
|
||||
.ok_or(OpusCodecError::MalformedPacket(
|
||||
"code 3 payload cursor exceeds packet",
|
||||
))?;
|
||||
if declared > remaining {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"code 3 declared frame lengths exceed packet payload",
|
||||
));
|
||||
}
|
||||
lengths.push(remaining - declared);
|
||||
|
||||
let mut frames = Vec::with_capacity(frame_count);
|
||||
let mut payload_cursor = cursor;
|
||||
for frame_len in lengths {
|
||||
let next = payload_cursor + frame_len;
|
||||
frames.push(&packet[payload_cursor..next]);
|
||||
payload_cursor = next;
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct PacketLayout {
|
||||
subframe_count: usize,
|
||||
@@ -328,7 +710,7 @@ impl PacketLayout {
|
||||
let subframe_sample_frames = (sample_rate_hz as usize) / 50;
|
||||
if sample_frames != 0
|
||||
&& subframe_sample_frames != 0
|
||||
&& sample_frames % subframe_sample_frames == 0
|
||||
&& sample_frames.is_multiple_of(subframe_sample_frames)
|
||||
&& supports_direct_frame(sample_rate_hz, subframe_sample_frames)
|
||||
{
|
||||
return Ok(Self {
|
||||
@@ -351,44 +733,11 @@ fn opus_application(application: OpusApplication) -> Application {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_sample_rate(profile: OpusProfile) -> u32 {
|
||||
match profile {
|
||||
// Python LXST uses libopus with an output byte ceiling but no fixed
|
||||
// bitrate or bandwidth CTLs. At Medium's 8 kbps ceiling, libopus is
|
||||
// free to pick lower voice bandwidth; opus-rs otherwise forces
|
||||
// superwideband/hybrid from the 24 kHz API rate, which is poor for
|
||||
// speech at this budget.
|
||||
OpusProfile::VoiceMedium => 16_000,
|
||||
_ => profile.sample_rate(),
|
||||
}
|
||||
}
|
||||
|
||||
fn scale_sample_frames(
|
||||
sample_frames: usize,
|
||||
source_sample_rate: u32,
|
||||
encode_sample_rate: u32,
|
||||
) -> Result<usize, OpusCodecError> {
|
||||
let numerator = sample_frames
|
||||
.checked_mul(encode_sample_rate as usize)
|
||||
.ok_or(OpusCodecError::UnsupportedFrameDuration {
|
||||
sample_rate_hz: encode_sample_rate,
|
||||
sample_frames,
|
||||
})?;
|
||||
let denominator = source_sample_rate as usize;
|
||||
if numerator % denominator != 0 {
|
||||
return Err(OpusCodecError::UnsupportedFrameDuration {
|
||||
sample_rate_hz: encode_sample_rate,
|
||||
sample_frames,
|
||||
});
|
||||
}
|
||||
Ok(numerator / denominator)
|
||||
}
|
||||
|
||||
fn supports_direct_frame(sample_rate_hz: u32, sample_frames: usize) -> bool {
|
||||
sample_frames != 0 && (sample_rate_hz as usize) % sample_frames == 0
|
||||
sample_frames != 0 && (sample_rate_hz as usize).is_multiple_of(sample_frames)
|
||||
}
|
||||
|
||||
fn resample_interleaved_linear(
|
||||
pub(crate) fn resample_interleaved_linear(
|
||||
input: &[f32],
|
||||
input_frames: usize,
|
||||
output_frames: usize,
|
||||
@@ -525,7 +874,7 @@ fn parse_code3_subframe_payloads(
|
||||
Ok(payloads)
|
||||
} else {
|
||||
let compressed = &packet[cursor..payload_end];
|
||||
if compressed.len() % frame_count != 0 {
|
||||
if !compressed.len().is_multiple_of(frame_count) {
|
||||
return Err(OpusCodecError::MalformedPacket(
|
||||
"CBR code 3 payload is not evenly divisible",
|
||||
));
|
||||
@@ -561,6 +910,12 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::SyntheticSourceKind;
|
||||
|
||||
#[test]
|
||||
fn upstream_opus_state_remains_heap_backed() {
|
||||
assert!(std::mem::size_of::<OpusEncoder>() < 4_096);
|
||||
assert!(std::mem::size_of::<OpusDecoder>() < 4_096);
|
||||
}
|
||||
|
||||
fn source_for(profile: Profile) -> crate::SyntheticSource {
|
||||
crate::SyntheticSource::new(
|
||||
profile.channels(),
|
||||
@@ -574,6 +929,81 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn encoded_mono_packet(sample_frames: usize, bitrate_bps: i32) -> Vec<u8> {
|
||||
let samples = (0..sample_frames)
|
||||
.map(|index| {
|
||||
let phase = std::f32::consts::TAU * 440.0 * index as f32
|
||||
/ OPUS_MONO_DECODE_SAMPLE_RATE_HZ as f32;
|
||||
phase.sin() * 0.2
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut encoder = OpusEncoder::new(
|
||||
OPUS_MONO_DECODE_SAMPLE_RATE_HZ as i32,
|
||||
1,
|
||||
Application::RestrictedLowDelay,
|
||||
)
|
||||
.unwrap();
|
||||
encoder.bitrate_bps = bitrate_bps;
|
||||
encoder.use_cbr = true;
|
||||
let mut packet = vec![0u8; OPUS_ENCODED_FRAME_MAX_BYTES + 1];
|
||||
let written = encoder
|
||||
.encode(&samples, sample_frames, &mut packet)
|
||||
.unwrap();
|
||||
packet.truncate(written);
|
||||
assert_eq!(packet[0] & 0x03, 0);
|
||||
assert_eq!(opus_samples_per_frame_48k(packet[0]), sample_frames);
|
||||
packet
|
||||
}
|
||||
|
||||
fn encoded_twenty_ms_mono_packet() -> Vec<u8> {
|
||||
encoded_mono_packet(960, 16_000)
|
||||
}
|
||||
|
||||
fn repacketize_cbr(packet: &[u8], frame_count: usize) -> Vec<u8> {
|
||||
assert!((1..=48).contains(&frame_count));
|
||||
let toc = packet[0] & !0x03;
|
||||
let payload = &packet[1..];
|
||||
let mut combined = Vec::new();
|
||||
match frame_count {
|
||||
1 => combined.push(toc),
|
||||
2 => combined.push(toc | 0x01),
|
||||
_ => {
|
||||
combined.push(toc | 0x03);
|
||||
combined.push(frame_count as u8);
|
||||
}
|
||||
}
|
||||
for _ in 0..frame_count {
|
||||
combined.extend_from_slice(payload);
|
||||
}
|
||||
combined
|
||||
}
|
||||
|
||||
fn repacketize_vbr(packet: &[u8], frame_count: usize, padding: usize) -> Vec<u8> {
|
||||
assert!((2..=48).contains(&frame_count));
|
||||
assert!(padding < 255);
|
||||
let toc = packet[0] & !0x03;
|
||||
let payload = &packet[1..];
|
||||
let mut combined = Vec::new();
|
||||
if frame_count == 2 && padding == 0 {
|
||||
combined.push(toc | 0x02);
|
||||
push_subframe_payload_len(&mut combined, payload.len()).unwrap();
|
||||
} else {
|
||||
combined.push(toc | 0x03);
|
||||
combined.push(0x80 | (frame_count as u8) | if padding == 0 { 0 } else { 0x40 });
|
||||
if padding != 0 {
|
||||
combined.push(padding as u8);
|
||||
}
|
||||
for _ in 0..frame_count - 1 {
|
||||
push_subframe_payload_len(&mut combined, payload.len()).unwrap();
|
||||
}
|
||||
}
|
||||
for _ in 0..frame_count {
|
||||
combined.extend_from_slice(payload);
|
||||
}
|
||||
combined.resize(combined.len() + padding, 0);
|
||||
combined
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opus_encoder_rejects_codec2_profiles() {
|
||||
assert!(matches!(
|
||||
@@ -692,4 +1122,264 @@ mod tests {
|
||||
Profile::QualityMedium.sample_frames_per_packet()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_packet_inspection_follows_rfc_vbr_lengths_and_padding() {
|
||||
let toc = 0xF8;
|
||||
|
||||
let mut code_two = vec![toc | 0x02, 252, 0];
|
||||
code_two.extend(std::iter::repeat_n(0, 253));
|
||||
assert_eq!(opus_packet_duration_samples_48k(&code_two).unwrap(), 1_920);
|
||||
|
||||
let padded_code_three = [toc | 0x03, 0x43, 1, 0, 0, 0, 0];
|
||||
assert_eq!(
|
||||
opus_packet_duration_samples_48k(&padded_code_three).unwrap(),
|
||||
2_880
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_packet_inspection_accepts_every_two_and_half_ms_quantum() {
|
||||
let toc = 0x80;
|
||||
for frame_count in 1..=48 {
|
||||
let packet = match frame_count {
|
||||
1 => vec![toc],
|
||||
2 => vec![toc | 0x01],
|
||||
_ => vec![toc | 0x03, frame_count as u8],
|
||||
};
|
||||
assert_eq!(
|
||||
opus_packet_duration_samples_48k(&packet),
|
||||
Ok(frame_count * 120)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_decoder_decodes_rfc_duration_range_at_the_48khz_clock() {
|
||||
let two_and_half = encoded_mono_packet(120, 64_000);
|
||||
let five = encoded_mono_packet(240, 64_000);
|
||||
let ten = encoded_mono_packet(480, 64_000);
|
||||
let twenty = encoded_twenty_ms_mono_packet();
|
||||
let packets = [
|
||||
(two_and_half, 120),
|
||||
(five, 240),
|
||||
(ten.clone(), 480),
|
||||
(twenty.clone(), 960),
|
||||
(repacketize_cbr(&ten, 3), 1_440),
|
||||
(repacketize_cbr(&twenty, 2), 1_920),
|
||||
(repacketize_cbr(&twenty, 3), 2_880),
|
||||
(repacketize_cbr(&twenty, 4), 3_840),
|
||||
(repacketize_cbr(&twenty, 5), 4_800),
|
||||
(repacketize_cbr(&twenty, 6), 5_760),
|
||||
];
|
||||
let mut decoder = OpusMonoDecoder::new().unwrap();
|
||||
assert_eq!(decoder.sample_rate_hz(), 48_000);
|
||||
assert_eq!(decoder.channels(), 1);
|
||||
|
||||
for (packet, expected_sample_frames) in packets {
|
||||
assert!(packet.len() <= OPUS_ENCODED_PACKET_MAX_BYTES);
|
||||
assert_eq!(
|
||||
opus_packet_duration_samples_48k(&packet),
|
||||
Ok(expected_sample_frames)
|
||||
);
|
||||
let decoded = decoder.decode_packet(&packet).unwrap();
|
||||
assert_eq!(decoded.channels, 1);
|
||||
assert_eq!(decoded.sample_frames(), expected_sample_frames);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_decoder_accepts_mixed_rfc_packet_framing() {
|
||||
let direct = encoded_twenty_ms_mono_packet();
|
||||
let packets = [
|
||||
(direct.clone(), 960),
|
||||
(repacketize_cbr(&direct, 2), 1_920),
|
||||
(repacketize_vbr(&direct, 2, 0), 1_920),
|
||||
(repacketize_cbr(&direct, 3), 2_880),
|
||||
(repacketize_vbr(&direct, 3, 7), 2_880),
|
||||
];
|
||||
let mut decoder = OpusMonoDecoder::new().unwrap();
|
||||
|
||||
for (packet, expected_sample_frames) in packets {
|
||||
assert_eq!(
|
||||
opus_packet_duration_samples_48k(&packet),
|
||||
Ok(expected_sample_frames)
|
||||
);
|
||||
assert_eq!(
|
||||
decoder.decode_packet(&packet).unwrap().sample_frames(),
|
||||
expected_sample_frames
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_decoder_accepts_code3_zero_byte_plc_frames() {
|
||||
let toc = encoded_twenty_ms_mono_packet()[0] & !0x03;
|
||||
let packets = [vec![toc | 0x03, 0x03], vec![toc | 0x03, 0x83, 0, 0]];
|
||||
let mut decoder = OpusMonoDecoder::new().unwrap();
|
||||
|
||||
for packet in packets {
|
||||
assert_eq!(opus_packet_duration_samples_48k(&packet), Ok(2_880));
|
||||
assert_eq!(
|
||||
decoder.decode_packet(&packet).unwrap().sample_frames(),
|
||||
2_880
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_decoder_accepts_compound_packets_above_one_frame_ceiling() {
|
||||
let direct = encoded_mono_packet(960, 510_000);
|
||||
assert!(direct.len() - 1 <= OPUS_ENCODED_FRAME_MAX_BYTES);
|
||||
|
||||
let compound = repacketize_cbr(&direct, 2);
|
||||
assert!(compound.len() > OPUS_ENCODED_FRAME_MAX_BYTES);
|
||||
assert!(compound.len() <= OPUS_ENCODED_PACKET_MAX_BYTES);
|
||||
assert_eq!(opus_packet_duration_samples_48k(&compound), Ok(1_920));
|
||||
|
||||
let decoded = OpusMonoDecoder::new()
|
||||
.unwrap()
|
||||
.decode_packet(&compound)
|
||||
.unwrap();
|
||||
assert_eq!(decoded.sample_frames(), 1_920);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_decoder_accepts_current_quality_medium_packets() {
|
||||
let profile = Profile::QualityMedium;
|
||||
let frame = source_for(profile).next_raw_frame().unwrap();
|
||||
let packet = OpusEncoderState::new(profile)
|
||||
.unwrap()
|
||||
.encode_frame(&frame)
|
||||
.unwrap();
|
||||
|
||||
let decoded = OpusMonoDecoder::new()
|
||||
.unwrap()
|
||||
.decode_packet(&packet.payload)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(opus_packet_duration_samples_48k(&packet.payload), Ok(2_880));
|
||||
assert_eq!(decoded.channels, 1);
|
||||
assert_eq!(decoded.sample_frames(), 2_880);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_decoder_rejects_stereo_packets_before_decoding() {
|
||||
let stereo_twenty_ms = [0xFC, 0];
|
||||
assert_eq!(opus_packet_duration_samples_48k(&stereo_twenty_ms), Ok(960));
|
||||
assert!(matches!(
|
||||
OpusMonoDecoder::new()
|
||||
.unwrap()
|
||||
.decode_packet(&stereo_twenty_ms),
|
||||
Err(OpusCodecError::ChannelMismatch {
|
||||
expected: 1,
|
||||
actual: 2
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_packet_policy_enforces_frame_packet_and_duration_bounds() {
|
||||
let oversize = vec![0xF8; OPUS_ENCODED_PACKET_MAX_BYTES + 1];
|
||||
assert_eq!(
|
||||
opus_packet_duration_samples_48k(&oversize),
|
||||
Err(OpusCodecError::EncodedPacketTooLarge {
|
||||
actual: OPUS_ENCODED_PACKET_MAX_BYTES + 1,
|
||||
maximum: OPUS_ENCODED_PACKET_MAX_BYTES,
|
||||
})
|
||||
);
|
||||
|
||||
let oversized_direct_frame = vec![0xF8; OPUS_ENCODED_FRAME_MAX_BYTES + 2];
|
||||
assert_eq!(
|
||||
opus_packet_duration_samples_48k(&oversized_direct_frame),
|
||||
Err(OpusCodecError::EncodedFrameTooLarge {
|
||||
index: 0,
|
||||
actual: OPUS_ENCODED_FRAME_MAX_BYTES + 1,
|
||||
maximum: OPUS_ENCODED_FRAME_MAX_BYTES,
|
||||
})
|
||||
);
|
||||
|
||||
let overlong_twenty_ms = [0xFB, 0x07, 0, 0, 0, 0, 0, 0, 0];
|
||||
assert!(matches!(
|
||||
opus_packet_duration_samples_48k(&overlong_twenty_ms),
|
||||
Err(OpusCodecError::MalformedPacket(
|
||||
"packet duration exceeds 120 milliseconds"
|
||||
))
|
||||
));
|
||||
|
||||
let too_many_two_and_half_ms = [0x83, 49];
|
||||
assert!(matches!(
|
||||
opus_packet_duration_samples_48k(&too_many_two_and_half_ms),
|
||||
Err(OpusCodecError::MalformedPacket(
|
||||
"code 3 frame count exceeds 48"
|
||||
))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interoperable_packet_inspection_rejects_malformed_framing() {
|
||||
let malformed = [
|
||||
Vec::new(),
|
||||
vec![0xFB],
|
||||
vec![0xF9, 0],
|
||||
vec![0xFA, 252],
|
||||
vec![0xFB, 0],
|
||||
vec![0xFB, 0x03, 0, 0],
|
||||
vec![0xFB, 0x43, 2, 0],
|
||||
];
|
||||
|
||||
for packet in malformed {
|
||||
assert!(matches!(
|
||||
opus_packet_duration_samples_48k(&packet),
|
||||
Err(OpusCodecError::MalformedPacket(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Fuzz-found sequence: the last packet drove opus-rs 0.1.29 `silk_decode_core` to a
|
||||
// negative LTP start index and a panic. 0.1.42 decodes or refuses it.
|
||||
fn silk_panic_window() -> Vec<Vec<u8>> {
|
||||
include_str!("../tests/data/opus_silk_negative_ltp_start.hex")
|
||||
.lines()
|
||||
.map(|line| hex::decode(line).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_decoder_survives_fuzz_found_silk_frame() {
|
||||
let window = silk_panic_window();
|
||||
let (last, prefix) = window.split_last().unwrap();
|
||||
let mut decoder = OpusMonoDecoder::new().unwrap();
|
||||
for packet in prefix {
|
||||
let _ = decoder.decode_packet(packet);
|
||||
}
|
||||
let _ = decoder.decode_packet(last);
|
||||
|
||||
let good = encoded_mono_packet(960, 32_000);
|
||||
let after = decoder.decode_packet(&good).unwrap();
|
||||
let fresh = OpusMonoDecoder::new()
|
||||
.unwrap()
|
||||
.decode_packet(&good)
|
||||
.unwrap();
|
||||
assert_eq!(after.samples.len(), fresh.samples.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_decoder_survives_fuzz_found_silk_frame() {
|
||||
let window = silk_panic_window();
|
||||
let (last, prefix) = window.split_last().unwrap();
|
||||
let mut decoder = OpusPacketDecoder::new(OPUS_MONO_DECODE_SAMPLE_RATE_HZ, 1).unwrap();
|
||||
for packet in prefix {
|
||||
let _ = decoder.decode_packet(packet);
|
||||
}
|
||||
let _ = decoder.decode_packet(last);
|
||||
|
||||
let good = encoded_mono_packet(960, 32_000);
|
||||
let after = decoder.decode_packet(&good).unwrap();
|
||||
let fresh = OpusPacketDecoder::new(OPUS_MONO_DECODE_SAMPLE_RATE_HZ, 1)
|
||||
.unwrap()
|
||||
.decode_packet(&good)
|
||||
.unwrap();
|
||||
assert_eq!(after.samples.len(), fresh.samples.len());
|
||||
}
|
||||
}
|
||||
+86
-20
@@ -46,6 +46,46 @@ impl RawAudioFrame {
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert to `channels`: mono is duplicated, extra channels are averaged to mono,
|
||||
/// otherwise the leading channels are kept and the last one repeated.
|
||||
pub fn with_channels(self, channels: u8) -> Result<Self, Error> {
|
||||
if channels == self.channels {
|
||||
return Ok(self);
|
||||
}
|
||||
let source = usize::from(self.channels);
|
||||
let target = usize::from(channels);
|
||||
let mut samples = Vec::with_capacity(self.sample_frames() * target);
|
||||
for frame in self.samples.chunks_exact(source) {
|
||||
if target == 1 {
|
||||
samples.push(frame.iter().sum::<f32>() / source as f32);
|
||||
} else {
|
||||
for channel in 0..target {
|
||||
samples.push(frame[channel.min(source - 1)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::new(channels, samples)
|
||||
}
|
||||
|
||||
/// Linearly resample from `input_rate_hz` to `output_rate_hz`.
|
||||
pub fn resampled(&self, input_rate_hz: u32, output_rate_hz: u32) -> Self {
|
||||
if input_rate_hz == output_rate_hz || input_rate_hz == 0 {
|
||||
return self.clone();
|
||||
}
|
||||
let input_frames = self.sample_frames();
|
||||
let output_frames =
|
||||
(input_frames as u64 * u64::from(output_rate_hz) / u64::from(input_rate_hz)) as usize;
|
||||
Self {
|
||||
channels: self.channels,
|
||||
samples: crate::opus::resample_interleaved_linear(
|
||||
&self.samples,
|
||||
input_frames,
|
||||
output_frames,
|
||||
usize::from(self.channels),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_payload(&self, bit_depth: RawBitDepth) -> Result<Vec<u8>, Error> {
|
||||
validate_sample_count(self.channels, self.samples.len())?;
|
||||
let header = RawFrameHeader::new(self.channels, bit_depth)?;
|
||||
@@ -58,7 +98,7 @@ impl RawAudioFrame {
|
||||
|
||||
fn validate_sample_count(channels: u8, samples: usize) -> Result<(), Error> {
|
||||
RawFrameHeader::new(channels, RawBitDepth::Float16)?;
|
||||
if samples % usize::from(channels) != 0 {
|
||||
if !samples.is_multiple_of(usize::from(channels)) {
|
||||
Err(Error::InvalidRawSampleCount { samples, channels })
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -67,32 +107,32 @@ fn validate_sample_count(channels: u8, samples: usize) -> Result<(), Error> {
|
||||
|
||||
fn decode_samples(bytes: &[u8], bit_depth: RawBitDepth) -> Result<Vec<f32>, Error> {
|
||||
let bytes_per_sample = bit_depth.bytes_per_sample();
|
||||
if bytes.len() % bytes_per_sample != 0 {
|
||||
if !bytes.len().is_multiple_of(bytes_per_sample) {
|
||||
return Err(Error::InvalidRawSampleBytes { bytes_per_sample });
|
||||
}
|
||||
|
||||
let mut samples = Vec::with_capacity(bytes.len() / bytes_per_sample);
|
||||
match bit_depth {
|
||||
RawBitDepth::Float16 => {
|
||||
for chunk in bytes.chunks_exact(2) {
|
||||
for chunk in bytes.as_chunks::<2>().0 {
|
||||
samples.push(f16::from_le_bytes([chunk[0], chunk[1]]).to_f32());
|
||||
}
|
||||
}
|
||||
RawBitDepth::Float32 => {
|
||||
for chunk in bytes.chunks_exact(4) {
|
||||
for chunk in bytes.as_chunks::<4>().0 {
|
||||
samples.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
|
||||
}
|
||||
}
|
||||
RawBitDepth::Float64 => {
|
||||
for chunk in bytes.chunks_exact(8) {
|
||||
for chunk in bytes.as_chunks::<8>().0 {
|
||||
samples.push(f64::from_le_bytes([
|
||||
chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
|
||||
]) as f32);
|
||||
}
|
||||
}
|
||||
RawBitDepth::Float128 => {
|
||||
for chunk in bytes.chunks_exact(16) {
|
||||
samples.push(decode_float128_lossy(chunk));
|
||||
for chunk in bytes.as_chunks::<16>().0 {
|
||||
samples.push(decode_float128(chunk));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,24 +165,50 @@ fn encode_samples(samples: &[f32], bit_depth: RawBitDepth, out: &mut Vec<u8>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_float128_lossy(bytes: &[u8]) -> f32 {
|
||||
// Python/Numpy names this dtype "float128", but on common little-endian
|
||||
// platforms it may be backed by an 80-bit extended value padded to 16 bytes.
|
||||
// We preserve finite zero exactly and otherwise use the leading f64 lane as
|
||||
// a conservative lossy fallback until a platform-specific long-double codec
|
||||
// is introduced.
|
||||
if bytes.iter().all(|byte| *byte == 0) {
|
||||
// numpy float128 is IEEE binary128 on Linux aarch64; x86_64 pads an 80-bit value instead.
|
||||
const BINARY128_EXPONENT_BIAS: i32 = 16_383;
|
||||
const BINARY128_MANTISSA_BITS: u32 = 112;
|
||||
|
||||
fn decode_float128(bytes: &[u8]) -> f32 {
|
||||
let mut le = [0u8; 16];
|
||||
le.copy_from_slice(bytes);
|
||||
let bits = u128::from_le_bytes(le);
|
||||
let negative = bits >> 127 != 0;
|
||||
let exponent = ((bits >> BINARY128_MANTISSA_BITS) & 0x7FFF) as i32;
|
||||
let mantissa = bits & ((1u128 << BINARY128_MANTISSA_BITS) - 1);
|
||||
let magnitude = if exponent == 0x7FFF {
|
||||
if mantissa == 0 {
|
||||
f64::INFINITY
|
||||
} else {
|
||||
f64::NAN
|
||||
}
|
||||
} else if exponent == 0 {
|
||||
// Subnormal binary128 values are far below the f32 range.
|
||||
0.0
|
||||
} else {
|
||||
f64::from_le_bytes([
|
||||
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
|
||||
]) as f32
|
||||
}
|
||||
let fraction = (mantissa >> (BINARY128_MANTISSA_BITS - 52)) as f64 / (1u64 << 52) as f64;
|
||||
(1.0 + fraction) * 2f64.powi(exponent - BINARY128_EXPONENT_BIAS)
|
||||
};
|
||||
(if negative { -magnitude } else { magnitude }) as f32
|
||||
}
|
||||
|
||||
fn encode_float128_from_f32(sample: f32, out: &mut Vec<u8>) {
|
||||
out.extend_from_slice(&f64::from(sample).to_le_bytes());
|
||||
out.extend_from_slice(&[0u8; 8]);
|
||||
let value = f64::from(sample);
|
||||
let f64_bits = value.to_bits();
|
||||
let sign = u128::from(f64_bits >> 63) << 127;
|
||||
let exponent = ((f64_bits >> 52) & 0x7FF) as i32;
|
||||
let mantissa = u128::from(f64_bits & ((1u64 << 52) - 1));
|
||||
let bits = if value == 0.0 {
|
||||
sign
|
||||
} else if exponent == 0x7FF {
|
||||
let nan_mantissa = if mantissa == 0 { 0 } else { 1u128 << 111 };
|
||||
sign | (0x7FFFu128 << BINARY128_MANTISSA_BITS) | nan_mantissa
|
||||
} else {
|
||||
// Every f32 widens to a normal f64.
|
||||
let exponent = (exponent - 1023 + BINARY128_EXPONENT_BIAS) as u128;
|
||||
sign | (exponent << BINARY128_MANTISSA_BITS) | (mantissa << (BINARY128_MANTISSA_BITS - 52))
|
||||
};
|
||||
out.extend_from_slice(&bits.to_le_bytes());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
use crate::Signal;
|
||||
use crate::TelephonyAction;
|
||||
|
||||
/// Every current transition emits at most six ordered actions.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Actions {
|
||||
items: [TelephonyAction; 6],
|
||||
length: usize,
|
||||
}
|
||||
impl Actions {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
items: [const { TelephonyAction::IgnoreSignal(Signal::Raw(0)) }; 6],
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
pub(crate) fn from_array<const N: usize>(items: [TelephonyAction; N]) -> Self {
|
||||
let mut actions = Self::new();
|
||||
for item in items {
|
||||
actions.push(item);
|
||||
}
|
||||
actions
|
||||
}
|
||||
pub(crate) fn push(&mut self, action: TelephonyAction) {
|
||||
assert!(
|
||||
self.length < self.items.len(),
|
||||
"transition action capacity exceeded"
|
||||
);
|
||||
self.items[self.length] = action;
|
||||
self.length += 1;
|
||||
}
|
||||
pub fn as_slice(&self) -> &[TelephonyAction] {
|
||||
&self.items[..self.length]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use crate::{CallMode, Profile, Signal, SignallingStatus};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum CallRole {
|
||||
Incoming,
|
||||
Outgoing,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TelephonyAction {
|
||||
SendSignal(Signal),
|
||||
/// Send both signals in one packet, as Python sends profile and mode on RINGING.
|
||||
SendSignalPair(Signal, Signal),
|
||||
IdentifyLocalIdentity,
|
||||
SelectProfile(Profile),
|
||||
PrepareDialingPipelines,
|
||||
ResetDialingPipelines,
|
||||
OpenAudioPipelines,
|
||||
StartAudioPipelines,
|
||||
StartDialTone,
|
||||
Terminate(Option<SignallingStatus>),
|
||||
TeardownLink,
|
||||
RingIncomingCall,
|
||||
SwitchProfile(Profile),
|
||||
SelectMode(CallMode),
|
||||
SwitchMode(CallMode),
|
||||
IgnoreSignal(Signal),
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Bounded LXST Codec2 packet processing over caller-owned PCM and byte buffers.
|
||||
//
|
||||
// A backend processes native Codec2 frames. This module owns the LXST mode
|
||||
// header and profile aggregation; it does not own LXMF memo containers or their
|
||||
// different audio-mode identifiers. Backend memory, math, timing and supported
|
||||
// modes must be qualified separately before selecting one for a device.
|
||||
|
||||
use crate::{AudioCodec, Codec2Mode, Profile};
|
||||
use thiserror::Error;
|
||||
|
||||
/// A stateful native Codec2 implementation at one fixed mode, mono 8 kHz PCM16.
|
||||
///
|
||||
/// Each operation receives exactly one native frame and an exactly sized output.
|
||||
/// Implementations must not retain the borrowed buffers. A backend error may
|
||||
/// advance its state: the caller must discard that packet and replace the codec
|
||||
/// before continuing. Construction, scratch storage and reset belong to the
|
||||
/// backend owner, allowing host and embedded implementations to differ.
|
||||
pub trait Codec2Backend {
|
||||
type Error;
|
||||
|
||||
fn mode(&self) -> Codec2Mode;
|
||||
fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error>;
|
||||
fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum Codec2PacketError<E> {
|
||||
#[error("profile {0:?} does not use Codec2")]
|
||||
NonCodec2Profile(Profile),
|
||||
#[error("Codec2 backend mode {actual:?} does not match {expected:?}")]
|
||||
BackendModeMismatch {
|
||||
expected: Codec2Mode,
|
||||
actual: Codec2Mode,
|
||||
},
|
||||
#[error("Codec2 PCM sample count {actual} does not match {expected}")]
|
||||
SampleCount { expected: usize, actual: usize },
|
||||
#[error("Codec2 output capacity {actual} is below {required}")]
|
||||
OutputCapacity { required: usize, actual: usize },
|
||||
#[error("Codec2 payload length {actual} does not match {expected}")]
|
||||
PayloadLength { expected: usize, actual: usize },
|
||||
#[error("Codec2 mode header {actual:#04x} does not match {expected:#04x}")]
|
||||
ModeHeader { expected: u8, actual: u8 },
|
||||
#[error("Codec2 backend failed: {0}")]
|
||||
Backend(E),
|
||||
#[error("Codec2 must be replaced after a backend failure")]
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// One fixed-profile LXST Codec2 stream. Wrapper operations allocate no memory.
|
||||
///
|
||||
/// The native backend may allocate; this type makes no claim about its footprint.
|
||||
/// Use separate instances for independent streams. Mode/profile changes require
|
||||
/// a new instance so predictor state cannot leak between differently framed media.
|
||||
pub struct Codec2PacketCodec<B> {
|
||||
backend: B,
|
||||
profile: Profile,
|
||||
mode: Codec2Mode,
|
||||
native_samples: usize,
|
||||
native_bytes: usize,
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl<B: Codec2Backend> Codec2PacketCodec<B> {
|
||||
pub fn new(profile: Profile, backend: B) -> Result<Self, Codec2PacketError<B::Error>> {
|
||||
let AudioCodec::Codec2(mode) = profile.audio_codec() else {
|
||||
return Err(Codec2PacketError::NonCodec2Profile(profile));
|
||||
};
|
||||
if backend.mode() != mode {
|
||||
return Err(Codec2PacketError::BackendModeMismatch {
|
||||
expected: mode,
|
||||
actual: backend.mode(),
|
||||
});
|
||||
}
|
||||
// 700C carries 28 bits in FOUR bytes per native frame. Padding is per
|
||||
// native frame, not once over the aggregated 400 ms packet.
|
||||
let (native_samples, native_bytes) = match profile {
|
||||
Profile::BandwidthUltraLow => (320, 4),
|
||||
Profile::BandwidthVeryLow => (320, 8),
|
||||
Profile::BandwidthLow => (160, 8),
|
||||
_ => return Err(Codec2PacketError::NonCodec2Profile(profile)),
|
||||
};
|
||||
Ok(Self {
|
||||
backend,
|
||||
profile,
|
||||
mode,
|
||||
native_samples,
|
||||
native_bytes,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub const fn profile(&self) -> Profile {
|
||||
self.profile
|
||||
}
|
||||
|
||||
pub const fn mode(&self) -> Codec2Mode {
|
||||
self.mode
|
||||
}
|
||||
|
||||
pub const fn sample_frames(&self) -> usize {
|
||||
self.profile.sample_frames_per_packet()
|
||||
}
|
||||
|
||||
/// Payload bytes including the mode header, excluding the outer codec byte.
|
||||
pub const fn payload_bytes(&self) -> usize {
|
||||
1 + self.sample_frames() / self.native_samples * self.native_bytes
|
||||
}
|
||||
|
||||
fn ready(&self) -> Result<(), Codec2PacketError<B::Error>> {
|
||||
if self.failed {
|
||||
return Err(Codec2PacketError::Failed);
|
||||
}
|
||||
let actual = self.backend.mode();
|
||||
if actual != self.mode {
|
||||
return Err(Codec2PacketError::BackendModeMismatch {
|
||||
expected: self.mode,
|
||||
actual,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode exactly one profile packet. PCM is mono 8 kHz, signed 16-bit.
|
||||
///
|
||||
/// Capacity/shape errors leave output unchanged and do not call the native
|
||||
/// encoder. A backend error invalidates this stream and its partial output;
|
||||
/// replace it before reuse. Bytes beyond the returned length stay untouched.
|
||||
pub fn encode_into(
|
||||
&mut self,
|
||||
pcm: &[i16],
|
||||
output: &mut [u8],
|
||||
) -> Result<usize, Codec2PacketError<B::Error>> {
|
||||
self.ready()?;
|
||||
if pcm.len() != self.sample_frames() {
|
||||
return Err(Codec2PacketError::SampleCount {
|
||||
expected: self.sample_frames(),
|
||||
actual: pcm.len(),
|
||||
});
|
||||
}
|
||||
let required = self.payload_bytes();
|
||||
if output.len() < required {
|
||||
return Err(Codec2PacketError::OutputCapacity {
|
||||
required,
|
||||
actual: output.len(),
|
||||
});
|
||||
}
|
||||
for (samples, bytes) in pcm
|
||||
.chunks_exact(self.native_samples)
|
||||
.zip(output[1..required].chunks_exact_mut(self.native_bytes))
|
||||
{
|
||||
if let Err(error) = self.backend.encode_native(samples, bytes) {
|
||||
self.failed = true;
|
||||
return Err(Codec2PacketError::Backend(error));
|
||||
}
|
||||
}
|
||||
output[0] = self.mode.header();
|
||||
Ok(required)
|
||||
}
|
||||
|
||||
/// Decode exactly one negotiated-profile payload, including its mode header.
|
||||
///
|
||||
/// The wrapper fixes the mode and frame count and allocates no memory.
|
||||
/// It checks mode header, payload length and output capacity before calling
|
||||
/// the native decoder; codec-content validation belongs to the backend.
|
||||
/// On backend failure discard the partial PCM and replace this stream.
|
||||
pub fn decode_into(
|
||||
&mut self,
|
||||
payload: &[u8],
|
||||
output: &mut [i16],
|
||||
) -> Result<usize, Codec2PacketError<B::Error>> {
|
||||
self.ready()?;
|
||||
if payload.len() != self.payload_bytes() {
|
||||
return Err(Codec2PacketError::PayloadLength {
|
||||
expected: self.payload_bytes(),
|
||||
actual: payload.len(),
|
||||
});
|
||||
}
|
||||
if payload[0] != self.mode.header() {
|
||||
return Err(Codec2PacketError::ModeHeader {
|
||||
expected: self.mode.header(),
|
||||
actual: payload[0],
|
||||
});
|
||||
}
|
||||
let required = self.sample_frames();
|
||||
if output.len() < required {
|
||||
return Err(Codec2PacketError::OutputCapacity {
|
||||
required,
|
||||
actual: output.len(),
|
||||
});
|
||||
}
|
||||
for (bytes, samples) in payload[1..]
|
||||
.chunks_exact(self.native_bytes)
|
||||
.zip(output[..required].chunks_exact_mut(self.native_samples))
|
||||
{
|
||||
if let Err(error) = self.backend.decode_native(bytes, samples) {
|
||||
self.failed = true;
|
||||
return Err(Codec2PacketError::Backend(error));
|
||||
}
|
||||
}
|
||||
Ok(required)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::wire::{Codec2Mode, CodecKind};
|
||||
use crate::{Codec2Mode, CodecKind};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u32)]
|
||||
@@ -159,6 +159,21 @@ impl Profile {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `Profiles.get_buffer_frames`: its sink holds one frame more than this and
|
||||
/// starts playback at `max(1, buffer_frames() - 2)` frames.
|
||||
pub const fn buffer_frames(self) -> u8 {
|
||||
match self {
|
||||
Self::BandwidthUltraLow => 2,
|
||||
Self::BandwidthVeryLow => 2,
|
||||
Self::BandwidthLow => 2,
|
||||
Self::QualityMedium => 5,
|
||||
Self::QualityHigh => 5,
|
||||
Self::QualityMax => 5,
|
||||
Self::LatencyLow => 3,
|
||||
Self::LatencyUltraLow => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next(self) -> Self {
|
||||
let index = Self::ORDER
|
||||
.iter()
|
||||
@@ -168,6 +183,44 @@ impl Profile {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum CallMode {
|
||||
FullDuplex = 0x01,
|
||||
HalfDuplex = 0x02,
|
||||
}
|
||||
|
||||
impl CallMode {
|
||||
pub const DEFAULT: Self = Self::FullDuplex;
|
||||
pub const AVAILABLE: [Self; 2] = [Self::FullDuplex, Self::HalfDuplex];
|
||||
|
||||
pub const fn wire_value(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
|
||||
pub const fn from_wire(value: u8) -> Option<Self> {
|
||||
match value {
|
||||
0x01 => Some(Self::FullDuplex),
|
||||
0x02 => Some(Self::HalfDuplex),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::FullDuplex => "Full Duplex",
|
||||
Self::HalfDuplex => "Half Duplex",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn abbreviation(self) -> &'static str {
|
||||
match self {
|
||||
Self::FullDuplex => "FDX",
|
||||
Self::HalfDuplex => "HDX",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum AudioCodec {
|
||||
Opus(OpusProfile),
|
||||
@@ -0,0 +1,334 @@
|
||||
use crate::actions::Actions;
|
||||
use crate::{CallMode, CallRole, Profile, Signal, SignallingStatus, TelephonyAction};
|
||||
|
||||
macro_rules! actions {
|
||||
($($value:expr),* $(,)?) => { Actions::from_array([$($value),*]) };
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CallState {
|
||||
role: CallRole,
|
||||
status: SignallingStatus,
|
||||
profile: Option<Profile>,
|
||||
/// Raw mode value; Python stores unknown modes without acting on them.
|
||||
mode: Option<u8>,
|
||||
answered: bool,
|
||||
pipelines_started: bool,
|
||||
transmit_squelched: bool,
|
||||
remote_mode_follow_disabled: bool,
|
||||
}
|
||||
|
||||
impl CallState {
|
||||
pub fn outgoing(profile: Option<Profile>) -> Self {
|
||||
Self::outgoing_with_mode(profile, None)
|
||||
}
|
||||
|
||||
pub fn outgoing_with_mode(profile: Option<Profile>, mode: Option<CallMode>) -> Self {
|
||||
Self {
|
||||
role: CallRole::Outgoing,
|
||||
status: SignallingStatus::Calling,
|
||||
profile,
|
||||
mode: mode.map(|mode| mode.wire_value()),
|
||||
answered: false,
|
||||
pipelines_started: false,
|
||||
transmit_squelched: false,
|
||||
remote_mode_follow_disabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn incoming() -> Self {
|
||||
Self {
|
||||
role: CallRole::Incoming,
|
||||
status: SignallingStatus::Available,
|
||||
profile: None,
|
||||
mode: None,
|
||||
answered: false,
|
||||
pipelines_started: false,
|
||||
transmit_squelched: false,
|
||||
remote_mode_follow_disabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn role(&self) -> CallRole {
|
||||
self.role
|
||||
}
|
||||
|
||||
pub const fn status(&self) -> SignallingStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub const fn profile(&self) -> Option<Profile> {
|
||||
self.profile
|
||||
}
|
||||
|
||||
pub const fn answered(&self) -> bool {
|
||||
self.answered
|
||||
}
|
||||
|
||||
/// Whether audio pipelines were started; a caller only starts them on the callee's ESTABLISHED.
|
||||
pub const fn audio_started(&self) -> bool {
|
||||
self.pipelines_started
|
||||
}
|
||||
|
||||
/// Selected call mode, or `None` before selection or for an unknown remote mode.
|
||||
pub const fn mode(&self) -> Option<CallMode> {
|
||||
match self.mode {
|
||||
Some(value) => CallMode::from_wire(value),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether outbound media frames are dropped, as Python's squelched Packetizer.
|
||||
pub const fn transmit_squelched(&self) -> bool {
|
||||
self.transmit_squelched
|
||||
}
|
||||
|
||||
/// Squelch or unsquelch transmit locally without signalling, as Python `squelch_transmit`.
|
||||
pub fn set_transmit_squelched(&mut self, squelched: bool) {
|
||||
self.transmit_squelched = squelched;
|
||||
}
|
||||
|
||||
/// Ignore later remote mode switches, as Python `disable_remote_mode_follow`.
|
||||
pub fn disable_remote_mode_follow(&mut self) {
|
||||
self.remote_mode_follow_disabled = true;
|
||||
}
|
||||
|
||||
pub fn incoming_link_established(line_busy: bool) -> Actions {
|
||||
if line_busy {
|
||||
actions![
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)),
|
||||
TelephonyAction::TeardownLink,
|
||||
]
|
||||
} else {
|
||||
actions![TelephonyAction::SendSignal(Signal::from(
|
||||
SignallingStatus::Available,
|
||||
))]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn caller_identified(&mut self, line_busy: bool, allowed: bool) -> Actions {
|
||||
if line_busy || !allowed {
|
||||
return actions![
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)),
|
||||
TelephonyAction::TeardownLink,
|
||||
];
|
||||
}
|
||||
|
||||
let mut actions = Actions::new();
|
||||
actions.push(TelephonyAction::ResetDialingPipelines);
|
||||
self.push_status_signal(SignallingStatus::Ringing, &mut actions);
|
||||
actions.push(TelephonyAction::RingIncomingCall);
|
||||
actions
|
||||
}
|
||||
|
||||
pub fn answer(&mut self) -> Actions {
|
||||
if self.role != CallRole::Incoming || self.status != SignallingStatus::Ringing {
|
||||
return Actions::new();
|
||||
}
|
||||
|
||||
let mut actions = Actions::new();
|
||||
self.answered = true;
|
||||
self.ensure_profile(&mut actions);
|
||||
self.ensure_mode(&mut actions);
|
||||
self.squelch_for_opened_pipelines();
|
||||
self.push_status_signal(SignallingStatus::Connecting, &mut actions);
|
||||
actions.push(TelephonyAction::OpenAudioPipelines);
|
||||
self.push_status_signal(SignallingStatus::Established, &mut actions);
|
||||
actions.push(TelephonyAction::StartAudioPipelines);
|
||||
self.pipelines_started = true;
|
||||
actions
|
||||
}
|
||||
|
||||
pub fn receive_signal(&mut self, signal: Signal) -> Actions {
|
||||
if self.role == CallRole::Incoming && !self.answered && matches!(signal, Signal::Status(_))
|
||||
{
|
||||
return actions![TelephonyAction::IgnoreSignal(signal)];
|
||||
}
|
||||
|
||||
match signal {
|
||||
Signal::Status(SignallingStatus::Busy) => {
|
||||
actions![TelephonyAction::Terminate(Some(SignallingStatus::Busy))]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Rejected) => {
|
||||
actions![TelephonyAction::Terminate(Some(SignallingStatus::Rejected))]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Calling) => {
|
||||
actions![TelephonyAction::IgnoreSignal(signal)]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Available) => {
|
||||
if self.status.wire_value() >= SignallingStatus::Available.wire_value() {
|
||||
return actions![TelephonyAction::IgnoreSignal(signal)];
|
||||
}
|
||||
self.status = SignallingStatus::Available;
|
||||
actions![TelephonyAction::IdentifyLocalIdentity]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Ringing) => {
|
||||
if self.status.wire_value() >= SignallingStatus::Ringing.wire_value() {
|
||||
return actions![TelephonyAction::IgnoreSignal(signal)];
|
||||
}
|
||||
let mut actions = Actions::new();
|
||||
self.status = SignallingStatus::Ringing;
|
||||
let profile = self.ensure_profile(&mut actions);
|
||||
let mode = self.ensure_mode(&mut actions);
|
||||
actions.push(TelephonyAction::PrepareDialingPipelines);
|
||||
actions.push(TelephonyAction::SendSignalPair(
|
||||
Signal::from(profile),
|
||||
Signal::PreferredMode(mode),
|
||||
));
|
||||
actions.push(TelephonyAction::StartDialTone);
|
||||
actions
|
||||
}
|
||||
Signal::Status(SignallingStatus::Connecting) => {
|
||||
if self.role == CallRole::Outgoing
|
||||
&& self.status.wire_value() >= SignallingStatus::Connecting.wire_value()
|
||||
{
|
||||
// Python answers every CONNECTING with ESTABLISHED, and callees
|
||||
// from rsLXST 0.3.1 and earlier resend CONNECTING until they see it.
|
||||
return actions![TelephonyAction::SendSignal(Signal::from(
|
||||
SignallingStatus::Established,
|
||||
))];
|
||||
}
|
||||
if self.status.wire_value() >= SignallingStatus::Connecting.wire_value() {
|
||||
return actions![TelephonyAction::IgnoreSignal(signal)];
|
||||
}
|
||||
self.status = SignallingStatus::Connecting;
|
||||
self.squelch_for_opened_pipelines();
|
||||
let mut actions = actions![
|
||||
TelephonyAction::ResetDialingPipelines,
|
||||
TelephonyAction::OpenAudioPipelines,
|
||||
];
|
||||
if self.role == CallRole::Outgoing {
|
||||
// Python's caller signals ESTABLISHED once its pipelines are open,
|
||||
// which makes its own call status ESTABLISHED.
|
||||
self.push_status_signal(SignallingStatus::Established, &mut actions);
|
||||
}
|
||||
actions
|
||||
}
|
||||
Signal::Status(SignallingStatus::Established) => {
|
||||
if self.role != CallRole::Outgoing || self.pipelines_started {
|
||||
return actions![TelephonyAction::IgnoreSignal(signal)];
|
||||
}
|
||||
self.status = SignallingStatus::Established;
|
||||
self.pipelines_started = true;
|
||||
actions![TelephonyAction::StartAudioPipelines]
|
||||
}
|
||||
Signal::PreferredProfile(profile) => {
|
||||
if self.profile == Some(profile) {
|
||||
return Actions::new();
|
||||
}
|
||||
|
||||
self.profile = Some(profile);
|
||||
if self.status == SignallingStatus::Established {
|
||||
actions![TelephonyAction::SwitchProfile(profile)]
|
||||
} else {
|
||||
actions![TelephonyAction::SelectProfile(profile)]
|
||||
}
|
||||
}
|
||||
Signal::PreferredMode(mode) => {
|
||||
if self.status == SignallingStatus::Established {
|
||||
if self.remote_mode_follow_disabled || self.mode == Some(mode) {
|
||||
return Actions::new();
|
||||
}
|
||||
let Some(known) = CallMode::from_wire(mode) else {
|
||||
return Actions::new();
|
||||
};
|
||||
self.mode = Some(mode);
|
||||
self.apply_mode_squelch(known);
|
||||
actions![TelephonyAction::SwitchMode(known)]
|
||||
} else {
|
||||
self.mode = Some(mode);
|
||||
match CallMode::from_wire(mode) {
|
||||
Some(known) => {
|
||||
self.apply_mode_squelch(known);
|
||||
actions![TelephonyAction::SelectMode(known)]
|
||||
}
|
||||
None => Actions::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Signal::Raw(_) => actions![TelephonyAction::IgnoreSignal(signal)],
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch the mode of an established call and signal it, as Python `switch_mode`.
|
||||
pub fn switch_mode(&mut self, mode: CallMode) -> Actions {
|
||||
if self.status != SignallingStatus::Established || self.mode == Some(mode.wire_value()) {
|
||||
return Actions::new();
|
||||
}
|
||||
self.mode = Some(mode.wire_value());
|
||||
self.apply_mode_squelch(mode);
|
||||
actions![
|
||||
TelephonyAction::SendSignal(Signal::from(mode)),
|
||||
TelephonyAction::SwitchMode(mode),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn switch_profile(&mut self, profile: Profile) -> Actions {
|
||||
if self.profile == Some(profile) {
|
||||
return Actions::new();
|
||||
}
|
||||
|
||||
self.profile = Some(profile);
|
||||
if self.status == SignallingStatus::Established {
|
||||
actions![
|
||||
TelephonyAction::SendSignal(Signal::from(profile)),
|
||||
TelephonyAction::SwitchProfile(profile),
|
||||
]
|
||||
} else {
|
||||
actions![TelephonyAction::SelectProfile(profile)]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hangup(&mut self, ring_timeout: bool) -> Actions {
|
||||
let mut actions = Actions::new();
|
||||
|
||||
if self.role == CallRole::Incoming
|
||||
&& self.status == SignallingStatus::Ringing
|
||||
&& !ring_timeout
|
||||
{
|
||||
actions.push(TelephonyAction::SendSignal(Signal::from(
|
||||
SignallingStatus::Rejected,
|
||||
)));
|
||||
}
|
||||
|
||||
actions.push(TelephonyAction::TeardownLink);
|
||||
self.status = SignallingStatus::Available;
|
||||
self.answered = false;
|
||||
self.pipelines_started = false;
|
||||
actions
|
||||
}
|
||||
|
||||
fn ensure_profile(&mut self, actions: &mut Actions) -> Profile {
|
||||
let profile = self.profile.unwrap_or(Profile::DEFAULT);
|
||||
self.profile = Some(profile);
|
||||
actions.push(TelephonyAction::SelectProfile(profile));
|
||||
profile
|
||||
}
|
||||
|
||||
/// Python `__select_call_mode`: an unset mode becomes the default, an unknown one is kept.
|
||||
fn ensure_mode(&mut self, actions: &mut Actions) -> u8 {
|
||||
let mode = self.mode.unwrap_or(CallMode::DEFAULT.wire_value());
|
||||
self.mode = Some(mode);
|
||||
if let Some(known) = CallMode::from_wire(mode) {
|
||||
self.apply_mode_squelch(known);
|
||||
actions.push(TelephonyAction::SelectMode(known));
|
||||
}
|
||||
mode
|
||||
}
|
||||
|
||||
fn apply_mode_squelch(&mut self, mode: CallMode) {
|
||||
self.transmit_squelched = mode == CallMode::HalfDuplex;
|
||||
}
|
||||
|
||||
/// Python builds a new Packetizer when pipelines open and squelches it only for half duplex.
|
||||
fn squelch_for_opened_pipelines(&mut self) {
|
||||
self.transmit_squelched = self.mode == Some(CallMode::HalfDuplex.wire_value());
|
||||
}
|
||||
|
||||
fn push_status_signal(&mut self, status: SignallingStatus, actions: &mut Actions) {
|
||||
if status.is_auto_status() {
|
||||
self.status = status;
|
||||
}
|
||||
actions.push(TelephonyAction::SendSignal(Signal::from(status)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// Shared directly with lxst-embedded. The enclosing wire module supplies its
|
||||
// own error type; wire identifiers and conversions have one implementation.
|
||||
use crate::profile::{CallMode, Profile, SignallingStatus};
|
||||
const PREFERRED_MODE_BASE: u32 = 0xF0;
|
||||
const PREFERRED_PROFILE_BASE: u32 = 0xFF;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum CodecKind {
|
||||
Raw = 0x00,
|
||||
Opus = 0x01,
|
||||
Codec2 = 0x02,
|
||||
Null = 0xFF,
|
||||
}
|
||||
|
||||
impl CodecKind {
|
||||
pub const fn wire_id(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
|
||||
pub const fn from_wire(id: u8) -> Result<Self, Error> {
|
||||
match id {
|
||||
0x00 => Ok(Self::Raw),
|
||||
0x01 => Ok(Self::Opus),
|
||||
0x02 => Ok(Self::Codec2),
|
||||
0xFF => Ok(Self::Null),
|
||||
other => Err(Error::UnknownCodec(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_transmittable(self) -> bool {
|
||||
!matches!(self, Self::Null)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Signal {
|
||||
Status(SignallingStatus),
|
||||
PreferredProfile(Profile),
|
||||
/// Raw mode byte after `0xF0`; unknown modes are carried, not rejected.
|
||||
PreferredMode(u8),
|
||||
Raw(u32),
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
pub const fn wire_value(self) -> u32 {
|
||||
match self {
|
||||
Self::Status(status) => status.wire_value(),
|
||||
Self::PreferredProfile(profile) => PREFERRED_PROFILE_BASE + profile.wire_value(),
|
||||
Self::PreferredMode(mode) => PREFERRED_MODE_BASE + mode as u32,
|
||||
Self::Raw(value) => value,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn from_wire(value: u32) -> Self {
|
||||
if let Some(status) = SignallingStatus::from_wire(value) {
|
||||
Self::Status(status)
|
||||
} else if value >= PREFERRED_PROFILE_BASE {
|
||||
let profile_value = value - PREFERRED_PROFILE_BASE;
|
||||
if let Some(profile) = Profile::from_wire(profile_value) {
|
||||
Self::PreferredProfile(profile)
|
||||
} else {
|
||||
Self::Raw(value)
|
||||
}
|
||||
} else if value >= PREFERRED_MODE_BASE {
|
||||
Self::PreferredMode((value - PREFERRED_MODE_BASE) as u8)
|
||||
} else {
|
||||
Self::Raw(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SignallingStatus> for Signal {
|
||||
fn from(value: SignallingStatus) -> Self {
|
||||
Self::Status(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CallMode> for Signal {
|
||||
fn from(value: CallMode) -> Self {
|
||||
Self::PreferredMode(value.wire_value())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Profile> for Signal {
|
||||
fn from(value: Profile) -> Self {
|
||||
Self::PreferredProfile(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum Codec2Mode {
|
||||
Mode700C = 0x00,
|
||||
Mode1200 = 0x01,
|
||||
Mode1300 = 0x02,
|
||||
Mode1400 = 0x03,
|
||||
Mode1600 = 0x04,
|
||||
Mode2400 = 0x05,
|
||||
Mode3200 = 0x06,
|
||||
}
|
||||
|
||||
impl Codec2Mode {
|
||||
pub const fn from_header(byte: u8) -> Result<Self, Error> {
|
||||
match byte {
|
||||
0x00 => Ok(Self::Mode700C),
|
||||
0x01 => Ok(Self::Mode1200),
|
||||
0x02 => Ok(Self::Mode1300),
|
||||
0x03 => Ok(Self::Mode1400),
|
||||
0x04 => Ok(Self::Mode1600),
|
||||
0x05 => Ok(Self::Mode2400),
|
||||
0x06 => Ok(Self::Mode3200),
|
||||
other => Err(Error::UnknownCodec2Mode(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn header(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
|
||||
pub const fn bitrate(self) -> u16 {
|
||||
match self {
|
||||
Self::Mode700C => 700,
|
||||
Self::Mode1200 => 1200,
|
||||
Self::Mode1300 => 1300,
|
||||
Self::Mode1400 => 1400,
|
||||
Self::Mode1600 => 1600,
|
||||
Self::Mode2400 => 2400,
|
||||
Self::Mode3200 => 3200,
|
||||
}
|
||||
}
|
||||
}
|
||||
+279
-183
@@ -1,217 +1,79 @@
|
||||
use crate::{Profile, Signal, SignallingStatus};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum CallRole {
|
||||
Incoming,
|
||||
Outgoing,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TelephonyAction {
|
||||
SendSignal(Signal),
|
||||
IdentifyLocalIdentity,
|
||||
SelectProfile(Profile),
|
||||
PrepareDialingPipelines,
|
||||
ResetDialingPipelines,
|
||||
OpenAudioPipelines,
|
||||
StartAudioPipelines,
|
||||
StartDialTone,
|
||||
Terminate(Option<SignallingStatus>),
|
||||
TeardownLink,
|
||||
RingIncomingCall,
|
||||
SwitchProfile(Profile),
|
||||
IgnoreSignal(Signal),
|
||||
}
|
||||
use crate::call_state::CallState;
|
||||
include!("shared/call_types.rs");
|
||||
|
||||
/// Allocating host facade over the same bounded transition core used on MCUs.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TelephonyCall {
|
||||
role: CallRole,
|
||||
status: SignallingStatus,
|
||||
profile: Option<Profile>,
|
||||
answered: bool,
|
||||
state: CallState,
|
||||
}
|
||||
|
||||
impl TelephonyCall {
|
||||
pub fn outgoing(profile: Option<Profile>) -> Self {
|
||||
Self {
|
||||
role: CallRole::Outgoing,
|
||||
status: SignallingStatus::Calling,
|
||||
profile,
|
||||
answered: false,
|
||||
state: CallState::outgoing(profile),
|
||||
}
|
||||
}
|
||||
pub fn outgoing_with_mode(profile: Option<Profile>, mode: Option<CallMode>) -> Self {
|
||||
Self {
|
||||
state: CallState::outgoing_with_mode(profile, mode),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn incoming() -> Self {
|
||||
Self {
|
||||
role: CallRole::Incoming,
|
||||
status: SignallingStatus::Available,
|
||||
profile: None,
|
||||
answered: false,
|
||||
state: CallState::incoming(),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn role(&self) -> CallRole {
|
||||
self.role
|
||||
self.state.role()
|
||||
}
|
||||
|
||||
pub const fn status(&self) -> SignallingStatus {
|
||||
self.status
|
||||
self.state.status()
|
||||
}
|
||||
|
||||
pub const fn profile(&self) -> Option<Profile> {
|
||||
self.profile
|
||||
self.state.profile()
|
||||
}
|
||||
|
||||
pub const fn answered(&self) -> bool {
|
||||
self.answered
|
||||
self.state.answered()
|
||||
}
|
||||
pub const fn audio_started(&self) -> bool {
|
||||
self.state.audio_started()
|
||||
}
|
||||
pub const fn mode(&self) -> Option<CallMode> {
|
||||
self.state.mode()
|
||||
}
|
||||
pub const fn transmit_squelched(&self) -> bool {
|
||||
self.state.transmit_squelched()
|
||||
}
|
||||
pub fn set_transmit_squelched(&mut self, squelched: bool) {
|
||||
self.state.set_transmit_squelched(squelched);
|
||||
}
|
||||
pub fn disable_remote_mode_follow(&mut self) {
|
||||
self.state.disable_remote_mode_follow();
|
||||
}
|
||||
pub fn switch_mode(&mut self, mode: CallMode) -> Vec<TelephonyAction> {
|
||||
self.state.switch_mode(mode).as_slice().to_vec()
|
||||
}
|
||||
|
||||
pub fn incoming_link_established(line_busy: bool) -> Vec<TelephonyAction> {
|
||||
if line_busy {
|
||||
vec![
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)),
|
||||
TelephonyAction::TeardownLink,
|
||||
]
|
||||
} else {
|
||||
vec![TelephonyAction::SendSignal(Signal::from(
|
||||
SignallingStatus::Available,
|
||||
))]
|
||||
}
|
||||
CallState::incoming_link_established(line_busy)
|
||||
.as_slice()
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
pub fn caller_identified(&mut self, line_busy: bool, allowed: bool) -> Vec<TelephonyAction> {
|
||||
if line_busy || !allowed {
|
||||
return vec![
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)),
|
||||
TelephonyAction::TeardownLink,
|
||||
];
|
||||
}
|
||||
|
||||
let mut actions = Vec::new();
|
||||
actions.push(TelephonyAction::ResetDialingPipelines);
|
||||
self.push_status_signal(SignallingStatus::Ringing, &mut actions);
|
||||
actions.push(TelephonyAction::RingIncomingCall);
|
||||
actions
|
||||
self.state
|
||||
.caller_identified(line_busy, allowed)
|
||||
.as_slice()
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
pub fn answer(&mut self) -> Vec<TelephonyAction> {
|
||||
if self.role != CallRole::Incoming || self.status != SignallingStatus::Ringing {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut actions = Vec::new();
|
||||
self.answered = true;
|
||||
self.ensure_profile(&mut actions);
|
||||
self.push_status_signal(SignallingStatus::Connecting, &mut actions);
|
||||
actions.push(TelephonyAction::OpenAudioPipelines);
|
||||
self.push_status_signal(SignallingStatus::Established, &mut actions);
|
||||
actions.push(TelephonyAction::StartAudioPipelines);
|
||||
actions
|
||||
self.state.answer().as_slice().to_vec()
|
||||
}
|
||||
|
||||
pub fn receive_signal(&mut self, signal: Signal) -> Vec<TelephonyAction> {
|
||||
if self.role == CallRole::Incoming && !self.answered && matches!(signal, Signal::Status(_))
|
||||
{
|
||||
return vec![TelephonyAction::IgnoreSignal(signal)];
|
||||
}
|
||||
|
||||
match signal {
|
||||
Signal::Status(SignallingStatus::Busy) => {
|
||||
vec![TelephonyAction::Terminate(Some(SignallingStatus::Busy))]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Rejected) => {
|
||||
vec![TelephonyAction::Terminate(Some(SignallingStatus::Rejected))]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Calling) => {
|
||||
vec![TelephonyAction::IgnoreSignal(signal)]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Available) => {
|
||||
self.status = SignallingStatus::Available;
|
||||
vec![TelephonyAction::IdentifyLocalIdentity]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Ringing) => {
|
||||
let mut actions = Vec::new();
|
||||
self.status = SignallingStatus::Ringing;
|
||||
self.ensure_profile(&mut actions);
|
||||
actions.push(TelephonyAction::PrepareDialingPipelines);
|
||||
if let Some(profile) = self.profile {
|
||||
actions.push(TelephonyAction::SendSignal(Signal::from(profile)));
|
||||
}
|
||||
actions.push(TelephonyAction::StartDialTone);
|
||||
actions
|
||||
}
|
||||
Signal::Status(SignallingStatus::Connecting) => {
|
||||
self.status = SignallingStatus::Connecting;
|
||||
vec![
|
||||
TelephonyAction::ResetDialingPipelines,
|
||||
TelephonyAction::OpenAudioPipelines,
|
||||
]
|
||||
}
|
||||
Signal::Status(SignallingStatus::Established) => {
|
||||
self.status = SignallingStatus::Established;
|
||||
vec![TelephonyAction::StartAudioPipelines]
|
||||
}
|
||||
Signal::PreferredProfile(profile) => {
|
||||
if self.profile == Some(profile) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
self.profile = Some(profile);
|
||||
if self.status == SignallingStatus::Established {
|
||||
vec![TelephonyAction::SwitchProfile(profile)]
|
||||
} else {
|
||||
vec![TelephonyAction::SelectProfile(profile)]
|
||||
}
|
||||
}
|
||||
Signal::Raw(_) => vec![TelephonyAction::IgnoreSignal(signal)],
|
||||
}
|
||||
self.state.receive_signal(signal).as_slice().to_vec()
|
||||
}
|
||||
|
||||
pub fn switch_profile(&mut self, profile: Profile) -> Vec<TelephonyAction> {
|
||||
if self.profile == Some(profile) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
self.profile = Some(profile);
|
||||
if self.status == SignallingStatus::Established {
|
||||
vec![
|
||||
TelephonyAction::SendSignal(Signal::from(profile)),
|
||||
TelephonyAction::SwitchProfile(profile),
|
||||
]
|
||||
} else {
|
||||
vec![TelephonyAction::SelectProfile(profile)]
|
||||
}
|
||||
self.state.switch_profile(profile).as_slice().to_vec()
|
||||
}
|
||||
|
||||
pub fn hangup(&mut self, ring_timeout: bool) -> Vec<TelephonyAction> {
|
||||
let mut actions = Vec::new();
|
||||
|
||||
if self.role == CallRole::Incoming
|
||||
&& self.status == SignallingStatus::Ringing
|
||||
&& !ring_timeout
|
||||
{
|
||||
actions.push(TelephonyAction::SendSignal(Signal::from(
|
||||
SignallingStatus::Rejected,
|
||||
)));
|
||||
}
|
||||
|
||||
actions.push(TelephonyAction::TeardownLink);
|
||||
self.status = SignallingStatus::Available;
|
||||
self.answered = false;
|
||||
actions
|
||||
}
|
||||
|
||||
fn ensure_profile(&mut self, actions: &mut Vec<TelephonyAction>) {
|
||||
let profile = self.profile.unwrap_or(Profile::DEFAULT);
|
||||
self.profile = Some(profile);
|
||||
actions.push(TelephonyAction::SelectProfile(profile));
|
||||
}
|
||||
|
||||
fn push_status_signal(&mut self, status: SignallingStatus, actions: &mut Vec<TelephonyAction>) {
|
||||
if status.is_auto_status() {
|
||||
self.status = status;
|
||||
}
|
||||
actions.push(TelephonyAction::SendSignal(Signal::from(status)));
|
||||
self.state.hangup(ring_timeout).as_slice().to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,16 +116,26 @@ mod tests {
|
||||
assert_eq!(call.status(), SignallingStatus::Established);
|
||||
assert!(call.answered());
|
||||
assert_eq!(call.profile(), Some(Profile::DEFAULT));
|
||||
assert_eq!(call.mode(), Some(CallMode::FullDuplex));
|
||||
assert_eq!(
|
||||
answer,
|
||||
vec![
|
||||
TelephonyAction::SelectProfile(Profile::DEFAULT),
|
||||
TelephonyAction::SelectMode(CallMode::FullDuplex),
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)),
|
||||
TelephonyAction::OpenAudioPipelines,
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)),
|
||||
TelephonyAction::StartAudioPipelines,
|
||||
]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
call.receive_signal(Signal::from(SignallingStatus::Established)),
|
||||
vec![TelephonyAction::IgnoreSignal(Signal::from(
|
||||
SignallingStatus::Established
|
||||
))]
|
||||
);
|
||||
assert_eq!(call.status(), SignallingStatus::Established);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -281,8 +153,12 @@ mod tests {
|
||||
ringing,
|
||||
vec![
|
||||
TelephonyAction::SelectProfile(Profile::DEFAULT),
|
||||
TelephonyAction::SelectMode(CallMode::FullDuplex),
|
||||
TelephonyAction::PrepareDialingPipelines,
|
||||
TelephonyAction::SendSignal(Signal::from(Profile::DEFAULT)),
|
||||
TelephonyAction::SendSignalPair(
|
||||
Signal::from(Profile::DEFAULT),
|
||||
Signal::from(CallMode::FullDuplex),
|
||||
),
|
||||
TelephonyAction::StartDialTone,
|
||||
]
|
||||
);
|
||||
@@ -292,6 +168,7 @@ mod tests {
|
||||
vec![
|
||||
TelephonyAction::ResetDialingPipelines,
|
||||
TelephonyAction::OpenAudioPipelines,
|
||||
TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -301,6 +178,225 @@ mod tests {
|
||||
assert_eq!(call.status(), SignallingStatus::Established);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callee_is_established_on_answer_and_ignores_the_caller_echo() {
|
||||
let mut incoming = TelephonyCall::incoming();
|
||||
incoming.caller_identified(false, true);
|
||||
incoming.answer();
|
||||
assert_eq!(incoming.status(), SignallingStatus::Established);
|
||||
assert_eq!(
|
||||
incoming.receive_signal(Signal::from(SignallingStatus::Established)),
|
||||
vec![TelephonyAction::IgnoreSignal(Signal::from(
|
||||
SignallingStatus::Established
|
||||
))]
|
||||
);
|
||||
assert!(incoming.answer().is_empty());
|
||||
|
||||
let mut outgoing = TelephonyCall::outgoing(Some(Profile::DEFAULT));
|
||||
outgoing.receive_signal(Signal::from(SignallingStatus::Available));
|
||||
outgoing.receive_signal(Signal::from(SignallingStatus::Ringing));
|
||||
outgoing.receive_signal(Signal::from(SignallingStatus::Connecting));
|
||||
outgoing.receive_signal(Signal::from(SignallingStatus::Established));
|
||||
assert_eq!(
|
||||
outgoing.receive_signal(Signal::from(SignallingStatus::Connecting)),
|
||||
vec![TelephonyAction::SendSignal(Signal::from(
|
||||
SignallingStatus::Established
|
||||
))]
|
||||
);
|
||||
assert_eq!(outgoing.status(), SignallingStatus::Established);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller_is_established_after_connecting_and_starts_audio_on_callee_established() {
|
||||
let mut call = TelephonyCall::outgoing(None);
|
||||
call.receive_signal(Signal::from(SignallingStatus::Available));
|
||||
call.receive_signal(Signal::from(SignallingStatus::Ringing));
|
||||
call.receive_signal(Signal::from(SignallingStatus::Connecting));
|
||||
assert_eq!(call.status(), SignallingStatus::Established);
|
||||
assert_eq!(
|
||||
call.receive_signal(Signal::from(SignallingStatus::Established)),
|
||||
vec![TelephonyAction::StartAudioPipelines]
|
||||
);
|
||||
assert_eq!(
|
||||
call.receive_signal(Signal::from(SignallingStatus::Established)),
|
||||
vec![TelephonyAction::IgnoreSignal(Signal::from(
|
||||
SignallingStatus::Established
|
||||
))]
|
||||
);
|
||||
}
|
||||
|
||||
fn signals(packet: &str) -> Vec<Signal> {
|
||||
crate::LxstPacket::decode(&hex::decode(packet).unwrap())
|
||||
.unwrap()
|
||||
.signals
|
||||
}
|
||||
|
||||
fn sent(actions: &[TelephonyAction]) -> Vec<Vec<u8>> {
|
||||
actions
|
||||
.iter()
|
||||
.filter_map(|action| match action {
|
||||
TelephonyAction::SendSignal(signal) => Some(vec![*signal]),
|
||||
TelephonyAction::SendSignalPair(first, second) => Some(vec![*first, *second]),
|
||||
_ => None,
|
||||
})
|
||||
.map(|signals| crate::LxstPacket::signalling(signals).encode().unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Packets recorded from the rsLXST 0.3.1 call state machine; it decodes the mode
|
||||
// byte of a profile-and-mode packet as an ignored raw signal.
|
||||
#[test]
|
||||
fn caller_completes_a_call_with_a_0_3_1_callee() {
|
||||
let mut call = TelephonyCall::outgoing(None);
|
||||
let mut out = Vec::new();
|
||||
for packet in ["81009103", "81009104", "81009105", "81009106", "81009105"] {
|
||||
for signal in signals(packet) {
|
||||
out.extend(sent(&call.receive_signal(signal)));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
out.iter().map(hex::encode).collect::<Vec<_>>(),
|
||||
["810092cd013fccf1", "81009106", "81009106"]
|
||||
);
|
||||
assert_eq!(call.status(), SignallingStatus::Established);
|
||||
assert!(call.audio_started());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callee_completes_a_call_with_a_0_3_1_caller() {
|
||||
let mut call = TelephonyCall::incoming();
|
||||
call.caller_identified(false, true);
|
||||
for signal in signals("810091cd013f") {
|
||||
call.receive_signal(signal);
|
||||
}
|
||||
assert_eq!(
|
||||
sent(&call.answer())
|
||||
.iter()
|
||||
.map(hex::encode)
|
||||
.collect::<Vec<_>>(),
|
||||
["81009105", "81009106"]
|
||||
);
|
||||
for signal in signals("81009106") {
|
||||
assert!(matches!(
|
||||
call.receive_signal(signal).as_slice(),
|
||||
[TelephonyAction::IgnoreSignal(_)]
|
||||
));
|
||||
}
|
||||
assert_eq!(call.status(), SignallingStatus::Established);
|
||||
assert_eq!(call.profile(), Some(Profile::QualityMedium));
|
||||
assert_eq!(call.mode(), Some(CallMode::FullDuplex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ringing_sends_profile_and_requested_mode_in_one_packet() {
|
||||
let mut call = TelephonyCall::outgoing_with_mode(
|
||||
Some(Profile::BandwidthLow),
|
||||
Some(CallMode::HalfDuplex),
|
||||
);
|
||||
call.receive_signal(Signal::from(SignallingStatus::Available));
|
||||
let ringing = call.receive_signal(Signal::from(SignallingStatus::Ringing));
|
||||
assert!(ringing.contains(&TelephonyAction::SendSignalPair(
|
||||
Signal::from(Profile::BandwidthLow),
|
||||
Signal::from(CallMode::HalfDuplex),
|
||||
)));
|
||||
assert!(call.transmit_squelched());
|
||||
assert_eq!(Signal::from(CallMode::HalfDuplex).wire_value(), 0xF2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_signal_before_answer_is_selected_but_status_is_ignored() {
|
||||
let mut call = TelephonyCall::incoming();
|
||||
call.caller_identified(false, true);
|
||||
assert_eq!(
|
||||
call.receive_signal(Signal::from_wire(0xF2)),
|
||||
vec![TelephonyAction::SelectMode(CallMode::HalfDuplex)]
|
||||
);
|
||||
assert!(call.transmit_squelched());
|
||||
assert_eq!(
|
||||
call.receive_signal(Signal::from(SignallingStatus::Connecting)),
|
||||
vec![TelephonyAction::IgnoreSignal(Signal::from(
|
||||
SignallingStatus::Connecting
|
||||
))]
|
||||
);
|
||||
let answer = call.answer();
|
||||
assert!(answer.contains(&TelephonyAction::SelectMode(CallMode::HalfDuplex)));
|
||||
assert!(call.transmit_squelched());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_mode_is_stored_without_squelch_change_or_error() {
|
||||
let mut call = TelephonyCall::incoming();
|
||||
call.caller_identified(false, true);
|
||||
assert!(call.receive_signal(Signal::from_wire(0xF3)).is_empty());
|
||||
assert_eq!(call.mode(), None);
|
||||
assert!(!call.transmit_squelched());
|
||||
call.answer();
|
||||
assert!(!call.transmit_squelched());
|
||||
assert!(call.receive_signal(Signal::from_wire(0xF0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_pipelines_squelches_only_for_half_duplex() {
|
||||
let mut callee = TelephonyCall::incoming();
|
||||
callee.caller_identified(false, true);
|
||||
callee.receive_signal(Signal::from(CallMode::HalfDuplex));
|
||||
assert!(callee.receive_signal(Signal::from_wire(0xF5)).is_empty());
|
||||
assert!(callee.transmit_squelched());
|
||||
callee.answer();
|
||||
assert!(!callee.transmit_squelched());
|
||||
|
||||
let mut caller = TelephonyCall::outgoing(None);
|
||||
caller.receive_signal(Signal::from(SignallingStatus::Available));
|
||||
caller.receive_signal(Signal::from(SignallingStatus::Ringing));
|
||||
caller.set_transmit_squelched(true);
|
||||
caller.receive_signal(Signal::from(SignallingStatus::Connecting));
|
||||
assert!(!caller.transmit_squelched());
|
||||
|
||||
let mut half_duplex = TelephonyCall::outgoing_with_mode(None, Some(CallMode::HalfDuplex));
|
||||
half_duplex.receive_signal(Signal::from(SignallingStatus::Available));
|
||||
half_duplex.receive_signal(Signal::from(SignallingStatus::Ringing));
|
||||
half_duplex.receive_signal(Signal::from(SignallingStatus::Connecting));
|
||||
assert!(half_duplex.transmit_squelched());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn established_mode_switch_follows_remote_unless_disabled() {
|
||||
let mut call = TelephonyCall::incoming();
|
||||
call.caller_identified(false, true);
|
||||
call.answer();
|
||||
assert_eq!(
|
||||
call.receive_signal(Signal::from(CallMode::HalfDuplex)),
|
||||
vec![TelephonyAction::SwitchMode(CallMode::HalfDuplex)]
|
||||
);
|
||||
assert!(call.transmit_squelched());
|
||||
assert!(
|
||||
call.receive_signal(Signal::from(CallMode::HalfDuplex))
|
||||
.is_empty()
|
||||
);
|
||||
call.disable_remote_mode_follow();
|
||||
assert!(
|
||||
call.receive_signal(Signal::from(CallMode::FullDuplex))
|
||||
.is_empty()
|
||||
);
|
||||
assert!(call.transmit_squelched());
|
||||
assert_eq!(
|
||||
call.switch_mode(CallMode::FullDuplex),
|
||||
vec![
|
||||
TelephonyAction::SendSignal(Signal::from(CallMode::FullDuplex)),
|
||||
TelephonyAction::SwitchMode(CallMode::FullDuplex),
|
||||
]
|
||||
);
|
||||
assert!(!call.transmit_squelched());
|
||||
assert!(call.switch_mode(CallMode::FullDuplex).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_mode_switch_requires_established_call() {
|
||||
let mut call = TelephonyCall::outgoing(None);
|
||||
assert!(call.switch_mode(CallMode::HalfDuplex).is_empty());
|
||||
assert_eq!(call.mode(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_signals_select_or_switch_profile_by_call_status() {
|
||||
let mut call = TelephonyCall::outgoing(None);
|
||||
|
||||
@@ -3,13 +3,9 @@ use rmpv::decode::read_value;
|
||||
use rmpv::encode::write_value;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::profile::{Profile, SignallingStatus};
|
||||
|
||||
pub const FIELD_SIGNALLING: u8 = 0x00;
|
||||
pub const FIELD_FRAMES: u8 = 0x01;
|
||||
|
||||
const PREFERRED_PROFILE_BASE: u32 = 0xFF;
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
#[error("msgpack decode error: {0}")]
|
||||
@@ -46,78 +42,7 @@ pub enum Error {
|
||||
UnknownCodec2Mode(u8),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum CodecKind {
|
||||
Raw = 0x00,
|
||||
Opus = 0x01,
|
||||
Codec2 = 0x02,
|
||||
Null = 0xFF,
|
||||
}
|
||||
|
||||
impl CodecKind {
|
||||
pub const fn wire_id(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
|
||||
pub const fn from_wire(id: u8) -> Result<Self, Error> {
|
||||
match id {
|
||||
0x00 => Ok(Self::Raw),
|
||||
0x01 => Ok(Self::Opus),
|
||||
0x02 => Ok(Self::Codec2),
|
||||
0xFF => Ok(Self::Null),
|
||||
other => Err(Error::UnknownCodec(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_transmittable(self) -> bool {
|
||||
!matches!(self, Self::Null)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Signal {
|
||||
Status(SignallingStatus),
|
||||
PreferredProfile(Profile),
|
||||
Raw(u32),
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
pub const fn wire_value(self) -> u32 {
|
||||
match self {
|
||||
Self::Status(status) => status.wire_value(),
|
||||
Self::PreferredProfile(profile) => PREFERRED_PROFILE_BASE + profile.wire_value(),
|
||||
Self::Raw(value) => value,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn from_wire(value: u32) -> Self {
|
||||
if let Some(status) = SignallingStatus::from_wire(value) {
|
||||
Self::Status(status)
|
||||
} else if value >= PREFERRED_PROFILE_BASE {
|
||||
let profile_value = value - PREFERRED_PROFILE_BASE;
|
||||
if let Some(profile) = Profile::from_wire(profile_value) {
|
||||
Self::PreferredProfile(profile)
|
||||
} else {
|
||||
Self::Raw(value)
|
||||
}
|
||||
} else {
|
||||
Self::Raw(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SignallingStatus> for Signal {
|
||||
fn from(value: SignallingStatus) -> Self {
|
||||
Self::Status(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Profile> for Signal {
|
||||
fn from(value: Profile) -> Self {
|
||||
Self::PreferredProfile(value)
|
||||
}
|
||||
}
|
||||
include!("shared/wire_types.rs");
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Frame {
|
||||
@@ -217,6 +142,10 @@ impl LxstPacket {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decode the first MessagePack value as an LXST packet. Trailing bytes are
|
||||
/// ignored, and repeated signalling/frame fields are concatenated.
|
||||
/// This allocating parser has no packet-size limit; bound input before use.
|
||||
/// Codec headers are checked, but encoded audio content is not decoded here.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
|
||||
let value = read_value(&mut &bytes[..]).map_err(|e| Error::Decode(e.to_string()))?;
|
||||
Self::from_value(value)
|
||||
@@ -361,49 +290,6 @@ impl RawFrameHeader {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum Codec2Mode {
|
||||
Mode700C = 0x00,
|
||||
Mode1200 = 0x01,
|
||||
Mode1300 = 0x02,
|
||||
Mode1400 = 0x03,
|
||||
Mode1600 = 0x04,
|
||||
Mode2400 = 0x05,
|
||||
Mode3200 = 0x06,
|
||||
}
|
||||
|
||||
impl Codec2Mode {
|
||||
pub const fn from_header(byte: u8) -> Result<Self, Error> {
|
||||
match byte {
|
||||
0x00 => Ok(Self::Mode700C),
|
||||
0x01 => Ok(Self::Mode1200),
|
||||
0x02 => Ok(Self::Mode1300),
|
||||
0x03 => Ok(Self::Mode1400),
|
||||
0x04 => Ok(Self::Mode1600),
|
||||
0x05 => Ok(Self::Mode2400),
|
||||
0x06 => Ok(Self::Mode3200),
|
||||
other => Err(Error::UnknownCodec2Mode(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn header(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
|
||||
pub const fn bitrate(self) -> u16 {
|
||||
match self {
|
||||
Self::Mode700C => 700,
|
||||
Self::Mode1200 => 1200,
|
||||
Self::Mode1300 => 1300,
|
||||
Self::Mode1400 => 1400,
|
||||
Self::Mode1600 => 1600,
|
||||
Self::Mode2400 => 2400,
|
||||
Self::Mode3200 => 3200,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
28afe918bca8941139ab60f9598427e7ae4741723a388b9907d9eb8c4c7d301b337931e7ee
|
||||
98b066163f47095412beadde8cb2f6a7c5df75e88d045d1e36272773afcb27b26be0d70dee
|
||||
98afe91a1c2d353ffebd6f412832c22d1cbd6c385de5967c27342e8cb160865b694472efee
|
||||
98b04dcf34ff809b86a63aae0319326095c1ab2eb02d7203ace62921c6b25a99e5e135ee
|
||||
98aca7b59d0483411f3e7a1882d257dfb0b842f92f88fa1cb0b3c920ea9ce7a1282031ee
|
||||
98afe918bca8941139ab60f9598427e7ae4741723a388b9907d9eb8c4c7d301b337931e7ee
|
||||
98b066f13f47095412beadde8cb2f6a7c5df75e88d045d1e36272773afcb27b26be0ee0d98
|
||||
e9afd71a1c2d353ffebd6f412832c22d1cbd6c385de5967c27342e8cb160865b694472efee
|
||||
98b04dcf34ff809b86a63aae0319326095c1ab2e002d7203ace62921c6b25a99e5e136ee
|
||||
98aca7b59d0483411f3e7a1882d257dfb0b842f92f88fa1cb0b3c920ea9ce7a1282031ee
|
||||
98afe918bca8941139ab60f9598427e7ae4741723a388b9907d9eb8c4c7d301b337931e7ee
|
||||
98b066f13f47095412beadde8cb2f6a7c5df75e88d045d1e36272773afcb27b26be0d70dee
|
||||
98afe91a1c2d353ffebd6f412832c22d1cbd6c385de5967c27342e8cb160865b694472efee
|
||||
98b04dcf34ff809b86a63aae0319326095c1ab2eb02d7203ace62921c6b25a99e5e135ee
|
||||
98aca7b59d0483411f3e7a1882d257dfb0b842f92f88fa1cb0b3c920ea9ce7a12820323d
|
||||
00000018bca8941139ab60f9598427e7ae4741723a388b9907d9eb8c4c7d302d337931e7ee
|
||||
@@ -120,8 +120,8 @@ fn raw_payload_errors_are_explicit() {
|
||||
|
||||
/// T3-5a finding: a SILK packet whose duration exceeds the profile's
|
||||
/// frame size used to clamp the resampler output but not its input,
|
||||
/// overrunning the buffer (vendor opus-rs silk/resampler.rs). libopus
|
||||
/// rejects such packets with OPUS_BUFFER_TOO_SMALL; the port now does too.
|
||||
/// overrunning the pure-Rust Opus resampler input buffer. libopus rejects such
|
||||
/// packets with OPUS_BUFFER_TOO_SMALL; the codec boundary must do so as well.
|
||||
#[test]
|
||||
fn opus_decoder_rejects_packet_longer_than_frame_size() {
|
||||
let mut decoder = OpusDecoderState::new(Profile::LatencyLow).expect("decoder");
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "lxst-embedded"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version = "1.87"
|
||||
publish.workspace = true
|
||||
description = "Bounded no_std LXST framing and authenticated PTT session policy"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { version = "2", default-features = false }
|
||||
lxst-codec2 = { path = "../lxst-codec2", version = "0.4.0" }
|
||||
|
||||
[dev-dependencies]
|
||||
lxst-core = { path = "../lxst-core", version = "0.4.0" }
|
||||
@@ -0,0 +1,41 @@
|
||||
# Embedded LXST boundary
|
||||
|
||||
`no_std`, allocation-free MessagePack framing, call policy, native Codec2 packet
|
||||
adaptation and a three-frame arrival-order queue. It supplies no threads, audio
|
||||
drivers, identities, transport, storage or global state.
|
||||
|
||||
Profile tables, wire identifiers, native packet aggregation and call transitions
|
||||
are compiled directly from the shared sources in `lxst-core/src/shared`. The
|
||||
host `TelephonyCall` API retains its allocating return values as a facade over
|
||||
the same fixed action list. Preserve this shared source layout in source bundles;
|
||||
these unpublished workspace crates are built from the complete repository.
|
||||
|
||||
`wire::Packet` borrows validated input with fixed ceilings (512 packet bytes,
|
||||
eight signals, four frames, 256 bytes per encoded frame including its codec
|
||||
identifier). It rejects duplicate signal/media fields, trailing data, excessive
|
||||
nesting and oversized declared containers. Unknown
|
||||
metadata is skipped within those limits. `wire::encode` matches the full Rust
|
||||
encoder's canonical MessagePack forms and validates before writing output.
|
||||
The negotiated Reticulum Link MDU can be smaller than the parser ceiling; the
|
||||
embedding transport must enforce its exact current MDU before sending.
|
||||
|
||||
`Session` wraps the shared transitions with verified-peer, local acceptance,
|
||||
audio-readiness, profile and PTT gates. The embedding Link owner alone calls
|
||||
`peer_verified`, after checking the exact identity and interface incarnation.
|
||||
Opening or answering never starts capture. Only a fresh Talk press can start it;
|
||||
release, timeout, reconfiguration and teardown stop it. Input edges and worker
|
||||
completions must carry session/view generations; audio configuration completions
|
||||
also carry `audio_generation`. Capability sets express previously qualified
|
||||
local codec/route budgets, not peer capabilities or an extension to LXST.
|
||||
|
||||
Unsupported preferences receive one supported suggestion with a deadline;
|
||||
repeated unsupported preferences close the session. Local PTT does not grant a
|
||||
remote floor: while capturing, conflicting receive audio is discarded. The
|
||||
queue uses local expiry times; it cannot infer a sender timestamp, recover packet
|
||||
order, claim delivery or route speech through LXMF propagation.
|
||||
|
||||
The native `Codec2Backend` implementation borrows a codec initialized in final
|
||||
storage. It never moves a large codec state onto the task stack. Native
|
||||
700C/1600/3200 implement standard ULBW/VLBW/LBW; `ProfileSet::CODEC2` includes
|
||||
all three. Embedders must restrict this set to the actual route and device
|
||||
budget. Opus requires a separate backend and device qualification.
|
||||
@@ -0,0 +1,2 @@
|
||||
# Keep lint suggestions compatible with the standalone MCU compiler floor.
|
||||
msrv = "1.87"
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Allocation-free LXST wire/session boundary for constrained clients.
|
||||
//! Shared profile, wire identifiers and telephony transitions come directly from
|
||||
//! lxst-core. Authentication, permissions, audio devices and routing are owned by
|
||||
//! the embedding runtime; parsing bytes never establishes a trusted identity.
|
||||
#![no_std]
|
||||
|
||||
#[path = "../../lxst-core/src/shared/actions.rs"]
|
||||
mod actions;
|
||||
#[path = "../../lxst-core/src/shared/telephony.rs"]
|
||||
mod call_state;
|
||||
#[path = "../../lxst-core/src/shared/profile.rs"]
|
||||
mod profile;
|
||||
pub mod wire;
|
||||
|
||||
pub use actions::Actions;
|
||||
pub use call_state::CallState;
|
||||
#[path = "../../lxst-core/src/shared/call_types.rs"]
|
||||
mod call_types;
|
||||
pub use call_types::{CallRole, TelephonyAction};
|
||||
pub use profile::{AudioCodec, CallMode, OpusApplication, OpusProfile, Profile, SignallingStatus};
|
||||
pub use wire::{Codec2Mode, CodecKind, Signal};
|
||||
|
||||
#[path = "../../lxst-core/src/shared/codec2.rs"]
|
||||
mod codec2;
|
||||
pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError};
|
||||
mod session;
|
||||
pub use session::{
|
||||
CallTimes, ConfigError, EndReason, Event, Events, ProfileSet, Session, SessionConfig,
|
||||
};
|
||||
|
||||
impl Codec2Backend for &mut lxst_codec2::Codec {
|
||||
type Error = lxst_codec2::Error;
|
||||
fn mode(&self) -> Codec2Mode {
|
||||
match lxst_codec2::Codec::mode(self) {
|
||||
lxst_codec2::Mode::Rate1600 => Codec2Mode::Mode1600,
|
||||
lxst_codec2::Mode::Rate3200 => Codec2Mode::Mode3200,
|
||||
lxst_codec2::Mode::Rate700C => Codec2Mode::Mode700C,
|
||||
}
|
||||
}
|
||||
fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error> {
|
||||
self.encode(pcm, encoded)
|
||||
}
|
||||
fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error> {
|
||||
self.decode(encoded, pcm)
|
||||
}
|
||||
}
|
||||
|
||||
mod queue;
|
||||
pub use queue::{MediaQueue, QueueError};
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Local arrival/capture deadlines, not a claim about end-to-end packet age.
|
||||
//! LXST has no sequence/timestamp in its baseline wire contract.
|
||||
use crate::wire::MAX_FRAME_BYTES;
|
||||
const CAPACITY: usize = 3;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QueueError {
|
||||
EmptyPayload,
|
||||
PayloadTooLarge,
|
||||
Expired,
|
||||
OutputCapacity,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Slot {
|
||||
bytes: [u8; MAX_FRAME_BYTES],
|
||||
length: usize,
|
||||
expires: u64,
|
||||
generation: u32,
|
||||
}
|
||||
impl Slot {
|
||||
const EMPTY: Self = Self {
|
||||
bytes: [0; MAX_FRAME_BYTES],
|
||||
length: 0,
|
||||
expires: 0,
|
||||
generation: 0,
|
||||
};
|
||||
}
|
||||
/// Three arrival-ordered encoded frames. Pressure drops the oldest frame;
|
||||
/// draining discards expired and stale-generation frames before returning data.
|
||||
pub struct MediaQueue {
|
||||
slots: [Slot; CAPACITY],
|
||||
head: usize,
|
||||
length: usize,
|
||||
dropped: u64,
|
||||
}
|
||||
impl Default for MediaQueue {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl MediaQueue {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
slots: [Slot::EMPTY; CAPACITY],
|
||||
head: 0,
|
||||
length: 0,
|
||||
dropped: 0,
|
||||
}
|
||||
}
|
||||
pub const fn len(&self) -> usize {
|
||||
self.length
|
||||
}
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.length == 0
|
||||
}
|
||||
pub const fn dropped(&self) -> u64 {
|
||||
self.dropped
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.slots.fill(Slot::EMPTY);
|
||||
self.head = 0;
|
||||
self.length = 0;
|
||||
}
|
||||
fn retire(&mut self, dropped: bool) {
|
||||
self.slots[self.head] = Slot::EMPTY;
|
||||
self.head = (self.head + 1) % CAPACITY;
|
||||
self.length -= 1;
|
||||
if dropped {
|
||||
self.dropped = self.dropped.saturating_add(1);
|
||||
}
|
||||
}
|
||||
pub fn push(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
generation: u32,
|
||||
now_ms: u64,
|
||||
expires_ms: u64,
|
||||
) -> Result<(), QueueError> {
|
||||
if bytes.is_empty() {
|
||||
return Err(QueueError::EmptyPayload);
|
||||
}
|
||||
if bytes.len() > MAX_FRAME_BYTES {
|
||||
return Err(QueueError::PayloadTooLarge);
|
||||
}
|
||||
if expires_ms <= now_ms {
|
||||
return Err(QueueError::Expired);
|
||||
}
|
||||
if self.length == CAPACITY {
|
||||
self.retire(true);
|
||||
}
|
||||
let slot = &mut self.slots[(self.head + self.length) % CAPACITY];
|
||||
slot.bytes[..bytes.len()].copy_from_slice(bytes);
|
||||
slot.length = bytes.len();
|
||||
slot.expires = expires_ms;
|
||||
slot.generation = generation;
|
||||
self.length += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub fn pop(
|
||||
&mut self,
|
||||
now_ms: u64,
|
||||
generation: u32,
|
||||
output: &mut [u8],
|
||||
) -> Result<Option<usize>, QueueError> {
|
||||
while self.length != 0 {
|
||||
let slot = &self.slots[self.head];
|
||||
if slot.expires <= now_ms || slot.generation != generation {
|
||||
self.retire(true);
|
||||
continue;
|
||||
}
|
||||
if output.len() < slot.length {
|
||||
return Err(QueueError::OutputCapacity);
|
||||
}
|
||||
let length = slot.length;
|
||||
output[..length].copy_from_slice(&slot.bytes[..length]);
|
||||
self.retire(false);
|
||||
return Ok(Some(length));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
//! Local admission and microphone policy around the trusted call transitions.
|
||||
//! No extra wire extension, turn token or directional capability is invented.
|
||||
use crate::{
|
||||
Actions, CallMode, CallRole, CallState, Profile, Signal, SignallingStatus, TelephonyAction,
|
||||
};
|
||||
|
||||
/// Local limit for an incoming link to identify its caller; Python has no counterpart.
|
||||
const SETUP_MS: u64 = 30_000;
|
||||
const PROFILE_MS: u64 = 5_000;
|
||||
pub const TALK_LIMIT_MS: u64 = 30_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ProfileSet(u8);
|
||||
impl ProfileSet {
|
||||
pub const CODEC2: Self = Self(0b0000_0111);
|
||||
pub const OPUS_MEDIUM: Self = Self(0b0000_1000);
|
||||
pub const fn contains(self, profile: Profile) -> bool {
|
||||
self.0 & (1 << (profile.wire_value() / 16 - 1)) != 0
|
||||
}
|
||||
pub const fn union(self, other: Self) -> Self {
|
||||
Self(self.0 | other.0)
|
||||
}
|
||||
pub const fn only(profile: Profile) -> Self {
|
||||
Self(1 << (profile.wire_value() / 16 - 1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Call setup limits in milliseconds; the defaults are Python `Telephone`'s.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CallTimes {
|
||||
/// Python `CONNECT_TIME` (`set_connect_timeout`): the callee must ring within this time of the call start.
|
||||
pub connect_ms: u64,
|
||||
/// Python `wait_time`, measured from the start of the outgoing call.
|
||||
pub wait_ms: u64,
|
||||
/// Python `ring_time`.
|
||||
pub ring_ms: u64,
|
||||
}
|
||||
impl CallTimes {
|
||||
pub const DEFAULT: Self = Self {
|
||||
connect_ms: 5_000,
|
||||
wait_ms: 70_000,
|
||||
ring_ms: 60_000,
|
||||
};
|
||||
}
|
||||
impl Default for CallTimes {
|
||||
fn default() -> Self {
|
||||
Self::DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct SessionConfig {
|
||||
/// The embedder must qualify each selected codec and route before admission.
|
||||
pub allowed: ProfileSet,
|
||||
pub preferred: Profile,
|
||||
pub capture: bool,
|
||||
pub playback: bool,
|
||||
pub times: CallTimes,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ConfigError {
|
||||
NoAudioDirection,
|
||||
UnsupportedPreferredProfile,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EndReason {
|
||||
Local,
|
||||
Remote,
|
||||
Rejected,
|
||||
Busy,
|
||||
Timeout,
|
||||
ProfileUnsupported,
|
||||
AudioUnavailable,
|
||||
RouteLost,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Event {
|
||||
Transition(TelephonyAction),
|
||||
Capture(bool),
|
||||
FlushMedia,
|
||||
Ended(EndReason),
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Events {
|
||||
items: [Event; 8],
|
||||
length: usize,
|
||||
}
|
||||
impl Events {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
items: [const { Event::FlushMedia }; 8],
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
fn push(&mut self, event: Event) {
|
||||
assert!(self.length < self.items.len());
|
||||
self.items[self.length] = event;
|
||||
self.length += 1;
|
||||
}
|
||||
fn transitions(&mut self, actions: Actions) {
|
||||
for action in actions.as_slice() {
|
||||
self.push(Event::Transition(action.clone()));
|
||||
}
|
||||
}
|
||||
pub fn as_slice(&self) -> &[Event] {
|
||||
&self.items[..self.length]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Session {
|
||||
call: CallState,
|
||||
config: SessionConfig,
|
||||
verified: bool,
|
||||
linked: bool,
|
||||
ready: bool,
|
||||
transmitting: bool,
|
||||
input_down: bool,
|
||||
audio_generation: u32,
|
||||
ended: Option<EndReason>,
|
||||
deadline: u64,
|
||||
connect_deadline: Option<u64>,
|
||||
talk_started: u64,
|
||||
suggested: bool,
|
||||
profile_deadline: Option<u64>,
|
||||
}
|
||||
impl Session {
|
||||
pub fn new(role: CallRole, config: SessionConfig, now_ms: u64) -> Result<Self, ConfigError> {
|
||||
if !config.capture && !config.playback {
|
||||
return Err(ConfigError::NoAudioDirection);
|
||||
}
|
||||
if !config.allowed.contains(config.preferred) {
|
||||
return Err(ConfigError::UnsupportedPreferredProfile);
|
||||
}
|
||||
let mut call = match role {
|
||||
CallRole::Incoming => CallState::incoming(),
|
||||
CallRole::Outgoing => CallState::outgoing(Some(config.preferred)),
|
||||
};
|
||||
call.switch_profile(config.preferred);
|
||||
Ok(Self {
|
||||
call,
|
||||
config,
|
||||
verified: false,
|
||||
linked: false,
|
||||
ready: false,
|
||||
transmitting: false,
|
||||
input_down: false,
|
||||
audio_generation: 1,
|
||||
ended: None,
|
||||
deadline: now_ms.saturating_add(match role {
|
||||
CallRole::Incoming => SETUP_MS,
|
||||
CallRole::Outgoing => config.times.wait_ms,
|
||||
}),
|
||||
connect_deadline: match role {
|
||||
CallRole::Incoming => None,
|
||||
CallRole::Outgoing => Some(now_ms.saturating_add(config.times.connect_ms)),
|
||||
},
|
||||
talk_started: 0,
|
||||
suggested: false,
|
||||
profile_deadline: None,
|
||||
})
|
||||
}
|
||||
pub const fn status(&self) -> SignallingStatus {
|
||||
self.call.status()
|
||||
}
|
||||
pub const fn profile(&self) -> Option<Profile> {
|
||||
self.call.profile()
|
||||
}
|
||||
pub const fn mode(&self) -> Option<CallMode> {
|
||||
self.call.mode()
|
||||
}
|
||||
pub const fn ended(&self) -> Option<EndReason> {
|
||||
self.ended
|
||||
}
|
||||
pub const fn audio_generation(&self) -> u32 {
|
||||
self.audio_generation
|
||||
}
|
||||
pub const fn transmitting(&self) -> bool {
|
||||
self.transmitting
|
||||
}
|
||||
pub fn media_ready(&self) -> bool {
|
||||
self.ended.is_none()
|
||||
&& self.linked
|
||||
&& self.verified
|
||||
&& self.ready
|
||||
&& self.profile_deadline.is_none()
|
||||
&& self.call.status() == SignallingStatus::Established
|
||||
&& self.call.audio_started()
|
||||
}
|
||||
pub fn playback_allowed(&self) -> bool {
|
||||
self.media_ready() && self.config.playback && !self.transmitting
|
||||
}
|
||||
|
||||
pub fn link_established(&mut self) -> Events {
|
||||
let mut events = Events::new();
|
||||
if self.ended.is_some() || self.linked {
|
||||
return events;
|
||||
}
|
||||
self.linked = true;
|
||||
if self.call.role() == CallRole::Incoming {
|
||||
events.transitions(CallState::incoming_link_established(false));
|
||||
}
|
||||
events
|
||||
}
|
||||
/// Call only after the Link owner verified the exact peer identity for this
|
||||
/// session and immutable route. Parsing a signal cannot invoke this authority.
|
||||
pub fn peer_verified(&mut self, now_ms: u64) -> Events {
|
||||
let mut events = Events::new();
|
||||
if self.ended.is_some() || !self.linked || self.verified {
|
||||
return events;
|
||||
}
|
||||
self.verified = true;
|
||||
if self.call.role() == CallRole::Incoming {
|
||||
self.deadline = now_ms.saturating_add(self.config.times.ring_ms);
|
||||
events.transitions(self.call.caller_identified(false, true));
|
||||
events.push(Event::Transition(TelephonyAction::SendSignal(
|
||||
self.config.preferred.into(),
|
||||
)));
|
||||
}
|
||||
events
|
||||
}
|
||||
pub fn answer(&mut self, _now_ms: u64) -> Events {
|
||||
let mut events = Events::new();
|
||||
if self.ended.is_some()
|
||||
|| !self.verified
|
||||
|| self.call.role() != CallRole::Incoming
|
||||
|| self.call.status() != SignallingStatus::Ringing
|
||||
{
|
||||
return events;
|
||||
}
|
||||
events.transitions(self.call.answer());
|
||||
events
|
||||
}
|
||||
pub fn receive_signal(&mut self, signal: Signal, now_ms: u64) -> Events {
|
||||
let mut events = Events::new();
|
||||
if self.ended.is_some() || !self.linked || !self.verified {
|
||||
return events;
|
||||
}
|
||||
if let Signal::PreferredProfile(profile) = signal {
|
||||
if !self.config.allowed.contains(profile) {
|
||||
if self.suggested {
|
||||
return self.end(EndReason::ProfileUnsupported);
|
||||
}
|
||||
self.suggested = true;
|
||||
self.profile_deadline = Some(now_ms.saturating_add(PROFILE_MS));
|
||||
self.stop_capture(&mut events);
|
||||
events.push(Event::FlushMedia);
|
||||
events.push(Event::Transition(TelephonyAction::SendSignal(
|
||||
self.call.profile().unwrap_or(self.config.preferred).into(),
|
||||
)));
|
||||
return events;
|
||||
}
|
||||
self.profile_deadline = None;
|
||||
self.suggested = false;
|
||||
if self.call.profile() != Some(profile) {
|
||||
self.stop_capture(&mut events);
|
||||
self.ready = false;
|
||||
self.audio_generation = self.audio_generation.wrapping_add(1);
|
||||
events.push(Event::FlushMedia);
|
||||
// Our incoming preference can cross the caller's offer. Confirm
|
||||
// the adopted profile so the caller does not retain our older
|
||||
// preference while we start using its offer. Only the incoming
|
||||
// side echoes changes; duplicate offers cannot create a loop.
|
||||
if self.call.role() == CallRole::Incoming {
|
||||
events.push(Event::Transition(TelephonyAction::SendSignal(
|
||||
profile.into(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Signal::Status(status) = signal {
|
||||
match status {
|
||||
SignallingStatus::Busy => return self.end(EndReason::Busy),
|
||||
SignallingStatus::Rejected => return self.end(EndReason::Rejected),
|
||||
SignallingStatus::Calling => return events,
|
||||
_ => {}
|
||||
}
|
||||
let current = self.call.status();
|
||||
let allowed = match self.call.role() {
|
||||
CallRole::Incoming => {
|
||||
self.call.answered() && status == SignallingStatus::Established
|
||||
}
|
||||
CallRole::Outgoing => match status {
|
||||
SignallingStatus::Available => matches!(
|
||||
current,
|
||||
SignallingStatus::Calling | SignallingStatus::Available
|
||||
),
|
||||
SignallingStatus::Ringing => matches!(
|
||||
current,
|
||||
SignallingStatus::Available | SignallingStatus::Ringing
|
||||
),
|
||||
SignallingStatus::Connecting => matches!(
|
||||
current,
|
||||
SignallingStatus::Ringing
|
||||
| SignallingStatus::Connecting
|
||||
| SignallingStatus::Established
|
||||
),
|
||||
SignallingStatus::Established => matches!(
|
||||
current,
|
||||
SignallingStatus::Connecting | SignallingStatus::Established
|
||||
),
|
||||
_ => false,
|
||||
},
|
||||
};
|
||||
if !allowed {
|
||||
return events;
|
||||
}
|
||||
if status == SignallingStatus::Ringing {
|
||||
self.connect_deadline = None;
|
||||
}
|
||||
}
|
||||
events.transitions(self.call.receive_signal(signal));
|
||||
events
|
||||
}
|
||||
/// Confirm adoption of the current suggested profile using authenticated media.
|
||||
/// The embedder must first validate codec, mode and complete native packet size.
|
||||
/// This clears a pending profile deadline only; it does not change the
|
||||
/// selected profile, open audio, answer a call or start the microphone.
|
||||
pub fn receive_profile_media(&mut self, profile: Profile, now_ms: u64) -> Events {
|
||||
if self.ended.is_none()
|
||||
&& self.linked
|
||||
&& self.verified
|
||||
&& self.call.status() == SignallingStatus::Established
|
||||
&& self.call.profile() == Some(profile)
|
||||
&& self.config.allowed.contains(profile)
|
||||
&& self
|
||||
.profile_deadline
|
||||
.is_some_and(|deadline| now_ms < deadline)
|
||||
{
|
||||
self.profile_deadline = None;
|
||||
}
|
||||
Events::new()
|
||||
}
|
||||
/// A successfully configured device/codec is necessary but never starts capture.
|
||||
pub fn audio_ready(&mut self, generation: u32, success: bool) -> Events {
|
||||
if self.ended.is_some() || generation != self.audio_generation {
|
||||
return Events::new();
|
||||
}
|
||||
if !success {
|
||||
return self.end(EndReason::AudioUnavailable);
|
||||
}
|
||||
self.ready = true;
|
||||
Events::new()
|
||||
}
|
||||
/// The embedder must fence input edges by session and view generation.
|
||||
pub fn set_transmitting(&mut self, pressed: bool, now_ms: u64) -> Events {
|
||||
let mut events = Events::new();
|
||||
if !pressed {
|
||||
self.input_down = false;
|
||||
self.stop_capture(&mut events);
|
||||
events.push(Event::FlushMedia);
|
||||
} else if !self.input_down {
|
||||
self.input_down = true;
|
||||
if !self.media_ready() || !self.config.capture {
|
||||
return events;
|
||||
}
|
||||
self.transmitting = true;
|
||||
self.talk_started = now_ms;
|
||||
events.push(Event::FlushMedia);
|
||||
events.push(Event::Capture(true));
|
||||
}
|
||||
events
|
||||
}
|
||||
fn stop_capture(&mut self, events: &mut Events) {
|
||||
if self.transmitting {
|
||||
self.transmitting = false;
|
||||
events.push(Event::Capture(false));
|
||||
}
|
||||
}
|
||||
pub fn tick(&mut self, now_ms: u64) -> Events {
|
||||
let mut events = Events::new();
|
||||
if self.ended.is_some() {
|
||||
return events;
|
||||
}
|
||||
if self
|
||||
.profile_deadline
|
||||
.is_some_and(|deadline| now_ms >= deadline)
|
||||
{
|
||||
return self.end(EndReason::ProfileUnsupported);
|
||||
}
|
||||
if self.status() != SignallingStatus::Established && now_ms >= self.deadline {
|
||||
return self.end(EndReason::Timeout);
|
||||
}
|
||||
if self
|
||||
.connect_deadline
|
||||
.is_some_and(|deadline| now_ms >= deadline)
|
||||
{
|
||||
return self.end(EndReason::Timeout);
|
||||
}
|
||||
if self.transmitting && now_ms.saturating_sub(self.talk_started) >= TALK_LIMIT_MS {
|
||||
self.stop_capture(&mut events);
|
||||
events.push(Event::FlushMedia);
|
||||
}
|
||||
events
|
||||
}
|
||||
pub fn end(&mut self, reason: EndReason) -> Events {
|
||||
let mut events = Events::new();
|
||||
if self.ended.is_some() {
|
||||
return events;
|
||||
}
|
||||
self.stop_capture(&mut events);
|
||||
events.push(Event::FlushMedia);
|
||||
self.ready = false;
|
||||
self.ended = Some(reason);
|
||||
events.transitions(self.call.hangup(reason == EndReason::Timeout));
|
||||
events.push(Event::Ended(reason));
|
||||
events
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! Borrowed, bounded MessagePack adaptation of lxst-core::wire.
|
||||
include!("../../lxst-core/src/shared/wire_types.rs");
|
||||
|
||||
pub const MAX_PACKET_BYTES: usize = 512;
|
||||
pub const MAX_FRAME_BYTES: usize = 256;
|
||||
pub const MAX_SIGNALS: usize = 8;
|
||||
pub const MAX_FRAMES: usize = 4;
|
||||
const MAX_FIELDS: usize = 16;
|
||||
const MAX_DEPTH: usize = 8;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Truncated,
|
||||
Shape,
|
||||
Limit,
|
||||
DuplicateField,
|
||||
TrailingData,
|
||||
OutputCapacity,
|
||||
UnknownCodec(u8),
|
||||
UnknownCodec2Mode(u8),
|
||||
EmptyFrame,
|
||||
NonTransmittableCodec(CodecKind),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Frame<'a> {
|
||||
pub codec: CodecKind,
|
||||
pub payload: &'a [u8],
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Packet<'a> {
|
||||
signals: [Signal; MAX_SIGNALS],
|
||||
signal_count: usize,
|
||||
frames: [Frame<'a>; MAX_FRAMES],
|
||||
frame_count: usize,
|
||||
}
|
||||
impl<'a> Packet<'a> {
|
||||
pub fn signals(&self) -> &[Signal] {
|
||||
&self.signals[..self.signal_count]
|
||||
}
|
||||
pub fn frames(&self) -> &[Frame<'a>] {
|
||||
&self.frames[..self.frame_count]
|
||||
}
|
||||
|
||||
/// Borrow one complete packet within the fixed size and item-count limits.
|
||||
/// Trailing bytes and duplicate signalling/frame fields are rejected.
|
||||
/// Unknown fields are skipped within bounded depth; their duplicates are
|
||||
/// not tracked. Codec payload contents require validation by the embedder.
|
||||
pub fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
|
||||
if bytes.len() > MAX_PACKET_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let mut reader = Reader { bytes, offset: 0 };
|
||||
let fields = reader.map_len()?;
|
||||
if fields > MAX_FIELDS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let mut packet = Self {
|
||||
signals: [Signal::Raw(0); MAX_SIGNALS],
|
||||
signal_count: 0,
|
||||
frames: [Frame {
|
||||
codec: CodecKind::Null,
|
||||
payload: &[],
|
||||
}; MAX_FRAMES],
|
||||
frame_count: 0,
|
||||
};
|
||||
let mut seen = 0;
|
||||
for _ in 0..fields {
|
||||
let key = reader.uint()?;
|
||||
if key > u8::MAX as u64 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
match key {
|
||||
0 => {
|
||||
if seen & 1 != 0 {
|
||||
return Err(Error::DuplicateField);
|
||||
}
|
||||
seen |= 1;
|
||||
let count = reader.array_len()?.unwrap_or(1);
|
||||
if count > MAX_SIGNALS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for signal in &mut packet.signals[..count] {
|
||||
let raw = u32::try_from(reader.uint()?).map_err(|_| Error::Shape)?;
|
||||
*signal = Signal::from_wire(raw);
|
||||
}
|
||||
packet.signal_count = count;
|
||||
}
|
||||
1 => {
|
||||
if seen & 2 != 0 {
|
||||
return Err(Error::DuplicateField);
|
||||
}
|
||||
seen |= 2;
|
||||
let count = reader.array_len()?.unwrap_or(1);
|
||||
if count > MAX_FRAMES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
for frame in &mut packet.frames[..count] {
|
||||
let bytes = reader.binary()?;
|
||||
let (&codec, payload) = bytes.split_first().ok_or(Error::EmptyFrame)?;
|
||||
if bytes.len() > MAX_FRAME_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let codec = CodecKind::from_wire(codec)?;
|
||||
if !codec.is_transmittable() {
|
||||
return Err(Error::NonTransmittableCodec(codec));
|
||||
}
|
||||
*frame = Frame { codec, payload };
|
||||
}
|
||||
packet.frame_count = count;
|
||||
}
|
||||
_ => reader.skip(0)?,
|
||||
}
|
||||
}
|
||||
if reader.offset != bytes.len() {
|
||||
return Err(Error::TrailingData);
|
||||
}
|
||||
Ok(packet)
|
||||
}
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
offset: usize,
|
||||
}
|
||||
impl<'a> Reader<'a> {
|
||||
fn take(&mut self, count: usize) -> Result<&'a [u8], Error> {
|
||||
let end = self.offset.checked_add(count).ok_or(Error::Limit)?;
|
||||
let value = self.bytes.get(self.offset..end).ok_or(Error::Truncated)?;
|
||||
self.offset = end;
|
||||
Ok(value)
|
||||
}
|
||||
fn byte(&mut self) -> Result<u8, Error> {
|
||||
Ok(self.take(1)?[0])
|
||||
}
|
||||
fn number(&mut self, size: usize) -> Result<u64, Error> {
|
||||
Ok(self
|
||||
.take(size)?
|
||||
.iter()
|
||||
.fold(0, |value, byte| value << 8 | u64::from(*byte)))
|
||||
}
|
||||
fn uint(&mut self) -> Result<u64, Error> {
|
||||
match self.byte()? {
|
||||
value @ 0..=127 => Ok(u64::from(value)),
|
||||
0xcc => self.number(1),
|
||||
0xcd => self.number(2),
|
||||
0xce => self.number(4),
|
||||
0xcf => self.number(8),
|
||||
tag @ 0xd0..=0xd3 => {
|
||||
let size = 1 << (tag - 0xd0);
|
||||
let value = self.number(size)?;
|
||||
if value >> (size * 8 - 1) != 0 {
|
||||
Err(Error::Shape)
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::Shape),
|
||||
}
|
||||
}
|
||||
fn map_len(&mut self) -> Result<usize, Error> {
|
||||
match self.byte()? {
|
||||
tag @ 0x80..=0x8f => Ok(usize::from(tag & 15)),
|
||||
0xde => Ok(self.number(2)? as usize),
|
||||
0xdf => usize::try_from(self.number(4)?).map_err(|_| Error::Limit),
|
||||
_ => Err(Error::Shape),
|
||||
}
|
||||
}
|
||||
fn array_len(&mut self) -> Result<Option<usize>, Error> {
|
||||
let tag = *self.bytes.get(self.offset).ok_or(Error::Truncated)?;
|
||||
let count = match tag {
|
||||
0x90..=0x9f => {
|
||||
self.offset += 1;
|
||||
usize::from(tag & 15)
|
||||
}
|
||||
0xdc => {
|
||||
self.offset += 1;
|
||||
self.number(2)? as usize
|
||||
}
|
||||
0xdd => {
|
||||
self.offset += 1;
|
||||
usize::try_from(self.number(4)?).map_err(|_| Error::Limit)?
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(count))
|
||||
}
|
||||
fn binary(&mut self) -> Result<&'a [u8], Error> {
|
||||
let count = match self.byte()? {
|
||||
0xc4 => self.number(1)?,
|
||||
0xc5 => self.number(2)?,
|
||||
0xc6 => self.number(4)?,
|
||||
_ => return Err(Error::Shape),
|
||||
};
|
||||
self.take(usize::try_from(count).map_err(|_| Error::Limit)?)
|
||||
}
|
||||
fn skip(&mut self, depth: usize) -> Result<(), Error> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let tag = self.byte()?;
|
||||
let (bytes, children) = match tag {
|
||||
0x00..=0x7f | 0xe0..=0xff | 0xc0 | 0xc2 | 0xc3 => (0, 0),
|
||||
0x80..=0x8f => (0, usize::from(tag & 15) * 2),
|
||||
0x90..=0x9f => (0, usize::from(tag & 15)),
|
||||
0xa0..=0xbf => (usize::from(tag & 31), 0),
|
||||
0xcc | 0xd0 => (1, 0),
|
||||
0xcd | 0xd1 => (2, 0),
|
||||
0xce | 0xd2 | 0xca => (4, 0),
|
||||
0xcf | 0xd3 | 0xcb => (8, 0),
|
||||
0xc4 | 0xd9 => (self.number(1)? as usize, 0),
|
||||
0xc5 | 0xda => (self.number(2)? as usize, 0),
|
||||
0xc6 | 0xdb => (
|
||||
usize::try_from(self.number(4)?).map_err(|_| Error::Limit)?,
|
||||
0,
|
||||
),
|
||||
0xdc..=0xdf => {
|
||||
let size = if tag & 1 == 0 { 2 } else { 4 };
|
||||
let count = usize::try_from(self.number(size)?).map_err(|_| Error::Limit)?;
|
||||
let children = count
|
||||
.checked_mul(if tag >= 0xde { 2 } else { 1 })
|
||||
.ok_or(Error::Limit)?;
|
||||
(0, children)
|
||||
}
|
||||
0xd4..=0xd8 => (1 + (1 << (tag - 0xd4)), 0),
|
||||
0xc7..=0xc9 => {
|
||||
let count =
|
||||
usize::try_from(self.number(1 << (tag - 0xc7))?).map_err(|_| Error::Limit)?;
|
||||
(count.checked_add(1).ok_or(Error::Limit)?, 0)
|
||||
}
|
||||
_ => return Err(Error::Shape),
|
||||
};
|
||||
if children > MAX_PACKET_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
self.take(bytes)?;
|
||||
for _ in 0..children {
|
||||
self.skip(depth + 1)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn uint_bytes(value: u32) -> usize {
|
||||
match value {
|
||||
0..=127 => 1,
|
||||
128..=255 => 2,
|
||||
256..=65535 => 3,
|
||||
_ => 5,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode the same canonical map/array/binary forms as the full Rust codec.
|
||||
/// Validation precedes all writes; malformed shape/capacity leaves output intact.
|
||||
pub fn encode(signals: &[Signal], frames: &[Frame<'_>], output: &mut [u8]) -> Result<usize, Error> {
|
||||
if signals.len() > MAX_SIGNALS || frames.len() > MAX_FRAMES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let mut size = 1;
|
||||
if !signals.is_empty() {
|
||||
size += 2 + signals
|
||||
.iter()
|
||||
.map(|v| uint_bytes(v.wire_value()))
|
||||
.sum::<usize>();
|
||||
}
|
||||
if !frames.is_empty() {
|
||||
size += 1 + usize::from(frames.len() > 1);
|
||||
for frame in frames {
|
||||
if !frame.codec.is_transmittable() {
|
||||
return Err(Error::NonTransmittableCodec(frame.codec));
|
||||
}
|
||||
if frame.payload.len() >= MAX_FRAME_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let length = frame.payload.len() + 1;
|
||||
size += length + if length <= 255 { 2 } else { 3 };
|
||||
}
|
||||
}
|
||||
if size > MAX_PACKET_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
if output.len() < size {
|
||||
return Err(Error::OutputCapacity);
|
||||
}
|
||||
let mut writer = Writer { output, offset: 0 };
|
||||
writer.byte(0x80 | (u8::from(!signals.is_empty()) + u8::from(!frames.is_empty())));
|
||||
if !signals.is_empty() {
|
||||
writer.byte(0);
|
||||
writer.byte(0x90 | signals.len() as u8);
|
||||
for signal in signals {
|
||||
writer.uint(signal.wire_value());
|
||||
}
|
||||
}
|
||||
if !frames.is_empty() {
|
||||
writer.byte(1);
|
||||
if frames.len() > 1 {
|
||||
writer.byte(0x90 | frames.len() as u8);
|
||||
}
|
||||
for frame in frames {
|
||||
let length = frame.payload.len() + 1;
|
||||
if length <= 255 {
|
||||
writer.byte(0xc4);
|
||||
writer.byte(length as u8);
|
||||
} else {
|
||||
writer.byte(0xc5);
|
||||
writer.bytes(&(length as u16).to_be_bytes());
|
||||
}
|
||||
writer.byte(frame.codec.wire_id());
|
||||
writer.bytes(frame.payload);
|
||||
}
|
||||
}
|
||||
debug_assert_eq!(writer.offset, size);
|
||||
Ok(size)
|
||||
}
|
||||
struct Writer<'a> {
|
||||
output: &'a mut [u8],
|
||||
offset: usize,
|
||||
}
|
||||
impl Writer<'_> {
|
||||
fn byte(&mut self, value: u8) {
|
||||
self.output[self.offset] = value;
|
||||
self.offset += 1;
|
||||
}
|
||||
fn bytes(&mut self, bytes: &[u8]) {
|
||||
self.output[self.offset..self.offset + bytes.len()].copy_from_slice(bytes);
|
||||
self.offset += bytes.len();
|
||||
}
|
||||
fn uint(&mut self, value: u32) {
|
||||
match value {
|
||||
0..=127 => self.byte(value as u8),
|
||||
128..=255 => {
|
||||
self.byte(0xcc);
|
||||
self.byte(value as u8);
|
||||
}
|
||||
256..=65535 => {
|
||||
self.byte(0xcd);
|
||||
self.bytes(&(value as u16).to_be_bytes());
|
||||
}
|
||||
_ => {
|
||||
self.byte(0xce);
|
||||
self.bytes(&value.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use lxst_embedded::{Codec2PacketCodec, MediaQueue, Profile, QueueError};
|
||||
#[test]
|
||||
fn stalled_media_drops_old_frames_and_never_crosses_generations() {
|
||||
let mut queue = MediaQueue::new();
|
||||
for value in 1..=4 {
|
||||
queue.push(&[value, value], 7, 10, 100).unwrap();
|
||||
}
|
||||
assert_eq!(queue.len(), 3);
|
||||
assert_eq!(queue.dropped(), 1);
|
||||
let mut output = [0xa5; 8];
|
||||
assert_eq!(
|
||||
queue.pop(11, 7, &mut output[..1]),
|
||||
Err(QueueError::OutputCapacity)
|
||||
);
|
||||
assert_eq!(queue.len(), 3);
|
||||
assert_eq!(output, [0xa5; 8]);
|
||||
assert_eq!(queue.pop(12, 7, &mut output), Ok(Some(2)));
|
||||
assert_eq!(output[..2], [2, 2]);
|
||||
assert_eq!(queue.pop(100, 7, &mut output), Ok(None));
|
||||
assert_eq!(queue.dropped(), 3);
|
||||
queue.push(&[5], 7, 100, 110).unwrap();
|
||||
assert_eq!(queue.pop(101, 8, &mut output), Ok(None));
|
||||
assert_eq!(queue.push(&[6], 8, 110, 110), Err(QueueError::Expired));
|
||||
queue.push(&[7], 8, 120, 130).unwrap();
|
||||
queue.clear();
|
||||
assert_eq!(queue.pop(121, 8, &mut output), Ok(None));
|
||||
assert_eq!(queue.dropped(), 4);
|
||||
}
|
||||
#[test]
|
||||
fn borrowed_native_backend_runs_shared_packet_adapter_without_state_moves() {
|
||||
for (mode, profile, bytes, samples) in [
|
||||
(
|
||||
lxst_codec2::Mode::Rate700C,
|
||||
Profile::BandwidthUltraLow,
|
||||
41,
|
||||
3200,
|
||||
),
|
||||
(
|
||||
lxst_codec2::Mode::Rate1600,
|
||||
Profile::BandwidthVeryLow,
|
||||
65,
|
||||
2560,
|
||||
),
|
||||
(lxst_codec2::Mode::Rate3200, Profile::BandwidthLow, 81, 1600),
|
||||
] {
|
||||
let mut storage = Box::<lxst_codec2::Codec>::new_uninit();
|
||||
let native = lxst_codec2::Codec::initialise(&mut storage, mode);
|
||||
let mut codec = Codec2PacketCodec::new(profile, native).unwrap();
|
||||
let mut output = [0xa5; 90];
|
||||
let pcm = [0; 3200];
|
||||
assert_eq!(
|
||||
codec.encode_into(&pcm[..samples], &mut output).unwrap(),
|
||||
bytes
|
||||
);
|
||||
let mut decoded = [123; 3208];
|
||||
assert_eq!(
|
||||
codec.decode_into(&output[..bytes], &mut decoded).unwrap(),
|
||||
samples
|
||||
);
|
||||
assert!(decoded[samples..].iter().all(|v| *v == 123));
|
||||
assert!(output[bytes..].iter().all(|v| *v == 0xa5));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
use lxst_embedded::{
|
||||
CallMode, CallRole, CallState, CallTimes, EndReason, Event, Profile, ProfileSet, Session,
|
||||
SessionConfig, Signal, SignallingStatus as Status, TelephonyAction as Action,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn crossed_profile_offers_converge_before_media_without_an_echo_loop() {
|
||||
for (preferred, offered) in [
|
||||
(Profile::BandwidthLow, Profile::BandwidthVeryLow),
|
||||
(Profile::BandwidthLow, Profile::BandwidthUltraLow),
|
||||
(Profile::BandwidthUltraLow, Profile::BandwidthVeryLow),
|
||||
(Profile::BandwidthVeryLow, Profile::BandwidthUltraLow),
|
||||
(Profile::BandwidthVeryLow, Profile::BandwidthLow),
|
||||
] {
|
||||
let mut cfg = config();
|
||||
cfg.preferred = preferred;
|
||||
let mut receiver = Session::new(CallRole::Incoming, cfg, 0).unwrap();
|
||||
let mut caller = CallState::outgoing(Some(offered));
|
||||
receiver.link_established();
|
||||
caller.receive_signal(Status::Available.into());
|
||||
let mut in_flight = Vec::new();
|
||||
// Delay the caller's response until it has received both RINGING and
|
||||
// the receiver preference, reproducing the actual TCP interop race.
|
||||
for event in receiver.peer_verified(1).as_slice() {
|
||||
if let Event::Transition(Action::SendSignal(signal)) = event {
|
||||
for action in caller.receive_signal(*signal).as_slice() {
|
||||
match action {
|
||||
Action::SendSignal(signal) => in_flight.push(*signal),
|
||||
Action::SendSignalPair(first, second) => {
|
||||
in_flight.push(*first);
|
||||
in_flight.push(*second);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(caller.profile(), Some(preferred));
|
||||
assert_eq!(
|
||||
in_flight,
|
||||
vec![Signal::from(offered), Signal::from(CallMode::FullDuplex)]
|
||||
);
|
||||
for signal in in_flight {
|
||||
for event in receiver.receive_signal(signal, 2).as_slice() {
|
||||
if let Event::Transition(Action::SendSignal(signal)) = event {
|
||||
caller.receive_signal(*signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(receiver.profile(), Some(offered));
|
||||
assert_eq!(caller.profile(), receiver.profile());
|
||||
assert!(!receiver.media_ready());
|
||||
assert!(
|
||||
receiver
|
||||
.receive_signal(offered.into(), 3)
|
||||
.as_slice()
|
||||
.is_empty()
|
||||
);
|
||||
let answer = receiver.answer(4);
|
||||
receiver.audio_ready(receiver.audio_generation(), true);
|
||||
for event in answer.as_slice() {
|
||||
if let Event::Transition(Action::SendSignal(signal)) = event {
|
||||
for action in caller.receive_signal(*signal).as_slice() {
|
||||
if let Action::SendSignal(signal) = action {
|
||||
receiver.receive_signal(*signal, 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(caller.status(), Status::Established);
|
||||
assert_eq!(caller.profile(), receiver.profile());
|
||||
assert!(receiver.media_ready());
|
||||
assert!(!receiver.transmitting());
|
||||
}
|
||||
}
|
||||
|
||||
fn config() -> SessionConfig {
|
||||
SessionConfig {
|
||||
allowed: ProfileSet::CODEC2,
|
||||
preferred: Profile::BandwidthVeryLow,
|
||||
capture: true,
|
||||
playback: true,
|
||||
times: CallTimes::default(),
|
||||
}
|
||||
}
|
||||
fn connect(role: CallRole) -> Session {
|
||||
let mut session = Session::new(role, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
match role {
|
||||
CallRole::Incoming => {
|
||||
session.answer(5);
|
||||
}
|
||||
CallRole::Outgoing => {
|
||||
for status in [Status::Available, Status::Ringing, Status::Connecting] {
|
||||
session.receive_signal(status.into(), 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
session.audio_ready(session.audio_generation(), true);
|
||||
session.receive_signal(Status::Established.into(), 6);
|
||||
assert!(session.media_ready());
|
||||
session
|
||||
}
|
||||
#[test]
|
||||
fn media_requires_identity_acceptance_correct_order_readiness_and_fresh_press() {
|
||||
for role in [CallRole::Incoming, CallRole::Outgoing] {
|
||||
let mut session = Session::new(role, config(), 0).unwrap();
|
||||
session.set_transmitting(true, 0);
|
||||
session.audio_ready(session.audio_generation(), true);
|
||||
for status in [
|
||||
Status::Available,
|
||||
Status::Ringing,
|
||||
Status::Connecting,
|
||||
Status::Established,
|
||||
] {
|
||||
session.receive_signal(status.into(), 1);
|
||||
}
|
||||
assert!(!session.media_ready());
|
||||
session.link_established();
|
||||
session.receive_signal(Status::Established.into(), 2);
|
||||
assert!(!session.media_ready());
|
||||
session.peer_verified(3);
|
||||
session.receive_signal(Status::Established.into(), 4);
|
||||
assert!(!session.media_ready());
|
||||
if role == CallRole::Incoming {
|
||||
session.answer(5);
|
||||
} else {
|
||||
for status in [Status::Available, Status::Ringing, Status::Connecting] {
|
||||
session.receive_signal(status.into(), 5);
|
||||
}
|
||||
}
|
||||
session.receive_signal(Status::Established.into(), 6);
|
||||
assert!(session.media_ready());
|
||||
assert!(!session.transmitting());
|
||||
// A press held across establishment is not a new capture request.
|
||||
assert!(session.set_transmitting(true, 7).as_slice().is_empty());
|
||||
session.set_transmitting(false, 8);
|
||||
assert_eq!(
|
||||
session.set_transmitting(true, 9).as_slice(),
|
||||
&[Event::FlushMedia, Event::Capture(true)]
|
||||
);
|
||||
assert!(!session.playback_allowed());
|
||||
assert_eq!(
|
||||
session.set_transmitting(false, 10).as_slice(),
|
||||
&[Event::Capture(false), Event::FlushMedia]
|
||||
);
|
||||
assert!(session.playback_allowed());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn timeout_teardown_and_stale_setup_never_restart_capture() {
|
||||
let mut session = connect(CallRole::Outgoing);
|
||||
session.set_transmitting(true, 100);
|
||||
assert_eq!(
|
||||
session.tick(30100).as_slice(),
|
||||
&[Event::Capture(false), Event::FlushMedia]
|
||||
);
|
||||
assert!(session.set_transmitting(true, 30101).as_slice().is_empty());
|
||||
session.set_transmitting(false, 30102);
|
||||
session.set_transmitting(true, 30103);
|
||||
let old = session.audio_generation();
|
||||
let events = session.receive_signal(Profile::BandwidthLow.into(), 30104);
|
||||
assert_eq!(
|
||||
&events.as_slice()[..2],
|
||||
&[Event::Capture(false), Event::FlushMedia]
|
||||
);
|
||||
assert!(!session.media_ready());
|
||||
session.audio_ready(old, true);
|
||||
assert!(!session.media_ready());
|
||||
session.audio_ready(session.audio_generation(), true);
|
||||
assert!(session.media_ready());
|
||||
assert!(session.set_transmitting(true, 30105).as_slice().is_empty());
|
||||
session.set_transmitting(false, 30106);
|
||||
session.set_transmitting(true, 30107);
|
||||
let events = session.end(EndReason::RouteLost);
|
||||
assert_eq!(events.as_slice()[0], Event::Capture(false));
|
||||
assert_eq!(
|
||||
events.as_slice().last(),
|
||||
Some(&Event::Ended(EndReason::RouteLost))
|
||||
);
|
||||
assert!(session.set_transmitting(true, 30108).as_slice().is_empty());
|
||||
assert!(
|
||||
session
|
||||
.audio_ready(session.audio_generation(), true)
|
||||
.as_slice()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(!session.media_ready());
|
||||
}
|
||||
#[test]
|
||||
fn unsupported_profile_has_one_bounded_offer_then_closes() {
|
||||
let mut session = connect(CallRole::Outgoing);
|
||||
session.set_transmitting(true, 10);
|
||||
let events = session.receive_signal(Profile::QualityHigh.into(), 11);
|
||||
assert_eq!(
|
||||
events.as_slice(),
|
||||
&[
|
||||
Event::Capture(false),
|
||||
Event::FlushMedia,
|
||||
Event::Transition(Action::SendSignal(Profile::BandwidthVeryLow.into())),
|
||||
]
|
||||
);
|
||||
assert!(!session.media_ready());
|
||||
assert!(session.tick(5010).as_slice().is_empty());
|
||||
session.tick(5011);
|
||||
assert_eq!(session.ended(), Some(EndReason::ProfileUnsupported));
|
||||
let mut session = connect(CallRole::Incoming);
|
||||
session.receive_signal(Profile::QualityHigh.into(), 20);
|
||||
session.receive_signal(Profile::BandwidthVeryLow.into(), 21);
|
||||
assert!(session.media_ready());
|
||||
let events = session.receive_signal(Profile::QualityHigh.into(), 22);
|
||||
assert_eq!(session.ended(), None);
|
||||
assert!(
|
||||
events
|
||||
.as_slice()
|
||||
.contains(&Event::Transition(Action::SendSignal(
|
||||
Profile::BandwidthVeryLow.into()
|
||||
)))
|
||||
);
|
||||
session.receive_signal(Profile::QualityMax.into(), 23);
|
||||
assert_eq!(session.ended(), Some(EndReason::ProfileUnsupported));
|
||||
}
|
||||
#[test]
|
||||
fn answer_establishes_without_retries_and_one_direction_devices_work() {
|
||||
let mut session = Session::new(CallRole::Incoming, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
let answer = session.answer(2);
|
||||
let sent = answer
|
||||
.as_slice()
|
||||
.iter()
|
||||
.filter(|event| matches!(event, Event::Transition(Action::SendSignal(_))))
|
||||
.count();
|
||||
assert_eq!(sent, 2);
|
||||
assert_eq!(session.status(), Status::Established);
|
||||
for n in 1..=20 {
|
||||
assert!(session.tick(2 + n * 1000).as_slice().is_empty());
|
||||
}
|
||||
assert_eq!(session.ended(), None);
|
||||
for (capture, playback) in [(true, false), (false, true)] {
|
||||
let mut cfg = config();
|
||||
cfg.capture = capture;
|
||||
cfg.playback = playback;
|
||||
let mut session = Session::new(CallRole::Incoming, cfg, 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
session.answer(2);
|
||||
session.audio_ready(session.audio_generation(), true);
|
||||
session.receive_signal(Status::Established.into(), 3);
|
||||
assert_eq!(session.playback_allowed(), playback);
|
||||
session.set_transmitting(true, 4);
|
||||
assert_eq!(session.transmitting(), capture);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn adversarial_event_sequences_remain_bounded() {
|
||||
let mut rng = 401_u32;
|
||||
for role in [CallRole::Incoming, CallRole::Outgoing] {
|
||||
for _ in 0..1000 {
|
||||
let mut session = Session::new(role, config(), 0).unwrap();
|
||||
for now in 0..100 {
|
||||
rng = rng.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
match rng % 10 {
|
||||
0 => {
|
||||
session.link_established();
|
||||
}
|
||||
1 => {
|
||||
session.peer_verified(now);
|
||||
}
|
||||
2 => {
|
||||
session.answer(now);
|
||||
}
|
||||
3 => {
|
||||
session.audio_ready(session.audio_generation(), true);
|
||||
}
|
||||
4 => {
|
||||
session.set_transmitting(true, now);
|
||||
}
|
||||
5 => {
|
||||
session.set_transmitting(false, now);
|
||||
}
|
||||
6 => {
|
||||
session.tick(now);
|
||||
}
|
||||
_ => {
|
||||
session.receive_signal(Signal::from_wire((rng >> 16) % 512), now);
|
||||
}
|
||||
}
|
||||
if session.transmitting() {
|
||||
assert!(session.media_ready());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticated_matching_media_confirms_standard_profile_fallback_without_echo() {
|
||||
let mut session = connect(CallRole::Outgoing);
|
||||
session.receive_signal(Profile::QualityMedium.into(), 100);
|
||||
assert!(!session.media_ready());
|
||||
session.receive_profile_media(Profile::BandwidthLow, 200);
|
||||
assert!(!session.media_ready());
|
||||
session.receive_profile_media(Profile::BandwidthVeryLow, 201);
|
||||
assert!(session.media_ready());
|
||||
assert!(!session.transmitting());
|
||||
session.tick(6000);
|
||||
assert_eq!(session.ended(), None);
|
||||
|
||||
let mut late = connect(CallRole::Outgoing);
|
||||
late.receive_signal(Profile::QualityMedium.into(), 100);
|
||||
late.receive_profile_media(Profile::BandwidthVeryLow, 5100);
|
||||
late.tick(5100);
|
||||
assert_eq!(late.ended(), Some(EndReason::ProfileUnsupported));
|
||||
|
||||
let mut ringing = Session::new(CallRole::Incoming, config(), 0).unwrap();
|
||||
ringing.link_established();
|
||||
ringing.peer_verified(1);
|
||||
ringing.receive_signal(Profile::QualityMedium.into(), 100);
|
||||
ringing.receive_profile_media(Profile::BandwidthVeryLow, 200);
|
||||
ringing.tick(5100);
|
||||
assert_eq!(ringing.ended(), Some(EndReason::ProfileUnsupported));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoming_ring_times_out_after_python_ring_time() {
|
||||
let mut session = Session::new(CallRole::Incoming, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(0);
|
||||
session.tick(59_999);
|
||||
assert_eq!(session.ended(), None);
|
||||
session.tick(60_000);
|
||||
assert_eq!(session.ended(), Some(EndReason::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_call_ends_when_callee_does_not_ring_within_connect_time() {
|
||||
let mut session = Session::new(CallRole::Outgoing, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
session.receive_signal(Status::Available.into(), 100);
|
||||
session.tick(4_999);
|
||||
assert_eq!(session.ended(), None);
|
||||
session.tick(5_000);
|
||||
assert_eq!(session.ended(), Some(EndReason::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_wait_time_runs_from_call_start_once_ringing() {
|
||||
let mut session = Session::new(CallRole::Outgoing, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
session.receive_signal(Status::Available.into(), 100);
|
||||
session.receive_signal(Status::Ringing.into(), 4_000);
|
||||
session.tick(69_999);
|
||||
assert_eq!(session.ended(), None);
|
||||
session.tick(70_000);
|
||||
assert_eq!(session.ended(), Some(EndReason::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_mode_signal_is_recorded_by_the_session() {
|
||||
let mut session = Session::new(CallRole::Incoming, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
session.receive_signal(Signal::from_wire(0xF2), 2);
|
||||
assert_eq!(session.mode(), Some(CallMode::HalfDuplex));
|
||||
assert_eq!(session.ended(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_call_times_replace_the_python_defaults() {
|
||||
let slow = SessionConfig {
|
||||
times: CallTimes {
|
||||
connect_ms: 20_000,
|
||||
wait_ms: 200_000,
|
||||
ring_ms: 150_000,
|
||||
},
|
||||
..config()
|
||||
};
|
||||
let mut outgoing = Session::new(CallRole::Outgoing, slow, 0).unwrap();
|
||||
outgoing.link_established();
|
||||
outgoing.peer_verified(1);
|
||||
outgoing.tick(19_999);
|
||||
assert_eq!(outgoing.ended(), None);
|
||||
outgoing.receive_signal(Status::Available.into(), 19_999);
|
||||
outgoing.receive_signal(Status::Ringing.into(), 19_999);
|
||||
outgoing.tick(199_999);
|
||||
assert_eq!(outgoing.ended(), None);
|
||||
outgoing.tick(200_000);
|
||||
assert_eq!(outgoing.ended(), Some(EndReason::Timeout));
|
||||
|
||||
let mut incoming = Session::new(CallRole::Incoming, slow, 0).unwrap();
|
||||
incoming.link_established();
|
||||
incoming.peer_verified(0);
|
||||
incoming.tick(149_999);
|
||||
assert_eq!(incoming.ended(), None);
|
||||
incoming.tick(150_000);
|
||||
assert_eq!(incoming.ended(), Some(EndReason::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller_keeps_call_past_wait_time_when_callee_established_is_lost() {
|
||||
let mut session = Session::new(CallRole::Outgoing, config(), 0).unwrap();
|
||||
session.link_established();
|
||||
session.peer_verified(1);
|
||||
for status in [Status::Available, Status::Ringing, Status::Connecting] {
|
||||
session.receive_signal(status.into(), 100);
|
||||
}
|
||||
session.audio_ready(session.audio_generation(), true);
|
||||
assert_eq!(session.status(), Status::Established);
|
||||
assert!(!session.media_ready());
|
||||
session.tick(70_001);
|
||||
assert_eq!(session.ended(), None);
|
||||
session.receive_signal(Status::Established.into(), 70_002);
|
||||
assert!(session.media_ready());
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
use lxst_embedded::wire::{self, Error, Frame, Packet};
|
||||
use lxst_embedded::{CodecKind, Profile, Signal};
|
||||
|
||||
#[test]
|
||||
fn bounded_wire_matches_full_rust_canonical_packets() {
|
||||
let signal_values = [0, 6, 127, 128, 255, 256, 65535, u32::MAX];
|
||||
for count in 0..=8 {
|
||||
let signals: Vec<_> = signal_values[..count]
|
||||
.iter()
|
||||
.map(|v| Signal::from_wire(*v))
|
||||
.collect();
|
||||
for lengths in [vec![], vec![0], vec![64], vec![255], vec![0, 64, 80, 120]] {
|
||||
let payloads: Vec<_> = lengths.iter().map(|n| vec![0x5a; *n]).collect();
|
||||
let frames: Vec<_> = payloads
|
||||
.iter()
|
||||
.map(|p| Frame {
|
||||
codec: CodecKind::Codec2,
|
||||
payload: p,
|
||||
})
|
||||
.collect();
|
||||
let host = lxst_core::LxstPacket {
|
||||
signals: signals
|
||||
.iter()
|
||||
.map(|s| lxst_core::Signal::from_wire(s.wire_value()))
|
||||
.collect(),
|
||||
frames: payloads
|
||||
.iter()
|
||||
.map(|p| lxst_core::Frame::new(lxst_core::CodecKind::Codec2, p.clone()))
|
||||
.collect(),
|
||||
};
|
||||
let expected = host.encode().unwrap();
|
||||
let mut encoded = [0xa5; 512];
|
||||
let size = wire::encode(&signals, &frames, &mut encoded).unwrap();
|
||||
assert_eq!(encoded[..size], expected);
|
||||
assert!(encoded[size..].iter().all(|v| *v == 0xa5));
|
||||
let decoded = Packet::decode(&encoded[..size]).unwrap();
|
||||
assert_eq!(decoded.signals(), signals);
|
||||
assert_eq!(decoded.frames(), frames);
|
||||
for end in 0..size {
|
||||
assert!(Packet::decode(&encoded[..end]).is_err());
|
||||
}
|
||||
let mut too_small = vec![0xa5; size - 1];
|
||||
assert_eq!(
|
||||
wire::encode(&signals, &frames, &mut too_small),
|
||||
Err(Error::OutputCapacity)
|
||||
);
|
||||
assert!(too_small.iter().all(|v| *v == 0xa5));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_integer_and_container_forms_remain_compatible() {
|
||||
for bytes in [
|
||||
vec![0x81, 0, 4],
|
||||
vec![0xde, 0, 1, 0xcc, 0, 0xdc, 0, 1, 0xd1, 0, 4],
|
||||
vec![
|
||||
0xdf, 0, 0, 0, 1, 0, 0xdd, 0, 0, 0, 1, 0xd3, 0, 0, 0, 0, 0, 0, 0, 4,
|
||||
],
|
||||
] {
|
||||
let packet = Packet::decode(&bytes).unwrap();
|
||||
assert_eq!(packet.signals()[0].wire_value(), 4);
|
||||
assert_eq!(
|
||||
lxst_core::LxstPacket::decode(&bytes).unwrap().signals[0].wire_value(),
|
||||
4
|
||||
);
|
||||
}
|
||||
for bytes in [
|
||||
vec![0x81, 1, 0xc5, 0, 2, 2, 4],
|
||||
vec![0x81, 1, 0xc6, 0, 0, 0, 2, 2, 4],
|
||||
] {
|
||||
assert_eq!(Packet::decode(&bytes).unwrap().frames()[0].payload, &[4]);
|
||||
}
|
||||
// Unknown metadata is skipped, bounded by packet bytes and nesting depth.
|
||||
let bytes = [0x82, 8, 0x92, 0xc0, 0x81, 0xa1, b'a', 0xc7, 1, 3, 8, 0, 4];
|
||||
assert_eq!(Packet::decode(&bytes).unwrap().signals()[0].wire_value(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_shapes_are_rejected_without_unbounded_work() {
|
||||
for bytes in [
|
||||
vec![0x81, 0, 0xff],
|
||||
vec![0x81, 0, 0xd0, 0xff],
|
||||
vec![0x81, 0, 0xcf, 1, 0, 0, 0, 0, 0, 0, 0],
|
||||
vec![0x81, 0, 0xdd, 255, 255, 255, 255],
|
||||
vec![0x81, 1, 0xc6, 255, 255, 255, 255],
|
||||
vec![0x81, 1, 0xc4, 0],
|
||||
vec![0x81, 1, 0xc4, 1, 255],
|
||||
vec![0x82, 0, 4, 0, 4],
|
||||
vec![0x81, 0, 4, 0],
|
||||
vec![0x81, 1, 0x95],
|
||||
vec![0x81, 0, 0x99],
|
||||
vec![
|
||||
0x81, 8, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0,
|
||||
],
|
||||
] {
|
||||
assert!(Packet::decode(&bytes).is_err(), "accepted {bytes:x?}");
|
||||
}
|
||||
let mut output = [0xa5; 512];
|
||||
let frames = [Frame {
|
||||
codec: CodecKind::Null,
|
||||
payload: &[],
|
||||
}];
|
||||
assert_eq!(
|
||||
wire::encode(&[], &frames, &mut output),
|
||||
Err(Error::NonTransmittableCodec(CodecKind::Null))
|
||||
);
|
||||
assert_eq!(output, [0xa5; 512]);
|
||||
let mut random = 123_u32;
|
||||
let mut bytes = [0; 520];
|
||||
for iteration in 0..100000 {
|
||||
let length = iteration % bytes.len();
|
||||
for byte in &mut bytes[..length] {
|
||||
random = random.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
*byte = (random >> 24) as u8;
|
||||
}
|
||||
let _ = Packet::decode(&bytes[..length]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_transitions_retain_full_rust_actions() {
|
||||
use lxst_embedded::{CallState, SignallingStatus};
|
||||
let mut embedded = CallState::outgoing(Some(Profile::BandwidthVeryLow));
|
||||
let mut host = lxst_core::TelephonyCall::outgoing(Some(lxst_core::Profile::BandwidthVeryLow));
|
||||
for signal in [
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
5,
|
||||
6,
|
||||
0x11f,
|
||||
0x12f,
|
||||
0xf1,
|
||||
0xf2,
|
||||
0xf3,
|
||||
0,
|
||||
1,
|
||||
u32::MAX,
|
||||
] {
|
||||
let a = embedded.receive_signal(Signal::from_wire(signal));
|
||||
let b = host.receive_signal(lxst_core::Signal::from_wire(signal));
|
||||
assert_eq!(format!("{:?}", a.as_slice()), format!("{b:?}"));
|
||||
assert_eq!(embedded.status().wire_value(), host.status().wire_value());
|
||||
}
|
||||
// Explore combinations including adversarial order to prove the shared
|
||||
// fixed action bound; session policy separately restricts allowed ordering.
|
||||
for first in 0..512 {
|
||||
for second in [0, 3, 4, 5, 6, 0x11f, 0x12f, 0x13f, 0xf1, 0xf2] {
|
||||
let mut call = CallState::incoming();
|
||||
call.caller_identified(false, true);
|
||||
call.receive_signal(Signal::from_wire(first));
|
||||
call.answer();
|
||||
call.receive_signal(Signal::from_wire(second));
|
||||
call.hangup(false);
|
||||
assert_eq!(call.status(), SignallingStatus::Available);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
name = "lxst-rns"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
|
||||
+141
-39
@@ -1,8 +1,8 @@
|
||||
//! Reticulum transport boundary for LXST.
|
||||
//!
|
||||
//! This crate is intentionally small: it turns already-encoded LXST packets into
|
||||
//! Reticulum link data packets and leaves call state, audio, and codec work to
|
||||
//! higher layers.
|
||||
//! Packet helpers encrypt LXST payloads for Reticulum Links; ingress/egress
|
||||
//! adapters track frames, provide a jitter queue and convert raw or Opus audio.
|
||||
//! Call policy and audio-device ownership stay with the embedding runtime.
|
||||
|
||||
use bytes::Bytes;
|
||||
use lxst_core::{
|
||||
@@ -10,9 +10,11 @@ use lxst_core::{
|
||||
JitterPush, JitterStats, LxstPacket, OpusDecoderState, RawAudioFrame, RawBitDepth,
|
||||
};
|
||||
use rns_link::link::{Link, LinkState};
|
||||
use rns_transport::messages::{OutboundRequest, TransportMessage};
|
||||
use rns_transport::messages::{
|
||||
LinkEndpointRole, LinkEndpointSendResult, OutboundRequest, TransportMessage,
|
||||
};
|
||||
use thiserror::Error;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
@@ -28,10 +30,6 @@ pub enum Error {
|
||||
PayloadExceedsMdu { payload_len: usize, mdu: usize },
|
||||
#[error("Reticulum link encryption failed: {0}")]
|
||||
LinkEncrypt(String),
|
||||
#[error("Reticulum outbound queue is closed")]
|
||||
TransportClosed,
|
||||
#[error("Reticulum outbound queue is full")]
|
||||
TransportFull,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -69,6 +67,8 @@ impl LxstLinkIngress {
|
||||
}
|
||||
|
||||
/// Decode decrypted plaintext from `LinkManager::set_link_packet_channel`.
|
||||
/// The caller supplies the authenticated Link association; parsing does not
|
||||
/// verify `link_id`. Input parsing follows [`LxstPacket::decode`].
|
||||
pub fn accept_plaintext(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -247,41 +247,109 @@ pub fn pack_link_payload(link: &Link, payload: &[u8]) -> Result<PackedLinkPacket
|
||||
})
|
||||
}
|
||||
|
||||
/// Pack and queue an already-encoded LXST payload for Reticulum transmission.
|
||||
pub fn queue_link_payload(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
/// Pack an already-encoded LXST payload and prepare an exact-interface
|
||||
/// established-Link transport command.
|
||||
pub fn prepare_link_payload_send(
|
||||
link: &Link,
|
||||
role: LinkEndpointRole,
|
||||
payload: &[u8],
|
||||
) -> Result<PackedLinkPacket, Error> {
|
||||
) -> Result<PreparedLinkEndpointSend, Error> {
|
||||
let packet = pack_link_payload(link, payload)?;
|
||||
queue_packed_link_packet(transport_tx, packet)
|
||||
Ok(prepare_packed_link_endpoint_send(packet, role))
|
||||
}
|
||||
|
||||
/// Pack and queue a structured LXST packet for Reticulum transmission.
|
||||
pub fn queue_lxst_link_packet(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
/// Pack a structured LXST packet and prepare an exact-interface established-
|
||||
/// Link transport command.
|
||||
pub fn prepare_lxst_link_packet_send(
|
||||
link: &Link,
|
||||
role: LinkEndpointRole,
|
||||
packet: &LxstPacket,
|
||||
) -> Result<PackedLinkPacket, Error> {
|
||||
) -> Result<PreparedLinkEndpointSend, Error> {
|
||||
let packet = pack_lxst_link_packet(link, packet)?;
|
||||
queue_packed_link_packet(transport_tx, packet)
|
||||
Ok(prepare_packed_link_endpoint_send(packet, role))
|
||||
}
|
||||
|
||||
fn queue_packed_link_packet(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
/// One packet, a transport command and its local admission result.
|
||||
///
|
||||
/// Enqueue `message` and inspect `result_rx`. `Sent` and `Queued` do not
|
||||
/// acknowledge peer receipt; later failures need endpoint-lifecycle handling.
|
||||
pub struct PreparedLinkEndpointSend {
|
||||
pub packet: PackedLinkPacket,
|
||||
pub message: TransportMessage,
|
||||
pub result_rx: oneshot::Receiver<LinkEndpointSendResult>,
|
||||
}
|
||||
|
||||
/// Prepare an ordered send for an already packed Link packet.
|
||||
/// This only constructs the command; it does not enqueue or transmit it.
|
||||
pub fn prepare_packed_link_endpoint_send(
|
||||
packet: PackedLinkPacket,
|
||||
) -> Result<PackedLinkPacket, Error> {
|
||||
transport_tx
|
||||
.try_send(TransportMessage::Outbound(OutboundRequest {
|
||||
role: LinkEndpointRole,
|
||||
) -> PreparedLinkEndpointSend {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
let message = TransportMessage::SendLinkEndpoint {
|
||||
link_id: packet.destination_hash,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw: packet.raw.clone(),
|
||||
destination_hash: packet.destination_hash,
|
||||
}))
|
||||
.map_err(|e| match e {
|
||||
mpsc::error::TrySendError::Full(_) => Error::TransportFull,
|
||||
mpsc::error::TrySendError::Closed(_) => Error::TransportClosed,
|
||||
})?;
|
||||
},
|
||||
result_tx,
|
||||
};
|
||||
PreparedLinkEndpointSend {
|
||||
packet,
|
||||
message,
|
||||
result_rx,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(packet)
|
||||
/// Prepare an ordered send followed by endpoint unbinding.
|
||||
/// Once admitted, the transport drains earlier control packets and this packet
|
||||
/// before unbinding; a terminal send/interface error may end the Link earlier.
|
||||
/// The caller must enqueue the command and inspect its local result.
|
||||
pub fn prepare_packed_link_endpoint_final_send(
|
||||
packet: PackedLinkPacket,
|
||||
role: LinkEndpointRole,
|
||||
) -> PreparedLinkEndpointSend {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
let message = TransportMessage::SendLinkEndpointAndUnbind {
|
||||
link_id: packet.destination_hash,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw: packet.raw.clone(),
|
||||
destination_hash: packet.destination_hash,
|
||||
},
|
||||
result_tx,
|
||||
};
|
||||
PreparedLinkEndpointSend {
|
||||
packet,
|
||||
message,
|
||||
result_rx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare realtime media for exact-interface, best-effort Link delivery.
|
||||
///
|
||||
/// Unlike [`prepare_packed_link_endpoint_send`], this operation never enters
|
||||
/// the ordered control FIFO when the target interface is backpressured.
|
||||
pub fn prepare_packed_link_endpoint_best_effort_send(
|
||||
packet: PackedLinkPacket,
|
||||
role: LinkEndpointRole,
|
||||
) -> PreparedLinkEndpointSend {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
let message = TransportMessage::SendLinkEndpointBestEffort {
|
||||
link_id: packet.destination_hash,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw: packet.raw.clone(),
|
||||
destination_hash: packet.destination_hash,
|
||||
},
|
||||
result_tx,
|
||||
};
|
||||
PreparedLinkEndpointSend {
|
||||
packet,
|
||||
message,
|
||||
result_rx,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -334,21 +402,55 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_sends_outbound_transport_message() {
|
||||
fn prepared_send_uses_typed_link_endpoint_transport_message() {
|
||||
let (initiator, _responder) = active_link_pair();
|
||||
let payload = LxstPacket::frame(Frame::new(CodecKind::Raw, [0x00, 0x11, 0x22]))
|
||||
.encode()
|
||||
.unwrap();
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
|
||||
let packet = queue_link_payload(&tx, &initiator, &payload).unwrap();
|
||||
let sent = rx.try_recv().unwrap();
|
||||
let TransportMessage::Outbound(outbound) = sent else {
|
||||
panic!("expected outbound transport message");
|
||||
let prepared =
|
||||
prepare_link_payload_send(&initiator, LinkEndpointRole::Initiator, &payload).unwrap();
|
||||
let TransportMessage::SendLinkEndpoint {
|
||||
link_id,
|
||||
role,
|
||||
request,
|
||||
..
|
||||
} = prepared.message
|
||||
else {
|
||||
panic!("expected typed Link endpoint transport message");
|
||||
};
|
||||
|
||||
assert_eq!(outbound.raw, packet.raw);
|
||||
assert_eq!(outbound.destination_hash, initiator.link_id);
|
||||
assert_eq!(link_id, initiator.link_id);
|
||||
assert_eq!(role, LinkEndpointRole::Initiator);
|
||||
assert_eq!(request.raw, prepared.packet.raw);
|
||||
assert_eq!(request.destination_hash, initiator.link_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_media_send_uses_best_effort_endpoint_without_receipt_registration() {
|
||||
let (initiator, _responder) = active_link_pair();
|
||||
let packet = pack_lxst_link_packet(
|
||||
&initiator,
|
||||
&LxstPacket::frame(Frame::new(CodecKind::Raw, [0x00, 0x11])),
|
||||
)
|
||||
.unwrap();
|
||||
let prepared = prepare_packed_link_endpoint_best_effort_send(
|
||||
packet.clone(),
|
||||
LinkEndpointRole::Initiator,
|
||||
);
|
||||
let TransportMessage::SendLinkEndpointBestEffort {
|
||||
link_id,
|
||||
role,
|
||||
request,
|
||||
..
|
||||
} = prepared.message
|
||||
else {
|
||||
panic!("expected best-effort Link endpoint transport message");
|
||||
};
|
||||
|
||||
assert_eq!(link_id, initiator.link_id);
|
||||
assert_eq!(role, LinkEndpointRole::Initiator);
|
||||
assert_eq!(request.raw, packet.raw);
|
||||
assert_eq!(request.destination_hash, initiator.link_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
name = "lxst-telephony"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
lxst-core.workspace = true
|
||||
lxst-codec2 = { path = "../lxst-codec2", version = "0.4.0" }
|
||||
lxst-rns.workspace = true
|
||||
rns-crypto.workspace = true
|
||||
rns-identity.workspace = true
|
||||
@@ -19,6 +21,7 @@ thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
hex.workspace = true
|
||||
rns-interface.workspace = true
|
||||
serial_test.workspace = true
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Construct the canonical experimental telephony service boundary.
|
||||
|
||||
use lxst_telephony::{TelephonyControl, TelephonyService, TelephonyServiceEvent};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(32);
|
||||
let identity = Identity::new();
|
||||
let parts = TelephonyService::registered(transport_tx, &identity)?;
|
||||
|
||||
let _service: TelephonyService = parts.service;
|
||||
let _control: mpsc::Sender<TelephonyControl> = parts.control_tx;
|
||||
let _events: mpsc::Receiver<TelephonyServiceEvent> = parts.event_rx;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A local PTT lease that expires after 750 ms without renewal or a ten-second
|
||||
/// burst. The caller must check [`Self::allows`] before forwarding each frame;
|
||||
/// this gate does not stop an audio device itself. Once expiry is observed,
|
||||
/// a release is required before another press. It adds no LXST wire fields.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct AudioTransmitGate {
|
||||
state: Mutex<State>,
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
struct State {
|
||||
serial: u64,
|
||||
began: Option<Instant>,
|
||||
until: Option<Instant>,
|
||||
blocked: bool,
|
||||
}
|
||||
impl AudioTransmitGate {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
/// Monotonically increasing serial for each edge; renew using the press
|
||||
/// serial. A delayed press/renew after a later release is rejected.
|
||||
pub fn update(&self, serial: u64, pressed: bool) -> bool {
|
||||
self.update_at(serial, pressed, Instant::now())
|
||||
}
|
||||
fn update_at(&self, serial: u64, pressed: bool, now: Instant) -> bool {
|
||||
let Ok(mut state) = self.state.lock() else {
|
||||
return false;
|
||||
};
|
||||
if serial == 0 || serial < state.serial {
|
||||
return false;
|
||||
}
|
||||
if serial > state.serial {
|
||||
state.serial = serial;
|
||||
state.began = None;
|
||||
state.until = None;
|
||||
if !pressed {
|
||||
state.blocked = false;
|
||||
return true;
|
||||
}
|
||||
if state.blocked {
|
||||
return false;
|
||||
}
|
||||
state.began = Some(now);
|
||||
}
|
||||
if !pressed {
|
||||
state.began = None;
|
||||
state.until = None;
|
||||
state.blocked = false;
|
||||
return true;
|
||||
}
|
||||
if state.blocked || state.began.is_none() {
|
||||
return false;
|
||||
}
|
||||
if now.duration_since(state.began.unwrap()) >= Duration::from_secs(10)
|
||||
|| state.until.is_some_and(|end| now >= end)
|
||||
{
|
||||
state.blocked = true;
|
||||
state.until = None;
|
||||
return false;
|
||||
}
|
||||
state.until = Some(now + Duration::from_millis(750));
|
||||
true
|
||||
}
|
||||
pub fn serial(&self) -> u64 {
|
||||
self.state.lock().map(|s| s.serial).unwrap_or(0)
|
||||
}
|
||||
/// Permanently revoke this owner; replace it for a new session.
|
||||
pub fn close(&self) {
|
||||
if let Ok(mut state) = self.state.lock() {
|
||||
state.serial = u64::MAX;
|
||||
state.until = None;
|
||||
state.began = None;
|
||||
state.blocked = true;
|
||||
}
|
||||
}
|
||||
/// Check the current lease; contention, expiry or closure returns `false`.
|
||||
/// This may mark an expired press blocked until a release arrives.
|
||||
pub fn allows(&self) -> bool {
|
||||
self.allows_at(Instant::now())
|
||||
}
|
||||
fn allows_at(&self, now: Instant) -> bool {
|
||||
let Ok(mut state) = self.state.try_lock() else {
|
||||
return false;
|
||||
};
|
||||
let allowed = !state.blocked
|
||||
&& state.until.is_some_and(|end| now < end)
|
||||
&& state
|
||||
.began
|
||||
.is_some_and(|begin| now.duration_since(begin) < Duration::from_secs(10));
|
||||
if !allowed && state.began.is_some() {
|
||||
state.blocked = true;
|
||||
state.until = None;
|
||||
}
|
||||
allowed
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn release_stale_renew_stall_and_burst_are_fenced() {
|
||||
let gate = AudioTransmitGate::new();
|
||||
let start = Instant::now();
|
||||
assert!(!gate.allows_at(start));
|
||||
assert!(gate.update_at(1, true, start));
|
||||
assert!(gate.allows_at(start));
|
||||
assert!(gate.update_at(2, false, start));
|
||||
assert!(!gate.update_at(1, true, start));
|
||||
assert!(gate.update_at(3, true, start));
|
||||
assert!(!gate.allows_at(start + Duration::from_secs(1)));
|
||||
assert!(!gate.update_at(4, true, start + Duration::from_secs(1))); // new press still requires release after timeout
|
||||
assert!(gate.update_at(5, false, start));
|
||||
assert!(gate.update_at(6, true, start));
|
||||
for ms in (250..10000).step_by(250) {
|
||||
assert!(gate.update_at(6, true, start + Duration::from_millis(ms)));
|
||||
}
|
||||
assert!(!gate.update_at(6, true, start + Duration::from_secs(10)));
|
||||
assert!(!gate.allows_at(start + Duration::from_secs(10)));
|
||||
}
|
||||
}
|
||||
+1534
-432
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
//! Host PCM adapter. The same bounded native Codec2 backend and packet framing
|
||||
//! as handheld firmware; original Opus controls/events remain compatible.
|
||||
use crate::Error;
|
||||
use lxst_codec2::{Codec, Mode};
|
||||
use lxst_core::{
|
||||
AudioCodec, Codec2Backend, Codec2Mode, Codec2PacketCodec, CodecKind, Frame, OpusEncoderState,
|
||||
OpusPacketDecoder, Profile, RawAudioFrame,
|
||||
};
|
||||
|
||||
struct Native(Box<Codec>);
|
||||
impl Codec2Backend for Native {
|
||||
type Error = &'static str;
|
||||
fn mode(&self) -> Codec2Mode {
|
||||
match self.0.mode() {
|
||||
Mode::Rate1600 => Codec2Mode::Mode1600,
|
||||
Mode::Rate3200 => Codec2Mode::Mode3200,
|
||||
Mode::Rate700C => Codec2Mode::Mode700C,
|
||||
}
|
||||
}
|
||||
fn encode_native(&mut self, pcm: &[i16], bytes: &mut [u8]) -> Result<(), Self::Error> {
|
||||
self.0
|
||||
.encode(pcm, bytes)
|
||||
.map_err(|_| "invalid native frame")
|
||||
}
|
||||
fn decode_native(&mut self, bytes: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error> {
|
||||
self.0
|
||||
.decode(bytes, pcm)
|
||||
.map_err(|_| "invalid native frame")
|
||||
}
|
||||
}
|
||||
pub(crate) struct Codec2Audio {
|
||||
codec: Codec2PacketCodec<Native>,
|
||||
pcm: Vec<i16>,
|
||||
}
|
||||
impl Codec2Audio {
|
||||
fn new(profile: Profile) -> Result<Self, Error> {
|
||||
let mode = match profile {
|
||||
Profile::BandwidthUltraLow => Mode::Rate700C,
|
||||
Profile::BandwidthVeryLow => Mode::Rate1600,
|
||||
Profile::BandwidthLow => Mode::Rate3200,
|
||||
_ => return Err(Error::Audio("unsupported native Codec2 profile".into())),
|
||||
};
|
||||
let mut storage = Box::<Codec>::new_uninit();
|
||||
Codec::initialise(&mut storage, mode);
|
||||
// SAFETY: initialise completed in final storage above.
|
||||
let backend = Native(unsafe { storage.assume_init() });
|
||||
let codec =
|
||||
Codec2PacketCodec::new(profile, backend).map_err(|e| Error::Audio(e.to_string()))?;
|
||||
Ok(Self {
|
||||
pcm: vec![0; codec.sample_frames()],
|
||||
codec,
|
||||
})
|
||||
}
|
||||
fn encode(&mut self, frame: &RawAudioFrame) -> Result<Frame, Error> {
|
||||
if frame.channels != 1
|
||||
|| frame.samples.len() != self.pcm.len()
|
||||
|| frame.samples.iter().any(|v| !v.is_finite())
|
||||
{
|
||||
return Err(Error::Audio(
|
||||
"invalid Codec2 PCM shape or non-finite sample".into(),
|
||||
));
|
||||
}
|
||||
for (to, from) in self.pcm.iter_mut().zip(&frame.samples) {
|
||||
*to = (from.clamp(-1.0, 1.0) * 32768.0)
|
||||
.round()
|
||||
.clamp(-32768.0, 32767.0) as i16;
|
||||
}
|
||||
let mut payload = vec![0; self.codec.payload_bytes()];
|
||||
let result = self
|
||||
.codec
|
||||
.encode_into(&self.pcm, &mut payload)
|
||||
.map_err(|e| Error::Audio(e.to_string()));
|
||||
self.pcm.fill(0);
|
||||
result?;
|
||||
Ok(Frame::new(CodecKind::Codec2, payload))
|
||||
}
|
||||
}
|
||||
pub(crate) enum AudioEncoder {
|
||||
Opus(Box<OpusEncoderState>),
|
||||
Codec2(Codec2Audio),
|
||||
}
|
||||
impl AudioEncoder {
|
||||
pub(crate) fn new(profile: Profile) -> Result<Self, Error> {
|
||||
match profile.audio_codec() {
|
||||
AudioCodec::Opus(_) => Ok(Self::Opus(Box::new(OpusEncoderState::new(profile)?))),
|
||||
AudioCodec::Codec2(_) => Ok(Self::Codec2(Codec2Audio::new(profile)?)),
|
||||
}
|
||||
}
|
||||
pub(crate) fn encode_frame(&mut self, frame: &RawAudioFrame) -> Result<Frame, Error> {
|
||||
match self {
|
||||
Self::Opus(codec) => Ok(codec.encode_frame(frame)?),
|
||||
Self::Codec2(codec) => codec.encode(frame),
|
||||
}
|
||||
}
|
||||
}
|
||||
const CODEC2_SAMPLE_RATE_HZ: u32 = 8_000;
|
||||
|
||||
/// Follows the codec and Codec2 mode of each received frame, as Python `LinkSource`
|
||||
/// does, and converts the output to the local profile's sample rate and channels.
|
||||
pub(crate) struct ReceiveDecoder {
|
||||
sample_rate_hz: u32,
|
||||
channels: u8,
|
||||
opus: Option<OpusPacketDecoder>,
|
||||
codec2: Vec<(Codec2Mode, Box<Codec>)>,
|
||||
}
|
||||
|
||||
impl ReceiveDecoder {
|
||||
pub(crate) fn new(profile: Profile) -> Self {
|
||||
Self {
|
||||
sample_rate_hz: profile.sample_rate_hz(),
|
||||
channels: profile.channels(),
|
||||
opus: None,
|
||||
codec2: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode_frame(&mut self, frame: &Frame) -> Result<RawAudioFrame, Error> {
|
||||
match frame.codec {
|
||||
CodecKind::Opus => {
|
||||
if self.opus.is_none() {
|
||||
self.opus = Some(OpusPacketDecoder::new(self.sample_rate_hz, self.channels)?);
|
||||
}
|
||||
let decoder = self
|
||||
.opus
|
||||
.as_mut()
|
||||
.expect("Opus decoder exists after creation");
|
||||
Ok(decoder.decode_packet(&frame.payload)?)
|
||||
}
|
||||
CodecKind::Codec2 => self.decode_codec2(&frame.payload),
|
||||
other => Err(Error::Audio(format!("unexpected media codec {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_codec2(&mut self, payload: &[u8]) -> Result<RawAudioFrame, Error> {
|
||||
let (&header, bytes) = payload
|
||||
.split_first()
|
||||
.ok_or_else(|| Error::Audio("empty Codec2 frame".into()))?;
|
||||
let wire_mode =
|
||||
Codec2Mode::from_header(header).map_err(|error| Error::Audio(error.to_string()))?;
|
||||
let mode = match wire_mode {
|
||||
Codec2Mode::Mode700C => Mode::Rate700C,
|
||||
Codec2Mode::Mode1600 => Mode::Rate1600,
|
||||
Codec2Mode::Mode3200 => Mode::Rate3200,
|
||||
other => {
|
||||
return Err(Error::Audio(format!(
|
||||
"unsupported native Codec2 mode {other:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let index = match self.codec2.iter().position(|(m, _)| *m == wire_mode) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let mut storage = Box::<Codec>::new_uninit();
|
||||
Codec::initialise(&mut storage, mode);
|
||||
// SAFETY: initialise completed in final storage above.
|
||||
self.codec2
|
||||
.push((wire_mode, unsafe { storage.assume_init() }));
|
||||
self.codec2.len() - 1
|
||||
}
|
||||
};
|
||||
let codec = &mut self.codec2[index].1;
|
||||
// Python decodes every whole native frame in the payload.
|
||||
let mut pcm = vec![0i16; mode.samples()];
|
||||
let mut samples = Vec::with_capacity(bytes.len() / mode.bytes() * mode.samples());
|
||||
for chunk in bytes.chunks_exact(mode.bytes()) {
|
||||
codec
|
||||
.decode(chunk, &mut pcm)
|
||||
.map_err(|_| Error::Audio("invalid native frame".into()))?;
|
||||
samples.extend(pcm.iter().map(|v| f32::from(*v) / 32768.0));
|
||||
}
|
||||
let mono = RawAudioFrame::new(1, samples).map_err(|e| Error::Audio(e.to_string()))?;
|
||||
mono.resampled(CODEC2_SAMPLE_RATE_HZ, self.sample_rate_hz)
|
||||
.with_channels(self.channels)
|
||||
.map_err(|e| Error::Audio(e.to_string()))
|
||||
}
|
||||
}
|
||||
+1767
-297
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"generator": "tools/fixtures/lxst_media_fixtures.py",
|
||||
"lxst_version": "0.6.0",
|
||||
"lxst_commit": "6a329bf6d956ca8b15077d4c470afe4cb7c669cc",
|
||||
"rns_version": "1.6.0",
|
||||
"rns_commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4",
|
||||
"buffer_frames": {"16": 2, "32": 2, "48": 2, "64": 5, "80": 5, "96": 5, "112": 2, "128": 3},
|
||||
"frame_time_ms": {"16": 400, "32": 320, "48": 200, "64": 60, "80": 60, "96": 60, "112": 10, "128": 20},
|
||||
"raw128": {"machine": "aarch64", "longdouble_bits": 128, "longdouble_nmant": 112, "samples": [0.0, 0.5, -0.25, 1.0], "payload_hex": "c0000000000000000000000000000000000000000000000000000000000000fe3f0000000000000000000000000000fdbf0000000000000000000000000000ff3f", "decoded": [0.0, 0.5, -0.25, 1.0]},
|
||||
"mixed_batch": [
|
||||
{"name": "opus_60ms", "codec": 1, "wire_hex": "01db037b5af3c47e60df913de2a4bc5f21a2bd4eb9afea6c144d002a6a9a8c966f0ffd97d00daeb04dcf27e9a5f40332fd4ef0fcea52582fae", "decoded_sample_frames": 2880},
|
||||
{"name": "codec2_3200_200ms", "codec": 2, "wire_hex": "0206c07d231bd4ace738c0002900d6bdeb5ac681000019f81dd0c5b962029b86d5ffc5884a0094bd6b5ac591840194adebdac5802900d6bdeb5ac581000019f81dd0c5b962029b86d5ffc5884a0094bd6b5a", "decoded_sample_frames": 9595},
|
||||
{"name": "opus_20ms", "codec": 1, "wire_hex": "01d8b51a679c5c8787e2a9b61c6bc130233e9db6b2", "decoded_sample_frames": 960}
|
||||
]
|
||||
}
|
||||
@@ -69,7 +69,8 @@ fn python_telephone_helper_loads_reference_and_creates_destination() {
|
||||
.expect("READY event");
|
||||
assert_eq!(ready["app_name"], "lxst");
|
||||
assert_eq!(ready["primitive_name"], "telephony");
|
||||
assert_eq!(ready["lxst_version"], "0.4.5");
|
||||
assert_eq!(ready["lxst_version"], "0.6.0");
|
||||
assert_eq!(ready["rns_version"], "1.6.1");
|
||||
let lxst_root = PathBuf::from(ready["lxst_root"].as_str().expect("LXST root"));
|
||||
if let Ok(configured) = std::env::var("LXST_UPSTREAM_DIR") {
|
||||
let configured = PathBuf::from(configured)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The headless Telephone helper, plus path hop counts and per-frame codec headers.
|
||||
|
||||
Commands added to tools/interop/lxst_telephone_helper.py:
|
||||
{"cmd": "hops", "destination_hash": hex, "timeout": s}
|
||||
-> HOPS with RNS.Transport.hops_to
|
||||
{"cmd": "send_call_frames", "count": n}
|
||||
encodes n 48 kHz sine frames with a fresh copy of the Telephone's transmit
|
||||
codec, paced at its target frame time -> CALL_FRAMES_DONE
|
||||
{"cmd": "profile_codec", "profile": p}
|
||||
-> PROFILE_CODEC, the codec header byte, channels and frame time Telephony.Profiles gives p
|
||||
Events added:
|
||||
FRAME_SENT {"codec", "stereo" (Opus TOC s bit), "digest"} of each frame Packetizer puts on the wire
|
||||
FRAME_RECEIVED {"frames": [{"codec", "stereo", "digest"}]} of each packet LinkSource reads
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools" / "interop"))
|
||||
import lxst_telephone_helper as helper # noqa: E402
|
||||
|
||||
OPUS = 0x01
|
||||
|
||||
_setup_python_stack = helper.setup_python_stack
|
||||
_handle_command = helper.handle_command
|
||||
|
||||
|
||||
def frame_fields(frame: bytes) -> dict:
|
||||
return {
|
||||
"codec": int(frame[0]),
|
||||
"stereo": bool(frame[1] & 0x04) if frame[0] == OPUS and len(frame) > 1 else None,
|
||||
"digest": hashlib.sha256(bytes(frame)).hexdigest()[:16],
|
||||
}
|
||||
|
||||
|
||||
def setup_python_stack():
|
||||
codec2_stubbed = _setup_python_stack()
|
||||
import LXST.Network as Network
|
||||
import RNS.vendor.umsgpack as mp
|
||||
from LXST.Codecs import codec_header_byte
|
||||
|
||||
packetizer_handle_frame = Network.Packetizer.handle_frame
|
||||
link_source_packet = Network.LinkSource._packet
|
||||
|
||||
def handle_frame(self, frame, source=None):
|
||||
sendable = not (
|
||||
type(self.destination) == helper._RNS.Link and not self.destination.status == helper._RNS.Link.ACTIVE
|
||||
) and not self.squelched
|
||||
result = packetizer_handle_frame(self, frame, source)
|
||||
if sendable:
|
||||
helper.emit({"event": "FRAME_SENT", **frame_fields(codec_header_byte(type(self.source.codec)) + frame)})
|
||||
return result
|
||||
|
||||
def packet(self, data, packet):
|
||||
try:
|
||||
unpacked = mp.unpackb(data)
|
||||
if type(unpacked) == dict and Network.FIELD_FRAMES in unpacked:
|
||||
frames = unpacked[Network.FIELD_FRAMES]
|
||||
if type(frames) != list:
|
||||
frames = [frames]
|
||||
helper.emit({"event": "FRAME_RECEIVED", "frames": [frame_fields(frame) for frame in frames]})
|
||||
except Exception:
|
||||
pass
|
||||
return link_source_packet(self, data, packet)
|
||||
|
||||
Network.Packetizer.handle_frame = handle_frame
|
||||
Network.LinkSource._packet = packet
|
||||
return codec2_stubbed
|
||||
|
||||
|
||||
def send_call_frames(command: dict) -> None:
|
||||
np = helper._np
|
||||
telephone = helper._telephone
|
||||
profile = telephone.active_profile
|
||||
codec = type(telephone.transmit_codec)(profile=telephone.transmit_codec.profile)
|
||||
frame_ms = telephone.target_frame_time_ms
|
||||
|
||||
class Source:
|
||||
samplerate = 48000
|
||||
channels = 1
|
||||
|
||||
samples = 48000 * frame_ms // 1000
|
||||
sent = 0
|
||||
started = time.time()
|
||||
for index in range(int(command["count"])):
|
||||
t = (np.arange(samples) + index * samples) / 48000.0
|
||||
frame = (0.25 * np.sin(2 * math.pi * 440.0 * t)).astype(np.float32).reshape((samples, 1))
|
||||
# send_packetized_frame rebinds codec.source to the packetizer's source.
|
||||
codec.source = Source()
|
||||
sent += bool(helper.send_packetized_frame(codec, codec.encode(frame)))
|
||||
time.sleep(max(0.0, started + (index + 1) * frame_ms / 1000.0 - time.time()))
|
||||
helper.emit({"event": "CALL_FRAMES_DONE", "id": command.get("id"), "profile": profile, "frame_ms": frame_ms, "sent": sent})
|
||||
|
||||
|
||||
def profile_codec(command: dict) -> None:
|
||||
from LXST.Codecs import codec_header_byte
|
||||
|
||||
Profiles = helper._Telephony.Profiles
|
||||
profile = int(command["profile"])
|
||||
helper.emit(
|
||||
{
|
||||
"event": "PROFILE_CODEC",
|
||||
"id": command.get("id"),
|
||||
"profile": profile,
|
||||
"codec": codec_header_byte(type(Profiles.get_codec(profile)))[0],
|
||||
"channels": Profiles.get_codec(profile).channels,
|
||||
"frame_ms": Profiles.get_frame_time(profile),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def handle_command(command: dict, args) -> bool:
|
||||
if command.get("cmd") == "profile_codec":
|
||||
profile_codec(command)
|
||||
return True
|
||||
if command.get("cmd") == "send_call_frames":
|
||||
threading.Thread(target=send_call_frames, args=(command,), daemon=True).start()
|
||||
return True
|
||||
if command.get("cmd") != "hops":
|
||||
return _handle_command(command, args)
|
||||
RNS = helper._RNS
|
||||
destination_hash = bytes.fromhex(command["destination_hash"])
|
||||
deadline = time.time() + float(command.get("timeout", 10))
|
||||
requested = 0.0
|
||||
while not RNS.Transport.has_path(destination_hash) and time.time() < deadline:
|
||||
if time.time() - requested > 1.0:
|
||||
RNS.Transport.request_path(destination_hash)
|
||||
requested = time.time()
|
||||
time.sleep(0.1)
|
||||
helper.emit(
|
||||
{
|
||||
"event": "HOPS",
|
||||
"id": command.get("id"),
|
||||
"has_path": bool(RNS.Transport.has_path(destination_hash)),
|
||||
"hops": RNS.Transport.hops_to(destination_hash),
|
||||
}
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
helper.setup_python_stack = setup_python_stack
|
||||
helper.handle_command = handle_command
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(helper.main())
|
||||
@@ -44,4 +44,4 @@ Microsoft Corporation:
|
||||
https://datatracker.ietf.org/ipr/1914/
|
||||
|
||||
Broadcom Corporation:
|
||||
https://datatracker.ietf.org/ipr/1526/
|
||||
https://datatracker.ietf.org/ipr/1526/
|
||||
@@ -0,0 +1,333 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate or refresh the reviewed public-API compatibility snapshots."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CONFIG_PATH = ROOT / "api" / "stability.json"
|
||||
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
|
||||
HASH_PATTERN = re.compile(r"^[0-9a-f]{64}$")
|
||||
TIERS = {
|
||||
"candidate-stable",
|
||||
"provisional",
|
||||
"experimental",
|
||||
"application-internal",
|
||||
"tool-internal",
|
||||
}
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
print(f"api baseline: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def run(args: list[str], *, env: dict[str, str] | None = None) -> str:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
if result.stdout:
|
||||
print(result.stdout, file=sys.stderr, end="")
|
||||
if result.stderr:
|
||||
print(result.stderr, file=sys.stderr, end="")
|
||||
fail(f"command failed ({result.returncode}): {' '.join(args)}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def load_config() -> dict[str, object]:
|
||||
try:
|
||||
config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as error:
|
||||
fail(f"cannot read {CONFIG_PATH.name}: {error}")
|
||||
if not isinstance(config, dict) or config.get("schemaVersion") != 2:
|
||||
fail("unsupported api-stability schema")
|
||||
return config
|
||||
|
||||
|
||||
def require_keys(
|
||||
record: object, required: set[str], label: str,
|
||||
optional: set[str] | None = None,
|
||||
) -> None:
|
||||
if not isinstance(record, dict):
|
||||
fail(f"{label} must be an object")
|
||||
missing = required - set(record)
|
||||
unknown = set(record) - required - (optional or set())
|
||||
if missing or unknown:
|
||||
fail(f"{label}: missing fields {sorted(missing)}, unknown fields {sorted(unknown)}")
|
||||
|
||||
|
||||
def public_packages(manifest_path: str) -> set[str]:
|
||||
metadata = json.loads(
|
||||
run(
|
||||
[
|
||||
"cargo",
|
||||
"metadata",
|
||||
"--format-version",
|
||||
"1",
|
||||
"--no-deps",
|
||||
"--manifest-path",
|
||||
manifest_path,
|
||||
]
|
||||
)
|
||||
)
|
||||
return {
|
||||
str(package["name"])
|
||||
for package in metadata["packages"]
|
||||
if any("lib" in target["kind"] for target in package["targets"])
|
||||
}
|
||||
|
||||
|
||||
def validate_metadata(
|
||||
config: dict[str, object], *, updating: bool = False
|
||||
) -> list[dict[str, object]]:
|
||||
require_keys(
|
||||
config, {"schemaVersion", "tool", "baseline", "compatibilityFloor", "packages", "newPackages"},
|
||||
"metadata",
|
||||
)
|
||||
if config["schemaVersion"] != 2:
|
||||
fail("unsupported api-stability schema")
|
||||
require_keys(
|
||||
config["tool"], {"name", "version", "rustdocToolchain", "target", "arguments"},
|
||||
"tool",
|
||||
)
|
||||
require_keys(config["baseline"], {"commit"}, "baseline")
|
||||
require_keys(
|
||||
config["compatibilityFloor"], {"evidenceCommit", "sourceCommit"},
|
||||
"compatibility floor",
|
||||
)
|
||||
new_packages = config["newPackages"]
|
||||
if (not isinstance(new_packages, list)
|
||||
or not all(isinstance(item, str) and item for item in new_packages)
|
||||
or new_packages != sorted(set(new_packages))):
|
||||
fail("newPackages must be a sorted list of unique package names")
|
||||
|
||||
tool = config.get("tool")
|
||||
if not isinstance(tool, dict):
|
||||
fail("tool contract is missing")
|
||||
if tool.get("name") != "cargo-public-api" or tool.get("version") != "0.52.0":
|
||||
fail("tool must be cargo-public-api 0.52.0")
|
||||
if tool.get("rustdocToolchain") != "nightly-2026-08-01":
|
||||
fail("rustdoc toolchain must be nightly-2026-08-01")
|
||||
if tool.get("target") != "aarch64-apple-darwin":
|
||||
fail("API target must be aarch64-apple-darwin")
|
||||
if tool.get("arguments") != ["--all-features", "-sss"]:
|
||||
fail("API arguments must remain all-features and simplified")
|
||||
|
||||
baseline = config.get("baseline")
|
||||
if not isinstance(baseline, dict):
|
||||
fail("baseline identity is missing")
|
||||
commit = baseline.get("commit")
|
||||
if not isinstance(commit, str) or not SHA_PATTERN.fullmatch(commit):
|
||||
fail("baseline commit must be a full Git commit")
|
||||
commit_check = subprocess.run(
|
||||
["git", "cat-file", "-e", f"{commit}^{{commit}}"], cwd=ROOT
|
||||
)
|
||||
if commit_check.returncode != 0:
|
||||
fail(f"baseline commit {commit} is unavailable in this checkout")
|
||||
ancestor_check = subprocess.run(
|
||||
["git", "merge-base", "--is-ancestor", commit, "HEAD"], cwd=ROOT
|
||||
)
|
||||
if ancestor_check.returncode != 0:
|
||||
fail(f"baseline commit {commit} is not an ancestor of HEAD")
|
||||
|
||||
compatibility_floor = config.get("compatibilityFloor")
|
||||
if not isinstance(compatibility_floor, dict):
|
||||
fail("compatibility floor identity is missing")
|
||||
floor_evidence = compatibility_floor.get("evidenceCommit")
|
||||
floor_source = compatibility_floor.get("sourceCommit")
|
||||
for label, floor_commit in (
|
||||
("evidence", floor_evidence),
|
||||
("source", floor_source),
|
||||
):
|
||||
if not isinstance(floor_commit, str) or not SHA_PATTERN.fullmatch(
|
||||
floor_commit
|
||||
):
|
||||
fail(f"compatibility floor {label} commit must be a full Git commit")
|
||||
floor_check = subprocess.run(
|
||||
["git", "cat-file", "-e", f"{floor_commit}^{{commit}}"], cwd=ROOT
|
||||
)
|
||||
if floor_check.returncode != 0:
|
||||
fail(f"compatibility floor {label} commit {floor_commit} is unavailable")
|
||||
floor_ancestor = subprocess.run(
|
||||
["git", "merge-base", "--is-ancestor", floor_commit, "HEAD"], cwd=ROOT
|
||||
)
|
||||
if floor_ancestor.returncode != 0:
|
||||
fail(f"compatibility floor {label} commit is not an ancestor of HEAD")
|
||||
|
||||
packages = config.get("packages")
|
||||
if not isinstance(packages, list) or not packages:
|
||||
fail("package ledger is empty")
|
||||
|
||||
manifests: dict[str, set[str]] = {}
|
||||
seen_names: set[tuple[str, str]] = set()
|
||||
for package in packages:
|
||||
if not isinstance(package, dict):
|
||||
fail("package ledger entry is not an object")
|
||||
require_keys(package, {"name", "manifestPath", "tier", "compatibility",
|
||||
"snapshot", "itemCount", "sha256"}, "package")
|
||||
if type(package["itemCount"]) is not int or package["itemCount"] < 0:
|
||||
fail("package item count must be a non-negative integer")
|
||||
name = package.get("name")
|
||||
manifest = package.get("manifestPath")
|
||||
snapshot = package.get("snapshot")
|
||||
if not isinstance(name, str) or not isinstance(manifest, str):
|
||||
fail("package name or manifest path is invalid")
|
||||
if (manifest, name) in seen_names:
|
||||
fail(f"duplicate package ledger entry {manifest}:{name}")
|
||||
seen_names.add((manifest, name))
|
||||
if package.get("tier") not in TIERS:
|
||||
fail(f"{name} has an unknown stability tier")
|
||||
if package.get("compatibility") != "reviewed-snapshot":
|
||||
fail(f"{name} must use the reviewed-snapshot compatibility policy")
|
||||
if not isinstance(snapshot, str) or not snapshot.startswith("api/snapshots/"):
|
||||
fail(f"{name} has an invalid snapshot path")
|
||||
snapshot_path = (ROOT / snapshot).resolve()
|
||||
if not snapshot_path.is_relative_to(ROOT / "api/snapshots"):
|
||||
fail(f"{name} snapshot must stay inside api/snapshots")
|
||||
if not snapshot_path.is_file() and not updating:
|
||||
fail(f"{name} snapshot is missing: {snapshot}")
|
||||
if not updating:
|
||||
snapshot_bytes = snapshot_path.read_bytes()
|
||||
expected_hash = package.get("sha256")
|
||||
actual_hash = hashlib.sha256(snapshot_bytes).hexdigest()
|
||||
if not isinstance(expected_hash, str) or not HASH_PATTERN.fullmatch(expected_hash):
|
||||
fail(f"{name} has an invalid snapshot hash")
|
||||
if actual_hash != expected_hash:
|
||||
fail(f"{name} snapshot hash is {actual_hash}, expected {expected_hash}")
|
||||
item_count = len(snapshot_bytes.decode("utf-8").splitlines())
|
||||
if package.get("itemCount") != item_count:
|
||||
fail(
|
||||
f"{name} snapshot has {item_count} items, "
|
||||
f"expected {package.get('itemCount')}"
|
||||
)
|
||||
manifests.setdefault(manifest, public_packages(manifest))
|
||||
|
||||
for manifest, actual_names in manifests.items():
|
||||
recorded_names = {
|
||||
str(package["name"])
|
||||
for package in packages
|
||||
if package["manifestPath"] == manifest
|
||||
}
|
||||
if recorded_names != actual_names:
|
||||
fail(
|
||||
f"library inventory drift for {manifest}: "
|
||||
f"recorded={sorted(recorded_names)}, actual={sorted(actual_names)}"
|
||||
)
|
||||
return packages
|
||||
|
||||
|
||||
def tool_path_and_environment(config: dict[str, object]) -> tuple[str, dict[str, str]]:
|
||||
tool_config = config["tool"]
|
||||
assert isinstance(tool_config, dict)
|
||||
executable = os.environ.get("CARGO_PUBLIC_API") or shutil.which("cargo-public-api")
|
||||
if not executable:
|
||||
fail("cargo-public-api is unavailable; install exact version 0.52.0")
|
||||
version = run([executable, "public-api", "--version"]).strip()
|
||||
if version != "cargo-public-api 0.52.0":
|
||||
fail(f"unexpected cargo-public-api version: {version!r}")
|
||||
environment = os.environ.copy()
|
||||
environment["RUSTUP_TOOLCHAIN"] = str(tool_config["rustdocToolchain"])
|
||||
return executable, environment
|
||||
|
||||
|
||||
def render_snapshot(
|
||||
executable: str,
|
||||
environment: dict[str, str],
|
||||
config: dict[str, object],
|
||||
package: dict[str, object],
|
||||
) -> bytes:
|
||||
tool = config["tool"]
|
||||
assert isinstance(tool, dict)
|
||||
arguments = tool["arguments"]
|
||||
assert isinstance(arguments, list)
|
||||
output = run(
|
||||
[
|
||||
executable,
|
||||
"public-api",
|
||||
"--manifest-path",
|
||||
str(package["manifestPath"]),
|
||||
"--package",
|
||||
str(package["name"]),
|
||||
*[str(argument) for argument in arguments],
|
||||
"--target",
|
||||
str(tool["target"]),
|
||||
"--color",
|
||||
"never",
|
||||
],
|
||||
env=environment,
|
||||
)
|
||||
return (output.rstrip() + "\n").encode("utf-8")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Compare current public APIs with the stored snapshots, or refresh them after review."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--metadata-only", action="store_true",
|
||||
help="validate metadata, package inventory and stored snapshot hashes without generating API output; incompatible with --update",
|
||||
)
|
||||
parser.add_argument("--update", action="store_true",
|
||||
help="regenerate snapshots and update their counts/hashes in api/stability.json; review the diff before committing")
|
||||
parser.add_argument("--snapshot-source-commit",
|
||||
help="optional HEAD guard for --update; includes uncommitted source changes")
|
||||
args = parser.parse_args()
|
||||
if args.metadata_only and args.update:
|
||||
fail("--metadata-only and --update are mutually exclusive")
|
||||
|
||||
config = load_config()
|
||||
if args.snapshot_source_commit is not None:
|
||||
if not args.update:
|
||||
fail("--snapshot-source-commit requires --update")
|
||||
head = run(["git", "rev-parse", "HEAD"]).strip()
|
||||
if args.snapshot_source_commit != head:
|
||||
fail("snapshot source guard must match HEAD")
|
||||
packages = validate_metadata(config, updating=args.update)
|
||||
if args.metadata_only:
|
||||
print("api baseline metadata: ok")
|
||||
return
|
||||
|
||||
executable, environment = tool_path_and_environment(config)
|
||||
changed = False
|
||||
for package in packages:
|
||||
rendered = render_snapshot(executable, environment, config, package)
|
||||
snapshot_path = ROOT / str(package["snapshot"])
|
||||
if args.update:
|
||||
if not snapshot_path.is_file() or snapshot_path.read_bytes() != rendered:
|
||||
snapshot_path.write_bytes(rendered)
|
||||
changed = True
|
||||
package["itemCount"] = len(rendered.decode("utf-8").splitlines())
|
||||
package["sha256"] = hashlib.sha256(rendered).hexdigest()
|
||||
elif snapshot_path.read_bytes() != rendered:
|
||||
fail(
|
||||
f"{package['name']} public API differs from {package['snapshot']}; "
|
||||
"review the diff before running --update"
|
||||
)
|
||||
|
||||
if args.update:
|
||||
updated = json.dumps(config, indent=2) + "\n"
|
||||
if CONFIG_PATH.read_text(encoding="utf-8") != updated:
|
||||
CONFIG_PATH.write_text(updated, encoding="utf-8")
|
||||
changed = True
|
||||
print("api baseline snapshots updated" if changed else "api baseline unchanged")
|
||||
else:
|
||||
print("api baseline: ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reject removals from the reviewed public-API compatibility floor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LEDGER_PATH = ROOT / "api" / "stability.json"
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
print(f"api compatibility: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def git_show(commit: str, path: str) -> str:
|
||||
result = subprocess.run(
|
||||
["git", "show", f"{commit}:{path}"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
if result.stderr:
|
||||
print(result.stderr, file=sys.stderr, end="")
|
||||
fail(f"cannot read compatibility floor {commit}:{path}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def load_floor_ledger(commit: str) -> dict[str, object]:
|
||||
for path in ("api/stability.json", "api-stability.json"):
|
||||
result = subprocess.run(
|
||||
["git", "show", f"{commit}:{path}"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
return json.loads(result.stdout)
|
||||
fail(f"cannot read API ledger at compatibility floor {commit}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
metadata = subprocess.run(
|
||||
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
|
||||
)
|
||||
if metadata.returncode != 0:
|
||||
fail("snapshot metadata is invalid")
|
||||
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
|
||||
floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit")
|
||||
if not isinstance(floor, str):
|
||||
fail("api/stability.json has no compatibility-floor commit")
|
||||
floor_ledger = load_floor_ledger(floor)
|
||||
floor_snapshots = {
|
||||
package["name"]: package["snapshot"] for package in floor_ledger["packages"]
|
||||
}
|
||||
current_names = {package["name"] for package in ledger["packages"]}
|
||||
removed_packages = set(floor_snapshots) - current_names
|
||||
if removed_packages:
|
||||
fail(f"compatibility-floor packages removed: {sorted(removed_packages)}")
|
||||
new_packages = sorted(current_names - set(floor_snapshots))
|
||||
if ledger["newPackages"] != new_packages:
|
||||
fail("newPackages must match additions to the compatibility floor")
|
||||
total_added = 0
|
||||
total_removed = 0
|
||||
for package in ledger["packages"]:
|
||||
path = package["snapshot"]
|
||||
floor_path = floor_snapshots.get(package["name"])
|
||||
before = set(git_show(floor, floor_path).splitlines()) if floor_path else set()
|
||||
after = set((ROOT / path).read_text(encoding="utf-8").splitlines())
|
||||
added = sorted(after - before)
|
||||
removed = sorted(before - after)
|
||||
total_added += len(added)
|
||||
total_removed += len(removed)
|
||||
print(f"{package['name']}: +{len(added)} -{len(removed)}")
|
||||
if removed:
|
||||
for line in removed:
|
||||
print(f"- {line}", file=sys.stderr)
|
||||
if total_removed:
|
||||
fail(
|
||||
f"{total_removed} public API lines were removed from the compatibility floor; "
|
||||
"the current policy permits additions only"
|
||||
)
|
||||
print(f"api compatibility: additive-only (+{total_added}, -0)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the reviewed Cargo manifest and feature contract for library packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import difflib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LEDGER_PATH = ROOT / "api" / "stability.json"
|
||||
CONTRACT_PATH = ROOT / "api" / "snapshots" / "manifest-contract.json"
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
print(f"api manifest contract: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def metadata(manifest_path: str) -> dict[str, object]:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"cargo",
|
||||
"metadata",
|
||||
"--format-version",
|
||||
"1",
|
||||
"--no-deps",
|
||||
"--manifest-path",
|
||||
manifest_path,
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
if result.stderr:
|
||||
print(result.stderr, file=sys.stderr, end="")
|
||||
fail(f"cargo metadata failed for {manifest_path}")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def dependency_contract(dependency: dict[str, object]) -> dict[str, object]:
|
||||
source = dependency.get("source")
|
||||
return {
|
||||
"name": dependency["name"],
|
||||
"rename": dependency.get("rename"),
|
||||
"kind": dependency.get("kind"),
|
||||
"target": dependency.get("target"),
|
||||
"requirement": dependency["req"],
|
||||
"optional": dependency["optional"],
|
||||
"defaultFeatures": dependency["uses_default_features"],
|
||||
"features": sorted(dependency["features"]),
|
||||
"sourceKind": "registry" if source else "path",
|
||||
}
|
||||
|
||||
|
||||
def package_contract(package: dict[str, object]) -> dict[str, object]:
|
||||
targets = []
|
||||
for target in package["targets"]:
|
||||
if "lib" not in target["kind"]:
|
||||
continue
|
||||
targets.append(
|
||||
{
|
||||
"name": target["name"],
|
||||
"kind": sorted(target["kind"]),
|
||||
"crateTypes": sorted(target["crate_types"]),
|
||||
"requiredFeatures": sorted(target.get("required-features", [])),
|
||||
}
|
||||
)
|
||||
dependencies = [
|
||||
dependency_contract(dependency)
|
||||
for dependency in package["dependencies"]
|
||||
if dependency.get("kind") != "dev"
|
||||
]
|
||||
dependencies.sort(
|
||||
key=lambda item: (
|
||||
str(item["kind"]),
|
||||
str(item["target"]),
|
||||
str(item["rename"]),
|
||||
str(item["name"]),
|
||||
)
|
||||
)
|
||||
return {
|
||||
"name": package["name"],
|
||||
"version": package["version"],
|
||||
"rustVersion": package.get("rust_version"),
|
||||
"edition": package["edition"],
|
||||
"features": {
|
||||
name: sorted(values)
|
||||
for name, values in sorted(package["features"].items())
|
||||
},
|
||||
"targets": sorted(targets, key=lambda item: str(item["name"])),
|
||||
"dependencies": dependencies,
|
||||
}
|
||||
|
||||
|
||||
def render_contract() -> str:
|
||||
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
|
||||
manifests = sorted({entry["manifestPath"] for entry in ledger["packages"]})
|
||||
recorded_names = {entry["name"] for entry in ledger["packages"]}
|
||||
packages: list[dict[str, object]] = []
|
||||
for manifest in manifests:
|
||||
for package in metadata(manifest)["packages"]:
|
||||
if package["name"] in recorded_names:
|
||||
packages.append(package_contract(package))
|
||||
actual_names = {entry["name"] for entry in packages}
|
||||
if actual_names != recorded_names:
|
||||
fail(
|
||||
f"package inventory differs: expected={sorted(recorded_names)}, "
|
||||
f"actual={sorted(actual_names)}"
|
||||
)
|
||||
contract = {
|
||||
"schemaVersion": 1,
|
||||
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
|
||||
"packages": sorted(packages, key=lambda item: str(item["name"])),
|
||||
}
|
||||
return json.dumps(contract, indent=2) + "\n"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Compare current library Cargo metadata with api/snapshots/manifest-contract.json."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--print",
|
||||
action="store_true",
|
||||
dest="print_contract",
|
||||
help="print current Cargo contract JSON instead of comparing it with the saved snapshot",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--update",
|
||||
action="store_true",
|
||||
help="replace the saved manifest contract with current Cargo metadata; review the diff before committing",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.print_contract and args.update:
|
||||
fail("--print and --update are mutually exclusive")
|
||||
rendered = render_contract()
|
||||
if args.print_contract:
|
||||
print(rendered, end="")
|
||||
return
|
||||
if args.update:
|
||||
CONTRACT_PATH.write_text(rendered, encoding="utf-8")
|
||||
print("api manifest contract updated")
|
||||
return
|
||||
if not CONTRACT_PATH.is_file():
|
||||
fail(f"missing {CONTRACT_PATH.relative_to(ROOT)}")
|
||||
expected = CONTRACT_PATH.read_text(encoding="utf-8")
|
||||
if expected != rendered:
|
||||
print(
|
||||
"".join(
|
||||
difflib.unified_diff(
|
||||
expected.splitlines(keepends=True),
|
||||
rendered.splitlines(keepends=True),
|
||||
fromfile=str(CONTRACT_PATH.relative_to(ROOT)),
|
||||
tofile="current Cargo metadata",
|
||||
)
|
||||
),
|
||||
file=sys.stderr,
|
||||
end="",
|
||||
)
|
||||
fail("manifest, feature, target, or dependency contract drift")
|
||||
print("api manifest contract: ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check source-release metadata that must stay true for this workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EXPECTED_PACKAGES = {"lxst-core", "lxst-codec2", "lxst-embedded", "lxst-rns", "lxst-telephony"}
|
||||
EXPECTED_MSRV = "1.89"
|
||||
EMBEDDED_MSRV = {"lxst-codec2": "1.87", "lxst-embedded": "1.87"}
|
||||
EXPECTED_RETICULUM_VERSION = "1.5.1"
|
||||
EXPECTED_RETICULUM_COMMIT = "f6d0d698dd7e6edc180f9c3697ab1c873571f372"
|
||||
EXPECTED_OPUS_DEPENDENCY = (
|
||||
'opus-rs = { version = "=0.1.42", default-features = false, '
|
||||
'features = ["heap"] }'
|
||||
)
|
||||
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
print(f"source-release contract: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
metadata = json.loads(
|
||||
subprocess.run(
|
||||
["cargo", "metadata", "--format-version", "1", "--no-deps", "--locked"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout
|
||||
)
|
||||
|
||||
packages = {package["name"]: package for package in metadata["packages"]}
|
||||
if set(packages) != EXPECTED_PACKAGES:
|
||||
fail(
|
||||
"package inventory changed; update this check deliberately "
|
||||
f"(expected {sorted(EXPECTED_PACKAGES)}, found {sorted(packages)})"
|
||||
)
|
||||
|
||||
reticulum_requirements: set[str] = set()
|
||||
for name, package in sorted(packages.items()):
|
||||
if package["publish"] != []:
|
||||
fail(f"{name} must declare publish = false")
|
||||
expected_msrv = EMBEDDED_MSRV.get(name, EXPECTED_MSRV)
|
||||
if package["rust_version"] != expected_msrv:
|
||||
fail(
|
||||
f"{name} must declare Rust {expected_msrv} "
|
||||
f"(found {package['rust_version']!r})"
|
||||
)
|
||||
for dependency in package["dependencies"]:
|
||||
if dependency["name"].startswith("rns-"):
|
||||
reticulum_requirements.add(dependency["req"])
|
||||
|
||||
if len(reticulum_requirements) != 1:
|
||||
fail(
|
||||
"rsReticulum dependencies must share one compatibility requirement "
|
||||
f"(found {sorted(reticulum_requirements)})"
|
||||
)
|
||||
reticulum_requirement = reticulum_requirements.pop()
|
||||
if reticulum_requirement != f"~{EXPECTED_RETICULUM_VERSION}":
|
||||
fail(
|
||||
"rsReticulum compatibility requirement is "
|
||||
f"{reticulum_requirement!r}, expected ~{EXPECTED_RETICULUM_VERSION}"
|
||||
)
|
||||
|
||||
if not (ROOT / "Cargo.lock").is_file():
|
||||
fail("Cargo.lock must be committed for reproducible workspace builds")
|
||||
|
||||
if "## Unreleased" not in (ROOT / "CHANGELOG.md").read_text(encoding="utf-8"):
|
||||
fail("CHANGELOG.md must retain an Unreleased section")
|
||||
|
||||
root_manifest = (ROOT / "Cargo.toml").read_text(encoding="utf-8")
|
||||
if EXPECTED_OPUS_DEPENDENCY not in root_manifest:
|
||||
fail("workspace must consume exact upstream opus-rs 0.1.42 with heap state")
|
||||
if (ROOT / "vendor/opus-rs").exists():
|
||||
fail("local opus-rs vendor/fork must not exist")
|
||||
|
||||
subprocess.run(
|
||||
[sys.executable, "tools/check-third-party-licenses.py"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
|
||||
workflow = (ROOT / ".github/workflows/ci.yml").read_text(encoding="utf-8")
|
||||
version_match = re.search(
|
||||
r"^\s*RSLXST_RSRETICULUM_VERSION:\s*(\S+)\s*$", workflow, re.MULTILINE
|
||||
)
|
||||
commit_match = re.search(
|
||||
r"^\s*RSLXST_RSRETICULUM_COMMIT:\s*([0-9a-f]+)\s*$", workflow, re.MULTILINE
|
||||
)
|
||||
if not version_match or version_match.group(1) != EXPECTED_RETICULUM_VERSION:
|
||||
fail("CI rsReticulum compatibility version does not match the manifest contract")
|
||||
if not commit_match or commit_match.group(1) != EXPECTED_RETICULUM_COMMIT:
|
||||
fail("CI rsReticulum source is not pinned to the qualified commit")
|
||||
|
||||
action_uses = re.findall(r"^\s*-\s+uses:\s+([^\s#]+)", workflow, re.MULTILINE)
|
||||
if not action_uses:
|
||||
fail("CI workflow contains no external actions")
|
||||
for action in action_uses:
|
||||
if action.startswith("./"):
|
||||
continue
|
||||
if "@" not in action or not SHA_PATTERN.fullmatch(action.rsplit("@", 1)[1]):
|
||||
fail(f"CI action is not pinned to a full commit: {action}")
|
||||
|
||||
reticulum_checkouts = []
|
||||
python_checkouts: dict[str, list[str]] = {"LXST": [], "Reticulum": []}
|
||||
lines = workflow.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
match = re.match(r"^(\s*)-\s+uses:\s+([^\s#]+)", line)
|
||||
if not match:
|
||||
continue
|
||||
indentation = len(match.group(1))
|
||||
block = [line]
|
||||
for following in lines[index + 1 :]:
|
||||
if following.strip() and len(following) - len(following.lstrip()) <= indentation:
|
||||
break
|
||||
block.append(following)
|
||||
text = "\n".join(block)
|
||||
if "repository: ${{ github.repository_owner }}/rsReticulum" in text:
|
||||
reticulum_checkouts.append(text)
|
||||
for name in python_checkouts:
|
||||
if f"repository: markqvist/{name}\n" in text:
|
||||
python_checkouts[name].append(text)
|
||||
|
||||
if not reticulum_checkouts:
|
||||
fail("CI workflow contains no rsReticulum checkout")
|
||||
expected_ref = "ref: ${{ env.RSLXST_RSRETICULUM_COMMIT }}"
|
||||
for checkout in reticulum_checkouts:
|
||||
if expected_ref not in checkout:
|
||||
fail("every CI rsReticulum checkout must use the qualified commit")
|
||||
|
||||
# The Python trees are fixed parity oracles, never moving implementation inputs.
|
||||
python_pins = {
|
||||
"LXST": (
|
||||
"RSLXST_PYTHON_LXST_COMMIT",
|
||||
json.loads((ROOT / "tools/reference/lxst_reference_lock.json").read_text())["commit"],
|
||||
),
|
||||
"Reticulum": ("RSLXST_PYTHON_RNS_COMMIT", "cff4d03fdbd6bfb63b765280cd944756ac5cce8d"),
|
||||
}
|
||||
for name, (variable, revision) in python_pins.items():
|
||||
pin = re.search(rf"^ {variable}: ([0-9a-f]{{40}})$", workflow, re.MULTILINE)
|
||||
if not pin or pin.group(1) != revision:
|
||||
fail(f"CI Python {name} must select its reviewed reference commit")
|
||||
if not python_checkouts[name]:
|
||||
fail(f"CI is missing its Python {name} reference checkout")
|
||||
for checkout in python_checkouts[name]:
|
||||
if f"ref: ${{{{ env.{variable} }}}}" not in checkout:
|
||||
fail(f"every CI Python {name} checkout must use its reviewed commit")
|
||||
|
||||
for target in (
|
||||
"aarch64-linux-android",
|
||||
"armv7-linux-androideabi",
|
||||
"x86_64-linux-android",
|
||||
"aarch64-apple-ios",
|
||||
):
|
||||
if target not in workflow:
|
||||
fail(f"CI does not qualify supported target {target}")
|
||||
if "i686-linux-android" in workflow:
|
||||
fail("Android i686 is unsupported and must not appear in the CI target matrix")
|
||||
|
||||
reticulum_root = ROOT.parent / "rsReticulum"
|
||||
if not reticulum_root.is_dir():
|
||||
fail(f"rsReticulum sibling checkout is missing at {reticulum_root}")
|
||||
actual_reticulum_commit = subprocess.run(
|
||||
["git", "rev-parse", "HEAD"],
|
||||
cwd=reticulum_root,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
if actual_reticulum_commit != EXPECTED_RETICULUM_COMMIT:
|
||||
fail(
|
||||
f"rsReticulum sibling is {actual_reticulum_commit}, "
|
||||
f"expected {EXPECTED_RETICULUM_COMMIT}"
|
||||
)
|
||||
|
||||
subprocess.run(
|
||||
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
|
||||
print("source-release contract: ok")
|
||||
Executable
+177
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate or verify the locked non-dev third-party dependency inventory."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
INVENTORY = ROOT / "THIRD_PARTY_LICENSES.json"
|
||||
UPSTREAM_OPUS_COMMIT = "5d8230f362b2618b9e730e6201c0d8f98961dfe1"
|
||||
UPSTREAM_OPUS_VERSION = "0.1.42"
|
||||
UPSTREAM_OPUS_LICENSE = "BSD-3-Clause"
|
||||
UPSTREAM_OPUS_REPOSITORY = "https://github.com/restsend/opus-rs"
|
||||
UPSTREAM_OPUS_SOURCE = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
UPSTREAM_OPUS_CRATE_CHECKSUM = (
|
||||
"bafbcaf2ed381cdf68ced4ed8d16517de90ffd7424e36f0b9e45d67fbe30b1f9"
|
||||
)
|
||||
UPSTREAM_OPUS_COPYING = "third_party/opus-rs-0.1.42-COPYING"
|
||||
UPSTREAM_OPUS_COPYING_SHA256 = (
|
||||
"67c6f0a4bac3019fb08948838d7203bf661a629416f69057081c6f39db5e96a5"
|
||||
)
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
print(f"third-party license inventory: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def load_metadata() -> dict:
|
||||
return json.loads(
|
||||
subprocess.run(
|
||||
["cargo", "metadata", "--format-version", "1", "--locked"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout
|
||||
)
|
||||
|
||||
|
||||
def build_inventory() -> dict:
|
||||
metadata = load_metadata()
|
||||
packages = {package["id"]: package for package in metadata["packages"]}
|
||||
nodes = {node["id"]: node for node in metadata["resolve"]["nodes"]}
|
||||
reachable = set(metadata["workspace_members"])
|
||||
pending = list(reachable)
|
||||
|
||||
while pending:
|
||||
package_id = pending.pop()
|
||||
for dependency in nodes[package_id]["deps"]:
|
||||
if not any(
|
||||
dep_kind["kind"] in (None, "build")
|
||||
for dep_kind in dependency["dep_kinds"]
|
||||
):
|
||||
continue
|
||||
if dependency["pkg"] not in reachable:
|
||||
reachable.add(dependency["pkg"])
|
||||
pending.append(dependency["pkg"])
|
||||
|
||||
entries = []
|
||||
upstream_opus_count = 0
|
||||
for package_id in reachable:
|
||||
package = packages[package_id]
|
||||
source = package["source"]
|
||||
if source is None:
|
||||
continue
|
||||
if not package["license"]:
|
||||
fail(f"{package['name']} {package['version']} has no declared license")
|
||||
|
||||
entry = {
|
||||
"name": package["name"],
|
||||
"version": package["version"],
|
||||
"license": package["license"],
|
||||
"repository": package["repository"],
|
||||
"source": source,
|
||||
}
|
||||
if package["name"] == "opus-rs":
|
||||
upstream_opus_count += 1
|
||||
expected_manifest = (
|
||||
UPSTREAM_OPUS_VERSION,
|
||||
UPSTREAM_OPUS_LICENSE,
|
||||
UPSTREAM_OPUS_REPOSITORY,
|
||||
UPSTREAM_OPUS_SOURCE,
|
||||
)
|
||||
actual_manifest = (
|
||||
package["version"],
|
||||
package["license"],
|
||||
package["repository"],
|
||||
package["source"],
|
||||
)
|
||||
if actual_manifest != expected_manifest:
|
||||
fail(
|
||||
"upstream opus-rs manifest provenance changed "
|
||||
f"(expected {expected_manifest!r}, found {actual_manifest!r})"
|
||||
)
|
||||
entry.update(
|
||||
{
|
||||
"crateChecksum": UPSTREAM_OPUS_CRATE_CHECKSUM,
|
||||
"upstreamCommit": UPSTREAM_OPUS_COMMIT,
|
||||
"licenseText": UPSTREAM_OPUS_COPYING,
|
||||
}
|
||||
)
|
||||
entries.append(entry)
|
||||
|
||||
if upstream_opus_count != 1:
|
||||
fail(f"expected one upstream opus-rs package, found {upstream_opus_count}")
|
||||
|
||||
lock = tomllib.loads((ROOT / "Cargo.lock").read_text(encoding="utf-8"))
|
||||
locked_opus = [
|
||||
package
|
||||
for package in lock["package"]
|
||||
if package["name"] == "opus-rs" and package["version"] == UPSTREAM_OPUS_VERSION
|
||||
]
|
||||
if len(locked_opus) != 1:
|
||||
fail(f"expected one locked opus-rs {UPSTREAM_OPUS_VERSION} package")
|
||||
if locked_opus[0].get("source") != UPSTREAM_OPUS_SOURCE:
|
||||
fail("locked opus-rs source is not crates.io")
|
||||
if locked_opus[0].get("checksum") != UPSTREAM_OPUS_CRATE_CHECKSUM:
|
||||
fail("locked opus-rs crate checksum changed")
|
||||
copying_hash = hashlib.sha256(
|
||||
(ROOT / UPSTREAM_OPUS_COPYING).read_bytes()
|
||||
).hexdigest()
|
||||
if copying_hash != UPSTREAM_OPUS_COPYING_SHA256:
|
||||
fail(f"preserved opus-rs COPYING changed (found {copying_hash})")
|
||||
|
||||
adapted = ROOT / "crates/lxst-codec2"
|
||||
provenance = json.loads((adapted / "UPSTREAM.json").read_text())
|
||||
if (provenance["version"], provenance["commit"], provenance["crate_sha256"]) != (
|
||||
"0.3.1", "24ec3b7c5b9892c268e180802ee3a5ce7737f214",
|
||||
"3c3c8ba70382a99c0b5ebadf6ad50e7d98fb6eb9bcc4c0e30d422f6321798d99",
|
||||
):
|
||||
fail("adapted Codec2 immutable upstream provenance changed")
|
||||
entries.append({
|
||||
"name": "codec2 (adapted as lxst-codec2)", "version": provenance["version"],
|
||||
"license": "LGPL-2.1-only AND MIT AND BSD-3-Clause",
|
||||
"repository": provenance["repository"], "source": "local-adaptation",
|
||||
"upstreamCommit": provenance["commit"], "crateChecksum": provenance["crate_sha256"],
|
||||
"provenance": "crates/lxst-codec2/UPSTREAM.json",
|
||||
"additionalSources": [provenance["codec2_700c"]],
|
||||
"notices": {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in [adapted / "NOTICE", *sorted((adapted / "licenses").iterdir())]},
|
||||
})
|
||||
entries.sort(key=lambda entry: (entry["name"], entry["version"], entry["source"]))
|
||||
lockfile_hash = hashlib.sha256((ROOT / "Cargo.lock").read_bytes()).hexdigest()
|
||||
return {
|
||||
"schemaVersion": 1,
|
||||
"scope": (
|
||||
"Adapted Codec2 and all registry third-party normal/build dependencies "
|
||||
"reachable from rsLXST workspace members across declared targets; "
|
||||
"dev-only and first-party path packages are excluded."
|
||||
),
|
||||
"cargoLockSha256": lockfile_hash,
|
||||
"packages": entries,
|
||||
}
|
||||
|
||||
|
||||
expected = json.dumps(build_inventory(), indent=2, sort_keys=False) + "\n"
|
||||
if len(sys.argv) == 2 and sys.argv[1] == "--write":
|
||||
INVENTORY.write_text(expected, encoding="utf-8")
|
||||
elif len(sys.argv) != 1:
|
||||
fail(
|
||||
"usage: check-third-party-licenses.py [--write]\n"
|
||||
"Without --write, compare the locked dependency inventory with THIRD_PARTY_LICENSES.json.\n"
|
||||
"With --write, replace that file after checking dependency provenance; review the diff before committing."
|
||||
)
|
||||
elif not INVENTORY.is_file():
|
||||
fail("THIRD_PARTY_LICENSES.json is missing; run with --write")
|
||||
elif INVENTORY.read_text(encoding="utf-8") != expected:
|
||||
fail("THIRD_PARTY_LICENSES.json is stale; review changes and run with --write")
|
||||
else:
|
||||
print(f"third-party license inventory: ok ({len(json.loads(expected)['packages'])} packages)")
|
||||
@@ -23,8 +23,12 @@ def main_root() -> Path:
|
||||
return repo_root().parent
|
||||
|
||||
|
||||
def _upstream_checkout(name: str) -> Path:
|
||||
return main_root() / "upstream" / name
|
||||
|
||||
|
||||
def upstream_lxst_root() -> Path:
|
||||
return Path(os.environ.get("LXST_UPSTREAM_DIR", main_root() / "upstream" / "LXST")).resolve()
|
||||
return Path(os.environ.get("LXST_UPSTREAM_DIR", _upstream_checkout("LXST"))).resolve()
|
||||
|
||||
|
||||
def upstream_reticulum_root() -> Path:
|
||||
@@ -32,7 +36,7 @@ def upstream_reticulum_root() -> Path:
|
||||
if configured:
|
||||
return Path(configured).resolve()
|
||||
|
||||
upstream = main_root() / "upstream" / "Reticulum"
|
||||
upstream = _upstream_checkout("Reticulum")
|
||||
if upstream.exists():
|
||||
return upstream.resolve()
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate LXST media-path vectors by calling upstream Python LXST.
|
||||
|
||||
usage: python tools/fixtures/lxst_media_fixtures.py crates/lxst-telephony/tests/fixtures/media_vectors.json
|
||||
|
||||
Upstream checkouts come from LXST_UPSTREAM_DIR / RETICULUM_UPSTREAM_DIR, or the
|
||||
workspace upstream directory (see tools/common/lxst_reference.py). Real Opus and
|
||||
Codec2 codecs are required: the generator refuses to run with the Codec2 stub.
|
||||
|
||||
Emits buffer_frames and frame_time_ms per profile, raw128 (Raw(bitdepth=128) bytes,
|
||||
platform-specific) and mixed_batch (one packet switching codec mid-batch, with the
|
||||
sample counts upstream's per-frame codec switching decodes, Network.py LinkSource).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))
|
||||
from lxst_reference import git_output, prepare_python_path, upstream_lxst_root, upstream_reticulum_root # noqa: E402
|
||||
|
||||
try:
|
||||
import pycodec2 # noqa: F401 loaded first so the locator never installs its Codec2 stub
|
||||
except ImportError:
|
||||
raise SystemExit("pycodec2 is not installed; Codec2 vectors need the real codec")
|
||||
|
||||
prepare_python_path()
|
||||
|
||||
import numpy as np # noqa: E402
|
||||
import RNS # noqa: E402
|
||||
from LXST._version import __version__ as LXST_VERSION # noqa: E402
|
||||
from LXST.Codecs import Codec2, Opus, Raw, codec_header_byte, codec_type # noqa: E402
|
||||
from LXST.Primitives.Telephony import Profiles # noqa: E402
|
||||
|
||||
assert LXST_VERSION == "0.6.0", LXST_VERSION
|
||||
assert RNS.__version__ == "1.6.0", RNS.__version__
|
||||
|
||||
|
||||
class Src: # encoders read only samplerate from their source
|
||||
def __init__(self, rate):
|
||||
self.samplerate = rate
|
||||
|
||||
|
||||
class Sink: # decoders read samplerate and channels from their sink
|
||||
def __init__(self, rate, channels):
|
||||
self.samplerate = rate
|
||||
self.channels = channels
|
||||
|
||||
|
||||
def tone(rate, ms):
|
||||
n = int(rate * ms / 1000)
|
||||
t = np.arange(n) / rate
|
||||
return (0.3 * np.sin(2 * np.pi * 440 * t)).reshape(n, 1).astype("float32")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
out_path = Path(sys.argv[1])
|
||||
lxst_root = upstream_lxst_root()
|
||||
out = {
|
||||
"generator": "tools/fixtures/lxst_media_fixtures.py",
|
||||
"lxst_version": LXST_VERSION,
|
||||
"lxst_commit": git_output(["rev-parse", "HEAD"], lxst_root),
|
||||
"rns_version": RNS.__version__,
|
||||
"rns_commit": git_output(["rev-parse", "HEAD"], upstream_reticulum_root()),
|
||||
}
|
||||
profiles = [Profiles.BANDWIDTH_ULTRA_LOW, Profiles.BANDWIDTH_VERY_LOW, Profiles.BANDWIDTH_LOW,
|
||||
Profiles.QUALITY_MEDIUM, Profiles.QUALITY_HIGH, Profiles.QUALITY_MAX,
|
||||
Profiles.LATENCY_ULTRA_LOW, Profiles.LATENCY_LOW]
|
||||
out["buffer_frames"] = {str(p): Profiles.get_buffer_frames(p) for p in profiles}
|
||||
out["frame_time_ms"] = {str(p): Profiles.get_frame_time(p) for p in profiles}
|
||||
|
||||
samples = np.array([[0.0], [0.5], [-0.25], [1.0]], dtype="float32")
|
||||
encoded = Raw(channels=1, bitdepth=128).encode(samples)
|
||||
decoded = Raw().decode(encoded)
|
||||
out["raw128"] = {"machine": platform.machine(),
|
||||
"longdouble_bits": int(np.finfo(np.longdouble).bits),
|
||||
"longdouble_nmant": int(np.finfo(np.longdouble).nmant),
|
||||
"samples": samples[:, 0].tolist(), "payload_hex": encoded.hex(),
|
||||
"decoded": [float(x) for x in decoded[:, 0]]}
|
||||
|
||||
frames = []
|
||||
opus = Opus(profile=Opus.PROFILE_VOICE_MEDIUM)
|
||||
opus.source = Src(24000)
|
||||
frames.append(("opus_60ms", codec_header_byte(Opus) + opus.encode(tone(24000, 60))))
|
||||
codec2 = Codec2(mode=Codec2.CODEC2_3200)
|
||||
codec2.source = Src(8000)
|
||||
frames.append(("codec2_3200_200ms", codec_header_byte(Codec2) + codec2.encode(np.repeat(tone(8000, 200), 2, axis=1))))
|
||||
frames.append(("opus_20ms", codec_header_byte(Opus) + opus.encode(tone(24000, 20))))
|
||||
|
||||
sink = Sink(48000, 1)
|
||||
codec = Opus()
|
||||
codec.sink = sink
|
||||
batch = []
|
||||
for name, wire in frames:
|
||||
frame_codec = codec_type(wire[0])
|
||||
if type(codec) != frame_codec:
|
||||
codec = frame_codec()
|
||||
codec.sink = sink
|
||||
samples_out = codec.decode(wire[1:])
|
||||
batch.append({"name": name, "codec": int(wire[0]), "wire_hex": wire.hex(),
|
||||
"decoded_sample_frames": int(samples_out.shape[0])})
|
||||
out["mixed_batch"] = batch
|
||||
|
||||
lines = []
|
||||
for key, value in out.items():
|
||||
if isinstance(value, list):
|
||||
items = ",\n".join(" " + json.dumps(item) for item in value)
|
||||
lines.append(f"{json.dumps(key)}: [\n{items}\n ]")
|
||||
else:
|
||||
lines.append(f"{json.dumps(key)}: {json.dumps(value)}")
|
||||
out_path.write_text("{\n " + ",\n ".join(lines) + "\n}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -62,8 +62,9 @@ def generate_fixtures():
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--decode-hex", default="")
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--decode-hex", default="",
|
||||
help="decode a hex-encoded Raw codec payload to JSON; omit or pass an empty string to generate fixture cases")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.decode_hex:
|
||||
|
||||
@@ -90,8 +90,9 @@ def generate_fixtures():
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--decode-hex", default="")
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--decode-hex", default="",
|
||||
help="decode a hex-encoded LXST wire packet to JSON; omit or pass an empty string to generate fixture cases")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.decode_hex:
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate Rust 700C codebooks from Codec2 inputs with pinned source hashes."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BACKEND = ROOT / "crates/lxst-codec2"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("source", type=Path, help="Codec2 source-tree root containing the codebook files listed in UPSTREAM.json")
|
||||
parser.add_argument("--check", action="store_true", help="compare with the generated Rust file without rewriting it")
|
||||
args = parser.parse_args()
|
||||
provenance = json.loads((BACKEND / "UPSTREAM.json").read_text())["codec2_700c"]
|
||||
lines = [
|
||||
"// Generated by tools/generate-codec2-700c-codebooks.py; do not edit.",
|
||||
"// Codec2 codebooks, Copyright David Rowe 2017. LGPL-2.1-only.",
|
||||
f"// Source: {provenance['repository']} at {provenance['commit']}.",
|
||||
"// Exact input hashes and original notices: UPSTREAM.json and NOTICE.",
|
||||
"",
|
||||
]
|
||||
for name, relative, width, count in [
|
||||
("VQ1", "src/codebook/train_120_1.txt", 20, 512),
|
||||
("VQ2", "src/codebook/train_120_2.txt", 20, 512),
|
||||
("ENERGY", "src/codebook/newamp1_energy_q.txt", 1, 16),
|
||||
]:
|
||||
raw = (args.source / relative).read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == provenance["source_sha256"][relative], relative
|
||||
dimensions, entries, *values = raw.decode().split()
|
||||
assert (int(dimensions), int(entries), len(values)) == (width, count, width * count)
|
||||
lines.append(f"pub(super) static {name}: [f32; {len(values)}] = [")
|
||||
for i in range(0, len(values), width):
|
||||
lines.append(" " + ", ".join(values[i:i + width]) + ",")
|
||||
lines.extend(["];", ""])
|
||||
output = "\n".join(lines)
|
||||
path = BACKEND / "src/native/codebook700c.rs"
|
||||
if args.check:
|
||||
assert path.read_text() == output, "700C codebooks differ from pinned generation"
|
||||
else:
|
||||
path.write_text(output)
|
||||
print("700C codebooks: pinned source hashes and 20×512 + 20×512 + 16 entries verified")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -86,6 +86,12 @@ def patch_headless_audio(Telephony, LXST, np, opus_available: bool) -> None:
|
||||
self.should_run = False
|
||||
self.samplerate = 48000
|
||||
self.channels = 1
|
||||
self.buffer_max_height = 3
|
||||
self.autostart_min = 1
|
||||
self.streaming = False
|
||||
|
||||
def wait_for_frames(self):
|
||||
return None
|
||||
|
||||
def start(self):
|
||||
self.should_run = True
|
||||
@@ -249,6 +255,8 @@ def patch_headless_audio(Telephony, LXST, np, opus_available: bool) -> None:
|
||||
Telephony.Pipeline = HeadlessPipeline
|
||||
Telephony.BandPass = NoopFilter
|
||||
Telephony.AGC = NoopFilter
|
||||
if hasattr(Telephony, "EchoSuppressor"):
|
||||
Telephony.EchoSuppressor = NoopFilter
|
||||
|
||||
if not opus_available:
|
||||
original_get_codec = Telephony.Profiles.get_codec
|
||||
@@ -269,14 +277,49 @@ def patch_headless_audio(Telephony, LXST, np, opus_available: bool) -> None:
|
||||
|
||||
def patch_signalling_events(Telephony) -> None:
|
||||
original = Telephony.Telephone.signalling_received
|
||||
# LXST_HELPER_DROP_RECEIVED lists signal values this phone never sees, to model loss.
|
||||
dropped = {int(value) for value in os.environ.get("LXST_HELPER_DROP_RECEIVED", "").split(",") if value.strip()}
|
||||
|
||||
def signalling_received(self, signals, source):
|
||||
emit({"event": "SIGNALS", "signals": [int(signal) for signal in signals]})
|
||||
signals = [signal for signal in signals if int(signal) not in dropped]
|
||||
return original(self, signals, source)
|
||||
|
||||
Telephony.Telephone.signalling_received = signalling_received
|
||||
|
||||
|
||||
def patch_dropped_signals() -> None:
|
||||
# LXST_HELPER_DROP_SENT lists signal values this phone never puts on the wire, to model loss.
|
||||
dropped = {int(value) for value in os.environ.get("LXST_HELPER_DROP_SENT", "").split(",") if value.strip()}
|
||||
if not dropped:
|
||||
return
|
||||
import LXST.Network as Network
|
||||
|
||||
original = Network.SignallingReceiver.signal
|
||||
|
||||
def signal(self, signal, destination, immediate=True):
|
||||
signals = signal if type(signal) == list else [signal]
|
||||
kept = [value for value in signals if value not in dropped]
|
||||
if kept:
|
||||
return original(self, kept, destination, immediate)
|
||||
|
||||
Network.SignallingReceiver.signal = signal
|
||||
|
||||
|
||||
def patch_open_pipelines_observer(Telephony) -> None:
|
||||
# LXST_HELPER_OPEN_DELAY delays the caller's pipeline setup to model a slow or distant phone.
|
||||
delay = float(os.environ.get("LXST_HELPER_OPEN_DELAY", "0") or 0)
|
||||
original = Telephony.Telephone._Telephone__open_pipelines
|
||||
|
||||
def open_pipelines(self, identity):
|
||||
emit({"event": "OPEN_PIPELINES"})
|
||||
if delay and self.active_call is not None and getattr(self.active_call, "is_outgoing", False):
|
||||
time.sleep(delay)
|
||||
return original(self, identity)
|
||||
|
||||
Telephony.Telephone._Telephone__open_pipelines = open_pipelines
|
||||
|
||||
|
||||
def setup_python_stack():
|
||||
global _RNS, _LXST, _Telephony, _np, _opus_available
|
||||
_RNS, _LXST, codec2_stubbed = import_rns_lxst()
|
||||
@@ -286,6 +329,8 @@ def setup_python_stack():
|
||||
_opus_available = python_opus_available(Telephony)
|
||||
patch_headless_audio(Telephony, _LXST, np, _opus_available)
|
||||
patch_signalling_events(Telephony)
|
||||
patch_open_pipelines_observer(Telephony)
|
||||
patch_dropped_signals()
|
||||
_Telephony = Telephony
|
||||
_np = np
|
||||
return codec2_stubbed
|
||||
@@ -299,8 +344,11 @@ def snapshot_event():
|
||||
active = {
|
||||
"identity_hash": bytes(remote.hash).hex() if remote else None,
|
||||
"profile": getattr(telephone.active_call, "profile", None),
|
||||
"call_mode": getattr(telephone.active_call, "call_mode", None),
|
||||
"squelched": bool(getattr(getattr(telephone.active_call, "packetizer", None), "squelched", False)),
|
||||
"status": telephone.call_status,
|
||||
"answered": bool(getattr(telephone.active_call, "answered", False)),
|
||||
"audio_started": bool(telephone.audio_input is not None and telephone.audio_input.should_run),
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -322,6 +370,7 @@ def emit_ready(identity, telephone, codec2_stubbed):
|
||||
"app_name": "lxst",
|
||||
"primitive_name": "telephony",
|
||||
"lxst_version": lxst_version,
|
||||
"rns_version": _RNS.__version__,
|
||||
"lxst_root": str(upstream_lxst_root()),
|
||||
"codec2_stubbed": bool(codec2_stubbed),
|
||||
"headless_audio": True,
|
||||
@@ -368,9 +417,13 @@ def setup_reticulum(storage: Path, tcp_role: str, tcp_host: str, tcp_port: int,
|
||||
config_dir = storage / "rns"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
(config_dir / "config").write_text(
|
||||
build_rns_config(tcp_role, tcp_host, tcp_port, enable_transport),
|
||||
build_rns_config(tcp_role, tcp_host, tcp_port, enable_transport)
|
||||
+ ("\n[stamps]\n" + os.environ["LXST_HELPER_STAMPS"].replace(";", "\n") + "\n" if os.environ.get("LXST_HELPER_STAMPS") else ""),
|
||||
encoding="utf-8",
|
||||
)
|
||||
# Destination stamping opt-in, as before Reticulum 1.6.1 ([stamps] still turns it on):
|
||||
# macOS stamps on one core, and a value-25 stamp takes about a minute there.
|
||||
_RNS.Transport.STAMP_DESTINATIONS = False
|
||||
|
||||
loglevel = os.environ.get("LXST_PYTHON_LOGLEVEL")
|
||||
if loglevel:
|
||||
@@ -391,7 +444,7 @@ def create_telephone(args):
|
||||
telephone = _Telephony.Telephone(
|
||||
identity,
|
||||
ring_time=args.ring_time,
|
||||
wait_time=args.wait_time,
|
||||
wait_time=float(os.environ.get("LXST_HELPER_WAIT_TIME", args.wait_time)),
|
||||
)
|
||||
configure_callbacks(telephone)
|
||||
_telephone = telephone
|
||||
@@ -491,7 +544,7 @@ def handle_command(command: dict, args) -> bool:
|
||||
}
|
||||
)
|
||||
return True
|
||||
_telephone.call(identity, profile=command.get("profile"))
|
||||
_telephone.call(identity, profile=command.get("profile"), mode=command.get("mode"))
|
||||
emit(
|
||||
{
|
||||
"event": "CALL_REQUESTED",
|
||||
@@ -547,6 +600,16 @@ def handle_command(command: dict, args) -> bool:
|
||||
emit({"event": "OPUS_FRAME_SENT", "id": command.get("id"), "sent": sent})
|
||||
return True
|
||||
|
||||
if cmd == "switch_mode":
|
||||
_telephone.switch_mode(int(command["mode"]))
|
||||
emit({"event": "MODE_SWITCHED", "id": command.get("id"), "mode": _telephone.active_mode})
|
||||
return True
|
||||
|
||||
if cmd == "unsquelch":
|
||||
_telephone.unsquelch_transmit()
|
||||
emit({"event": "UNSQUELCHED", "id": command.get("id")})
|
||||
return True
|
||||
|
||||
if cmd == "switch_profile":
|
||||
profile = int(command["profile"])
|
||||
_telephone.switch_profile(profile)
|
||||
@@ -577,15 +640,17 @@ def run_command_loop(args):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--mode", choices=["self-test", "host"], required=True)
|
||||
parser.add_argument("--storage-dir", required=True)
|
||||
parser.add_argument("--tcp-role", choices=["server", "client"], default="client")
|
||||
parser.add_argument("--tcp-host", default="127.0.0.1")
|
||||
parser.add_argument("--tcp-port", type=int, default=0)
|
||||
parser.add_argument("--ring-time", type=float, default=20.0)
|
||||
parser.add_argument("--wait-time", type=float, default=20.0)
|
||||
parser.add_argument("--enable-transport", action="store_true")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Headless LXST interop harness: starts Reticulum and exchanges JSON events/commands without physical audio."
|
||||
)
|
||||
parser.add_argument("--mode", choices=["self-test", "host"], required=True, help="self-test starts the stack, emits a snapshot and stops; host reads JSON commands from stdin")
|
||||
parser.add_argument("--storage-dir", required=True, help="scratch directory: existing contents are deleted and the directory is recreated on startup in both modes")
|
||||
parser.add_argument("--tcp-role", choices=["server", "client"], default="client", help="TCP interface role when --tcp-port is positive (default: client)")
|
||||
parser.add_argument("--tcp-host", default="127.0.0.1", help="client destination or server listen address (default: 127.0.0.1)")
|
||||
parser.add_argument("--tcp-port", type=int, default=0, help="TCP port; zero or negative omits the TCP interface (default: 0)")
|
||||
parser.add_argument("--ring-time", type=float, default=20.0, help="incoming-call ring timeout in seconds (default: 20)")
|
||||
parser.add_argument("--wait-time", type=float, default=20.0, help="outgoing-call/path-recall timeout in seconds (default: 20)")
|
||||
parser.add_argument("--enable-transport", action="store_true", help="enable transport mode in the generated Reticulum config (default: off)")
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
{
|
||||
"commit": "1194c9011fe6402edc7aebe7ffe9650ea3b1afee",
|
||||
"commit": "6a329bf6d956ca8b15077d4c470afe4cb7c669cc",
|
||||
"dirty": false,
|
||||
"files": {
|
||||
"LXST/Codecs/Codec2.py": {
|
||||
"bytes": 4107,
|
||||
"sha256": "e43a0be0b3b5b66665c47f468e8b102040632652a88e73598fc8cdbad8d4819a"
|
||||
"bytes": 4221,
|
||||
"sha256": "bb5727a4da4083ceddc0f692a12cf4aa17c8ad48c4394bcc71a61d4bdf5d572c"
|
||||
},
|
||||
"LXST/Codecs/Opus.py": {
|
||||
"bytes": 7806,
|
||||
"sha256": "0f0e6f9ffa48e899a80220b33485226fc411d70cd07dce3ff0b7582a208deb03"
|
||||
"bytes": 8688,
|
||||
"sha256": "bd3c7b0d777bddfbfc80acd51765b3d9bf623ba02bc0f1d1a6e128a2ab5bdd48"
|
||||
},
|
||||
"LXST/Codecs/Raw.py": {
|
||||
"bytes": 2316,
|
||||
"sha256": "8bda42cb8602797e7ef62dd71bac074d2ec547278ec2b0bc5bf8bcb7c100a026"
|
||||
"bytes": 2451,
|
||||
"sha256": "bce228630cf26a0c3a72b8d068eef3f9bbd099f077184b4ebf467259a42dbb0f"
|
||||
},
|
||||
"LXST/Codecs/__init__.py": {
|
||||
"bytes": 704,
|
||||
"sha256": "48c3f7adaf9c89326a81abf29f394f9857b11ea17315b3790214eaf7d45c03de"
|
||||
"bytes": 739,
|
||||
"sha256": "7977e713a3b8fa2167762db122024d1dcad8d09a1e8d98d25099271b22abfe1b"
|
||||
},
|
||||
"LXST/Network.py": {
|
||||
"bytes": 6172,
|
||||
"sha256": "3da8422a5c2c73f6e9c7d8e784b1e9cb307d079ebb5bf99183fc5daadfbd9701"
|
||||
"bytes": 6458,
|
||||
"sha256": "1f58806a43b2eadac536e1062857493fede551688ef92414b427aaffd6492923"
|
||||
},
|
||||
"LXST/Primitives/Telephony.py": {
|
||||
"bytes": 37026,
|
||||
"sha256": "35b2a4093368223145a548ac671504b43a4dcdac62368db754b082fe40138825"
|
||||
"bytes": 46484,
|
||||
"sha256": "da13879d66d2f4f83ea3b39c141a6566f29fc0ef7c96636a4c0b5dd619c0ab1c"
|
||||
},
|
||||
"LXST/_version.py": {
|
||||
"bytes": 22,
|
||||
"sha256": "12b90b908d930c15f5388aa2d8619adb408f7aee1972e9448be5df7d16cb53a3"
|
||||
"sha256": "7080f58cb9c2fef8f8f0680c37a61bd4503726c43de73366087991604f131616"
|
||||
}
|
||||
},
|
||||
"missing_files": [],
|
||||
"package_version": "0.4.5",
|
||||
"package_version": "0.6.0",
|
||||
"remote": "https://github.com/markqvist/LXST.git",
|
||||
"upstream": "../upstream/LXST"
|
||||
}
|
||||
Vendored
-11
@@ -1,11 +0,0 @@
|
||||
[package]
|
||||
edition = "2024"
|
||||
authors = ["jinti<shenjindi@fourz.cn>"]
|
||||
name = "opus-rs"
|
||||
version = "0.1.19"
|
||||
description = "pure Rust implementation of Opus codec"
|
||||
readme = "README.md"
|
||||
license = "BSD-3-Clause"
|
||||
repository = "https://github.com/restsend/opus-rs"
|
||||
|
||||
[dependencies]
|
||||
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user