File size: 27,366 Bytes
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f0b6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29439fe
 
16f0b6b
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
16f0b6b
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f0b6b
 
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f0b6b
29439fe
 
 
 
 
 
16f0b6b
 
29439fe
 
 
16f0b6b
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
"""Bidirectional streaming inference for TTS-V4 (Qwen3-TTS-12Hz architecture).

Text can be pushed incrementally while audio is produced frame by frame
(12.5 frames/s, 80 ms each) and decoded incrementally with the causal audio
decoder. Layouts (streaming_layout.py) are Qwen3-TTS native dual-track
streaming; V4 is trained on them:
  mode='icl'  - reference audio codes + reference transcript (best cloning and
                naturalness; starts once about ref_frames - ref_tokens target
                tokens exist, or when the text ends)
  mode='xvec' - speaker embedding only (starts after the first text token)

    engine = StreamingTTS('/path/to/TTS-V4')          # complete local model
    session = engine.session('bank_collection_female', mode='icl')
    session.push_text('您好,您的订单金额是'); session.push_text('235.60元。'); session.end()
    for pcm in session.audio():                       # float32 chunks, 24 kHz
        ...
"""
import json
import queue
import re
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path

import librosa
import numpy as np
import torch
torch.backends.cuda.enable_cudnn_sdp(False)  # avoid sporadic cuDNN SDPA failures under GPU sharing
from transformers.cache_utils import DynamicCache

from streaming_layout import PAD, EOS, frame_embeds, prefix_positions, required_target_tokens, stream_prefix, text_embeds
from text_normalization import normalize_text

EOS_CODE = 2150
BOUNDARY = set(',。!?;:、,!?;:\n')
ASCII_ALNUM = re.compile(r'[0-9A-Za-z]')


class IncrementalNormalizer:
    """Commit text only where spoken-form normalization cannot change later.

    Commits at punctuation. Long digit-free runs are committed except the last
    six characters (so keywords like 订单编号 stay attached to their digits).
    """

    def __init__(self):
        self.buffer = ''

    def push(self, text):
        self.buffer += text
        cut = max((i + 1 for i, c in enumerate(self.buffer) if c in BOUNDARY), default=0)
        if cut == 0 and len(self.buffer) >= 12 and not ASCII_ALNUM.search(self.buffer):
            cut = len(self.buffer) - 6
        if cut == 0:
            return []
        segment, self.buffer = self.buffer[:cut], self.buffer[cut:]
        return [normalize_text(segment)] if segment.strip() else []

    def flush(self):
        segment, self.buffer = self.buffer, ''
        return [normalize_text(segment)] if segment.strip() else []


@dataclass
class Voice:
    ref_codes: torch.Tensor
    speaker: torch.Tensor
    ref_ids: list


@dataclass
class Stats:
    t_first_text: float = None
    t_prefill: float = None
    t_first_audio: float = None
    t_done: float = None
    frames: int = 0
    audio_s: float = 0.0
    waits_for_text: int = 0
    eos: bool = False
    cancelled: bool = False
    extra: dict = field(default_factory=dict)


