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.

29.1 KB
Raw Blame
"""A voice's reference clip chosen from many media files of the same speaker."""

from __future__ import annotations

import asyncio
import contextlib
import logging
import math
import shutil
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any

import numpy as np
import soundfile as sf

from .. import aio, components, config, media, reflang, speech
from ..registry import Context, EngineError, method
from . import pace, quality, store
from ._audio import HOP_S, resample, write_wav

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

SR = 44100
GAP_S = 0.4
MAX_POOL_S = 20 * 60.0
DECODE_SLACK_S = 120.0
MAX_FILES = 500
LONG_PAUSE_S, KEEP_PAUSE_S = 0.7, 0.3
MIN_SPEECH_S = 3.0
FADE_S = 0.005

# The speech model uses a clip of up to 12 s whole and cuts longer ones itself.
WIN_LO_S, WIN_HI_S, WIN_FALLBACK_HI_S, WIN_IDEAL_S = 8.0, 12.0, 15.0, 10.0
KEEP_PER_FILE = 12
KEEP_TOTAL = 24
N_SHOW, MAX_SHOW_PER_FILE = 5, 2
# Measured: a clean recording has 40-60 dB here, speech over music 10-30 dB.
AUTO_BACKGROUND_SNR_DB = 35.0
ASR_SR = 16000
LANG_WIN_S = 30.0  # Whisper hears 30 s at a time
LANG_WINDOWS_GPU, LANG_WINDOWS_CPU = 5, 3
LANG_MIN_SHARE = 0.5

_RUNNING: dict[str, str] = {}  # voice id -> job id; loop thread only


class _Skip(Exception):
    """A file that cannot be used; the message is shown to the user."""


def _silent_runs(sil: np.ndarray) -> list[tuple[int, int]]:
    d = np.diff(np.concatenate([[0], sil.astype(np.int8), [0]]))
    return list(zip(np.flatnonzero(d == 1).tolist(), np.flatnonzero(d == -1).tolist()))


def _shorten_pauses(y: np.ndarray, sr: int, m: dict[str, Any]) -> np.ndarray:
    sil = m["_frame_db"] < m["_silence_thr"]
    hop = max(int(sr * HOP_S), 1)
    long_f, half_f = int(LONG_PAUSE_S / HOP_S), int(KEEP_PAUSE_S / 2.0 / HOP_S)
    ramp_n = max(int(sr * FADE_S), 1)
    ramp = np.linspace(0.0, 1.0, ramp_n, dtype=np.float32)
    pieces: list[np.ndarray] = []
    pos = 0
    for a, b in _silent_runs(sil):
        if b - a <= long_f or a == 0 or b >= len(sil):
            continue  # edges keep the padding trim_silence leaves on purpose
        cut_a, cut_b = (a + half_f) * hop, (b - half_f) * hop
        if cut_b - cut_a < ramp_n * 2 or cut_a <= pos:
            continue
        piece = y[pos:cut_a].copy()
        if len(piece) >= ramp_n:
            piece[-ramp_n:] *= ramp[::-1]
        if pieces and len(piece) >= ramp_n:
            piece[:ramp_n] *= ramp
        pieces.append(piece)
        pos = cut_b
    if not pieces:
        return y
    tail = y[pos:].copy()
    if len(tail) >= ramp_n:
        tail[:ramp_n] *= ramp
    pieces.append(tail)
    return np.concatenate(pieces)


def _cut_at_pause(y: np.ndarray, sr: int, m: dict[str, Any], limit_s: float) -> np.ndarray:
    hop = max(int(sr * HOP_S), 1)
    end_f = int(limit_s / HOP_S)
    sil = np.flatnonzero(m["_frame_db"][max(end_f - int(10.0 / HOP_S), 0) : end_f] < m["_silence_thr"])
    end = (max(end_f - int(10.0 / HOP_S), 0) + int(sil[-1])) * hop if sil.size else int(limit_s * sr)
    return store._fade(y[: max(end, sr)], sr)


