Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
7e1b936
media: add bounded PCM playout and artifact-based NetEq comparisons
theomonnom Nov 28, 2026
9c3e076
media: place listening faults in verified active speech
theomonnom Nov 28, 2026
de33119
media: add voiced and unvoiced concealment with aligned recovery
theomonnom Nov 28, 2026
927b4e4
media: make the listening underrun 30ms and label its timing
theomonnom Nov 28, 2026
3ecaa39
media: align audible comparison faults near five seconds
theomonnom Nov 28, 2026
2977ef9
media: add sustained slow jitter evaluation and document limits
theomonnom Nov 28, 2026
ca3a718
media: focus comparisons on first answer chunks and reported jitter
theomonnom Nov 28, 2026
d4e11c8
media: reject silent startup listening fixtures
theomonnom Nov 28, 2026
8a9e139
media: document expanded listening comparison matrix
theomonnom Nov 28, 2026
8040ce8
media: improve adaptive reserve and speech gap recovery
theomonnom Nov 28, 2026
4c7ef1c
media: add remaining PCM NetEq stages and catch-up traces
theomonnom Nov 28, 2026
a5426ed
media: add reproducible catch-up timing plots
theomonnom Nov 28, 2026
49a6d58
media: add twenty-second sustained jitter comparison
theomonnom Nov 28, 2026
3079950
media: add audible repeated-stall stress fixture
theomonnom Nov 28, 2026
4cd5678
media: cluster stall demo into six-second previews
theomonnom Nov 28, 2026
6ac9b28
media: learn startup timing across answers and build reserve safely
theomonnom Nov 28, 2026
78fc40d
media: expose startup learning and capture answer latency comparisons
theomonnom Nov 28, 2026
7af1fba
media: demonstrate startup learning with an explicit slow delivery tr…
theomonnom Nov 28, 2026
a73625f
media: audit playout regressions and consolidate optional NetEq compa…
theomonnom Nov 28, 2026
7f56ef6
media: tidy supporting files
theomonnom Nov 28, 2026
75653c4
media: improve tool readability
theomonnom Nov 28, 2026
24c0120
media: clarify stream lifecycles and replay profiles
theomonnom Nov 28, 2026
2bb44b7
media: support native PCM rates
theomonnom Nov 28, 2026
70ddbb3
media: align playout time scaling
theomonnom Nov 28, 2026
8dcf8d9
media: enforce splice selection and replay invariants
theomonnom Nov 28, 2026
c66a2e6
media: simplify splice ranking and comparison tooling
theomonnom Nov 28, 2026
f20b987
media: preserve exact splice matches and validate startup recovery
theomonnom Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 2 additions & 48 deletions rust/crates/lk-agents-media/src/audio_byte_stream_tests.rs
Original file line number Diff line number Diff line change
@@ -1,49 +1,5 @@
use super::audio_byte_stream::AudioByteStream;
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;

struct CountedSystem;

thread_local! {
static ALLOCATED: Cell<Option<usize>> = const { Cell::new(None) };
}

fn count(bytes: usize) {
let _ = ALLOCATED.try_with(|counter| {
if let Some(total) = counter.get() {
counter.set(Some(total + bytes));
}
});
}

// SAFETY: every operation forwards its original pointers and layouts to System.
unsafe impl GlobalAlloc for CountedSystem {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
count(layout.size());
// SAFETY: the allocator contract supplies a valid layout.
unsafe { System.alloc(layout) }
}

unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
count(layout.size());
// SAFETY: the allocator contract supplies a valid layout.
unsafe { System.alloc_zeroed(layout) }
}

unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
// SAFETY: allocation and deallocation both use System with the caller's layout.
unsafe { System.dealloc(ptr, layout) }
}

unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
count(new_size);
// SAFETY: the caller supplies an allocated pointer and valid replacement size.
unsafe { System.realloc(ptr, layout, new_size) }
}
}

#[global_allocator]
static ALLOCATOR: CountedSystem = CountedSystem;
use crate::test_alloc::allocated;