class StreamingTTS:
    def __init__(self, model_dir, adapter=None, device='cuda:0', voices_json=None):
        import os
        os.environ.setdefault('HF_HUB_OFFLINE', '1')
        from qwen_tts import Qwen3TTSModel
        self.root = Path(model_dir)
        self.tts = Qwen3TTSModel.from_pretrained(str(self.root), device_map=device, dtype=torch.bfloat16,
                                                 attn_implementation='sdpa', local_files_only=True)
        if adapter:
            from qwen_v4 import load_adapter
            load_adapter(self.tts.model, adapter)
        self.tts.model.eval()
        self.model = self.tts.model
        self.talker = self.model.talker
        self.decoder = self.model.speech_tokenizer.model.decoder
        self.upsample = int(self.decoder.total_upsample)
        self.sample_rate = int(self.model.speech_tokenizer.get_output_sample_rate())
        self.role_ids = self.tts._tokenize_texts([self.tts._build_assistant_text('好')])[0][0, :3].cpu()
        self.lock = threading.Lock()
        with torch.inference_mode():
            from streaming_layout import special_embeds
            _, self.eos_emb, self.pad_emb = special_embeds(self.tts)
        self.predictor = self.talker.code_predictor
        self.voices = {}
        vj = Path(voices_json) if voices_json else self.root / 'data/voices.json'
        self.voice_info = json.loads(vj.read_text()) if vj.exists() else {}
        self._residual_graphs = {}
        self.cuda_graphs_enabled = False
        if os.environ.get('V4_CUDA_GRAPH') == '1':
            self.enable_cuda_graphs()

    def enable_cuda_graphs(self, sampling=None):
        """Capture the 15-codebook loop once; applies to this incremental engine.

        Call before serving concurrent requests. Native SDK/offline generate is
        a separate path. Model weights and chunking are unchanged.
        """
        if self.model.device.type != 'cuda':
            raise ValueError('V4_CUDA_GRAPH requires a CUDA device')
        settings = dict(DEFAULT_SAMPLING, **(sampling or {}))
        with self.lock:
            self._residual_graph(settings)
            self.cuda_graphs_enabled = True

    def _residual_graph(self, sampling):
        key = (bool(sampling['subtalker_do_sample']), float(sampling['subtalker_temperature']),
               int(sampling['subtalker_top_k']))
        if key not in self._residual_graphs:
            from residual_graph import ResidualGraph
            # Bound graph memory if a service permits arbitrary temperatures.
            if len(self._residual_graphs) >= 4:
                return None
            self._residual_graphs[key] = ResidualGraph(self, sampling)
        return self._residual_graphs[key]

    # ------------------------------------------------------------ prompts
    def tokenize(self, text):
        return self.tts.processor.tokenizer(text, add_special_tokens=False)['input_ids']

    @torch.inference_mode()
    def voice(self, name=None, ref_audio=None, ref_text=None):
        key = name or (str(ref_audio), ref_text)
        if key in self.voices:
            return self.voices[key]
        if name is not None:
            info = self.voice_info[name]
            local = self.root / 'data/voices' / f'{name}.wav'
            ref_audio = str(local) if local.exists() else info['audio']
            ref_text = info['text']
        with self.lock:
            item = self.tts.create_voice_clone_prompt(ref_audio=str(ref_audio), ref_text=ref_text, x_vector_only_mode=False)[0]
        ref_ids = self.tts._tokenize_texts([self.tts._build_ref_text(ref_text)])[0][0, 3:-2].tolist()
        v = Voice(item.ref_code.to(self.model.device), item.ref_spk_embedding, ref_ids)
        self.voices[key] = v
        return v

    def session(self, voice=None, ref_audio=None, ref_text=None, segment='token', speed=1.0, **kw):
        """segment='token': text goes to the model as it arrives (Session).
        segment='sentence': each complete sentence is synthesized with its full text known (SentenceSession).
        speed: pitch-preserving rate change of the output (1.0 = as generated; >1 faster)."""
        v = self.voice(voice, ref_audio, ref_text)
        if segment == 'sentence':
            session = SentenceSession(self, v, **kw)
        elif segment == 'token':
            session = Session(self, v, **kw)
        else:
            raise ValueError("segment must be 'token' or 'sentence'")
        return session if speed == 1.0 else SpeedSession(session, speed, self.sample_rate)

    # ------------------------------------------------------------ model steps
    def _forward(self, embeds, cache, start):
        pos = torch.arange(start, start + embeds.shape[0], device=embeds.device).view(1, 1, -1).expand(3, 1, -1)
        out = self.talker.model(inputs_embeds=embeds[None], position_ids=pos, past_key_values=cache, use_cache=True)
        hidden = out.last_hidden_state
        return self.talker.codec_head(hidden[:, -1]).float(), hidden[:, -1:]

    def _residuals(self, token, past_hidden, sampling):
        """Residual codebooks 1..15 (same computation as code_predictor.generate, no HF overhead)."""
        if self.cuda_graphs_enabled:
            graph = self._residual_graph(sampling)
            if graph is not None:
                return graph.run(token, past_hidden)
        p = self.predictor
        last = self.talker.get_input_embeddings()(token.view(1, 1))
        x = p.small_to_mtp_projection(torch.cat([past_hidden, last], dim=1))
        cache = DynamicCache()
        codes = [token.view(1)]
        pos = 0
        for j in range(15):
            n = x.shape[1]
            out = p.model(inputs_embeds=x, past_key_values=cache, use_cache=True,
                          position_ids=torch.arange(pos, pos + n, device=x.device).view(1, -1))
            pos += n
            logits = p.lm_head[j](out.last_hidden_state[:, -1]).float()[0]
            if sampling['subtalker_do_sample']:
                logits = logits / sampling['subtalker_temperature']
                k = sampling['subtalker_top_k']
                if k:
                    kth = torch.topk(logits, k).values[-1]
                    logits = logits.masked_fill(logits < kth, -float('inf'))
                code = torch.multinomial(logits.softmax(-1), 1)
            else:
                code = logits.argmax().view(1)
            codes.append(code)
            if j < 14:
                x = p.small_to_mtp_projection(p.model.get_input_embeddings()[j](code.view(1, 1)))
        return torch.cat(codes)

    def _text_embed(self, element):
        if element == PAD:
            return self.pad_emb[None]
        if element == EOS:
            return self.eos_emb[None]
        ids = torch.tensor([[element]], device=self.pad_emb.device)
        return self.talker.text_projection(self.talker.get_text_embeddings()(ids))[0]

    def _decode(self, codes, new):
        """codes [T,16] (context + new frames) -> float32 samples for the last `new` frames."""
        wav = self.decoder(codes.T[None].clamp(min=0))
        return wav[0, 0, -new * self.upsample:].float().cpu().numpy()