def _decode(path: Path, room_s: float) -> dict[str, Any]:
    """IO thread. Returns ``{"y", "truncated", "snr_db"}``; raises ``_Skip``."""
    if not path.is_file():
        raise _Skip("file not found")
    limit = room_s + DECODE_SLACK_S
    try:
        y, sr = media.read_audio(path, sr=SR, max_s=limit)
    except EngineError as exc:
        raise _Skip(exc.message.rstrip(".") if exc.message else "cannot be read") from None
    except Exception as exc:
        raise _Skip(f"cannot be read ({type(exc).__name__})") from None
    if len(y) < int(0.5 * sr):
        raise _Skip("no audio")
    truncated = len(y) >= int((limit - 0.5) * sr)
    y = _dc(y)
    return {"y": y, "truncated": truncated, "snr_db": float(quality.measure(y, sr)["snr_db"])}


def _dc(y: np.ndarray) -> np.ndarray:
    return (y - np.float32(np.mean(y, dtype=np.float64))).astype(np.float32, copy=False)


def _finish(y: np.ndarray, truncated: bool, room_s: float, analyse: bool) -> dict[str, Any]:
    """IO thread. Returns ``{"y", "truncated", "clip_pen", "rate", "windows"}``; raises ``_Skip``."""
    sr = SR
    m0 = quality.measure(y, sr)
    if m0["speech_db"] <= -90.0 or m0["snr_db"] < 6.0:
        raise _Skip("no clear speech found")
    clip_pen = pace.CLIP_PENALTY if m0["clipping_pct"] > 0.05 else 0.0
    y = store.trim_silence(y, sr, m0)
    del m0
    m = quality.measure(y, sr)
    if m["snr_db"] >= quality.SNR_BAD_DB:  # in a noisy file quiet syllables pass for silence
        y = _shorten_pauses(y, sr, m)
        m = quality.measure(y, sr)
    if len(y) > room_s * sr:
        y = _cut_at_pause(y, sr, m, room_s)
        truncated = True
        m = quality.measure(y, sr)
    y = store.normalise(y, m)
    del m
    if len(y) < MIN_SPEECH_S * sr:
        raise _Skip(f"less than {MIN_SPEECH_S:g} s of speech")
    if not analyse:
        return {"y": y, "truncated": truncated, "clip_pen": clip_pen, "rate": 0.0, "windows": []}
    an = pace.PartAnalysis(y, sr)
    wins: list[dict[str, Any]] = []
    rate = pace.part_rate(an) if an.ok else 0.0
    if an.ok:
        scored = []
        for a, b in an.windows(WIN_LO_S, WIN_HI_S, WIN_FALLBACK_HI_S, WIN_IDEAL_S):
            mm = an.measure(a, b)
            scored.append({**mm, "score": pace.window_score(mm, rate, 0.0, clip_pen, WIN_IDEAL_S)})
        spoken = [c for c in scored if c["rate"] > 0]  # windows with under 3 s of speech have no rate
        scored = spoken or scored
        scored.sort(key=lambda c: -c["score"])
        wins = _distinct(scored, KEEP_PER_FILE)
    return {"y": y, "truncated": truncated, "clip_pen": clip_pen, "rate": rate, "windows": wins}


async def _clean(
    path: Path,
    room_s: float,
    analyse: bool = True,
    separate: _Separator | None = None,
    on_separate: speech.Progress | None = None,
) -> dict[str, Any]:
    d = await aio.run_io(_decode, path, room_s)
    y, removed = d.pop("y"), False
    if separate is not None and separate.wanted(path, d["snr_db"]):
        vocals = await separate.run(y, on_separate)
        if vocals is not None:
            y, removed = await aio.run_io(_dc, vocals), True
            del vocals
    res = await aio.run_io(_finish, y, d["truncated"], room_s, analyse)
    res["music_removed"] = removed
    return res


