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.
Rust chatterboxdesktopdubbingmobilemultilingualofflineomnivoicerustrvcspeech-synthesisspeech-to-textstttext-to-speechttsvoice-cloningvoxcpm2whisper
from __future__ import annotations
import asyncio
import bisect
import concurrent.futures
import contextlib
import itertools
import json
import logging
import math
import os
import shutil
import threading
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
from . import aio, book, config, media, results
from .redub import langs, subtitles, video
from .registry import Context, EngineError, method
log = logging.getLogger("mimvox.videoexport")
FORMATS = ("mp4", "mkv", "webm", "mov")
WIDTH, HEIGHT = 1920, 1080
MAX_FRAME_S = 1.0 # a still repeats every second so players and seeking always find a picture
KEYFRAME_FRAMES = 10
PREPARE_PCT = 10.0
FADE_S = 0.6 # a photo fades in from black, and into the next, over this long
FADE_FPS = 25
ENERGY_SR = 8000
FRAME_S = 0.02
SPEECH_RANGE_DB = 30.0
SILENCE_DB = -70.0
WORD_GAP_S = 0.3
MIN_SPEECH_S = 0.1
SNAP = 0.5
_AAC = ("aac", ["-aac_coder", "fast", "-b:a", "192k"]) # 10 min of sound: 20 s with the default coder, 7.6 s fast
_OPUS = ("libopus", ["-b:a", "160k"])
_VORBIS = ("libvorbis", ["-q:a", "6"])
_X264 = ("libx264", ["-preset", "veryfast", "-crf", "20"])
HW_QUALITY = 23 # NVENC CQ 23 matched x264 CRF 20 here: SSIM 0.963 on noisy 1080p, 11% larger
_OPENH264 = ("libopenh264", ["-b:v", "6M"])
_MPEG4 = ("mpeg4", ["-q:v", "3"])
_VP9 = ("libvpx-vp9", ["-deadline", "realtime", "-cpu-used", "8", "-row-mt", "1", "-crf", "32", "-b:v", "0"])
_VP8 = ("libvpx", ["-deadline", "realtime", "-cpu-used", "8", "-crf", "10", "-b:v", "6M"])
_H264 = (_X264, _OPENH264, _MPEG4)
_PICTURE: dict[str, tuple[tuple[str, list[str]], ...]] = {
"mp4": _H264,
"mov": _H264,
"mkv": _H264,
"webm": (_VP9, _VP8),
}
_AUDIO: dict[str, tuple[tuple[str, list[str]], ...]] = {
"mp4": (_AAC,),
"mov": (_AAC,),
"mkv": (_AAC,),
"webm": (_OPUS, _VORBIS),
}
_KEEP_AUDIO = {"mp4": {"aac"}, "mov": {"aac"}, "mkv": {"aac"}, "webm": {"opus"}}
# Codecs each container takes as they are (None: any).
_REMUX: dict[str, tuple[set[str] | None, set[str] | None]] = {
"mp4": ({"h264", "hevc", "mpeg4", "av1"}, {"aac", "mp3", "ac3", "eac3", "alac"}),
"mov": ({"h264", "hevc", "mpeg4", "prores", "mjpeg"}, {"aac", "mp3", "ac3", "alac", "pcm_s16le", "pcm_s24le"}),
"mkv": (None, None),
"webm": ({"vp8", "vp9", "av1"}, {"opus", "vorbis"}),
}
_FASTSTART = {"mp4", "mov"}
_STILL = ["-r", "1000", "-f", "yuv4mpegpipe"] # the concat demuxer times a still in its rate: 1/25 s steps by default
_NO_LIBASS = "This ffmpeg build cannot draw subtitles (it has no libass)."
_running: set[str] = set()
Encoder = tuple[str, list[str]]
Progress = Callable[[str, float], None]
SR = video.VIDEO_AUDIO_SR
@dataclass(frozen=True)
class Part:
"""A sound file of the video, from ``start``; ``lines`` None: its subtitles come from its sidecar."""
path: Path
start: float
duration: float
channels: int = 1
lines: list[subtitles.Line] | None = None
source: str | None = None
image: Path | None = None
@property
def samples(self) -> int:
return round(self.duration * SR)
@dataclass(frozen=True)
class Request:
path: Path
dest: Path
fmt: str
position: str | None
images: list[Path | None] # the picture of each span, None: black
spans: list[tuple[float, float]]
sidecar: Path | None
duration: float
is_video: bool
audio_codec: str
parts: tuple[Part, ...] = ()
fade: bool = False
@property
def pieces(self) -> tuple[Part, ...]:
return self.parts or (Part(self.path, 0.0, self.duration),)
@dataclass(frozen=True)
class Subs:
cues: list[subtitles.Cue]
source: str | None
note: str | None
language: str | None
def _pick(choices: tuple[Encoder, ...], encoders: set[str]) -> Encoder | None:
return next((c for c in choices if c[0] in encoders), None)
def containers(encoders: set[str]) -> list[str]:
"""``formats.list`` ``export_video``: the containers this ffmpeg has a picture and a sound encoder for."""
return [f for f in FORMATS if _pick(_PICTURE[f], encoders) and _pick(_AUDIO[f], encoders)]
def _container(path: Path) -> str:
ext = path.suffix.lower().lstrip(".")
return media._IMPORT_ALIASES.get(ext, ext)
def parse_images(value: Any, from_zero: bool = True) -> tuple[list[Path], list[float] | None]:
"""The pictures and their starts (None: evenly spaced)."""
if value is None:
return [], None
if not isinstance(value, list):
raise EngineError("bad_request", '\'images\' must be a list of {"path", "start"?}')
paths: list[Path] = []
starts: list[float | None] = []
for k, item in enumerate(value, 1):
if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not item["path"]:
raise EngineError("bad_request", f"image {k} needs a 'path'")
start = item.get("start")
if start is not None and (
isinstance(start, bool) or not isinstance(start, (int, float)) or not math.isfinite(start) or start < 0
):
raise EngineError("bad_request", f"the start of image {k} must be a number of seconds")
paths.append(Path(item["path"]))
starts.append(None if start is None else float(start))
given = [s for s in starts if s is not None]
if given and len(given) != len(starts):
raise EngineError("bad_request", "give every image a start, or none of them")
if given:
if from_zero and given[0] != 0:
raise EngineError("bad_request", "the first image must start at 0")
for k, (a, b) in enumerate(itertools.pairwise(given), 2):
if b <= a:
raise EngineError("bad_request", f"image {k} must start after image {k - 1}")
for p in paths:
if not p.is_file():
raise EngineError("not_found", f"image not found: {p}")
return paths, (given or None)
def schedule(count: int, starts: list[float] | None, duration: float) -> list[tuple[float, float]]:
"""(start, end) of each picture."""
if count == 0:
return []
if starts is None:
step = duration / count
return [(k * step, duration if k == count - 1 else (k + 1) * step) for k in range(count)]
if starts[-1] >= duration:
raise EngineError(
"bad_request", f"image {len(starts)} starts at {starts[-1]:g} s, after the end ({duration:g} s)"
)
return list(itertools.pairwise([*starts, duration]))
def merge_images(
paths: list[Path], starts: list[float] | None, parts: list[Part], duration: float
) -> tuple[list[Path | None], list[tuple[float, float]]]:
"""The pictures of ``images`` and of the parts by time (a part's picture wins at the same start), each until the
next; black before the first."""
marks = [(a, 0, p) for (a, _), p in zip(schedule(len(paths), starts, duration), paths)]
marks += [(part.start, 1, part.image) for part in parts if part.image is not None]
shown: dict[float, Path | None] = {}
for a, _, p in sorted(marks, key=lambda m: (m[0], m[1])):
shown[round(a, 6)] = p
if not shown:
return [], []
if min(shown) > 0:
shown[0.0] = None
order = sorted(shown)
return [shown[a] for a in order], list(itertools.pairwise([*order, duration]))
def timeline(spans: list[tuple[float, float]], cuts: list[float], duration: float) -> list[tuple[int, float]]:
"""(picture, start) of each frame: a frame where the picture or a subtitle changes, and at least one a second."""
starts = [a for a, _ in spans] or [0.0]
marks = sorted({round(t, 3) for t in [*starts, *cuts] if 0 <= t < duration} | {0.0})
frames: list[tuple[int, float]] = []
for a, b in itertools.pairwise([*marks, duration]):
n = max(math.ceil((b - a) / MAX_FRAME_S - 1e-9), 1)
for k in range(n):
t = a + k * (b - a) / n
frames.append((max(bisect.bisect_right(starts, t + 1e-9) - 1, 0), t))
return frames
def concat_list(names: list[str], frames: list[tuple[int, float]], duration: float) -> str:
lines = ["ffconcat version 1.0"]
for k, (pic, t) in enumerate(frames):
end = frames[k + 1][1] if k + 1 < len(frames) else duration
lines += [f"file '{names[pic]}'", f"duration {end - t:.6f}"]
lines.append(f"file '{names[frames[-1][0]]}'") # the concat demuxer drops the last duration unless repeated
return "\n".join(lines) + "\n"
def transitions(params: dict[str, Any]) -> bool:
value = params.get("transitions", False)
if not isinstance(value, bool):
raise EngineError("bad_request", "'transitions' must be true or false")
return value
Blend = tuple[str, str, int, int] # (from, to, step, steps)
def fade_windows(names: list[str], spans: list[tuple[float, float]], black: str) -> list[tuple[float, float, str, str]]:
"""(start, length, from, to) of each fade: the first picture from black, then each into the next."""
out: list[tuple[float, float, str, str]] = []
if spans and names[0] != black:
out.append((0.0, min(FADE_S, spans[0][1] - spans[0][0]), black, names[0]))
for k in range(1, len(spans)):
if names[k] != names[k - 1]:
a, b = spans[k]
out.append((a, min(FADE_S, b - a), names[k - 1], names[k]))
return out
def fade_frames(
frames: list[tuple[str, float]], windows: list[tuple[float, float, str, str]], duration: float
) -> list[tuple[str | Blend, float]]:
"""The frames with each fade drawn in ``FADE_FPS`` steps; a frame inside a fade (a subtitle changing) shows the
step it falls in."""
times = [t for _, t in frames]
every = {round(t, 6) for t in times}
for t0, d, _, _ in windows:
n = max(round(d * FADE_FPS), 1)
every.update(round(t0 + k * d / n, 6) for k in range(n + 1))
out: list[tuple[str | Blend, float]] = []
for t in sorted(x for x in every if 0 <= x < duration):
if out and t - out[-1][1] < 0.005: # a subtitle change and a fade step a few ms apart: one frame
continue
shown: str | Blend = frames[max(bisect.bisect_right(times, t + 1e-9) - 1, 0)][0]
for t0, d, a, b in windows:
if t0 <= t < t0 + d - 1e-9:
n = max(round(d * FADE_FPS), 1)
k = math.floor((t - t0) / d * n + 1e-6)
shown = a if k == 0 else (a, b, k, n)
break
out.append((shown, t))
return out
def _y4m(path: Path) -> tuple[bytes, np.ndarray]:
head, rest = path.read_bytes().split(b"\n", 1)
return head + b"\n", np.frombuffer(rest.split(b"\n", 1)[1], np.uint8)
def blend_stills(work: Path, blends: dict[Blend, str]) -> None:
"""Blocking: each blend's still, eased between its two pictures."""
cache: dict[str, tuple[bytes, np.ndarray]] = {}
for (a, b, k, n), name in blends.items():
for p in (a, b):
if p not in cache:
cache[p] = _y4m(work / p)
p = k / n
mix = p * p * (3 - 2 * p)
head, x = cache[a]
y = cache[b][1]
out = (x.astype(np.float32) * (1 - mix) + y.astype(np.float32) * mix + 0.5).astype(np.uint8)
(work / name).write_bytes(head + b"FRAME\n" + out.tobytes())
def composite_command(exe: str | Path, src: str | Path, dst: str | Path) -> list[str | Path]:
graph = (
f"[0:v]split[a][b];[a]scale=384:216,gblur=sigma=10,scale={WIDTH}:{HEIGHT}[bg];"
f"[b]scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=decrease:force_divisible_by=2[fg];"
"[bg][fg]overlay=(W-w)/2:(H-h)/2,setsar=1,format=yuv420p[v]"
)
out = ["-map", "[v]", "-frames:v", "1", *_STILL, dst]
return [exe, "-nostdin", "-v", "error", "-y", "-i", src, "-filter_complex", graph, *out]
def black_command(exe: str | Path, dst: str | Path) -> list[str | Path]:
out = ["-frames:v", "1", "-pix_fmt", "yuv420p", *_STILL, dst]
return [exe, "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", f"color=c=black:s={WIDTH}x{HEIGHT}", *out]
def _audio_args(audio: Encoder | None) -> list[str]:
if audio is None:
return ["-c:a", "copy"]
return ["-c:a", audio[0], *audio[1], "-ar", str(video.VIDEO_AUDIO_SR)]
def _tail_args(fmt: str, part: Path) -> list[str | Path]:
fast = ["-movflags", "+faststart"] if fmt in _FASTSTART else []
return ["-map_metadata", "-1", *fast, "-progress", "pipe:1", "-nostats", part]
def joined_sound(parts: list[Part]) -> str:
"""The parts' sound one after the other (inputs 1..n), each padded or cut to its length in samples."""
layout = "stereo" if any(p.channels > 1 for p in parts) else "mono"
legs = "".join(
f"[{k}:a:0]aresample={SR},aformat=channel_layouts={layout},"
f"apad=whole_len={p.samples},atrim=end_sample={p.samples}[a{k}];"
for k, p in enumerate(parts, 1)
)
joins = "".join(f"[a{k}]" for k in range(1, len(parts) + 1))
return f"{legs}{joins}concat=n={len(parts)}:v=0:a=1,asetpts=N/SR/TB[a]"
def slideshow_command(
exe: str | Path,
listing: Path,
source: Path | list[Part],
part: Path,
fmt: str,
picture: Encoder,
audio: Encoder | None,
duration: float,
ass: Path | None = None,
) -> list[str | Path]:
"""``audio`` None copies the source's sound; a list of parts is joined (and needs ``audio``)."""
chain = (f"subtitles=filename={subtitles.filter_path(ass)}," if ass else "") + media.encoder_format(picture[0])
tune = ["-tune", "stillimage"] if picture[0] == "libx264" else []
graph = f"[0:v]{chain}[v]"
if isinstance(source, list):
inputs: list[str | Path] = [x for p in source for x in ("-i", p.path)]
graph, sound = f"{graph};{joined_sound(source)}", "[a]"
else:
inputs, sound = ["-i", source], "1:a:0"
return [
exe,
"-nostdin",
"-v",
"error",
"-y",
"-f",
"concat",
"-i",
listing,
*inputs,
"-filter_complex",
graph,
"-map",
"[v]",
"-map",
sound,
"-c:v",
picture[0],
*picture[1],
*tune,
"-g",
str(KEYFRAME_FRAMES),
*_audio_args(audio),
*_tail_args(fmt, part),
]
def remux_command(exe: str | Path, source: Path, part: Path, fmt: str) -> list[str | Path]:
streams = ["-map", "0:V:0", "-map", "0:a:0?", "-c", "copy"]
return [exe, "-nostdin", "-v", "error", "-y", "-i", source, *streams, *_tail_args(fmt, part)]
def reencode_command(
exe: str | Path,
source: Path,
part: Path,
fmt: str,
picture: Encoder,
audio: Encoder | None,
ass: Path | None = None,
) -> list[str | Path]:
burn = f"{media.caption_fps(source)}subtitles=filename={subtitles.filter_path(ass)}," if ass else ""
graph = f"[0:V:0]scale=trunc(iw/2)*2:trunc(ih/2)*2,{burn}{media.encoder_format(picture[0])}[v]"
return [
exe,
"-nostdin",
"-v",
"error",
"-y",
*media.HWACCEL,
"-i",
source,
"-filter_complex",
graph,
"-map",
"[v]",
"-map",
"0:a:0?",
"-c:v",
picture[0],
*picture[1],
*_audio_args(audio),
*_tail_args(fmt, part),
]
def sentences(text: str) -> list[str]:
out: list[str] = []
for line in text.splitlines():
out += [s.strip() for s in subtitles._SENTENCE.split(" ".join(line.split())) if s.strip()]
return out
def speech_regions(y: np.ndarray, sr: int) -> list[tuple[float, float]]:
"""Where the sound is within ``SPEECH_RANGE_DB`` of its loud part; pauses under ``WORD_GAP_S`` are bridged."""
hop = max(round(sr * FRAME_S), 1)
n = len(y) // hop
if n == 0:
return []
frames = y[: n * hop].reshape(n, hop)
db = 10.0 * np.log10(np.einsum("ij,ij->i", frames, frames) / hop + 1e-12)
loud = float(np.percentile(db, 95))
if loud < SILENCE_DB:
return []
on = np.concatenate(([0], (db > loud - SPEECH_RANGE_DB).astype(np.int8), [0]))
edges = np.flatnonzero(np.diff(on)) * (hop / sr)
out: list[tuple[float, float]] = []
for a, b in zip(edges[::2].tolist(), edges[1::2].tolist()):
if out and a - out[-1][1] < WORD_GAP_S:
out[-1] = (out[-1][0], b)
else:
out.append((a, b))
return [(a, b) for a, b in out if b - a >= MIN_SPEECH_S]
def estimate(text: str, regions: list[tuple[float, float]], duration: float) -> list[subtitles.Line]:
"""Each sentence's time: the speech shared by character count, each break between sentences moved to a pause
near it."""
parts = sentences(text)
if not parts:
return []
regions = regions or [(0.0, duration)]
cum = list(itertools.accumulate((b - a for a, b in regions), initial=0.0))
weights = list(itertools.accumulate((max(len(p.replace(" ", "")), 1) for p in parts), initial=0))
targets = [cum[-1] * w / weights[-1] for w in weights]
gaps = cum[1:-1]
def at(t: float) -> float:
j = min(max(bisect.bisect_right(cum, t) - 1, 0), len(regions) - 1)
return regions[j][0] + t - cum[j]
bounds = [(regions[0][0], regions[0][0])]
last = 0.0
for k in range(1, len(parts)):
t = targets[k]
tol = SNAP * min(t - targets[k - 1], targets[k + 1] - t)
i = bisect.bisect_left(gaps, t)
near = min((j for j in (i - 1, i) if 0 <= j < len(gaps)), key=lambda j: abs(gaps[j] - t), default=None)
if near is not None and abs(gaps[near] - t) <= tol and gaps[near] > last:
bounds.append((regions[near][1], regions[near + 1][0]))
last = gaps[near]
else:
last = max(t, last)
bounds.append((at(last), at(last)))
bounds.append((regions[-1][1], regions[-1][1]))
return [(bounds[k][1], bounds[k + 1][0], p) for k, p in enumerate(parts)]
def _num(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def recorded(side: dict[str, Any], duration: float) -> list[subtitles.Line]:
segs = side.get("segments")
out: list[subtitles.Line] = []
for s in segs if isinstance(segs, list) else []:
if not isinstance(s, dict):
continue
a, b, text = s.get("start"), s.get("end"), s.get("text")
if _num(a) and _num(b) and isinstance(text, str) and text.strip():
a, b = max(float(a), 0.0), min(float(b), duration)
if s.get("kind") == "title" and text.rstrip()[-1] not in ".!?…。!?":
text = text.rstrip() + "." # a chapter title is a sentence of its own, not the start of the first one
if b > a:
out.append((a, b, text))
return out
def _read_side(path: Path) -> dict[str, Any]:
try:
obj = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return obj if isinstance(obj, dict) else {}
def part_lines(part: Part, sidecar: Path | None) -> tuple[list[subtitles.Line], str | None, str | None]:
"""Blocking. (lines in the part's time, source, language): the lines given, else the sidecar's recorded segments,
else an estimate from its text over the speech found in the sound."""
if part.lines is not None:
got = [(max(a, 0.0), min(b, part.duration), t) for a, b, t in part.lines]
return [(a, b, t) for a, b, t in got if b > a and t.strip()], part.source, None
side = _read_side(sidecar or results.sidecar_path(part.path))
language = next((v for v in (side.get("language"), side.get("to")) if isinstance(v, str) and v), None)
lines = recorded(side, part.duration)
if lines:
return lines, "recorded", language
text = side.get("text")
if isinstance(text, str) and text.strip():
regions = speech_regions(media.decode_pcm(part.path, ENERGY_SR), ENERGY_SR)
return estimate(text, regions, part.duration), "estimated", language
return [], None, language
def subtitle_cues(req: Request) -> Subs:
"""Blocking. Each part's lines, moved to its start."""
if "subtitles" not in media._ffmpeg_filters():
return Subs([], None, _NO_LIBASS, None)
pieces = req.pieces
lines: list[subtitles.Line] = []
sources: set[str | None] = set()
language, bare = None, []
for k, part in enumerate(pieces, 1):
got, source, lang = part_lines(part, req.sidecar)
language = language or lang
if got:
sources.add(source)
lines += [(a + part.start, b + part.start, t) for a, b, t in got]
else:
bare.append(k)
items = subtitles.cues(lines)
if not items:
return Subs([], None, "This result has no saved text, so the video has no subtitles.", language)
source = next(s for s in ("estimated", "recorded", "given") if s in sources)
language = language or langs.script_language_guess(" ".join(t for *_, t in lines))
note = None
if bare and len(pieces) > 1:
which = f"Part {bare[0]} has" if len(bare) == 1 else f"Parts {', '.join(map(str, bare))} have"
note = f"{which} no saved text, so no subtitles."
return Subs(items, source, note, language)
def given_cues(lines: list[subtitles.Line], language: str | None, words: list[subtitles.Words] | None = None) -> Subs:
"""Blocking. Cues of lines given with their times (and their words' times, when known)."""
if "subtitles" not in media._ffmpeg_filters():
return Subs([], None, _NO_LIBASS, language)
items = subtitles.cues(lines, words)
if not items:
return Subs([], None, "No line has a length, so the video has no subtitles.", language)
return Subs(items, "given", None, language)
def own_format(path: Path, is_video: bool) -> str:
"""Blocking. A video keeps its container (MKV for one this export cannot write); a sound file gets an MP4."""
own = _container(path)
fmt = (own if own in FORMATS else "mkv") if is_video else "mp4"
media.require_ffmpeg()
if fmt not in containers(media._ffmpeg_lists()[2]):
raise EngineError("not_ready", f"This ffmpeg build has no encoder for {fmt.upper()} video.")
return fmt
def audio_offset(path: Path) -> float:
"""Blocking. Where the first audio sample sits in the timeline ffmpeg writes (the file's start is moved to 0)."""
exe = media.ffprobe_path()
if exe is None:
return 0.0
cmd = [exe, "-v", "error", "-select_streams", "a:0", "-show_entries", "format=start_time:stream=start_time"]
res = media._run([*cmd, "-of", "json", path], 60)
try:
info = json.loads(res.stdout.decode("utf-8", errors="replace"))
return max(float(info["streams"][0]["start_time"]) - float(info["format"]["start_time"]), 0.0)
except (ValueError, KeyError, IndexError, TypeError):
return 0.0
def _segment_lines(value: Any, where: str) -> list[subtitles.Line]:
if not isinstance(value, list):
raise EngineError("bad_request", f'{where}\'segments\' must be a list of {{"start", "end", "text"}}')
out: list[subtitles.Line] = []
for k, s in enumerate(value, 1):
if not (isinstance(s, dict) and _num(s.get("start")) and _num(s.get("end")) and isinstance(s.get("text"), str)):
raise EngineError("bad_request", f"{where}segment {k} needs a 'start', an 'end' and a 'text'")
out.append((float(s["start"]), float(s["end"]), s["text"]))
return out
def _segments_file(value: Any, where: str) -> list[subtitles.Line]:
"""A book's segment file or a result sidecar: its ``segments``."""
if not isinstance(value, str):
raise EngineError("bad_request", f"{where}'segments_path' must be a file path")
path = Path(value)
if not path.is_file():
raise EngineError("not_found", f"file not found: {path}")
side = _read_side(path)
if not isinstance(side.get("segments"), list):
raise EngineError("bad_request", f"{where}{path.name} has no 'segments' list")
return recorded(side, math.inf)
def given_lines(item: dict[str, Any], where: str = "") -> tuple[list[subtitles.Line] | None, str | None]:
"""(lines, source) from ``segments`` or ``segments_path``; (None, None): neither is given."""
segs, path = item.get("segments"), item.get("segments_path")
if segs is not None and path not in (None, ""):
raise EngineError("bad_request", f"{where}give 'segments' or 'segments_path', not both")
if segs is not None:
return _segment_lines(segs, where), "given"
if path not in (None, ""):
return _segments_file(path, where), "recorded"
return None, None
def parse_parts(value: Any) -> list[Part]:
"""Blocking (probes every file)."""
if not isinstance(value, list) or not value:
raise EngineError(
"bad_request", '\'parts\' must be a list of {"path", "segments"?, "segments_path"?, "image"?}'
)
items: list[tuple[Path, Path | None, list[subtitles.Line] | None, str | None]] = []
for k, item in enumerate(value, 1):
if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not item["path"]:
raise EngineError("bad_request", f"part {k} needs a 'path'")
path = media._check_file(item["path"])
image = item.get("image")
if image in (None, ""):
image = None
elif not isinstance(image, str):
raise EngineError("bad_request", f"part {k}: 'image' must be a file path")
else:
image = Path(image)
if not image.is_file():
raise EngineError("not_found", f"image not found: {image}")
items.append((path, image, *given_lines(item, f"part {k}: ")))
with concurrent.futures.ThreadPoolExecutor(8) as pool:
infos = list(pool.map(media.probe, [p for p, *_ in items]))
parts: list[Part] = []
at = 0
for k, ((path, image, lines, source), info) in enumerate(zip(items, infos), 1):
if info["has_video"]:
raise EngineError("bad_request", f"part {k} ({path.name}) is a video: parts must be sound files")
if not info["has_audio"]:
raise EngineError("bad_request", f"part {k} ({path.name}) has no audio track")
n = round(float(info["duration_s"]) * SR)
if n <= 0:
raise EngineError("bad_request", f"part {k} ({path.name}) has no length")
parts.append(Part(path, at / SR, n / SR, int(info["channels"] or 1), lines, source, image))
at += n
return parts
def _dest(params: dict[str, Any], fmt: str) -> Path:
dest = params.get("dest")
if not isinstance(dest, str) or not Path(dest).is_absolute():
raise EngineError("bad_request", "'dest' must be an absolute file path")
out = Path(dest)
if out.suffix.lower() != f".{fmt}":
raise EngineError("bad_request", f"'dest' must end in .{fmt}")
if out.is_dir():
raise EngineError("bad_request", "'dest' must be a file path, not a folder")
return out
def _sidecar(params: dict[str, Any]) -> Path | None:
side = params.get("sidecar")
if side in (None, ""):
return None
if not isinstance(side, str):
raise EngineError("bad_request", "'sidecar' must be a file path")
if not Path(side).is_file():
raise EngineError("not_found", f"file not found: {side}")
return Path(side)
def request(params: dict[str, Any]) -> Request:
"""Blocking (probes the files)."""
fmt = params.get("format")
if fmt not in FORMATS:
raise EngineError("bad_request", f"'format' must be one of {', '.join(FORMATS)}")
joined = params.get("parts")
if joined is not None and params.get("path") is not None:
raise EngineError("bad_request", "give 'path' or 'parts', not both")
if joined is not None:
for key in ("segments", "segments_path", "sidecar"):
if params.get(key) not in (None, ""):
raise EngineError("bad_request", f"with 'parts', '{key}' goes into each part")
path = None if joined is not None else media._check_file(params.get("path"))
out = _dest(params, fmt)
subs = params.get("subtitles")
position = None
if subs is not None:
position = subs.get("position", "bottom") if isinstance(subs, dict) else None
if position not in video.POSITIONS:
raise EngineError("bad_request", '\'subtitles\' must be null or {"position": "bottom" | "top"}')
images, starts = parse_images(params.get("images"), from_zero=joined is None)
if path is None:
parts = parse_parts(joined)
if any(out.resolve() == p.path.resolve() for p in parts):
raise EngineError("bad_request", "'dest' must differ from the source files")
media.require_ffmpeg()
if fmt not in containers(media._ffmpeg_lists()[2]):
raise EngineError("not_ready", f"This ffmpeg build has no encoder for {fmt.upper()} video.")
duration = sum(p.samples for p in parts) / SR
shown, spans = merge_images(images, starts, parts, duration)
return Request(
parts[0].path,
out,
fmt,
position,
shown,
spans,
None,
duration,
False,
"",
tuple(parts),
transitions(params),
)
if out.resolve() == path.resolve():
raise EngineError("bad_request", "'dest' must differ from the source file")
lines, source = given_lines(params)
sidecar = _sidecar(params)
media.require_ffmpeg()
if fmt not in containers(media._ffmpeg_lists()[2]):
raise EngineError("not_ready", f"This ffmpeg build has no encoder for {fmt.upper()} video.")
info = media.probe(path)
if not info["has_audio"]:
raise EngineError("bad_request", "This file has no audio track.")
duration = float(info["duration_s"])
if duration <= 0:
raise EngineError("bad_request", "This file has no length.")
is_video = bool(info["has_video"])
spans = [] if is_video else schedule(len(images), starts, duration)
part = Part(path, 0.0, duration, int(info["channels"] or 1), lines, source)
shown: list[Path | None] = list(images)
return Request(
path,
out,
fmt,
position,
shown,
spans,
sidecar,
duration,
is_video,
str(info["codec"]),
(part,),
transitions(params),
)
def _codecs(path: Path) -> tuple[str, str]:
"""(picture codec, sound codec) of the first streams."""
exe = media.ffprobe_path()
if exe is None:
return "", ""
res = media._run([exe, "-v", "error", "-show_entries", "stream=codec_type,codec_name", "-of", "json", path], 60)
try:
streams = json.loads(res.stdout.decode("utf-8", errors="replace")).get("streams") or []
except ValueError:
return "", ""
def first(kind: str) -> str:
return next((str(s.get("codec_name") or "") for s in streams if s.get("codec_type") == kind), "")
return first("video"), first("audio")
def fits(fmt: str, codecs: tuple[str, str]) -> bool:
pictures, sounds = _REMUX[fmt]
v, a = codecs
return bool(v) and (pictures is None or v in pictures) and (not a or sounds is None or a in sounds)
async def _ffmpeg(cmd: list[str | Path], total_s: float, on_pct: Callable[[float], None]) -> tuple[int, bytes]:
stop = threading.Event()
task = asyncio.ensure_future(
aio.run_io(book._ffmpeg_with_progress, cmd, total_s, lambda pct, _eta: on_pct(pct), stop)
)
try:
return await asyncio.shield(task)
except asyncio.CancelledError:
stop.set()
await task
raise
def _keep(part: Path, dest: Path) -> bool:
if not part.is_file():
return False
part.replace(dest)
return True
def _clean(part: Path, work: Path) -> None:
with contextlib.suppress(OSError):
part.unlink(missing_ok=True)
shutil.rmtree(work, ignore_errors=True)
async def _write(
command: Callable[[Encoder], list[str | Path]],
pictures: list[Encoder],
part: Path,
dest: Path,
total_s: float,
progress: Progress,
) -> None:
"""Encodes with the first picture encoder that works."""
err = b""
for k, picture in enumerate(pictures):
code, err = await _ffmpeg(command(picture), total_s, lambda pct: progress("encode", pct))
if code == 0 and await aio.run_io(_keep, part, dest):
log.info("video %s encoded with %s", dest.name, picture[0])
return
if k + 1 < len(pictures):
log.warning(
"%s could not encode %s (%s); trying %s", picture[0], dest.name, media._tail(err), pictures[k + 1][0]
)
raise EngineError("internal", f"Could not write the video ({media._tail(err)}).")
def _audio_for(fmt: str, codec: str, encoders: set[str]) -> Encoder | None:
"""None: the sound is copied as it is."""
if codec in _KEEP_AUDIO[fmt]:
return None
choice = _pick(_AUDIO[fmt], encoders)
if choice is None:
raise EngineError("not_ready", f"This ffmpeg build has no audio encoder for {fmt.upper()} video.")
return choice
def pictures_for(fmt: str, encoders: set[str]) -> list[Encoder]:
"""Best first: a hardware H.264 encoder that works here, then the software ones. Blocking (the first call probes
the hardware)."""
soft = [c for c in _PICTURE[fmt] if c[0] in encoders]
if not soft:
raise EngineError("not_ready", f"This ffmpeg build has no video encoder for {fmt.upper()}.")
hw = media.h264_hardware() if _PICTURE[fmt] is _H264 else None
return [(hw, media.h264_hardware_args(hw, HW_QUALITY)), *soft] if hw else soft
async def _slideshow(req: Request, work: Path, part: Path, subs: Subs, ass: Path | None, progress: Progress) -> None:
exe = media.require_ffmpeg()
encoders = media._ffmpeg_lists()[2]
unique = list(dict.fromkeys(p for p in req.images if p is not None))
names: dict[Path | None, str] = {p: f"p{k}.y4m" for k, p in enumerate(unique)}
if not req.images or None in req.images or (req.fade and req.spans):
names[None] = "black.y4m"
res = await aio.run_io(media._run, black_command(exe, work / names[None]), 120)
if res.returncode != 0:
raise EngineError("internal", f"Could not make the black picture ({media._tail(res.stderr)}).")
for k, img in enumerate(unique):
res = await aio.run_io(media._run, composite_command(exe, img, work / names[img]), 300)
if res.returncode != 0 or not (work / names[img]).is_file():
raise EngineError("bad_request", f"The picture {img.name} cannot be read ({media._tail(res.stderr)}).")
progress("prepare", 30.0 + 70.0 * (k + 1) / len(unique))
shown = [names[p] for p in req.images] or [names[None]]
cuts = subtitles.change_times(subs.cues)
listing = work / "frames.ffconcat"
frames = timeline(req.spans, cuts, req.duration)
if req.fade and req.spans:
windows = fade_windows(shown, req.spans, names[None])
faded = fade_frames([(shown[i], t) for i, t in frames], windows, req.duration)
blends = {key: f"x{k}.y4m" for k, key in enumerate(dict.fromkeys(x for x, _ in faded if isinstance(x, tuple)))}
await aio.run_io(blend_stills, work, blends)
named = [blends[x] if isinstance(x, tuple) else x for x, _ in faded]
shown = list(dict.fromkeys(named))
at = {n: k for k, n in enumerate(shown)}
frames = [(at[n], t) for n, (_, t) in zip(named, faded, strict=True)]
await aio.run_io(listing.write_text, concat_list(shown, frames, req.duration), "utf-8")
pictures = await aio.run_io(pictures_for, req.fmt, encoders)
joined = list(req.parts) if len(req.parts) > 1 else None
audio = _audio_for(req.fmt, "" if joined else req.audio_codec, encoders)
source = joined or req.path
def command(picture: Encoder) -> list[str | Path]:
return slideshow_command(exe, listing, source, part, req.fmt, picture, audio, req.duration, ass)
await _write(command, pictures, part, req.dest, req.duration, progress)
async def _from_video(req: Request, part: Path, ass: Path | None, progress: Progress) -> bool:
"""True when the file was copied as it is."""
exe = media.require_ffmpeg()
if ass is None and _container(req.path) == req.fmt:
await aio.run_io(shutil.copyfile, req.path, part)
await aio.run_io(_keep, part, req.dest)
return True
codecs = await aio.run_io(_codecs, req.path)
if ass is None and fits(req.fmt, codecs):
code, err = await _ffmpeg(remux_command(exe, req.path, part, req.fmt), req.duration, lambda _pct: None)
if code == 0 and await aio.run_io(_keep, part, req.dest):
return False
log.warning("remux of %s to %s failed (%s); encoding it", req.path.name, req.fmt, media._tail(err))
encoders = media._ffmpeg_lists()[2]
pictures = await aio.run_io(pictures_for, req.fmt, encoders)
audio = _audio_for(req.fmt, codecs[1], encoders)
def command(picture: Encoder) -> list[str | Path]:
return reencode_command(exe, req.path, part, req.fmt, picture, audio, ass)
await _write(command, pictures, part, req.dest, req.duration, progress)
return False
async def make(req: Request, work: Path, part: Path, subs: Subs, progress: Progress) -> bool:
"""Writes ``req.dest`` with ``subs`` burned in (none without ``req.position``); True when the file was copied as it
is."""
ass = None
if subs.cues and req.position is not None:
width, height = await aio.run_io(video.picture_size, req.path) if req.is_video else (WIDTH, HEIGHT)
ass = work / "subtitles.ass"
doc = subtitles.ass(subs.cues, width, height, req.position, subs.language)
await aio.run_io(ass.write_text, doc, "utf-8")
progress("prepare", 30)
if req.is_video:
return await _from_video(req, part, ass, progress)
await _slideshow(req, work, part, subs, ass, progress)
return False
async def _run(ctx: Context, job: str, req: Request) -> None:
work = config.data_dir(ctx).tmp / f"video_{job}"
part = req.dest.with_name(f"{req.dest.name}.part-{os.getpid()}.{req.fmt}")
last = [0.0]
def progress(stage: str, pct: float) -> None:
lo, hi = (0.0, PREPARE_PCT) if stage == "prepare" else (PREPARE_PCT, 100.0)
last[0] = max(last[0], lo + (hi - lo) * min(max(pct, 0.0), 100.0) / 100.0)
ctx.emit("video.progress", {"stage": stage, "pct": round(last[0], 1)}, job=job)
def end(event: str, data: dict[str, Any]) -> None:
_running.discard(job) # free before the app can see the end and start the next export
ctx.emit(event, data, job=job)
try:
progress("prepare", 0)
await aio.run_io(work.mkdir, parents=True, exist_ok=True)
await aio.run_io(req.dest.parent.mkdir, parents=True, exist_ok=True)
subs = Subs([], None, None, None)
if req.position is not None:
subs = await aio.run_io(subtitle_cues, req)
copied = await make(req, work, part, subs, progress)
try:
duration = float((await aio.run_io(media.probe, req.dest))["duration_s"]) or req.duration
except EngineError:
duration = req.duration
done: dict[str, Any] = {
"dest": str(req.dest),
"duration_s": round(duration, 3),
"copied": copied,
"subtitles": {"lines": len(subs.cues), "source": subs.source} if subs.cues else None,
"parts": [
{"path": str(p.path), "start": round(p.start, 3), "duration_s": round(p.duration, 3)}
for p in req.pieces
],
}
if subs.note:
done["subtitle_note"] = subs.note
end("video.done", done)
except asyncio.CancelledError:
end("video.error", {"code": "cancelled", "message": "cancelled"})
except EngineError as exc:
end("video.error", {"code": exc.code, "message": exc.message})
except Exception as exc:
log.exception("video export %s failed", job)
end("video.error", {"code": "internal", "message": f"{type(exc).__name__}: {exc}"})
finally:
_running.discard(job)
await aio.run_io(_clean, part, work)
@method("video.export")
async def video_export(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
req = await aio.run_io(request, params)
if _running:
raise EngineError("busy", "a video is being exported; wait for it or cancel it")
async def run(job: str) -> None:
await _run(ctx, job, req)
job = ctx.start_job(run)
_running.add(job)
return {"job": job}
@method("video.cancel")
async def video_cancel(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
job = params.get("job")
if job is not None and not isinstance(job, str):
raise EngineError("bad_request", "'job' must be a job id")
hit = [j for j in ([job] if job is not None else list(_running)) if j in _running]
for j in hit:
ctx.cancel(j)
return {"cancelled": bool(hit)}
def _heard(segments: Any) -> list[subtitles.Words]:
out: list[subtitles.Words] = []
for s in segments:
words = s.get("words") if isinstance(s.get("words"), list) else []
ok = (w for w in words if isinstance(w, list | tuple) and len(w) == 3)
out.append([(float(a), float(b), w) for a, b, w in ok if _num(a) and _num(b) and isinstance(w, str)])
return out
def save_subtitles(params: dict[str, Any]) -> dict[str, Any]:
"""Blocking (probes the file, and decodes it when its lines are estimated)."""
fmt = params.get("format")
if fmt not in subtitles.WRITERS:
raise EngineError("bad_request", f"'format' must be one of {', '.join(subtitles.WRITERS)}")
dest = _dest(params, fmt)
lines, source = given_lines(params)
words = _heard(params["segments"]) if lines is not None and source == "given" else None
if lines is None:
if params.get("path") in (None, ""):
raise EngineError("bad_request", "give 'segments', 'segments_path' or 'path'")
path = media._check_file(params.get("path"))
sidecar = _sidecar(params)
duration = float(media.probe(path)["duration_s"])
lines, source, _ = part_lines(Part(path, 0.0, duration), sidecar)
if not lines:
raise EngineError("bad_request", "This file has no saved text, so it has no subtitles.")
items = subtitles.cues(lines, words)
if not items:
raise EngineError("bad_request", "No line has a text and a length, so there are no subtitles.")
dest.parent.mkdir(parents=True, exist_ok=True)
part = dest.with_name(f"{dest.name}.part-{os.getpid()}")
part.write_text(subtitles.WRITERS[fmt](items), encoding="utf-8")
part.replace(dest)
return {"path": str(dest), "cues": len(items), "source": source, "size_bytes": dest.stat().st_size}
@method("subtitles.export")
async def subtitles_export(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
return await aio.run_io(save_subtitles, params)