def _sample(logits, history, step, s):
    scores = logits[0].clone()
    if s['repetition_penalty'] != 1.0 and history:
        idx = torch.tensor(sorted(set(history)), device=scores.device)
        val = scores[idx]
        scores[idx] = torch.where(val > 0, val / s['repetition_penalty'], val * s['repetition_penalty'])
    vocab = scores.shape[0]
    keep = scores[EOS_CODE].clone()
    scores[vocab - 1024:] = -float('inf')
    scores[EOS_CODE] = keep if step >= 2 else -float('inf')
    if not s['do_sample']:
        return int(scores.argmax())
    scores = scores / s['temperature']
    if s['top_k']:
        kth = torch.topk(scores, s['top_k']).values[-1]
        scores[scores < kth] = -float('inf')
    return int(torch.multinomial(scores.softmax(-1), 1))


DEFAULT_SAMPLING = dict(do_sample=True, temperature=0.8, top_k=50, repetition_penalty=1.05,
                        subtalker_do_sample=True, subtalker_temperature=0.8, subtalker_top_k=50, subtalker_top_p=1.0)


def _soft_limit(x, knee=0.85, ceiling=0.98):
    mag = np.abs(x)
    over = mag > knee
    if not np.any(over):
        return x
    headroom = ceiling - knee
    out = x.copy()
    out[over] = np.sign(x[over]) * (knee + headroom * np.tanh((mag[over] - knee) / headroom))
    return out


def level_audio(audio, sample_rate=24000, target_db=-20.0, max_gain_db=14.0, min_gain_db=-12.0):
    """Offline active-speech RMS leveling with soft peak limiting."""
    x = np.asarray(audio, dtype=np.float32).reshape(-1)
    if len(x) == 0:
        return x
    hop = max(1, int(0.02 * sample_rate))
    n = len(x) // hop
    if n > 0:
        frm = np.sqrt(np.mean(x[:n * hop].reshape(n, hop) ** 2, axis=1) + 1e-12)
        active = frm[frm > 10 ** (-42.0 / 20.0)]
        cur_rms = float(np.sqrt(np.mean(active ** 2))) if len(active) else float(np.sqrt(np.mean(x ** 2)))
    else:
        cur_rms = float(np.sqrt(np.mean(x ** 2)))
    if cur_rms < 1e-6:
        return x
    target = 10 ** (target_db / 20.0)
    gain = float(np.clip(target / cur_rms, 10 ** (min_gain_db / 20.0), 10 ** (max_gain_db / 20.0)))
    return _soft_limit(x * gain).astype(np.float32)