class _Separator:
    """Vocal separation in the speech worker; ``mode`` None is "auto". Never fails the job: ``reason`` says why."""

    NOT_INSTALLED = "the music-removal model is not installed (run setup again)"

    def __init__(self, ctx: Context, mode: bool | None, tag: str) -> None:
        from .. import tts

        data = config.data_dir(ctx)
        self.mode = mode
        self.model = speech.separator_path(data.root)
        self.worker = speech.get(ctx.runtime, data.root)
        self.gpu = config.backend(ctx.runtime) == "cuda" and "paused" not in tts.models_status().values()
        self.workdir = data.tmp / f"separate-{tag}"
        self.installed: bool | None = None
        self.failed = False
        self.reason: str | None = "turned off" if mode is False else None
        self.count = 0
        self.device: str | None = None

    def wanted(self, path: Path, snr_db: float) -> bool:
        if self.mode is False or self.failed or self.installed is False:
            return False
        if self.mode is True:
            return True
        if not media.is_video(path) or snr_db >= AUTO_BACKGROUND_SNR_DB:
            return False
        if not self.gpu:
            self.reason = self.reason or "no GPU for it (tick Remove background music to run it on the CPU)"
            return False
        return True

    def summary(self) -> dict[str, Any]:
        if self.count == 0:
            reason = self.reason or "no background sound found under the voice"
        else:
            reason = self.reason if self.failed else None
        return {
            "music_removed": self.count > 0,
            "music_files": self.count,
            "music_reason": reason,
            "music_device": self.device,
        }

    async def run(self, y: np.ndarray, on_progress: speech.Progress | None) -> np.ndarray | None:
        if self.installed is None:
            self.installed = not components.off("music_removal") and await aio.run_io(self.model.is_file)
        if not self.installed:
            self.reason = self.NOT_INSTALLED
            return None
        src = self.workdir / "mix.npy"
        dst = self.workdir / "vocals.npy"
        await aio.run_io(_save_npy, src, y)
        try:
            res = await self.worker.separate_vocals(src, dst, len(y) / SR, on_progress, allow_cuda=self.gpu)
            vocals = await aio.run_io(np.load, dst)
        except speech.SpeechError as exc:
            if exc.code == "model_missing":
                self.installed, self.reason = False, self.NOT_INSTALLED
            else:
                self.failed, self.reason = True, f"music removal failed ({exc.message})"
            log.warning("vocal separation: %s", exc.message)
            return None
        except speech.Cancelled:
            self.reason = "music removal was interrupted"
            return None
        finally:
            await aio.run_io(_remove_many, src, dst)
        self.count += 1
        self.device = str(res.get("device") or "")
        log.info(
            "vocal separation: %.1f s of audio in %.1f s on %s",
            len(y) / SR,
            float(res.get("elapsed_s", 0.0)),
            self.device,
        )
        return vocals

    def close(self) -> None:
        shutil.rmtree(self.workdir, ignore_errors=True)


def _save_npy(path: Path, y: np.ndarray) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    np.save(path, np.ascontiguousarray(y, dtype=np.float32))


def _remove_many(*paths: Path) -> None:
    for p in paths:
        _remove(p)


def _music_mode(params: dict[str, Any]) -> bool | None:
    v = params.get("remove_music", "auto")
    if v is None or v == "auto":
        return None
    if isinstance(v, bool):
        return v
    raise EngineError("bad_request", "'remove_music' must be true, false or \"auto\"")


def _distinct(cands: list[dict[str, Any]], count: int, per_file: int | None = None) -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []
    per: dict[Any, int] = {}
    for c in cands:
        if len(out) >= count:
            break
        if any(pace._overlap(c, o) > pace.MAX_OVERLAP for o in out):
            continue
        f = c.get("file")
        if per_file is not None and per.get(f, 0) >= per_file:
            continue
        out.append(c)
        per[f] = per.get(f, 0) + 1
    return out


def rank(cands: list[dict[str, Any]], median: float) -> list[dict[str, Any]]:
    out = []
    for c in cands:
        m = {k: float(c[k]) for k in ("start_s", "end_s", "duration_s", "rate", "pauses", "snr_db")}
        out.append({**c, "score": pace.window_score(m, median, 0.0, float(c.get("clip_pen", 0.0)), WIN_IDEAL_S)})
    out.sort(key=lambda c: -c["score"])
    return out


def show_candidates(media_meta: dict[str, Any]) -> list[dict[str, Any]]:
    files = len(media_meta.get("files") or [])
    ranked = rank(list(media_meta.get("cands") or []), float(media_meta.get("rate_median") or 0.0))
    return _distinct(ranked, N_SHOW, MAX_SHOW_PER_FILE if files >= 3 else None)


def target_name(code: str | None) -> str:
    return "reference.wav" if not code else f"reference_{code}.wav"


def _drop_sidecar(vdir: str | Path, name: str) -> None:
    (Path(vdir) / name).with_suffix(".omnivoice.json").unlink(missing_ok=True)


