"""FFmpeg do Clipador: áudio dos blocos (volume por segundo + WAV para o Whisper), corte vertical e miniatura. Subprocesso sempre sem shell, argumentos em lista, com timeout; código != 0 é falha.""" from __future__ import annotations import io import math import subprocess import sys import wave from array import array from pathlib import Path from . import layout SAMPLE_RATE = 16_000 NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0 class MediaError(RuntimeError): pass def run(args: list[str], timeout: float, cwd: Path | None = None) -> bytes: try: result = subprocess.run(args, capture_output=True, timeout=timeout, cwd=cwd, creationflags=NO_WINDOW) except subprocess.TimeoutExpired as exc: raise MediaError(f"{Path(args[0]).name} passou de {timeout:.0f} s") from exc if result.returncode != 0: tail = result.stderr.decode("utf-8", errors="replace").strip().splitlines()[-3:] raise MediaError(f"{Path(args[0]).name} saiu com código {result.returncode}: {' | '.join(tail)}") return result.stdout def decode_pcm(ffmpeg: str, files: list[Path]) -> bytes: """Áudio mono 16 kHz s16le dos arquivos, em sequência.""" out = bytearray() for file in files: out += run([ffmpeg, "-v", "error", "-i", str(file), "-vn", "-ac", "1", "-ar", str(SAMPLE_RATE), "-f", "s16le", "-"], 120) return bytes(out) def loudness_per_second(pcm: bytes) -> list[float | None]: """RMS em dBFS por segundo (None = silêncio absoluto).""" samples = array("h") samples.frombytes(pcm[: len(pcm) - len(pcm) % 2]) out: list[float | None] = [] for i in range(0, len(samples), SAMPLE_RATE): chunk = samples[i: i + SAMPLE_RATE] if len(chunk) < SAMPLE_RATE // 4: break rms = math.sqrt(sum(s * s for s in chunk) / len(chunk)) out.append(round(20 * math.log10(rms / 32768), 2) if rms > 0 else None) return out def to_wav(pcm: bytes) -> bytes: buffer = io.BytesIO() with wave.open(buffer, "wb") as wav: wav.setnchannels(1) wav.setsampwidth(2) wav.setframerate(SAMPLE_RATE) wav.writeframes(pcm) return buffer.getvalue() def pick_encoder(ffmpeg: str, wanted: str) -> list[str]: if wanted == "auto": try: encoders = run([ffmpeg, "-hide_banner", "-encoders"], 30).decode(errors="replace") except MediaError: encoders = "" wanted = "h264_nvenc" if "h264_nvenc" in encoders else "libx264" if wanted == "h264_nvenc": return ["-c:v", "h264_nvenc", "-preset", "p5", "-rc", "vbr", "-cq", "23", "-b:v", "0"] return ["-c:v", "libx264", "-preset", "veryfast", "-crf", "21"] def render_vertical(ffmpeg: str, encoder: list[str], segments: list[tuple[Path, float]], start_s: float, end_s: float, ass_text: str, out_file: Path, settings: dict | None = None) -> None: """`segments` = blocos (arquivo, início na sessão) que cobrem [start_s, end_s], em ordem. `settings` = configuração do corte efetiva (layout.merge); define layout, câmera e legenda.""" if not segments: raise MediaError("nenhum bloco gravado cobre o trecho") work = out_file.parent work.mkdir(parents=True, exist_ok=True) stem = out_file.stem # O filtro `ass` recebe o nome relativo (cwd = pasta do corte): caminho absoluto do Windows ("C:\...") # exigiria escapar ":" e "\" dentro do filtergraph. ass_file = work / f"{stem}.ass" ass_file.write_text(ass_text, encoding="utf-8") concat = work / f"{stem}.concat.txt" concat.write_text("".join(f"file '{p.as_posix()}'\n" for p, _ in segments), encoding="utf-8") offset = start_s - segments[0][1] tmp = work / f"{stem}.tmp.mp4" try: run( # -ss ANTES do -i: os quadros entram no filtro já com tempo 0 = início do corte. Depois do -i o # filtro `ass` veria o tempo do bloco e a legenda sairia deslocada (medido: sumia do vídeo). [ffmpeg, "-y", "-v", "error", "-ss", f"{max(0.0, offset):.3f}", "-f", "concat", "-safe", "0", "-i", concat.name, "-t", f"{end_s - start_s:.3f}", "-filter_complex", layout.video_filter(settings or layout.merge(), ass_file.name, ass_text), "-map", "[v]", "-map", "0:a:0?", *encoder, "-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-movflags", "+faststart", tmp.name], timeout=600, cwd=work, ) tmp.replace(out_file) finally: concat.unlink(missing_ok=True) ass_file.unlink(missing_ok=True) tmp.unlink(missing_ok=True) def segment_at(segments: list[tuple[Path, float, float]], t: float) -> tuple[Path, float] | None: """Bloco (arquivo, deslocamento dentro dele) que contém o instante `t` da sessão.""" for file, start, end in segments: if start <= t < end: return file, t - start if segments and t >= segments[-1][2]: file, start, end = segments[-1] return file, max(0.0, end - start - 0.5) return None # Busca num bloco .ts: o demuxer mpegts do FFmpeg trata todo pacote como ponto de busca, então `-ss` antes do `-i` # cai num quadro P perto do alvo. Medido (17/11/2026): no H.264 sai o PRÓXIMO quadro-chave (até 2 s depois do # pedido); no HEVC (2K da Twitch) sai um quadro CINZA (referências faltando) — frames do juiz, capa e YuNet # estragados. Um 2º `-ss` depois do `-i` também erra quando o bloco tem áudio (a base de tempo vem do áudio; 7,5 s # virou 6,06 s). Agora: busca rápida `SEEK_PREROLL_S` antes, tempo absoluto do bloco (`-copyts -start_at_zero`) e # o 1º quadro com t ≥ alvo (`select`). GOP da Twitch = 2 s; o YouTube recomenda ≤ 4 s. O concat (render, proxy) # não tem esse problema: não passa por aqui. SEEK_PREROLL_S = 4.0 def seek_args(offset: float) -> tuple[list[str], str]: """(argumentos antes do `-i`, filtro `select` do quadro exato) para o instante `offset` s de um bloco .ts.""" offset = max(0.0, offset) return (["-ss", f"{max(0.0, offset - SEEK_PREROLL_S):.3f}", "-copyts", "-start_at_zero"], f"select='gte(t,{offset:.3f})'") def grab_frame(ffmpeg: str, segments: list[tuple[Path, float, float]], t: float, out_file: Path, width: int = 768) -> Path: """Um quadro do instante `t` (sessão) em JPG. Para a IA olhar a tela e para o editor de layout.""" found = segment_at(segments, t) if not found: raise MediaError(f"nenhum bloco gravado em {t:.0f}s") file, offset = found out_file.parent.mkdir(parents=True, exist_ok=True) before, select = seek_args(offset) vf = select + (f",scale={width}:-2" if width else "") run([ffmpeg, "-y", "-v", "error", *before, "-i", str(file), "-map", "0:v:0", "-vf", vf, "-frames:v", "1", "-q:v", "4", str(out_file)], 60) return out_file def preview_still(ffmpeg: str, frame_file: Path, settings: dict, ass_text: str, out_file: Path, reframe=None) -> Path: """Prévia do layout num quadro só (imagem no formato do corte com câmera, jogo, legenda e crédito de exemplo). `reframe` = reenquadramento parado do jogo (capa de um corte com keyframes; ver `reframe.static_reframe`).""" work = out_file.parent ass_file = work / f"{out_file.stem}.ass" ass_file.write_text(ass_text, encoding="utf-8") try: run([ffmpeg, "-y", "-v", "error", "-loop", "1", "-t", "1", "-i", frame_file.name, "-filter_complex", layout.video_filter(settings, ass_file.name, ass_text, reframe), "-map", "[v]", "-frames:v", "1", "-q:v", "3", out_file.name], 60, cwd=work) finally: ass_file.unlink(missing_ok=True) return out_file def thumbnail(ffmpeg: str, video: Path, at_s: float, out_file: Path) -> None: run([ffmpeg, "-y", "-v", "error", "-ss", f"{max(0.0, at_s):.2f}", "-i", str(video), "-frames:v", "1", "-vf", "scale=360:-2", "-q:v", "4", str(out_file)], 60) def probe_size(ffprobe: str, file: Path) -> tuple[int, int]: """(largura, altura) do vídeo; 1280×720 se não der para ler (as camadas inseridas usam a proporção).""" try: out = run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", str(file)], 30).decode().strip().split(",") return int(out[0]), int(out[1]) except (MediaError, ValueError, IndexError): return 1280, 720 def probe_duration(ffprobe: str, file: Path) -> float: out = run([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(file)], 30) return float(out.decode().strip() or 0)