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.

20.6 KB
Raw Blame
from __future__ import annotations

import asyncio
import hashlib
import json
import logging
import shutil
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import numpy as np

from .. import aio, components, config, media, speech
from ..registry import Context, EngineError
from . import langs, subtitles

log = logging.getLogger("mimvox.redub.video")

SR = 44100
SEP_PREFIX = "redub_sep_"  # <data>/tmp/redub_sep_<file key>/{vocals,background}.npy
OUTPUTS = ("video", "audio")

# Container (by the source's extension) -> audio encoders to try, best first: (encoder, options).
_AAC = ("aac", ["-b:a", "192k"])
_OPUS = ("libopus", ["-b:a", "160k"])
_CONTAINERS: dict[str, tuple[tuple[str, list[str]], ...]] = {
    "mp4": (_AAC,),
    "m4v": (_AAC,),
    "mov": (_AAC,),
    "mkv": (_OPUS, _AAC),
    "webm": (_OPUS, ("libvorbis", ["-q:a", "6"])),
    "avi": (("libmp3lame", ["-b:a", "192k"]), _AAC),
}
# Burning the subtitles in re-encodes the picture: encoders best first, per container.
_X264 = ("libx264", ["-crf", "18", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
_OPENH264 = ("libopenh264", ["-b:v", "12M", "-pix_fmt", "yuv420p"])
_MPEG4 = ("mpeg4", ["-q:v", "2"])
HW_QUALITY = 19  # NVENC is no better below CQ 19 here (SSIM 0.965 on noisy 1080p; x264 CRF 18: 0.968)
_VP9 = ("libvpx-vp9", ["-crf", "24", "-b:v", "0", "-deadline", "good", "-cpu-used", "4", "-row-mt", "1"])
_PICTURE: dict[str, tuple[tuple[str, list[str]], ...]] = {
    "mp4": (_X264, _OPENH264, _MPEG4),
    "m4v": (_X264, _OPENH264, _MPEG4),
    "mov": (_X264, _OPENH264, _MPEG4),
    "mkv": (_X264, _OPENH264, _VP9, _MPEG4),
    "webm": (_VP9, ("libvpx", ["-crf", "8", "-b:v", "12M"])),
    "avi": (_X264, _MPEG4),
}
_SUBTITLE_TRACK = {"mp4": "mov_text", "m4v": "mov_text", "mov": "mov_text", "mkv": "ass", "webm": "webvtt"}
_AS_TRACK = "the video has them as a track to turn on in the player."
_NO_LIBASS = f"This ffmpeg build cannot draw subtitles (it has no libass), so they are not in the picture: {_AS_TRACK}"
_NO_SUBTITLES = "This ffmpeg build cannot draw subtitles (it has no libass), and AVI takes no subtitle track."
POSITIONS = ("bottom", "top")
VIDEO_AUDIO_SR = 48000  # the video's audio track is written at the video standard rate
FALLBACK_CONTAINER = "mkv"  # a video in another container (ts, flv, ...) is written as Matroska
_FASTSTART = {"mp4", "m4v", "mov"}

# NLLB codes whose first three letters are not the ISO 639-2 code that containers use for the audio language.
_ISO639_2 = {
    "arb": "ara",
    "pes": "fas",
    "zsm": "msa",
    "swh": "swa",
    "khk": "mon",
    "azj": "aze",
    "lvs": "lav",
    "npi": "nep",
    "uzn": "uzb",
    "als": "sqi",
    "plt": "mlg",
    "pbt": "pus",
    "ydd": "yid",
    "gaz": "orm",
    "quy": "que",
    "ory": "ori",
    "yue": "zho",
    "nob": "nor",
    "est": "est",
}


def file_key(path: str | Path) -> str:
    """(path, mtime, size): the preview and the stems are cached by it."""
    st = Path(path).stat()
    return hashlib.sha1(f"{path}|{st.st_mtime_ns}|{st.st_size}".encode(), usedforsecurity=False).hexdigest()[:16]


def language_tag(code: str | None) -> str | None:
    """``en`` -> ``eng``, or None."""
    nllb = langs.nllb_code(code) if code else None
    if not nllb:
        return None
    three = nllb.split("_")[0]
    return _ISO639_2.get(three, three)


@dataclass
class Output:
    output: str
    keep_background: bool
    has_video: bool
    container: str  # the extension of the video result
    subtitles: bool = False
    subtitle_position: str = "bottom"

    @property
    def video(self) -> bool:
        return self.output == "video"

    @property
    def mixes(self) -> bool:
        """Any video, or a kept background, goes through the mix (loudness, background, limiter)."""
        return self.video or self.keep_background


def options(params: dict[str, Any], path: str | Path) -> Output:
    """Defaults: ``output`` audio, ``keep_background`` true for a video output. Blocking (probes)."""
    out = params.get("output")
    out = "audio" if out in (None, "") else out
    if out not in OUTPUTS:
        raise EngineError("bad_request", '\'output\' must be "video" or "audio"')
    keep = params.get("keep_background")
    if keep is None:
        keep = out == "video"
    if not isinstance(keep, bool):
        raise EngineError("bad_request", "'keep_background' must be true or false")
    has_video = False
    if out == "video" or keep:
        has_video = bool(media.probe(path).get("has_video"))
    if out == "video" and not has_video:
        raise EngineError("bad_request", 'This file has no picture, so there is no video to write: use output "audio".')
    subs = params.get("subtitles", False)
    if not isinstance(subs, bool):
        raise EngineError("bad_request", "'subtitles' must be true or false")
    position = params.get("subtitle_position") or "bottom"
    if position not in POSITIONS:
        raise EngineError("bad_request", '\'subtitle_position\' must be "bottom" or "top"')
    ext = Path(path).suffix.lower().lstrip(".")
    container = ext if ext in _CONTAINERS else FALLBACK_CONTAINER
    return Output(out, keep, has_video, container, subs and out == "video", position)


@dataclass
class Stems:
    """A file split into ``vocals`` and ``background`` (drums + bass + other): float32 ``(channels, n)`` ``.npy``
    files at 44.1 kHz, read memory-mapped."""

    folder: Path
    channels: int
    frames: int
    device: str
    elapsed_s: float  # the separation itself (model load excluded)
    total_s: float  # decode + load + separation
    cached: bool = False  # found ready (a finished preload, or an earlier job)
    wait_s: float = 0.0  # how long the caller waited for them (joining a preload in flight, or separating)

    @property
    def vocals_path(self) -> Path:
        return self.folder / "vocals.npy"

    @property
    def background_path(self) -> Path:
        return self.folder / "background.npy"

    def vocals(self) -> np.ndarray:
        return np.load(self.vocals_path, mmap_mode="r")

    def background(self) -> np.ndarray:
        return np.load(self.background_path, mmap_mode="r")

    def exists(self) -> bool:
        return self.vocals_path.is_file() and self.background_path.is_file()


@dataclass
class _Run:
    task: asyncio.Task[Stems] | None = None
    background: bool = True
    listeners: list[Callable[[str, float], None]] = field(default_factory=list)


_RUNS: dict[str, _Run] = {}  # file key -> separation in flight (loop thread)
_DONE: dict[str, Stems] = {}


def installed(data: config.DataDir) -> bool:
    return not components.off("music_removal") and speech.separator_path(data.root).is_file()


def _decode(path: str | Path, folder: Path) -> tuple[Path, int, int]:
    """``<folder>/mix.npy``: float32 ``(channels, n)`` at 44.1 kHz, at most stereo; returns (path, channels, n)."""
    info = media.probe(path)
    channels = 1 if int(info.get("channels") or 0) == 1 else 2
    y = media.decode_pcm(path, SR, channels=channels)
    folder.mkdir(parents=True, exist_ok=True)
    out = folder / "mix.npy"
    np.save(out, np.ascontiguousarray(y.reshape(channels, -1), dtype=np.float32))
    return out, channels, int(y.shape[-1])


def _drop_others(data: config.DataDir, keep: str) -> None:
    """One cached separation at a time: they are large."""
    try:
        entries = list(data.tmp.iterdir())
    except OSError:
        return
    for entry in entries:
        name = entry.name
        if name.startswith(SEP_PREFIX) and name != SEP_PREFIX + keep and name[len(SEP_PREFIX) :] not in _RUNS:
            shutil.rmtree(entry, ignore_errors=True)
            _DONE.pop(name[len(SEP_PREFIX) :], None)


async def _separate(ctx: Context, data: config.DataDir, path: str | Path, key: str, run: _Run) -> Stems:
    folder = data.tmp / (SEP_PREFIX + key)
    sp = speech.get(ctx.runtime, data.root)
    t0 = time.time()

    def progress(stage: str, pct: float) -> None:
        for cb in list(run.listeners):
            cb(stage, pct)

    try:
        await aio.run_io(_drop_others, data, key)
        mix, channels, frames = await aio.run_io(_decode, path, folder)
        res = await sp.separate_vocals(
            mix,
            folder / "vocals.npy",
            frames / SR,
            progress,
            background_out=folder / "background.npy",
            tag=key if run.background else None,
        )
        await aio.run_io(mix.unlink)
        stems = Stems(
            folder,
            channels,
            frames,
            str(res.get("device") or ""),
            float(res.get("elapsed_s") or 0.0),
            round(time.time() - t0, 2),
        )
        _DONE[key] = stems
        log.info(
            "separated %s: %.1fs of %d-channel audio in %.1fs on %s (%.1fs with decoding and loading)",
            Path(path).name,
            frames / SR,
            channels,
            stems.elapsed_s,
            stems.device,
            stems.total_s,
        )
        return stems
    except BaseException:
        await asyncio.shield(aio.run_io(shutil.rmtree, folder, True))
        raise
    finally:
        _RUNS.pop(key, None)
        sp.background_tags.discard(key)


async def separate(
    ctx: Context,
    data: config.DataDir,
    path: str | Path,
    progress: Callable[[str, float], None] | None = None,
    background: bool = False,
) -> Stems:
    """Cached, joined from a run in flight, or separated now. A ``background`` preload may be stopped by another GPU
    job; a job that was waiting for it starts it again."""
    t0 = time.time()
    key = await aio.run_io(file_key, path)
    done = _DONE.get(key)
    if done is not None and await aio.run_io(done.exists):
        return Stems(**{**done.__dict__, "cached": True, "wait_s": 0.0})
    run = _RUNS.get(key)
    joined = run is not None
    if run is None:
        run = _Run(background=background)
        _RUNS[key] = run
        if background:
            speech.get(ctx.runtime, data.root).background_tags.add(key)
        run.task = aio.spawn(_separate(ctx, data, path, key, run), name=f"redub-separate-{key}")
    elif not background and run.background:
        run.background = False  # a job waits for it now: no longer a preload another job may stop
        speech.get(ctx.runtime, data.root).background_tags.discard(key)
    if progress is not None:
        run.listeners.append(progress)
    assert run.task is not None
    try:
        stems = await asyncio.shield(run.task)
    except speech.Cancelled:
        if background or not joined:
            raise
        return await separate(ctx, data, path, progress, background=False)  # the preload was stopped: run it now
    finally:
        if progress is not None and progress in run.listeners:
            run.listeners.remove(progress)
    return Stems(**{**stems.__dict__, "cached": False, "wait_s": round(time.time() - t0, 2)})


def forget(key: str) -> None:
    _DONE.pop(key, None)


def write_mix_wav(path: str | Path, x: np.ndarray, sr: int = SR) -> Path:
    """``x`` (channels, n) as a 32-bit float WAV (no rounding before the encoder)."""
    import soundfile as sf

    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    data = x.reshape(1, -1) if x.ndim == 1 else x
    sf.write(path, np.ascontiguousarray(data.T, dtype=np.float32), sr, subtype="FLOAT", format="WAV")
    return path


def _audio_start(path: str | Path) -> float:
    """The start time of the source's first audio stream (the decoded samples begin there), 0 when unknown."""
    exe = media.ffprobe_path()
    if not exe:
        return 0.0
    res = media._run(
        [
            exe,
            "-v",
            "error",
            "-select_streams",
            "a:0",
            "-show_entries",
            "stream=start_time",
            "-of",
            "default=nw=1:nk=1",
            path,
        ],
        60,
    )
    try:
        return float(res.stdout.decode("utf-8", errors="replace").strip().splitlines()[0])
    except (ValueError, IndexError):
        return 0.0


def picture_size(path: str | Path) -> tuple[int, int]:
    """The main picture's size as filters see it (a rotated phone video is turned upright first); 1920x1080 when
    unknown."""
    exe = media.ffprobe_path()
    if exe:
        res = media._run(
            [
                exe,
                "-v",
                "error",
                "-select_streams",
                "V:0",
                "-show_entries",
                "stream=width,height:stream_side_data=rotation",
                "-of",
                "json",
                path,
            ],
            60,
        )
        try:
            stream = json.loads(res.stdout.decode("utf-8", errors="replace"))["streams"][0]
            w, h = int(stream["width"]), int(stream["height"])
            turn = next((int(d["rotation"]) for d in stream.get("side_data_list") or [] if "rotation" in d), 0)
            if w > 0 and h > 0:
                return (h, w) if abs(turn) % 180 == 90 else (w, h)
        except (ValueError, KeyError, IndexError, TypeError):
            pass
    return 1920, 1080


@dataclass(frozen=True)
class _Attempt:
    picture: tuple[str, list[str]] | None  # encoder that burns the subtitles in, None: the picture is copied
    originals: bool  # the source's subtitles, attachments and chapters
    track: str | None  # encoder of the added subtitle track


@dataclass(frozen=True)
class _SubFiles:
    ass: Path
    srt: Path
    burn: list[tuple[str, list[str]]]
    track: str | None
    burned_track: str | None  # MP4 and MOV show their only subtitle track, which would draw the text twice


def mux_command(
    exe: str | Path,
    source: str | Path,
    audio: str | Path,
    part: Path,
    container: str,
    audio_encoder: tuple[str, list[str]],
    start: float,
    language: str | None,
    attempt: _Attempt,
    files: _SubFiles | None = None,
) -> list[str | Path]:
    offset = ["-itsoffset", f"{start:.6f}"] if abs(start) > 0.0005 else []
    decode: list[str] = []
    if attempt.picture is not None and files is not None:
        name = attempt.picture[0]
        tail = f",{media.encoder_format(name)}" if name in media.HARDWARE_H264 else ""
        graph = f"[0:V:0]{media.caption_fps(source)}subtitles=filename={subtitles.filter_path(files.ass)}{tail}[v]"
        picture = ["-filter_complex", graph, "-map", "[v]", "-c:v", name, *attempt.picture[1]]
        decode = media.HWACCEL
    else:
        picture = ["-map", "0:v"]
    subs_in: list[str | Path] = []
    track: list[str | Path] = []
    if attempt.track and files is not None:
        subs_in = ["-i", files.ass if attempt.track == "ass" else files.srt]
        shown = "0" if attempt.picture is not None else "default"
        track = ["-map", "2:0", "-c:s:0", attempt.track, "-disposition:s:0", shown]
        track += ["-metadata:s:s:0", f"language={language}"] if language else []
    extra = ["-map", "0:s?", "-map", "0:t?"] if attempt.originals else []
    encoder, args = audio_encoder
    tag = ["-metadata:s:a:0", f"language={language}"] if language else []
    fast = ["-movflags", "+faststart"] if container in _FASTSTART else []
    return [
        exe,
        "-nostdin",
        "-v",
        "error",
        "-y",
        *decode,
        "-i",
        source,
        *offset,
        "-i",
        audio,
        *subs_in,
        "-c",
        "copy",
        *picture,
        *track,
        *extra,
        "-map",
        "1:a:0",
        "-map_metadata",
        "0",
        "-map_chapters",
        "0" if attempt.originals else "-1",
        "-c:a",
        encoder,
        *args,
        "-ar",
        str(VIDEO_AUDIO_SR),
        *tag,
        "-disposition:a:0",
        "default",
        *fast,
        part,
    ]


def _attempts(files: _SubFiles | None) -> list[_Attempt]:
    """Burning encoders best first, then the copied picture; for each, the source's extras and the added track are
    dropped one after the other when the container refuses them."""
    plans: list[tuple[tuple[str, list[str]] | None, str | None]] = [(None, None)]
    if files is not None:
        plans = [*((enc, files.burned_track) for enc in files.burn), (None, files.track)]
    out = []
    for picture, track in plans:
        out += [_Attempt(picture, True, track), _Attempt(picture, False, track)]
        if track:
            out.append(_Attempt(picture, False, None))
    return out


def _subtitle_setup(
    source: str | Path, container: str, encoders: set[str], plan: subtitles.Plan, start: float
) -> tuple[_SubFiles | None, dict[str, Any]]:
    items = subtitles.cues([(a + start, b + start, t) for a, b, t in plan.lines or []])
    fields: dict[str, Any] = {"subtitles_burned": False, "subtitle_lines": len(items)}
    if not items:
        fields["subtitle_note"] = (
            "Convert voice keeps the original words without a transcript, so there is no text for subtitles."
            if plan.lines is None
            else "Nothing was spoken, so the video has no subtitles."
        )
        return None, fields
    width, height = picture_size(source)
    ass, srt = subtitles.write(plan, items, width, height)
    codec = _SUBTITLE_TRACK.get(container)
    track = codec if codec in encoders else None
    burned_track = None if container in _FASTSTART else track
    if "subtitles" not in media._ffmpeg_filters():
        fields["subtitle_note"] = _NO_LIBASS if track else _NO_SUBTITLES
        return _SubFiles(ass, srt, [], track, burned_track), fields
    choices = _PICTURE.get(container, _PICTURE[FALLBACK_CONTAINER])
    burn = [c for c in choices if c[0] in encoders]
    hw = media.h264_hardware() if choices[0] is _X264 else None
    if hw:
        burn.insert(0, (hw, media.h264_hardware_args(hw, HW_QUALITY)))
    if not burn:
        fields["subtitle_note"] = (
            f"This ffmpeg build has no video encoder for {container.upper()}, so the subtitles could not be drawn "
            "into the picture" + (f": {_AS_TRACK}" if track else ".")
        )
    return _SubFiles(ass, srt, burn, track, burned_track), fields


def _subtitle_note(container: str, files: _SubFiles, attempt: _Attempt, err: str) -> str | None:
    """None when the subtitles came out as planned (the note of a plan without burning is already set)."""
    if attempt.picture is not None:
        if files.burned_track and not attempt.track:
            return (
                "The subtitles are drawn into the picture only: the "
                f"{container.upper()} file did not take them as a track ({err})."
            )
        return None
    if not files.burn:
        return f"The subtitles could not be added to the video ({err})." if files.track and not attempt.track else None
    if attempt.track:
        return f"The subtitles could not be drawn into the picture ({err}): {_AS_TRACK}"
    return f"The subtitles could not be added to the video ({err})."


def mux(
    source: str | Path,
    audio: str | Path,
    dest: str | Path,
    container: str,
    language: str | None = None,
    subs: subtitles.Plan | None = None,
) -> dict[str, Any]:
    """Copy the picture of ``source`` (with subtitles, attachments, chapters where the container takes them) and
    encode ``audio`` as the only audio track. With ``subs`` the picture is re-encoded with the subtitles drawn
    in, and they are also added as a track. Blocking."""
    exe = media.require_ffmpeg()
    _, _, encoders, _ = media._ffmpeg_lists()
    choices = [c for c in _CONTAINERS.get(container, _CONTAINERS[FALLBACK_CONTAINER]) if c[0] in encoders]
    if not choices:
        raise EngineError("not_ready", f"this ffmpeg build has no audio encoder for {container.upper()} video")
    start = _audio_start(source)
    files, fields = None, {}
    if subs is not None:
        files, fields = _subtitle_setup(source, container, encoders, subs, start)
    dest = Path(dest)
    part = dest.with_name(f"{dest.name}.part.{container}")
    last = ""
    for attempt in _attempts(files):
        res = media._run(mux_command(exe, source, audio, part, container, choices[0], start, language, attempt, files))
        if res.returncode == 0 and part.is_file():
            part.replace(dest)
            if files is not None:
                fields["subtitles_burned"] = attempt.picture is not None
                note = _subtitle_note(container, files, attempt, last)
                if note:
                    fields["subtitle_note"] = note
            return {
                "audio_codec": choices[0][0],
                "faststart": container in _FASTSTART,
                "video_codec": attempt.picture[0] if attempt.picture is not None else "copy",
                "subtitles": fields,
            }
        last = media._tail(res.stderr)
        log.warning("mux %s failed (%s): %s", dest.name, last, attempt)
        part.unlink(missing_ok=True)
    raise EngineError("internal", f"Could not write the video ({last}).")