Files
CenaForge/scripts/lib/render.ts
T
MateuusandClaude Opus 5.5 84f30bbc2d 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>
2026-11-17 16:35:09 -03:00

419 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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;
}