Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

39.5 KB
Raw Blame
from __future__ import annotations

import asyncio
import contextlib
import logging
import os
import re
import shutil
import time
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from pathlib import Path
from typing import Any

import numpy as np

from . import accent, aio, backends, components, config, media, reflang, results, rvc, speech, voices, zsvc
from . import audio_util as au
from .backends import SynthParams, names
from .backends.holos import HOLOS
from .backends.omnivoice import OMNIVOICE
from .backends.omnivoice import installed as omnivoice_installed
from .registry import Context, EngineError, method

log = logging.getLogger("mimvox.tts")

SPEED_MIN, SPEED_MAX = 0.8, 1.3
PAUSE_SENTENCE_MS = 200  # silence appended to a chunk that ends mid-paragraph
PAUSE_PARAGRAPH_MS = 480  # ... and at a paragraph end
MIN_FIRST_TOKENS = 6  # the first segment is one sentence unless that is shorter than this
FIRST_TOKENS = 40  # cap for segment 0 (normally just the first sentence, ~13 tokens = ~4 s of speech)
GROWTH = float(os.environ.get("MIMVOX_SEGMENT_GROWTH", "2.5"))  # measured: lowest total time
LATER_TOKENS = 70
MIN_PIECE_WORDS = 3  # a cut sentence never leaves a piece shorter than this many words...
MIN_PIECE_SHARE = 0.3  # ...or than this share of the segment budget
MIN_TAIL_TOKENS = 10  # a paragraph never ends in a segment shorter than this (merged into the previous one)

# Loop-thread state (only the event loop changes it, so no locks).
_RVC_STATUS = ["loading"]
_ACTIVE: list[str | None] = [None]  # the job holding the one generation slot (tts.generate, Redub GPU jobs, books)
_HOLDER: list[str | None] = [None]  # what a busy answer says while that job runs, when it says more than the caller's
_WARMING: set[str] = set()
_SETTLED: asyncio.Event | None = None  # set while no model is "loading"


def speech_status() -> str:
    own = OMNIVOICE.status()
    if own != "missing":
        return own
    others = {b.status() for b in backends.selectable() if b is not OMNIVOICE}
    for state in ("ready", "idle", "loading", "paused"):
        if state in others:
            return "ready" if state == "idle" else state
    return "missing"


def models_status() -> dict[str, str]:
    snap = {"tts": speech_status(), "rvc": _RVC_STATUS[0]}
    why = OMNIVOICE.status_message()
    if why:
        snap["tts_message"] = why
    return snap


def _settled() -> asyncio.Event:
    global _SETTLED
    if _SETTLED is None:
        _SETTLED = asyncio.Event()
        if "loading" not in models_status().values():
            _SETTLED.set()
    return _SETTLED


def _set_status(ctx: Context | None, **kv: str) -> None:
    if "tts" in kv:
        OMNIVOICE.set_status(kv["tts"])
    if "rvc" in kv:
        _RVC_STATUS[0] = kv["rvc"]
    snap = models_status()
    ev = _settled()
    if "loading" in snap.values():
        ev.clear()
    else:
        ev.set()
    if ctx is not None:
        ctx.emit("models", snap)


async def wait_settled(timeout: float) -> bool:
    """Until no model is ``loading``; False after ``timeout`` seconds."""
    try:
        await asyncio.wait_for(_settled().wait(), timeout)
        return True
    except TimeoutError:
        return False


_ABBREV = {
    "mr",
    "mrs",
    "ms",
    "dr",
    "prof",
    "sr",
    "jr",
    "st",
    "vs",
    "etc",
    "e.g",
    "i.e",
    "no",
    "inc",
    "ltd",
    "mt",
    "gen",
    "col",
    "lt",
    "capt",
    "sgt",
    "fig",
    "approx",
}
_SENT_END = re.compile(r"""([.!?…]+["'”’»)\]]*)\s+""")
_CLAUSE = re.compile(r"(?<=[,;:—–])\s+")


def _split_sentences(par: str) -> list[str]:
    out, start = [], 0
    for m in _SENT_END.finditer(par):
        head = par[start : m.start()] + m.group(1)
        last = re.findall(r"[A-Za-z.]+$", par[start : m.start()])
        word = last[0].lower().rstrip(".") if last else ""
        if m.group(1).startswith(".") and (word in _ABBREV or (len(word) == 1 and word.isalpha())):
            continue  # "Dr. Smith", "J. Smith", "e.g. this"
        out.append(head.strip())
        start = m.end()
    tail = par[start:].strip()
    if tail:
        out.append(tail)
    return out


