From a2293721c637088e5901474ff05c2b09cff74833 Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 01:41:17 +0800 Subject: [PATCH 1/2] fix(dac): hop size from the decoder's upsampling strides HF descript/dac_16khz's config says hop_length 512, but its ratios (2*4*5*8) give 320, and the converter wrote the config value: codec_model_hop_size reported 512 for a 320-sample hop. The loader now takes the product of the decoder blocks' ConvTranspose strides when the weights disagree with codec.hop_size (with a warning, so existing GGUFs are right without re-converting), and the converter writes the product of downsampling_ratios. Decoded audio is unchanged. Co-Authored-By: Claude Opus 5.5 --- scripts/converters/dac.py | 7 +++++-- src/models/dac.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/scripts/converters/dac.py b/scripts/converters/dac.py index f3aa100..5115259 100644 --- a/scripts/converters/dac.py +++ b/scripts/converters/dac.py @@ -426,7 +426,9 @@ def load_from_checkpoint(self, checkpoint_dir: Path) -> None: cfg = json.load(f) self.config = { "sample_rate": int(cfg.get("sampling_rate", cfg.get("sample_rate", 24000))), - "hop_size": int(cfg.get("hop_length", cfg.get("hop_size", 320))), + # the product of the downsampling ratios (HF dac_16khz's hop_length says 512, its ratios give 320) + "hop_size": int(np.prod(cfg["downsampling_ratios"])) if cfg.get("downsampling_ratios") + else int(cfg.get("hop_length", cfg.get("hop_size", 320))), "n_q": int(cfg.get("n_codebooks", cfg.get("n_q", 12))), "codebook_size": int(cfg.get("codebook_size", 1024)), "latent_dim": int(cfg.get("hidden_size", cfg.get("latent_dim", 1024))), @@ -457,7 +459,8 @@ def load_from_huggingface(self, model_id: str) -> None: cfg = model.config self.config = { "sample_rate": int(getattr(cfg, "sampling_rate", getattr(cfg, "sample_rate", 24000))), - "hop_size": int(getattr(cfg, "hop_length", getattr(cfg, "hop_size", 320))), + "hop_size": int(np.prod(cfg.downsampling_ratios)) if getattr(cfg, "downsampling_ratios", None) + else int(getattr(cfg, "hop_length", getattr(cfg, "hop_size", 320))), "n_q": int(getattr(cfg, "n_codebooks", getattr(cfg, "n_q", 12))), "codebook_size": int(getattr(cfg, "codebook_size", 1024)), "latent_dim": int(getattr(cfg, "hidden_size", getattr(cfg, "latent_dim", 1024))), diff --git a/src/models/dac.cpp b/src/models/dac.cpp index 6cad4ab..eb1c515 100644 --- a/src/models/dac.cpp +++ b/src/models/dac.cpp @@ -17,6 +17,8 @@ #include #include +static int32_t codec_dac_decoder_hop(struct codec_model * model); + enum codec_status codec_dac_init(struct codec_model * model) { codec_dac & dac = *static_cast(model->impl); @@ -32,6 +34,14 @@ enum codec_status codec_dac_init(struct codec_model * model) { model->sample_rate = dac.sample_rate; model->has_encoder = dac.has_encoder; model->has_decoder = dac.has_decoder; + // The hop is the product of the decoder's upsampling strides. GGUFs converted from the HF config can carry + // its hop_length instead (512 for dac_16khz, whose ratios 2 * 4 * 5 * 8 give 320). + const int32_t hop_w = codec_dac_decoder_hop(model); + if (hop_w > 0 && hop_w != dac.hop_size) { + codec_log(CODEC_LOG_LEVEL_WARN, "dac: codec.hop_size is %d, the decoder's strides give %d; using %d\n", + dac.hop_size, hop_w, hop_w); + dac.hop_size = hop_w; + } model->hop_size = dac.hop_size; model->n_q = dac.n_q; model->codebook_size = dac.codebook_size; @@ -283,6 +293,26 @@ static std::string codec_dac_model_block_convtr_b_name(int32_t naming_mode, int3 return codec_dac_model_block_prefix(naming_mode, bi) + "conv_t1.bias"; } +static bool codec_dac_infer_convtr_shape(ggml_tensor * w, ggml_tensor * b, int32_t * kernel, int32_t * in_c, int32_t * out_c); + +// Product of the decoder blocks' ConvTranspose strides (kernel = 2 * stride), 0 if the weights don't say. +static int32_t codec_dac_decoder_hop(struct codec_model * model) { + if (model == nullptr || model->weights == nullptr) return 0; + for (int32_t mode : {CODEC_DAC_NAMING_MODEL, CODEC_DAC_NAMING_LEGACY}) { + int32_t hop = 1, n = 0; + for (int32_t bi = 0; bi < CODEC_DAC_MAX_BLOCKS; ++bi) { + ggml_tensor * w = ggml_get_tensor(model->weights, codec_dac_model_block_convtr_w_name(mode, bi).c_str()); + ggml_tensor * b = ggml_get_tensor(model->weights, codec_dac_model_block_convtr_b_name(mode, bi).c_str()); + int32_t k = 0, ci = 0, co = 0; + if (w == nullptr || b == nullptr || !codec_dac_infer_convtr_shape(w, b, &k, &ci, &co)) break; + hop *= std::max(1, k / 2); + ++n; + } + if (n > 0) return hop; + } + return 0; +} + static std::string codec_dac_model_resunit_snake1_name(int32_t naming_mode, int32_t bi, int32_t ri) { return codec_dac_model_block_prefix(naming_mode, bi) + "res_unit" + std::to_string(ri + 1) + ".snake1.alpha"; } From bf5f788018c1c705506857d8d7ac716793690b2f Mon Sep 17 00:00:00 2001 From: Hans Date: Mon, 16 Nov 2026 11:05:52 +0800 Subject: [PATCH 2/2] feat(audio-lm): stream causal decoders through codec memory, window the rest from look_* codec_audio_lm_stream_poll, rebuilt on the codec memory API (#9): - 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, created at the first stream. No hold-back, no cross-fade; the stream equals the batch decode to float rounding (Qwen3 ICL rel. RMS 8.2e-4, CSM/Mimi 4.8e-5). - ICL voices: the reference's codes are decoded into the memory once per voice; the memory state after them (codec_memory_state_get_data) is kept in the audio_lm context and restored for the next generation with that voice. Batch decodes are unchanged (they still decode reference + generation on the context's own codec context and cut). - Other decoders: the stateless window of the windowed streamer, with left context and hold-back read from codec.decoder.look_back / look_ahead (GGUF keys, else the per-arch defaults) instead of a per-arch table. An unbounded look_back or look_ahead decodes from the first frame (exact, quadratic) and holds back 0.32 s, as before. Internal only: src/audio_lm_stream.h, src/audio_lm_window.h and src/codec_look.h are in the audio_lm objects' private include dir. No change to include/ or common/*.h. tests/e2e/audio_lm_stream_smoke.py checks the memory path against batch (rel. RMS <= 1e-3, a repeat stream with the restored ICL state identical) and the windowed path (DAC) perceptually. Co-Authored-By: Claude Opus 5.5 --- common/audio_lm.cpp | 129 ++++++++++++++++++++++++++++- common/audio_lm_c.cpp | 99 ++++++++++++++++------ docs/codec_common_api.md | 29 ++++++- src/audio_lm_stream.h | 26 ++++++ src/audio_lm_window.h | 20 +++++ src/codec.cpp | 6 ++ src/codec_look.h | 13 +++ tests/e2e/audio_lm_stream_smoke.py | 113 +++++++++++++++++++++++++ 8 files changed, 402 insertions(+), 33 deletions(-) create mode 100644 src/audio_lm_stream.h create mode 100644 src/audio_lm_window.h create mode 100644 src/codec_look.h create mode 100644 tests/e2e/audio_lm_stream_smoke.py diff --git a/common/audio_lm.cpp b/common/audio_lm.cpp index 1b5bd81..34ccb5b 100644 --- a/common/audio_lm.cpp +++ b/common/audio_lm.cpp @@ -1,4 +1,7 @@ #include "codec_common.h" +#include "audio_lm_window.h" +#include "audio_lm_stream.h" +#include "codec_look.h" #include #include @@ -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 prefix_codes; + const codec_speaker * prefix_speaker = nullptr; + std::vector prefix_state; + // Cached capabilities (read once at init). uint32_t modality_mask = 0; int32_t n_cb = 0; @@ -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; } @@ -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; } @@ -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; @@ -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; } @@ -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 * 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(d), static_cast(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 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 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 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) { diff --git a/common/audio_lm_c.cpp b/common/audio_lm_c.cpp index 20e922e..1fd71b8 100644 --- a/common/audio_lm_c.cpp +++ b/common/audio_lm_c.cpp @@ -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 #include @@ -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) {} @@ -31,12 +38,21 @@ class alm_streamer { bool poll(int32_t chunk_ms, std::vector * 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 * 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); } @@ -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 *, int32_t * sr, int32_t * nch) const { @@ -55,52 +71,85 @@ class alm_streamer { } bool window(int32_t avail, bool final, std::vector * 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(len, (int64_t) (commit - w0) * spf_); + const int64_t keep = final ? 0 : std::min(xfade_, std::max(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 * 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 pending_; std::string error_; diff --git a/docs/codec_common_api.md b/docs/codec_common_api.md index a70a897..c8cb72a 100644 --- a/docs/codec_common_api.md +++ b/docs/codec_common_api.md @@ -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), diff --git a/src/audio_lm_stream.h b/src/audio_lm_stream.h new file mode 100644 index 0000000..b5b2801 --- /dev/null +++ b/src/audio_lm_stream.h @@ -0,0 +1,26 @@ +#ifndef CODEC_AUDIO_LM_STREAM_H +#define CODEC_AUDIO_LM_STREAM_H + +// Internal to libcodec (the audio_lm objects' private include dir; not installed, not part of include/ or +// common/*.h). +// +// Streaming decode with codec memory (docs/proposals/codec_memory.md): for a causal decoder, each +// codec_audio_lm_stream_poll decodes only the new frames on a second codec context whose decoder memory carries +// the decoder's state. An in-context reference voice is decoded into the memory first, once per voice (the state +// after it is kept and restored for the next generation). + +#include "codec_common.h" + +namespace codec_common { + +// Starts a stream for the current generation: clears the stream context's decoder memory, or restores the state +// after the current voice's in-context reference. 1: started; 0: the codec has no memory streaming (a non-causal +// decoder, no state to carry, continuous latents); -1: an error (last_error set). +int32_t audio_lm_stream_begin(audio_lm_context * ctx); +// Decodes accumulated frames [frame_begin, frame_end) on the stream context; frame_begin must be where the +// previous call ended (0 after begin). +bool audio_lm_stream_decode(audio_lm_context * ctx, int32_t frame_begin, int32_t frame_end, audio_lm_audio_output * out); + +} // namespace codec_common + +#endif diff --git a/src/audio_lm_window.h b/src/audio_lm_window.h new file mode 100644 index 0000000..848adb9 --- /dev/null +++ b/src/audio_lm_window.h @@ -0,0 +1,20 @@ +#ifndef CODEC_AUDIO_LM_WINDOW_H +#define CODEC_AUDIO_LM_WINDOW_H + +// Internal to libcodec (the audio_lm objects' private include dir; not installed, not part of include/ or +// common/*.h). + +#include "codec_common.h" + +namespace codec_common { + +// The stateless streaming window of the context's codec, in codec frames: each poll decodes +// [committed - left, avail), holds back `right` (the frames the decoder may still revise), and cross-fades the joins. +// Read from the decoder's look_back / look_ahead (GGUF codec.decoder.look_*, else the per-arch defaults). false: an +// unbounded look_back or look_ahead; the streamer decodes from the generation's first frame (exact, quadratic). +// Causal decoders with memory do not use it (src/audio_lm_stream.h). +bool audio_lm_stream_window(const audio_lm_context * ctx, int32_t * left, int32_t * right); + +} // namespace codec_common + +#endif diff --git a/src/codec.cpp b/src/codec.cpp index 8af72dd..a784ea8 100644 --- a/src/codec.cpp +++ b/src/codec.cpp @@ -1,4 +1,5 @@ #include "codec_internal.h" +#include "codec_look.h" #include @@ -262,6 +263,11 @@ static void codec_model_look_defaults(codec_model * model) { } } +void codec_model_decoder_look(const codec_model * model, int32_t * look_back, int32_t * look_ahead) { + *look_back = model != nullptr ? model->dec_look_back : -1; + *look_ahead = model != nullptr ? model->dec_look_ahead : -1; +} + static void codec_model_load_look(codec_model * model) { codec_model_look_defaults(model); model->enc_look_back = codec_read_i32_kv(model->gguf, "codec.encoder.look_back", model->enc_look_back); diff --git a/src/codec_look.h b/src/codec_look.h new file mode 100644 index 0000000..b9be523 --- /dev/null +++ b/src/codec_look.h @@ -0,0 +1,13 @@ +#ifndef CODEC_LOOK_H +#define CODEC_LOOK_H + +// Internal to libcodec: the model's decoder look_back / look_ahead in codec frames (GGUF +// codec.decoder.look_back / look_ahead, else the per-arch defaults; -1 = unbounded). + +#include + +struct codec_model; + +void codec_model_decoder_look(const struct codec_model * model, int32_t * look_back, int32_t * look_ahead); + +#endif diff --git a/tests/e2e/audio_lm_stream_smoke.py b/tests/e2e/audio_lm_stream_smoke.py new file mode 100644 index 0000000..7858ab1 --- /dev/null +++ b/tests/e2e/audio_lm_stream_smoke.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""E2E smoke for streaming (codec_audio_lm_stream_poll). + +* Causal decoders (Qwen3-TTS-Tokenizer, Mimi): codec memory. Each poll decodes + only the new frames through the carried decoder state, so the stream equals + one batch decode to float rounding (relative RMS <= 1e-3, as + tests/e2e/codec_memory_smoke.py). An ICL voice's reference is decoded into + the memory once; a second stream with the same voice (restored state) must + give the same samples. +* Others (DAC): each poll decodes a window statelessly, [committed - look_back, + avail) with the decoder's look_back / look_ahead (GGUF codec.decoder.look_*), + and cross-fades the joins. The stream must match the batch decode + perceptually: same length, log-mel distance well under the codec's own + reconstruction error (3-5 dB against the input audio), no spectral jump at + the joins beyond the batch decode's own. + +Run from the repo root: .venv/bin/python tests/e2e/audio_lm_stream_smoke.py +""" + +import sys +import time +from math import gcd +from pathlib import Path + +import numpy as np +from scipy.signal import resample_poly, stft + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO / "python")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import codec_cpp # noqa: E402 +from _common import MODEL_SAMPLING # noqa: E402 + +M = REPO / "models" +REF = REPO / "assets" / "refs" +TEXT = "The birch canoe slid on the smooth planks. Glue the sheet to the dark blue background." +CASES = [ # name, path, codec gguf, backbone, options + ("qwen3_tts_icl", "qwen3 12 Hz: memory", M / "qwen3_tts/qwen3_tts_06b_base.gguf", M / "qwen3_tts/qwen3_tts_talker.gguf", + dict(MODEL_SAMPLING.get("qwen3_tts", {}), seed=2, ref_audio=REF / "jfk_en.wav", + ref_text=(REF / "jfk_en.txt").read_text().strip() if (REF / "jfk_en.txt").exists() else None)), + ("csm", "mimi: memory", M / "csm/csm.gguf", M / "csm/llama_backbone.gguf", dict(MODEL_SAMPLING.get("csm", {}), seed=7, temp=0)), + ("outetts_1_0", "dac 24 kHz: left 0.32 s, right 0.32 s", M / "output/outetts/outetts-1.0-0.6b-codec-F32.gguf", + M / "hf/outetts_1_0/OuteTTS-1.0-0.6B-Q8_0.gguf", dict(MODEL_SAMPLING.get("outetts_1_0", {}), seed=1)), +] +LSD_MAX, SEAM_MAX = 1.5, 2.0 # windowed path +REL_RMS_MAX = 1e-3 # memory path + + +def melfb(n_fft=400, n_mels=80, sr=16000): + hz = lambda m: 700 * (10 ** (m / 2595) - 1) # noqa: E731 + mel = lambda f: 2595 * np.log10(1 + f / 700) # noqa: E731 + pts = hz(np.linspace(0, mel(sr / 2), n_mels + 2)) + bins = np.floor((n_fft + 1) * pts / sr).astype(int) + fb = np.zeros((n_mels, n_fft // 2 + 1)) + for m in range(1, n_mels + 1): + a, b, c = bins[m - 1], bins[m], bins[m + 1] + fb[m - 1, a:b] = (np.arange(a, b) - a) / max(1, b - a) + fb[m - 1, b:c] = (c - np.arange(b, c)) / max(1, c - b) + return fb + + +FB = melfb() + + +def logmel(x, sr): + g = gcd(16000, sr) + y = resample_poly(x.astype(np.float64), 16000 // g, sr // g) + _, _, z = stft(y, 16000, nperseg=400, noverlap=240, boundary=None) # 10 ms hop + return 10 * np.log10(FB @ (np.abs(z) ** 2) + 1e-8) + + +def main() -> int: + failed = 0 + for name, win, codec, backbone, opts in CASES: + if not codec.exists() or not backbone.exists(): + print(f"[skip] {name}: missing GGUFs") + continue + opts = {k: v for k, v in opts.items() if v is not None} + memory = "memory" in win + with codec_cpp.TTS(backbone, codec) as tts: + t0 = time.time(); batch, sr = tts.synthesize(TEXT, **opts); tb = time.time() - t0 + t0 = time.time(); pieces = list(tts.stream(TEXT, chunk_ms=500, **opts)); ts = time.time() - t0 + again = [p for p, _ in tts.stream(TEXT, chunk_ms=500, **opts)] if memory else None + stream = np.concatenate([p for p, _ in pieces]) if pieces else np.zeros(0, np.float32) + joins = np.cumsum([len(p) for p, _ in pieces])[:-1] / sr + ok_len = abs(len(stream) - len(batch)) == 0 + A, B = logmel(batch, sr), logmel(stream, sr) + k = min(A.shape[1], B.shape[1]) + lsd = float(np.mean(np.sqrt(np.mean((A[:, :k] - B[:, :k]) ** 2, axis=0)))) + flux = lambda X: np.sqrt(np.mean(np.diff(X, axis=1) ** 2, axis=0)) # noqa: E731 + fa, fb = flux(A[:, :k]), flux(B[:, :k]) + js = [int(j * 100) for j in joins if 0 < int(j * 100) < len(fa) - 1] + seam = max([max(fb[j - 1:j + 2]) - max(fa[j - 1:j + 2]) for j in js], default=0.0) + ok = ok_len and len(pieces) > 2 + if memory: + n = min(len(stream), len(batch)) + rel = float(np.sqrt(np.mean((stream[:n] - batch[:n]) ** 2) / max(np.mean(batch[:n] ** 2), 1e-20))) + same = again is not None and len(again) == len(pieces) and np.array_equal(np.concatenate(again), stream) + ok = ok and rel <= REL_RMS_MAX and same + detail = f"rel rms vs batch {rel:.1e}, repeat stream {'identical' if same else 'DIFFERS'}" + else: + ok = ok and lsd <= LSD_MAX and seam <= SEAM_MAX + detail = f"worst seam {seam:+.2f} dB" + print(f"[{'PASS' if ok else 'FAIL'}] {name} ({win}): {len(pieces)} pieces, {len(stream)} samples " + f"(batch {len(batch)}), log-mel distance {lsd:.2f} dB, {detail}, " + f"time stream {ts:.1f} s / batch {tb:.1f} s") + failed += not ok + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main())