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:
+183
@@ -0,0 +1,183 @@
|
||||
// Lançador local da prova de conceito. Não é backend nem painel: só unifica os
|
||||
// comandos de Godot e FFmpeg. Uso: pnpm <comando> -- [opções]
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { parseArgs, stringOption, numberOption, UsageError, type ParsedArgs } from "./lib/args.ts";
|
||||
import { GODOT_OVERRIDE_FILE, GODOT_PROJECT_DIR, LOCK_FILE, OUTPUT_DIR, displayPath, displayToolPath, resolveFromRoot } from "./lib/paths.ts";
|
||||
import { runProcess, succeeded, describeFailure } from "./lib/process.ts";
|
||||
import { ffmpegEncoders, findTool, toolVersion, chooseVideoEncoder, MissingToolError, type ToolName, type Tool } from "./lib/tools.ts";
|
||||
import { render, PROFILES, type ProfileName } from "./lib/render.ts";
|
||||
import { evaluateProbe, probeVideo, type Expectation } from "./lib/verify.ts";
|
||||
|
||||
const DEFAULT_CONFIG = "config/demo-street.json";
|
||||
|
||||
const HELP = `CenaForge — prova de conceito de vídeo com Godot
|
||||
|
||||
Comandos:
|
||||
pnpm run doctor checa executáveis, versões e diretórios
|
||||
(no pnpm 11, "pnpm doctor" é o diagnóstico do próprio pnpm)
|
||||
pnpm preview [-- --config <json>] abre a cena na Godot (tempo real)
|
||||
pnpm render -- --config <json> --profile preview|final [--keep-frames] [--debug-frame-index] [--warmup-frames N]
|
||||
pnpm verify -- --file <arquivo.mp4> [--width N --height N --fps N --duration S --frames N]
|
||||
pnpm prepare-assets gera as fachadas distantes (headless)
|
||||
pnpm test testes do lançador e da lógica da cena
|
||||
|
||||
Caminhos relativos partem da raiz do projeto.`;
|
||||
|
||||
async function main(argv: string[]): Promise<number> {
|
||||
const [command, ...rest] = argv.filter((a, i) => !(i === 0 && a === "--"));
|
||||
const args = parseArgs(rest);
|
||||
switch (command) {
|
||||
case "doctor":
|
||||
return doctor();
|
||||
case "preview":
|
||||
return preview(args);
|
||||
case "render":
|
||||
return renderCommand(args);
|
||||
case "verify":
|
||||
return verifyCommand(args);
|
||||
case "prepare-assets":
|
||||
return godotHeadlessScript("res://tools/generate_backgrounds.gd");
|
||||
case "test-godot":
|
||||
return godotHeadlessScript("res://tests/run_tests.gd");
|
||||
case undefined:
|
||||
case "help":
|
||||
case "--help":
|
||||
console.log(HELP);
|
||||
return 0;
|
||||
default:
|
||||
console.error(`Comando desconhecido: ${command}\n\n${HELP}`);
|
||||
return 64;
|
||||
}
|
||||
}
|
||||
|
||||
async function doctor(): Promise<number> {
|
||||
let problems = 0;
|
||||
console.log(`Node ${process.version} em ${process.platform}/${process.arch}`);
|
||||
const tools: Partial<Record<ToolName, Tool>> = {};
|
||||
for (const name of ["godot", "ffmpeg", "ffprobe"] as const) {
|
||||
try {
|
||||
const tool = findTool(name);
|
||||
tools[name] = tool;
|
||||
console.log(`ok ${name.padEnd(8)} ${await toolVersion(tool)} [${tool.source}: ${displayToolPath(tool.path)}]`);
|
||||
} catch (error) {
|
||||
problems++;
|
||||
console.log(`FALTA ${name.padEnd(8)} ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
if (tools.ffmpeg) {
|
||||
const enc = await ffmpegEncoders(tools.ffmpeg);
|
||||
try {
|
||||
console.log(`ok encoder ${chooseVideoEncoder(enc).name} (libx264=${enc.libx264} h264_nvenc=${enc.h264_nvenc} libopenh264=${enc.libopenh264} aac=${enc.aac})`);
|
||||
} catch (error) {
|
||||
problems++;
|
||||
console.log(`FALTA encoder ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
|
||||
fs.accessSync(OUTPUT_DIR, fs.constants.W_OK);
|
||||
const stat = fs.statfsSync(OUTPUT_DIR);
|
||||
const freeGB = (stat.bavail * stat.bsize) / 2 ** 30;
|
||||
console.log(`${freeGB < 2 ? "AVISO" : "ok "} saída ${displayPath(OUTPUT_DIR)} gravável, ${freeGB.toFixed(1)} GB livres (prévia usa ~0,3 GB de PNG temporário; final ~1,5 GB)`);
|
||||
} catch (error) {
|
||||
problems++;
|
||||
console.log(`FALTA saída ${(error as Error).message}`);
|
||||
}
|
||||
const graphical = process.platform === "win32" || process.platform === "darwin" || !!process.env.DISPLAY || !!process.env.WAYLAND_DISPLAY;
|
||||
console.log(`${graphical ? "ok " : "AVISO"} gráfico ${graphical ? "sessão gráfica presumida (o render abre uma janela)" : "sem DISPLAY/WAYLAND_DISPLAY: o render 3D precisa de backend gráfico"}`);
|
||||
console.log("info GPU o adaptador real é registrado no report.json de cada render");
|
||||
if (fs.existsSync(GODOT_OVERRIDE_FILE)) console.log(`AVISO override ${displayPath(GODOT_OVERRIDE_FILE)} existe (sobra de render interrompido?)`);
|
||||
if (fs.existsSync(LOCK_FILE)) console.log(`AVISO trava ${displayPath(LOCK_FILE)} existe`);
|
||||
console.log(problems === 0 ? "\nAmbiente pronto." : `\n${problems} problema(s) encontrado(s).`);
|
||||
return problems === 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
async function preview(args: ParsedArgs): Promise<number> {
|
||||
const config = resolveFromRoot(stringOption(args, "config") ?? DEFAULT_CONFIG);
|
||||
const godot = findTool("godot");
|
||||
if (fs.existsSync(GODOT_OVERRIDE_FILE) && !fs.existsSync(LOCK_FILE)) {
|
||||
// Sobra de render interrompido: alteraria o tamanho da janela da prévia.
|
||||
fs.rmSync(GODOT_OVERRIDE_FILE);
|
||||
console.warn("Removido override.cfg deixado por um render interrompido.");
|
||||
}
|
||||
console.log(`Prévia de ${displayPath(config)} — Espaço pausa, R reinicia, ←/→ quadro a quadro, L repete, Esc sai.`);
|
||||
const r = await runProcess(godot.path, ["--path", GODOT_PROJECT_DIR, "--", "--config", config], { inheritStdio: true });
|
||||
if (!succeeded(r)) {
|
||||
console.error(describeFailure("godot", r));
|
||||
return r.exitCode ?? 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function renderCommand(args: ParsedArgs): Promise<number> {
|
||||
const profile = (stringOption(args, "profile") ?? "preview") as ProfileName;
|
||||
if (!(profile in PROFILES)) throw new UsageError(`--profile precisa ser ${Object.keys(PROFILES).join(" ou ")}`);
|
||||
const warmup = numberOption(args, "warmup-frames") ?? 3;
|
||||
if (!Number.isInteger(warmup) || warmup < 0 || warmup > 30) throw new UsageError("--warmup-frames precisa ser inteiro entre 0 e 30");
|
||||
return render({
|
||||
configPath: stringOption(args, "config") ?? DEFAULT_CONFIG,
|
||||
profile,
|
||||
keepFrames: args.options.has("keep-frames"),
|
||||
debugFrameIndex: args.options.has("debug-frame-index"),
|
||||
warmupFrames: warmup,
|
||||
});
|
||||
}
|
||||
|
||||
async function verifyCommand(args: ParsedArgs): Promise<number> {
|
||||
const fileArg = stringOption(args, "file");
|
||||
if (!fileArg) throw new UsageError("informe --file <arquivo.mp4>");
|
||||
const file = resolveFromRoot(fileArg);
|
||||
if (!fs.existsSync(file)) {
|
||||
console.error(`Arquivo não encontrado: ${fileArg}`);
|
||||
return 1;
|
||||
}
|
||||
// Expectativas: opções explícitas > scene.json da mesma pasta de execução.
|
||||
const expectation: Expectation = {};
|
||||
const sceneFile = path.join(path.dirname(file), "scene.json");
|
||||
if (fs.existsSync(sceneFile)) {
|
||||
const scene = JSON.parse(fs.readFileSync(sceneFile, "utf8"));
|
||||
expectation.width = scene.video?.width;
|
||||
expectation.height = scene.video?.height;
|
||||
expectation.fps = scene.video?.fps;
|
||||
expectation.durationSeconds = scene.video?.durationSeconds;
|
||||
if (expectation.fps && expectation.durationSeconds) expectation.frames = Math.round(expectation.fps * expectation.durationSeconds);
|
||||
expectation.audio = scene.audio?.enabled === true;
|
||||
console.log(`Expectativas lidas de ${displayPath(sceneFile)}`);
|
||||
}
|
||||
expectation.width = numberOption(args, "width") ?? expectation.width;
|
||||
expectation.height = numberOption(args, "height") ?? expectation.height;
|
||||
expectation.fps = numberOption(args, "fps") ?? expectation.fps;
|
||||
expectation.durationSeconds = numberOption(args, "duration") ?? expectation.durationSeconds;
|
||||
expectation.frames = numberOption(args, "frames") ?? expectation.frames;
|
||||
|
||||
const probe = await probeVideo(findTool("ffprobe"), file);
|
||||
const checks = evaluateProbe(probe, expectation);
|
||||
console.log(`\n${displayPath(file)}`);
|
||||
for (const c of checks) console.log(` ${c.ok ? "ok " : "FALHA"} ${c.name} — ${c.detail}`);
|
||||
const ok = checks.every((c) => c.ok);
|
||||
console.log(ok ? "\nVídeo verificado." : "\nVerificação falhou.");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
async function godotHeadlessScript(script: string): Promise<number> {
|
||||
const godot = findTool("godot");
|
||||
const r = await runProcess(godot.path, ["--headless", "--path", GODOT_PROJECT_DIR, "--script", script], { inheritStdio: true });
|
||||
if (!succeeded(r)) console.error(describeFailure(`godot ${script}`, r));
|
||||
return succeeded(r) ? 0 : r.exitCode ?? 1;
|
||||
}
|
||||
|
||||
main(process.argv.slice(2)).then(
|
||||
(code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (error instanceof UsageError || error instanceof MissingToolError) {
|
||||
console.error(`Erro: ${error.message}`);
|
||||
process.exitCode = 64;
|
||||
} else {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
},
|
||||
);
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
// `pnpm dev` (ou start.bat): sobe o serviço de voz (127.0.0.1:4510), o Clipador (127.0.0.1:4520), o Publicador
|
||||
// (127.0.0.1:4530) e o painel (127.0.0.1:4500) juntos. Ctrl+C encerra todos. Serviço que o setup ainda não
|
||||
// instalou é pulado com aviso.
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const voiceDir = path.join(root, "voice");
|
||||
const python = path.join(voiceDir, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
const PORT_RANGE = [4500, 4599] as const; // faixa do CenaForge (ver CLAUDE.md)
|
||||
|
||||
function readEnv(file: string): Record<string, string> {
|
||||
if (!fs.existsSync(file)) return {};
|
||||
const entries = fs
|
||||
.readFileSync(file, "utf8")
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.includes("=") && !line.trimStart().startsWith("#"))
|
||||
.map((line) => {
|
||||
const at = line.indexOf("=");
|
||||
return [line.slice(0, at).trim(), line.slice(at + 1).trim()] as [string, string];
|
||||
});
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
const voiceOnly = process.argv.includes("--voice-only");
|
||||
const envFile = path.join(voiceDir, ".env");
|
||||
const children: ChildProcess[] = [];
|
||||
let voiceChild: ChildProcess | null = null;
|
||||
let clipperChild: ChildProcess | null = null;
|
||||
let cloneChild: ChildProcess | null = null;
|
||||
let publisherChild: ChildProcess | null = null;
|
||||
// Clonagem de voz (Chatterbox): venv próprio porque fixa torch/numpy/transformers diferentes do serviço de voz.
|
||||
const clonePython = path.join(voiceDir, ".venv-clone", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
const clipperDir = path.join(root, "clipper");
|
||||
const clipperPython = path.join(clipperDir, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
const publisherDir = path.join(root, "publisher");
|
||||
const publisherPython = path.join(publisherDir, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
// Processos de voz parados de propósito (reinício): o "exit" deles chega depois, de forma assíncrona,
|
||||
// e não pode encerrar o lançador no modo --voice-only.
|
||||
const replaced = new WeakSet<ChildProcess>();
|
||||
|
||||
function prefixed(name: string, color: number, child: ChildProcess): void {
|
||||
const tag = `\x1b[${color}m[${name}]\x1b[0m `;
|
||||
for (const stream of [child.stdout, child.stderr]) {
|
||||
let pending = "";
|
||||
stream?.setEncoding("utf8");
|
||||
stream?.on("data", (chunk: string) => {
|
||||
const lines = (pending + chunk).split(/\r?\n/);
|
||||
pending = lines.pop() ?? "";
|
||||
for (const line of lines) process.stdout.write(tag + line + "\n");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function stop(child: ChildProcess): void {
|
||||
if (child.exitCode !== null || child.pid === undefined) return;
|
||||
// No Windows o painel roda via shell (pnpm.cmd): só o taskkill /T derruba a árvore inteira.
|
||||
if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
else child.kill("SIGTERM");
|
||||
}
|
||||
|
||||
function stopAll(): void {
|
||||
const services = [voiceChild, clipperChild, cloneChild, publisherChild].filter((child): child is ChildProcess => child !== null);
|
||||
for (const child of [...children, ...services]) stop(child);
|
||||
}
|
||||
|
||||
/** A porta está livre em 127.0.0.1? (tenta ouvir nela e solta em seguida) */
|
||||
function portFree(port: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const probe = net.createServer();
|
||||
probe.once("error", () => resolve(false));
|
||||
probe.listen(port, "127.0.0.1", () => probe.close(() => resolve(true)));
|
||||
});
|
||||
}
|
||||
|
||||
async function waitPortFree(port: number, timeoutMs: number): Promise<boolean> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (await portFree(port)) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
return portFree(port);
|
||||
}
|
||||
|
||||
async function startVoice(): Promise<void> {
|
||||
const env = readEnv(envFile);
|
||||
if (!fs.existsSync(python) || !env.VOICE_SERVICE_KEY) {
|
||||
console.warn("\x1b[33m[voz]\x1b[0m serviço de voz não instalado; rode setup.bat. Subindo só o painel.");
|
||||
return;
|
||||
}
|
||||
const port = Number(env.VOICE_PORT || 4510);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`VOICE_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
// No reinício o Windows leva um instante para soltar a porta; fora dele, porta ocupada = outro CenaForge aberto.
|
||||
if (!(await waitPortFree(port, 10_000))) {
|
||||
console.warn(
|
||||
`\x1b[33m[voz]\x1b[0m porta ${port} ocupada (outro CenaForge ou serviço de voz já aberto?). ` +
|
||||
"Feche o outro processo; o painel segue sem iniciar uma segunda voz.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const child = spawn(
|
||||
python,
|
||||
["-m", "uvicorn", "app.main:build", "--factory", "--host", "127.0.0.1", "--port", String(port), "--no-access-log"],
|
||||
{ cwd: voiceDir, env: { ...process.env, PYTHONUTF8: "1" } },
|
||||
);
|
||||
voiceChild = child;
|
||||
prefixed("voz", 35, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[35m[voz]\x1b[0m encerrado (código ${code})`);
|
||||
if (voiceChild === child) voiceChild = null;
|
||||
if (voiceOnly && !replaced.has(child)) process.exit(code ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
/** Clonagem de voz (opcional: setup.bat -Clone). Só ouve 127.0.0.1 e exige a mesma chave do serviço de voz. */
|
||||
async function startClone(): Promise<void> {
|
||||
const env = readEnv(envFile);
|
||||
if (!fs.existsSync(clonePython) || !env.VOICE_SERVICE_KEY) return; // não instalada: as vozes clonadas avisam no painel
|
||||
const port = Number(env.VOICE_CLONE_PORT || 4511);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`VOICE_CLONE_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
if (!(await waitPortFree(port, 10_000))) {
|
||||
console.warn(`\x1b[34m[clone]\x1b[0m porta ${port} ocupada (outro CenaForge aberto?). Seguindo sem a clonagem.`);
|
||||
return;
|
||||
}
|
||||
const child = spawn(clonePython, [path.join(voiceDir, "clone", "worker.py")], {
|
||||
cwd: voiceDir,
|
||||
env: { ...process.env, ...env, VOICE_CLONE_PORT: String(port), PYTHONUTF8: "1" },
|
||||
});
|
||||
cloneChild = child;
|
||||
prefixed("clone", 34, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[34m[clone]\x1b[0m encerrado (código ${code})`);
|
||||
if (cloneChild === child) cloneChild = null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Clipador (cortes de live): grava, lê o chat, transcreve pela voz e renderiza. Opcional como a voz. */
|
||||
async function startClipper(): Promise<void> {
|
||||
const env = readEnv(path.join(clipperDir, ".env"));
|
||||
if (!fs.existsSync(clipperPython) || !env.CLIPPER_SERVICE_KEY) {
|
||||
console.warn("[33m[clip][0m Clipador não instalado; rode setup.bat. Seguindo sem ele.");
|
||||
return;
|
||||
}
|
||||
const port = Number(env.CLIPPER_PORT || 4520);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`CLIPPER_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
if (!(await waitPortFree(port, 5_000))) {
|
||||
console.warn(`[33m[clip][0m porta ${port} ocupada (outro Clipador aberto?). Seguindo sem iniciar um segundo.`);
|
||||
return;
|
||||
}
|
||||
const child = spawn(
|
||||
clipperPython,
|
||||
["-m", "uvicorn", "app.main:build", "--factory", "--host", "127.0.0.1", "--port", String(port), "--no-access-log"],
|
||||
{ cwd: clipperDir, env: { ...process.env, PYTHONUTF8: "1" } },
|
||||
);
|
||||
clipperChild = child;
|
||||
prefixed("clip", 33, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`[33m[clip][0m encerrado (código ${code})`);
|
||||
if (clipperChild === child) clipperChild = null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Publicador (envio para YouTube, TikTok e Instagram): cofre de tokens, OAuth, navegador do modo sessão. Opcional. */
|
||||
async function startPublisher(): Promise<void> {
|
||||
const env = readEnv(path.join(publisherDir, ".env"));
|
||||
if (!fs.existsSync(publisherPython) || !env.PUBLISHER_SERVICE_KEY) {
|
||||
console.warn("\x1b[33m[pub]\x1b[0m Publicador não instalado; rode setup.bat. Seguindo sem ele (nada é publicado).");
|
||||
return;
|
||||
}
|
||||
const port = Number(env.PUBLISHER_PORT || 4530);
|
||||
if (!(port >= PORT_RANGE[0] && port <= PORT_RANGE[1])) {
|
||||
throw new Error(`PUBLISHER_PORT=${port} fora da faixa ${PORT_RANGE[0]}–${PORT_RANGE[1]} do CenaForge`);
|
||||
}
|
||||
if (!(await waitPortFree(port, 5_000))) {
|
||||
console.warn(`\x1b[33m[pub]\x1b[0m porta ${port} ocupada (outro Publicador aberto?). Seguindo sem iniciar um segundo.`);
|
||||
return;
|
||||
}
|
||||
const child = spawn(
|
||||
publisherPython,
|
||||
["-m", "uvicorn", "app.main:build", "--factory", "--host", "127.0.0.1", "--port", String(port), "--no-access-log"],
|
||||
{ cwd: publisherDir, env: { ...process.env, PYTHONUTF8: "1" } },
|
||||
);
|
||||
publisherChild = child;
|
||||
prefixed("pub", 32, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[32m[pub]\x1b[0m encerrado (código ${code})`);
|
||||
if (publisherChild === child) publisherChild = null;
|
||||
});
|
||||
}
|
||||
|
||||
// O painel grava as configurações da voz no voice/.env: quando ele muda, o serviço reinicia sozinho.
|
||||
function watchVoiceEnv(): void {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
fs.watchFile(envFile, { interval: 1000 }, (current, previous) => {
|
||||
if (current.mtimeMs === previous.mtimeMs) return;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
console.log("\x1b[35m[voz]\x1b[0m voice/.env mudou: reiniciando o serviço de voz");
|
||||
if (voiceChild) {
|
||||
replaced.add(voiceChild);
|
||||
stop(voiceChild);
|
||||
}
|
||||
voiceChild = null;
|
||||
void startVoice();
|
||||
// A clonagem lê o mesmo .env (dispositivo, chave): reinicia junto.
|
||||
if (cloneChild) {
|
||||
stop(cloneChild);
|
||||
cloneChild = null;
|
||||
}
|
||||
void startClone();
|
||||
}, 1500);
|
||||
});
|
||||
}
|
||||
|
||||
function startPanel(): void {
|
||||
// Argumentos fixos (nada vem de fora): o shell só existe para achar o pnpm.cmd no Windows.
|
||||
const child = spawn("pnpm", ["--filter", "cenaforge-panel", "dev"], { cwd: root, shell: true });
|
||||
children.push(child);
|
||||
prefixed("painel", 36, child);
|
||||
child.on("exit", (code) => {
|
||||
console.log(`\x1b[36m[painel]\x1b[0m encerrado (código ${code})`);
|
||||
stopAll();
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
}
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
stopAll();
|
||||
process.exit(0);
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
stopAll();
|
||||
process.exit(0);
|
||||
});
|
||||
// Qualquer saída (inclusive por erro) leva os filhos junto: nada de serviço de voz órfão segurando a porta.
|
||||
process.on("exit", stopAll);
|
||||
|
||||
await startVoice();
|
||||
await startClone();
|
||||
watchVoiceEnv();
|
||||
if (voiceOnly) {
|
||||
if (!voiceChild) process.exit(1);
|
||||
} else {
|
||||
await startClipper();
|
||||
await startPublisher();
|
||||
startPanel();
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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"],
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
# Instalação do CenaForge no Windows (chamado pelo setup.bat na raiz).
|
||||
#
|
||||
# O que faz, nesta ordem (pode rodar de novo: o que já está pronto é pulado):
|
||||
# 1. Node.js + pnpm e as dependências do projeto (pnpm install)
|
||||
# 2. uv + Python 3.12 isolado em voice/.venv (não mexe no Python do sistema)
|
||||
# 3. Serviço de voz: dependências; DLLs do CUDA se houver GPU NVIDIA
|
||||
# 4. voice/.env com chave aleatória (Whisper large-v3-turbo com GPU, small sem GPU)
|
||||
# 5. Pesos dos modelos (Piper + Whisper) com conferência de sha256
|
||||
# 6. Applio 3.7.0 (vozes de personagem/RVC): torch CUDA ou CPU + pré-requisitos [pule com -NoRvc]
|
||||
# 6b. Clipador e 6b2. Publicador (venv + chave em clipper/.env e publisher/.env)
|
||||
# 6c. Clonagem de voz (Chatterbox, venv próprio voice/.venv-clone) [só com -Clone]
|
||||
# 7. pnpm run doctor (Godot/FFmpeg)
|
||||
#
|
||||
# Uso: setup.bat instalação completa
|
||||
# setup.bat -NoRvc sem Applio (economiza ~4 GB; vozes de personagem ficam desligadas)
|
||||
# setup.bat -Cpu força CPU mesmo com GPU NVIDIA
|
||||
# setup.bat -Clone também instala a clonagem de voz (~4 GB: torch 2.6 + Chatterbox)
|
||||
param(
|
||||
[switch]$NoRvc,
|
||||
[switch]$Cpu,
|
||||
[switch]$Clone
|
||||
)
|
||||
|
||||
# "Continue" e não "Stop": no PowerShell 5.1 o stderr de um executável (o uv escreve progresso lá) vira
|
||||
# NativeCommandError. Cada comando externo é conferido pelo código de saída em Run().
|
||||
$ErrorActionPreference = "Continue"
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$Voice = Join-Path $Root "voice"
|
||||
$VenvPython = Join-Path $Voice ".venv\Scripts\python.exe"
|
||||
$ApplioDir = Join-Path $Voice "vendor\applio"
|
||||
$ApplioTag = "3.7.0"
|
||||
$TorchVersion = "2.11.0"
|
||||
|
||||
function Step($text) { Write-Host ""; Write-Host "==> $text" -ForegroundColor Cyan }
|
||||
function Ok($text) { Write-Host " ok: $text" -ForegroundColor Green }
|
||||
function Warn($text) { Write-Host " aviso: $text" -ForegroundColor Yellow }
|
||||
function Fail($text) { Write-Host ""; Write-Host "ERRO: $text" -ForegroundColor Red; exit 1 }
|
||||
function Has($cmd) { return [bool](Get-Command $cmd -ErrorAction SilentlyContinue) }
|
||||
function Run($exe, [string[]]$arguments) {
|
||||
& $exe @arguments
|
||||
if ($LASTEXITCODE -ne 0) { Fail "$exe $($arguments -join ' ') terminou com código $LASTEXITCODE" }
|
||||
}
|
||||
function Set-EnvValue($file, $name, $value) {
|
||||
$lines = Get-Content $file -Encoding utf8
|
||||
if ($lines -match "^$name=") { $lines = $lines -replace "^$name=.*$", "$name=$value" }
|
||||
else { $lines += "$name=$value" }
|
||||
Set-Content -Path $file -Value $lines -Encoding utf8
|
||||
}
|
||||
|
||||
Write-Host "CenaForge — instalação" -ForegroundColor White
|
||||
Write-Host "Pasta: $Root"
|
||||
|
||||
# ---------- 1. Node + pnpm ----------
|
||||
Step "Node.js e pnpm"
|
||||
if (-not (Has "node")) { Fail "Node.js 20.10+ não encontrado. Instale em https://nodejs.org (versão LTS) e rode o setup de novo." }
|
||||
$nodeVersion = (node --version).TrimStart("v")
|
||||
if ([version]$nodeVersion -lt [version]"20.10.0") { Fail "Node.js $nodeVersion é antigo; o CenaForge exige 20.10+." }
|
||||
Ok "node $nodeVersion"
|
||||
if (-not (Has "pnpm")) {
|
||||
Warn "pnpm ausente; ativando pelo corepack"
|
||||
Run "corepack" @("enable")
|
||||
if (-not (Has "pnpm")) { Run "npm" @("install", "-g", "pnpm") }
|
||||
}
|
||||
Ok "pnpm $(pnpm --version)"
|
||||
Push-Location $Root
|
||||
Run "pnpm" @("install")
|
||||
Pop-Location
|
||||
|
||||
# ---------- 2. uv + Python 3.12 ----------
|
||||
Step "Python 3.12 isolado (uv)"
|
||||
if (-not (Has "uv")) {
|
||||
Warn "uv ausente; instalando (https://astral.sh/uv)"
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/install.ps1 | iex"
|
||||
$env:Path = "$env:USERPROFILE\.local\bin;$env:Path"
|
||||
if (-not (Has "uv")) { Fail "não consegui instalar o uv; instale à mão e rode o setup de novo" }
|
||||
}
|
||||
Ok "uv $((uv --version) -replace 'uv ', '')"
|
||||
if (-not (Test-Path $VenvPython)) { Run "uv" @("venv", (Join-Path $Voice ".venv"), "--python", "3.12") }
|
||||
Ok "voice/.venv ($(& $VenvPython --version))"
|
||||
|
||||
# ---------- 3. Dependências do serviço de voz ----------
|
||||
Step "Dependências do serviço de voz"
|
||||
Run "uv" @("pip", "install", "--python", $VenvPython, "-r", (Join-Path $Voice "requirements.txt"))
|
||||
$Gpu = $false
|
||||
if (-not $Cpu -and (Has "nvidia-smi")) {
|
||||
# Sem "| Select-Object -First 1" direto no nvidia-smi: cortar o pipeline mata o processo e o
|
||||
# $LASTEXITCODE deixa de ser 0 (foi assim que uma RTX 2060 passou por "sem GPU").
|
||||
$gpuLines = @(nvidia-smi --query-gpu=name --format=csv,noheader 2>$null)
|
||||
if ($LASTEXITCODE -eq 0 -and $gpuLines.Count -gt 0 -and $gpuLines[0]) { $Gpu = $true; Ok "GPU NVIDIA: $($gpuLines[0])" }
|
||||
}
|
||||
if ($Gpu) {
|
||||
Run "uv" @("pip", "install", "--python", $VenvPython, "-r", (Join-Path $Voice "requirements-cuda.txt"))
|
||||
Ok "DLLs do CUDA 12 (cuBLAS, cuDNN)"
|
||||
} else {
|
||||
Warn "sem GPU NVIDIA utilizável: tudo roda na CPU (mais lento na legenda e nas vozes de personagem)"
|
||||
}
|
||||
|
||||
# ---------- 4. voice/.env ----------
|
||||
Step "Configuração (voice/.env)"
|
||||
$EnvFile = Join-Path $Voice ".env"
|
||||
if (-not (Test-Path $EnvFile)) {
|
||||
Copy-Item (Join-Path $Voice ".env.example") $EnvFile
|
||||
$key = & $VenvPython -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
Set-EnvValue $EnvFile "VOICE_SERVICE_KEY" $key
|
||||
Set-EnvValue $EnvFile "VOICE_STT_MODEL" ($(if ($Gpu) { "large-v3-turbo" } else { "small" }))
|
||||
Ok "voice/.env criado com chave nova"
|
||||
} else {
|
||||
Ok "voice/.env já existe (mantido)"
|
||||
}
|
||||
Set-EnvValue $EnvFile "VOICE_DEVICE" ($(if ($Cpu) { "cpu" } else { "auto" }))
|
||||
$sttModel = ((Get-Content $EnvFile -Encoding utf8) -match "^VOICE_STT_MODEL=" | Select-Object -First 1) -replace "^VOICE_STT_MODEL=", ""
|
||||
if (-not $sttModel) { $sttModel = "small" }
|
||||
|
||||
# ---------- 5. Pesos ----------
|
||||
Step "Modelos de voz e transcrição (Whisper $sttModel)"
|
||||
Run $VenvPython @((Join-Path $Voice "scripts\fetch_models.py"), "--group", "v1", "--group", "stt-$sttModel")
|
||||
|
||||
# ---------- 6. Applio (RVC) ----------
|
||||
if ($NoRvc) {
|
||||
Step "Applio (RVC): pulado (-NoRvc)"
|
||||
Set-EnvValue $EnvFile "VOICE_ENABLE_RVC" "0"
|
||||
} else {
|
||||
Step "Applio $ApplioTag (vozes de personagem / RVC)"
|
||||
if (-not (Test-Path (Join-Path $ApplioDir "rvc\infer\infer.py"))) {
|
||||
New-Item -ItemType Directory -Force (Split-Path $ApplioDir) | Out-Null
|
||||
if (Has "git") {
|
||||
Run "git" @("clone", "--depth", "1", "--branch", $ApplioTag, "https://github.com/IAHispano/Applio.git", $ApplioDir)
|
||||
} else {
|
||||
$zip = Join-Path $env:TEMP "applio-$ApplioTag.zip"
|
||||
Invoke-WebRequest -UseBasicParsing "https://github.com/IAHispano/Applio/archive/refs/tags/$ApplioTag.zip" -OutFile $zip
|
||||
Expand-Archive $zip (Split-Path $ApplioDir) -Force
|
||||
Rename-Item (Join-Path (Split-Path $ApplioDir) "Applio-$ApplioTag") $ApplioDir
|
||||
Remove-Item $zip
|
||||
}
|
||||
}
|
||||
Ok "Applio em voice/vendor/applio"
|
||||
# Variante explícita (+cu128/+cpu): "torch==2.11.0" sozinho aceitaria a variante errada já instalada.
|
||||
$variant = if ($Gpu) { "cu128" } else { "cpu" }
|
||||
$index = "https://download.pytorch.org/whl/$variant"
|
||||
Run "uv" @("pip", "install", "--python", $VenvPython, "--index-url", $index, "torch==$TorchVersion+$variant", "torchaudio==$TorchVersion+$variant")
|
||||
Ok "torch $TorchVersion ($(if ($Gpu) { 'CUDA 12.8' } else { 'CPU' }))"
|
||||
Run "uv" @("pip", "install", "--python", $VenvPython, "-r", (Join-Path $Voice "requirements-rvc.txt"))
|
||||
# Pré-requisitos de inferência (contentvec, rmvpe, fcpe). Os pré-treinados de treino ficam para quando treinarmos.
|
||||
Push-Location $ApplioDir
|
||||
Run $VenvPython @("-c", "from rvc.lib.tools.prerequisites_download import prequisites_download_pipeline as p; p(False, True, False)")
|
||||
Pop-Location
|
||||
Set-EnvValue $EnvFile "VOICE_ENABLE_RVC" "1"
|
||||
Ok "RVC ligado"
|
||||
}
|
||||
|
||||
# ---------- 6b. Clipador (cortes de live) ----------
|
||||
Step "Clipador (cortes de live: Streamlink + chat + IA)"
|
||||
$Clipper = Join-Path $Root "clipper"
|
||||
$ClipperPython = Join-Path $Clipper ".venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $ClipperPython)) { Run "uv" @("venv", (Join-Path $Clipper ".venv"), "--python", "3.12") }
|
||||
Run "uv" @("pip", "install", "--python", $ClipperPython, "-r", (Join-Path $Clipper "requirements.txt"))
|
||||
$ClipperEnv = Join-Path $Clipper ".env"
|
||||
if (-not (Test-Path $ClipperEnv)) {
|
||||
Copy-Item (Join-Path $Clipper ".env.example") $ClipperEnv
|
||||
$key = & $ClipperPython -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
Set-EnvValue $ClipperEnv "CLIPPER_SERVICE_KEY" $key
|
||||
Ok "clipper/.env criado com chave nova"
|
||||
} else {
|
||||
Ok "clipper/.env já existe (mantido)"
|
||||
}
|
||||
Ok "Streamlink $(& (Join-Path $Clipper '.venv\Scripts\streamlink.exe') --version)"
|
||||
if (-not (Has "codex") -and -not (Has "claude")) {
|
||||
Warn "nem Codex nem Claude CLI no PATH: o juiz de IA dos cortes fica desligado até instalar e fazer login"
|
||||
}
|
||||
# Rastreio de reação: o cv2 tem de vir do opencv-contrib-python (puxado pelo MediaPipe), com FaceDetectorYN.
|
||||
& $ClipperPython -c "import cv2, mediapipe; cv2.FaceDetectorYN; from mediapipe.tasks.python import vision; vision.FaceLandmarker"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Warn "cv2/MediaPipe não importam no clipper/.venv (opencv-python-headless instalado junto?): rastreio de reação fica desligado"
|
||||
}
|
||||
# Pesos do rastreio (YuNet, MediaPipe, OpenSeeFace): URL fixa + sha256 em clipper/models.lock.json.
|
||||
$ModelLock = Get-Content (Join-Path $Clipper "models.lock.json") -Raw -Encoding utf8 | ConvertFrom-Json
|
||||
$ModelDir = Join-Path $Root $ModelLock.dir
|
||||
New-Item -ItemType Directory -Force $ModelDir | Out-Null
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
||||
$oldProgress = $ProgressPreference
|
||||
$ProgressPreference = "SilentlyContinue" # a barra de progresso do Invoke-WebRequest deixa o download lento no 5.1
|
||||
foreach ($m in $ModelLock.models) {
|
||||
$dest = Join-Path $ModelDir $m.file
|
||||
if ((Test-Path $dest) -and ((Get-FileHash $dest -Algorithm SHA256).Hash -eq $m.sha256.ToUpper())) {
|
||||
Ok "modelo $($m.file) (sha256 confere)"
|
||||
continue
|
||||
}
|
||||
$tmp = "$dest.part"
|
||||
try {
|
||||
Invoke-WebRequest -Uri $m.url -OutFile $tmp -UseBasicParsing
|
||||
} catch {
|
||||
Warn "não consegui baixar $($m.file): $($_.Exception.Message) (o Clipador tenta de novo quando precisar)"
|
||||
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
|
||||
continue
|
||||
}
|
||||
if ((Get-FileHash $tmp -Algorithm SHA256).Hash -ne $m.sha256.ToUpper()) {
|
||||
Remove-Item $tmp -Force
|
||||
Warn "sha256 de $($m.file) não confere com clipper/models.lock.json; arquivo descartado"
|
||||
continue
|
||||
}
|
||||
Move-Item $tmp $dest -Force
|
||||
Ok "modelo $($m.file) baixado (sha256 confere)"
|
||||
}
|
||||
$ProgressPreference = $oldProgress
|
||||
|
||||
# ---------- 6b2. Publicador (envio para YouTube, TikTok e Instagram) ----------
|
||||
Step "Publicador (envio para as redes: API oficial ou sessão logada)"
|
||||
$Publisher = Join-Path $Root "publisher"
|
||||
$PublisherPython = Join-Path $Publisher ".venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $PublisherPython)) { Run "uv" @("venv", (Join-Path $Publisher ".venv"), "--python", "3.12") }
|
||||
# Só o pacote do Playwright (driver). NÃO rodamos "playwright install": o modo sessão usa o Chrome/Edge já instalado.
|
||||
Run "uv" @("pip", "install", "--python", $PublisherPython, "-r", (Join-Path $Publisher "requirements.txt"))
|
||||
$PublisherEnv = Join-Path $Publisher ".env"
|
||||
if (-not (Test-Path $PublisherEnv)) {
|
||||
Copy-Item (Join-Path $Publisher ".env.example") $PublisherEnv
|
||||
$key = & $PublisherPython -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
Set-EnvValue $PublisherEnv "PUBLISHER_SERVICE_KEY" $key
|
||||
Ok "publisher/.env criado com chave nova"
|
||||
} else {
|
||||
Ok "publisher/.env já existe (mantido)"
|
||||
}
|
||||
# Segredos do Publicador (chave do serviço, cofre de tokens, banco, sessões logadas do navegador, capturas):
|
||||
# só o usuário atual do Windows lê. Sem herança de permissões; pasta com (OI)(CI) para valer nos arquivos de dentro.
|
||||
$PublisherData = Join-Path $Root "data\publisher"
|
||||
New-Item -ItemType Directory -Force $PublisherData | Out-Null
|
||||
$MySid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
& icacls $PublisherEnv /inheritance:r /grant:r "*${MySid}:F" | Out-Null
|
||||
$aclEnvOk = $LASTEXITCODE -eq 0
|
||||
& icacls $PublisherData /inheritance:r /grant:r "*${MySid}:(OI)(CI)F" | Out-Null
|
||||
$aclDataOk = $LASTEXITCODE -eq 0
|
||||
# Os filhos que já existem passam a herdar SÓ da pasta. (Não use /T com (OI)(CI): em arquivo isso vira ACL vazia.)
|
||||
if (Get-ChildItem $PublisherData -Force -ErrorAction SilentlyContinue) {
|
||||
& icacls (Join-Path $PublisherData "*") /reset /T /C | Out-Null
|
||||
$aclDataOk = $aclDataOk -and $LASTEXITCODE -eq 0
|
||||
}
|
||||
if ($aclEnvOk -and $aclDataOk) { Ok "permissões de publisher/.env e data/publisher restritas ao seu usuário" }
|
||||
else { Warn "não consegui restringir as permissões de publisher/.env ou data/publisher (icacls); siga, mas confira depois" }
|
||||
$chromePaths = @("$env:ProgramFiles\Google\Chrome\Application\chrome.exe", "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe",
|
||||
"$env:LOCALAPPDATA\Google\Chrome\Application\chrome.exe", "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe",
|
||||
"$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe")
|
||||
if (-not ($chromePaths | Where-Object { Test-Path $_ })) {
|
||||
Warn "Chrome/Edge não encontrado: o modo Sessão logada fica indisponível (a API oficial funciona)"
|
||||
}
|
||||
|
||||
# ---------- 6c. Clonagem de voz (opcional) ----------
|
||||
# O Chatterbox fixa torch 2.6, numpy < 2 e outro transformers: não cabe no voice/.venv, então ganha o seu.
|
||||
$CloneVenv = Join-Path $Voice ".venv-clone"
|
||||
$ClonePython = Join-Path $CloneVenv "Scripts\python.exe"
|
||||
if ($Clone) {
|
||||
Step "Clonagem de voz (Chatterbox Multilingual, MIT)"
|
||||
if (-not (Test-Path $ClonePython)) { Run "uv" @("venv", $CloneVenv, "--python", "3.12") }
|
||||
$cloneVariant = if ($Gpu) { "cu124" } else { "cpu" }
|
||||
$cloneIndex = "https://download.pytorch.org/whl/$cloneVariant"
|
||||
Run "uv" @("pip", "install", "--python", $ClonePython, "--index-url", $cloneIndex, "torch==2.6.0+$cloneVariant", "torchaudio==2.6.0+$cloneVariant")
|
||||
Run "uv" @("pip", "install", "--python", $ClonePython, "-r", (Join-Path $Voice "clone\requirements.txt"),
|
||||
"torch==2.6.0+$cloneVariant", "torchaudio==2.6.0+$cloneVariant",
|
||||
"--extra-index-url", $cloneIndex, "--index-strategy", "unsafe-best-match")
|
||||
Ok "Chatterbox instalado ($(if ($Gpu) { 'CUDA 12.4' } else { 'CPU: cada fala leva bem mais tempo' })); os pesos (~3 GB) baixam na primeira subida"
|
||||
} elseif (Test-Path $ClonePython) {
|
||||
Ok "clonagem de voz já instalada (voice/.venv-clone)"
|
||||
} else {
|
||||
Ok "clonagem de voz não instalada (opcional: setup.bat -Clone)"
|
||||
}
|
||||
|
||||
# ---------- 7. Diagnóstico ----------
|
||||
Step "Diagnóstico do projeto (Godot, FFmpeg)"
|
||||
Push-Location $Root
|
||||
pnpm run doctor
|
||||
if ($LASTEXITCODE -ne 0) { Warn "o doctor apontou pendências acima (render de vídeo); a voz já está instalada" }
|
||||
Pop-Location
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Pronto. Para subir o CenaForge (painel 4500 + voz 4510 + Clipador 4520 + Publicador 4530): start.bat (ou: pnpm dev)" -ForegroundColor Green
|
||||
@@ -0,0 +1,195 @@
|
||||
// Testes do lançador: falhas de subprocesso, trava de render, conferência de
|
||||
// quadros, critérios do FFprobe e áudio opcional.
|
||||
import { test, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { runProcess, succeeded, describeFailure, cancelActiveProcesses, resetCancellation } from "../lib/process.ts";
|
||||
import { parseArgs } from "../lib/args.ts";
|
||||
import { acquireLock, applyProfile } from "../lib/render.ts";
|
||||
import { checkFrames, readPngSize } from "../lib/frames.ts";
|
||||
import { evaluateProbe, parseProbe, type ProbeSummary } from "../lib/verify.ts";
|
||||
import { planAudio, audioFfmpegArgs, AudioError } from "../lib/audio.ts";
|
||||
import { findTool, type Tool } from "../lib/tools.ts";
|
||||
|
||||
const created: string[] = [];
|
||||
const tmp = () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cenaforge-test-"));
|
||||
created.push(dir);
|
||||
return dir;
|
||||
};
|
||||
after(() => created.forEach((dir) => fs.rmSync(dir, { recursive: true, force: true })));
|
||||
const node = process.execPath;
|
||||
|
||||
function tryTool(name: "ffmpeg" | "ffprobe"): Tool | null {
|
||||
try {
|
||||
return findTool(name);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- subprocessos -------------------------------------------------------------
|
||||
|
||||
test("código de saída diferente de zero não é sucesso", async () => {
|
||||
const r = await runProcess(node, ["-e", "process.exit(3)"]);
|
||||
assert.equal(r.exitCode, 3);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.match(describeFailure("node", r), /código 3/);
|
||||
});
|
||||
|
||||
test("executável inexistente vira falha, não exceção nem sucesso", async () => {
|
||||
const r = await runProcess(path.join(tmp(), "nao-existe.exe"), []);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.ok(r.spawnError);
|
||||
});
|
||||
|
||||
test("argumentos com espaços chegam intactos (sem shell)", async () => {
|
||||
const arg = "C:/pasta com espaço/arquivo; echo injetado.json";
|
||||
const r = await runProcess(node, ["-e", "process.stdout.write(process.argv[1])", arg]);
|
||||
assert.ok(succeeded(r));
|
||||
assert.equal(r.stdout, arg);
|
||||
});
|
||||
|
||||
test("timeout encerra o processo e é falha", async () => {
|
||||
const r = await runProcess(node, ["-e", "setTimeout(() => {}, 60000)"], { timeoutMs: 300 });
|
||||
assert.equal(r.timedOut, true);
|
||||
assert.equal(succeeded(r), false);
|
||||
});
|
||||
|
||||
test("cancelamento encerra o subprocesso e marca como cancelado", async () => {
|
||||
const pending = runProcess(node, ["-e", "setTimeout(() => {}, 60000)"]);
|
||||
setTimeout(cancelActiveProcesses, 200);
|
||||
const r = await pending;
|
||||
resetCancellation();
|
||||
assert.equal(r.cancelled, true);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.ok(r.durationMs < 30_000);
|
||||
});
|
||||
|
||||
test("FFmpeg com erro não resulta em sucesso", { skip: !tryTool("ffmpeg") && "ffmpeg ausente" }, async () => {
|
||||
const ffmpeg = tryTool("ffmpeg")!;
|
||||
const dir = tmp();
|
||||
const r = await runProcess(ffmpeg.path, ["-hide_banner", "-y", "-framerate", "30", "-i", path.join(dir, "frame%08d.png"), path.join(dir, "out.mp4")]);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.notEqual(r.exitCode, 0);
|
||||
});
|
||||
|
||||
// --- argumentos e perfil --------------------------------------------------------
|
||||
|
||||
test("'--' solto repassado pelo pnpm é ignorado", () => {
|
||||
const a = parseArgs(["--", "--config", "config/x.json", "--profile=final", "--keep-frames"]);
|
||||
assert.equal(a.options.get("config"), "config/x.json");
|
||||
assert.equal(a.options.get("profile"), "final");
|
||||
assert.equal(a.options.get("keep-frames"), true);
|
||||
});
|
||||
|
||||
test("perfil altera só a resolução e não muta o original", () => {
|
||||
const raw = { id: "x", video: { width: 540, height: 960, fps: 30, durationSeconds: 12 } };
|
||||
const out = applyProfile(raw, { width: 1080, height: 1920 }) as { video: Record<string, number> };
|
||||
assert.deepEqual(out.video, { width: 1080, height: 1920, fps: 30, durationSeconds: 12 });
|
||||
assert.equal(raw.video.width, 540);
|
||||
});
|
||||
|
||||
// --- trava ----------------------------------------------------------------------
|
||||
|
||||
test("só um render por vez; trava abandonada é recuperada", () => {
|
||||
const lock = path.join(tmp(), ".render.lock");
|
||||
const release = acquireLock(lock);
|
||||
assert.equal(typeof release, "function");
|
||||
assert.match(String(acquireLock(lock)), /em andamento/);
|
||||
(release as () => void)();
|
||||
// Trava de um processo que não existe mais.
|
||||
fs.writeFileSync(lock, JSON.stringify({ pid: 999_999_999 }));
|
||||
const again = acquireLock(lock);
|
||||
assert.equal(typeof again, "function");
|
||||
(again as () => void)();
|
||||
});
|
||||
|
||||
// --- quadros --------------------------------------------------------------------
|
||||
|
||||
function fakePng(file: string, width: number, height: number): void {
|
||||
const header = Buffer.alloc(24);
|
||||
Buffer.from("89504e470d0a1a0a", "hex").copy(header, 0);
|
||||
header.writeUInt32BE(13, 8);
|
||||
header.write("IHDR", 12, "ascii");
|
||||
header.writeUInt32BE(width, 16);
|
||||
header.writeUInt32BE(height, 20);
|
||||
fs.writeFileSync(file, Buffer.concat([header, Buffer.alloc(4096, 1)]));
|
||||
}
|
||||
|
||||
test("sequência completa passa; lacuna, quantidade e tamanho errados falham", () => {
|
||||
const dir = tmp();
|
||||
for (let i = 0; i < 5; i++) fakePng(path.join(dir, `frame${String(i).padStart(8, "0")}.png`), 540, 960);
|
||||
assert.deepEqual(readPngSize(path.join(dir, "frame00000000.png")), { width: 540, height: 960 });
|
||||
assert.equal(checkFrames(dir, 5, { width: 540, height: 960 }, 1).ok, true);
|
||||
|
||||
const wrongCount = checkFrames(dir, 6, { width: 540, height: 960 }, 1);
|
||||
assert.equal(wrongCount.ok, false);
|
||||
assert.match(wrongCount.problems.join(), /esperado 6/);
|
||||
|
||||
const wrongSize = checkFrames(dir, 5, { width: 1080, height: 1920 }, 1);
|
||||
assert.match(wrongSize.problems.join(), /esperado 1080x1920/);
|
||||
|
||||
fs.rmSync(path.join(dir, "frame00000002.png"));
|
||||
assert.match(checkFrames(dir, 4, { width: 540, height: 960 }, 1).problems.join(), /lacuna/);
|
||||
});
|
||||
|
||||
test("pasta sem PNG falha", () => {
|
||||
assert.equal(checkFrames(tmp(), 360, { width: 540, height: 960 }, 3).ok, false);
|
||||
});
|
||||
|
||||
// --- critérios do FFprobe ------------------------------------------------------
|
||||
|
||||
const goodProbe: ProbeSummary = parseProbe(JSON.stringify({
|
||||
streams: [{ codec_type: "video", codec_name: "h264", width: 540, height: 960, pix_fmt: "yuv420p", r_frame_rate: "30/1", avg_frame_rate: "30/1", nb_read_frames: "360" }],
|
||||
format: { format_name: "mov,mp4,m4a,3gp,3g2,mj2", duration: "12.000000", size: "1234567" },
|
||||
}));
|
||||
const expected = { width: 540, height: 960, fps: 30, durationSeconds: 12, frames: 360, audio: false };
|
||||
|
||||
test("MP4 correto passa em todos os critérios", () => {
|
||||
const failed = evaluateProbe(goodProbe, expected).filter((c) => !c.ok);
|
||||
assert.deepEqual(failed, []);
|
||||
});
|
||||
|
||||
test("duração fora da tolerância de um quadro falha; dentro passa", () => {
|
||||
const off = (d: number) => evaluateProbe({ ...goodProbe, durationSeconds: d }, expected).find((c) => c.name.startsWith("duração"))!;
|
||||
assert.equal(off(12 + 1 / 30).ok, true);
|
||||
assert.equal(off(12 + 2 / 30).ok, false);
|
||||
});
|
||||
|
||||
test("FPS, dimensões e contagem errados falham", () => {
|
||||
const bad = { ...goodProbe, video: { ...goodProbe.video!, rFrameRate: "25/1", width: 720, frames: 359 } };
|
||||
const failed = evaluateProbe(bad, expected).filter((c) => !c.ok).map((c) => c.name);
|
||||
assert.ok(failed.includes("FPS"));
|
||||
assert.ok(failed.includes("dimensões"));
|
||||
assert.ok(failed.includes("total de quadros"));
|
||||
});
|
||||
|
||||
// --- áudio opcional ------------------------------------------------------------
|
||||
|
||||
test("áudio desabilitado não gera plano", async () => {
|
||||
const fakeProbe: Tool = { name: "ffprobe", path: "nao-usado", source: "PATH" };
|
||||
assert.equal(await planAudio({ enabled: false, file: null }, 12, fakeProbe), null);
|
||||
});
|
||||
|
||||
test("arquivo de áudio inexistente é rejeitado com mensagem clara", async () => {
|
||||
const fakeProbe: Tool = { name: "ffprobe", path: "nao-usado", source: "PATH" };
|
||||
await assert.rejects(planAudio({ enabled: true, file: "audio/nao-existe.wav" }, 12, fakeProbe), (e: unknown) => e instanceof AudioError && /não encontrado/.test(e.message));
|
||||
await assert.rejects(planAudio({ enabled: true, file: null }, 12, fakeProbe), AudioError);
|
||||
});
|
||||
|
||||
test("áudio maior que a cena gera aviso de corte; filtro não usa -shortest", { skip: !(tryTool("ffmpeg") && tryTool("ffprobe")) && "ffmpeg/ffprobe ausentes" }, async () => {
|
||||
const dir = tmp();
|
||||
const wav = path.join(dir, "tom de teste.wav");
|
||||
const gen = await runProcess(tryTool("ffmpeg")!.path, ["-hide_banner", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=5", wav]);
|
||||
assert.ok(succeeded(gen));
|
||||
const plan = (await planAudio({ enabled: true, file: wav, offsetSeconds: 9 }, 12, tryTool("ffprobe")!))!;
|
||||
assert.ok(Math.abs(plan.sourceDurationSeconds - 5) < 0.05);
|
||||
assert.ok(Math.abs(plan.cutSeconds - 2) < 0.05);
|
||||
assert.match(plan.warnings.join(), /CORTADO/);
|
||||
const args = audioFfmpegArgs(plan);
|
||||
assert.ok(!args.mapping.includes("-shortest"));
|
||||
assert.match(args.mapping.join(" "), /adelay=delays=9000:all=1,apad,atrim=end=12/);
|
||||
});
|
||||
Reference in New Issue
Block a user