def write_target(
    vdir: str | Path, meta: dict[str, Any], start_s: float, end_s: float, code: str | None, info: dict[str, Any]
) -> dict[str, Any]:
    """The caller holds the store lock."""
    clip, sr = store.cut_media(vdir, start_s, end_s)
    name = target_name(code)
    write_wav(Path(vdir) / name, clip, sr)
    _drop_sidecar(vdir, name)
    pool = meta["media"].get("pool") if isinstance(meta.get("media"), dict) else None
    entry = {
        "source": "media",
        "start_s": round(start_s, 3),
        "end_s": round(end_s, 3),
        "duration_s": round(len(clip) / sr, 2),
        "manual": True,
        "pool": pool,
        **info,
    }
    if code is None:
        meta["reference"] = entry
    if isinstance(meta.get("media"), dict):
        meta["media"]["current"] = {"start_s": entry["start_s"], "end_s": entry["end_s"]}
    return entry


def file_at(media_meta: dict[str, Any], start_s: float, end_s: float) -> dict[str, Any] | None:
    best, best_len = None, 0.0
    for f in media_meta.get("files") or []:
        inter = min(end_s, float(f["end_s"])) - max(start_s, float(f["start_s"]))
        if inter > best_len:
            best, best_len = f, inter
    return best


def _language(ctx: Context, vid: str, value: Any) -> str | None:
    from .. import config, voices
    from .reference import _speech_language

    own = str(voices.read_meta(config.data_dir(ctx), vid).get("language") or "en").lower()
    if value in (None, "", "auto"):
        return None
    code = _speech_language(value)
    return None if code == own.split("-")[0] else code


def language_windows(total_s: float, count: int, win_s: float = LANG_WIN_S) -> list[tuple[float, float]]:
    """Up to ``count`` windows of ``win_s`` spread evenly from the pool's start to its end."""
    if total_s <= win_s or count <= 1:
        start = max((total_s - win_s) / 2.0, 0.0)
        return [(round(start, 3), round(min(start + win_s, total_s), 3))]
    n = min(count, math.ceil(total_s / win_s))
    step = (total_s - win_s) / (n - 1)
    return [(round(k * step, 3), round(k * step + win_s, 3)) for k in range(n)]


def vote_language(windows: list[dict[str, Any]]) -> tuple[str | None, float]:
    """(best code, its share): each window's probabilities summed, weighted by the seconds it heard."""
    totals: dict[str, float] = {}
    heard = 0.0
    for w in windows:
        span = max(float(w.get("end", 0.0)) - float(w.get("start", 0.0)), 0.0)
        probs = w.get("probs") or {}
        if span <= 0.0 or not probs:
            continue
        heard += span
        for code, p in probs.items():
            c = reflang.norm(code)
            if c:
                totals[c] = totals.get(c, 0.0) + span * float(p)
    if not totals:
        return None, 0.0
    code, mass = max(totals.items(), key=lambda kv: kv[1])
    return code, mass / heard


def pick_language(windows: list[dict[str, Any]], speakable: Callable[[str], bool]) -> str | None:
    code, share = vote_language(windows)
    if code is None or share < LANG_MIN_SHARE or not speakable(code):
        return None
    return code


def _speakable(code: str) -> bool:
    from .. import backends
    from . import lang

    return code in lang.LANGUAGES or backends.for_language(code) is not None


def _window_audio(pool: np.ndarray, spans: list[tuple[float, float]]) -> tuple[np.ndarray, list[list[float]]]:
    """IO thread. The pool's windows at 16 kHz back to back, and where each one lies in that clip."""
    clips: list[np.ndarray] = []
    local: list[list[float]] = []
    pos = 0
    for a, b in spans:
        y = resample(pool[int(a * SR) : int(b * SR)].astype(np.float32) / 32768.0, SR, ASR_SR)
        clips.append(y)
        local.append([round(pos / ASR_SR, 3), round((pos + len(y)) / ASR_SR, 3)])
        pos += len(y)
    return np.concatenate(clips), local


