Files
CenaForge/cartoon/render.ts
T
MateuusandClaude Opus 5.5 2d8b1a582d Cartoon: mãos, membros e cenários novos; elenco de Noé e a Arca
- Mãos com formas e rotações próprias, membros articulados (limbs) e animais.
- Elementos de cenário separados (natureza, construções, interiores) e testes de lugares.
- Personagens reaproveitáveis de Noé e a Arca (Noé, esposa, Sem, Cam e Jafé) e a fonte Barlow Semi Condensed.
- História noe-e-a-arca: pauta, bíblia, roteiro do ep. 1, tomadas Cartoon e montagem.
- Montagem: narração mais corrida (tira silêncios longos) e cabeçalho com o número do vídeo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:51:11 -03:00

132 lines
7.5 KiB
TypeScript

// Render do estilo Cartoon por linha de comando. Empacota uma vez e renderiza todos os trechos pedidos.
//
// tsx render.ts --jobs <arquivo.json> [{ "spec": "<spec.json>", "out": "<trecho.mp4>" }, ...]
// tsx render.ts --spec <spec.json> --out <trecho.mp4>
// tsx render.ts --sample --out <exemplo.mp4>
//
// Caminhos relativos valem a partir da raiz do repositório. Última linha do stdout = relatório JSON
// ({ ok, results: [{ out, frames, ms }], error? }); código de saída 0 só se todos saírem.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { bundle } from "@remotion/bundler";
import { renderMedia, renderStill, selectComposition } from "@remotion/renderer";
import { validateLook } from "./src/character";
import { frameCount, validateSpec, type ShotSpec } from "./src/spec";
import { SAMPLE } from "./src/sample";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO = path.resolve(HERE, "..");
const resolve = (p: string) => (path.isAbsolute(p) ? p : path.resolve(REPO, p));
type Job = { spec: ShotSpec; out: string };
function arg(name: string): string | undefined {
const i = process.argv.indexOf(`--${name}`);
return i >= 0 ? process.argv[i + 1] : undefined;
}
function readJobs(): Job[] {
const jobsFile = arg("jobs");
if (jobsFile) {
const list = JSON.parse(fs.readFileSync(resolve(jobsFile), "utf8")) as { spec: string; out: string }[];
if (!Array.isArray(list) || list.length === 0) throw new Error("--jobs precisa ser uma lista com pelo menos um trecho");
return list.map((j) => ({ spec: JSON.parse(fs.readFileSync(resolve(j.spec), "utf8")), out: resolve(j.out) }));
}
const out = arg("out");
if (!out) throw new Error("falta --out (ou use --jobs)");
if (process.argv.includes("--sample")) return [{ spec: SAMPLE, out: resolve(out) }];
const spec = arg("spec");
if (!spec) throw new Error("falta --spec (ou use --jobs / --sample)");
return [{ spec: JSON.parse(fs.readFileSync(resolve(spec), "utf8")), out: resolve(out) }];
}
/** `--still --props <json> --out <png> [--frame N]`: imagem parada do cartão de personagem (prévia da biblioteca). */
async function still() {
const propsFile = arg("props");
const out = arg("out");
// `--still --spec <trecho.json> --out <png> [--frame N]`: um quadro de um trecho (conferir peças sem gerar o vídeo).
// `--still --list <lista.json>` ([{spec, out, frame?}]): vários quadros num empacotamento só (folhas de conferência).
const listFile = arg("list");
if (listFile) {
const list = JSON.parse(fs.readFileSync(resolve(listFile), "utf8")) as { spec: string; out: string; frame?: number }[];
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
const results: { out: string; frames: number; ms: number }[] = [];
for (const item of list) {
const t0 = Date.now();
const spec = JSON.parse(fs.readFileSync(resolve(item.spec), "utf8")) as ShotSpec;
const errors = validateSpec(spec);
if (errors.length) throw new Error(`${item.spec}: ${errors.join("; ")}`);
const inputProps = spec as unknown as Record<string, unknown>;
const composition = await selectComposition({ serveUrl, id: "Shot", inputProps });
fs.mkdirSync(path.dirname(resolve(item.out)), { recursive: true });
const frame = Math.min(frameCount(spec) - 1, item.frame ?? Math.floor(frameCount(spec) / 2));
await renderStill({ composition, serveUrl, inputProps, output: resolve(item.out), frame, imageFormat: "png", browserExecutable: process.env.CARTOON_CHROME || null });
results.push({ out: path.relative(REPO, resolve(item.out)).replace(/\\/g, "/"), frames: 1, ms: Date.now() - t0 });
}
console.log(JSON.stringify({ ok: true, results }));
return;
}
const specFile = arg("spec");
if (specFile && out) {
const spec = JSON.parse(fs.readFileSync(resolve(specFile), "utf8")) as ShotSpec;
const errors = validateSpec(spec);
if (errors.length) throw new Error(`spec: ${errors.join("; ")}`);
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
const inputProps = spec as unknown as Record<string, unknown>;
const composition = await selectComposition({ serveUrl, id: "Shot", inputProps });
fs.mkdirSync(path.dirname(resolve(out)), { recursive: true });
const frame = Math.min(frameCount(spec) - 1, Number(arg("frame") ?? Math.floor(frameCount(spec) / 2)));
await renderStill({ composition, serveUrl, inputProps, output: resolve(out), frame, imageFormat: "png", browserExecutable: process.env.CARTOON_CHROME || null });
console.log(JSON.stringify({ ok: true, results: [{ out: path.relative(REPO, resolve(out)).replace(/\\/g, "/"), frames: 1, ms: 0 }] }));
return;
}
if (!propsFile || !out) throw new Error("--still precisa de --props e --out");
const inputProps = JSON.parse(fs.readFileSync(resolve(propsFile), "utf8")) as Record<string, unknown>;
const looks = (inputProps.figures as { look: unknown }[] | undefined) ?? [];
if (!looks.length) throw new Error("--still: figures vazio");
for (const [i, f] of looks.entries()) {
const errors = validateLook(f.look);
if (errors.length) throw new Error(`figures[${i}].look: ${errors.join("; ")}`);
}
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
const composition = await selectComposition({ serveUrl, id: "Character", inputProps });
fs.mkdirSync(path.dirname(resolve(out)), { recursive: true });
await renderStill({ composition, serveUrl, inputProps, output: resolve(out), frame: Number(arg("frame") ?? 0), imageFormat: "png",
browserExecutable: process.env.CARTOON_CHROME || null });
console.log(JSON.stringify({ ok: true, results: [{ out: path.relative(REPO, resolve(out)).replace(/\\/g, "/"), frames: 1, ms: 0 }] }));
}
async function main() {
if (process.argv.includes("--still")) return still();
const jobs = readJobs();
for (const [i, job] of jobs.entries()) {
const errors = validateSpec(job.spec);
if (errors.length) throw new Error(`trecho ${i + 1} (${path.basename(job.out)}): ${errors.join("; ")}`);
}
const started = Date.now();
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
console.log(`empacotado em ${((Date.now() - started) / 1000).toFixed(1)} s`);
const results: { out: string; frames: number; ms: number }[] = [];
for (const job of jobs) {
const t0 = Date.now();
const inputProps = job.spec as unknown as Record<string, unknown>;
const composition = await selectComposition({ serveUrl, id: "Shot", inputProps });
fs.mkdirSync(path.dirname(job.out), { recursive: true });
await renderMedia({
composition, serveUrl, inputProps, codec: "h264", outputLocation: job.out, crf: 18, pixelFormat: "yuv420p",
imageFormat: "jpeg", jpegQuality: 92, muted: true, overwrite: true,
browserExecutable: process.env.CARTOON_CHROME || null,
});
results.push({ out: path.relative(REPO, job.out).replace(/\\/g, "/"), frames: frameCount(job.spec), ms: Date.now() - t0 });
console.log(`ok ${path.basename(job.out)} (${frameCount(job.spec)} quadros, ${((Date.now() - t0) / 1000).toFixed(1)} s)`);
}
console.log(JSON.stringify({ ok: true, results }));
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
console.log(JSON.stringify({ ok: false, error: message }));
process.exit(1);
});