Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
129 changes: 125 additions & 4 deletions common/audio_lm.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
#include "codec_common.h"
#include "audio_lm_window.h"
#include "audio_lm_stream.h"
#include "codec_look.h"

#include <algorithm>
#include <cstring>
Expand Down Expand Up @@ -46,6 +49,15 @@ struct audio_lm_context {
// the caller (owned here). NULL = model default.
const codec_speaker * decode_speaker = nullptr;

// Streaming decode with codec memory (src/audio_lm_stream.h): a second codec context over `model` whose decoder
// memory carries the decoder's state between polls, created at the first stream of a causal codec. The memory
// state after the last in-context reference voice is kept, keyed by its codes and the decode speaker.
codec_context * stream_ctx = nullptr;
bool stream_tried = false;
std::vector<int32_t> prefix_codes;
const codec_speaker * prefix_speaker = nullptr;
std::vector<uint8_t> prefix_state;

// Cached capabilities (read once at init).
uint32_t modality_mask = 0;
int32_t n_cb = 0;
Expand Down Expand Up @@ -424,6 +436,7 @@ void audio_lm_free(audio_lm_context * ctx) {
if (ctx->state) codec_lm_state_free(ctx->state);
if (ctx->lm) codec_lm_free(ctx->lm);
if (ctx->codec_ctx) codec_free(ctx->codec_ctx);
if (ctx->stream_ctx) codec_free(ctx->stream_ctx);
if (ctx->model && ctx->owns_model) codec_model_free(ctx->model);
delete ctx;
}
Expand Down Expand Up @@ -1772,6 +1785,18 @@ static int32_t audio_lm_max_delay(const audio_lm_context * ctx) {
return max_delay;
}

// The codec's decoder look_back / look_ahead (GGUF codec.decoder.look_*, else the per-arch defaults), in codec
// frames. An unbounded look_back (-1) has no window.
bool audio_lm_stream_window(const audio_lm_context * ctx, int32_t * left, int32_t * right) {
if (ctx == nullptr || ctx->model == nullptr) return false;
int32_t back = -1, ahead = -1;
codec_model_decoder_look(ctx->model, &back, &ahead);
if (back < 0) return false;
*left = back;
*right = std::max(0, ahead);
return ahead >= 0;
}

int32_t audio_lm_codec_hop(const audio_lm_context * ctx) {
return ctx != nullptr && ctx->model != nullptr ? codec_model_hop_size(ctx->model) : 0;
}
Expand Down Expand Up @@ -1903,9 +1928,20 @@ bool audio_lm_codec_codes(audio_lm_context * ctx, const int32_t * lm_codes, int3
return true;
}

static bool audio_lm_decode_codes_on(audio_lm_context * ctx, codec_context * cctx, const int32_t * codes,
int32_t n_frames, int32_t n_q, audio_lm_audio_output * out);

bool audio_lm_decode_codec_codes(audio_lm_context * ctx, const int32_t * codes, int32_t n_frames, int32_t n_q,
audio_lm_audio_output * out) {
if (ctx == nullptr || codes == nullptr || out == nullptr) return false;
if (ctx == nullptr) return false;
return audio_lm_decode_codes_on(ctx, ctx->codec_ctx, codes, n_frames, n_q, out);
}

// codec_decode of codec codes (n_frames x n_q) on `cctx` (the context's own codec context, or its stream context).
// out == nullptr: the audio is dropped.
static bool audio_lm_decode_codes_on(audio_lm_context * ctx, codec_context * cctx, const int32_t * codes,
int32_t n_frames, int32_t n_q, audio_lm_audio_output * out) {
if (ctx == nullptr || cctx == nullptr || codes == nullptr) return false;
if (n_frames <= 0 || n_q <= 0) {
ctx->last_error = "audio_lm_decode_audio: no codes";
return false;
Expand Down Expand Up @@ -1933,14 +1969,14 @@ bool audio_lm_decode_codec_codes(audio_lm_context * ctx, const int32_t * codes,
dp.n_q = n_q;
dp.speaker = ctx->decode_speaker;
const enum codec_status rc =
codec_decode(ctx->codec_ctx, &tokens, &pcm, dp);
codec_decode(cctx, &tokens, &pcm, dp);
if (rc != CODEC_STATUS_SUCCESS) {
const char * raw = codec_get_last_error(ctx->codec_ctx);
const char * raw = codec_get_last_error(cctx);
ctx->last_error = std::string("audio_lm_decode_audio: codec_decode failed (")
+ (raw ? raw : "?") + ")";
return false;
}
audio_lm_take_pcm(&pcm, out);
if (out != nullptr) audio_lm_take_pcm(&pcm, out); else codec_pcm_buffer_free(&pcm);
return true;
}

Expand Down Expand Up @@ -2000,6 +2036,91 @@ bool audio_lm_decode_audio_range(audio_lm_context * ctx, int32_t frame_begin, in
return audio_lm_decode_codec_codes(ctx, codes.data(), (int32_t) (codes.size() / (size_t) n_q), n_q, out);
}

// ─── Streaming decode with codec memory (internal: src/audio_lm_stream.h) ───

// The stream context: a codec context with decoder memory, when the codec's decoder is causal and has state to
// carry (codec_model_decoder_is_causal, memory size > 0) and the generation is codes.
static codec_context * audio_lm_stream_ctx(audio_lm_context * ctx) {
if (ctx->stream_ctx != nullptr || ctx->stream_tried) return ctx->stream_ctx;
ctx->stream_tried = true;
if (ctx->is_continuous || !(ctx->modality_mask & OUTPUT_AUDIO) || !codec_model_has_decoder(ctx->model) ||
!codec_model_decoder_is_causal(ctx->model)) {
return nullptr;
}
auto cp = codec_context_default_params();
cp.decoder_memory = true;
codec_context * c = codec_init_from_model(ctx->model, cp);
if (c == nullptr) return nullptr;
if (codec_memory_state_get_size(codec_get_decoder_memory(c)) == 0) {
codec_free(c);
return nullptr;
}
ctx->stream_ctx = c;
return c;
}

// The current voice's in-context reference (Qwen3-TTS ICL: a talker with a text projection, a voice with ref_text
// and ref_codes), as audio_lm_family_codebook decodes it ahead of the generation.
static bool audio_lm_icl_prefix(const audio_lm_context * ctx, std::vector<int32_t> * ref) {
ref->clear();
const codec_speaker * spk = audio_lm_decode_speaker(ctx);
if (spk == nullptr || !audio_lm_talker_has_projection(ctx)) return false;
codec_speaker_slot_type ty;
int64_t ne[4];
const void * d = nullptr;
const char * text = codec_speaker_ref_text(spk);
if (text == nullptr || !*text || !codec_speaker_get_slot(spk, "ref_codes", &ty, ne, &d) ||
ty != CODEC_SPEAKER_SLOT_I32 || ne[0] != ctx->n_cb) {
return false;
}
ref->assign(static_cast<const int32_t *>(d), static_cast<const int32_t *>(d) + ne[0] * ne[1]);
return true;
}

int32_t audio_lm_stream_begin(audio_lm_context * ctx) {
if (ctx == nullptr) return -1;
codec_context * sc = audio_lm_stream_ctx(ctx);
if (sc == nullptr) return 0;
codec_memory_t mem = codec_get_decoder_memory(sc);
std::vector<int32_t> ref;
if (!audio_lm_icl_prefix(ctx, &ref) || ctx->audio_cb_offset != 0 || ctx->cb0_speech_offset != 0) {
codec_memory_clear(mem);
return 1;
}
// ICL voice: the decoder state after the reference's codes, decoded once per voice.
const bool cached = !ctx->prefix_state.empty() && ref == ctx->prefix_codes && ctx->prefix_speaker == ctx->decode_speaker;
if (cached && codec_memory_state_set_data(mem, ctx->prefix_state.data(), ctx->prefix_state.size()) ==
ctx->prefix_state.size()) {
return 1;
}
ctx->prefix_state.clear();
codec_memory_clear(mem);
const int32_t n_ref = (int32_t) (ref.size() / (size_t) ctx->n_cb);
if (!audio_lm_decode_codes_on(ctx, sc, ref.data(), n_ref, ctx->n_cb, nullptr)) return -1;
std::vector<uint8_t> st(codec_memory_state_get_size(mem));
if (st.empty() || codec_memory_state_get_data(mem, st.data(), st.size()) != st.size()) {
ctx->last_error = "streaming: could not save the decoder state after the reference voice";
return -1;
}
ctx->prefix_state = std::move(st);
ctx->prefix_codes = std::move(ref);
ctx->prefix_speaker = ctx->decode_speaker;
return 1;
}

bool audio_lm_stream_decode(audio_lm_context * ctx, int32_t frame_begin, int32_t frame_end, audio_lm_audio_output * out) {
if (ctx == nullptr || ctx->stream_ctx == nullptr || out == nullptr) return false;
if (ctx->codes_n_frames <= 0 || ctx->n_cb <= 0) {
ctx->last_error = "audio_lm_decode_audio: no codes accumulated";
return false;
}
std::vector<int32_t> codes;
int32_t n_q = 0;
return audio_lm_codec_codes(ctx, ctx->codes.data(), ctx->codes_n_frames, ctx->n_cb, frame_begin, frame_end, &codes,
&n_q) &&
audio_lm_decode_codes_on(ctx, ctx->stream_ctx, codes.data(), (int32_t) (codes.size() / (size_t) n_q), n_q, out);
}

// ─── Decoder speaker ────────────────────────────────────────────────

bool audio_lm_codec_can_speaker_from_audio(const audio_lm_context * ctx) {
Expand Down
99 changes: 74 additions & 25 deletions common/audio_lm_c.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include "audio_lm_family.h"
#include "codec_audio_lm.h"
#include "codec_common.h"
#include "audio_lm_window.h"
#include "audio_lm_stream.h"

#include <algorithm>
#include <cmath>
Expand All @@ -19,10 +21,15 @@ using namespace codec_common;

namespace {

// Frame-level streaming over the current generation: re-decodes [0, avail)
// once enough new frames exist (causal decoders need the whole left
// context), holds back the right edge the decoder may still revise, and
// cross-fades the joins.
// Frame-level streaming over the current generation.
// * Causal decoders with codec memory (src/audio_lm_stream.h): each poll decodes only the new frames, in whole
// chunk_ms pieces, through the carried decoder state; pieces join as one decode would (no hold-back, no
// cross-fade). An in-context reference voice is decoded into the memory first (once per voice).
// * Otherwise each poll decodes a window statelessly: [committed - left, avail) with the decoder's look_back /
// look_ahead (src/audio_lm_window.h), so the cost per poll is bounded, or [0, avail) when they are unbounded
// (exact, quadratic). It holds back the right edge (frames the decoder may still revise) and the last
// cross-fade span before the commit point; the next window decodes that span again and the two are
// cross-faded (20 ms).
class alm_streamer {
public:
explicit alm_streamer(audio_lm_context * alm) : alm_(alm) {}
Expand All @@ -31,12 +38,21 @@ class alm_streamer {
bool poll(int32_t chunk_ms, std::vector<float> * piece, int32_t * sr, int32_t * nch) {
chunk_ms_ = chunk_ms;
const int32_t avail = audio_lm_decodable_frames(alm_);
if (avail > 0 && !opened_ && !open()) return false;
if (memory_) {
// whole chunks once the rate is known (few graph shapes); the first piece as soon as a frame exists
const int32_t step = chunk_ > 0 ? chunk_ : 1;
const int32_t end = committed_ + (avail - committed_) / step * step;
return (end <= committed_ || memory_piece(end, piece)) && out(piece, sr, nch);
}
if (spf_ == 0 ? avail < k_probe_frames : avail < committed_ + chunk_ + right_) return out(piece, sr, nch);
return window(avail, false, piece) && out(piece, sr, nch);
}

bool finish(std::vector<float> * piece, int32_t * sr, int32_t * nch) {
const int32_t avail = audio_lm_decodable_frames(alm_);
if (avail > 0 && !opened_ && !open()) return false;
if (memory_) return (avail <= committed_ || memory_piece(avail, piece)) && out(piece, sr, nch);
if (avail > committed_ && !window(avail, true, piece)) return false;
return out(piece, sr, nch);
}
Expand All @@ -45,7 +61,7 @@ class alm_streamer {

private:
static constexpr int32_t k_probe_frames = 8;
static constexpr double k_right_s = 0.32;
static constexpr double k_right_s = 0.32; // codecs with an unbounded look_ahead
static constexpr double k_xfade_s = 0.02;

bool out(std::vector<float> *, int32_t * sr, int32_t * nch) const {
Expand All @@ -55,52 +71,85 @@ class alm_streamer {
}

bool window(int32_t avail, bool final, std::vector<float> * piece) {
if (spf_ == 0) {
spf_ = audio_lm_codec_hop(alm_);
if (spf_ <= 0) return fail("streaming: the codec reports no hop size");
bounded_ = audio_lm_stream_window(alm_, &look_back_, &look_ahead_);
}
// first frame of the window: enough left context, and the held-back span must be in it
const int32_t w0 = !bounded_ ? 0 : std::max(0, committed_ - left_);
audio_lm_audio_output w;
if (!audio_lm_decode_audio_range(alm_, 0, avail, &w)) {
if (!audio_lm_decode_audio_range(alm_, w0, avail, &w)) {
return fail(std::string("streaming decode failed: ") + audio_lm_last_error(alm_));
}
const int32_t nch = std::max(1, w.n_channels);
const int64_t len = (int64_t) (w.pcm.size() / (size_t) nch);
if (spf_ == 0) {
spf_ = audio_lm_codec_hop(alm_);
if (spf_ <= 0) return fail("streaming: the codec reports no hop size");
if (sr_ == 0) {
sr_ = w.sample_rate;
nch_ = nch;
const double frames_per_s = (double) sr_ / spf_;
chunk_ = std::max(1, (int32_t) std::lround(chunk_ms_ * frames_per_s / 1000.0));
right_ = std::max(1, (int32_t) std::lround(k_right_s * frames_per_s));
xfade_ = std::min((int32_t) std::lround(k_xfade_s * sr_), right_ * spf_);
right_ = bounded_ ? look_ahead_ : std::max(1, (int32_t) std::lround(k_right_s * frames_per_s));
xfade_ = (int32_t) std::lround(k_xfade_s * sr_);
left_ = std::max(look_back_, (xfade_ + spf_ - 1) / spf_ + 1);
}
if (nch != nch_ || std::llabs(len - (int64_t) avail * spf_) > spf_) {
return fail("streaming: a window of " + std::to_string(avail) + " frames decoded to " +
std::to_string(len) + " samples, not about " + std::to_string((int64_t) avail * spf_));
if (nch != nch_ || std::llabs(len - (int64_t) (avail - w0) * spf_) > spf_) {
return fail("streaming: a window of " + std::to_string(avail - w0) + " frames decoded to " +
std::to_string(len) + " samples, not about " + std::to_string((int64_t) (avail - w0) * spf_));
}
const int32_t commit = final ? avail : std::max(committed_, avail - right_);
const size_t base = (size_t) committed_ * spf_;
if ((int64_t) base > len) return fail("streaming: decoded window too short");
const size_t n_new = final ? (size_t) len - base : (size_t) (commit - committed_) * spf_;
piece->assign(w.pcm.begin() + (ptrdiff_t) (base * nch_), w.pcm.begin() + (ptrdiff_t) ((base + n_new) * nch_));
const size_t nx = std::min(pending_.size() / nch_, n_new);
for (size_t i = 0; i < nx; ++i) {
const float g = (float) (i + 1) / (float) (nx + 1);
const size_t held = pending_.size() / (size_t) nch_; // samples before `committed_` not emitted yet
const int64_t b0 = (int64_t) (committed_ - w0) * spf_ - (int64_t) held; // in this window
const int64_t e0 = final ? len : std::min<int64_t>(len, (int64_t) (commit - w0) * spf_);
const int64_t keep = final ? 0 : std::min<int64_t>(xfade_, std::max<int64_t>(0, e0 - b0 - (int64_t) held));
if (b0 < 0 || e0 < b0) return fail("streaming: decoded window too short");
piece->assign(w.pcm.begin() + (ptrdiff_t) (b0 * nch_), w.pcm.begin() + (ptrdiff_t) ((e0 - keep) * nch_));
for (size_t i = 0; i < held && i < piece->size() / (size_t) nch_; ++i) { // previous window fades out
const float g = (float) (i + 1) / (float) (held + 1);
for (int32_t c = 0; c < nch_; ++c) {
float & v = (*piece)[i * nch_ + c];
v = g * v + (1.0f - g) * pending_[i * nch_ + c];
}
}
const size_t tail = base + n_new;
const size_t np = final ? 0 : std::min((size_t) xfade_, (size_t) len - tail);
pending_.assign(w.pcm.begin() + (ptrdiff_t) (tail * nch_), w.pcm.begin() + (ptrdiff_t) ((tail + np) * nch_));
pending_.assign(w.pcm.begin() + (ptrdiff_t) ((e0 - keep) * nch_), w.pcm.begin() + (ptrdiff_t) (e0 * nch_));
committed_ = commit;
return true;
}

bool fail(const std::string & e) { error_ = e; return false; }

// The path is chosen once per generation, when its first frame is decodable.
bool open() {
opened_ = true;
const int32_t rc = audio_lm_stream_begin(alm_);
if (rc < 0) return fail(std::string("streaming: ") + audio_lm_last_error(alm_));
memory_ = rc > 0;
return true;
}

bool memory_piece(int32_t end, std::vector<float> * piece) {
audio_lm_audio_output w;
if (!audio_lm_stream_decode(alm_, committed_, end, &w)) {
return fail(std::string("streaming decode failed: ") + audio_lm_last_error(alm_));
}
sr_ = w.sample_rate;
nch_ = std::max(1, w.n_channels);
if (chunk_ == 0) {
const int32_t hop = audio_lm_codec_hop(alm_);
if (hop > 0 && sr_ > 0) chunk_ = std::max(1, (int32_t) std::lround(chunk_ms_ * (double) sr_ / hop / 1000.0));
}
*piece = std::move(w.pcm);
committed_ = end;
return true;
}

audio_lm_context * alm_;
bool opened_ = false, memory_ = false;
int32_t chunk_ms_ = 0;
int32_t spf_ = 0, sr_ = 0, nch_ = 1;
int32_t chunk_ = 0, right_ = 0, xfade_ = 0;
int32_t chunk_ = 0, right_ = 0, left_ = 0, xfade_ = 0;
bool bounded_ = false;
int32_t look_back_ = 0, look_ahead_ = 0;
int32_t committed_ = 0;
std::vector<float> pending_;
std::string error_;
Expand Down
29 changes: 25 additions & 4 deletions docs/codec_common_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,31 @@ does not report the end token.

`codec_audio_lm_decode` returns the generation's audio. For streaming, call
`codec_audio_lm_stream_poll(alm, chunk_ms, &pcm)` after each `frame_done` step: it
returns the audio that became final since the last call. Each window is
re-decoded from the first frame (causal decoders need the whole left context),
the right edge the decoder may still revise is held back (0.32 s), and the
joins are crossfaded (20 ms). `codec_audio_lm_stream_finish` returns the rest.
returns the audio that became final since the last call.
`codec_audio_lm_stream_finish` returns the rest.

* **Causal decoders** (`codec_model_decoder_is_causal`, with memory state:
Qwen3-TTS-Tokenizer-12Hz, Mimi, NeMo, MOSS-Audio): each poll decodes only the
new frames, in whole `chunk_ms` pieces, on a second codec context with
decoder memory (`docs/proposals/codec_memory.md`). The pieces join as one
decode would, with no hold-back and no cross-fade, and the stream equals the
batch decode to float rounding. An in-context (ICL) reference voice is decoded
into the memory once per voice. The state after it is kept and restored for
the next generation with that voice.
* **Other decoders** decode a window statelessly on each poll. The window is
`[committed - look_back, avail)`, from the decoder's `codec.decoder.look_back`
/ `look_ahead` (GGUF keys, else per-arch defaults), at a linear total cost.
The `look_ahead` frames the decoder may still revise are held back, and the
joins are cross-faded (20 ms). An unbounded `look_back` or `look_ahead` (-1)
decodes from the first frame instead (exact, quadratic) and holds back 0.32 s.

| Codec | path | stream vs batch |
|---|---|---|
| Qwen3-TTS-Tokenizer-12Hz | memory | rel. RMS 8e-4 (ICL voice) |
| Mimi (CSM) | memory | rel. RMS 5e-5 |
| DAC | window 0.32 s / 0.32 s | identical |
| WavTokenizer | window 1.28 s / 0.32 s | log-mel 1.8 dB (codec's own error 4.8 dB) |
| others | from the first frame / 0.32 s | exact |
`decodable_frames` says how many frames are decodable so far.

To decode later (out of order, several generations on, more than once),
Expand Down
Loading
Loading