async def detect_language(ctx: Context, pool: np.ndarray, gpu: bool) -> str | None:
    """The language spoken in ``pool`` (16-bit, ``SR``); None when Whisper is unsure, missing or fails."""
    data = config.data_dir(ctx)
    if len(pool) == 0 or not await aio.run_io(speech.asr_path(data.root).is_file):
        return None
    spans = language_windows(len(pool) / SR, LANG_WINDOWS_GPU if gpu else LANG_WINDOWS_CPU)
    npy = data.tmp / f"language-{time.time_ns():x}.npy"
    try:
        clip, local = await aio.run_io(_window_audio, pool, spans)
        await aio.run_io(_save_npy, npy, clip)
        del clip
        res = await speech.get(ctx.runtime, data.root).detect_language(npy, local, gpu)
    except speech.SpeechError as exc:
        log.warning("language detection: %s", exc.message)
        return None
    except speech.Cancelled:
        log.warning("language detection was interrupted")
        return None
    finally:
        await aio.run_io(_remove, npy)
    windows = list(res.get("windows") or [])
    best, share = vote_language(windows)
    code = pick_language(windows, _speakable)
    log.info("language of %d window(s): %s (%s, %.0f %%)", len(windows), code or "not set", best, share * 100.0)
    return code


def _wants_language(params: dict[str, Any]) -> bool:
    value = params.get("language")
    if value is None:
        return False
    if value == "auto":
        return True
    raise EngineError("bad_request", "'language' must be \"auto\" or left out")


def _paths(params: dict[str, Any]) -> list[Path]:
    paths = params.get("paths")
    if not isinstance(paths, list) or not paths or not all(isinstance(p, str) and p for p in paths):
        raise EngineError("bad_request", "'paths' must be a non-empty list of file paths")
    if len(paths) > MAX_FILES:
        raise EngineError("bad_request", f"at most {MAX_FILES} files at once")
    seen, out = set(), []
    for p in paths:
        a = Path(p).absolute()
        if a not in seen:
            seen.add(a)
            out.append(a)
    return out