def segment_text(text: str, count: Callable[[str], int], fixed: int | None = None) -> list[tuple[str, int]]:
    """``(segment, pause_after_ms)`` pairs. The first segment is one sentence so the first audio arrives fast; ``fixed``
    (narration) packs every segment up to ``fixed`` tokens, with no streaming schedule."""
    cap = fixed or LATER_TOKENS
    paragraphs = [re.sub(r"\s+", " ", p).strip() for p in re.split(r"\n\s*\n|\r\n\s*\r\n|\n", text)]
    paragraphs = [p for p in paragraphs if p]
    segs: list[tuple[str, int]] = []

    target = [fixed or FIRST_TOKENS]

    def budget() -> int:
        """Each segment may hold ~GROWTH x the previous target (2.5 measured best), so playing a chunk covers generating
        the next (generation runs at ~1.05-1.4x real time)."""
        return target[0]

    def add(seg: str, pause: int) -> None:
        if fixed is not None:
            pass
        elif not segs:
            target[0] = min(LATER_TOKENS, max(count(seg) + 6, round(count(seg) * GROWTH)))
        else:
            target[0] = min(LATER_TOKENS, max(target[0] + 6, round(target[0] * GROWTH)))
        segs.append((seg, pause))

    def words_split(words: list[str], parts: int) -> list[str]:
        """About equal runs, never an empty or one-word run when avoidable."""
        goal = count(" ".join(words)) / max(parts, 1)
        out: list[str] = []
        cur: list[str] = []
        for i, w in enumerate(words):
            left = len(words) - i  # words not placed yet, this one included
            if cur and len(out) < parts - 1 and left >= 2 and count(" ".join([*cur, w])) > goal:
                carry: list[str] = []
                # A run never ends on a preposition, conjunction or article ("з", "the"): it belongs with the next word.
                while len(cur) > 1 and len(cur[-1].strip("\"'«»()")) <= 3 and not re.search(r"[,.;:!?…—–]$", cur[-1]):
                    carry.insert(0, cur.pop())
                out.append(" ".join(cur))
                cur = [*carry, w]
            else:
                cur.append(w)
        out.append(" ".join(cur))
        return out

    def short(piece: str, limit: int) -> bool:
        return len(piece.split()) < MIN_PIECE_WORDS or count(piece) < limit * MIN_PIECE_SHARE

    def balanced(parts: list[str], limit: int) -> list[str]:
        """Fewest pieces of at most ``limit`` tokens, cut at the clause boundaries that make them most even."""
        n = len(parts)
        cost = [[count(" ".join(parts[i:j])) if j > i else 0 for j in range(n + 1)] for i in range(n + 1)]
        inf = float("inf")
        best: list[list[float]] = [[inf] * (n + 1)]  # best[g][j]: the smallest largest piece of parts[:j] in g pieces
        best[0][0] = 0
        cut: list[list[int]] = [[0] * (n + 1)]
        for g in range(1, n + 1):
            row, back = [inf] * (n + 1), [0] * (n + 1)
            for j in range(1, n + 1):
                for i in range(j):
                    if best[g - 1][i] < inf and cost[i][j] <= limit:
                        v = max(best[g - 1][i], cost[i][j])
                        if v < row[j]:
                            row[j], back[j] = v, i
            best.append(row)
            cut.append(back)
            if row[n] < inf:
                pieces_, j = [], n
                for gg in range(g, 0, -1):
                    i = cut[gg][j]
                    pieces_.insert(0, " ".join(parts[i:j]))
                    j = i
                return pieces_
        return parts  # (each part fits by construction; unreachable)

    def pieces(sentence: str, limit: int) -> list[str]:
        """At clause punctuation first, a clause over LATER_TOKENS into equal runs of words; no piece is left as a stub
        (a last word or two on its own)."""
        if count(sentence) <= limit:
            return [sentence]
        out: list[str] = []
        for clause in _CLAUSE.split(sentence):
            n = -(-count(clause) // cap)
            out.extend([clause] if n <= 1 else words_split(clause.split(" "), n))
        if fixed is not None:
            return balanced(out, limit)
        merged: list[str] = []
        for p in out:
            if merged and count(merged[-1] + " " + p) <= limit:
                merged[-1] += " " + p
            else:
                merged.append(p)
        # stubs: join them to a neighbour when the pair still fits (a little over is fine), else re-cut the pair evenly
        i = 0
        while i < len(merged):
            if len(merged) > 1 and short(merged[i], limit):
                j = i - 1 if i > 0 else i + 1
                a, b = (merged[j], merged[i]) if j < i else (merged[i], merged[j])
                pair = f"{a} {b}"
                k = min(i, j)
                if count(pair) <= limit + MIN_TAIL_TOKENS:
                    merged[k : k + 2] = [pair]
                else:
                    merged[k : k + 2] = words_split(pair.split(" "), 2)
                    i = k + 2
                    continue
                i = max(k, 0)
                continue
            i += 1
        return merged

    for par in paragraphs:
        cur = ""
        par_start = len(segs)
        for sent in _split_sentences(par):
            if fixed is None and not segs and cur and count(cur) >= MIN_FIRST_TOKENS:  # segment 0: the first sentence
                add(cur, PAUSE_SENTENCE_MS)
                cur = ""
            for piece in pieces(sent, budget()):
                if not cur:
                    cur = piece
                elif (fixed is None and not segs and count(cur) >= MIN_FIRST_TOKENS) or count(
                    cur + " " + piece
                ) > budget():
                    add(cur, PAUSE_SENTENCE_MS)
                    cur = piece
                else:
                    cur = f"{cur} {piece}"
        if cur:
            if (
                len(segs) > max(par_start, 1)
                and count(cur) < MIN_TAIL_TOKENS
                and count(segs[-1][0]) + count(cur) <= cap + MIN_TAIL_TOKENS
            ):
                cur = f"{segs.pop()[0]} {cur}"  # no tiny trailing segment: its fixed cost is not worth it
            add(cur, PAUSE_PARAGRAPH_MS)
    return segs


def _pick_warm_voice(data: config.DataDir) -> tuple[Path | None, str | None]:
    """(reference path, voice id with an RVC model) to warm with: prefer a trained voice."""
    ref_only = None
    for vid in voices.list_voice_ids(data):
        ref = data.reference(vid)
        if not ref.is_file():
            continue
        if data.rvc_model(vid)[0].is_file():
            return ref, vid
        ref_only = ref_only or ref
    return ref_only, None


async def load_models(ctx: Context) -> None:
    """The RVC worker starts only when a trained voice is warmed or used: a voice without a model never pays for it
    (6.5 GB of commit, 3 GB of RAM). The ``models`` event says ``ready`` after the warm-up, which is skipped on the
    CPU: there it takes minutes, and a request sent meanwhile would wait behind it."""
    data = config.data_dir(ctx)
    errors: dict[str, str] = {}
    worker = rvc.get(ctx.runtime)
    _set_status(ctx, tts="loading", rvc="loading")

    async def do_tts() -> None:
        try:
            await OMNIVOICE.load(ctx.runtime)
            if OMNIVOICE.status() == "missing" and omnivoice_installed(ctx.runtime):
                errors["tts"] = "OmniVoice failed to load (see the log); run setup"
            elif OMNIVOICE.status() == "no_memory":
                errors["tts"] = OMNIVOICE.status_message() or "not enough memory (RAM)"
        except Exception as exc:
            log.exception("the speech model failed to load")
            errors["tts"] = f"{type(exc).__name__}: {exc}"

    async def do_rvc() -> None:
        if worker is None:
            errors["rvc"] = "voice training is turned off" if components.off("training") else "RVC runtime not found"

    async def do_others() -> None:
        for b in backends.all_backends():
            if b is not OMNIVOICE:
                try:
                    await b.load(ctx.runtime)
                except Exception:
                    log.exception("TTS backend %s failed to load", b.name)

    t0 = time.time()
    await asyncio.gather(do_tts(), do_rvc(), do_others())
    if aio.closing():
        log.info("model loading stopped: the engine is shutting down")
        return
    tts_state = "ready" if "tts" not in errors else "no_memory" if OMNIVOICE.status() == "no_memory" else "missing"
    if OMNIVOICE.status() == "missing" and speech_status() == "missing" and "tts" not in errors:
        errors["tts"] = "no voice-cloning model is installed; run setup"
    if tts_state == "ready" and OMNIVOICE.status() != "missing" and not OMNIVOICE.on_cpu():
        await _warm_up(data)
    if aio.closing():
        return
    _set_status(ctx, tts=tts_state, rvc="ready" if "rvc" not in errors and worker is not None else "missing")
    log.info("models ready in %.1fs: %s", time.time() - t0, models_status())
    if errors:
        log.warning("model start-up problems: %s", errors)
    aio.spawn(aio.run_io(_prewarm_redub), name="redub-prewarm")


async def _warm_up(data: config.DataDir) -> None:
    warm_dir = data.tmp / "_warm"
    try:
        ref, trained_voice = await aio.run_io(_pick_warm_voice, data)
        if ref is None:  # without any voice there is nothing to clone yet: the first generation warms up
            return
        await aio.run_io(warm_dir.mkdir, parents=True, exist_ok=True)
        t1 = time.time()
        lang = await aio.run_io(_voice_language, data, trained_voice) if trained_voice else "en"
        await OMNIVOICE.synthesize(
            _WARM_TEXT.get(lang, _WARM_TEXT["en"]),
            lang,
            ref,
            SynthParams(out_path=warm_dir / "warm_tts.wav", first=True),
        )
        log.info("speech model warm-up %.1fs", time.time() - t1)
    except EngineError as exc:
        log.warning("speech model warm-up skipped: %s", exc.message)
    except Exception:
        log.exception("speech model warm-up failed")
    finally:
        await aio.run_io(shutil.rmtree, warm_dir, ignore_errors=True)


def _prewarm_redub() -> None:
    """Librosa's first call compiles numba kernels (measured ~20 s in the middle of the first dub) and the ffmpeg filter
    list is read once: pay both after start-up."""
    try:
        import librosa

        t0 = time.time()
        y = (0.1 * np.sin(np.arange(22050) * 0.05)).astype(np.float32)
        librosa.effects.trim(y, top_db=40, frame_length=512, hop_length=128)
        log.info("librosa warmed up in %.1fs", time.time() - t0)
    except Exception:
        log.exception("librosa warm-up failed")
    try:
        log.info("redub time-stretch: %s", ", ".join(media.stretch_filters()) or "none (long clips overrun)")
    except Exception:
        log.exception("listing the ffmpeg filters failed")


_WARM_TEXT = {"en": "Warming up the voice engine.", "uk": "Розігріваю голосовий рушій."}


def _voice_language(data: config.DataDir, voice_id: str) -> str:
    try:
        return str(voices.read_meta(data, voice_id).get("language") or "en").lower()
    except EngineError:
        return "en"


def duration_factor_for(speed: float) -> float:
    """Length of the speech relative to natural (below 1 is faster)."""
    return round(1.0 / min(SPEED_MAX, max(SPEED_MIN, float(speed))), 4)


def _num(params: dict[str, Any], key: str, default: float, lo: float, hi: float) -> float:
    v = params.get(key, default)
    if v is None:
        v = default
    if isinstance(v, bool) or not isinstance(v, (int, float)):
        raise EngineError("bad_request", f"'{key}' must be a number")
    return min(hi, max(lo, float(v)))


def speech_language(params: dict[str, Any], key: str = "language") -> tuple[str, backends.TtsBackend]:
    lang = params.get(key) or "en"
    if not isinstance(lang, str):
        raise EngineError("bad_request", f"'{key}' must be a language code such as \"en\"")
    lang = lang.lower()
    exact = params.get("exact_stress", True)
    if not isinstance(exact, bool):
        raise EngineError("bad_request", "'exact_stress' must be true or false")
    model = params.get("model") or "auto"
    if model == "omnivoice" and exact:
        # OmniVoice with exact stress: Ukrainian is read by HolosTTS, as with "auto"; it fell back to OmniVoice before.
        holos = backends.by_name("holos")
        if holos is not None and lang in holos.languages and holos.available():
            return lang, holos
    if model != "auto":
        return lang, named_model(model, lang)
    backend = backends.for_language(lang, skip=() if exact else ("holos",))
    if backend is None:
        raise EngineError(
            "bad_request", f"no voice model speaks {lang!r} (available: {', '.join(sorted(backends.languages()))})"
        )
    return lang, backend


def named_model(model: Any, lang: str) -> backends.TtsBackend:
    backend = backends.by_name(model) if isinstance(model, str) else None
    if backend is None or backend.name == "holos":
        raise EngineError(
            "bad_request",
            f"'model' must be \"auto\" or one of: "
            f"{', '.join(b.name for b in backends.all_backends() if b.name != 'holos')}",
        )
    if backend.status() == "missing":
        raise EngineError("not_ready", f"{backend.label} is not installed (add it in Settings or run setup)")
    if lang not in backend.languages:
        raise EngineError("bad_request", f"{backend.label} does not speak {names.name(lang)} ({lang!r})")
    return backend


def check_backend_ready(backend: backends.TtsBackend) -> None:
    _check_state(backend.status(), backend.status_message())


def check_speech_ready() -> None:
    _check_state(speech_status(), OMNIVOICE.status_message())


def _check_state(state: str, message: str | None) -> None:
    if state == "no_memory":
        raise EngineError("no_memory", message or "not enough memory (RAM) for speech")
    if state not in ("ready", "idle"):
        raise EngineError(
            "not_ready",
            "the speech model is still loading"
            if state == "loading"
            else "speech is paused while a voice trains"
            if state == "paused"
            else "the speech model is not available",
        )


@method("text.stress")
async def text_stress(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    """Ukrainian text with HolosTTS's word stress (U+0301 after each stressed vowel) and the words of two or more
    syllables left without one. ``not_ready`` without the Ukrainian speech component."""
    text = params.get("text")
    if not isinstance(text, str) or not text.strip():
        raise EngineError("bad_request", "'text' is required")
    if len(text) > 200_000:
        raise EngineError("bad_request", "text.stress takes at most 200,000 characters at a time")
    if not HOLOS.available():
        raise EngineError("not_ready", "Ukrainian speech (HolosTTS) is not installed or not loaded")
    res = await HOLOS.stress(text)
    return {"stressed": res.get("stressed", ""), "unsure": res.get("unsure", [])}


@method("tts.generate")
async def tts_generate(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    data = config.data_dir(ctx)
    text = params.get("text")
    if not isinstance(text, str) or not text.strip():
        raise EngineError("bad_request", "'text' must be a non-empty string")
    voice_id = str(params.get("voice_id") or "")
    temperature = _num(params, "expressiveness", 0.8, 0.1, 1.5)
    index_rate = _num(params, "voice_match", 1.0, 0.0, 1.0)
    speed = _num(params, "speed", 1.0, SPEED_MIN, SPEED_MAX)
    quality = params.get("quality") or "best"
    if quality not in ("best", "fast"):
        raise EngineError("bad_request", '\'quality\' must be "best" or "fast"')
    lang, backend = speech_language(params)
    requested, native_voice = accent.parse(params), accent.parse_voice(params)
    check_backend_ready(backend)
    meta = await aio.run_io(voices.read_meta, data, voice_id)  # not_found
    out_fmt = await aio.run_io(media.output_format, params)
    rvc_rate = rvc.index_rate_for(index_rate, lang, meta.get("language"))  # capped for foreign languages
    ref = data.reference(voice_id)
    pth, idx = data.rvc_model(voice_id)
    has_ref, has_pth = await aio.run_io(lambda: (ref.is_file(), pth.is_file()))
    if not has_ref:
        raise EngineError("not_found", "this voice has no recording yet (reference.wav is missing)")
    use_rvc = has_pth and index_rate > 0
    worker = rvc.get(ctx.runtime) if use_rvc else None
    if use_rvc and (worker is None or models_status()["rvc"] != "ready"):
        raise EngineError("not_ready", "the voice-conversion model is not ready")
    zs_worker = await aio.run_io(zsvc.get, ctx.runtime, data.root) if requested == "native-us" else None
    # native-us: RVC for a trained voice, else the zero-shot converter; without either the voice's own reference
    choice = accent.choose(requested, native_voice, lang, has_pth, index_rate, zs_worker is not None)
    zs = zero_shot(ctx, choice, zs_worker, ref, quality)
    # The clip that will speak and its real language (a foreign one carries its accent into `lang`).
    ref_fields = await aio.run_io(reflang.fields, ref, lang, choice.accent == "native-us")
    segs = segment_text(text, backend.count_tokens)
    if not segs:
        raise EngineError("bad_request", "nothing to say in this text")
    # (no await between the busy check in start_exclusive and taking the slot: the loop makes it atomic)
    about = {
        "kind": "speak",
        "voice_id": voice_id,
        "voice_name": str(meta.get("name") or voice_id),
        "text": text,
        "language": lang,
    }
    job = start_exclusive(
        ctx,
        lambda j: _generate(
            ctx,
            j,
            data,
            backend,
            lang,
            ref,
            segs,
            temperature,
            quality,
            pth,
            idx,
            rvc_rate,
            worker,
            duration_factor_for(speed),
            out_fmt,
            choice,
            index_rate,
            zs,
            about,
        ),
        "another generation is running",
    )
    return {
        "job": job,
        "segments": len(segs),
        "segment_chars": [len(t) for t, _ in segs],
        "model": backend.name,
        **choice.fields(),
        **ref_fields,
    }


def zero_shot(
    ctx: Context, choice: accent.Choice, worker: zsvc.ZsvcWorker | None, ref: str, quality: str = "best"
) -> zsvc.Bound | None:
    """Bound to ``ref`` (the timbre) and the diffusion steps of ``quality``; None when ``choice`` does not use it."""
    if choice.converter != "zero-shot" or worker is None:
        return None
    vram = float((getattr(ctx, "device", None) or {}).get("vram_gb") or 0.0)
    return zsvc.Bound(worker, ref, zsvc.turn_lock(vram), quality)


@method("tts.cancel")
async def tts_cancel(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    job = params.get("job")
    if not isinstance(job, str):
        raise EngineError("bad_request", "'job' is required")
    ctx.cancel(job)
    return {}


def _chunk_from(src: str | Path, i: int, last: bool, pause: int, jobdir: Path) -> tuple[np.ndarray, Path, float, int]:
    """IO thread: the final 44.1 kHz chunk ``i`` from a synthesized or converted WAV (pause appended), on disk, and
    the number of its samples that are speech."""
    x, sr = au.read_mono(src)
    x = au.resample(x, sr, au.OUT_SR)
    spoken = len(x)
    if not last:
        x = np.concatenate([x, au.silence(pause)])
    path = jobdir / f"chunk{i:03d}.wav"
    au.write_wav(path, x, au.OUT_SR)
    for p in (jobdir / f"s{i}_{k}.wav" for k in ("tts", "rvc", "vc")):
        with contextlib.suppress(OSError):
            p.unlink()
    return x, path, au.duration_s(x), spoken


def _timeline(texts: list[str], chunks: list[np.ndarray], spoken: list[int]) -> list[tuple[float, float, str]]:
    """Where each segment's speech sits in the chunks joined end to end."""
    out, at = [], 0
    for text, x, n in zip(texts, chunks, spoken, strict=True):
        out.append((at / au.OUT_SR, (at + n) / au.OUT_SR, text))
        at += len(x)
    return out


async def _generate(
    ctx: Context,
    job: str,
    data: config.DataDir,
    backend: backends.TtsBackend,
    lang: str,
    ref: str | Path,
    segs: list[tuple[str, int]],
    temperature: float,
    quality: str,
    pth: str | Path,
    idx: str | Path,
    index_rate: float,
    worker: rvc.RvcWorker | None,
    duration_factor: float,
    out_fmt: str,
    choice: accent.Choice | None = None,
    voice_match: float = 1.0,
    zs: zsvc.Bound | None = None,
    about: dict[str, Any] | None = None,
) -> None:
    """With a ``native-us`` ``choice`` OmniVoice speaks from the native clip and RVC (or ``zs``, for an untrained voice)
    gives each segment the timbre of ``ref``."""
    t_start = time.time()
    choice = choice or accent.Choice("own")

    def finish(event: str, payload: dict[str, Any]) -> None:
        release_job(job)  # free the slot before the app can see the end of this job (it may start the next one)
        ctx.emit(event, payload, job=job)

    jobdir = data.tmp / job
    try:
        await aio.run_io(_prepare_jobdir, data, jobdir)
        native = await aio.run_io(accent.prepare, choice, ref, voice_match) if choice.accent == "native-us" else None
        if choice.accent == "native-us" and native is None:
            choice = accent.Choice("own", choice.native_voice, "unavailable")
        if native is None and choice.converter == "zero-shot":
            zs = None
        synth_ref, ref_text, pitch = (native.ref.path, native.ref.text, native.pitch) if native else (ref, None, 0)
        if native is not None:
            index_rate = native.index_rate
        await speech.yield_gpu()  # Whisper / NLLB (if warm) leave the GPU to the speech model and RVC
        log.info(
            "job %s: %s (accent %s%s), %d segment(s), RVC index %s pitch %+d: %s",
            job,
            lang,
            choice.accent,
            ", zero-shot conversion" if zs is not None else "",
            len(segs),
            index_rate if worker is not None else "-",
            pitch,
            [s for s, _ in segs],
        )
        turn = zs.turn if zs is not None else None
        chunks: list[np.ndarray | None] = [None] * len(segs)
        spoken = [0] * len(segs)
        todo: asyncio.Queue[tuple[int, str, int] | None] = asyncio.Queue(maxsize=2)
        first_chunk_at: list[float] = []
        last_ready = [0.0]

        async def produce() -> None:
            for i, (seg, pause) in enumerate(segs):
                t0 = time.time()
                async with zsvc.gpu_turn(turn):  # a tight GPU: never at the same time as the converter
                    path = await backend.synthesize(
                        seg,
                        lang,
                        synth_ref,
                        SynthParams(
                            out_path=jobdir / f"s{i}_tts.wav",
                            temperature=temperature,
                            quality=quality,
                            duration_factor=duration_factor,
                            first=(i == 0),
                            reference_text=ref_text,
                        ),
                    )
                log.info("job %s seg %d: %s %.2fs", job, i, backend.name, time.time() - t0)
                await todo.put((i, path, pause))  # waits while two segments are ahead of the consumer
            await todo.put(None)

        async def consume() -> None:
            async for i, path, pause in aio.queue_items(todo):
                src: str | Path = path
                if zs is not None:
                    src = jobdir / f"s{i}_vc.wav"
                    await zs.convert(path, src)
                elif worker is not None:
                    src = jobdir / f"s{i}_rvc.wav"
                    await worker.convert(path, src, pth, idx, index_rate, pitch=pitch)
                last = i == len(segs) - 1
                x, chunk, dur, spoken[i] = await aio.run_io(_chunk_from, src, i, last, pause, jobdir)
                chunks[i] = x
                now = time.time() - t_start
                if not first_chunk_at:
                    first_chunk_at.append(now)
                speech_s = max(spoken[i] / au.OUT_SR, 0.01)
                rtf = (now - last_ready[0]) / speech_s  # wall time since the previous chunk / this chunk's speech
                last_ready[0] = now
                ctx.emit(
                    "tts.chunk",
                    {
                        "index": i,
                        "path": chunk,
                        "duration_s": dur,
                        "segments": len(segs),
                        "ready_s": round(now, 2),
                        "rtf": round(rtf, 2),
                    },
                    job=job,
                )

        await aio.gather_or_cancel(produce(), consume())
        done = [c for c in chunks if c is not None]
        full = np.concatenate(done)
        lines = _timeline([s for s, _ in segs], done, spoken)
        saved = await aio.run_io(media.save_result, data, full, au.OUT_SR, "", out_fmt)
        # Read again: the first synthesis from a new clip has just transcribed it (and detected its language).
        ref_fields = await aio.run_io(reflang.fields, ref, lang, native is not None)
        duration_s, elapsed_s = au.duration_s(full), round(time.time() - t_start, 2)
        await aio.run_io(
            results.record,
            saved,
            {
                **(about or {"kind": "speak"}),
                "accent": choice.accent,
                "duration_s": duration_s,
                "elapsed_s": elapsed_s,
                "segments": results.segments(lines),
            },
        )
        finish(
            "tts.done",
            {
                **saved,
                "duration_s": duration_s,
                "elapsed_s": elapsed_s,
                "model": backend.name,
                **choice.fields(),
                **(native.fields() if native else {}),
                **ref_fields,
            },
        )
        log.info(
            "job %s done in %.1fs (first chunk %.1fs)",
            job,
            time.time() - t_start,
            first_chunk_at[0] if first_chunk_at else -1,
        )
    except asyncio.CancelledError:
        finish("tts.error", {"code": "cancelled", "message": "generation cancelled"})
    except EngineError as exc:
        finish("tts.error", {"code": exc.code, "message": exc.message})
    except Exception as exc:
        log.exception("job %s failed", job)
        finish("tts.error", {"code": "internal", "message": f"{type(exc).__name__}: {exc}"})
    finally:
        release_job(job)


def _prepare_jobdir(data: config.DataDir, jobdir: Path) -> None:
    jobdir.mkdir(parents=True, exist_ok=True)
    _gc_tmp(data)


def start_exclusive(
    ctx: Context,
    fn: Callable[[str], Awaitable[None]],
    busy_message: str = "another generation or Redub job is running",
    holder: str | None = None,
) -> str:
    """Take the one generation slot for ``fn(job)``, which should call :func:`release_job` before its final event. Loop
    thread only (the check-and-take is atomic there). Raises ``busy`` with the holder's text, else ``busy_message``."""
    if _ACTIVE[0] is not None:
        raise EngineError("busy", _HOLDER[0] or busy_message)

    async def body(job: str) -> None:
        try:
            await fn(job)
        finally:
            release_job(job)

    job = ctx.start_job(body)
    _ACTIVE[0] = job
    _HOLDER[0] = holder
    return job


@contextlib.contextmanager
def holding(holder: str, busy_message: str = "another generation or Redub job is running") -> Iterator[None]:
    """The one generation slot for work that is no job (``voices.design``); others are refused with ``holder``. Loop
    thread only, entered with no await before it (the check-and-take is atomic there)."""
    if _ACTIVE[0] is not None:
        raise EngineError("busy", _HOLDER[0] or busy_message)
    token = f"hold-{time.monotonic_ns()}"
    _ACTIVE[0], _HOLDER[0] = token, holder
    try:
        yield
    finally:
        release_job(token)


def release_job(job: str) -> None:
    if _ACTIVE[0] == job:
        _ACTIVE[0] = None
        _HOLDER[0] = None


def is_busy() -> bool:
    return _ACTIVE[0] is not None


def busy_message(default: str) -> str:
    return _HOLDER[0] or default


def _gc_tmp(data: config.DataDir) -> None:
    try:
        for p in data.tmp.iterdir():
            if p.name.startswith("job-") and p.is_dir() and time.time() - p.stat().st_mtime > 3600:
                shutil.rmtree(p, ignore_errors=True)
    except OSError:
        pass


def forget_reference() -> None:
    """Call after ``reference.wav`` was replaced. Callable from any thread."""
    for b in backends.all_backends():
        b.forget_reference()


@method("voices.warm")
async def voices_warm(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    """Precompute a voice's speaker conditioning in the background (called when the user selects a voice)."""
    data = config.data_dir(ctx)
    vid = str(params.get("id") or "")
    requested, native_voice = accent.parse(params), accent.parse_voice(params)
    meta = await aio.run_io(voices.read_meta, data, vid)  # not_found
    lang = str(meta.get("language") or "en").lower()
    ref = data.reference(vid)
    pth, idx = data.rvc_model(vid)
    has_ref, has_pth = await aio.run_io(lambda: (ref.is_file(), pth.is_file()))
    if not has_ref:
        raise EngineError("not_found", "this voice has no recording yet (reference.wav is missing)")
    check_speech_ready()
    if OMNIVOICE.status() == "missing":
        if (await aio.run_io(reflang.detected, ref))[0] is not None:
            return {"warming": False, "reason": "already_warm"}
        if _ACTIVE[0] is not None:
            return {"warming": False, "reason": "busy"}
        if vid not in _WARMING:
            _WARMING.add(vid)
            aio.spawn(_warm(ctx, data, vid, ref, lang, None, pth, idx), name=f"warm-{vid}")
        return {"warming": True}
    worker = rvc.get(ctx.runtime) if has_pth else None
    if worker is not None and (models_status()["rvc"] != "ready" or OMNIVOICE.on_cpu()):
        worker = None
    zs_worker = await aio.run_io(zsvc.get, ctx.runtime, data.root) if requested == "native-us" else None
    choice = accent.choose(requested, native_voice, accent.NATIVE_LANG, worker is not None, 1.0, zs_worker is not None)
    if choice.converter != "zero-shot":
        zs_worker = None
    if choice.accent == "native-us":
        known, native_ref = await aio.run_io(accent.peek_native, ref, native_voice)
        native_warm = (
            known
            and native_ref is not None
            and OMNIVOICE.is_warm(native_ref.path)
            and (zs_worker is None or zs_worker.is_warm(ref))
        )
    else:
        native_warm = True
    if OMNIVOICE.is_warm(ref) and (worker is None or worker.loaded_model == rvc.model_sig(pth)) and native_warm:
        return {"warming": False, "reason": "already_warm"}
    if _ACTIVE[0] is not None:
        return {"warming": False, "reason": "busy"}
    if vid in _WARMING:
        return {"warming": True}
    _WARMING.add(vid)
    aio.spawn(_warm(ctx, data, vid, ref, lang, worker, pth, idx, choice, zs_worker), name=f"warm-{vid}")
    return {"warming": True}


async def _warm(
    ctx: Context,
    data: config.DataDir,
    vid: str,
    ref: str | Path,
    lang: str,
    worker: rvc.RvcWorker | None,
    pth: str | Path,
    idx: str | Path,
    choice: accent.Choice | None = None,
    zs_worker: zsvc.ZsvcWorker | None = None,
) -> None:
    t0 = time.time()
    warm_dir = data.tmp / f"_warm_{vid}"
    try:
        await aio.run_io(warm_dir.mkdir, parents=True, exist_ok=True)
        speak_lang = lang if lang in OMNIVOICE.languages else "en"
        if OMNIVOICE.status() != "missing":
            if OMNIVOICE.on_cpu():  # a sentence takes minutes there: only the prompt, which the first generation needs
                await OMNIVOICE.warm(ref, speak_lang)
            else:
                # The shortest real inference: builds the voice-clone prompt (and, the first time for a clip, its
                # transcript).
                src = await OMNIVOICE.synthesize(
                    _WARM_TEXT.get(lang, _WARM_TEXT["en"]),
                    speak_lang,
                    ref,
                    SynthParams(out_path=warm_dir / "in.wav", first=True),
                )
                if worker is not None:  # load the voice's RVC model and index too (about 16 s cold, 1.7 s warm)
                    await worker.convert(src, warm_dir / "out.wav", pth, idx, 1.0)
        if lang == "uk" and HOLOS.available():  # Ukrainian with exact stress: the voice's style vector (~0.2 s)
            await HOLOS.warm(ref)
        if choice is not None and choice.accent == "native-us":
            # The voice's pitch (pYIN, a few seconds of CPU once per clip) and the native clip's prompt (no Whisper).
            native = await aio.run_io(accent.prepare, choice, ref, 1.0)
            if native is not None:
                await OMNIVOICE.warm(native.ref.path, accent.NATIVE_LANG, native.ref.text)
                if zs_worker is not None:  # an untrained voice: the converter and its prompt of reference.wav
                    await zs_worker.warm(ref)
        # The warm-up above transcribed reference.wav when it spoke from it; otherwise the worker detects its language
        # now (Whisper only).
        ref_lang = await aio.run_io(lambda: reflang.detected(ref)[0])
        if ref_lang is None:
            ref_lang = await OMNIVOICE.inspect(ref)
        ctx.emit(
            "voice.warm",
            {
                "id": vid,
                "ok": True,
                "elapsed_s": round(time.time() - t0, 2),
                "reference_language": reflang.norm(ref_lang),
            },
        )
    except asyncio.CancelledError:
        ctx.emit("voice.warm", {"id": vid, "ok": False, "message": "cancelled"})
    except EngineError as exc:
        log.warning("warm-up of voice %s refused: %s", vid, exc.message)
        ctx.emit("voice.warm", {"id": vid, "ok": False, "message": exc.message})
    except Exception as exc:
        log.exception("warm-up of voice %s failed", vid)
        ctx.emit("voice.warm", {"id": vid, "ok": False, "message": f"{type(exc).__name__}: {exc}"})
    finally:
        _WARMING.discard(vid)
        await aio.run_io(shutil.rmtree, warm_dir, ignore_errors=True)


async def release_gpu(ctx: Context, holder: str | None = None) -> None:
    """Unload the speech models and stop the worker processes for training. Raises ``busy`` during a generation other
    than ``holder``'s; until :func:`reacquire_gpu` finishes, the models report ``paused`` and ``tts.generate`` answers
    ``not_ready``."""
    if _ACTIVE[0] is not None and _ACTIVE[0] != holder:
        raise EngineError("busy", busy_message("a generation is running; wait for it or cancel it before training"))
    _set_status(ctx, tts="paused", rvc="paused")
    for b in backends.all_backends():
        try:
            await b.release()
        except Exception:
            log.exception("TTS backend %s could not release the GPU", b.name)
    await asyncio.gather(rvc.shutdown(), speech.shutdown(), zsvc.shutdown())


def reacquire_gpu(ctx: Context) -> asyncio.Task[None] | None:
    """Reload in the background (about 50 s); a fresh RVC worker reads a freshly trained ``rvc/model.pth``. Not while
    the engine shuts down."""
    if aio.closing():
        return None
    return aio.spawn(load_models(ctx), name="model-reload")


@contextlib.asynccontextmanager
async def gpu_released(ctx: Context) -> AsyncIterator[None]:
    """Release before, reload in the background after (also on error)."""
    await release_gpu(ctx)
    try:
        yield
    finally:
        reacquire_gpu(ctx)