class Leveler:
    """Zero-latency streaming active-speech RMS leveler with smooth gain ramping & soft limiting."""

    def __init__(self, sample_rate=24000, target_db=-20.0, max_gain_db=14.0, min_gain_db=-12.0):
        self.sr = sample_rate
        self.target = 10 ** (target_db / 20.0)
        self.min_gain = 10 ** (min_gain_db / 20.0)
        self.max_gain = 10 ** (max_gain_db / 20.0)
        self.floor = 10 ** (-42.0 / 20.0)
        self.gain = 1.0
        self.ema_rms = None
        self.new_sentence = True

    def on_sentence_start(self):
        self.new_sentence = True

    def process(self, chunk):
        x = np.asarray(chunk, dtype=np.float32).reshape(-1)
        if len(x) == 0:
            return x
        hop = max(1, int(0.02 * self.sr))
        n = len(x) // hop
        if n > 0:
            frm = np.sqrt(np.mean(x[:n * hop].reshape(n, hop) ** 2, axis=1) + 1e-12)
            active = frm[frm > self.floor]
            rms = float(np.sqrt(np.mean(active ** 2))) if len(active) else 0.0
        else:
            rms = float(np.sqrt(np.mean(x ** 2)))
            rms = rms if rms > self.floor else 0.0
        target_gain = self.gain
        if rms > 0.0:
            if self.ema_rms is None or self.new_sentence:
                self.ema_rms = rms if self.ema_rms is None else 0.8 * rms + 0.2 * self.ema_rms
                self.new_sentence = False
            else:
                self.ema_rms = 0.45 * rms + 0.55 * self.ema_rms
            target_gain = float(np.clip(self.target / self.ema_rms, self.min_gain, self.max_gain))
        ramp = min(len(x), int(0.04 * self.sr))
        if ramp > 1 and abs(target_gain - self.gain) > 1e-4:
            env = np.empty(len(x), dtype=np.float32)
            env[:ramp] = np.linspace(self.gain, target_gain, ramp, dtype=np.float32)
            env[ramp:] = target_gain
            y = x * env
        else:
            y = x * target_gain
        self.gain = target_gain
        return _soft_limit(y).astype(np.float32)