@method("voices.reference_from_media")
async def reference_from_media(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    from .. import tts

    vid = params.get("id", params.get("voice_id"))
    vdir = store._voice_dir(ctx, {"voice_id": vid})
    vid = str(vid)
    paths = _paths(params)
    music = _music_mode(params)
    code = await aio.run_io(_language, ctx, vid, params.get("language"))
    if tts.is_busy():
        raise EngineError("busy", tts.busy_message("a generation is running; add media when it has finished"))
    if vid in _RUNNING:
        raise EngineError("busy", "media files are already being combined for this voice")

    async def run(job: str) -> None:
        try:
            await _job(ctx, job, vid, vdir, paths, code, music)
        finally:
            if _RUNNING.get(vid) == job:
                del _RUNNING[vid]

    job = ctx.start_job(run)
    _RUNNING[vid] = job
    return {"job": job, "files": len(paths)}


@method("media.combine")
async def combine(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    from .. import voices

    paths = _paths(params)
    music = _music_mode(params)
    detect = _wants_language(params)
    data = config.data_dir(ctx)
    vid = params.get("voice_id")
    if vid is not None:
        vid = str((await aio.run_io(voices.read_meta, data, str(vid)))["id"])
    sep = _Separator(ctx, music, f"combine-{time.time_ns():x}")
    out_dir = Path(ctx.data_dir) / "tmp" / "combined"
    pieces: list[np.ndarray] = []
    files: list[dict[str, Any]] = []
    skipped: list[dict[str, Any]] = []
    unused: list[str] = []
    gap = np.zeros(int(GAP_S * SR), dtype=np.int16)
    pos = 0
    try:
        for k, path in enumerate(paths):
            room = MAX_POOL_S - pos / SR
            if room < MIN_SPEECH_S:
                unused.extend(p.name for p in paths[k:])
                break
            try:
                res = await _clean(path, room, False, sep)
            except _Skip as exc:
                skipped.append({"name": path.name, "path": path, "reason": str(exc)})
                continue
            if pieces:
                pieces.append(gap)
                pos += len(gap)
            y = res.pop("y")
            pieces.append(np.round(np.clip(y, -1.0, 1.0) * 32767.0).astype(np.int16))
            pos += len(y)
            files.append(
                {
                    "name": path.name,
                    "duration_s": round(len(y) / SR, 2),
                    "truncated": bool(res["truncated"]),
                    "music_removed": bool(res["music_removed"]),
                }
            )
            del y, res
    finally:
        await aio.run_io(sep.close)
    if not files:
        raise EngineError(
            "bad_request",
            "None of the files has usable speech: " + "; ".join(f"{x['name']}: {x['reason']}" for x in skipped),
        )
    pool = await aio.run_io(np.concatenate, pieces)
    pieces.clear()
    out_dir.mkdir(parents=True, exist_ok=True)
    out = out_dir / f"combined-{time.strftime('%Y%m%d-%H%M%S')}-{len(files)}files.wav"
    await aio.run_io(_write_pool, out, [pool])
    language, adopted = None, False
    if detect and not (vid and await aio.run_io(voices.has_recordings, data, vid)):
        language = await detect_language(ctx, pool, sep.gpu)
        if language and vid:
            adopted = await aio.run_io(voices.adopt_language, data, vid, language)
    del pool
    log.info(
        "media.combine: %d file(s) -> %s (%.1f s), %d skipped, music removed from %d",
        len(files),
        out,
        pos / SR,
        len(skipped),
        sep.count,
    )
    return {
        "path": out,
        "duration_s": round(pos / SR, 2),
        "files": files,
        "skipped": skipped,
        "unused": unused,
        "language": language,
        "language_set": adopted,
        **sep.summary(),
    }


@method("voices.media_cancel")
async def media_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 {}


@method("voices.clear_media")
async def clear_media(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    vid = params.get("id", params.get("voice_id"))
    vdir = store._voice_dir(ctx, {"voice_id": vid})
    if str(vid) in _RUNNING:
        raise EngineError("busy", "media files are being combined for this voice")

    def clear() -> None:
        with store._LOCK:
            meta = store._load_meta(vdir)
            if meta.pop("media", None) is not None:
                store._save_meta(vdir, meta)
            (vdir / store.MEDIA_POOL).unlink(missing_ok=True)

    await aio.run_io(clear)
    return {}


async def _job(
    ctx: Context, job: str, vid: str, vdir: Path, paths: list[Path], code: str | None, music: bool | None
) -> None:
    from .. import tts

    n = len(paths)
    t0 = time.time()

    def progress(stage: str, pct: float, k: int | None = None) -> None:
        data: dict[str, Any] = {"id": vid, "stage": stage, "pct": round(min(max(pct, 0.0), 100.0), 1), "files": n}
        if k is not None:
            data.update(file=k + 1, name=paths[k].name)
        ctx.emit("voices.media.progress", data, job=job)

    pieces: list[np.ndarray] = []
    files: list[dict[str, Any]] = []
    skipped: list[dict[str, Any]] = []
    unused: list[str] = []
    cands: list[dict[str, Any]] = []
    rates: list[float] = []
    pos = 0
    gap = np.zeros(int(GAP_S * SR), dtype=np.int16)
    tmp = vdir / f"{store.MEDIA_POOL}.{job}.tmp.wav"
    sep = _Separator(ctx, music, job)

    def separating(k: int) -> speech.Progress:
        def cb(stage: str, pct: float) -> None:
            sub = 0.1 * pct if stage == "load_model" else 10.0 + 0.9 * pct
            progress("separate", 85.0 * (k + 0.1 + 0.8 * sub / 100.0) / n, k)

        return cb

    try:
        for k, path in enumerate(paths):
            room = MAX_POOL_S - pos / SR
            if room < MIN_SPEECH_S:
                unused.extend(p.name for p in paths[k:])
                break
            progress("decode", 85.0 * k / n, k)
            try:
                res = await _clean(path, room, True, sep, separating(k))
            except _Skip as exc:
                skipped.append({"name": path.name, "path": path, "reason": str(exc)})
                continue
            if pieces:
                pieces.append(gap)
                pos += len(gap)
            y = res.pop("y")
            off = pos / SR
            pieces.append(np.round(np.clip(y, -1.0, 1.0) * 32767.0).astype(np.int16))
            pos += len(y)
            entry = {
                "index": k + 1,
                "name": path.name,
                "start_s": round(off, 3),
                "end_s": round(pos / SR, 3),
                "truncated": bool(res["truncated"]),
                "music_removed": bool(res["music_removed"]),
            }
            files.append(entry)
            if res["rate"] > 0:
                rates.append(float(res["rate"]))
            cands.extend(
                {
                    "file": k + 1,
                    "start_s": round(off + w["start_s"], 3),
                    "end_s": round(off + w["end_s"], 3),
                    "duration_s": round(w["duration_s"], 3),
                    "rate": round(w["rate"], 3),
                    "pauses": round(w["pauses"], 3),
                    "snr_db": round(w["snr_db"], 2),
                    "clip_pen": res["clip_pen"],
                }
                for w in res["windows"]
            )
            del y, res
        if not files:
            ctx.emit(
                "voices.media.error",
                {
                    "code": "bad_request",
                    "message": "None of the files has usable speech.",
                    "skipped": skipped,
                    **sep.summary(),
                },
                job=job,
            )
            return
        progress("combine", 88.0)
        await aio.run_io(_write_pool, tmp, pieces)
        pieces.clear()
        progress("analyse", 94.0)
        median = float(np.median(rates)) if rates else 0.0
        ranked = rank(cands, median)
        keep = _distinct(ranked, KEEP_TOTAL)
        best = keep[0] if keep else None
        busy = tts.is_busy()  # on the loop thread: a generation that started meanwhile keeps its reference
        progress("apply", 97.0)
        media_meta = {
            "version": 1,
            "pool": f"{int(time.time() * 1000):x}",
            "created": time.strftime("%Y-%m-%dT%H:%M:%S"),
            "language": code,
            "duration_s": round(pos / SR, 2),
            "files": files,
            "skipped": skipped,
            "unused": unused,
            "rate_median": round(median, 3),
            "cands": keep,
            "current": None,
            "music_removed": sep.count,
        }
        install = asyncio.ensure_future(aio.run_io(_install, vdir, tmp, media_meta, None if busy else best, code))
        try:
            ref = await asyncio.shield(install)
        except asyncio.CancelledError:
            ref = await install  # already writing: finish, so the pool, meta and reference stay consistent
    except asyncio.CancelledError:
        ctx.emit("voices.media.error", {"code": "cancelled", "message": "cancelled"}, job=job)
        _remove(tmp)
        return
    except EngineError as exc:
        ctx.emit("voices.media.error", {"code": exc.code, "message": exc.message}, job=job)
        _remove(tmp)
        return
    except Exception as exc:
        log.exception("media reference job %s failed", job)
        ctx.emit("voices.media.error", {"code": "internal", "message": f"{type(exc).__name__}: {exc}"}, job=job)
        _remove(tmp)
        return
    finally:
        sep.close()

    warming = False
    if ref is not None:
        tts.forget_reference()
        if code is None:
            with contextlib.suppress(EngineError):
                warming = bool((await tts.voices_warm(ctx, {"id": vid})).get("warming"))
    message = None
    if best is None:
        message = "No clip of 8-12 s with steady speech was found in these files."
    elif busy:
        message = "A generation was running, so the reference was not changed. Pick a clip from the list."
    elif unused:
        message = f"The 20-minute limit was reached; {len(unused)} file(s) were not used."
    ctx.emit(
        "voices.media.done",
        {
            "id": vid,
            "files": len(files),
            "duration_s": round(pos / SR, 2),
            "language": code,
            "target": target_name(code),
            "applied": ref is not None,
            "reference": ref,
            "warming": warming,
            "preview_path": vdir / target_name(code) if ref is not None else None,
            "skipped": skipped,
            "unused": unused,
            "truncated": [f["name"] for f in files if f["truncated"]],
            "message": message,
            "elapsed_s": round(time.time() - t0, 1),
            **sep.summary(),
        },
        job=job,
    )


def _write_pool(tmp: Path, pieces: list[np.ndarray]) -> None:
    sf.write(tmp, np.concatenate(pieces) if len(pieces) > 1 else pieces[0], SR, subtype="PCM_16", format="WAV")


def _remove(path: Path) -> None:
    with contextlib.suppress(OSError):
        path.unlink()


def _install(
    vdir: Path, tmp: Path, media_meta: dict[str, Any], best: dict[str, Any] | None, code: str | None
) -> dict[str, Any] | None:
    with store._LOCK:
        tmp.replace(vdir / store.MEDIA_POOL)
        meta = store._load_meta(vdir)
        meta["media"] = media_meta
        ref = None
        if best is not None:
            f = file_at(media_meta, best["start_s"], best["end_s"]) or {}
            info = {
                "file": f.get("index"),
                "title": f.get("name"),
                "rate": best["rate"],
                "pauses": best["pauses"],
                "snr_db": best["snr_db"],
            }
            ref = write_target(vdir, meta, float(best["start_s"]), float(best["end_s"]), code, info)
        store._save_meta(vdir, meta)
        return ref