CenaForge: primeira versão pública

Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 16:35:09 -03:00
co-authored by Claude Opus 5.5
commit 84f30bbc2d
484 changed files with 74826 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
// Leitura mínima de argumentos: --chave valor, --chave=valor e --flag.
// Um "--" solto (que o pnpm pode repassar) é ignorado.
export type ParsedArgs = { positional: string[]; options: Map<string, string | true> };
export function parseArgs(argv: string[]): ParsedArgs {
const positional: string[] = [];
const options = new Map<string, string | true>();
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--") continue;
if (arg.startsWith("--")) {
const body = arg.slice(2);
const eq = body.indexOf("=");
if (eq >= 0) {
options.set(body.slice(0, eq), body.slice(eq + 1));
} else if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) {
options.set(body, argv[++i]);
} else {
options.set(body, true);
}
} else {
positional.push(arg);
}
}
return { positional, options };
}
export function stringOption(args: ParsedArgs, name: string): string | undefined {
const value = args.options.get(name);
if (value === undefined) return undefined;
if (value === true) throw new UsageError(`--${name} exige um valor`);
return value;
}
export function numberOption(args: ParsedArgs, name: string): number | undefined {
const raw = stringOption(args, name);
if (raw === undefined) return undefined;
const value = Number(raw);
if (!Number.isFinite(value)) throw new UsageError(`--${name} precisa ser número (recebido "${raw}")`);
return value;
}
export class UsageError extends Error {}
+55
View File
@@ -0,0 +1,55 @@
// Áudio opcional fornecido pelo usuário. Composto no FFmpeg, fora da Godot.
// Não gera narração nem integra com Applio: só aceita um arquivo indicado.
import fs from "node:fs";
import { resolveFromRoot } from "./paths.ts";
import { runProcess, succeeded, describeFailure } from "./process.ts";
import type { Tool } from "./tools.ts";
export type AudioConfig = { enabled: boolean; file: string | null; offsetSeconds?: number };
export type AudioPlan = {
file: string;
sourceDurationSeconds: number;
offsetSeconds: number;
sceneDurationSeconds: number;
/** Segundos do áudio que ficariam além do fim da cena e serão cortados. */
cutSeconds: number;
warnings: string[];
};
export class AudioError extends Error {}
export async function planAudio(audio: AudioConfig | undefined, sceneDurationSeconds: number, ffprobe: Tool): Promise<AudioPlan | null> {
if (!audio || !audio.enabled) return null;
if (!audio.file) throw new AudioError("audio.enabled = true, mas audio.file está vazio");
const file = resolveFromRoot(audio.file);
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) {
throw new AudioError(`arquivo de áudio não encontrado: ${audio.file} (caminhos relativos partem da raiz do projeto)`);
}
const r = await runProcess(ffprobe.path, ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file], { timeoutMs: 60_000 });
if (!succeeded(r)) throw new AudioError(describeFailure("ffprobe (áudio)", r));
const duration = Number(r.stdout.trim());
if (!Number.isFinite(duration) || duration <= 0) throw new AudioError(`não foi possível obter a duração de ${audio.file}`);
const offset = audio.offsetSeconds ?? 0;
const cut = Math.max(0, offset + duration - sceneDurationSeconds);
const warnings: string[] = [];
if (cut > 0.0005) {
warnings.push(`o áudio termina ${cut.toFixed(2)} s depois do fim da cena e será CORTADO em ${sceneDurationSeconds} s (a duração da cena não foi alterada; ajuste durationSeconds ou o áudio se quiser ouvir tudo)`);
}
return { file, sourceDurationSeconds: duration, offsetSeconds: offset, sceneDurationSeconds, cutSeconds: cut, warnings };
}
/**
* Argumentos do FFmpeg para o áudio (entrada #1). O áudio é atrasado pelo
* offset, completado com silêncio e limitado à duração da cena. Sem -shortest:
* o vídeo nunca é truncado quando o áudio acaba antes.
*/
export function audioFfmpegArgs(plan: AudioPlan): { inputs: string[]; mapping: string[] } {
const delayMs = Math.round(plan.offsetSeconds * 1000);
const filter = `[1:a]adelay=delays=${delayMs}:all=1,apad,atrim=end=${plan.sceneDurationSeconds},asetpts=PTS-STARTPTS[aout]`;
return {
inputs: ["-i", plan.file],
mapping: ["-filter_complex", filter, "-map", "0:v", "-map", "[aout]", "-c:a", "aac", "-b:a", "192k", "-ar", "48000"],
};
}
+77
View File
@@ -0,0 +1,77 @@
// Conferência da sequência PNG do Movie Maker antes da conversão.
// Padrão confirmado na Godot 4.7.2: <base>%08d.png começando em 0, mais <base>.wav.
import fs from "node:fs";
import path from "node:path";
export const FRAME_PATTERN = /^frame(\d{8})\.png$/;
export const FFMPEG_FRAME_PATTERN = "frame%08d.png";
/** PNG de 540x960 com conteúdo real tem dezenas de KB; abaixo disto é suspeito. */
const MIN_FRAME_BYTES = 2048;
export type FrameCheck = {
ok: boolean;
count: number;
firstIndex: number | null;
lastIndex: number | null;
problems: string[];
firstSceneFrameSize?: { width: number; height: number };
lastFrameSize?: { width: number; height: number };
};
export function checkFrames(dir: string, expectedTotal: number, expectedSize: { width: number; height: number }, firstSceneIndex: number): FrameCheck {
const problems: string[] = [];
const indices = fs.existsSync(dir)
? fs.readdirSync(dir).map((f) => FRAME_PATTERN.exec(f)).filter((m): m is RegExpExecArray => m !== null).map((m) => Number(m[1])).sort((a, b) => a - b)
: [];
const check: FrameCheck = {
ok: false,
count: indices.length,
firstIndex: indices[0] ?? null,
lastIndex: indices.at(-1) ?? null,
problems,
};
if (indices.length === 0) {
problems.push("nenhum PNG no padrão frame%08d.png");
return check;
}
if (indices[0] !== 0) problems.push(`primeiro índice é ${indices[0]}, esperado 0`);
for (let i = 1; i < indices.length; i++) {
if (indices[i] !== indices[i - 1] + 1) {
problems.push(`sequência com lacuna entre ${indices[i - 1]} e ${indices[i]}`);
break;
}
}
if (indices.length !== expectedTotal) problems.push(`${indices.length} PNGs, esperado ${expectedTotal}`);
const fileOf = (i: number) => path.join(dir, `frame${String(i).padStart(8, "0")}.png`);
if (firstSceneIndex <= (check.lastIndex ?? -1)) {
check.firstSceneFrameSize = readPngSize(fileOf(firstSceneIndex)) ?? undefined;
check.lastFrameSize = readPngSize(fileOf(check.lastIndex!)) ?? undefined;
for (const [label, size] of [["primeiro quadro da cena", check.firstSceneFrameSize], ["último quadro", check.lastFrameSize]] as const) {
if (!size) problems.push(`${label}: PNG ilegível`);
else if (size.width !== expectedSize.width || size.height !== expectedSize.height) {
problems.push(`${label}: ${size.width}x${size.height}, esperado ${expectedSize.width}x${expectedSize.height}`);
}
}
}
const tiny = indices.filter((i) => fs.statSync(fileOf(i)).size < MIN_FRAME_BYTES);
if (tiny.length > 0) problems.push(`${tiny.length} PNG(s) suspeitos de vazio (< ${MIN_FRAME_BYTES} bytes), ex.: índice ${tiny[0]}`);
check.ok = problems.length === 0;
return check;
}
/** Lê largura/altura do cabeçalho IHDR, sem decodificar a imagem. */
export function readPngSize(file: string): { width: number; height: number } | null {
try {
const fd = fs.openSync(file, "r");
const buf = Buffer.alloc(24);
fs.readSync(fd, buf, 0, 24, 0);
fs.closeSync(fd);
const signature = buf.subarray(0, 8).toString("hex");
if (signature !== "89504e470d0a1a0a" || buf.subarray(12, 16).toString("ascii") !== "IHDR") return null;
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
} catch {
return null;
}
}
+31
View File
@@ -0,0 +1,31 @@
// Caminhos do projeto. Tudo que é relativo resolve a partir da RAIZ DO
// REPOSITÓRIO (pasta que contém package.json e godot/), nunca do diretório em
// que o comando foi chamado. A cena Godot usa a mesma regra.
import path from "node:path";
import { fileURLToPath } from "node:url";
export const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
export const GODOT_PROJECT_DIR = path.join(REPO_ROOT, "godot");
export const GODOT_OVERRIDE_FILE = path.join(GODOT_PROJECT_DIR, "override.cfg");
export const OUTPUT_DIR = path.join(REPO_ROOT, "output");
export const RUNS_DIR = path.join(OUTPUT_DIR, "runs");
export const LOCK_FILE = path.join(OUTPUT_DIR, ".render.lock");
export const LAST_SUCCESS_FILE = path.join(OUTPUT_DIR, "last-success.json");
export const LOCAL_TOOLS_DIR = path.join(REPO_ROOT, ".tools");
export function resolveFromRoot(p: string): string {
return path.isAbsolute(p) ? path.normalize(p) : path.resolve(REPO_ROOT, p);
}
/** Caminho para relatórios: relativo à raiz quando possível, com "/". */
export function displayPath(p: string): string {
const rel = path.relative(REPO_ROOT, p);
if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return p;
return rel.split(path.sep).join("/");
}
/** Para executáveis fora do projeto, registra só o nome do arquivo (sem pasta pessoal). */
export function displayToolPath(p: string): string {
const shown = displayPath(p);
return shown === p ? path.basename(p) : shown;
}
+126
View File
@@ -0,0 +1,126 @@
// Execução de subprocessos sem shell: argumentos vão como lista (espaços em
// caminhos funcionam e nada do JSON vira comando). Um código de saída diferente
// de zero, timeout, cancelamento ou falha ao iniciar NUNCA conta como sucesso.
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
export type RunOptions = {
cwd?: string;
timeoutMs?: number;
/** Recebe cada pedaço de stdout/stderr conforme chega (para o render.log). */
onOutput?: (stream: "stdout" | "stderr", chunk: string) => void;
/** Herda o terminal (prévia interativa). */
inheritStdio?: boolean;
};
export type RunResult = {
command: string;
args: string[];
exitCode: number | null;
signal: NodeJS.Signals | null;
stdout: string;
stderr: string;
timedOut: boolean;
cancelled: boolean;
spawnError?: string;
durationMs: number;
};
const MAX_CAPTURE = 8 * 1024 * 1024;
const active = new Set<ChildProcess>();
let cancelRequested = false;
export function runProcess(command: string, args: string[], options: RunOptions = {}): Promise<RunResult> {
const started = Date.now();
return new Promise((resolve) => {
let stdout = "";
let stderr = "";
let timedOut = false;
let settled = false;
const result = (partial: Partial<RunResult>): RunResult => ({
command, args, exitCode: null, signal: null, stdout, stderr, timedOut,
cancelled: cancelRequested, durationMs: Date.now() - started, ...partial,
});
if (cancelRequested) {
resolve(result({ cancelled: true, spawnError: "cancelado antes de iniciar" }));
return;
}
let child: ChildProcess;
try {
child = spawn(command, args, {
cwd: options.cwd,
shell: false,
windowsHide: !options.inheritStdio,
stdio: options.inheritStdio ? "inherit" : ["ignore", "pipe", "pipe"],
});
} catch (error) {
resolve(result({ spawnError: (error as Error).message }));
return;
}
active.add(child);
const timer = options.timeoutMs
? setTimeout(() => {
timedOut = true;
killTree(child);
}, options.timeoutMs)
: undefined;
child.stdout?.setEncoding("utf8");
child.stderr?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
if (stdout.length < MAX_CAPTURE) stdout += chunk;
options.onOutput?.("stdout", chunk);
});
child.stderr?.on("data", (chunk: string) => {
if (stderr.length < MAX_CAPTURE) stderr += chunk;
options.onOutput?.("stderr", chunk);
});
const finish = (partial: Partial<RunResult>) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
active.delete(child);
resolve(result(partial));
};
child.on("error", (error) => finish({ spawnError: error.message }));
child.on("close", (code, signal) => finish({ exitCode: code, signal }));
});
}
export function succeeded(r: RunResult): boolean {
return r.exitCode === 0 && !r.timedOut && !r.cancelled && r.spawnError === undefined;
}
/** Mensagem curta e útil para o usuário, com o fim do stderr. */
export function describeFailure(label: string, r: RunResult): string {
let reason: string;
if (r.cancelled) reason = "cancelado pelo usuário";
else if (r.spawnError) reason = `não iniciou: ${r.spawnError}`;
else if (r.timedOut) reason = `excedeu o tempo limite (${Math.round(r.durationMs / 1000)} s)`;
else reason = `saiu com código ${r.exitCode}${r.signal ? ` (sinal ${r.signal})` : ""}`;
const tail = (r.stderr || r.stdout).trim().split(/\r?\n/).slice(-8).join("\n");
return `${label} ${reason}${tail ? `\n${tail}` : ""}`;
}
/** Cancelamento (Ctrl+C): encerra todos os subprocessos ativos e impede novos. */
export function cancelActiveProcesses(): void {
cancelRequested = true;
for (const child of active) killTree(child);
}
export function resetCancellation(): void {
cancelRequested = false;
}
function killTree(child: ChildProcess): void {
if (child.pid === undefined || child.exitCode !== null) return;
if (process.platform === "win32") {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
} else {
child.kill("SIGTERM");
setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), 3000).unref();
}
}
+418
View File
@@ -0,0 +1,418 @@
// Pipeline de render: validação -> Godot (Movie Maker, PNG) -> conferência dos
// quadros -> FFmpeg (MP4) -> FFprobe -> quadros de inspeção -> relatório.
//
// Cada execução ganha uma pasta única em output/runs/ e nunca sobrescreve a
// anterior. Só um render por vez (output/.render.lock). Em falha ou
// cancelamento a pasta fica marcada como incompleta e o último sucesso
// (output/last-success.json) continua apontando para o render válido anterior.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
GODOT_OVERRIDE_FILE, GODOT_PROJECT_DIR, LAST_SUCCESS_FILE, LOCK_FILE, RUNS_DIR,
displayPath, displayToolPath, resolveFromRoot,
} from "./paths.ts";
import { cancelActiveProcesses, describeFailure, runProcess, succeeded, type RunResult } from "./process.ts";
import { chooseVideoEncoder, ffmpegEncoders, findTool, toolVersion, type Tool } from "./tools.ts";
import { checkFrames, FFMPEG_FRAME_PATTERN } from "./frames.ts";
import { evaluateProbe, probeVideo, type Check } from "./verify.ts";
import { audioFfmpegArgs, planAudio, type AudioConfig, type AudioPlan } from "./audio.ts";
export const PROFILES = {
preview: { width: 540, height: 960 },
final: { width: 1080, height: 1920 },
} as const;
export type ProfileName = keyof typeof PROFILES;
export type RenderOptions = {
configPath: string;
profile: ProfileName;
keepFrames: boolean;
debugFrameIndex: boolean;
warmupFrames: number;
};
/** Momentos extraídos do MP4 para conferência visual (limitados à duração). */
const INSPECTION_TIMES = [0.5, 4, 8, 11];
/** Altura da janela durante o render; o viewport interno tem o tamanho do perfil. */
const RENDER_WINDOW_HEIGHT = 720;
/** Luminância média mínima (0–255) para um quadro não ser considerado preto. */
const MIN_AVERAGE_LUMA = 20;
// Cenas 2D do documentário têm fundo escuro de propósito (#0d0d10 ≈ 13): só reprova quadro totalmente preto.
const MIN_AVERAGE_LUMA_DOC2D = 4;
type Stage = "setup" | "validate" | "audio" | "render" | "frames" | "encode" | "verify" | "inspect" | "done";
class StageError extends Error {
constructor(readonly stage: Stage, message: string) {
super(message);
}
}
export async function render(options: RenderOptions): Promise<number> {
const startedAt = new Date();
const configPath = resolveFromRoot(options.configPath);
const profile = PROFILES[options.profile];
// --- leitura e perfil ------------------------------------------------------
let raw: Record<string, unknown>;
try {
raw = JSON.parse(fs.readFileSync(configPath, "utf8"));
} catch (error) {
console.error(`Não foi possível ler ${options.configPath}: ${(error as Error).message}`);
return 2;
}
const scene = applyProfile(raw, profile);
const video = scene.video as { width: number; height: number; fps: number; durationSeconds: number };
// kind "doc2d"/"doc3d": cenas do documentário (godot/scenes/doc.tscn); sem kind: a rua 3D (cena principal).
const doc2d = scene.kind === "doc2d" || scene.kind === "doc3d";
const sceneArgs = doc2d ? ["res://scenes/doc.tscn"] : [];
const configId = typeof scene.id === "string" && /^[a-z0-9][a-z0-9_-]*$/.test(scene.id) ? scene.id : "cena";
fs.mkdirSync(RUNS_DIR, { recursive: true });
const release = acquireLock();
if (typeof release === "string") {
console.error(release);
return 3;
}
const runDir = createRunDir(startedAt, configId, options.profile);
const framesDir = path.join(runDir, "frames");
const inspectDir = path.join(runDir, "inspect");
const sceneFile = path.join(runDir, "scene.json");
const manifestFile = path.join(runDir, "godot-manifest.json");
const logFile = path.join(runDir, "render.log");
const mp4File = path.join(runDir, `${configId}-${options.profile}.mp4`);
fs.mkdirSync(framesDir);
fs.writeFileSync(sceneFile, JSON.stringify(scene, null, 2) + "\n");
const log = fs.createWriteStream(logFile);
const report: Record<string, unknown> = {
status: "running",
runId: path.basename(runDir),
profile: options.profile,
configSource: displayPath(configPath),
sceneFile: displayPath(sceneFile),
startedAt: startedAt.toISOString(),
video: { width: profile.width, height: profile.height, fps: video.fps, durationSeconds: video.durationSeconds },
host: { platform: `${os.type()} ${os.release()}`, cpu: os.cpus()[0]?.model.trim(), ramGB: Math.round(os.totalmem() / 2 ** 30), node: process.version },
timingsSeconds: {} as Record<string, number>,
checks: [] as Check[],
warnings: [] as string[],
};
const timings = report.timingsSeconds as Record<string, number>;
const checks = report.checks as Check[];
const warnings = report.warnings as string[];
const writeReport = () => fs.writeFileSync(path.join(runDir, "report.json"), JSON.stringify(report, null, 2) + "\n");
writeReport();
let cancelled = false;
const onSigint = () => {
cancelled = true;
console.error("\nCancelando: encerrando subprocessos...");
cancelActiveProcesses();
};
process.on("SIGINT", onSigint);
const step = async (label: string, command: Tool, args: string[], stage: Stage, timeoutMs: number): Promise<RunResult> => {
log.write(`\n=== ${label} ===\n$ ${displayToolPath(command.path)} ${args.map(quoteForLog).join(" ")}\n`);
const r = await runProcess(command.path, args, { cwd: GODOT_PROJECT_DIR, timeoutMs, onOutput: (_s, chunk) => log.write(chunk) });
log.write(`\n[${label}] código=${r.exitCode} tempo=${(r.durationMs / 1000).toFixed(2)}s${r.timedOut ? " TIMEOUT" : ""}${r.cancelled ? " CANCELADO" : ""}\n`);
timings[stageKey(label)] = round(r.durationMs / 1000);
if (!succeeded(r)) throw new StageError(stage, describeFailure(label, r));
return r;
};
let wroteOverride = false;
let exitCode = 1;
try {
console.log(`Render ${options.profile} de ${displayPath(configPath)} -> ${displayPath(runDir)}`);
// --- ferramentas ----------------------------------------------------------
let godot: Tool, ffmpeg: Tool, ffprobe: Tool;
try {
godot = findTool("godot");
ffmpeg = findTool("ffmpeg");
ffprobe = findTool("ffprobe");
} catch (error) {
throw new StageError("setup", (error as Error).message);
}
const encoders = await ffmpegEncoders(ffmpeg);
const encoder = chooseVideoEncoder(encoders);
report.tools = {
godot: { path: displayToolPath(godot.path), source: godot.source, version: await toolVersion(godot) },
ffmpeg: { path: displayToolPath(ffmpeg.path), source: ffmpeg.source, version: await toolVersion(ffmpeg), videoEncoder: encoder.name },
ffprobe: { path: displayToolPath(ffprobe.path), source: ffprobe.source, version: await toolVersion(ffprobe) },
};
if (encoder.name !== "libx264") warnings.push(`libx264 indisponível; usando ${encoder.name}`);
writeReport();
// --- validação (headless, sem GPU) ---------------------------------------
console.log("1/6 Validando a configuração (Godot headless)...");
await step("godot validate", godot, ["--headless", "--path", GODOT_PROJECT_DIR, ...sceneArgs, "--", "--config", sceneFile, "--validate-only"], "validate", 120_000);
// --- áudio opcional -------------------------------------------------------
let audioPlan: AudioPlan | null = null;
try {
audioPlan = await planAudio(scene.audio as AudioConfig | undefined, video.durationSeconds, ffprobe);
} catch (error) {
throw new StageError("audio", (error as Error).message);
}
if (audioPlan) {
warnings.push(...audioPlan.warnings);
report.audio = { file: displayPath(audioPlan.file), sourceDurationSeconds: audioPlan.sourceDurationSeconds, offsetSeconds: audioPlan.offsetSeconds, cutSeconds: round(audioPlan.cutSeconds) };
for (const w of audioPlan.warnings) console.warn(`AVISO: ${w}`);
}
// --- render na Godot ------------------------------------------------------
// O Movie Maker fixa a resolução na inicialização a partir do viewport do
// projeto; o override.cfg temporário define o tamanho do perfil e uma
// janela menor que cabe na tela.
const windowWidth = Math.round((RENDER_WINDOW_HEIGHT * profile.width) / profile.height);
fs.writeFileSync(GODOT_OVERRIDE_FILE, [
"; Gerado pelo lançador durante um render. Removido ao final.",
"[display]",
`window/size/viewport_width=${profile.width}`,
`window/size/viewport_height=${profile.height}`,
`window/size/window_width_override=${windowWidth}`,
`window/size/window_height_override=${RENDER_WINDOW_HEIGHT}`,
'window/stretch/mode="viewport"',
'window/stretch/aspect="keep"',
"",
].join("\n"));
wroteOverride = true;
const expectedFrames = Math.round(video.fps * video.durationSeconds);
const totalPngs = expectedFrames + options.warmupFrames;
console.log(`2/6 Renderizando ${expectedFrames} quadros (+${options.warmupFrames} de aquecimento) em ${profile.width}x${profile.height} @ ${video.fps} FPS...`);
const godotArgs = [
"--path", GODOT_PROJECT_DIR,
...sceneArgs,
"--write-movie", path.join(framesDir, "frame.png"),
"--fixed-fps", String(video.fps),
"--disable-vsync",
"--", "--config", sceneFile, "--manifest", manifestFile, "--warmup-frames", String(options.warmupFrames),
...(options.debugFrameIndex ? ["--debug-frame-index"] : []),
];
const renderTimeout = Math.max(10 * 60_000, totalPngs * 3_000);
const godotRun = await step("godot render", godot, godotArgs, "render", renderTimeout);
fs.rmSync(GODOT_OVERRIDE_FILE, { force: true });
wroteOverride = false;
// A Godot anuncia resolução/FPS efetivos; conferimos contra o perfil.
const announced = /recording movie in (\d+)\D(\d+) @ (\d+) FPS/.exec(godotRun.stdout);
checks.push({
name: "Movie Maker: resolução e FPS anunciados",
ok: !!announced && Number(announced[1]) === profile.width && Number(announced[2]) === profile.height && Number(announced[3]) === video.fps,
detail: announced ? `${announced[1]}x${announced[2]} @ ${announced[3]} FPS` : "linha não encontrada no log",
});
const manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record<string, any>;
report.godot = {
renderer: manifest.renderer,
wallClockSeconds: manifest.wallClockSeconds,
stateDigest: manifest.stateDigest,
scene: manifest.scene,
finalDistanceMeters: manifest.finalDistanceMeters,
cruiseSpeedMetersPerSecond: manifest.cruiseSpeedMetersPerSecond,
};
checks.push({
name: "Godot: quadros de cena",
ok: manifest.framesRendered === expectedFrames && manifest.pngFramesWritten === totalPngs,
detail: `${manifest.framesRendered} de cena + ${manifest.warmupFrames} de aquecimento (esperado ${expectedFrames} + ${options.warmupFrames})`,
});
if (!doc2d) {
checks.push({
name: "moto termina no ponto configurado",
ok: Math.abs(manifest.finalDistanceMeters - manifest.travelMeters) < 1e-6,
detail: `${manifest.finalDistanceMeters} m de ${manifest.travelMeters} m`,
});
}
failIfAnyCheckFailed(checks, "render");
// --- quadros --------------------------------------------------------------
console.log("3/6 Conferindo a sequência PNG...");
const frameCheck = checkFrames(framesDir, totalPngs, profile, options.warmupFrames);
report.frames = { pattern: FFMPEG_FRAME_PATTERN, count: frameCheck.count, firstIndex: frameCheck.firstIndex, lastIndex: frameCheck.lastIndex, firstSceneIndex: options.warmupFrames };
checks.push({ name: "sequência PNG completa e contínua", ok: frameCheck.ok, detail: frameCheck.ok ? `${frameCheck.count} arquivos, índices ${frameCheck.firstIndex}..${frameCheck.lastIndex}` : frameCheck.problems.join("; ") });
failIfAnyCheckFailed(checks, "frames");
// --- conversão ------------------------------------------------------------
console.log(`4/6 Convertendo para MP4 (${encoder.name})...`);
const partial = mp4File.replace(/\.mp4$/, ".partial.mp4");
const audioArgs = audioPlan ? audioFfmpegArgs(audioPlan) : null;
await step("ffmpeg encode", ffmpeg, [
"-hide_banner", "-y",
"-framerate", String(video.fps),
"-start_number", String(options.warmupFrames),
"-i", path.join(framesDir, FFMPEG_FRAME_PATTERN),
...(audioArgs ? audioArgs.inputs : []),
"-frames:v", String(expectedFrames),
...encoder.args,
"-pix_fmt", "yuv420p",
"-r", String(video.fps),
...(audioArgs ? audioArgs.mapping : ["-an"]),
"-movflags", "+faststart",
partial,
], "encode", 15 * 60_000);
fs.renameSync(partial, mp4File);
report.mp4 = displayPath(mp4File);
// --- verificação ----------------------------------------------------------
console.log("5/6 Verificando com FFprobe...");
const t0 = Date.now();
const probe = await probeVideo(ffprobe, mp4File);
timings.ffprobe = round((Date.now() - t0) / 1000);
report.probe = probe;
checks.push(...evaluateProbe(probe, {
width: profile.width, height: profile.height, fps: video.fps,
durationSeconds: video.durationSeconds, frames: expectedFrames, audio: audioPlan !== null,
}));
failIfAnyCheckFailed(checks, "verify");
// --- quadros de inspeção --------------------------------------------------
console.log("6/6 Extraindo quadros de inspeção do MP4...");
fs.mkdirSync(inspectDir);
const times = INSPECTION_TIMES.filter((t) => t < video.durationSeconds);
const images: string[] = [];
for (const t of times) {
const out = path.join(inspectDir, `t${t.toFixed(2).padStart(5, "0")}s.png`);
await step(`ffmpeg inspect ${t}s`, ffmpeg, ["-hide_banner", "-y", "-ss", String(t), "-i", mp4File, "-frames:v", "1", out], "inspect", 60_000);
const luma = await averageLuma(ffmpeg, out);
checks.push({ name: `quadro em ${t}s não está preto`, ok: luma >= (doc2d ? MIN_AVERAGE_LUMA_DOC2D : MIN_AVERAGE_LUMA), detail: `luminância média ${luma.toFixed(1)}` });
images.push(out);
}
if (images.length > 1) {
const sheet = path.join(inspectDir, "contact-sheet.png");
await step("ffmpeg contact sheet", ffmpeg, [
"-hide_banner", "-y", ...images.flatMap((i) => ["-i", i]),
"-filter_complex", `hstack=inputs=${images.length},scale=-2:480`, sheet,
], "inspect", 60_000);
images.push(sheet);
}
report.inspection = images.map(displayPath);
failIfAnyCheckFailed(checks, "inspect");
// --- limpeza e sucesso ----------------------------------------------------
if (!options.keepFrames) {
fs.rmSync(framesDir, { recursive: true, force: true });
(report.frames as Record<string, unknown>).deletedAfterSuccess = true;
} else {
fs.rmSync(path.join(framesDir, "frame.wav"), { force: true });
}
report.status = "success";
exitCode = 0;
fs.writeFileSync(LAST_SUCCESS_FILE, JSON.stringify({ runDir: displayPath(runDir), mp4: displayPath(mp4File), profile: options.profile, finishedAt: new Date().toISOString() }, null, 2) + "\n");
} catch (error) {
const stage = error instanceof StageError ? error.stage : "setup";
report.status = cancelled ? "cancelled" : "failed";
report.failedStage = stage;
report.error = (error as Error).message;
exitCode = cancelled ? 130 : 1;
console.error(`\n${cancelled ? "CANCELADO" : "FALHOU"} na etapa "${stage}": ${(error as Error).message}`);
console.error(`Quadros e log preservados em ${displayPath(runDir)} para diagnóstico.`);
} finally {
if (wroteOverride) fs.rmSync(GODOT_OVERRIDE_FILE, { force: true });
process.off("SIGINT", onSigint);
const finishedAt = new Date();
report.finishedAt = finishedAt.toISOString();
timings.total = round((finishedAt.getTime() - startedAt.getTime()) / 1000);
writeReport();
await new Promise<void>((resolve) => log.end(resolve));
release();
}
printSummary(report, runDir);
return exitCode;
}
/** Copia a configuração aplicando o tamanho do perfil. O resto fica como está. */
export function applyProfile(raw: Record<string, unknown>, profile: { width: number; height: number }): Record<string, unknown> {
const copy = structuredClone(raw);
const video = (typeof copy.video === "object" && copy.video !== null ? copy.video : {}) as Record<string, unknown>;
video.width = profile.width;
video.height = profile.height;
copy.video = video;
return copy;
}
function failIfAnyCheckFailed(checks: Check[], stage: Stage): void {
const failed = checks.filter((c) => !c.ok);
if (failed.length > 0) throw new StageError(stage, failed.map((c) => `${c.name}: ${c.detail}`).join("; "));
}
async function averageLuma(ffmpeg: Tool, image: string): Promise<number> {
const r = await runProcess(ffmpeg.path, ["-hide_banner", "-i", image, "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG", "-f", "null", "-"], { timeoutMs: 60_000 });
const match = /lavfi\.signalstats\.YAVG=([\d.]+)/.exec(r.stderr + r.stdout);
return match ? Number(match[1]) : 0;
}
function createRunDir(date: Date, configId: string, profile: string): string {
const stamp = date.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
const base = path.join(RUNS_DIR, `${stamp}-${configId}-${profile}`);
for (let n = 0; n < 100; n++) {
const candidate = n === 0 ? base : `${base}-${n}`;
try {
fs.mkdirSync(candidate);
return candidate;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
}
throw new Error("não foi possível criar uma pasta de execução única");
}
/** Trava de render único. Devolve a função de liberação ou a mensagem de erro. */
export function acquireLock(lockFile = LOCK_FILE): (() => void) | string {
fs.mkdirSync(path.dirname(lockFile), { recursive: true });
for (let attempt = 0; attempt < 2; attempt++) {
try {
const fd = fs.openSync(lockFile, "wx");
fs.writeSync(fd, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }));
fs.closeSync(fd);
return () => fs.rmSync(lockFile, { force: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
let holder = 0;
try {
holder = Number(JSON.parse(fs.readFileSync(lockFile, "utf8")).pid);
} catch {
// Trava ilegível: tratada como abandonada.
}
if (holder && isAlive(holder)) return `Já existe um render em andamento (pid ${holder}). Aguarde terminar ou encerre-o.`;
fs.rmSync(lockFile, { force: true });
}
}
return "Não foi possível obter a trava de render.";
}
function isAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
function printSummary(report: Record<string, any>, runDir: string): void {
console.log("\nVerificações:");
for (const c of report.checks as Check[]) console.log(` ${c.ok ? "ok " : "FALHA"} ${c.name} — ${c.detail}`);
for (const w of report.warnings as string[]) console.log(` AVISO ${w}`);
const t = report.timingsSeconds as Record<string, number>;
console.log(`\nStatus: ${report.status} (total ${t.total}s; godot ${t.godotRender ?? "-"}s; ffmpeg ${t.ffmpegEncode ?? "-"}s)`);
if (report.mp4) console.log(`MP4: ${report.mp4}`);
console.log(`Relatório: ${displayPath(path.join(runDir, "report.json"))}`);
if (report.inspection) console.log(`Inspeção: ${displayPath(path.join(runDir, "inspect"))}`);
}
function stageKey(label: string): string {
return label.replace(/\s+(\w)/g, (_m, c: string) => c.toUpperCase()).replace(/[^\w]/g, "");
}
function round(n: number): number {
return Math.round(n * 100) / 100;
}
function quoteForLog(a: string): string {
return /\s/.test(a) ? `"${a}"` : a;
}
+105
View File
@@ -0,0 +1,105 @@
// Localiza Godot, FFmpeg e FFprobe sem varrer o disco:
// 1. variável de ambiente (GODOT_BIN, FFMPEG_BIN, FFPROBE_BIN);
// 2. PATH;
// 3. só para a Godot: executável oficial extraído em <raiz>/.tools/godot-*/.
import fs from "node:fs";
import path from "node:path";
import { LOCAL_TOOLS_DIR } from "./paths.ts";
import { runProcess, succeeded } from "./process.ts";
export type ToolName = "godot" | "ffmpeg" | "ffprobe";
export type ToolSource = "env" | "PATH" | "local-tools";
export type Tool = { name: ToolName; path: string; source: ToolSource };
export class MissingToolError extends Error {}
const ENV_VARS: Record<ToolName, string> = { godot: "GODOT_BIN", ffmpeg: "FFMPEG_BIN", ffprobe: "FFPROBE_BIN" };
const PATH_NAMES: Record<ToolName, string[]> = {
godot: ["godot", "godot4"],
ffmpeg: ["ffmpeg"],
ffprobe: ["ffprobe"],
};
export function findTool(name: ToolName): Tool {
const envVar = ENV_VARS[name];
const fromEnv = process.env[envVar];
if (fromEnv) {
// Se o usuário apontou um caminho, não trocamos por outro em silêncio.
if (!isFile(fromEnv)) throw new MissingToolError(`${envVar} aponta para "${fromEnv}", que não existe ou não é arquivo`);
return { name, path: fromEnv, source: "env" };
}
const onPath = findOnPath(PATH_NAMES[name]);
if (onPath) return { name, path: onPath, source: "PATH" };
if (name === "godot") {
const local = findLocalGodot();
if (local) return { name, path: local, source: "local-tools" };
}
throw new MissingToolError(
`${name} não encontrado. Instale ou defina ${envVar} com o caminho do executável` +
(name === "godot" ? " (ou extraia a Godot oficial em .tools/godot-<versão>/)." : "."),
);
}
export function findOnPath(names: string[]): string | null {
const dirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
const exts = process.platform === "win32"
? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").map((e) => e.toLowerCase())
: [""];
for (const dir of dirs) {
for (const name of names) {
for (const ext of exts) {
const candidate = path.join(dir, name + ext);
if (isFile(candidate)) return candidate;
}
}
}
return null;
}
/** Godot oficial em .tools/godot-<versão>/: escolhe o executável principal (não o _console). */
function findLocalGodot(): string | null {
if (!fs.existsSync(LOCAL_TOOLS_DIR)) return null;
const pattern = process.platform === "win32"
? /^Godot_v[\d.]+-stable_win64\.exe$/
: /^Godot_v[\d.]+-stable_linux\.x86_64$/;
const dirs = fs.readdirSync(LOCAL_TOOLS_DIR).filter((d) => d.startsWith("godot-")).sort().reverse();
for (const dir of dirs) {
const full = path.join(LOCAL_TOOLS_DIR, dir);
const exe = fs.readdirSync(full).find((f) => pattern.test(f));
if (exe) return path.join(full, exe);
}
return null;
}
export async function toolVersion(tool: Tool): Promise<string> {
const args = tool.name === "godot" ? ["--version"] : ["-hide_banner", "-version"];
const r = await runProcess(tool.path, args, { timeoutMs: 30_000 });
if (!succeeded(r)) return "desconhecida";
const first = r.stdout.trim().split(/\r?\n/)[0] ?? "";
return first.replace(/ Copyright.*$/, "");
}
export type EncoderSupport = { libx264: boolean; h264_nvenc: boolean; libopenh264: boolean; aac: boolean };
export async function ffmpegEncoders(ffmpeg: Tool): Promise<EncoderSupport> {
const r = await runProcess(ffmpeg.path, ["-hide_banner", "-encoders"], { timeoutMs: 30_000 });
const has = (name: string) => new RegExp(`^\\s*[VA][\\w.]{5}\\s+${name}\\s`, "m").test(r.stdout);
return { libx264: has("libx264"), h264_nvenc: has("h264_nvenc"), libopenh264: has("libopenh264"), aac: has("aac") };
}
/** Escolhe o encoder H.264: libx264 primeiro; alternativas documentadas no README. */
export function chooseVideoEncoder(enc: EncoderSupport): { name: string; args: string[] } {
if (enc.libx264) return { name: "libx264", args: ["-c:v", "libx264", "-preset", "medium", "-crf", "18"] };
if (enc.h264_nvenc) return { name: "h264_nvenc", args: ["-c:v", "h264_nvenc", "-preset", "p5", "-cq", "19"] };
if (enc.libopenh264) return { name: "libopenh264", args: ["-c:v", "libopenh264", "-b:v", "6M"] };
throw new MissingToolError("o FFmpeg instalado não tem encoder H.264 (libx264, h264_nvenc ou libopenh264). Rode `ffmpeg -encoders` e instale um build com libx264.");
}
function isFile(p: string): boolean {
try {
return fs.statSync(p).isFile();
} catch {
return false;
}
}
+106
View File
@@ -0,0 +1,106 @@
// Verificação do MP4 com FFprobe (contagem real de quadros decodificados).
import { runProcess, succeeded, describeFailure } from "./process.ts";
import type { Tool } from "./tools.ts";
export type ProbeSummary = {
formatName: string;
sizeBytes: number;
durationSeconds: number;
video: {
codec: string;
width: number;
height: number;
pixFmt: string;
rFrameRate: string;
avgFrameRate: string;
frames: number;
} | null;
audio: { codec: string; durationSeconds: number } | null;
};
export type Expectation = {
width?: number;
height?: number;
fps?: number;
durationSeconds?: number;
frames?: number;
audio?: boolean;
};
export type Check = { name: string; ok: boolean; detail: string };
export async function probeVideo(ffprobe: Tool, file: string): Promise<ProbeSummary> {
const r = await runProcess(ffprobe.path, [
"-v", "error",
"-count_frames",
"-show_entries", "stream=codec_type,codec_name,width,height,pix_fmt,r_frame_rate,avg_frame_rate,nb_read_frames,duration:format=duration,format_name,size",
"-of", "json",
file,
], { timeoutMs: 120_000 });
if (!succeeded(r)) throw new Error(describeFailure("ffprobe", r));
return parseProbe(r.stdout);
}
export function parseProbe(json: string): ProbeSummary {
type RawStream = Record<string, string | number | undefined>;
const raw = JSON.parse(json) as { streams?: RawStream[]; format?: Record<string, string> };
const streams = raw.streams ?? [];
const v = streams.find((s) => s.codec_type === "video");
const a = streams.find((s) => s.codec_type === "audio");
return {
formatName: raw.format?.format_name ?? "",
sizeBytes: Number(raw.format?.size ?? 0),
durationSeconds: Number(raw.format?.duration ?? NaN),
video: v
? {
codec: String(v.codec_name),
width: Number(v.width),
height: Number(v.height),
pixFmt: String(v.pix_fmt),
rFrameRate: String(v.r_frame_rate),
avgFrameRate: String(v.avg_frame_rate),
frames: Number(v.nb_read_frames),
}
: null,
audio: a ? { codec: String(a.codec_name), durationSeconds: Number(a.duration ?? NaN) } : null,
};
}
export function evaluateProbe(p: ProbeSummary, e: Expectation): Check[] {
const checks: Check[] = [];
const add = (name: string, ok: boolean, detail: string) => checks.push({ name, ok, detail });
add("arquivo não vazio", p.sizeBytes > 0, `${p.sizeBytes} bytes`);
add("contêiner MP4", p.formatName.includes("mp4"), p.formatName || "desconhecido");
if (!p.video) {
add("stream de vídeo", false, "nenhum stream de vídeo");
return checks;
}
add("codec H.264", p.video.codec === "h264", p.video.codec);
add("pixel format yuv420p", p.video.pixFmt === "yuv420p", p.video.pixFmt);
add("quadros decodificados > 0", p.video.frames > 0, `${p.video.frames}`);
if (e.width !== undefined && e.height !== undefined) {
add("dimensões", p.video.width === e.width && p.video.height === e.height, `${p.video.width}x${p.video.height} (esperado ${e.width}x${e.height})`);
}
if (e.fps !== undefined) {
const fps = ratio(p.video.rFrameRate);
add("FPS", Math.abs(fps - e.fps) < 1e-6, `${p.video.rFrameRate} (esperado ${e.fps}/1)`);
}
if (e.frames !== undefined) {
add("total de quadros", p.video.frames === e.frames, `${p.video.frames} (esperado ${e.frames})`);
}
if (e.durationSeconds !== undefined) {
// Tolerância de um quadro, conforme o critério de aceite.
const tolerance = e.fps ? 1 / e.fps : 1 / 30;
const diff = Math.abs(p.durationSeconds - e.durationSeconds);
add("duração (±1 quadro)", diff <= tolerance + 1e-9, `${p.durationSeconds.toFixed(4)} s (esperado ${e.durationSeconds} s, diferença ${diff.toFixed(4)} s)`);
}
if (e.audio !== undefined) {
add(e.audio ? "stream de áudio presente" : "sem áudio", e.audio === (p.audio !== null), p.audio ? `${p.audio.codec}, ${p.audio.durationSeconds} s` : "nenhum");
}
return checks;
}
function ratio(r: string): number {
const [n, d] = r.split("/").map(Number);
return d ? n / d : n;
}