Add native self-hosted instance connection to fluxer_desktop

Trimmed monorepo checkout (fluxer_desktop + packages/voice_engine_v2 +
tools/ci) with a "Connect to a Different Server" menu item and popout
that lets the desktop app switch to any self-hosted Fluxer instance,
plus fixes for well-known discovery on single-domain self-hosted
deployments and a false-positive ERR_ABORTED on same-origin client
redirects during the switch. Defaults to chat.fluxr.chat and uses an
isolated userData directory from the official build.
This commit is contained in:
2026-07-01 18:22:43 -04:00
commit 682afacd30
1763 changed files with 613720 additions and 0 deletions
+643
View File
@@ -0,0 +1,643 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "alloca"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4"
dependencies = [
"cc",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bumpalo"
version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.2.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clap"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "criterion"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3"
dependencies = [
"alloca",
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools",
"num-traits",
"oorandom",
"page_size",
"plotters",
"rayon",
"regex",
"serde",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "either"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "fluxer_audio_timing"
version = "0.0.0"
dependencies = [
"criterion",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2025f20d7a4fa7785846e7b63d10a76d3f1cee98ee5cb79ea59703f95e42162"
dependencies = [
"cfg-if",
"futures-util",
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "memchr"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "page_size"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "plotters"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
dependencies = [
"num-traits",
"plotters-backend",
"plotters-svg",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "plotters-backend"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
[[package]]
name = "plotters-svg"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
dependencies = [
"plotters-backend",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rayon"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a254a4b10c19a76f09a27640e7ffbf9bc30bf67e16a3bf28aaefa4920fe81563"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24a40fc75b0ec6f3746ceb10d36f53a93dcd68a93b11b6445983945d79eba0dc"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "908f34bd9b9ce3d4caf07b72dfab63d61504d156856c6bd3cd87fa350cf3985b"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7acbf7616c27b194bbb550bf77ed0c2c3e5b7fd1260a93082b95fb7f47959b92"
dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e0871acf327f283dc6da28a1696cdc64fb355ba9f935d052021fa77f35cce69"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zerocopy"
version = "0.8.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
@@ -0,0 +1,21 @@
[package]
name = "fluxer_audio_timing"
version = "0.0.0"
edition = "2024"
license = "AGPL-3.0-or-later"
publish = false
[workspace]
resolver = "2"
[lib]
crate-type = ["rlib"]
[dependencies]
[dev-dependencies]
criterion = "0.8"
[[bench]]
name = "smoother"
harness = false
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
use std::hint::black_box;
use criterion::{Criterion, criterion_group, criterion_main};
use fluxer_audio_timing::{AudioTimingSmoother, SmootherInput, SourceGainRamp, StaleSourceTracker};
const SR: u32 = 48_000;
const FRAMES_PER_TICK: u32 = 960;
const PERIOD_NS: u64 = 20_000_000;
fn bench_smoother_steady_snap(c: &mut Criterion) {
let mut group = c.benchmark_group("audio_timing_smoother");
group.sample_size(100);
group.bench_function("snap_steady_state", |b| {
let mut s = AudioTimingSmoother::new(1, SR).expect("ok");
let _ = s
.adjust(SmootherInput {
media_ts_ns: 0,
frames: FRAMES_PER_TICK,
wall_ns: 0,
})
.expect("ok");
let mut n: u64 = 1;
b.iter(|| {
let result = s
.adjust(SmootherInput {
media_ts_ns: n * PERIOD_NS,
frames: FRAMES_PER_TICK,
wall_ns: n * PERIOD_NS,
})
.expect("ok");
n = n.wrapping_add(1);
black_box(result);
});
});
group.finish();
}
fn bench_ramp_advance(c: &mut Criterion) {
let mut group = c.benchmark_group("audio_timing_ramp");
group.sample_size(100);
group.bench_function("advance_and_query_gain", |b| {
let mut r = SourceGainRamp::new();
b.iter(|| {
r.advance_tick();
let g = r.current_gain_q15();
if r.is_complete() {
r.reset();
}
black_box(g);
});
});
group.finish();
}
fn bench_stale_check(c: &mut Criterion) {
let mut group = c.benchmark_group("audio_timing_eviction");
group.sample_size(100);
group.bench_function("is_stale_lookup", |b| {
let mut t = StaleSourceTracker::new(16).expect("ok");
for n in 1..=16u64 {
t.register_source(n, n * 1_000).expect("ok");
}
let threshold = 5_000_000_000u64;
let mut now: u64 = 1_000_000_000;
b.iter(|| {
let stale = t.is_stale(8, now, threshold).expect("ok");
now = now.wrapping_add(PERIOD_NS);
black_box(stale);
});
});
group.finish();
}
criterion_group!(
benches,
bench_smoother_steady_snap,
bench_ramp_advance,
bench_stale_check
);
criterion_main!(benches);
@@ -0,0 +1,488 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
pub const EVICTION_NEVER_PUSHED_SENTINEL: u64 = u64::MAX;
pub const MAX_TRACKED_SOURCES: usize = 256;
const STALE_THRESHOLD_NS_MIN: u64 = 1_000_000;
const STALE_THRESHOLD_NS_MAX: u64 = 60_000_000_000;
#[derive(Debug, PartialEq, Eq)]
pub enum StaleSourceTrackerError {
CapacityExceeded { capacity: usize },
SourceIdZero,
UnknownSource { source_id: u64 },
StaleThresholdOutOfRange { stale_threshold_ns: u64 },
}
impl core::fmt::Display for StaleSourceTrackerError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
StaleSourceTrackerError::CapacityExceeded { capacity } => {
write!(f, "tracker capacity {capacity} exceeded")
}
StaleSourceTrackerError::SourceIdZero => write!(f, "source_id must be non-zero"),
StaleSourceTrackerError::UnknownSource { source_id } => {
write!(f, "source_id {source_id} not registered")
}
StaleSourceTrackerError::StaleThresholdOutOfRange { stale_threshold_ns } => {
write!(
f,
"stale threshold {stale_threshold_ns} ns outside accepted range"
)
}
}
}
}
impl std::error::Error for StaleSourceTrackerError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StaleSourceEntry {
pub source_id: u64,
pub registered_at_ns: u64,
pub last_active_ns: u64,
}
impl StaleSourceEntry {
pub fn ever_pushed(&self) -> bool {
self.last_active_ns != EVICTION_NEVER_PUSHED_SENTINEL
}
}
pub struct StaleSourceTracker {
entries: Vec<StaleSourceEntry>,
capacity: usize,
}
impl StaleSourceTracker {
pub fn new(capacity: usize) -> Result<Self, StaleSourceTrackerError> {
if capacity == 0 || capacity > MAX_TRACKED_SOURCES {
return Err(StaleSourceTrackerError::CapacityExceeded { capacity });
}
assert!(capacity > 0);
assert!(capacity <= MAX_TRACKED_SOURCES);
Ok(Self {
entries: Vec::with_capacity(capacity),
capacity,
})
}
pub fn len(&self) -> usize {
assert!(self.entries.len() <= self.capacity);
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn capacity(&self) -> usize {
assert!(self.capacity > 0);
assert!(self.capacity <= MAX_TRACKED_SOURCES);
self.capacity
}
pub fn register_source(
&mut self,
source_id: u64,
registered_at_ns: u64,
) -> Result<(), StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
if self.entries.len() >= self.capacity {
return Err(StaleSourceTrackerError::CapacityExceeded {
capacity: self.capacity,
});
}
assert!(source_id != 0);
if let Some(existing) = self.find_mut(source_id) {
existing.registered_at_ns = registered_at_ns;
existing.last_active_ns = EVICTION_NEVER_PUSHED_SENTINEL;
return Ok(());
}
self.entries.push(StaleSourceEntry {
source_id,
registered_at_ns,
last_active_ns: EVICTION_NEVER_PUSHED_SENTINEL,
});
assert!(self.entries.len() <= self.capacity);
Ok(())
}
pub fn unregister_source(&mut self, source_id: u64) -> Result<(), StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
assert!(source_id != 0);
let before = self.entries.len();
self.entries.retain(|e| e.source_id != source_id);
if self.entries.len() == before {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
}
assert!(self.entries.len() < before);
Ok(())
}
pub fn mark_pushed(
&mut self,
source_id: u64,
ts_ns: u64,
) -> Result<(), StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
assert!(source_id != 0);
let Some(entry) = self.find_mut(source_id) else {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
};
entry.last_active_ns = ts_ns;
assert!(entry.last_active_ns == ts_ns);
Ok(())
}
pub fn mark_pushed_at(
&mut self,
index: usize,
source_id: u64,
ts_ns: u64,
) -> Result<(), StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
assert!(source_id != 0);
assert!(self.entries.len() <= self.capacity);
if index >= self.entries.len() {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
}
if self.entries[index].source_id != source_id {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
}
self.entries[index].last_active_ns = ts_ns;
assert!(self.entries[index].last_active_ns == ts_ns);
Ok(())
}
pub fn is_stale(
&self,
source_id: u64,
now_ns: u64,
stale_threshold_ns: u64,
) -> Result<bool, StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
if !(STALE_THRESHOLD_NS_MIN..=STALE_THRESHOLD_NS_MAX).contains(&stale_threshold_ns) {
return Err(StaleSourceTrackerError::StaleThresholdOutOfRange { stale_threshold_ns });
}
assert!(source_id != 0);
let Some(entry) = self.find(source_id) else {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
};
Ok(Self::entry_is_stale(entry, now_ns, stale_threshold_ns))
}
pub fn is_stale_at(
&self,
index: usize,
source_id: u64,
now_ns: u64,
stale_threshold_ns: u64,
) -> Result<bool, StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
if !(STALE_THRESHOLD_NS_MIN..=STALE_THRESHOLD_NS_MAX).contains(&stale_threshold_ns) {
return Err(StaleSourceTrackerError::StaleThresholdOutOfRange { stale_threshold_ns });
}
assert!(source_id != 0);
assert!(self.entries.len() <= self.capacity);
if index >= self.entries.len() {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
}
let entry = &self.entries[index];
if entry.source_id != source_id {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
}
Ok(Self::entry_is_stale(entry, now_ns, stale_threshold_ns))
}
fn entry_is_stale(entry: &StaleSourceEntry, now_ns: u64, stale_threshold_ns: u64) -> bool {
assert!(entry.source_id != 0);
assert!(stale_threshold_ns >= STALE_THRESHOLD_NS_MIN);
assert!(stale_threshold_ns <= STALE_THRESHOLD_NS_MAX);
let baseline_ns = if entry.last_active_ns == EVICTION_NEVER_PUSHED_SENTINEL {
entry.registered_at_ns
} else {
entry.last_active_ns
};
if now_ns <= baseline_ns {
return false;
}
let age_ns = now_ns - baseline_ns;
age_ns > stale_threshold_ns
}
pub fn age_ns(&self, source_id: u64, now_ns: u64) -> Result<u64, StaleSourceTrackerError> {
if source_id == 0 {
return Err(StaleSourceTrackerError::SourceIdZero);
}
assert!(source_id != 0);
let Some(entry) = self.find(source_id) else {
return Err(StaleSourceTrackerError::UnknownSource { source_id });
};
let baseline_ns = if entry.last_active_ns == EVICTION_NEVER_PUSHED_SENTINEL {
entry.registered_at_ns
} else {
entry.last_active_ns
};
if now_ns <= baseline_ns {
return Ok(0);
}
Ok(now_ns - baseline_ns)
}
pub fn entry(&self, source_id: u64) -> Option<StaleSourceEntry> {
self.find(source_id).copied()
}
fn find(&self, source_id: u64) -> Option<&StaleSourceEntry> {
self.entries.iter().find(|e| e.source_id == source_id)
}
fn find_mut(&mut self, source_id: u64) -> Option<&mut StaleSourceEntry> {
self.entries.iter_mut().find(|e| e.source_id == source_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unregistered_source_is_error() {
let tracker = StaleSourceTracker::new(4).expect("ok");
let err = tracker.is_stale(7, 1_000_000_000, 5_000_000_000).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::UnknownSource { source_id: 7 })
));
}
#[test]
fn registered_source_starts_not_stale_at_registration_time() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 1_000_000).expect("ok");
let stale = t.is_stale(1, 1_000_000, 5_000_000_000).expect("ok");
assert!(!stale);
}
#[test]
fn registered_but_never_pushed_becomes_stale_past_threshold() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 1_000_000).expect("ok");
let threshold = 5_000_000_000;
let now = 1_000_000 + threshold + 1;
let stale = t.is_stale(1, now, threshold).expect("ok");
assert!(stale, "never-pushed source must go stale past threshold");
}
#[test]
fn registered_but_never_pushed_within_window_is_fresh() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 1_000_000).expect("ok");
let threshold = 5_000_000_000;
let now = 1_000_000 + threshold - 1;
let stale = t.is_stale(1, now, threshold).expect("ok");
assert!(!stale);
}
#[test]
fn marking_pushed_extends_freshness() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(2, 0).expect("ok");
t.mark_pushed(2, 1_000_000_000).expect("ok");
let threshold = 500_000_000;
let now = 1_000_000_000 + threshold + 1;
let stale = t.is_stale(2, now, threshold).expect("ok");
assert!(stale);
let now_within = 1_000_000_000 + threshold - 1;
let fresh = t.is_stale(2, now_within, threshold).expect("ok");
assert!(!fresh);
}
#[test]
fn unregister_removes_entry() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(3, 0).expect("ok");
assert_eq!(t.len(), 1);
t.unregister_source(3).expect("ok");
assert_eq!(t.len(), 0);
}
#[test]
fn capacity_exceeded_rejected() {
let mut t = StaleSourceTracker::new(2).expect("ok");
t.register_source(1, 0).expect("ok");
t.register_source(2, 0).expect("ok");
let err = t.register_source(3, 0).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::CapacityExceeded { .. })
));
}
#[test]
fn age_ns_uses_registration_for_never_pushed() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 1_000).expect("ok");
let age = t.age_ns(1, 5_000).expect("ok");
assert_eq!(age, 4_000);
}
#[test]
fn age_ns_uses_last_active_after_push() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 1_000).expect("ok");
t.mark_pushed(1, 2_000).expect("ok");
let age = t.age_ns(1, 5_000).expect("ok");
assert_eq!(age, 3_000);
}
#[test]
fn determinism_two_runs_produce_same_decisions() {
let run = || {
let mut t = StaleSourceTracker::new(8).expect("ok");
t.register_source(1, 0).expect("ok");
t.register_source(2, 0).expect("ok");
t.mark_pushed(2, 1_000_000_000).expect("ok");
let threshold = 2_000_000_000;
let out: Vec<bool> = vec![
t.is_stale(1, 3_000_000_000, threshold).expect("ok"),
t.is_stale(2, 3_000_000_000, threshold).expect("ok"),
];
out
};
let a = run();
let b = run();
assert_eq!(a, b);
}
#[test]
fn rejects_invalid_threshold() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 0).expect("ok");
let err = t.is_stale(1, 1_000_000, 0).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::StaleThresholdOutOfRange { .. })
));
}
#[test]
fn rejects_zero_source_id() {
let mut t = StaleSourceTracker::new(4).expect("ok");
let err = t.register_source(0, 0).err();
assert!(matches!(err, Some(StaleSourceTrackerError::SourceIdZero)));
}
#[test]
fn mark_pushed_at_succeeds_when_index_and_id_agree() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
t.register_source(20, 0).expect("ok");
t.mark_pushed_at(1, 20, 2_000).expect("ok");
let e = t.entry(20).expect("entry");
assert_eq!(e.last_active_ns, 2_000);
let untouched = t.entry(10).expect("entry");
assert!(!untouched.ever_pushed());
}
#[test]
fn mark_pushed_at_rejects_index_id_mismatch() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
t.register_source(20, 0).expect("ok");
let err = t.mark_pushed_at(0, 20, 2_000).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::UnknownSource { source_id: 20 })
));
assert!(!t.entry(10).expect("entry").ever_pushed());
assert!(!t.entry(20).expect("entry").ever_pushed());
}
#[test]
fn mark_pushed_at_rejects_out_of_range_index() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
let err = t.mark_pushed_at(1, 10, 2_000).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::UnknownSource { source_id: 10 })
));
}
#[test]
fn mark_pushed_at_rejects_zero_source_id() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
let err = t.mark_pushed_at(0, 0, 2_000).err();
assert!(matches!(err, Some(StaleSourceTrackerError::SourceIdZero)));
}
#[test]
fn is_stale_at_matches_is_stale() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
t.register_source(20, 0).expect("ok");
t.mark_pushed_at(1, 20, 1_000_000_000).expect("ok");
let threshold = 2_000_000_000;
for now in [500_000_000, 2_500_000_000, 4_000_000_000] {
let by_id = t.is_stale(20, now, threshold).expect("ok");
let by_index = t.is_stale_at(1, 20, now, threshold).expect("ok");
assert_eq!(by_id, by_index);
}
}
#[test]
fn is_stale_at_rejects_index_id_mismatch() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
t.register_source(20, 0).expect("ok");
let err = t.is_stale_at(0, 20, 3_000_000_000, 2_000_000_000).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::UnknownSource { source_id: 20 })
));
let err = t.is_stale_at(5, 10, 3_000_000_000, 2_000_000_000).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::UnknownSource { source_id: 10 })
));
}
#[test]
fn is_stale_at_rejects_invalid_threshold() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(10, 0).expect("ok");
let err = t.is_stale_at(0, 10, 1_000_000, 0).err();
assert!(matches!(
err,
Some(StaleSourceTrackerError::StaleThresholdOutOfRange { .. })
));
}
#[test]
fn ever_pushed_flag_reflects_state() {
let mut t = StaleSourceTracker::new(4).expect("ok");
t.register_source(1, 10).expect("ok");
let e = t.entry(1).expect("entry");
assert!(!e.ever_pushed());
t.mark_pushed(1, 100).expect("ok");
let e2 = t.entry(1).expect("entry");
assert!(e2.ever_pushed());
}
}
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
#![deny(clippy::too_many_lines)]
pub mod eviction;
pub mod ramping;
pub mod smoother;
pub use eviction::{
EVICTION_NEVER_PUSHED_SENTINEL, MAX_TRACKED_SOURCES, StaleSourceEntry, StaleSourceTracker,
StaleSourceTrackerError,
};
pub use ramping::{RAMP_GAIN_DENOMINATOR_Q15, RAMP_IN_TICKS_DEFAULT, RampError, SourceGainRamp};
pub use smoother::{
AudioTimingError, AudioTimingSmoother, MAX_TS_VAR_NS, NS_PER_SECOND, SmootherAction,
SmootherEvent, SmootherInput, SmootherResetReason, SmootherResult, TS_SMOOTHING_THRESHOLD_NS,
};
@@ -0,0 +1,216 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
pub const RAMP_IN_TICKS_DEFAULT: u32 = 5;
pub const RAMP_GAIN_DENOMINATOR_Q15: i32 = 32_768;
const RAMP_IN_TICKS_MIN: u32 = 1;
const RAMP_IN_TICKS_MAX: u32 = 1_024;
#[derive(Debug, PartialEq, Eq)]
pub enum RampError {
RampInTicksOutOfRange { ramp_in_ticks: u32 },
}
impl core::fmt::Display for RampError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
RampError::RampInTicksOutOfRange { ramp_in_ticks } => {
write!(f, "ramp_in_ticks {ramp_in_ticks} outside accepted range")
}
}
}
}
impl std::error::Error for RampError {}
pub struct SourceGainRamp {
tick_count: u32,
ramp_in_ticks: u32,
}
impl SourceGainRamp {
pub fn new() -> Self {
Self {
tick_count: 0,
ramp_in_ticks: RAMP_IN_TICKS_DEFAULT,
}
}
pub fn with_ramp_in_ticks(ramp_in_ticks: u32) -> Result<Self, RampError> {
if !(RAMP_IN_TICKS_MIN..=RAMP_IN_TICKS_MAX).contains(&ramp_in_ticks) {
return Err(RampError::RampInTicksOutOfRange { ramp_in_ticks });
}
assert!(ramp_in_ticks >= RAMP_IN_TICKS_MIN);
assert!(ramp_in_ticks <= RAMP_IN_TICKS_MAX);
Ok(Self {
tick_count: 0,
ramp_in_ticks,
})
}
pub fn tick_count(&self) -> u32 {
self.tick_count
}
pub fn ramp_in_ticks(&self) -> u32 {
assert!(self.ramp_in_ticks >= RAMP_IN_TICKS_MIN);
assert!(self.ramp_in_ticks <= RAMP_IN_TICKS_MAX);
self.ramp_in_ticks
}
pub fn is_complete(&self) -> bool {
self.tick_count >= self.ramp_in_ticks
}
pub fn current_gain(&self) -> f32 {
assert!(self.ramp_in_ticks >= RAMP_IN_TICKS_MIN);
let clamped = self.tick_count.min(self.ramp_in_ticks);
let g = (clamped as f32) / (self.ramp_in_ticks as f32);
assert!(g >= 0.0);
assert!(g <= 1.0);
g
}
pub fn current_gain_q15(&self) -> i32 {
assert!(self.ramp_in_ticks >= RAMP_IN_TICKS_MIN);
let clamped = self.tick_count.min(self.ramp_in_ticks);
let num = (clamped as i64) * (RAMP_GAIN_DENOMINATOR_Q15 as i64);
let den = self.ramp_in_ticks as i64;
let q = num / den;
assert!(q >= 0);
assert!(q <= RAMP_GAIN_DENOMINATOR_Q15 as i64);
q as i32
}
pub fn advance_tick(&mut self) {
let before = self.tick_count;
self.tick_count = self.tick_count.saturating_add(1);
assert!(self.tick_count >= before);
assert!(self.tick_count >= 1);
}
pub fn reset(&mut self) {
self.tick_count = 0;
assert_eq!(self.tick_count, 0);
assert!(self.ramp_in_ticks >= RAMP_IN_TICKS_MIN);
}
}
impl Default for SourceGainRamp {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fresh_ramp_starts_at_zero_gain() {
let r = SourceGainRamp::new();
assert_eq!(r.tick_count(), 0);
assert_eq!(r.current_gain(), 0.0);
assert!(!r.is_complete());
}
#[test]
fn five_ticks_increase_monotonically_to_one() {
let mut r = SourceGainRamp::new();
let mut prior = -1.0f32;
for expected_n in 1..=5u32 {
r.advance_tick();
let g = r.current_gain();
assert!(g > prior);
assert!(g >= 0.0);
assert!(g <= 1.0);
assert_eq!(r.tick_count(), expected_n);
prior = g;
}
assert_eq!(r.current_gain(), 1.0);
assert!(r.is_complete());
}
#[test]
fn gain_clamps_to_one_after_completion() {
let mut r = SourceGainRamp::new();
for _ in 0..20 {
r.advance_tick();
}
assert_eq!(r.current_gain(), 1.0);
assert!(r.is_complete());
}
#[test]
fn first_five_gains_are_quintiles() {
let mut r = SourceGainRamp::new();
let mut observed: Vec<f32> = Vec::with_capacity(5);
for _ in 0..5 {
r.advance_tick();
observed.push(r.current_gain());
}
assert_eq!(observed.len(), 5);
assert!((observed[0] - 0.2).abs() < f32::EPSILON);
assert!((observed[1] - 0.4).abs() < f32::EPSILON * 4.0);
assert!((observed[2] - 0.6).abs() < f32::EPSILON * 4.0);
assert!((observed[3] - 0.8).abs() < f32::EPSILON * 4.0);
assert_eq!(observed[4], 1.0);
}
#[test]
fn q15_gain_at_completion_equals_denominator() {
let mut r = SourceGainRamp::new();
for _ in 0..5 {
r.advance_tick();
}
assert_eq!(r.current_gain_q15(), RAMP_GAIN_DENOMINATOR_Q15);
}
#[test]
fn q15_gain_starts_at_zero() {
let r = SourceGainRamp::new();
assert_eq!(r.current_gain_q15(), 0);
}
#[test]
fn reset_returns_ramp_to_zero_gain() {
let mut r = SourceGainRamp::new();
for _ in 0..10 {
r.advance_tick();
}
assert_eq!(r.current_gain(), 1.0);
r.reset();
assert_eq!(r.tick_count(), 0);
assert_eq!(r.current_gain(), 0.0);
}
#[test]
fn custom_ramp_in_ticks_validates() {
let r = SourceGainRamp::with_ramp_in_ticks(10).expect("ok");
assert_eq!(r.ramp_in_ticks(), 10);
let err = SourceGainRamp::with_ramp_in_ticks(0).err();
assert!(matches!(err, Some(RampError::RampInTicksOutOfRange { .. })));
let err2 = SourceGainRamp::with_ramp_in_ticks(10_000).err();
assert!(matches!(
err2,
Some(RampError::RampInTicksOutOfRange { .. })
));
}
#[test]
fn determinism_two_ramps_produce_same_sequence() {
let run = || {
let mut r = SourceGainRamp::new();
let mut g: Vec<i32> = Vec::with_capacity(7);
for _ in 0..7 {
g.push(r.current_gain_q15());
r.advance_tick();
}
g
};
let a = run();
let b = run();
assert_eq!(a, b);
}
}
@@ -0,0 +1,579 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
pub const TS_SMOOTHING_THRESHOLD_NS: u64 = 70_000_000;
pub const MAX_TS_VAR_NS: u64 = 2_000_000_000;
pub const NS_PER_SECOND: u64 = 1_000_000_000;
const SAMPLE_RATE_HZ_MIN: u32 = 8_000;
const SAMPLE_RATE_HZ_MAX: u32 = 384_000;
const FRAMES_PER_INPUT_MAX: u32 = 1 << 24;
#[derive(Debug, PartialEq, Eq)]
pub enum AudioTimingError {
SampleRateOutOfRange { sample_rate_hz: u32 },
SourceIdZero,
FramesOutOfRange { frames: u32 },
}
impl core::fmt::Display for AudioTimingError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
AudioTimingError::SampleRateOutOfRange { sample_rate_hz } => {
write!(f, "sample rate {sample_rate_hz} hz outside accepted range")
}
AudioTimingError::SourceIdZero => write!(f, "source_id must be non-zero"),
AudioTimingError::FramesOutOfRange { frames } => {
write!(f, "frames {frames} outside accepted range")
}
}
}
}
impl std::error::Error for AudioTimingError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SmootherInput {
pub media_ts_ns: u64,
pub frames: u32,
pub wall_ns: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SmootherAction {
Snap,
Jump,
Reset,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SmootherResetReason {
FirstSample,
GapBeyondMaxVar,
Regression,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SmootherEvent {
Snapped {
source_id: u64,
incoming_media_ts_ns: u64,
snapped_ts_ns: u64,
delta_ns: i64,
frames_accumulated: u64,
},
Jumped {
source_id: u64,
incoming_media_ts_ns: u64,
previous_predicted_ts_ns: u64,
delta_ns: i64,
frames_accumulated: u64,
},
Reset {
source_id: u64,
incoming_media_ts_ns: u64,
wall_ns: u64,
timing_adjust_ns: i64,
frames_accumulated: u64,
reason: SmootherResetReason,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SmootherResult {
pub action: SmootherAction,
pub output_ts_ns: u64,
pub predicted_next_ts_ns: u64,
pub frames_accumulated: u64,
pub event: SmootherEvent,
}
pub struct AudioTimingSmoother {
source_id: u64,
sample_rate_hz: u32,
initialised: bool,
predicted_next_ts_ns: u64,
timing_adjust_ns: i64,
frames_accumulated: u64,
consecutive_jumps: u32,
}
impl AudioTimingSmoother {
pub fn new(source_id: u64, sample_rate_hz: u32) -> Result<Self, AudioTimingError> {
if source_id == 0 {
return Err(AudioTimingError::SourceIdZero);
}
if !(SAMPLE_RATE_HZ_MIN..=SAMPLE_RATE_HZ_MAX).contains(&sample_rate_hz) {
return Err(AudioTimingError::SampleRateOutOfRange { sample_rate_hz });
}
assert!(source_id != 0);
assert!(sample_rate_hz >= SAMPLE_RATE_HZ_MIN);
assert!(sample_rate_hz <= SAMPLE_RATE_HZ_MAX);
Ok(Self {
source_id,
sample_rate_hz,
initialised: false,
predicted_next_ts_ns: 0,
timing_adjust_ns: 0,
frames_accumulated: 0,
consecutive_jumps: 0,
})
}
pub fn source_id(&self) -> u64 {
assert!(self.source_id != 0);
self.source_id
}
pub fn sample_rate_hz(&self) -> u32 {
assert!(self.sample_rate_hz >= SAMPLE_RATE_HZ_MIN);
assert!(self.sample_rate_hz <= SAMPLE_RATE_HZ_MAX);
self.sample_rate_hz
}
pub fn initialised(&self) -> bool {
self.initialised
}
pub fn predicted_next_ts_ns(&self) -> u64 {
self.predicted_next_ts_ns
}
pub fn timing_adjust_ns(&self) -> i64 {
self.timing_adjust_ns
}
pub fn frames_accumulated(&self) -> u64 {
self.frames_accumulated
}
pub fn consecutive_jumps(&self) -> u32 {
self.consecutive_jumps
}
pub fn adjust(&mut self, input: SmootherInput) -> Result<SmootherResult, AudioTimingError> {
if input.frames == 0 || input.frames > FRAMES_PER_INPUT_MAX {
return Err(AudioTimingError::FramesOutOfRange {
frames: input.frames,
});
}
assert!(input.frames >= 1);
assert!(input.frames <= FRAMES_PER_INPUT_MAX);
if !self.initialised {
return Ok(self.initialise_from_first_sample(input));
}
Ok(self.adjust_initialised(input))
}
fn initialise_from_first_sample(&mut self, input: SmootherInput) -> SmootherResult {
assert!(!self.initialised);
assert_eq!(self.frames_accumulated, 0);
let increment_ns = frames_to_ns(input.frames as u64, self.sample_rate_hz);
let predicted_next = input.media_ts_ns.saturating_add(increment_ns);
let timing_adjust = wall_minus_media_signed(input.wall_ns, input.media_ts_ns);
self.frames_accumulated = input.frames as u64;
self.predicted_next_ts_ns = predicted_next;
self.timing_adjust_ns = timing_adjust;
self.initialised = true;
self.consecutive_jumps = 0;
assert!(predicted_next >= input.media_ts_ns);
let event = SmootherEvent::Reset {
source_id: self.source_id,
incoming_media_ts_ns: input.media_ts_ns,
wall_ns: input.wall_ns,
timing_adjust_ns: timing_adjust,
frames_accumulated: self.frames_accumulated,
reason: SmootherResetReason::FirstSample,
};
SmootherResult {
action: SmootherAction::Reset,
output_ts_ns: input.media_ts_ns,
predicted_next_ts_ns: predicted_next,
frames_accumulated: self.frames_accumulated,
event,
}
}
fn adjust_initialised(&mut self, input: SmootherInput) -> SmootherResult {
assert!(self.initialised);
let expected = self.predicted_next_ts_ns;
let delta = signed_delta(input.media_ts_ns, expected);
let absolute_delta = delta.unsigned_abs();
if absolute_delta <= TS_SMOOTHING_THRESHOLD_NS {
return self.apply_snap(input, expected, delta);
}
if absolute_delta <= MAX_TS_VAR_NS {
return self.apply_jump(input, expected, delta);
}
self.apply_full_reset(input, SmootherResetReason::GapBeyondMaxVar)
}
fn apply_snap(&mut self, input: SmootherInput, expected: u64, delta: i64) -> SmootherResult {
assert!(self.initialised);
let increment_ns = frames_to_ns(input.frames as u64, self.sample_rate_hz);
let new_predicted = expected.saturating_add(increment_ns);
self.frames_accumulated = self.frames_accumulated.saturating_add(input.frames as u64);
self.predicted_next_ts_ns = new_predicted;
self.consecutive_jumps = 0;
assert!(new_predicted >= expected);
let event = SmootherEvent::Snapped {
source_id: self.source_id,
incoming_media_ts_ns: input.media_ts_ns,
snapped_ts_ns: expected,
delta_ns: delta,
frames_accumulated: self.frames_accumulated,
};
SmootherResult {
action: SmootherAction::Snap,
output_ts_ns: expected,
predicted_next_ts_ns: new_predicted,
frames_accumulated: self.frames_accumulated,
event,
}
}
fn apply_jump(&mut self, input: SmootherInput, expected: u64, delta: i64) -> SmootherResult {
assert!(self.initialised);
if delta < 0 {
return self.apply_full_reset(input, SmootherResetReason::Regression);
}
let increment_ns = frames_to_ns(input.frames as u64, self.sample_rate_hz);
let new_predicted = input.media_ts_ns.saturating_add(increment_ns);
self.frames_accumulated = self.frames_accumulated.saturating_add(input.frames as u64);
self.predicted_next_ts_ns = new_predicted;
self.consecutive_jumps = self.consecutive_jumps.saturating_add(1);
assert!(new_predicted >= input.media_ts_ns);
let event = SmootherEvent::Jumped {
source_id: self.source_id,
incoming_media_ts_ns: input.media_ts_ns,
previous_predicted_ts_ns: expected,
delta_ns: delta,
frames_accumulated: self.frames_accumulated,
};
SmootherResult {
action: SmootherAction::Jump,
output_ts_ns: input.media_ts_ns,
predicted_next_ts_ns: new_predicted,
frames_accumulated: self.frames_accumulated,
event,
}
}
fn apply_full_reset(
&mut self,
input: SmootherInput,
reason: SmootherResetReason,
) -> SmootherResult {
assert!(self.initialised);
let increment_ns = frames_to_ns(input.frames as u64, self.sample_rate_hz);
let new_predicted = input.media_ts_ns.saturating_add(increment_ns);
let timing_adjust = wall_minus_media_signed(input.wall_ns, input.media_ts_ns);
self.frames_accumulated = self.frames_accumulated.saturating_add(input.frames as u64);
self.predicted_next_ts_ns = new_predicted;
self.timing_adjust_ns = timing_adjust;
self.consecutive_jumps = 0;
assert!(new_predicted >= input.media_ts_ns);
let event = SmootherEvent::Reset {
source_id: self.source_id,
incoming_media_ts_ns: input.media_ts_ns,
wall_ns: input.wall_ns,
timing_adjust_ns: timing_adjust,
frames_accumulated: self.frames_accumulated,
reason,
};
SmootherResult {
action: SmootherAction::Reset,
output_ts_ns: input.media_ts_ns,
predicted_next_ts_ns: new_predicted,
frames_accumulated: self.frames_accumulated,
event,
}
}
}
pub fn frames_to_ns(frames: u64, sample_rate_hz: u32) -> u64 {
assert!(sample_rate_hz >= SAMPLE_RATE_HZ_MIN);
assert!(sample_rate_hz <= SAMPLE_RATE_HZ_MAX);
let product = (frames as u128) * (NS_PER_SECOND as u128);
let div = product / (sample_rate_hz as u128);
assert!(div <= u64::MAX as u128);
div as u64
}
fn signed_delta(a: u64, b: u64) -> i64 {
if a >= b {
let diff = a - b;
assert!(diff <= i64::MAX as u64);
diff as i64
} else {
let diff = b - a;
assert!(diff <= i64::MAX as u64);
-(diff as i64)
}
}
fn wall_minus_media_signed(wall_ns: u64, media_ts_ns: u64) -> i64 {
signed_delta(wall_ns, media_ts_ns)
}
#[cfg(test)]
mod tests {
use super::*;
const SR: u32 = 48_000;
fn frames_per_20ms() -> u32 {
SR / 50
}
fn period_ns_20ms() -> u64 {
20_000_000
}
#[test]
fn first_sample_initialises_state() {
let mut smoother = AudioTimingSmoother::new(1, SR).expect("ok");
assert!(!smoother.initialised());
let result = smoother
.adjust(SmootherInput {
media_ts_ns: 1_000_000,
frames: frames_per_20ms(),
wall_ns: 1_500_000,
})
.expect("ok");
assert_eq!(result.action, SmootherAction::Reset);
assert!(smoother.initialised());
assert!(matches!(
result.event,
SmootherEvent::Reset {
reason: SmootherResetReason::FirstSample,
..
}
));
assert_eq!(result.output_ts_ns, 1_000_000);
assert_eq!(result.frames_accumulated, frames_per_20ms() as u64);
assert!(result.predicted_next_ts_ns >= result.output_ts_ns);
}
#[test]
fn second_sample_within_threshold_snaps_to_expected() {
let mut smoother = AudioTimingSmoother::new(2, SR).expect("ok");
let frames = frames_per_20ms();
let _ = smoother
.adjust(SmootherInput {
media_ts_ns: 0,
frames,
wall_ns: 0,
})
.expect("ok");
let expected = smoother.predicted_next_ts_ns();
let drift_ns = 10_000_000;
let r = smoother
.adjust(SmootherInput {
media_ts_ns: expected + drift_ns,
frames,
wall_ns: expected + drift_ns,
})
.expect("ok");
assert_eq!(r.action, SmootherAction::Snap);
assert_eq!(r.output_ts_ns, expected);
assert!(matches!(r.event, SmootherEvent::Snapped { .. }));
}
#[test]
fn jump_outside_threshold_but_within_max_var() {
let mut smoother = AudioTimingSmoother::new(3, SR).expect("ok");
let frames = frames_per_20ms();
let _ = smoother
.adjust(SmootherInput {
media_ts_ns: 0,
frames,
wall_ns: 0,
})
.expect("ok");
let expected = smoother.predicted_next_ts_ns();
let jump_ns = 100_000_000;
let r = smoother
.adjust(SmootherInput {
media_ts_ns: expected + jump_ns,
frames,
wall_ns: expected + jump_ns,
})
.expect("ok");
assert_eq!(r.action, SmootherAction::Jump);
assert_eq!(r.output_ts_ns, expected + jump_ns);
assert!(matches!(r.event, SmootherEvent::Jumped { .. }));
assert_eq!(smoother.consecutive_jumps(), 1);
}
#[test]
fn gap_beyond_max_var_triggers_full_reset() {
let mut smoother = AudioTimingSmoother::new(4, SR).expect("ok");
let frames = frames_per_20ms();
let _ = smoother
.adjust(SmootherInput {
media_ts_ns: 0,
frames,
wall_ns: 0,
})
.expect("ok");
let expected = smoother.predicted_next_ts_ns();
let huge_gap = 3 * NS_PER_SECOND;
let r = smoother
.adjust(SmootherInput {
media_ts_ns: expected + huge_gap,
frames,
wall_ns: expected + huge_gap,
})
.expect("ok");
assert_eq!(r.action, SmootherAction::Reset);
assert!(matches!(
r.event,
SmootherEvent::Reset {
reason: SmootherResetReason::GapBeyondMaxVar,
..
}
));
}
#[test]
fn regression_inside_jump_window_triggers_reset() {
let mut smoother = AudioTimingSmoother::new(5, SR).expect("ok");
let frames = frames_per_20ms();
let _ = smoother
.adjust(SmootherInput {
media_ts_ns: NS_PER_SECOND,
frames,
wall_ns: NS_PER_SECOND,
})
.expect("ok");
let expected = smoother.predicted_next_ts_ns();
assert!(expected > 200_000_000);
let r = smoother
.adjust(SmootherInput {
media_ts_ns: expected - 200_000_000,
frames,
wall_ns: NS_PER_SECOND,
})
.expect("ok");
assert_eq!(r.action, SmootherAction::Reset);
assert!(matches!(
r.event,
SmootherEvent::Reset {
reason: SmootherResetReason::Regression,
..
}
));
}
#[test]
fn monotonicity_preserved_across_1000_samples_with_jitter() {
let mut smoother = AudioTimingSmoother::new(6, SR).expect("ok");
let frames = frames_per_20ms();
let mut wall_ns: u64 = 0;
let mut media_ts: u64 = 0;
let mut last_predicted = 0u64;
for n in 0..1000u64 {
let jitter: i64 = ((n as i64 * 1_234_567) % 100_000_000) - 50_000_000;
let jittered_ts = if jitter < 0 {
media_ts.saturating_sub(jitter.unsigned_abs())
} else {
media_ts.saturating_add(jitter as u64)
};
let r = smoother
.adjust(SmootherInput {
media_ts_ns: jittered_ts,
frames,
wall_ns,
})
.expect("ok");
assert!(r.predicted_next_ts_ns >= last_predicted || r.action == SmootherAction::Reset);
last_predicted = r.predicted_next_ts_ns;
wall_ns = wall_ns.saturating_add(period_ns_20ms());
media_ts = media_ts.saturating_add(period_ns_20ms());
}
assert!(smoother.frames_accumulated() >= 1000 * frames as u64);
}
#[test]
fn frame_count_accumulates_monotonically() {
let mut smoother = AudioTimingSmoother::new(7, SR).expect("ok");
let frames = frames_per_20ms();
let mut prev = 0u64;
for n in 0..50u64 {
let r = smoother
.adjust(SmootherInput {
media_ts_ns: n * period_ns_20ms(),
frames,
wall_ns: n * period_ns_20ms(),
})
.expect("ok");
assert!(r.frames_accumulated > prev);
prev = r.frames_accumulated;
}
}
#[test]
fn rejects_zero_source_id() {
let err = AudioTimingSmoother::new(0, SR).err();
assert!(matches!(err, Some(AudioTimingError::SourceIdZero)));
}
#[test]
fn rejects_sample_rate_out_of_range() {
let err = AudioTimingSmoother::new(1, 1_000).err();
assert!(matches!(
err,
Some(AudioTimingError::SampleRateOutOfRange { .. })
));
}
#[test]
fn rejects_zero_frame_count() {
let mut smoother = AudioTimingSmoother::new(1, SR).expect("ok");
let err = smoother
.adjust(SmootherInput {
media_ts_ns: 0,
frames: 0,
wall_ns: 0,
})
.err();
assert!(matches!(
err,
Some(AudioTimingError::FramesOutOfRange { .. })
));
}
#[test]
fn frames_to_ns_is_round_trip_consistent() {
let ns = frames_to_ns(48_000, 48_000);
assert_eq!(ns, NS_PER_SECOND);
let ns_half = frames_to_ns(24_000, 48_000);
assert_eq!(ns_half, NS_PER_SECOND / 2);
}
#[test]
fn determinism_two_runs_produce_identical_outputs() {
let run = || {
let mut s = AudioTimingSmoother::new(9, SR).expect("ok");
let mut events: Vec<SmootherResult> = Vec::with_capacity(100);
for n in 0..100u64 {
let r = s
.adjust(SmootherInput {
media_ts_ns: n * period_ns_20ms(),
frames: frames_per_20ms(),
wall_ns: n * period_ns_20ms() + 1_000,
})
.expect("ok");
events.push(r);
}
events
};
let a = run();
let b = run();
assert_eq!(a, b);
}
}