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 contextlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any
import numpy as np
import soundfile as sf
from . import config
from .registry import EngineError, method
log = logging.getLogger("mimvox.media")
_EXE = ".exe" if os.name == "nt" else ""
_FLAGS = getattr(subprocess, "CREATE_NO_WINDOW", 0)
_runtime: dict[str, Any] = {}
_cache: dict[str, Any] = {}
_lock = threading.Lock()
# ext -> (kind, demuxers (any), decoders (any)) that make the import of that extension work.
_IMPORT: dict[str, tuple[str, tuple[str, ...], tuple[str, ...]]] = {
"wav": ("audio", ("wav",), ("pcm_s16le",)),
"mp3": ("audio", ("mp3",), ("mp3", "mp3float")),
"m4a": ("audio", ("mov",), ("aac",)),
"aac": ("audio", ("aac",), ("aac",)),
"flac": ("audio", ("flac",), ("flac",)),
"ogg": ("audio", ("ogg",), ("vorbis", "libvorbis", "opus", "libopus")),
"opus": ("audio", ("ogg",), ("opus", "libopus")),
"wma": ("audio", ("asf",), ("wmav2", "wmav1", "wmapro")),
"aiff": ("audio", ("aiff",), ("pcm_s16be",)),
"mp4": ("video", ("mov",), ("aac",)),
"mkv": ("video", ("matroska",), ("aac", "vorbis", "opus", "mp3", "flac", "pcm_s16le")),
"mov": ("video", ("mov",), ("aac",)),
"webm": ("video", ("matroska",), ("vorbis", "opus", "libopus", "libvorbis")),
"avi": ("video", ("avi",), ("mp3", "mp3float", "pcm_s16le", "ac3", "aac")),
}
_IMPORT_ALIASES = {
"aif": "aiff",
"aifc": "aiff",
"oga": "ogg",
"mpeg": "mp3",
"mp2": "mp3",
"m4b": "m4a",
"mka": "mkv",
"m4v": "mp4",
"wave": "wav",
}
_NATIVE_EXT = {".wav", ".flac", ".aiff", ".aif", ".aifc", ".ogg", ".oga"} # libsndfile first, ffmpeg as fallback
# Export formats: ext, encoder options per quality (high / standard / small), encoders that can do it.
_EXPORT: dict[str, dict[str, Any]] = {
"wav": {"ext": "wav", "args": ["-c:a", "pcm_s16le", "-ar", "44100"], "quality": False, "encoders": ("pcm_s16le",)},
"mp3": {
"ext": "mp3",
"args": ["-c:a", "libmp3lame", "-ar", "44100"],
"encoders": ("libmp3lame",),
"q": {"high": ["-b:a", "320k"], "standard": ["-b:a", "192k"], "small": ["-b:a", "128k"]},
},
"flac": {"ext": "flac", "args": ["-c:a", "flac", "-sample_fmt", "s16"], "quality": False, "encoders": ("flac",)},
"ogg": {
"ext": "ogg",
"args": ["-c:a", "libvorbis"],
"encoders": ("libvorbis", "vorbis"),
"q": {"high": ["-q:a", "7"], "standard": ["-q:a", "5"], "small": ["-q:a", "3"]},
},
"opus": {
"ext": "opus",
"args": ["-c:a", "libopus", "-ar", "48000"],
"encoders": ("libopus",),
"q": {"high": ["-b:a", "128k"], "standard": ["-b:a", "96k"], "small": ["-b:a", "64k"]},
},
"m4a": {
"ext": "m4a",
"args": ["-c:a", "aac", "-ar", "44100", "-movflags", "+faststart"],
"encoders": ("aac",),
"q": {"high": ["-b:a", "256k"], "standard": ["-b:a", "192k"], "small": ["-b:a", "128k"]},
},
"aiff": {
"ext": "aiff",
"args": ["-c:a", "pcm_s16be", "-ar", "44100"],
"quality": False,
"encoders": ("pcm_s16be",),
},
}
QUALITIES = ("high", "standard", "small")
def configure(runtime: dict[str, Any]) -> None:
"""Remember runtime.toml (for the Applio ffmpeg) and forget earlier lookups."""
with _lock:
_runtime.clear()
_runtime.update(runtime or {})
_cache.clear()
def _find(name: str) -> Path | None:
env = os.environ.get("MIMVOX_FFMPEG")
if env: # a folder, or the ffmpeg file itself (its siblings are used)
given = Path(env)
folder = given if given.is_dir() else given.parent
cand = folder / (name + _EXE)
if cand.is_file():
return cand
# Applio's own copies (Windows), then the portable build setup puts in <runtime>/ffmpeg when the system has none
applio = config.applio_dir(_runtime) if _runtime else None
root = config.runtime_root(_runtime) if _runtime else None
for folder in (applio, root / "ffmpeg" if root else None):
if folder and (cand := folder / (name + _EXE)).is_file():
return cand
found = shutil.which(name)
return Path(found) if found else None
def ffmpeg_path() -> Path | None:
with _lock:
if "ffmpeg" not in _cache:
_cache["ffmpeg"] = _find("ffmpeg")
return _cache["ffmpeg"]
def ffprobe_path() -> Path | None:
with _lock:
if "ffprobe" not in _cache:
_cache["ffprobe"] = _find("ffprobe")
return _cache["ffprobe"]
def add_to_path() -> None:
"""Put the ffmpeg folder first on PATH of this process (libraries that shell out to ``ffmpeg`` then find it)."""
exe = ffmpeg_path()
if exe:
folder = str(exe.absolute().parent)
if folder not in os.environ.get("PATH", "").split(os.pathsep):
os.environ["PATH"] = folder + os.pathsep + os.environ.get("PATH", "")
def require_ffmpeg() -> Path:
exe = ffmpeg_path()
if not exe:
raise EngineError(
"not_ready",
"ffmpeg was not found. On Windows it ships with the Applio runtime (re-run "
"setup); on Linux/macOS install it (apt install ffmpeg / brew install ffmpeg).",
)
return exe
def _run(
cmd: list[str | Path], timeout: float = 3600.0, data: bytes | None = None
) -> subprocess.CompletedProcess[bytes]:
"""``data`` is fed to stdin, otherwise stdin is closed."""
stdin: dict[str, Any] = {"stdin": subprocess.DEVNULL} if data is None else {"input": data}
try:
return subprocess.run(cmd, capture_output=True, timeout=timeout, creationflags=_FLAGS, check=False, **stdin)
except subprocess.TimeoutExpired as exc:
raise EngineError("internal", "ffmpeg timed out") from exc
except OSError as exc:
raise EngineError("not_ready", f"ffmpeg could not be started: {exc}") from exc
def _tail(err: bytes) -> str:
lines = [ln.strip() for ln in err.decode("utf-8", errors="replace").splitlines() if ln.strip()]
return lines[-1] if lines else "unknown error"
def _no_audio(err: bytes) -> bool:
text = err.decode("utf-8", errors="replace")
return "matches no streams" in text or "does not contain any stream" in text
def _check_file(path: Any) -> Path:
if not isinstance(path, (str, Path)) or path == "":
raise EngineError("bad_request", "'path' must be a file path")
path = Path(path).absolute()
if not path.is_file():
raise EngineError("not_found", f"file not found: {path}")
return path
def probe(path: str | Path) -> dict[str, Any]:
"""``{duration_s, sample_rate, channels, has_audio, format}`` plus ``codec`` and ``has_video``."""
path = _check_file(path)
ext = path.suffix.lower().lstrip(".")
probe_exe = ffprobe_path()
if probe_exe is None:
try: # no ffprobe: libsndfile can still describe plain audio files
info = sf.info(path)
return {
"duration_s": round(info.duration, 3),
"sample_rate": int(info.samplerate),
"channels": int(info.channels),
"has_audio": True,
"format": ext or info.format.lower(),
"codec": info.subtype.lower(),
"has_video": False,
}
except Exception:
require_ffmpeg()
raise EngineError("not_ready", "ffprobe was not found next to ffmpeg") from None
res = _run([probe_exe, "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path], 60)
if res.returncode != 0:
raise EngineError("bad_request", f"This file cannot be read as audio or video ({_tail(res.stderr)}).")
try:
info = json.loads(res.stdout.decode("utf-8", errors="replace"))
except ValueError as exc:
raise EngineError("bad_request", "This file cannot be read as audio or video.") from exc
streams = info.get("streams") or []
audio = next((s for s in streams if s.get("codec_type") == "audio"), None)
has_video = any(
s.get("codec_type") == "video" and not (s.get("disposition") or {}).get("attached_pic") for s in streams
)
fmt = info.get("format") or {}
names = [n for n in str(fmt.get("format_name", "")).split(",") if n]
# The extension the user knows beats ffprobe's "mov,mp4,m4a,3gp,3g2,mj2".
known = _IMPORT_ALIASES.get(ext, ext)
out_fmt = known if known in _IMPORT else (names[0] if names else ext)
duration = _float(fmt.get("duration"))
if not duration and audio is not None:
duration = _float(audio.get("duration"))
sample_rate = int(_float(audio.get("sample_rate"))) if audio else 0
if audio is not None and not duration:
try: # e.g. a webm without a duration header: count the decoded samples
y, sr = read_audio(path, sr=sample_rate or 44100)
duration = len(y) / float(sr)
except EngineError:
duration = 0.0
return {
"duration_s": round(float(duration or 0.0), 3),
"sample_rate": sample_rate,
"channels": int(audio.get("channels") or 0) if audio else 0,
"has_audio": audio is not None,
"format": out_fmt,
"codec": str(audio.get("codec_name", "")) if audio else "",
"has_video": has_video,
}
def is_video(path: str | Path) -> bool:
"""By extension: cheap, no process."""
ext = Path(path).suffix.lower().lstrip(".")
ext = _IMPORT_ALIASES.get(ext, ext)
return ext in _IMPORT and _IMPORT[ext][0] == "video"
def _float(v: Any) -> float:
try:
return float(v)
except (TypeError, ValueError):
return 0.0
def decode_pcm(path: str | Path, sr: int, max_s: float | None = None, channels: int = 1) -> np.ndarray:
"""Ffmpeg decode of the first audio track to float32 at ``sr`` (only the first ``max_s`` seconds if given): mono
``(n,)``, or ``(channels, n)`` with ``channels`` above 1 (ffmpeg up- or down-mixes)."""
exe = require_ffmpeg()
limit = ["-t", f"{float(max_s):.3f}"] if max_s else []
res = _run(
[
exe,
"-nostdin",
"-v",
"error",
"-i",
path,
"-vn",
"-map",
"0:a:0",
"-ac",
str(int(channels)),
"-ar",
str(int(sr)),
*limit,
"-f",
"f32le",
"pipe:1",
]
)
if res.returncode != 0 or not res.stdout:
msg = _tail(res.stderr)
if _no_audio(res.stderr):
raise EngineError("bad_request", "This file has no audio track.")
raise EngineError("bad_request", f"Cannot read this audio file ({msg}).")
y = np.frombuffer(res.stdout, dtype="<f4")
if channels > 1:
y = y[: len(y) - len(y) % channels].reshape(-1, channels).T
y = np.ascontiguousarray(y, dtype=np.float32)
if not np.all(np.isfinite(y)):
y = np.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)
return y
def read_audio(path: str | Path, sr: int | None = None, max_s: float | None = None) -> tuple[np.ndarray, int]:
"""Mono float32 samples and their rate; ``sr=None`` keeps the file's own rate, ``max_s`` bounds the memory of a long
file by reading only its start."""
path = _check_file(path)
ext = path.suffix.lower()
if ext in _NATIVE_EXT:
try:
frames = -1
if max_s:
frames = int(float(max_s) * sf.info(path).samplerate)
data, file_sr = sf.read(path, frames=frames, dtype="float32", always_2d=True)
y = data.mean(axis=1) if data.shape[1] > 1 else data[:, 0]
y = np.ascontiguousarray(y, dtype=np.float32)
if not np.all(np.isfinite(y)):
y = np.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)
if sr is not None and sr != file_sr:
from . import audio_util as au
y, file_sr = au.resample(y, int(file_sr), int(sr)), int(sr)
return y, int(file_sr)
except Exception:
pass
target = sr
if target is None:
try:
target = probe(path)["sample_rate"] or 44100
except EngineError:
target = 44100
return decode_pcm(path, int(target), max_s), int(target)
def decode_to_wav(src: str | Path, dst: str | Path, sr: int = 44100) -> float:
"""Mono 16-bit WAV of the first audio track; returns its duration."""
y, rate = read_audio(src, sr=sr)
if len(y) == 0:
raise EngineError("bad_request", "This file has no audio.")
Path(dst).parent.mkdir(parents=True, exist_ok=True)
sf.write(dst, np.clip(y, -1.0, 1.0), rate, subtype="PCM_16", format="WAV")
return len(y) / float(rate)
def play_wav(src: str | Path, dst: str | Path, sr: int, channels: int | None = None) -> Path:
"""Atomic 16-bit WAV of the first audio track; ``channels=None`` keeps the file's own. ffmpeg streams it, without
ffmpeg libsndfile reads it whole (mono). Blocking: call it on the IO pool."""
dst = Path(dst)
dst.parent.mkdir(parents=True, exist_ok=True)
part = dst.with_name(f"{dst.name}.part-{os.getpid()}-{threading.get_ident()}.wav")
try:
exe = ffmpeg_path()
if exe:
mix = ["-ac", str(int(channels))] if channels else []
res = _run(
[
exe,
"-nostdin",
"-v",
"error",
"-y",
"-i",
src,
"-vn",
"-map",
"0:a:0",
*mix,
"-ar",
str(int(sr)),
"-c:a",
"pcm_s16le",
part,
]
)
if res.returncode != 0 or not part.is_file():
if _no_audio(res.stderr):
raise EngineError("bad_request", "This file has no audio track.")
raise EngineError("internal", f"could not decode {Path(src).name} ({_tail(res.stderr)})")
else:
decode_to_wav(src, part, sr)
part.replace(dst)
finally:
with contextlib.suppress(OSError):
part.unlink(missing_ok=True)
return dst
def _ffmpeg_lists() -> tuple[set[str], set[str], set[str], str]:
with _lock:
if "lists" in _cache:
return _cache["lists"]
exe = ffmpeg_path()
demuxers: set[str] = set()
decoders: set[str] = set()
encoders: set[str] = set()
version = ""
if exe:
def listing(flag: str) -> list[str]:
res = _run([exe, "-hide_banner", flag], 30)
return res.stdout.decode("utf-8", errors="replace").splitlines()
for ln in listing("-formats"):
m = re.match(r"^\s([D ])([E ])\s+(\S+)\s", ln)
if m and m.group(1) == "D":
demuxers.update(m.group(3).split(","))
for ln in listing("-decoders"):
m = re.match(r"^\s(A)\S{5}\s+(\S+)\s", ln)
if m:
decoders.add(m.group(2))
for ln in listing("-encoders"):
m = re.match(r"^\s([AVS])\S{5}\s+(\S+)\s", ln)
if m:
encoders.add(m.group(2))
ver = _run([exe, "-version"], 15).stdout.decode("utf-8", errors="replace").splitlines()
version = ver[0] if ver else ""
out = (demuxers, decoders, encoders, version)
with _lock:
_cache["lists"] = out
return out
VAAPI_DEVICE = "/dev/dri/renderD128"
def caption_fps(path: str | Path) -> str:
"""``fps=N,`` that doubles a picture under 50 fps (each frame shown twice, so motion is unchanged), for burned
captions that fade and slide smoothly; empty when the rate is unknown or already high."""
exe = ffprobe_path()
if not exe:
return ""
try:
res = _run(
[
exe,
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=r_frame_rate",
"-of",
"csv=p=0",
path,
],
30,
)
num, _, den = res.stdout.decode().strip().partition("/")
rate = float(num) / float(den or 1)
except (EngineError, ValueError, ZeroDivisionError):
return ""
return f"fps={rate * 2:.6g}," if 0 < rate < 49 else ""
HWACCEL = ["-hwaccel", "auto"] # decoded frames come back to memory, so every software filter still works
HARDWARE_H264 = ("h264_nvenc", "h264_qsv", "h264_amf", "h264_videotoolbox", "h264_vaapi")
_hw_lock = threading.Lock()
def h264_hardware_args(name: str, quality: int) -> list[str]:
"""``quality``: the constant quality level (lower is better), as x264's CRF scale."""
q = str(quality)
return {
"h264_nvenc": ["-preset", "p4", "-rc", "vbr", "-cq", q, "-b:v", "0"],
"h264_qsv": ["-preset", "veryfast", "-global_quality", q],
"h264_amf": ["-quality", "balanced", "-rc", "cqp", "-qp_i", q, "-qp_p", q, "-qp_b", q],
"h264_videotoolbox": ["-q:v", "65"],
"h264_vaapi": ["-vaapi_device", VAAPI_DEVICE, "-rc_mode", "CQP", "-qp", q],
}[name]
def encoder_format(name: str) -> str:
"""The last filter of a picture for this encoder: VA-API takes its frames uploaded to the device."""
return {"h264_vaapi": "format=nv12,hwupload", "h264_qsv": "format=nv12"}.get(name, "format=yuv420p")
def _hardware_candidates(encoders: set[str]) -> list[str]:
allowed = {
"h264_amf": os.name == "nt",
"h264_videotoolbox": sys.platform == "darwin",
"h264_vaapi": sys.platform.startswith("linux") and Path(VAAPI_DEVICE).exists(),
}
return [n for n in HARDWARE_H264 if n in encoders and allowed.get(n, True)]
def _encodes(exe: Path, name: str) -> bool:
src = ["-f", "lavfi", "-i", "color=c=black:s=256x144:r=25:d=1"]
out = ["-vf", encoder_format(name), "-c:v", name, *h264_hardware_args(name, 23), "-f", "null", "-"]
try:
res = _run([exe, "-nostdin", "-v", "error", *src, *out], 30)
except EngineError:
return False
if res.returncode != 0:
log.info("H.264 encoder %s cannot run here: %s", name, _tail(res.stderr))
return res.returncode == 0
def h264_hardware() -> str | None:
"""The first hardware H.264 encoder that encodes a test second (ffmpeg lists encoders the machine has no device
for); None: none works. Probed once per process. Blocking."""
with _hw_lock:
with _lock:
if "h264_hw" in _cache:
return _cache["h264_hw"]
exe = ffmpeg_path()
found = None
if exe:
found = next((n for n in _hardware_candidates(_ffmpeg_lists()[2]) if _encodes(exe, n)), None)
log.info("H.264 encoder: %s", found or "libx264 (no hardware encoder works here)")
with _lock:
_cache["h264_hw"] = found
return found
def formats() -> dict[str, Any]:
"""The ``formats.list`` reply: what this machine can read and write."""
demuxers, decoders, encoders, version = _ffmpeg_lists()
if not version: # no ffmpeg: libsndfile only
avail = sf.available_formats()
imp = [e for e, k in (("wav", "WAV"), ("flac", "FLAC"), ("ogg", "OGG"), ("aiff", "AIFF")) if k in avail]
exp = [
e
for e, k in (("wav", "WAV"), ("mp3", "MP3"), ("flac", "FLAC"), ("ogg", "OGG"), ("aiff", "AIFF"))
if k in avail
]
return {
"import": imp,
"import_video": [],
"export": exp,
"export_video": [],
"qualities": list(QUALITIES),
"ffmpeg": None,
}
imp, video = [], []
for ext, (kind, dem, dec) in _IMPORT.items():
if any(d in demuxers for d in dem) and any(d in decoders for d in dec):
imp.append(ext)
if kind == "video":
video.append(ext)
exp = [f for f, spec in _EXPORT.items() if any(e in encoders for e in spec["encoders"])]
from . import videoexport
return {
"import": imp,
"import_video": video,
"export": exp,
"export_video": videoexport.containers(encoders),
"qualities": list(QUALITIES),
"ffmpeg": version,
}
@method("formats.list")
def formats_list(ctx: Any, params: dict[str, Any]) -> dict[str, Any]:
return formats()
# Best first; both keep the pitch and sound far cleaner on speech than a phase vocoder. rubberband is only in builds
# with librubberband ("crispness 6" settings), atempo (WSOLA) is in every build.
_STRETCH_FILTERS = (
("rubberband", "rubberband=tempo={rate:.6f}:window=short:phase=independent"),
("atempo", "atempo={rate:.6f}"),
)
def _ffmpeg_filters() -> set[str]:
"""Cached. Blocking: call it on the IO pool."""
with _lock:
if "filters" in _cache:
return _cache["filters"]
exe = ffmpeg_path()
names: set[str] = set()
if exe:
try:
res = _run([exe, "-hide_banner", "-filters"], 30)
for ln in res.stdout.decode("utf-8", errors="replace").splitlines():
# " ..C atempo A->A Adjust ..."; ffmpeg 8 lists two flags: " .. atempo"
m = re.match(r"^\s*[T.][S.][C.]?\s+(\S+)\s+\S*->\S*\s", ln)
if m:
names.add(m.group(1))
except EngineError as exc:
log.warning("could not list the ffmpeg filters: %s", exc.message)
with _lock:
_cache["filters"] = names
return names
def stretch_filters() -> list[str]:
have = _ffmpeg_filters()
return [name for name, _ in _STRETCH_FILTERS if name in have]
def time_stretch(y: np.ndarray, sr: int, rate: float) -> tuple[np.ndarray, str] | None:
"""``y`` played ``rate`` times faster with its pitch kept, and the filter used; ``None`` when no filter works (the
caller keeps the clip). Blocking: call it on the IO pool."""
exe = ffmpeg_path()
if not exe or len(y) == 0:
return None
data = np.ascontiguousarray(y, dtype="<f4").tobytes()
for name in stretch_filters():
graph = dict(_STRETCH_FILTERS)[name].format(rate=float(rate))
cmd = [
exe,
"-v",
"error",
"-f",
"f32le",
"-ar",
str(int(sr)),
"-ac",
"1",
"-i",
"pipe:0",
"-af",
graph,
"-f",
"f32le",
"-ac",
"1",
"pipe:1",
]
try:
res = _run(cmd, 60.0 + 4.0 * len(y) / float(sr), data=data)
except EngineError as exc:
res, err = None, exc.message
else:
err = _tail(res.stderr)
if res is not None and res.returncode == 0 and res.stdout:
out = np.frombuffer(res.stdout, dtype="<f4").astype(np.float32)
if not np.all(np.isfinite(out)):
out = np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0)
return out, name
log.warning("ffmpeg %s failed (%s); not using it again", name, err)
with _lock: # a filter that is listed but broken is dropped for the rest of the session
_cache.get("filters", set()).discard(name)
return None
def export(path: str | Path, fmt: str, dest: str | Path | None = None, quality: str = "standard") -> dict[str, Any]:
path = _check_file(path)
fmt = str(fmt or "").lower().lstrip(".")
fmt = _IMPORT_ALIASES.get(fmt, fmt)
spec = _EXPORT.get(fmt)
if spec is None:
raise EngineError("bad_request", f"unsupported export format {fmt!r} (use {', '.join(_EXPORT)})")
if quality not in QUALITIES:
raise EngineError("bad_request", f"'quality' must be one of {', '.join(QUALITIES)}")
if dest in (None, ""):
dest = path.with_suffix(f".{spec['ext']}")
if dest == path:
dest = path.with_name(f"{path.stem}_export.{spec['ext']}")
elif not isinstance(dest, (str, Path)):
raise EngineError("bad_request", "'dest' must be an absolute file path")
else:
dest = Path(dest)
if not dest.is_absolute():
raise EngineError("bad_request", "'dest' must be an absolute file path")
if dest.is_dir():
raise EngineError("bad_request", "'dest' must be a file path, not a folder")
if dest.resolve() == path.resolve():
raise EngineError("bad_request", "'dest' must differ from the source file")
dest.parent.mkdir(parents=True, exist_ok=True)
# keeps the extension so ffmpeg picks the muxer
tmp = dest.with_name(f"{dest.name}.part-{os.getpid()}.{spec['ext']}")
try:
if ffmpeg_path():
_encode_ffmpeg(path, tmp, fmt, spec, quality)
else:
_encode_soundfile(path, tmp, fmt)
tmp.replace(dest)
finally:
with contextlib.suppress(OSError):
tmp.unlink(missing_ok=True)
return {"path": dest, "size_bytes": dest.stat().st_size}
def _encode_ffmpeg(src: Path, dst: Path, fmt: str, spec: dict[str, Any], quality: str) -> None:
exe = ffmpeg_path()
assert exe
_, _, encoders, _ = _ffmpeg_lists()
args = list(spec["args"])
if fmt == "ogg" and "libvorbis" not in encoders:
if "vorbis" not in encoders:
raise EngineError("not_ready", "this ffmpeg build has no Vorbis encoder")
args = ["-c:a", "vorbis", "-strict", "-2"] # the built-in encoder is experimental, mono/stereo only
elif not any(e in encoders for e in spec["encoders"]):
raise EngineError("not_ready", f"this ffmpeg build cannot encode {fmt}")
args += spec.get("q", {}).get(quality, [])
cmd = [exe, "-nostdin", "-v", "error", "-y", "-i", src, "-vn", "-map", "0:a:0", "-map_metadata", "-1", *args, dst]
res = _run(cmd)
if res.returncode != 0 or not dst.is_file():
msg = _tail(res.stderr)
if _no_audio(res.stderr):
raise EngineError("bad_request", "This file has no audio track.")
raise EngineError("bad_request", f"Could not convert to {fmt} ({msg}).")
def _encode_soundfile(src: Path, dst: Path, fmt: str) -> None:
kinds = {"wav": "WAV", "mp3": "MP3", "flac": "FLAC", "ogg": "OGG", "aiff": "AIFF"}
if fmt not in kinds or kinds[fmt] not in sf.available_formats():
raise EngineError("not_ready", f"ffmpeg was not found and {fmt} cannot be written without it")
data, sr = sf.read(src, dtype="float32", always_2d=True)
sub = {"wav": "PCM_16", "flac": "PCM_16", "aiff": "PCM_16"}.get(fmt)
sf.write(dst, data, sr, format=kinds[fmt], **({"subtype": sub} if sub else {}))
@method("audio.export")
def audio_export(ctx: Any, params: dict[str, Any]) -> dict[str, Any]:
return export(params.get("path"), params.get("format"), params.get("dest"), params.get("quality") or "standard")
PLAY_DIR = "play" # <data>/tmp/play: playback WAVs of results saved in another format (tmp is emptied at start)
def output_format(params: dict[str, Any], key: str = "output_format") -> str:
"""Default ``wav``, checked against what this machine can write. Blocking: call it on the IO pool."""
v = params.get(key)
if v in (None, ""):
return "wav"
if not isinstance(v, str):
raise EngineError("bad_request", f"'{key}' must be one of {', '.join(_EXPORT)}")
fmt = v.lower().lstrip(".")
fmt = _IMPORT_ALIASES.get(fmt, fmt)
if fmt not in _EXPORT:
raise EngineError("bad_request", f"'{key}' must be one of {', '.join(_EXPORT)}")
if fmt != "wav" and fmt not in formats()["export"]:
why = "install ffmpeg" if not ffmpeg_path() else "this ffmpeg build lacks its encoder"
raise EngineError("not_ready", f"{fmt.upper()} cannot be written on this machine ({why})")
return fmt
def save_result(
data: config.DataDir, track: np.ndarray, sr: int, prefix: str, fmt: str, also_free: tuple[str, ...] = ()
) -> dict[str, Any]:
"""The app plays WAV only, so another ``fmt`` also gets a playback WAV in ``<data>/tmp/play/``. ``also_free``: other
extensions the name must be free for. If the encoder fails, the result is kept as WAV (``format`` says so)."""
from . import audio_util as au
ext = _EXPORT[fmt]["ext"]
play_dir = data.tmp / PLAY_DIR
stamp = time.strftime("%Y%m%d_%H%M%S")
name, n = f"{prefix}{stamp}", 1
def taken(nm: str) -> bool:
return (
any((data.outputs / f"{nm}.{e}").exists() for e in (ext, *also_free)) or (play_dir / f"{nm}.wav").exists()
)
while taken(name):
n += 1
name = f"{prefix}{stamp}_{n}"
data.outputs.mkdir(parents=True, exist_ok=True)
path = data.outputs / f"{name}.{ext}"
if fmt == "wav":
au.write_wav(path, track, sr)
return {"path": path, "path_play": path, "format": "wav"}
play = play_dir / f"{name}.wav"
au.write_wav(play, track, sr)
try:
export(play, fmt, path, "high")
except EngineError as exc:
log.warning("saving %s as %s failed (%s): keeping it as WAV", name, fmt, exc.message)
path = data.outputs / f"{name}.wav"
while path.exists():
n += 1
path = data.outputs / f"{prefix}{stamp}_{n}.wav"
shutil.copyfile(play, path)
return {"path": path, "path_play": play, "format": "wav"}
return {"path": path, "path_play": play, "format": fmt}
def _inside(path: str | Path, folder: str | Path) -> bool:
"""``path`` (already resolved) lies inside ``folder`` (resolved here), not ``folder`` itself."""
root = Path(folder).resolve()
p = Path(path)
return p != root and p.is_relative_to(root)
def delete_outputs(data: config.DataDir, paths: list[Any]) -> dict[str, Any]:
"""Delete files in ``<data>/outputs`` and ``<data>/tmp/play`` only: one path outside them refuses the whole request
(``bad_request``). A file already gone is not an error."""
allowed = (data.outputs, data.tmp / PLAY_DIR)
checked: list[Path] = []
for p in paths:
if not isinstance(p, str) or not p or not Path(p).is_absolute():
raise EngineError("bad_request", "'path' must be an absolute file path")
real = Path(p).resolve()
if not any(_inside(real, d) for d in allowed):
raise EngineError(
"bad_request", "only results in the outputs folder (and their playback WAVs) can be deleted"
)
if real.is_dir():
raise EngineError("bad_request", "'path' must be a file, not a folder")
checked.append(real)
# A Redub of a video saves its audio and video under one name, and every result has a .result.json sidecar: they
# are one result and go together.
if _inside(real, data.outputs):
stem = real.stem
try:
for sib in real.parent.iterdir():
same = sib.stem == stem or sib.name == stem + ".result.json"
if same and sib.is_file() and _inside(sib.resolve(), data.outputs):
checked.append(sib.resolve())
except OSError:
pass
deleted: list[Path] = []
for real in dict.fromkeys(checked):
try:
real.unlink()
deleted.append(real)
except FileNotFoundError:
pass
except OSError as exc:
raise EngineError("internal", f"Could not delete {real.name}: {exc.strerror or exc}") from exc
return {"deleted": deleted}
@method("outputs.delete")
def outputs_delete(ctx: Any, params: dict[str, Any]) -> dict[str, Any]:
paths = [params.get("path")]
if params.get("path_play") not in (None, ""):
paths.append(params.get("path_play"))
return delete_outputs(config.data_dir(ctx), paths)