/// Framing allocates only linear storage while preserving every PCM byte. https://github.com/livekit/agents/pull/4247
#[test]
Expand All @@ -52,9 +8,7 @@ fn extracting_many_frames_does_not_reallocate_the_remaining_tail_each_time() {
for frames in [128, 256, 512] {
let input: Vec<_> = (0..frames * 320).map(|i| (i % 251) as u8).collect();
let mut stream = AudioByteStream::new(16_000, 1, Some(160), false);
ALLOCATED.with(|counter| counter.set(Some(0)));
let out = stream.push(&input);
let allocated = ALLOCATED.with(|counter| counter.replace(None).unwrap());
let (out, allocated) = allocated(|| stream.push(&input));
assert_eq!(out.len(), frames);
assert_eq!(out.into_iter().flat_map(|f| f.data).collect::<Vec<_>>(), input);
assert!(
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/lk-agents-media/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ pub mod media_queue;
pub mod mime;
pub mod mixer;
pub mod pauses;
pub mod playout;
pub mod pool;
pub mod recorder;
pub mod resample;
pub mod source;
mod soxr;
#[cfg(test)]
mod test_alloc;
pub mod wav;

pub use audio_byte_stream::{AudioByteStream, Frame};
Expand Down
138 changes: 138 additions & 0 deletions rust/crates/lk-agents-media/src/playout/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Ordered PCM playout

Bounded mono 16/24/48 kHz PCM16 playout. Push complete chunks with monotonic arrival times
and render up to 20 ms on the consumer's clock (320/480/960 samples respectively). Chunk sizes may change. The caller owns
pacing and format conversion; capacity errors reject the entire chunk atomically.

Set `Config { sample_rate: 48_000, ..Config::default() }` at construction. The default is
24 kHz. Input and output use the same native rate; there is no implicit resampling or
runtime rate setter. `sample_rate()` reports the selected rate, which survives resets and
segment boundaries. Other rates are rejected explicitly.

## Choose the source lifecycle

| Source | Constructor | Lifecycle |
| --- | --- | --- |
| Continuous audio | `Playout::continuous(config)` | `push` / `render`; `finish` only at actual EOF |
| Explicit segments | `Playout::segmented(config)` | First segment is ready; `end_segment`, drain, then `begin_segment` |

The continuous type has no segment methods. It starts once and keeps learning delivery
timing without boundary events. PCM silence remains part of the stream; missing audio is
an underrun, never an inferred segment boundary. Keep rendering through delivery gaps.

The segmented type exposes symmetric `begin_segment()` / `end_segment()` methods instead
of `finish()`. Use it when a provider identifies answers or other source boundaries.
`end_segment()` rejects new input while accepted audio drains. Wait for `Render::drained`
before `begin_segment()` unless deliberately cancelling queued speech. A new segment
clears audio/DSP and resets its clock, counters and scaling cadence while retaining learned
delivery timing. In either mode, `reset()` discards audio **and** learned timing.

Both types use the same DSP and buffers. Mode selection has no runtime or allocation cost.

## Buffering

Defaults: 80 ms startup, 20–100 ms adaptive target, 2 s capacity and up to 200 ms
extrapolated speech. Targets are not hard latency caps. Time scaling uses NetEq's 30 ms
window, full-period crossfade, 0.9/0.5 normal/fast correlation thresholds and 50 ms ordinary
cadence. Above four times the high-delay threshold, emergency catch-up bypasses the wait.
There is no cumulative percentage quota. `time_stretching: false` disables scaling.
Queued bursts and EOF may release startup early. Across explicit segments, clean startup
observations gradually reduce the initial wait; worse history increases it within bounds.

Time scaling prefers quiet splices or matching pitch periods. Concealment blends voiced
and unvoiced continuation into source-trained room tone, then recovery merges returning
PCM. Generated sound never trains the noise model. Long outages still lose intelligibility.
The native-rate-only change preserved all 24 kHz outputs byte-for-byte. The subsequent
explicit cadence/splice tuning intentionally changes audio; the deterministic PCM hash
now pins that latest implementation. Tests cover accounting, allocation, lifecycle, silence/resumption, jitter/drift, scaling,
transients, recovery, capacity errors and EOF. Provider/runtime wiring remains separate.

## Optional NetEq comparison

Requires Python 3.11+, Cargo, clang++, FFmpeg and the extracted platform archive from
[livekit/rust-sdks: webrtc-a545de4](https://github.com/livekit/rust-sdks/releases/tag/webrtc-a545de4).

```sh
python3 rust/crates/lk-agents-media/tools/neteq_compare.py \
--input /path/to/mono-pcm16.wav \
--webrtc /path/to/mac-arm64-release --output /tmp/playout-comparison
```

The single script has typed, described presets for steady delivery, delayed startup,
bounded jitter, slow startup/jitter, positive/negative clock drift, short/long/repeated stalls,
catch-up and variable chunks. `--help` lists exact timings. All preserve ordered source;
RTP loss, reordering and encoded FEC/PLC are outside this reliable PCM layer.

A fixed seed and source-time clock make retries reproducible with the same inputs and
toolchain. Outputs include aligned WAVs, arrival/operation CSVs and a report containing
settings, preset descriptions, seed, hashes, startup delay and pre-EOF counters. The script
checks source accounting/drain and rejects silent fault onsets. A copied script accepts
`--crate /path/to/lk-agents-media`; embedded bridges build in a temporary directory.

The script accepts 16/24/48 kHz WAVs. Only NetEq converts to/from 48 kHz for L16 when
needed. It retains each enclosing chunk's arrival time
and its own native rate control; `--native-maximum-ms` sets an optional target cap. Onset
latency excludes model, live network and device delay. These are diagnostic comparisons,
not perceptual scores or a claim of NetEq parity. Existing PR recordings remain attached.

<details>
<summary>Upstream notices for adapted components</summary>

```text
Copyright (c) 2011, The WebRTC project authors. 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 name of Google nor the names of its 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
HOLDER 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.

Additional IP Rights Grant (Patents)

"This implementation" means the copyrightable works distributed by
Google as part of the WebRTC code package.

Google hereby grants to you a perpetual, worldwide, non-exclusive,
no-charge, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import,
transfer, and otherwise run, modify and propagate the contents of this
implementation of the WebRTC code package, where such license applies
only to those patent claims, both currently owned by Google and
acquired in the future, licensable by Google that are necessarily
infringed by this implementation of the WebRTC code package. This
grant does not include claims that would be infringed only as a
consequence of further modification of this implementation. If you or
your agent or exclusive licensee institute or order or agree to the
institution of patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that this
implementation of the WebRTC code package or any code incorporated
within this implementation of the WebRTC code package constitutes
direct or contributory patent infringement, or inducement of patent
infringement, then any patent rights granted to you under this License
for this implementation of the WebRTC code package shall terminate as
of the date such litigation is filed.
```

</details>
Loading
Loading