class Session:
    def __init__(self, engine, voice, mode='icl', first_chunk=2, chunk=6, context=25,
                 max_frames=2000, seed=None, sampling=None, level=True):
        if mode not in ('icl', 'xvec'):
            raise ValueError('mode must be icl or xvec')
        self.e, self.v, self.mode = engine, voice, mode
        self.first_chunk, self.chunk, self.context = first_chunk, chunk, context
        self.max_frames = max_frames
        self.sampling = dict(DEFAULT_SAMPLING, **(sampling or {}))
        self.seed = seed
        self.gap, self.forced_gap = 0, None  # forced_gap: layout tests of experimental PAD-gap layout only
        self.normalizer = IncrementalNormalizer()
        self.target_ids, self.ended, self.cancelled = [], False, False
        self.cv = threading.Condition()
        self.out = queue.Queue()
        self.stats = Stats()
        self.leveler = Leveler(engine.sample_rate) if level else None
        self.thread = None

    # ------------------------------------------------------------ text side
    def push_text(self, text):
        segments = self.normalizer.push(text)
        self._append(segments)

    def end(self):
        self._append(self.normalizer.flush(), end=True)

    def _append(self, segments, end=False):
        ids = [t for s in segments for t in self.e.tokenize(s)]
        with self.cv:
            if self.stats.t_first_text is None and (ids or end):
                self.stats.t_first_text = time.perf_counter()
            self.target_ids.extend(ids)
            self.ended = self.ended or end
            self.cv.notify_all()
        if self.thread is None:
            self.thread = threading.Thread(target=self._run, daemon=True)
            self.thread.start()

    def push_ids(self, ids, end=False):
        """Test hook: push already tokenized target ids."""
        with self.cv:
            if self.stats.t_first_text is None:
                self.stats.t_first_text = time.perf_counter()
            self.target_ids.extend(ids)
            self.ended = self.ended or end
            self.cv.notify_all()
        if self.thread is None:
            self.thread = threading.Thread(target=self._run, daemon=True)
            self.thread.start()

    def cancel(self):
        with self.cv:
            self.cancelled = True
            self.cv.notify_all()

    # ------------------------------------------------------------ audio side
    def audio(self):
        while True:
            item = self.out.get()
            if item is None:
                return
            if isinstance(item, Exception):
                raise item
            yield item

    def _wait_for(self, count):
        """Block until `count` target ids exist or text ended; False if cancelled."""
        with self.cv:
            while not self.cancelled and not self.ended and len(self.target_ids) < count:
                self.stats.waits_for_text += 1
                self.cv.wait()
            return not self.cancelled

    def _track_element(self, position):
        offset = len(self.v.ref_ids) + self.gap if self.mode == 'icl' else 0
        index = position - offset  # index into target ids
        if index < 0:
            return self.v.ref_ids[position]
        if not self._wait_for(index + 1):
            return None
        with self.cv:
            if index < len(self.target_ids):
                return self.target_ids[index]
            return EOS if index == len(self.target_ids) else PAD

    @torch.inference_mode()
    def _run(self):
        try:
            self._generate()
        except Exception as error:  # surface to consumer
            self.out.put(error)
        finally:
            self.stats.t_done = time.perf_counter()
            self.out.put(None)

    def _generate(self, forced_frames=None, collect_logits=None):
        e, v, s = self.e, self.v, self.sampling
        if self.seed is not None:
            torch.manual_seed(self.seed)
        n_ref = prefix_positions(self.mode, v.ref_codes)
        # icl: native layout needs about (reference frames - reference tokens) target tokens
        # (or the end of the text) before the first frame; xvec needs one token.
        need = required_target_tokens(self.mode, v.ref_ids, v.ref_codes)
        if not self._wait_for(need):
            self.stats.cancelled = True
            return
        with self.cv:
            ids, ended = list(self.target_ids), self.ended
        self.gap = self.forced_gap or 0
        self.stats.extra['start_tokens'] = len(ids)
        cache = DynamicCache()
        with e.lock:
            prefix, _ = stream_prefix(e.tts, self.mode, v.speaker, e.role_ids, v.ref_ids, v.ref_codes, ids, ended, self.gap)
            logits, past_hidden = e._forward(prefix, cache, 0)
        self.stats.t_prefill = time.perf_counter()
        cur = prefix.shape[0]
        history, frames, emitted = [], [], 0
        for k in range(self.max_frames):
            if self.cancelled:
                self.stats.cancelled = True
                return
            if collect_logits is not None:
                collect_logits.append(logits)
            with e.lock:
                if forced_frames is not None:
                    if k >= len(forced_frames):
                        return
                    frame = forced_frames[k].to(logits.device)
                else:
                    token = _sample(logits, history, k, s)
                    if token == EOS_CODE:
                        self.stats.eos = True
                        break
                    history.append(token)
                    frame = e._residuals(torch.tensor(token, device=logits.device), past_hidden, s)
            frames.append(frame)
            ready = len(frames) - emitted
            if forced_frames is None and ready >= (self.first_chunk if emitted == 0 else self.chunk):
                self._emit(frames, emitted, ready)
                emitted = len(frames)
            element = self._track_element(n_ref + k)
            if element is None:
                self.stats.cancelled = True
                return
            with e.lock:
                emb = frame_embeds(e.tts, frame[None]) + e._text_embed(element)
                logits, past_hidden = e._forward(emb, cache, cur)
            cur += 1
        if forced_frames is None and len(frames) > emitted:
            self._emit(frames, emitted, len(frames) - emitted)
        self.stats.frames = len(frames)

    def _emit(self, frames, emitted, new):
        e = self.e
        gen = torch.stack(frames)
        ctx_ref = self.v.ref_codes
        allc = torch.cat([ctx_ref, gen], dim=0)
        start = max(0, allc.shape[0] - new - self.context)
        with e.lock:
            pcm = e._decode(allc[start:], new)
        if self.leveler is not None:
            pcm = self.leveler.process(pcm)
        if self.stats.t_first_audio is None:
            self.stats.t_first_audio = time.perf_counter()
        self.stats.audio_s += len(pcm) / e.sample_rate
        self.out.put(pcm)

    # ------------------------------------------------------------ validation hook
    @torch.inference_mode()
    def teacher_force(self, target_ids, frames, gap=None):
        """Return per-step logits when the given frames are forced (for layout tests)."""
        self.target_ids, self.ended, self.forced_gap = list(target_ids), True, gap
        logits = []
        self._generate(forced_frames=frames, collect_logits=logits)
        return torch.cat(logits)


SENTENCE_END = set('。!?;!?;\n')
CLAUSE_END = set(',,、::')


class SentenceSession:
    """Same interface as Session (push_text / end / cancel / audio / stats), but text is cut
    into sentences and every sentence is generated with its whole text known.

    With mode='icl' this removes icl's start condition (enough text tokens to cover the
    reference): audio starts about 0.1-0.25 s after the first sentence is complete. A worker
    thread generates the sentences one after another as soon as each is complete, independent
    of how fast audio() is consumed, so a consumer that plays in real time hears no gaps.
    A sentence longer than `max_chars` without an end mark is cut at its last comma.
    """

    def __init__(self, engine, voice, max_chars=60, seed=None, **kw):
        self.e, self.v, self.kw, self.seed, self.max_chars = engine, voice, kw, seed, max_chars
        if kw.get('mode', 'icl') not in ('icl', 'xvec'):
            raise ValueError('mode must be icl or xvec')
        self.buffer, self.sentences, self.out = '', queue.Queue(), queue.Queue()
        self.cancelled, self.current, self.thread = False, None, None
        self.stats = Stats()
        self.lock = threading.Lock()

    def _start(self):
        if self.thread is None:
            self.thread = threading.Thread(target=self._worker, daemon=True)
            self.thread.start()

    def push_text(self, text):
        with self.lock:
            if self.stats.t_first_text is None and text:
                self.stats.t_first_text = time.perf_counter()
            self.buffer += text
            while True:
                cut = next((i + 1 for i, c in enumerate(self.buffer) if c in SENTENCE_END), 0)
                if not cut and len(self.buffer) > self.max_chars:
                    cut = max((i + 1 for i, c in enumerate(self.buffer) if c in CLAUSE_END), default=len(self.buffer))
                if not cut:
                    break
                sentence, self.buffer = self.buffer[:cut], self.buffer[cut:]
                if sentence.strip():
                    self.sentences.put(sentence)
            self._start()

    def end(self):
        with self.lock:
            if self.stats.t_first_text is None:
                self.stats.t_first_text = time.perf_counter()
            if self.buffer.strip():
                self.sentences.put(self.buffer)
            self.buffer = ''
            self.sentences.put(None)
            self._start()

    def cancel(self):
        self.cancelled = True
        current = self.current
        if current is not None:
            current.cancel()
        self.sentences.put(None)

    def _worker(self):
        st, n, eos = self.stats, 0, True
        leveler = Leveler(self.e.sample_rate)
        try:
            while not self.cancelled:
                sentence = self.sentences.get()
                if sentence is None or self.cancelled:
                    break
                seed = None if self.seed is None else self.seed + n
                leveler.on_sentence_start()
                self.current = Session(self.e, self.v, seed=seed, level=False, **self.kw)
                self.current.push_text(sentence)
                self.current.end()
                for pcm in self.current.audio():
                    pcm = leveler.process(pcm)
                    if st.t_first_audio is None:
                        st.t_first_audio = time.perf_counter()
                        st.t_prefill = self.current.stats.t_prefill
                    st.audio_s += len(pcm) / self.e.sample_rate
                    self.out.put(pcm)
                st.frames += self.current.stats.frames
                eos = eos and self.current.stats.eos
                n += 1
        except Exception as error:
            self.out.put(error)
        finally:
            st.eos, st.cancelled = eos and not self.cancelled, self.cancelled
            st.extra['sentences'] = n
            st.t_done = time.perf_counter()
            self.out.put(None)

    def audio(self):
        while True:
            item = self.out.get()
            if item is None:
                return
            if isinstance(item, Exception):
                raise item
            yield item


class SpeedSession:
    """Wraps a Session/SentenceSession and changes the speaking rate of its audio (WSOLA)."""

    def __init__(self, inner, speed, sample_rate):
        from speed import TimeStretch
        self.inner, self.ts = inner, TimeStretch(speed, sample_rate)
        self.stats = inner.stats
        self.stats.extra['speed'] = speed

    def push_text(self, text):
        self.inner.push_text(text)

    def end(self):
        self.inner.end()

    def cancel(self):
        self.inner.cancel()

    def audio(self):
        for pcm in self.inner.audio():
            out = self.ts.process(pcm)
            if len(out):
                yield out
        if not self.stats.cancelled:
            tail = self.ts.flush()
            if len(tail):
                yield tail


def synthesize_stream_to_array(engine, voice, text, chars_per_second=None, **kw):
    """Convenience: optionally simulate incremental text, return (audio, sr, stats)."""
    session = engine.session(voice, **kw)

    def feed():
        if chars_per_second:
            for ch in text:
                session.push_text(ch)
                time.sleep(1.0 / chars_per_second)
        else:
            session.push_text(text)
        session.end()
    feeder = threading.Thread(target=feed, daemon=True)
    feeder.start()
    chunks = list(session.audio())
    feeder.join()
    audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
    return audio, engine.sample_rate, session.stats