Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Faceless: narration timed before the scenes, cloud music on fal compose, deletes stop renders

Claudee902c51475f6
diff --git a/src/app/api/faceless/channels/[id]/avatar/route.ts b/src/app/api/faceless/channels/[id]/avatar/route.ts
index 4d90b502..44f09c6d 100644
--- a/src/app/api/faceless/channels/[id]/avatar/route.ts
+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts
@@ -1,6 +1,6 @@
import { handle, makeAvatar } from "@/server/faceless";
-/** Draw a channel avatar in the channel's style (one picture generation; PATCH avatarUrl with it when it's done). */
+/** Draw a channel avatar in the channel's style (one picture generation; it becomes the channel's picture when it's done). */
export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]/avatar">) {
return handle(async () => {
const { id } = await ctx.params;
diff --git a/src/app/api/faceless/channels/[id]/route.ts b/src/app/api/faceless/channels/[id]/route.ts
index f2e8deaa..2a435c70 100644
--- a/src/app/api/faceless/channels/[id]/route.ts
+++ b/src/app/api/faceless/channels/[id]/route.ts
@@ -30,11 +30,11 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/c
});
}
-/** Deletes the channel and its episodes (their videos stay in the Library). */
+/** Deletes the channel and its episodes, stopping what they still render (finished videos stay in the Library). */
export async function DELETE(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {
return handle(async () => {
const { id } = await ctx.params;
- deleteChannel(id);
+ await deleteChannel(id);
return new Response(null, { status: 204 });
});
}
diff --git a/src/app/api/faceless/episodes/[id]/[action]/route.ts b/src/app/api/faceless/episodes/[id]/[action]/route.ts
index faa7aee8..908c0468 100644
--- a/src/app/api/faceless/episodes/[id]/[action]/route.ts
+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts
@@ -1,4 +1,4 @@
-import { episodeView, handle, renderEpisode, retryEpisode, rewriteEpisode, undoChange } from "@/server/faceless";
+import { episodeView, handle, renderEpisode, retryEpisode, rewriteEpisode, undoChange, upscaleEpisode } from "@/server/faceless";
const ACTIONS = {
/** Render the reviewed script. */
@@ -9,6 +9,8 @@ const ACTIONS = {
rewrite: rewriteEpisode,
/** Go back to the version before the last change. */
undo: undoChange,
+ /** Upscale the finished film to 1080p (cloud). */
+ upscale: upscaleEpisode,
} as const;
export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/[action]">) {
diff --git a/src/app/api/faceless/episodes/[id]/route.ts b/src/app/api/faceless/episodes/[id]/route.ts
index 4950e09e..3a075834 100644
--- a/src/app/api/faceless/episodes/[id]/route.ts
+++ b/src/app/api/faceless/episodes/[id]/route.ts
@@ -28,11 +28,11 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/e
});
}
-/** Deletes the episode (its videos stay in the Library). */
+/** Deletes the episode and stops what it still renders (its finished videos stay in the Library). */
export async function DELETE(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {
return handle(async () => {
const { id } = await ctx.params;
- deleteEpisode(id);
+ await deleteEpisode(id);
return new Response(null, { status: 204 });
});
}
diff --git a/src/app/api/faceless/episodes/route.ts b/src/app/api/faceless/episodes/route.ts
index 8764aab9..c7cdf037 100644
--- a/src/app/api/faceless/episodes/route.ts
+++ b/src/app/api/faceless/episodes/route.ts
@@ -8,6 +8,8 @@ const Create = z.object({
topic: z.string().max(MAX_TOPIC, "Keep the topic under 5,000 characters"),
script: z.string().max(MAX_SCRIPT, "That script is too long to narrate. Shorten it and try again.").optional(),
settings: SettingsSchema,
+ /** Save this episode's look and sound as the channel's (default: only for its first episode). */
+ saveLook: z.boolean().optional(),
});
/** Episodes, newest first (`?channel=` for one channel). */
@@ -24,6 +26,6 @@ export async function POST(request: Request) {
return handle(async () => {
const input = await body(request, Create, "Pick a topic and the video settings");
if (!FACELESS_LENGTHS.includes(input.settings.length)) throw new FacelessError("Choose one of the offered video lengths");
- return Response.json(createEpisode({ kind: "faceless", channelId: input.channelId, topic: input.topic, script: input.script, settings: input.settings }), { status: 201 });
+ return Response.json(createEpisode({ kind: "faceless", channelId: input.channelId, topic: input.topic, script: input.script, settings: input.settings, saveLook: input.saveLook }), { status: 201 });
});
}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index c583f675..b3ae0fbf 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -9,4 +9,7 @@ export async function register() {
ensureRunner();
const { ensureTrashPurge } = await import("./server/library");
ensureTrashPurge();
+ // Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.
+ const { ensureFacelessRunner } = await import("./server/faceless");
+ ensureFacelessRunner();
}
diff --git a/src/lib/catalog/faceless.ts b/src/lib/catalog/faceless.ts
index 67c7d589..1fc50d43 100644
--- a/src/lib/catalog/faceless.ts
+++ b/src/lib/catalog/faceless.ts
@@ -563,8 +563,8 @@ export interface EngineModels {
captionsUseWords: boolean;
/** Pictures that show the subject of attached images, when the still model can't read images. */
sourceStill?: string;
- /** "Upscale to 1080p" on a finished episode. */
- upscale: string;
+ /** "Upscale to 1080p" on a finished episode (cloud: SeedVR2; the open 4× upscaler holds every frame in memory, so none). */
+ upscale?: string;
write: string;
}
@@ -610,7 +610,6 @@ export const ENGINE_MODELS: Record<Engine, EngineModels> = {
align: "oss-qwen3-asr",
captionsUseWords: true,
sourceStill: "oss-qwen-edit",
- upscale: "oss-upscale-video-esrgan",
write: "oss-text-llm",
},
};
@@ -651,10 +650,12 @@ export type ModelLookup = (id: string) => ModelDef | undefined;
export function shotsFor(seconds: number, durations: number[] | undefined, range?: [number, number]): number[] {
const need = Math.max(1, Math.round(seconds));
if (range) {
+ // Any whole length in the range: split as evenly as possible, so the shots add up to the block (11 → 6 + 5).
const [lo, hi] = range;
const n = Math.ceil(need / hi);
- const base = Math.max(lo, Math.ceil(need / n));
- return Array.from({ length: n }, () => Math.min(hi, base));
+ const base = Math.floor(need / n);
+ const extra = need - base * n;
+ return Array.from({ length: n }, (_, i) => Math.min(hi, Math.max(lo, base + (i < extra ? 1 : 0))));
}
const ds = [...new Set(durations?.length ? durations : [5])].filter((d) => d > 0).sort((a, b) => a - b);
const max = ds[ds.length - 1];
@@ -750,15 +751,22 @@ export interface GraphInput {
export interface ResolvedModels {
still: string;
+ /** "edit": the pictures are drawn from attached source images by an edit model (open engine). */
+ stillOp?: "edit";
video: string;
resolution: string;
narration: string;
music: string | null;
+ /** Brings the bed down under the voice before the mix (cloud). */
+ level: string | null;
mux: string;
join: string;
joinMax: number;
captions: string | null;
- transcribe: string | null;
+ /** Word timings of the narration: the scenes are cut to them. */
+ align: string;
+ /** The captions are burned from those timings (open engine). */
+ captionsUseWords: boolean;
}
/** Which models an episode runs on, from its engine and settings. */
@@ -770,17 +778,22 @@ export function resolveModels(settings: EpisodeSettings, narrationChars: number,
const wanted = settings.resolution && offered.includes(settings.resolution) ? settings.resolution : (DEFAULT_RESOLUTION[video]?.[settings.animation] ?? videoDef?.defaults?.resolution ?? offered[0] ?? "720p");
const sample = settings.voice?.kind === "sample";
const narration = settings.engine === "open" ? m.narration : sample ? m.cloneNarration : narrationChars > m.narrationMaxChars ? m.longNarration : m.narration;
+ // Style references win; attached source images otherwise go to a model that reads them.
+ const fromSources = !settings.styleRefs.length && !!settings.sourceImages?.length && !!m.sourceStill;
return {
- still: settings.styleRefs.length ? m.styleStill : m.still,
+ still: settings.styleRefs.length ? m.styleStill : fromSources ? m.sourceStill! : m.still,
+ ...(fromSources && { stillOp: "edit" as const }),
video,
resolution: wanted,
narration,
music: settings.music ? m.music : null,
+ level: settings.music ? (m.levelMusic ?? null) : null,
mux: settings.music ? m.mixMusic : m.mux,
join: m.join,
joinMax: m.joinMax,
captions: settings.subtitles ? m.captions : null,
- transcribe: settings.subtitles ? (m.transcribe ?? null) : null,
+ align: m.align,
+ captionsUseWords: m.captionsUseWords,
};
}
@@ -819,16 +832,25 @@ const pick = (lookup: ModelLookup, id: string) => {
return m;
};
-/** Music beds come in fixed lengths: the shortest that covers the film, else the longest there is. */
+/**
+ * How long the music bed is: as long as the film (plus a second) for models that make any length up to
+ * their limit (MUSIC_MAX), else the shortest fixed length that covers it, else the longest there is.
+ */
export function musicLength(model: ModelDef | undefined, seconds: number): number {
+ const max = model ? MUSIC_MAX[model.id] : undefined;
+ if (max) return Math.min(max, Math.max(10, Math.ceil(seconds) + 1));
const ds = [...(model?.options.durations ?? [])].sort((a, b) => a - b);
if (!ds.length) return Math.ceil(seconds);
return ds.find((d) => d >= seconds) ?? ds[ds.length - 1];
}
+/** Seconds of film a block's shots make (its planned or timed length, rounded up to what the model makes). */
+export const filmSeconds = (seconds: number, video: ModelDef | undefined) => blockShots(seconds, video).reduce((a, c) => a + c, 0);
+
/**
* Every step of an episode render, in dependency order. Pure: the server turns it into chained
- * generations (createPipeline), the editor uses it to work out what a change re-runs.
+ * generations, the editor uses it to work out what a change re-runs. Blocks carry their length: the
+ * planned one, or (once the narration is timed, see sceneTiming) the length cut to their lines.
*/
export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): GraphStep[] {
const { settings, blocks, feature } = input;
@@ -844,62 +866,58 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph
const steps: GraphStep[] = [];
const n = blocks.length;
const clipKeys: string[] = [];
- const sources = (settings.sourceImages ?? []).slice(0, 3);
+ const sources = (settings.sourceImages ?? []).slice(0, MAX_SOURCES);
const refs = settings.styleRefs.slice(0, MAX_STYLE_REFS);
const stillDef = pick(lookup, models.still);
+ const maxImages = stillDef.options.maxImages ?? 1;
// Reference images go where the still model reads them: a style-reference model takes only the style
- // images; a multi-reference model (Nano Banana Pro) takes them and the sources; a plain t2i model none.
+ // images; a multi-reference model (Nano Banana Pro) takes them and the sources; an edit model (open,
+ // with sources) the sources; a plain t2i model none.
const takesRefs = stillDef.routes.some((r) => r.op === "edit") || !!stillDef.options.maxImages;
- const maxRefs = stillDef.options.maxImages ?? 1;
- const stillImages = !takesRefs ? [] : stillDef.engine === "open" && refs.length ? refs.slice(0, maxRefs) : [...refs, ...sources].slice(0, maxRefs);
- const refCount = Math.min(refs.length, stillImages.length);
+ const stillImages =
+ models.stillOp === "edit" ? sources.slice(0, maxImages) : !takesRefs ? [] : stillDef.engine === "open" && refs.length ? refs.slice(0, maxImages) : [...refs, ...sources].slice(0, maxImages);
+ const refCount = models.stillOp === "edit" ? 0 : Math.min(refs.length, stillImages.length);
blocks.forEach((b, i) => {
const edit = input.stillEdits?.[b.id];
const stillKey = `still-${b.id}`;
- if (edit) {
- steps.push({
- key: stillKey,
- part: "still",
- block: i,
- label: `Scene ${i + 1} · picture`,
- request: {
- ...base,
- modelId: ENGINE_MODELS[settings.engine].editStill,
- op: "edit",
- prompt: `${clean(edit.instruction)}. Keep everything else the same: the art style, composition, characters and colours.`,
- inputs: { images: [edit.source] },
- params: { aspectRatio: ar, numOutputs: 1 },
- step: { label: `Scene ${i + 1} · picture`, index: i, of: n },
- },
- });
- } else {
- steps.push({
- key: stillKey,
- part: "still",
- block: i,
- label: `Scene ${i + 1} · picture`,
- request: {
- ...base,
- modelId: models.still,
- prompt: stillPrompt(style, b, { aspect: ar, refs: refCount, sources: stillImages.length - refCount }),
- ...(stillImages.length && { inputs: { images: stillImages } }),
- params: { aspectRatio: ar, numOutputs: 1 },
- step: { label: `Scene ${i + 1} · picture`, index: i, of: n },
- },
- });
- }
+ const label = `Scene ${i + 1} · picture`;
+ steps.push({
+ key: stillKey,
+ part: "still",
+ block: i,
+ label,
+ request: edit
+ ? {
+ ...base,
+ modelId: ENGINE_MODELS[settings.engine].editStill,
+ op: "edit",
+ prompt: `${clean(edit.instruction)}. Keep everything else the same: the art style, composition, characters and colours.`,
+ inputs: { images: [edit.source] },
+ params: { aspectRatio: ar, numOutputs: 1 },
+ step: { label, index: i, of: n },
+ }
+ : {
+ ...base,
+ modelId: models.still,
+ ...(models.stillOp && { op: models.stillOp }),
+ prompt: stillPrompt(style, b, { aspect: ar, refs: refCount, sources: stillImages.length - refCount }),
+ ...(stillImages.length && { inputs: { images: stillImages } }),
+ params: { aspectRatio: ar, numOutputs: 1 },
+ step: { label, index: i, of: n },
+ },
+ });
const shots = blockShots(b.seconds, videoDef);
shots.forEach((secs, s) => {
const key = `clip-${b.id}-${s + 1}`;
clipKeys.push(key);
- const label = shots.length > 1 ? `Scene ${i + 1} · clip ${s + 1} of ${shots.length}` : `Scene ${i + 1} · clip`;
+ const clipLabel = shots.length > 1 ? `Scene ${i + 1} · clip ${s + 1} of ${shots.length}` : `Scene ${i + 1} · clip`;
steps.push({
key,
part: "clip",
block: i,
shot: s,
- label,
+ label: clipLabel,
seconds: secs,
after: [stillKey],
chain: [{ slot: "images", position: "first" }],
@@ -916,7 +934,7 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph
// The narration replaces the clip's own sound.
...(videoDef.options.audio === true && { generateAudio: false }),
},
- step: { label, index: i, of: n },
+ step: { label: clipLabel, index: i, of: n },
},
});
});
@@ -946,9 +964,9 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph
}
}
const film = levels.length ? "join" : clipKeys[0];
- const filmSeconds = blocks.reduce((t, b) => t + blockShots(b.seconds, videoDef).reduce((a, c) => a + c, 0), 0);
+ const length = blocks.reduce((t, b) => t + filmSeconds(b.seconds, videoDef), 0);
- // The voice-over, read in one take.
+ // The voice-over, read in one take, then timed word by word.
const narrationDef = pick(lookup, models.narration);
const voice = settings.voice;
const sample = voice?.kind === "sample" ? voice.url : narrationDef.options.voiceClone && !narrationDef.options.voices?.length ? input.fallbackVoice : undefined;
@@ -967,69 +985,85 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph
step: { label: "Narration", index: n, of: n },
},
});
+ // Forced alignment reads the known script with the recording; an ASR just listens.
+ const alignDef = pick(lookup, models.align);
+ const alignReadsText = alignDef.routes.some((r) => r.op === "transcribe" && typeof r.map?.prompt === "string");
+ steps.push({
+ key: "words",
+ part: "words",
+ label: "Narration timing",
+ after: ["narration"],
+ chain: [{ slot: "audio" }],
+ request: { ...base, modelId: models.align, op: "transcribe", ...(alignReadsText && { prompt: voiceText }), step: { label: "Narration timing", index: n, of: n } },
+ });
if (models.music) {
const musicDef = pick(lookup, models.music);
+ const bed = musicLength(musicDef, length);
steps.push({
key: "music",
part: "music",
label: "Music bed",
- seconds: musicLength(musicDef, filmSeconds),
+ seconds: bed,
request: {
...base,
modelId: models.music,
op: "music",
prompt: musicPrompt(input.genre, style),
- params: { duration: musicLength(musicDef, filmSeconds), numOutputs: 1, ...(settings.engine === "open" && { extra: { lyrics: "[Instrumental]" } }) },
+ params: { duration: bed, numOutputs: 1, ...(settings.engine === "open" && { extra: { lyrics: "[Instrumental]" } }) },
step: { label: "Music", index: n, of: n },
},
});
+ if (models.level) {
+ steps.push({
+ key: "level",
+ part: "music",
+ label: "Music level",
+ after: ["music"],
+ chain: [{ slot: "audio" }],
+ request: { ...base, modelId: models.level, op: "level", params: { extra: { integrated_loudness: BED_LUFS } }, step: { label: "Music level", index: n, of: n } },
+ });
+ }
}
const muxDef = pick(lookup, models.mux);
- const mixAfter = models.music ? [film, "narration", "music"] : [film, "narration"];
+ // A timeline mixer (fal compose) places every track for the film's length.
+ const timeline = muxDef.routes.some((r) => r.op === "mux" && !!r.map?.tracks);
+ const bed = models.level ? "level" : "music";
+ const mixLabel = models.music ? "Mixing voice and music" : "Mixing";
steps.push({
key: "mix",
part: "mix",
- label: models.music ? "Voice and music" : "Voice-over",
- seconds: filmSeconds,
- after: mixAfter,
+ label: mixLabel,
+ seconds: length,
+ after: models.music ? [film, "narration", bed] : [film, "narration"],
chain: models.music ? [{ slot: "video" }, { slot: "audio" }, { slot: "audio2" }] : [{ slot: "video" }, { slot: "audio" }],
request: {
...base,
modelId: models.mux,
op: "mux",
- ...(muxDef.engine === "open" && models.music && { params: { extra: { backgroundVolumeDb: -14 } } }),
+ params: { ...(timeline && { duration: length }), ...(muxDef.engine === "open" && models.music && { extra: { backgroundVolumeDb: BED_DB } }) },
...(!models.captions && { title: input.title }),
- step: { label: models.music ? "Voice and music" : "Voice-over", index: n, of: n },
+ step: { label: mixLabel, index: n, of: n },
},
});
if (models.captions) {
- if (models.transcribe) {
- steps.push({
- key: "words",
- part: "words",
- label: "Caption timing",
- after: ["narration"],
- chain: [{ slot: "audio" }],
- request: { ...base, modelId: models.transcribe, op: "transcribe", step: { label: "Caption timing", index: n, of: n } },
- });
- }
+ const words = models.captionsUseWords;
const vertical = ar === "9:16";
steps.push({
key: "captions",
part: "captions",
label: "Subtitles",
- seconds: filmSeconds,
- after: models.transcribe ? ["mix", "words"] : ["mix"],
- chain: models.transcribe ? [{ slot: "video" }, { slot: "prompt" }] : [{ slot: "video" }],
+ seconds: length,
+ after: words ? ["mix", "words"] : ["mix"],
+ chain: words ? [{ slot: "video" }, { slot: "prompt" }] : [{ slot: "video" }],
request: {
...base,
modelId: models.captions,
op: "captions",
title: input.title,
- params: models.transcribe ? { extra: { fontSize: vertical ? 4 : 6, wordsPerCaption: vertical ? 3 : 5 } } : { extra: { words_per_subtitle: vertical ? 3 : 5 } },
+ params: words ? { extra: { fontSize: vertical ? 4 : 6, wordsPerCaption: vertical ? 3 : 5 } } : { extra: { words_per_subtitle: vertical ? 3 : 5 } },
step: { label: "Subtitles", index: n, of: n },
},
});
@@ -1055,6 +1089,140 @@ export function descendants(graph: Pick<GraphStep, "key" | "after">[], keys: Ite
return out;
}
+// ---------------------------------------------------------------------------
+// Timing: every scene cut to where its lines are spoken
+
+/**
+ * The steps rendered before the scenes are timed: the pictures, the narration and its word timings.
+ * The clips (and everything after them) wait until the narration is timed (sceneTiming).
+ */
+export const TIMING_PARTS: ReadonlySet<StepPart> = new Set<StepPart>(["still", "narration", "words"]);
+
+/** A scene is cut this long before the next one's lines start; the last one runs this long past its last word. */
+export const SCENE_LEAD = 0.2;
+export const SCENE_TAIL = 1;
+/** A change keeps a scene's clips when its new length is within this of the old one (the next scene absorbs the rest). */
+export const RETIME_TOLERANCE = 1;
+
+/** A timed stretch of the narration: a word, a phrase or a caption line (transcript cues). */
+export interface TimedText {
+ start: number;
+ end: number;
+ text: string;
+}
+
+const token = (w: string) =>
+ w
+ .toLowerCase()
+ .normalize("NFKD")
+ .replace(/[^\p{L}\p{N}]+/gu, "");
+const tokens = (s: string) => s.split(/\s+/).map(token).filter(Boolean);
+
+/** Where the narration's blocks start (null: a block without lines) and where its last word ends, in seconds. */
+export interface SpokenTimes {
+ starts: (number | null)[];
+ end: number;
+}
+
+/**
+ * When each block's lines are spoken, from the narration's timings: the script's words matched in
+ * order against the timed words (forced alignment gives every word; an ASR may hear some differently,
+ * and those are interpolated). Null when the timings can't be this narration (fewer than half the
+ * words match, e.g. a demo transcript).
+ */
+export function spokenTimes(blocks: Pick<ScriptBlock, "narration">[], cues: TimedText[]): SpokenTimes | null {
+ const heard: { w: string; start: number; end: number }[] = [];
+ for (const c of cues) {
+ if (!Number.isFinite(c.start) || !Number.isFinite(c.end) || c.end < c.start || typeof c.text !== "string") continue;
+ const ws = tokens(c.text);
+ const step = (c.end - c.start) / Math.max(1, ws.length);
+ ws.forEach((w, j) => heard.push({ w, start: c.start + step * j, end: c.start + step * (j + 1) }));
+ }
+ const script = blocks.flatMap((b, i) => tokens(b.narration).map((w) => ({ w, block: i })));
+ if (!heard.length || !script.length) return null;
+ const at: (number | null)[] = script.map(() => null);
+ const endAt: (number | null)[] = script.map(() => null);
+ let p = 0;
+ for (let i = 0; i < script.length; i++) {
+ for (let q = p; q < Math.min(heard.length, p + 6); q++) {
+ if (heard[q].w !== script[i].w) continue;
+ // Skipping heard words is only safe when the next word agrees too (a common word further on isn't a match).
+ if (q > p && i + 1 < script.length && q + 1 < heard.length && heard[q + 1].w !== script[i + 1].w) continue;
+ at[i] = heard[q].start;
+ endAt[i] = heard[q].end;
+ p = q + 1;
+ break;
+ }
+ }
+ const known = at.flatMap((t, i) => (t === null ? [] : [i]));
+ if (known.length < Math.max(1, script.length * 0.5)) return null;
+ const first = known[0];
+ const last = known[known.length - 1];
+ const pace = last > first ? (at[last]! - at[first]!) / (last - first) : 0.4;
+ // Words nobody heard: in proportion between the words around them.
+ let prev = -1;
+ for (const k of known) {
+ for (let i = prev + 1; i < k; i++) {
+ at[i] = prev < 0 ? Math.max(0, at[k]! - (k - i) * pace) : at[prev]! + ((at[k]! - at[prev]!) * (i - prev)) / (k - prev);
+ }
+ prev = k;
+ }
+ for (let i = last + 1; i < script.length; i++) at[i] = at[last]! + (i - last) * pace;
+ const starts: (number | null)[] = blocks.map(() => null);
+ script.forEach((s, i) => {
+ if (starts[s.block] === null) starts[s.block] = at[i];
+ });
+ const end = endAt[last]! + (script.length - 1 - last) * pace;
+ return { starts, end };
+}
+
+/**
+ * How many seconds of film each block gets: the span of its lines in the narration, made with the video
+ * model's shots. Each scene is measured from where the film is so far, so a shot's rounding is absorbed
+ * by the next scene and picture and voice stay together over the whole film. Blocks without lines keep
+ * their own length (carved out of the scene before them). With `current` (a re-timing after a change),
+ * a scene keeps its length — and its clips — when the new one is within RETIME_TOLERANCE.
+ */
+export function sceneTiming(blocks: ScriptBlock[], spoken: SpokenTimes, video: ModelDef | undefined, current?: Record<string, number>): Record<string, number> {
+ const out: Record<string, number> = {};
+ let film = 0;
+ blocks.forEach((b, i) => {
+ let want = b.seconds;
+ if (spoken.starts[i] !== null) {
+ let k = i + 1;
+ let quiet = 0;
+ while (k < blocks.length && spoken.starts[k] === null) quiet += blocks[k++].seconds;
+ const until = k < blocks.length ? spoken.starts[k]! - SCENE_LEAD : spoken.end + SCENE_TAIL;
+ want = until - quiet - film;
+ }
+ want = Math.max(MIN_BLOCK, want);
+ const keep = current?.[b.id];
+ const secs = keep !== undefined && keep >= MIN_BLOCK && Math.abs(keep - want) <= RETIME_TOLERANCE ? keep : filmSeconds(want, video);
+ out[b.id] = secs;
+ film += secs;
+ });
+ return out;
+}
+
+/** The planned lengths as film (no word timings to cut to). */
+export const plannedTiming = (blocks: ScriptBlock[], video: ModelDef | undefined): Record<string, number> => Object.fromEntries(blocks.map((b) => [b.id, filmSeconds(b.seconds, video)]));
+
+/** Blocks with their film lengths (once the narration is timed). */
+export const withTiming = (blocks: ScriptBlock[], timing: Record<string, number> | undefined): ScriptBlock[] =>
+ timing ? blocks.map((b) => (timing[b.id] !== undefined ? { ...b, seconds: timing[b.id] } : b)) : blocks;
+
+/** Where each scene sits in the film, from the graph's clips (what the film really is). */
+export function sceneSpans(graph: Pick<GraphStep, "part" | "block" | "seconds">[], count: number): { start: number; seconds: number }[] {
+ const secs = Array.from({ length: count }, () => 0);
+ for (const s of graph) if (s.part === "clip" && s.block !== undefined && s.block < count) secs[s.block] += s.seconds ?? 0;
+ let t = 0;
+ return secs.map((seconds) => {
+ const start = t;
+ t += seconds;
+ return { start, seconds };
+ });
+}
+
// ---------------------------------------------------------------------------
// Changes (timeline editor) and retries
@@ -1157,7 +1325,7 @@ export const PART_LABELS: Record<StepPart, string> = {
narration: "Narration",
music: "Music",
mix: "Mixing",
- words: "Caption timing",
+ words: "Timing",
captions: "Subtitles",
};
@@ -1249,6 +1417,12 @@ const OFFLINE_TOPICS: Record<FacelessGenre, [string, string][]> = {
["Myths about {s}, busted", "What's true, what isn't, and why."],
["{S} explained in three minutes", "Everything you need, nothing you don't."],
["What nobody tells you about {s}", "The part the textbooks skip."],
+ ["The biggest mistakes people make with {s}", "And the easy way to avoid them."],
+ ["Where {s} came from", "The origin story, in plain words."],
+ ["{S}: a beginner's guide", "Start here if you know nothing yet."],
+ ["Why {s} matters more than you think", "The everyday impact, made visible."],
+ ["The future of {s}", "What changes next, and what stays."],
+ ["{S} by the numbers", "The figures that tell the real story."],
],
history: [
["The untold beginning of {s}", "Where it really started."],
@@ -1257,6 +1431,12 @@ const OFFLINE_TOPICS: Record<FacelessGenre, [string, string][]> = {
["The rise and fall of {s}", "From the first spark to the end."],
["{S}: the mystery historians still argue about", "The evidence, and the theories."],
["A day in the life during {s}", "What it was really like to be there."],
+ ["The forgotten people of {s}", "Names that deserve to be remembered."],
+ ["The biggest mistake in the history of {s}", "One decision, and its price."],
+ ["{S} in five turning points", "The moments that decided everything."],
+ ["What really caused {s}?", "The causes behind the headlines."],
+ ["Myths and truths about {s}", "Separating legend from the record."],
+ ["The legacy of {s}", "What it left behind, and where to see it today."],
],
kids: [
["Let's learn about {s}!", "A bright, friendly first look."],
@@ -1265,6 +1445,12 @@ const OFFLINE_TOPICS: Record<FacelessGenre, [string, string][]> = {
["Why is {s} so amazing?", "Fun facts to share at dinner."],
["Counting with {s}", "One, two, three — let's go!"],
["Bedtime story: {s}", "A calm story to end the day."],
+ ["The colours of {s}", "Spot every colour together."],
+ ["{S}: true or false?", "A fun quiz with big surprises."],
+ ["A day with {s}", "Follow along from morning to night."],
+ ["Let's draw {s}!", "Easy shapes, step by step."],
+ ["The ABCs of {s}", "A letter for every fun fact."],
+ ["Super silly facts about {s}", "Giggles guaranteed."],
],
storytelling: [
["The legend of {s}", "An old tale, told from the beginning."],
@@ -1273,22 +1459,38 @@ const OFFLINE_TOPICS: Record<FacelessGenre, [string, string][]> = {
["{S}: a story told in one night", "From dusk to dawn, one story."],
["The map that led to {s}", "A journey nobody expected to finish."],
["When {s} came back", "Some things don't stay gone."],
+ ["The keeper of {s}", "Someone has guarded it for a hundred years."],
+ ["The promise of {s}", "A vow that could not be broken."],
+ ["Lost in {s}", "Finding the way home took everything."],
+ ["The thief who stole {s}", "A heist nobody saw coming."],
+ ["One stormy night: {s}", "One night, one choice, one storm."],
+ ["The final chapter of {s}", "How it all ends."],
],
};
const fill = (t: string, s: string) => t.replaceAll("{S}", capital(s)).replaceAll("{s}", s);
-/** Topic suggestions without an LLM: templates per genre around the channel's subject; each round starts one further. */
-export function offlineTopics(idea: string, genre: FacelessGenre, count = 5, round = 0): TopicIdea[] {
+/**
+ * Topic suggestions without an LLM: 12 templates per genre around the channel's subject. Titles in
+ * `avoid` (the ones already shown) are left out, so "Generate new" brings new ones until the templates
+ * run out; without `avoid`, each round pages on by `count`.
+ */
+export function offlineTopics(idea: string, genre: FacelessGenre, count = 5, round = 0, avoid: string[] = []): TopicIdea[] {
const s = subjectOf(idea);
// "The rise and fall of {s}" for a channel about the rise and fall of empires would say it twice.
const lead = (t: string) => t.split("{")[0].replace(/^the\s+/i, "").trim().toLowerCase();
- const all = OFFLINE_TOPICS[genre] ?? OFFLINE_TOPICS.education;
- const list = all.filter(([t]) => !lead(t) || !s.toLowerCase().includes(lead(t)));
- return Array.from({ length: Math.min(count, list.length) }, (_, i) => {
- const [title, hook] = list[(i + round) % list.length];
- return { title: fill(title, s), hook };
- });
+ const all = (OFFLINE_TOPICS[genre] ?? OFFLINE_TOPICS.education)
+ .filter(([t]) => !lead(t) || !s.toLowerCase().includes(lead(t)))
+ .map(([title, hook]) => ({ title: fill(title, s), hook }));
+ const seen = new Set(avoid.map((t) => t.trim().toLowerCase()));
+ const fresh = all.filter((t) => !seen.has(t.title.toLowerCase()));
+ const n = Math.min(count, all.length);
+ if (!seen.size) {
+ const start = (round * count) % all.length;
+ return Array.from({ length: n }, (_, i) => all[(start + i) % all.length]);
+ }
+ // Every template shown already: start over with the ones shown longest ago.
+ return [...fresh, ...all.filter((t) => seen.has(t.title.toLowerCase()))].slice(0, n);
}
export const scriptSystem = `You write scripts for faceless videos: one narrator speaking over illustrated scenes, no presenter on camera.
@@ -1485,8 +1687,13 @@ export function defaultSettings(engine: Engine, genre: GenreInfo, o: { explainer
export interface PickerData {
voices: { id: string; name: string; hint?: string }[];
videoModels: { id: string; name: string; engine: Engine; resolutions: string[] }[];
+ /** How many style references each engine's picture model reads (the open one takes 2). */
+ maxStyleRefs: Record<Engine, number>;
}
+/** Style references an engine's picture model reads. */
+export const styleRefLimit = (engine: Engine, lookup: ModelLookup) => Math.min(MAX_STYLE_REFS, lookup(ENGINE_MODELS[engine].styleStill)?.options.maxImages ?? MAX_STYLE_REFS);
+
export function pickerData(lookup: ModelLookup): PickerData {
const voices = lookup(ENGINE_MODELS.cloud.narration)?.options.voices ?? [];
const videoModels = (["cloud", "open"] as const).flatMap((engine) =>
@@ -1495,7 +1702,11 @@ export function pickerData(lookup: ModelLookup): PickerData {
return m ? [{ id, name: m.name, engine, resolutions: m.options.resolutions ?? [] }] : [];
}),
);
- return { voices: voices.map((v) => ({ id: v.id, name: v.name, ...(v.hint && { hint: v.hint }) })), videoModels };
+ return {
+ voices: voices.map((v) => ({ id: v.id, name: v.name, ...(v.hint && { hint: v.hint }) })),
+ videoModels,
+ maxStyleRefs: { cloud: styleRefLimit("cloud", lookup), open: styleRefLimit("open", lookup) },
+ };
}
/** A short line the narrator reads for a voice preview. */
@@ -1522,6 +1733,8 @@ export interface FacelessChannel {
idea: string;
genre: FacelessGenre;
avatarUrl: string | null;
+ /** An avatar being drawn (it becomes avatarUrl once it's done, whoever is watching). */
+ avatarJob: string | null;
reference: ChannelReference | null;
settings: ChannelSettings;
createdAt: number;
@@ -1551,6 +1764,8 @@ export interface EpisodeChange {
part: ChangePart;
instruction: string;
costUsd: number | null;
+ /** Undone (the version before it is back). */
+ undone?: boolean;
}
export type StillEdits = Record<string, { source: string; instruction: string }>;
@@ -1561,10 +1776,21 @@ export interface EpisodePlan {
ids: Record<string, string>;
/** Picture edits the current version was made with. */
stillEdits?: StillEdits;
+ /** Each scene's length in the film, cut to where its lines are spoken (set once the narration is timed). */
+ timing?: Record<string, number>;
+ /** The scenes follow the planned lengths: the narration's timings couldn't be read (a demo transcript, say). */
+ untimed?: boolean;
+ /**
+ * The pictures, the narration and its timing are rendering; the clips, joins, music, mix and subtitles
+ * are created once the narration is timed (stage two).
+ */
+ awaiting?: boolean;
/** The version before the last change (Undo). */
- previous?: { ids: Record<string, string>; blocks: ScriptBlock[]; stillEdits?: StillEdits };
+ previous?: { ids: Record<string, string>; blocks: ScriptBlock[]; stillEdits?: StillEdits; timing?: Record<string, number>; untimed?: boolean; awaiting?: boolean };
/** The last finished film, shown while a change renders. */
lastFinal?: string;
+ /** "Upscale to 1080p": the upscaled copy of the finished film. */
+ upscaled?: string;
changes: EpisodeChange[];
}
@@ -1605,6 +1831,14 @@ export interface EpisodeView {
/** What the current version cost so far, and the render's estimate. */
spentUsd: number;
estimate: CostBreakdown | null;
+ /** Where each scene sits in the film (by block index), from its clips. */
+ scenes: { id: string; start: number; seconds: number }[];
+ /** "narration": the scenes are cut to the spoken lines; "planned": to the planned lengths (not timed yet, or no timings). */
+ timing: "narration" | "planned";
+ /** The 1080p copy ("Upscale to 1080p"), once asked for. */
+ upscaled: Generation | null;
+ /** What "Upscale to 1080p" would cost (null: not offered on this engine). */
+ upscale: { costUsd: number | null; demo: boolean } | null;
}
/** One item in the Explainer's history or a channel's episode list. */
@@ -1615,6 +1849,8 @@ export interface EpisodeCard {
title: string;
status: EpisodeStatus;
styleId: string;
+ /** Made with the user's own style references (not a preset). */
+ ownStyle: boolean;
aspect: EpisodeAspect;
seconds: number;
favorite: boolean;
@@ -1634,6 +1870,8 @@ export interface EstimateResult {
seconds: number;
blocks: number;
error?: string;
+ /** Things to know that don't stop the render (a music bed shorter than the film, images a model can't read). */
+ notes?: string[];
}
export interface ChangePreview {
@@ -1641,4 +1879,6 @@ export interface ChangePreview {
labels: string[];
costUsd: number | null;
demo: boolean;
+ /** The narration is read again: scenes whose timing moves by more than a second are animated again too (priced once it's timed). */
+ retime?: boolean;
}
diff --git a/src/server/db.ts b/src/server/db.ts
index 796053f9..b3ca79b2 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -175,13 +175,14 @@ const MIGRATIONS: string[] = [
edited_at INTEGER
);
CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,
- // Faceless Studio channels (genre, saved style / voice / aspect / subtitles) and episodes (Faceless and Explainer: script, render plan).
+ // Faceless Studio channels (genre, saved style / voice / aspect / subtitles, the avatar being drawn) and episodes (Faceless and Explainer: script, render plan).
`CREATE TABLE IF NOT EXISTS faceless_channels (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
idea TEXT NOT NULL,
genre TEXT NOT NULL,
avatar_url TEXT,
+ avatar_job TEXT,
reference_json TEXT,
settings_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
index b86296e3..12eba60e 100644
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@ -11,10 +11,13 @@ import {
defaultSettings,
ENGINE_MODELS,
estimateGraph,
- finalKey,
+ EXPLAINER_MAX,
+ EXPLAINER_MIN,
genreInfo,
getStyle,
MAX_SCRIPT,
+ MAX_SOURCES,
+ musicLength,
narrationText,
normalizeBlocks,
OFFLINE_NOTE,
@@ -24,17 +27,24 @@ import {
parseTopics,
parseVisuals,
placeholderBlocks,
+ plannedTiming,
planRerun,
- planRetry,
previewLine,
+ resolveModels,
+ sceneSpans,
+ sceneTiming,
scriptBrief,
scriptSystem,
splitScript,
+ spokenTimes,
+ styleRefLimit,
+ TIMING_PARTS,
topicsBrief,
topicsSystem,
totalSeconds,
visualsBrief,
visualsSystem,
+ withTiming,
wordsFor,
youtubeKind,
YOUTUBE_ERROR,
@@ -58,11 +68,11 @@ import {
type NarratorVoice,
type ScriptBlock,
type StillEdits,
+ type TimedText,
type TopicIdea,
} from "@/lib/catalog/faceless";
import { routesFor } from "@/lib/catalog/plan";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
-import { createPipeline } from "./chains";
import { db } from "./db";
import { listElements } from "./elements";
import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
@@ -74,14 +84,19 @@ import { fileUrl, saveFile } from "./storage";
/**
* Faceless Studio and the Explainer on the server: channels (genre, saved style, narrator, aspect,
- * subtitles), episodes (topic → script → review → render), the render itself as chained generations
- * (createPipeline over the graph from src/lib/catalog/faceless.ts), retries, block changes from the
- * timeline editor (re-run that block's steps and everything after them) with Undo, voice previews,
- * topic suggestions, link summaries and estimates.
+ * subtitles, a name and an avatar made for them), episodes (topic → script → review → render), the
+ * render itself as chained generations over the graph from src/lib/catalog/faceless.ts, retries,
+ * block changes from the timeline editor (re-run that block's steps and everything after them) with
+ * Undo, "Upscale to 1080p", voice previews, topic suggestions, link summaries and estimates.
+ *
+ * A render runs in two stages. Stage one is the pictures, the narration and its word timings. Once the
+ * narration is timed, `advance` cuts every scene to where its lines are spoken and creates stage two:
+ * the clips, the joins, the music, the mix and the subtitles. Both stages live in the generations
+ * table, so they survive restarts; stage two is created by whoever looks first: a read of the episode,
+ * or the background sweep (ensureFacelessRunner, started at boot by src/instrumentation.ts).
*
* Writing a script runs in this process (the install's LLM through the "llm" provider, or the offline
- * writer); a restart while it writes leaves the episode "write-failed" with a Try again. Rendering lives
- * in the generations table, so it survives restarts like any chained job.
+ * writer); a restart while it writes leaves the episode "write-failed" with a Try again.
*/
export class FacelessError extends Error {
@@ -102,6 +117,7 @@ interface ChannelRow {
idea: string;
genre: string;
avatar_url: string | null;
+ avatar_job: string | null;
reference_json: string | null;
settings_json: string;
created_at: number;
@@ -131,6 +147,7 @@ const toChannel = (r: ChannelRow): FacelessChannel => ({
idea: r.idea,
genre: genreInfo(r.genre).id,
avatarUrl: r.avatar_url,
+ avatarJob: r.avatar_job ?? null,
reference: r.reference_json ? (JSON.parse(r.reference_json) as ChannelReference) : null,
settings: JSON.parse(r.settings_json) as ChannelSettings,
createdAt: r.created_at,
@@ -175,8 +192,21 @@ function mustEpisode(id: string): FacelessEpisode {
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+export interface AskOptions {
+ /** Hears why there's no answer (the LLM failed, or took too long). */
+ onError?: (msg: string) => void;
+ /** Stops waiting (and cancels the LLM's job): the episode was deleted. */
+ signal?: AbortSignal;
+ /** How long to wait for the answer (default 8 minutes: a script on a slow local model). */
+ timeoutMs?: number;
+}
+
+/** Channel names and topic suggestions are waited for: a slow model gives way to the offline wording. */
+const NAME_TIMEOUT_MS = 15_000;
+const TOPICS_TIMEOUT_MS = 25_000;
+
/** One answer from the engine's text model, or null (no LLM, AI helper off, demo mode on, or it failed: `onError` hears why). */
-export async function askLlm(engine: Engine, system: string, user: string, onError?: (msg: string) => void): Promise<string | null> {
+export async function askLlm(engine: Engine, system: string, user: string, o: AskOptions = {}): Promise<string | null> {
if (getSetting("demoMode") === "on") return null;
const model = getModel(ENGINE_MODELS[engine].write);
const route = model?.routes.find((r) => r.op === "write");
@@ -187,20 +217,24 @@ export async function askLlm(engine: Engine, system: string, user: string, onErr
try {
const { externalId } = await llm.submit({ generationId: `faceless_${nanoid(6)}`, model, route, input: { prompt: user, extra: { system } } });
const ctx = { externalId, meta: {}, route, model, createdAt: Date.now() };
- const deadline = Date.now() + 8 * 60_000;
+ const deadline = Date.now() + (o.timeoutMs ?? 8 * 60_000);
while (Date.now() < deadline) {
await sleep(350);
+ if (o.signal?.aborted) {
+ await llm.cancel?.(ctx).catch(() => {});
+ return null;
+ }
const r = await llm.poll(ctx);
if (r.state === "succeeded") return r.outputs[0]?.text?.trim() || null;
if (r.state === "failed") {
- onError?.(r.error);
+ o.onError?.(r.error);
return null;
}
}
- await llm.cancel?.(ctx);
- onError?.("The LLM took too long");
+ await llm.cancel?.(ctx).catch(() => {});
+ o.onError?.("The LLM took too long");
} catch (e) {
- onError?.((e as Error).message);
+ o.onError?.((e as Error).message);
}
return null;
}
@@ -213,8 +247,21 @@ const ChannelDefaults = (engine: Engine, genre: FacelessGenre): ChannelSettings
return { engine, styleId: s.styleId, styleRefs: [], voice: s.voice, aspect: s.aspect, subtitles: s.subtitles, music: s.music, animation: s.animation, length: s.length };
};
+/** A finished avatar becomes the channel's picture (whoever is watching); a failed one is let go. */
+function refreshAvatar(r: ChannelRow): ChannelRow {
+ if (!r.avatar_job) return r;
+ const g = getGeneration(r.avatar_job, { includeDeleted: true });
+ if (g && (g.status === "queued" || g.status === "running")) return r;
+ const url = g?.status === "succeeded" ? (g.outputs.find((o) => o.kind === "image")?.url ?? null) : null;
+ const next = { ...r, avatar_job: null, avatar_url: url ?? r.avatar_url };
+ db().prepare("UPDATE faceless_channels SET avatar_url = ?, avatar_job = NULL WHERE id = ? AND avatar_job = ?").run(next.avatar_url, r.id, r.avatar_job);
+ return next;
+}
+
+const channelRow = (id: string) => db().prepare("SELECT * FROM faceless_channels WHERE id = ?").get(id) as ChannelRow | undefined;
+
export function listChannels(): FacelessChannel[] {
- const rows = db().prepare("SELECT * FROM faceless_channels ORDER BY updated_at DESC").all() as ChannelRow[];
+ const rows = (db().prepare("SELECT * FROM faceless_channels ORDER BY updated_at DESC").all() as ChannelRow[]).map(refreshAvatar);
const counts = new Map(
(db().prepare("SELECT channel_id, COUNT(*) AS n FROM faceless_episodes WHERE channel_id IS NOT NULL GROUP BY channel_id").all() as { channel_id: string; n: number }[]).map((r) => [r.channel_id, r.n]),
);
@@ -229,8 +276,8 @@ export function listChannels(): FacelessChannel[] {
}
export function getChannel(id: string): FacelessChannel | null {
- const r = db().prepare("SELECT * FROM faceless_channels WHERE id = ?").get(id) as ChannelRow | undefined;
- return r ? toChannel(r) : null;
+ const r = channelRow(id);
+ return r ? toChannel(refreshAvatar(r)) : null;
}
/** Title and thumbnail of a YouTube link (oEmbed, through the SSRF-safe fetch); the thumbnail is saved as an upload. */
@@ -254,26 +301,33 @@ async function readReference(url: string): Promise<ChannelReference> {
return ref;
}
+declare global {
+ var __fuobeFacelessNaming: Map<string, Promise<void>> | undefined;
+}
+const naming = () => (globalThis.__fuobeFacelessNaming ??= new Map<string, Promise<void>>());
+
+/** Wait for a new channel's name and avatar to be started (tests). */
+export const channelReady = (id: string) => naming().get(id) ?? Promise.resolve();
+
+const NAME_SYSTEM = "You name YouTube channels. Reply with the name only: 2–4 words, memorable, no quotes, no emoji.";
+
+/**
+ * A new channel is there straight away with a name taken from the idea; the LLM's name replaces it when
+ * it answers (within 15 s, and only while the channel still has the first name), then the avatar is drawn.
+ */
export async function createChannel(input: { idea: string; genre: FacelessGenre; engine: Engine; reference?: string; name?: string }): Promise<FacelessChannel> {
const idea = input.idea.trim();
if (!idea) throw new FacelessError("Describe the channel first");
const reference = input.reference?.trim() ? await readReference(input.reference) : null;
- let name = input.name?.trim() || null;
- if (!name) {
- const answer = await askLlm(
- input.engine,
- "You name YouTube channels. Reply with the name only: 2–4 words, memorable, no quotes, no emoji.",
- `Channel idea: ${idea}\nGenre: ${genreInfo(input.genre).label}`,
- );
- name = answer?.split("\n")[0].replace(/^["'“”]+|["'“”.]+$/g, "").trim().slice(0, 60) || null;
- }
+ const given = input.name?.trim().slice(0, 60) || null;
const now = Date.now();
const row: ChannelRow = {
id: nanoid(10),
- name: name || channelName(idea),
+ name: given ?? channelName(idea),
idea: idea.slice(0, 500),
genre: input.genre,
avatar_url: null,
+ avatar_job: null,
reference_json: reference ? JSON.stringify(reference) : null,
settings_json: JSON.stringify(ChannelDefaults(input.engine, input.genre)),
created_at: now,
@@ -282,6 +336,19 @@ export async function createChannel(input: { idea: string; genre: FacelessGenre;
db()
.prepare(`INSERT INTO faceless_channels (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
.run(row);
+ const job = (async () => {
+ if (!given) {
+ const answer = await askLlm(input.engine, NAME_SYSTEM, `Channel idea: ${idea}\nGenre: ${genreInfo(input.genre).label}`, { timeoutMs: NAME_TIMEOUT_MS });
+ const name = answer?.split("\n")[0].replace(/^["'“”]+|["'“”.]+$/g, "").trim().slice(0, 60);
+ if (name) db().prepare("UPDATE faceless_channels SET name = ? WHERE id = ? AND name = ?").run(name, row.id, row.name);
+ }
+ try {
+ if (channelRow(row.id)) makeAvatar(row.id);
+ } catch {
+ // No picture model can run right now: the channel shows its initials, and "Draw an avatar" is there.
+ }
+ })().finally(() => naming().delete(row.id));
+ naming().set(row.id, job);
return toChannel(row);
}
@@ -295,7 +362,10 @@ export async function updateChannel(
if (patch.name !== undefined) fields.name = patch.name.trim().slice(0, 60) || cur.name;
if (patch.idea !== undefined) fields.idea = patch.idea.trim().slice(0, 500) || cur.idea;
if (patch.genre) fields.genre = patch.genre;
- if (patch.avatarUrl !== undefined) fields.avatar_url = patch.avatarUrl;
+ if (patch.avatarUrl !== undefined) {
+ fields.avatar_url = patch.avatarUrl;
+ fields.avatar_job = null;
+ }
if (patch.reference !== undefined) fields.reference_json = patch.reference ? JSON.stringify(await readReference(patch.reference)) : null;
if (patch.settings) fields.settings_json = JSON.stringify({ ...cur.settings, ...patch.settings });
const keys = Object.keys(fields);
@@ -307,16 +377,20 @@ export async function updateChannel(
return getChannel(id)!;
}
-/** Deletes the channel and its episodes; their videos stay in the Library. */
-export function deleteChannel(id: string): void {
- if (!getChannel(id)) throw new FacelessError("Channel not found", 404);
+/** Deletes the channel and its episodes, stopping whatever they still render; finished videos stay in the Library. */
+export async function deleteChannel(id: string): Promise<void> {
+ const c = channelRow(id);
+ if (!c) throw new FacelessError("Channel not found", 404);
+ const episodes = (db().prepare("SELECT * FROM faceless_episodes WHERE channel_id = ?").all(id) as EpisodeRow[]).map(toEpisode);
+ const stops = [...episodes.flatMap(stopEpisode), ...(c.avatar_job ? [cancelGeneration(c.avatar_job)] : [])];
db().transaction(() => {
db().prepare("DELETE FROM faceless_episodes WHERE channel_id = ?").run(id);
db().prepare("DELETE FROM faceless_channels WHERE id = ?").run(id);
})();
+ await Promise.all(stops);
}
-/** A channel avatar in the channel's style (one picture generation). */
+/** A channel avatar in the channel's style (one picture generation); it becomes the channel's picture when it's done. */
export function makeAvatar(id: string): Generation {
const c = getChannel(id);
if (!c) throw new FacelessError("Channel not found", 404);
@@ -329,6 +403,7 @@ export function makeAvatar(id: string): Generation {
params: { aspectRatio: "1:1", numOutputs: 1 },
title: `${c.name} · avatar`,
});
+ db().prepare("UPDATE faceless_channels SET avatar_job = ? WHERE id = ?").run(g.id, id);
return g;
}
@@ -338,19 +413,24 @@ export function makeAvatar(id: string): Generation {
export async function suggestTopics(input: { idea: string; genre: FacelessGenre; engine: Engine; avoid?: string[]; count?: number; round?: number; reference?: string }): Promise<{ topics: TopicIdea[]; offline: boolean }> {
const count = Math.max(4, Math.min(6, input.count ?? 5));
const genre = genreInfo(input.genre);
- const answer = await askLlm(input.engine, topicsSystem, topicsBrief({ idea: input.idea, genre, count, avoid: input.avoid, reference: input.reference }));
+ const answer = await askLlm(input.engine, topicsSystem, topicsBrief({ idea: input.idea, genre, count, avoid: input.avoid, reference: input.reference }), { timeoutMs: TOPICS_TIMEOUT_MS });
const topics = answer ? parseTopics(answer).slice(0, count) : [];
if (topics.length >= 3) return { topics, offline: false };
- return { topics: offlineTopics(input.idea, genre.id, count, input.round ?? 0), offline: true };
+ return { topics: offlineTopics(input.idea, genre.id, count, input.round ?? 0, input.avoid), offline: true };
}
// ---------------------------------------------------------------------------
// Episodes: create, write, review
+interface WritingJob {
+ job: Promise<void>;
+ abort: AbortController;
+}
+
declare global {
- var __fuobeFacelessWriting: Map<string, Promise<void>> | undefined;
+ var __fuobeFacelessWriting: Map<string, WritingJob> | undefined;
}
-const writing = () => (globalThis.__fuobeFacelessWriting ??= new Map<string, Promise<void>>());
+const writing = () => (globalThis.__fuobeFacelessWriting ??= new Map<string, WritingJob>());
export interface EpisodeInput {
kind: "faceless" | "explainer";
@@ -362,6 +442,8 @@ export interface EpisodeInput {
sources?: ExplainerSource[];
/** Explainer: render as soon as the script is written (no review step). */
autoRender?: boolean;
+ /** Save this episode's look and sound as the channel's (default: only for a channel's first episode). */
+ saveLook?: boolean;
}
function cleanSettings(s: EpisodeSettings): EpisodeSettings {
@@ -371,9 +453,9 @@ function cleanSettings(s: EpisodeSettings): EpisodeSettings {
}
return {
...s,
- styleRefs: s.styleRefs.slice(0, 3),
+ styleRefs: s.styleRefs.slice(0, styleRefLimit(s.engine, getModel)),
elements: [...new Set(s.elements)].slice(0, 8),
- length: Math.max(15, Math.min(600, Math.round(s.length))),
+ length: Math.max(EXPLAINER_MIN, Math.min(EXPLAINER_MAX, Math.round(s.length))),
};
}
@@ -385,7 +467,7 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
const channel = input.channelId ? getChannel(input.channelId) : null;
if (input.channelId && !channel) throw new FacelessError("Channel not found", 404);
const settings = cleanSettings(input.settings);
- const sources = (input.sources ?? []).slice(0, 3);
+ const sources = (input.sources ?? []).slice(0, MAX_SOURCES);
settings.sourceImages = sources.filter((s): s is Extract<ExplainerSource, { kind: "image" }> => s.kind === "image").map((s) => s.url);
const now = Date.now();
const title = (topic || pasted).replace(/\s+/g, " ").slice(0, 80) || "Untitled episode";
@@ -405,11 +487,11 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
created_at: now,
updated_at: now,
};
+ const first = channel ? !(db().prepare("SELECT 1 FROM faceless_episodes WHERE channel_id = ? LIMIT 1").get(channel.id) as unknown) : false;
db()
.prepare(`INSERT INTO faceless_episodes (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
.run(row);
- if (channel) {
- // The channel remembers the latest look and voice.
+ if (channel && (input.saveLook ?? first)) {
void updateChannel(channel.id, {
settings: { engine: settings.engine, styleId: settings.styleId, styleRefs: settings.styleRefs, voice: settings.voice, aspect: settings.aspect, subtitles: settings.subtitles, music: settings.music, animation: settings.animation, length: settings.length },
});
@@ -420,29 +502,32 @@ export function createEpisode(input: EpisodeInput): FacelessEpisode {
/** Write (or split) the script in the background; the episode moves to review, or straight to rendering. */
function startWriting(id: string, pasted: string, autoRender: boolean): Promise<void> {
+ const abort = new AbortController();
const job = (async () => {
try {
- await writeScript(id, pasted);
+ await writeScript(id, pasted, abort.signal);
} catch (e) {
- updateEpisodeRow(id, { status: "write-failed", error: (e as Error).message || "Couldn't write the script" });
+ if (!abort.signal.aborted && episodeRow(id)) updateEpisodeRow(id, { status: "write-failed", error: (e as Error).message || "Couldn't write the script" });
return;
}
- if (!autoRender) return;
+ if (!autoRender || abort.signal.aborted || !episodeRow(id)) return;
try {
renderEpisode(id);
} catch (e) {
// The script is there: show it with what's in the way (a missing voice, an engine that isn't connected).
updateEpisodeRow(id, { status: "review", error: (e as Error).message });
}
- })().finally(() => writing().delete(id));
- writing().set(id, job);
+ })().finally(() => {
+ if (writing().get(id)?.abort === abort) writing().delete(id);
+ });
+ writing().set(id, { job, abort });
return job;
}
/** Wait for a script that's being written (tests, and the API's `?wait=1`). */
-export const scriptWritten = (id: string) => writing().get(id) ?? Promise.resolve();
+export const scriptWritten = (id: string) => writing().get(id)?.job ?? Promise.resolve();
-async function writeScript(id: string, pasted: string): Promise<void> {
+async function writeScript(id: string, pasted: string, signal: AbortSignal): Promise<void> {
const ep = mustEpisode(id);
const genre = genreInfo(ep.channelId ? (getChannel(ep.channelId)?.genre ?? "education") : "education");
const channel = ep.channelId ? getChannel(ep.channelId) : null;
@@ -456,11 +541,11 @@ async function writeScript(id: string, pasted: string): Promise<void> {
.map((e) => ({ handle: e.handle, kind: e.kind, description: e.description }));
const textSources = ep.sources.flatMap((x) => (x.kind === "text" ? [`${x.name}: ${x.text.slice(0, 6000)}`] : x.kind === "link" ? [`${x.title ?? x.url} (${x.url}): ${x.text.slice(0, 6000)}`] : []));
let failure = "";
- const onError = (m: string) => (failure = m);
+ const ask = { onError: (m: string) => (failure = m), signal };
let script: EpisodeScript;
if (pasted) {
const blocks = splitScript(pasted);
- const answer = await askLlm(s.engine, visualsSystem, visualsBrief(blocks, style.name, ep.topic || pasted.slice(0, 200)), onError);
+ const answer = await askLlm(s.engine, visualsSystem, visualsBrief(blocks, style.name, ep.topic || pasted.slice(0, 200)), ask);
const visuals = answer ? parseVisuals(answer, blocks.length) : null;
script = {
source: "pasted",
@@ -481,7 +566,7 @@ async function writeScript(id: string, pasted: string): Promise<void> {
sources: textSources,
auto,
});
- const answer = await askLlm(s.engine, scriptSystem, brief, onError);
+ const answer = await askLlm(s.engine, scriptSystem, brief, ask);
const parsed = answer ? parseScript(answer) : null;
if (parsed?.blocks.length) {
script = { source: "ai", title: parsed.title ?? undefined, blocks: parsed.blocks };
@@ -491,7 +576,7 @@ async function writeScript(id: string, pasted: string): Promise<void> {
script = { source: "ai", blocks, offline: true, note: failure ? `${OFFLINE_NOTE} (${failure})` : OFFLINE_NOTE };
}
}
- if (!episodeRow(id)) return;
+ if (signal.aborted || !episodeRow(id)) return;
updateEpisodeRow(id, {
status: "review",
error: null,
@@ -503,7 +588,7 @@ async function writeScript(id: string, pasted: string): Promise<void> {
/** Write the script again (after a failure, or for a fresh draft). */
export function rewriteEpisode(id: string): FacelessEpisode {
const ep = mustEpisode(id);
- if (ep.status === "rendering" || ep.status === "done") throw new FacelessError("This episode is already rendered — change scenes in the timeline instead", 409);
+ if (ep.status === "rendering" || ep.status === "done" || ep.plan) throw new FacelessError("This episode is already rendered — change scenes in the timeline instead", 409);
if (writing().has(id)) return ep;
updateEpisodeRow(id, { status: "writing", error: null });
startWriting(id, ep.script.source === "pasted" ? ep.script.blocks.map((b) => b.narration).join(" ") : "", false);
@@ -529,9 +614,23 @@ export function updateEpisode(id: string, patch: { title?: string; favorite?: bo
return mustEpisode(id);
}
-export function deleteEpisode(id: string): void {
- mustEpisode(id);
+/** Stop an episode: the script writer, and every step still queued or running (now, and the version Undo keeps). */
+function stopEpisode(ep: FacelessEpisode): Promise<void>[] {
+ const w = writing().get(ep.id);
+ if (w) {
+ w.abort.abort();
+ writing().delete(ep.id);
+ }
+ const ids = new Set([...Object.values(ep.plan?.ids ?? {}), ...Object.values(ep.plan?.previous?.ids ?? {}), ...(ep.plan?.upscaled ? [ep.plan.upscaled] : [])]);
+ return [...ids].map((g) => cancelGeneration(g).catch(() => {}));
+}
+
+/** Deletes the episode and stops what it still renders; its finished pictures, clips and videos stay in the Library. */
+export async function deleteEpisode(id: string): Promise<void> {
+ const ep = mustEpisode(id);
+ const stops = stopEpisode(ep);
db().prepare("DELETE FROM faceless_episodes WHERE id = ?").run(id);
+ await Promise.all(stops);
}
// ---------------------------------------------------------------------------
@@ -595,60 +694,16 @@ function buildGraph(ep: FacelessEpisode, blocks = ep.script.blocks, stillEdits?:
}
}
-/**
- * Cloud episodes with a music bed are mixed by the open mixer (the cloud soundtrack tool takes one
- * track): it must run the way the rest does.
- */
-function checkMusicMix(ep: FacelessEpisode, graph: GraphStep[]): void {
- if (ep.settings.engine !== "cloud" || !ep.settings.music) return;
- const mix = graph.find((s) => s.key === "mix")!;
- if (engineMode() === "cloud") throw new FacelessError("A music bed is mixed under the voice by the open-source mixer, and this install is set to cloud APIs only — turn music off", 422);
- const mixDemo = runsAsDemo(mix.request.modelId, "mux");
- const videoDemo = runsAsDemo(graph.find((s) => s.part === "clip")!.request.modelId, "i2v");
- if (mixDemo && !videoDemo) throw new FacelessError("A music bed is mixed under the voice by ComfyUI (the cloud soundtrack tool takes one track) — start ComfyUI, or turn music off", 422);
-}
+/** The episode's graph as it renders now: its blocks at their film lengths (once timed) and its picture edits. */
+const currentGraph = (ep: FacelessEpisode, blocks = ep.script.blocks) => buildGraph(ep, withTiming(blocks, ep.plan?.timing), ep.plan?.stillEdits);
-function toPipelineSteps(graph: GraphStep[]) {
- return graph.map((s) => ({ key: s.key, request: { ...s.request, step: s.request.step ?? { label: s.label, index: 0, of: 1 } }, after: s.after, chain: s.chain }));
-}
+const previewStep = (s: GraphStep) => previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0);
-/** Start the render: every step as a chained generation (validated as a whole before anything is created). */
-export function renderEpisode(id: string): FacelessEpisode {
- const ep = mustEpisode(id);
- if (ep.status === "writing") throw new FacelessError("The script is still being written", 409);
- if (ep.status === "rendering") throw new FacelessError("This episode is already rendering", 409);
- if (ep.plan) throw new FacelessError(ep.status === "done" ? "This episode is done — change scenes in the timeline" : "This episode already rendered — use Retry", 409);
- const blocks = normalizeBlocks(ep.script.blocks);
- if (!blocks.length) throw new FacelessError("The script has no scenes yet");
- const ready = { ...ep, script: { ...ep.script, blocks } };
- const graph = buildGraph(ready, blocks);
- checkMusicMix(ready, graph);
- let pipeline: ReturnType<typeof createPipeline>;
- try {
- pipeline = createPipeline(toPipelineSteps(graph));
- } catch (e) {
- throw new FacelessError((e as Error).message, 422);
- }
- const plan: EpisodePlan = {
- batchId: pipeline.batchId,
- ids: Object.fromEntries(Object.entries(pipeline.byKey).map(([k, g]) => [k, g.id])),
- changes: [],
- };
- updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(plan), script_json: JSON.stringify(ready.script) });
- return mustEpisode(id);
-}
-
-/**
- * Create the `rerun` steps of a graph again, waiting on the new ones or on the current generations of
- * the steps that are kept. Everything is previewed first, so a bad step creates nothing.
- */
-function relaunch(graph: GraphStep[], ids: Record<string, string>, rerun: string[], batchId: string): Record<string, string> {
- const todo = new Set(rerun);
- const steps = graph.filter((s) => todo.has(s.key));
- for (const s of graph) if (!todo.has(s.key) && !ids[s.key]) throw new FacelessError(`“${s.label}” has no result to reuse — try again`, 409);
+/** Every step checked with placeholders for what earlier steps make, and one mode for all: nothing is created when one can't run. */
+function validate(steps: GraphStep[]): void {
const previews = steps.map((s) => {
try {
- return { key: s.key, label: s.label, ...previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0) };
+ return { label: s.label, ...previewStep(s) };
} catch (e) {
throw new FacelessError(`${s.label}: ${(e as Error).message}`, 422);
}
@@ -656,6 +711,21 @@ function relaunch(graph: GraphStep[], ids: Record<string, string>, rerun: string
const demo = previews.find((p) => p.demo);
const real = previews.find((p) => !p.demo);
if (demo && real) throw new FacelessError(`${demo.label} would run as a demo (${demo.model.name} isn't connected) while ${real.label} runs for real — connect it in Settings, or turn on demo mode`, 422);
+}
+
+/**
+ * Create the `rerun` steps of a graph, waiting on the new ones or on the current generations of the
+ * steps they reuse. They're all checked first, so a bad step creates nothing.
+ */
+function relaunch(graph: GraphStep[], ids: Record<string, string>, rerun: string[], batchId: string): Record<string, string> {
+ const todo = new Set(rerun);
+ const steps = graph.filter((s) => todo.has(s.key));
+ for (const s of steps) {
+ for (const a of s.after ?? []) {
+ if (!todo.has(a) && !ids[a]) throw new FacelessError(`“${graph.find((x) => x.key === a)?.label ?? a}” has no result to reuse — try again`, 409);
+ }
+ }
+ validate(steps);
const next = { ...ids };
const made: Generation[] = [];
try {
@@ -672,25 +742,130 @@ function relaunch(graph: GraphStep[], ids: Record<string, string>, rerun: string
return next;
}
+/** Only the steps the graph has (a re-timed scene may have fewer shots, a refolded join other keys). */
+const prune = (ids: Record<string, string>, graph: GraphStep[]) => {
+ const keys = new Set(graph.map((s) => s.key));
+ return Object.fromEntries(Object.entries(ids).filter(([k]) => keys.has(k)));
+};
+
+const partOf = (graph: GraphStep[]) => {
+ const m = new Map(graph.map((s) => [s.key, s.part]));
+ return (k: string) => m.get(k)!;
+};
+
+/**
+ * Start `changed` and everything after it. While the scenes aren't timed yet (the first render), or
+ * when the narration is read again, only the pictures, the narration and its timing start now: the
+ * rest waits for `advance`, which cuts the scenes to the new timing first.
+ */
+function launch(ep: FacelessEpisode, graph: GraphStep[], ids: Record<string, string>, changed: string[], batchId: string): { ids: Record<string, string>; awaiting: boolean; started: number } {
+ const { rerun } = planRerun(graph, changed);
+ const part = partOf(graph);
+ const needsTiming = !ep.plan?.timing || !!ep.plan.awaiting || rerun.includes("words");
+ if (!needsTiming) return { ids: prune(relaunch(graph, ids, rerun, batchId), graph), awaiting: false, started: rerun.length };
+ const now = rerun.filter((k) => TIMING_PARTS.has(part(k)));
+ const next = relaunch(graph, ids, now, batchId);
+ for (const k of rerun) if (!TIMING_PARTS.has(part(k))) delete next[k];
+ return { ids: prune(next, graph), awaiting: true, started: now.length };
+}
+
+/** The narration's timed words: forced alignment or ASR cues (null for a demo transcript or none). */
+function narrationCues(ep: FacelessEpisode): TimedText[] | null {
+ const words = getGeneration(ep.plan?.ids.words ?? "", { includeDeleted: true });
+ const out = words?.status === "succeeded" ? words.outputs.find((o) => o.kind === "text") : undefined;
+ if (!out || out.meta?.demo) return null;
+ return Array.isArray(out.meta?.cues) ? (out.meta.cues as TimedText[]) : null;
+}
+
+/**
+ * Stage two: the narration is timed, so each scene is cut to where its lines are spoken (sceneTiming),
+ * then the clips, joins, music, mix and subtitles are created. After a change, scenes whose length moved
+ * by more than RETIME_TOLERANCE are animated again; the others keep their clips. Without usable
+ * timings (a demo transcript) the scenes keep their planned lengths.
+ */
+function advance(ep: FacelessEpisode): FacelessEpisode {
+ const plan = ep.plan!;
+ const blocks = ep.script.blocks;
+ const video = getModel(resolveModels(ep.settings, narrationText(blocks).length, getModel).video);
+ const cues = narrationCues(ep);
+ const spoken = cues ? spokenTimes(blocks, cues) : null;
+ const timing = spoken ? sceneTiming(blocks, spoken, video, plan.timing) : (plan.timing ?? plannedTiming(blocks, video));
+ const graph = buildGraph(ep, withTiming(blocks, timing), plan.stillEdits);
+ const part = partOf(graph);
+ const status = statusMap(plan.ids);
+ const moved = new Set(blocks.filter((b) => plan.timing?.[b.id] !== timing[b.id]).map((b) => b.id));
+ const changed = graph
+ .filter((s) => !plan.ids[s.key] || status[s.key] === "failed" || status[s.key] === "canceled" || (s.part === "clip" && moved.has(blocks[s.block!].id)))
+ .map((s) => s.key);
+ // A bed that no longer covers the film is made again.
+ const music = graph.find((s) => s.key === "music");
+ if (music && plan.ids.music && !changed.includes("music")) {
+ const had = getGeneration(plan.ids.music, { includeDeleted: true })?.request.params?.duration ?? 0;
+ if (had < (music.request.params?.duration ?? 0)) changed.push("music");
+ }
+ const rerun = planRerun(graph, changed).rerun.filter((k) => !TIMING_PARTS.has(part(k)));
+ const ids = prune(relaunch(graph, plan.ids, rerun, plan.batchId), graph);
+ const next: EpisodePlan = { ...plan, ids, timing, untimed: !spoken, awaiting: false };
+ updateEpisodeRow(ep.id, { status: "rendering", error: null, plan_json: JSON.stringify(next) });
+ return mustEpisode(ep.id);
+}
+
+/** Start the render: the whole graph is checked first, then stage one (pictures, narration, its timing) starts. */
+export function renderEpisode(id: string): FacelessEpisode {
+ const ep = mustEpisode(id);
+ if (ep.status === "writing") throw new FacelessError("The script is still being written", 409);
+ if (ep.status === "rendering") throw new FacelessError("This episode is already rendering", 409);
+ if (ep.plan) throw new FacelessError(ep.status === "done" ? "This episode is done — change scenes in the timeline" : "This episode already rendered — use Retry", 409);
+ const blocks = normalizeBlocks(ep.script.blocks);
+ if (!blocks.length) throw new FacelessError("The script has no scenes yet");
+ const ready = { ...ep, script: { ...ep.script, blocks } };
+ const graph = buildGraph(ready, blocks);
+ validate(graph);
+ const batchId = nanoid(10);
+ const { ids, awaiting } = launch(ready, graph, {}, graph.map((s) => s.key), batchId);
+ const plan: EpisodePlan = { batchId, ids, awaiting, changes: [] };
+ updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(plan), script_json: JSON.stringify(ready.script) });
+ ensureFacelessRunner();
+ return mustEpisode(id);
+}
+
const statusMap = (ids: Record<string, string>) =>
- Object.fromEntries(Object.entries(ids).map(([k, id]) => [k, getGeneration(id)?.status])) as Record<string, string | undefined>;
+ Object.fromEntries(Object.entries(ids).map(([k, id]) => [k, getGeneration(id, { includeDeleted: true })?.status])) as Record<string, string | undefined>;
/** Redo the steps that failed (and what waited on them); finished steps are kept. */
export function retryEpisode(id: string): FacelessEpisode {
const ep = mustEpisode(id);
if (!ep.plan) return renderEpisode(id);
- const graph = buildGraph(ep, ep.script.blocks, ep.plan.stillEdits);
+ const graph = currentGraph(ep);
const status = statusMap(ep.plan.ids);
if (Object.values(status).some((s) => s === "queued" || s === "running")) {
// Steps still waiting on a failed one fail on the runner's next tick; retry those too.
const live = graph.filter((s) => status[s.key] === "queued" || status[s.key] === "running");
if (live.some((s) => !s.after?.length || s.after.some((a) => status[a] !== "failed" && status[a] !== "canceled"))) throw new FacelessError("Still rendering — retry once it stops", 409);
}
- const plan = planRetry(graph, Object.fromEntries(Object.entries(status).map(([k, v]) => [k, v === "queued" || v === "running" ? "failed" : v])));
- if (!plan.rerun.length) return ep;
- for (const k of plan.rerun) if (ep.plan.ids[k]) void cancelGeneration(ep.plan.ids[k]);
- const ids = relaunch(graph, ep.plan.ids, plan.rerun, ep.plan.batchId);
- updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify({ ...ep.plan, ids } satisfies EpisodePlan) });
+ const part = partOf(graph);
+ const broken = graph
+ .filter((s) => {
+ const st = status[s.key];
+ // Steps still to come after the timing aren't broken: advance makes them.
+ if (!st) return !ep.plan!.awaiting || TIMING_PARTS.has(part(s.key));
+ return st === "failed" || st === "canceled" || st === "queued" || st === "running";
+ })
+ .map((s) => s.key);
+ if (!broken.length && !ep.plan.awaiting) return ep;
+ for (const k of planRerun(graph, broken).rerun) if (ep.plan.ids[k]) void cancelGeneration(ep.plan.ids[k]);
+ const { ids, awaiting, started } = launch(ep, graph, ep.plan.ids, broken, ep.plan.batchId);
+ updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify({ ...ep.plan, ids, awaiting } satisfies EpisodePlan) });
+ ensureFacelessRunner();
+ // Everything before the timing is there (it was stage two that couldn't start): start it now.
+ if (awaiting && !started) {
+ try {
+ return advance(mustEpisode(id));
+ } catch (e) {
+ updateEpisodeRow(id, { status: "failed", error: (e as Error).message });
+ throw e instanceof FacelessError ? e : new FacelessError((e as Error).message, 422);
+ }
+ }
return mustEpisode(id);
}
@@ -706,7 +881,7 @@ export interface ChangeInput {
narration?: string[];
}
-/** The blocks, picture edits and graph a change would render. */
+/** The blocks, picture edits and graph a change would render, and the steps it touches. */
function changed(ep: FacelessEpisode, c: ChangeInput) {
if (!ep.plan) throw new FacelessError("Render the episode first", 409);
const ids = c.blocks.filter((b) => ep.script.blocks.some((x) => x.id === b));
@@ -716,7 +891,6 @@ function changed(ep: FacelessEpisode, c: ChangeInput) {
const stillEdits: StillEdits = { ...ep.plan.stillEdits };
if (c.part === "narration") {
if (!c.narration || c.narration.length !== ids.length || c.narration.some((n) => !n.trim())) throw new FacelessError("Write the new lines for each scene");
- // The block keeps its length (its clips are reused); lines that no longer fit are flagged in the editor.
blocks = blocks.map((b) => (ids.includes(b.id) ? { ...b, narration: c.narration![ids.indexOf(b.id)].replace(/\s+/g, " ").trim() } : b));
} else {
if (!instruction) throw new FacelessError(c.part === "picture" ? "Describe what to change in the picture" : "Describe the new movement");
@@ -732,11 +906,13 @@ function changed(ep: FacelessEpisode, c: ChangeInput) {
blocks = blocks.map((b) => (ids.includes(b.id) && !stillEdits[b.id] ? { ...b, visual: `${b.visual}. ${instruction}` } : b));
}
}
- const graph = buildGraph(ep, blocks, stillEdits);
+ const graph = buildGraph(ep, withTiming(blocks, ep.plan.timing), stillEdits);
// Steps that failed earlier are redone with the change, so the new version can finish.
const status = statusMap(ep.plan.ids);
- const broken = graph.filter((s) => !status[s.key] || status[s.key] === "failed" || status[s.key] === "canceled").map((s) => s.key);
- return { graph, blocks, stillEdits, plan: planRerun(graph, [...changedKeys(graph, ids, c.part), ...broken]), ids };
+ const part = partOf(graph);
+ const broken = graph.filter((s) => (!status[s.key] && (!ep.plan!.awaiting || TIMING_PARTS.has(part(s.key)))) || status[s.key] === "failed" || status[s.key] === "canceled").map((s) => s.key);
+ const keys = [...changedKeys(graph, ids, c.part), ...broken];
+ return { graph, blocks, stillEdits, keys, plan: planRerun(graph, keys), ids };
}
export function previewChange(id: string, c: ChangeInput): ChangePreview {
@@ -744,102 +920,225 @@ export function previewChange(id: string, c: ChangeInput): ChangePreview {
const { graph, plan } = changed(ep, c);
const est = estimateGraph(graph, getModel, plan.rerun);
const demo = plan.rerun.some((k) => {
- const s = graph.find((x) => x.key === k)!;
try {
- return previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0).demo;
+ return previewStep(graph.find((x) => x.key === k)!).demo;
} catch {
return false;
}
});
- return { rerun: plan.rerun, labels: plan.rerun.map((k) => graph.find((s) => s.key === k)!.label), costUsd: est.unknown ? null : est.total, demo };
+ return {
+ rerun: plan.rerun,
+ labels: plan.rerun.map((k) => graph.find((s) => s.key === k)!.label),
+ costUsd: est.unknown ? null : est.total,
+ demo,
+ ...(plan.rerun.includes("words") && { retime: true }),
+ };
}
/** Re-run what the change touches (that block's steps, the joins after it, the mix, the subtitles); Undo keeps the version before. */
export function applyChange(id: string, c: ChangeInput): FacelessEpisode {
const ep = mustEpisode(id);
if (ep.status === "rendering") throw new FacelessError("Wait for the current render to finish before changing scenes", 409);
- const { graph, blocks, stillEdits, plan, ids } = changed(ep, c);
+ const { graph, blocks, stillEdits, keys, plan, ids } = changed(ep, c);
const est = estimateGraph(graph, getModel, plan.rerun);
- const next = relaunch(graph, ep.plan!.ids, plan.rerun, ep.plan!.batchId);
- const final = getGeneration(ep.plan!.ids[finalKey(graph)] ?? "");
+ const next = launch({ ...ep, script: { ...ep.script, blocks } }, graph, ep.plan!.ids, keys, ep.plan!.batchId);
+ const final = getGeneration(ep.plan!.ids[finalKeyOf(ep)] ?? "");
+ const p = ep.plan!;
const updated: EpisodePlan = {
- ...ep.plan!,
- ids: next,
+ ...p,
+ ids: next.ids,
+ awaiting: next.awaiting,
stillEdits,
- previous: { ids: ep.plan!.ids, blocks: ep.script.blocks, stillEdits: ep.plan!.stillEdits },
- lastFinal: final?.status === "succeeded" ? final.id : ep.plan!.lastFinal,
- changes: [...ep.plan!.changes, { at: Date.now(), blocks: ids, part: c.part, instruction: c.part === "narration" ? (c.narration ?? []).join(" / ") : (c.instruction ?? ""), costUsd: est.unknown ? null : est.total }].slice(-50),
+ previous: { ids: p.ids, blocks: ep.script.blocks, stillEdits: p.stillEdits, timing: p.timing, untimed: p.untimed, awaiting: p.awaiting },
+ lastFinal: final?.status === "succeeded" ? final.id : p.lastFinal,
+ // A new version: its upscale is made again on request.
+ upscaled: undefined,
+ changes: [...p.changes, { at: Date.now(), blocks: ids, part: c.part, instruction: c.part === "narration" ? (c.narration ?? []).join(" / ") : (c.instruction ?? ""), costUsd: est.unknown ? null : est.total }].slice(-50),
};
updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(updated), script_json: JSON.stringify({ ...ep.script, blocks }) });
+ ensureFacelessRunner();
return mustEpisode(id);
}
-/** Back to the version before the last change (its generations are still there; nothing is refunded). */
+/** Back to the version before the last change: the newer steps still running are stopped (nothing is refunded). */
export function undoChange(id: string): FacelessEpisode {
const ep = mustEpisode(id);
const prev = ep.plan?.previous;
if (!prev) throw new FacelessError("Nothing to undo", 409);
for (const [k, gid] of Object.entries(ep.plan!.ids)) if (prev.ids[k] !== gid) void cancelGeneration(gid);
- const plan: EpisodePlan = { ...ep.plan!, ids: prev.ids, stillEdits: prev.stillEdits, previous: undefined, lastFinal: undefined };
- updateEpisodeRow(id, { status: "rendering", plan_json: JSON.stringify(plan), script_json: JSON.stringify({ ...ep.script, blocks: prev.blocks }) });
+ const changes = [...ep.plan!.changes];
+ const last = changes.map((x) => !x.undone).lastIndexOf(true);
+ if (last >= 0) changes[last] = { ...changes[last], undone: true };
+ const plan: EpisodePlan = {
+ ...ep.plan!,
+ ids: prev.ids,
+ stillEdits: prev.stillEdits,
+ timing: prev.timing,
+ untimed: prev.untimed,
+ awaiting: prev.awaiting,
+ previous: undefined,
+ lastFinal: undefined,
+ upscaled: undefined,
+ changes,
+ };
+ updateEpisodeRow(id, { status: "rendering", error: null, plan_json: JSON.stringify(plan), script_json: JSON.stringify({ ...ep.script, blocks: prev.blocks }) });
+ return mustEpisode(id);
+}
+
+// ---------------------------------------------------------------------------
+// Upscale to 1080p
+
+/** SeedVR2 bills per megapixel of output video: 1920 × 1080 at the clips' 24 fps. */
+const UPSCALE_FPS = 24;
+const UPSCALE_MP = (1920 * 1080) / 1e6;
+
+function upscaleOffer(ep: FacelessEpisode, seconds: number): EpisodeView["upscale"] {
+ const modelId = ENGINE_MODELS[ep.settings.engine].upscale;
+ const model = modelId ? getModel(modelId) : undefined;
+ if (!model) return null;
+ const demo = runsAsDemo(model.id, "upscale-video");
+ const p = model.pricing;
+ const costUsd = demo ? 0 : p?.unit === "megapixel" ? Math.round(p.usd * UPSCALE_MP * UPSCALE_FPS * seconds * 100) / 100 : p?.unit === "second" ? Math.round(p.usd * seconds * 100) / 100 : null;
+ return { costUsd, demo };
+}
+
+/** "Upscale to 1080p": one upscale step on the finished film, offered as the download once it's done. */
+export function upscaleEpisode(id: string): FacelessEpisode {
+ const ep = mustEpisode(id);
+ const modelId = ENGINE_MODELS[ep.settings.engine].upscale;
+ if (!modelId) throw new FacelessError("Upscaling runs on the cloud engine: the open-source upscaler holds every frame of the film in memory", 422);
+ const final = finalOf(ep);
+ if (!ep.plan || !final) throw new FacelessError("Wait for the episode to finish first", 409);
+ const had = ep.plan.upscaled ? getGeneration(ep.plan.upscaled) : null;
+ if (had && had.status !== "failed" && had.status !== "canceled") return ep;
+ let g: Generation;
+ try {
+ [g] = createGenerations(
+ { feature: ep.kind, modelId, op: "upscale-video", params: { resolution: "1080p" }, chain: [{ slot: "video" }], title: `${ep.title} · 1080p`, batchTitle: ep.title, step: { label: "Upscale to 1080p", index: 0, of: 1 } },
+ { batchId: ep.plan.batchId, dependsOn: final.id },
+ );
+ } catch (e) {
+ throw new FacelessError((e as Error).message, 422);
+ }
+ updateEpisodeRow(id, { plan_json: JSON.stringify({ ...ep.plan, upscaled: g.id } satisfies EpisodePlan) });
return mustEpisode(id);
}
// ---------------------------------------------------------------------------
-// Reading
+// Reading, and the sweep that starts stage two
+
+/** The step whose output is the finished episode. */
+const finalKeyOf = (ep: FacelessEpisode) => (ep.settings.subtitles ? "captions" : "mix");
function finalOf(ep: FacelessEpisode): Generation | null {
- if (!ep.plan) return null;
- const key = ep.plan.ids.captions ? "captions" : "mix";
- const g = getGeneration(ep.plan.ids[key] ?? "");
+ if (!ep.plan || ep.plan.awaiting) return null;
+ const g = getGeneration(ep.plan.ids[finalKeyOf(ep)] ?? "");
return g?.status === "succeeded" ? g : null;
}
-/** The episode's status from its generations (saved when it changes). */
-function settle(ep: FacelessEpisode, gens: Map<string, Generation | null>): EpisodeStatus {
+const brokenMessage = (g: Generation | null) =>
+ !g ? "A step was deleted — retry to make it again" : g.status === "canceled" ? "A step was cancelled — retry to make it again" : (g.error ?? "A step didn't finish — retry it");
+
+/**
+ * The episode's status from its generations (saved when it changes). Once stage one has finished, the
+ * first look starts stage two (advance).
+ */
+function settle(ep: FacelessEpisode, gens?: Map<string, Generation | null>): FacelessEpisode {
if (ep.status === "writing" && !writing().has(ep.id)) {
// A restart while the script was being written.
- updateEpisodeRow(ep.id, { status: "write-failed", error: "Interrupted while writing the script — try again" });
- return "write-failed";
+ const error = "Interrupted while writing the script — try again";
+ updateEpisodeRow(ep.id, { status: "write-failed", error });
+ return { ...ep, status: "write-failed", error };
}
- if (!ep.plan || ep.status === "writing" || ep.status === "write-failed" || ep.status === "review") return ep.status;
- const list = Object.entries(ep.plan.ids).map(([k, id]) => [k, gens.get(id) ?? null] as const);
- const final = list.find(([k]) => k === (ep.plan!.ids.captions ? "captions" : "mix"))?.[1];
+ if (!ep.plan || ep.status === "writing" || ep.status === "write-failed" || ep.status === "review") return ep;
+ const read = (id: string) => (gens?.has(id) ? gens.get(id)! : getGeneration(id, { includeDeleted: true }));
+ const list = Object.entries(ep.plan.ids).map(([k, id]) => [k, read(id)] as const);
const active = list.some(([, g]) => g && (g.status === "queued" || g.status === "running"));
const broken = list.find(([, g]) => !g || g.status === "failed" || g.status === "canceled");
- const status: EpisodeStatus = final?.status === "succeeded" ? "done" : !active && broken ? "failed" : "rendering";
- const error = status === "failed" ? (broken?.[1]?.error ?? "A step was deleted — retry to make it again") : null;
+ let status: EpisodeStatus;
+ let error: string | null = null;
+ if (ep.plan.awaiting) {
+ if (!active && !broken && ep.status !== "failed") {
+ try {
+ return settle(advance(ep));
+ } catch (e) {
+ status = "failed";
+ error = (e as Error).message;
+ }
+ } else status = active ? "rendering" : "failed";
+ if (status === "failed") error ??= ep.status === "failed" && !broken ? ep.error : brokenMessage(broken?.[1] ?? null);
+ } else {
+ const final = list.find(([k]) => k === finalKeyOf(ep))?.[1];
+ status = final?.status === "succeeded" ? "done" : !active && broken ? "failed" : "rendering";
+ if (status === "failed") error = brokenMessage(broken![1]);
+ }
if (status !== ep.status || error !== ep.error) updateEpisodeRow(ep.id, { status, error });
- return status;
+ return { ...ep, status, error };
+}
+
+declare global {
+ var __fuobeFacelessRunner: { timer: NodeJS.Timeout; tick: () => void } | undefined;
+}
+
+const SWEEP_MS = 2000;
+
+/** Episodes whose stage one has finished get stage two, even when nobody has them open. */
+function sweep(): void {
+ const rows = db().prepare("SELECT * FROM faceless_episodes WHERE status = 'rendering' AND plan_json LIKE '%\"awaiting\":true%'").all() as EpisodeRow[];
+ for (const r of rows) {
+ try {
+ settle(toEpisode(r));
+ } catch (e) {
+ console.warn(`[faceless] couldn't continue ${r.id}: ${(e as Error).message}`);
+ }
+ }
+}
+
+/** Start the background sweep (once per process: at boot, and whenever a render starts). */
+export function ensureFacelessRunner(): void {
+ const cur = globalThis.__fuobeFacelessRunner;
+ if (cur) {
+ // After a dev hot reload, point the timer at this module's code.
+ cur.tick = sweep;
+ return;
+ }
+ const state = { tick: sweep, timer: setInterval(() => globalThis.__fuobeFacelessRunner?.tick(), SWEEP_MS) };
+ state.timer.unref?.();
+ globalThis.__fuobeFacelessRunner = state;
}
const stepProgress = (g: Generation | null) => (!g ? 0 : g.status === "succeeded" ? 1 : g.status === "running" ? Math.max(0.05, Math.min(0.95, g.progress ?? 0.1)) : 0);
export function episodeView(id: string): EpisodeView {
- const ep = mustEpisode(id);
+ const current = settle(mustEpisode(id));
const gens = new Map<string, Generation | null>();
- for (const gid of Object.values(ep.plan?.ids ?? {})) gens.set(gid, getGeneration(gid));
- const status = settle(ep, gens);
- const current = { ...ep, status, error: status === ep.status ? ep.error : (episodeRow(id)?.error ?? null) };
+ for (const gid of Object.values(current.plan?.ids ?? {})) gens.set(gid, getGeneration(gid));
let graph: GraphStep[] = [];
try {
- if (current.script.blocks.length) graph = buildEpisodeGraph({ ...graphInputSafe(current), blocks: current.script.blocks, stillEdits: ep.plan?.stillEdits }, getModel);
+ if (current.script.blocks.length) graph = buildEpisodeGraph({ ...graphInputSafe(current), blocks: withTiming(current.script.blocks, current.plan?.timing), stillEdits: current.plan?.stillEdits }, getModel);
} catch {
graph = [];
}
- const steps = graph.map((s) => ({ key: s.key, part: s.part, block: s.block, label: s.label, generation: ep.plan?.ids[s.key] ? (gens.get(ep.plan.ids[s.key]) ?? null) : null }));
+ const plan = current.plan;
+ const steps = graph.map((s) => ({ key: s.key, part: s.part, block: s.block, label: s.label, generation: plan?.ids[s.key] ? (gens.get(plan.ids[s.key]) ?? null) : null }));
const final = finalOf(current);
- const previousFinal = !final && ep.plan?.lastFinal ? getGeneration(ep.plan.lastFinal) : null;
+ const previousFinal = !final && plan?.lastFinal ? getGeneration(plan.lastFinal) : null;
const spent = [...gens.values()].reduce((n, g) => n + (g && g.status !== "failed" && g.status !== "canceled" ? (g.costUsd ?? 0) : 0), 0);
+ const spans = sceneSpans(graph, current.script.blocks.length);
+ const upscaled = plan?.upscaled ? getGeneration(plan.upscaled) : null;
return {
episode: current,
channel: current.channelId ? getChannel(current.channelId) : null,
steps,
final,
previousFinal: previousFinal?.status === "succeeded" ? previousFinal : null,
- progress: steps.length && ep.plan ? steps.reduce((n, s) => n + stepProgress(s.generation), 0) / steps.length : 0,
+ progress: steps.length && plan ? steps.reduce((n, s) => n + stepProgress(s.generation), 0) / steps.length : 0,
spentUsd: Math.round(spent * 100) / 100,
estimate: graph.length ? estimateGraph(graph, getModel) : null,
+ scenes: current.script.blocks.map((b, i) => ({ id: b.id, start: spans[i]?.start ?? 0, seconds: spans[i]?.seconds ?? b.seconds })),
+ timing: plan?.timing && !plan.untimed ? "narration" : "planned",
+ upscaled,
+ upscale: final ? upscaleOffer(current, spans.reduce((n, s) => n + s.seconds, 0)) : null,
};
}
@@ -853,25 +1152,26 @@ function graphInputSafe(ep: FacelessEpisode): GraphInput {
}
function toCard(r: EpisodeRow): EpisodeCard {
- const ep = toEpisode(r);
+ const ep = settle(toEpisode(r));
const ids = Object.values(ep.plan?.ids ?? {});
const gens = new Map(ids.map((id) => [id, getGeneration(id)] as const));
- const status = ep.plan ? settle(ep, gens) : settle(ep, new Map());
- const final = ep.plan ? (gens.get(ep.plan.ids.captions ?? ep.plan.ids.mix ?? "") ?? null) : null;
+ const final = finalOf(ep);
const firstStill = ep.plan ? (gens.get(ep.plan.ids[`still-${ep.script.blocks[0]?.id}`] ?? "") ?? null) : null;
+ const timed = ep.plan?.timing;
return {
id: ep.id,
channelId: ep.channelId,
kind: ep.kind,
title: ep.title,
- status,
+ status: ep.status,
styleId: ep.settings.styleId,
+ ownStyle: ep.settings.styleRefs.length > 0,
aspect: ep.settings.aspect,
- seconds: totalSeconds(ep.script.blocks) || ep.settings.length,
+ seconds: (timed ? Object.values(timed).reduce((a, b) => a + b, 0) : totalSeconds(ep.script.blocks)) || ep.settings.length,
favorite: ep.favorite,
- poster: final?.status === "succeeded" ? final : null,
+ poster: final,
still: firstStill?.status === "succeeded" ? firstStill : null,
- updating: status === "rendering" && !!ep.plan?.lastFinal,
+ updating: ep.status === "rendering" && !!ep.plan?.lastFinal,
progress: ids.length ? [...gens.values()].reduce((n, g) => n + stepProgress(g ?? null), 0) / ids.length : 0,
createdAt: ep.createdAt,
};
@@ -907,7 +1207,6 @@ export function listEpisodes(o: { channelId?: string; kind?: "faceless" | "expla
export function estimateEpisode(input: { kind: "faceless" | "explainer"; settings: EpisodeSettings; blocks?: Partial<ScriptBlock>[]; genre?: FacelessGenre }): EstimateResult {
const settings = { ...input.settings, styleRefs: input.settings.styleRefs.slice(0, 3) };
const blocks = input.blocks?.length ? normalizeBlocks(input.blocks) : placeholderBlocks(settings.auto ? AUTO_SECONDS : settings.length);
- const seconds = totalSeconds(blocks);
const fake: FacelessEpisode = {
id: "estimate",
channelId: null,
@@ -928,13 +1227,13 @@ export function estimateEpisode(input: { kind: "faceless" | "explainer"; setting
try {
graph = buildEpisodeGraph({ ...graphInputSafe(fake), genre: genreInfo(input.genre) }, getModel);
} catch (e) {
- return { estimate: { total: 0, parts: {}, unknown: true }, demo: true, seconds, blocks: blocks.length, error: (e as Error).message };
+ return { estimate: { total: 0, parts: {}, unknown: true }, demo: true, seconds: totalSeconds(blocks), blocks: blocks.length, error: (e as Error).message };
}
+ const seconds = sceneSpans(graph, blocks.length).reduce((n, s) => n + s.seconds, 0);
let error: string | undefined;
let demo = false;
try {
cleanSettings(settings);
- checkMusicMix(fake, graph);
if (settings.engine === "open" && settings.voice?.kind !== "sample" && !runsAsDemo(ENGINE_MODELS.open.narration, "tts")) {
error = "Pick the narrator's voice: record or upload 10–60 s of speech, or use one of your saved voices";
}
@@ -948,13 +1247,26 @@ export function estimateEpisode(input: { kind: "faceless" | "explainer"; setting
if (seen.has(k)) continue;
seen.add(k);
try {
- const p = previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0);
- demo ||= p.demo;
+ demo ||= previewStep(s).demo;
} catch (e) {
error ??= `${s.label}: ${(e as Error).message}`;
}
}
- return { estimate: estimateGraph(graph, getModel), demo, seconds, blocks: blocks.length, ...(error && { error }) };
+ return { estimate: estimateGraph(graph, getModel), demo, seconds, blocks: blocks.length, ...(error && { error }), ...notesFor(settings, seconds) };
+}
+
+/** What the render will do differently from what was asked (nothing that stops it). */
+function notesFor(settings: EpisodeSettings, seconds: number): { notes?: string[] } {
+ const notes: string[] = [];
+ const m = resolveModels(settings, 0, getModel);
+ const limit = styleRefLimit(settings.engine, getModel);
+ if (settings.styleRefs.length > limit) notes.push(`The open-source picture model follows the first ${limit} style references.`);
+ if (settings.engine === "open" && settings.styleRefs.length && settings.sourceImages?.length) notes.push("Your style references set the look; the attached images aren't used for the open-source pictures.");
+ if (m.music) {
+ const max = musicLength(getModel(m.music), Number.MAX_SAFE_INTEGER);
+ if (seconds > max) notes.push(`The music bed is at most ${Math.floor(max / 60)} min ${max % 60 ? `${max % 60} s ` : ""}long, so the last ${Math.ceil(seconds - max)} s play without music.`);
+ }
+ return notes.length ? { notes } : {};
}
/** A short sample of a premade narrator (one cheap speech generation, reused once made). */
@@ -1010,6 +1322,7 @@ export async function summarizeLink(url: string, engine: Engine): Promise<Extrac
engine,
"You summarise web pages for a video script writer. Reply with the key facts, numbers, names and explanations as short plain sentences (at most 250 words). No preamble.",
`Page: ${title ?? url}\n\n${text.slice(0, 24_000)}`,
+ { timeoutMs: 2 * 60_000 },
);
return { kind: "link", url: res.url, title: title?.slice(0, 160), text: (summary ?? text).slice(0, 6000) };
}
@@ -1025,9 +1338,12 @@ export const VoiceSchema = z.union([
export const GenreSchema = z.enum(["education", "history", "kids", "storytelling"]);
export const EngineSchema = z.enum(["cloud", "open"]);
+/** The research's message for a length outside Auto / 15–600 s. */
+export const DURATION_ERROR = "Duration must be Auto or a whole number of seconds between 15 and 600";
+
export const SettingsSchema = z.object({
engine: EngineSchema,
- length: z.number().int().min(15).max(600),
+ length: z.number(DURATION_ERROR).int(DURATION_ERROR).min(EXPLAINER_MIN, DURATION_ERROR).max(EXPLAINER_MAX, DURATION_ERROR),
animation: z.enum(["animated", "frames"]),
aspect: z.enum(["16:9", "9:16"]),
subtitles: z.boolean(),
diff --git a/src/server/generations.ts b/src/server/generations.ts
index e5034312..7d55ff70 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -208,6 +208,9 @@ const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [
{ table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"] },
{ table: "cinema_items", cols: ["meta_json"], except: "generation_id" },
{ table: "canvases", cols: ["graph_json"] },
+ // Faceless / Explainer: a channel's avatar, style references and voice samples, episode sources.
+ { table: "faceless_channels", cols: ["avatar_url", "reference_json", "settings_json"] },
+ { table: "faceless_episodes", cols: ["settings_json", "sources_json"] },
];
/** Whether anything still refers to this stored file (see ASSET_REFS). */
diff --git a/tests/faceless-api.test.ts b/tests/faceless-api.test.ts
index eb2d1b0f..4f924167 100644
--- a/tests/faceless-api.test.ts
+++ b/tests/faceless-api.test.ts
@@ -11,6 +11,7 @@ process.env.COMFYUI_URL = "http://127.0.0.1:9";
process.env.OLLAMA_URL = "http://127.0.0.1:9";
const { setSetting } = await import("@/server/settings");
+const { db } = await import("@/server/db");
const gens = await import("@/server/generations");
const faceless = await import("@/server/faceless");
const channelsRoute = await import("@/app/api/faceless/channels/route");
@@ -34,6 +35,7 @@ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
const json = (method: string, body?: unknown) =>
new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const cloud: EpisodeSettings = {
engine: "cloud",
@@ -54,26 +56,42 @@ async function view(id: string): Promise<EpisodeView> {
return JSON.parse(JSON.stringify(faceless.episodeView(id)));
}
-/** Wait for an episode to finish rendering (demo jobs: a few seconds per step). */
-async function settled(id: string, ms = 90_000): Promise<EpisodeView> {
- const until = Date.now() + ms;
+/** Poll an episode until `done` says so (demo jobs: a few seconds per step). */
+async function until(id: string, done: (v: EpisodeView) => boolean, what: string, ms = 90_000): Promise<EpisodeView> {
+ const end = Date.now() + ms;
for (;;) {
const v = await view(id);
- if (v.episode.status === "done" || v.episode.status === "failed") return v;
- if (Date.now() > until) throw new Error(`timed out: ${v.episode.status} ${Math.round(v.progress * 100)}%`);
- await new Promise((r) => setTimeout(r, 500));
+ if (done(v)) return v;
+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}: ${v.episode.status} ${Math.round(v.progress * 100)}%`);
+ await sleep(500);
}
}
+const settled = (id: string) => until(id, (v) => v.episode.status === "done" || v.episode.status === "failed", "the render");
+
+/** Every generation an episode made (now and in its previous version) that's still queued or running. */
+const stillRunning = (ids: string[]) => ids.filter((g) => ["queued", "running"].includes(gens.getGeneration(g, { includeDeleted: true })?.status ?? ""));
let channel: FacelessChannel;
describe("Faceless channels and topics", () => {
- it("creates a channel with a written name, lists it, and saves its look", async () => {
+ it("creates a channel straight away with a name from the idea, then draws its avatar on the server", async () => {
const res = await channelsRoute.POST(json("POST", { idea: "Channel about the rise and fall of empires", genre: "history", engine: "cloud" }));
expect(res.status).toBe(201);
channel = await res.json();
expect(channel).toMatchObject({ name: "The Rise and Fall of Empires", genre: "history", settings: { styleId: "watercolor-chronicle", voice: { kind: "preset", id: "JBFqnCBsd6RMkjVDRZzb" }, aspect: "16:9", subtitles: true } });
expect(faceless.listChannels().map((c) => c.id)).toContain(channel.id);
+ // The avatar is drawn with the channel; it becomes the channel's picture without a browser watching.
+ await faceless.channelReady(channel.id);
+ const job = faceless.getChannel(channel.id)!.avatarJob!;
+ expect(gens.getGeneration(job)).toMatchObject({ feature: "faceless-avatar" });
+ for (let i = 0; i < 40 && gens.getGeneration(job)!.status !== "succeeded"; i++) await sleep(250);
+ const pictured = faceless.listChannels().find((c) => c.id === channel.id)!;
+ expect(pictured.avatarJob).toBeNull();
+ expect(pictured.avatarUrl).toBe(gens.getGeneration(job)!.outputs[0].url);
+ // Its file is in use: emptying the Library of that picture keeps it.
+ const asset = (db().prepare("SELECT id FROM assets WHERE generation_id = ?").get(job) as { id: string }).id;
+ expect(gens.assetInUse(asset, job)).toBe(true);
+
expect((await channelsRoute.POST(json("POST", { idea: "", genre: "history", engine: "cloud" }))).status).toBe(400);
const bad = await channelsRoute.POST(json("POST", { idea: "x", genre: "history", engine: "cloud", reference: "https://vimeo.com/1" }));
expect(bad.status).toBe(400);
@@ -83,14 +101,16 @@ describe("Faceless channels and topics", () => {
expect((await channelRoute.PATCH(json("PATCH", { name: "x" }), params({ id: "nope" }))).status).toBe(404);
});
- it("suggests 4–6 topics offline, and new ones on the next round", async () => {
+ it("suggests 4–6 topics offline, and different ones on the next round", async () => {
const first = await (await topicsRoute.POST(json("POST", { channelId: channel.id, engine: "cloud" }))).json();
expect(first.offline).toBe(true);
expect(first.topics.length).toBeGreaterThanOrEqual(4);
expect(first.topics.length).toBeLessThanOrEqual(6);
expect(first.topics[0].title).toMatch(/rise and fall of empires/i);
- const next = await (await topicsRoute.POST(json("POST", { channelId: channel.id, engine: "cloud", round: 1 }))).json();
- expect(next.topics[0].title).not.toBe(first.topics[0].title);
+ const titles = first.topics.map((t: { title: string }) => t.title);
+ const next = await (await topicsRoute.POST(json("POST", { channelId: channel.id, engine: "cloud", round: 1, avoid: titles }))).json();
+ expect(next.topics.length).toBeGreaterThanOrEqual(4);
+ expect(next.topics.filter((t: { title: string }) => titles.includes(t.title))).toEqual([]);
});
});
@@ -126,9 +146,17 @@ describe("Episodes", () => {
expect(edited.episode.script.blocks.every((b) => b.seconds <= 10)).toBe(true);
expect(edited.steps.filter((s) => s.part === "still")).toHaveLength(edited.episode.script.blocks.length);
expect(edited.estimate!.total).toBeGreaterThan(0);
- // The channel remembers the look and voice of its latest episode.
+ expect(edited.scenes.map((s) => s.id)).toEqual(edited.episode.script.blocks.map((b) => b.id));
+ expect(edited.timing).toBe("planned");
+ // A channel's first episode saves its look; later ones only when asked.
expect(faceless.listEpisodes({ channelId: channel.id }).map((e) => e.id)).toContain(ep.id);
expect(faceless.getChannel(channel.id)!.settings.aspect).toBe("16:9");
+ const vertical = faceless.createEpisode({ kind: "faceless", channelId: channel.id, topic: "Carthage", settings: { ...cloud, aspect: "9:16", styleId: "pixel-art" } });
+ expect(faceless.getChannel(channel.id)!.settings).toMatchObject({ aspect: "16:9", styleId: "editorial-motion-graphics" });
+ faceless.createEpisode({ kind: "faceless", channelId: channel.id, topic: "Sparta", settings: { ...cloud, aspect: "9:16" }, saveLook: true });
+ await sleep(50);
+ expect(faceless.getChannel(channel.id)!.settings.aspect).toBe("9:16");
+ await faceless.scriptWritten(vertical.id);
});
it("estimates by engine and mode, and says what's in the way", async () => {
@@ -142,19 +170,24 @@ describe("Episodes", () => {
const openEst = await est(open);
expect(openEst.estimate.total).toBe(0);
expect(openEst.error).toBeUndefined();
- // Cloud music needs the open mixer; with everything on the demo provider it still runs.
+ // Cloud music is mixed on the cloud (fal compose): fine on a cloud-only install too.
expect((await est({ ...cloud, music: true })).error).toBeUndefined();
setSetting("engineMode", "cloud");
try {
- expect((await est({ ...cloud, music: true })).error).toMatch(/turn music off/);
+ const music = await est({ ...cloud, music: true });
+ expect(music.error).toBeUndefined();
+ expect(music.estimate.parts.music).toBeGreaterThan(0);
expect((await est(open)).error).toMatch(/cloud APIs only/);
} finally {
setSetting("engineMode", "both");
}
+ // What the render will do differently: two of three style references on the open engine, a short music bed.
+ const notes = (await est({ ...open, length: 300, styleRefs: ["/api/files/a.png", "/api/files/b.png", "/api/files/c.png"] })).notes;
+ expect(notes).toEqual(expect.arrayContaining([expect.stringMatching(/first 2 style references/), expect.stringMatching(/at most 4 min/)]));
});
it(
- "renders end to end in demo mode on both engines, then re-runs one scene, undoes it and retries a failure",
+ "renders end to end in demo mode on both engines (narration timed first, then the scenes), re-runs one scene, undoes it and retries a failure",
async () => {
const make = async (settings: EpisodeSettings, topic: string) => {
const ep: FacelessEpisode = await (await episodesRoute.POST(json("POST", { channelId: channel.id, topic, settings }))).json();
@@ -167,22 +200,34 @@ describe("Episodes", () => {
expect(r.status).toBe(200);
return ep.id;
};
- const cloudId = await make(cloud, "Why Rome split in two");
+ // The cloud episode has a music bed: Sonilo, levelled, then composed with the voice on fal.
+ const cloudId = await make({ ...cloud, music: true }, "Why Rome split in two");
const openId = await make(open, "The fall of Byzantium");
expect((await actionRoute.POST(json("POST"), params({ id: cloudId, action: "render" }))).status).toBe(409);
+ // Stage one: the pictures, the narration (the demo voice cloned) and its timing. The clips wait for the timing.
const rendering = await view(openId);
expect(rendering.episode.status).toBe("rendering");
- // Open, frame by frame: 12 shots, folded joins, the demo voice cloned, music, timed captions.
- const ids = rendering.episode.plan!.ids;
- // A 10-second scene is two 5-second Wan shots; short scenes are one.
+ const blocks = rendering.episode.script.blocks;
+ expect(rendering.episode.plan!.awaiting).toBe(true);
+ expect(Object.keys(rendering.episode.plan!.ids).sort()).toEqual([...blocks.map((b) => `still-${b.id}`), "narration", "words"].sort());
+ expect(rendering.steps.filter((s) => s.part === "clip").every((s) => !s.generation)).toBe(true);
+ const narration = gens.getGeneration(rendering.episode.plan!.ids.narration)!;
+ expect(narration.request.inputs?.voiceAudio).toMatch(/^\/api\/files\/uploads\/.+\.wav$/);
+
+ // Stage two starts by itself once the narration is timed. A demo transcript can't time it: planned lengths.
+ const timed = await until(openId, (v) => !v.episode.plan!.awaiting, "stage two");
+ const ids = timed.episode.plan!.ids;
+ expect(timed.timing).toBe("planned");
+ expect(timed.episode.plan!.untimed).toBe(true);
+ // Open, frame by frame: 5-second Wan shots, folded joins, music, timed captions.
const clips = Object.keys(ids).filter((k) => k.startsWith("clip-"));
expect(clips.length).toBeGreaterThan(6);
- expect(clips).toHaveLength(rendering.steps.filter((s) => s.part === "clip").length);
+ expect(clips).toHaveLength(timed.steps.filter((s) => s.part === "clip").length);
expect(Object.keys(ids)).toEqual(expect.arrayContaining(["join", "join-1-1", "narration", "music", "mix", "words", "captions"]));
- const narration = gens.getGeneration(ids.narration)!;
- expect(narration.request.inputs?.voiceAudio).toMatch(/^\/api\/files\/uploads\/.+\.wav$/);
- expect(gens.getGeneration(ids["clip-" + rendering.episode.script.blocks[0].id + "-1"])!.request.prompt).toMatch(/still illustration/);
+ expect(gens.getGeneration(ids[`clip-${blocks[0].id}-1`])!.request.prompt).toMatch(/still illustration/);
+ // The timeline shows the film as the clips make it (Wan's 3- and 5-second shots).
+ expect(timed.scenes.reduce((n, s) => n + s.seconds, 0)).toBe(clips.reduce((n, k) => n + Number(gens.getGeneration(ids[k])!.request.params?.duration), 0));
const [doneCloud, doneOpen] = await Promise.all([settled(cloudId), settled(openId)]);
for (const v of [doneCloud, doneOpen]) {
@@ -194,6 +239,18 @@ describe("Episodes", () => {
}
expect(doneOpen.final!.op).toBe("captions");
expect(doneOpen.final!.request.title).toBe(doneOpen.episode.title);
+ const cloudIds = doneCloud.episode.plan!.ids;
+ expect(gens.getGeneration(cloudIds.mix)!.modelId).toBe("ffmpeg-compose");
+ expect(gens.getGeneration(cloudIds.level)!.request.inputs?.audio).toBeTruthy();
+
+ // Upscale to 1080p: one step on the finished film (cloud only).
+ expect(doneCloud.upscale).toEqual({ costUsd: 0, demo: true });
+ expect(doneOpen.upscale).toBeNull();
+ const upscaling: EpisodeView = await (await actionRoute.POST(json("POST"), params({ id: cloudId, action: "upscale" }))).json();
+ const up = gens.getGeneration(upscaling.episode.plan!.upscaled!)!;
+ expect(up).toMatchObject({ op: "upscale-video", modelId: "seedvr-video" });
+ expect(up.request.params?.resolution).toBe("1080p");
+ expect((await actionRoute.POST(json("POST"), params({ id: openId, action: "upscale" }))).status).toBe(422);
// Timeline editor: change scene 3's picture.
const target = doneCloud.episode.script.blocks[2].id;
@@ -202,21 +259,26 @@ describe("Episodes", () => {
expect(preview.rerun).toEqual([`still-${target}`, `clip-${target}-1`, "join", "mix", "captions"]);
expect(preview.costUsd).toBeGreaterThan(0.3);
expect(preview.demo).toBe(true);
+ expect(preview.retime).toBeUndefined();
const applied = await changeRoute.POST(json("POST", { blocks: [target], part: "picture", instruction: "make it night", apply: true }), params({ id: cloudId }));
expect(applied.status).toBe(201);
const changing: EpisodeView = await applied.json();
expect(changing.episode.status).toBe("rendering");
+ expect(changing.episode.plan!.awaiting).toBe(false);
const after = changing.episode.plan!.ids;
expect(after[`still-${target}`]).not.toBe(before[`still-${target}`]);
expect(after[`still-${doneCloud.episode.script.blocks[0].id}`]).toBe(before[`still-${doneCloud.episode.script.blocks[0].id}`]);
expect(after.narration).toBe(before.narration);
+ expect(after.music).toBe(before.music);
expect(gens.getGeneration(after[`still-${target}`])!.request).toMatchObject({ op: "edit", inputs: { images: [doneCloud.steps.find((s) => s.key === `still-${target}`)!.generation!.outputs[0].url] } });
expect(changing.previousFinal?.id).toBe(before.captions);
expect(changing.episode.plan!.changes).toHaveLength(1);
+ expect(changing.episode.plan!.upscaled).toBeUndefined();
- // A narration change re-voices the whole voice-over and re-mixes; the pictures are kept.
+ // A narration change reads the voice-over again and re-times the scenes before re-mixing.
const voice = await (await changeRoute.POST(json("POST", { blocks: [doneOpen.episode.script.blocks[2].id], part: "narration", narration: ["Night fell over the city."] }), params({ id: openId }))).json();
- expect(voice.rerun).toEqual(["narration", "mix", "words", "captions"]);
+ expect(voice.rerun).toEqual(["narration", "words", "mix", "captions"]);
+ expect(voice.retime).toBe(true);
// Retry (meanwhile, on the open episode): a step that fails takes what waits on it down; Retry redoes only those.
const failing = await view(openId);
@@ -230,24 +292,99 @@ describe("Episodes", () => {
const [changed, failed] = await Promise.all([settled(cloudId), settled(openId)]);
expect(changed.episode.status).toBe("done");
expect(changed.final!.id).toBe(after.captions);
- // Undo goes back to the version before.
+ // Undo goes back to the version before, and marks the change undone.
const undone: EpisodeView = await (await actionRoute.POST(json("POST"), params({ id: cloudId, action: "undo" }))).json();
expect(undone.episode.plan!.ids).toEqual(before);
+ expect(undone.episode.plan!.changes[0].undone).toBe(true);
expect((await settled(cloudId)).final!.id).toBe(before.captions);
expect(failed.episode.status).toBe("failed");
- expect(failed.episode.error).toBeTruthy();
+ expect(failed.episode.error).toBe("A step was cancelled — retry to make it again");
const retried: EpisodeView = await (await actionRoute.POST(json("POST"), params({ id: openId, action: "retry" }))).json();
expect(retried.episode.status).toBe("rendering");
expect(retried.episode.plan!.ids[clipKey]).not.toBe(mid.episode.plan!.ids[clipKey]);
expect(retried.episode.plan!.ids.narration).toBe(mid.episode.plan!.ids.narration);
// The redone clip runs (what follows it is the same chain the first render ran).
const redone = retried.episode.plan!.ids[clipKey];
- for (let i = 0; i < 60 && gens.getGeneration(redone)!.status !== "succeeded"; i++) await new Promise((r) => setTimeout(r, 500));
+ for (let i = 0; i < 60 && gens.getGeneration(redone)!.status !== "succeeded"; i++) await sleep(500);
expect(gens.getGeneration(redone)!.status).toBe("succeeded");
+
+ // A narration change on the cloud episode: the voice and its timing first, then the mix and subtitles.
+ // The demo can't time the new take, so the scenes keep their clips.
+ const restored = await view(cloudId);
+ const keep = restored.episode.plan!.ids;
+ const lines = await changeRoute.POST(json("POST", { blocks: [restored.episode.script.blocks[0].id], part: "narration", narration: ["Rome was never one city for long."], apply: true }), params({ id: cloudId }));
+ const relined: EpisodeView = await lines.json();
+ expect(relined.episode.plan!.awaiting).toBe(true);
+ expect(relined.episode.plan!.ids.narration).not.toBe(keep.narration);
+ expect(relined.episode.plan!.ids.mix).toBeUndefined();
+ expect(relined.previousFinal?.id).toBe(keep.captions);
+ // Undo while it's still reading: the new steps are stopped.
+ const newer = Object.entries(relined.episode.plan!.ids).filter(([k, g]) => keep[k] !== g).map(([, g]) => g);
+ expect(newer.length).toBeGreaterThanOrEqual(2);
+ await actionRoute.POST(json("POST"), params({ id: cloudId, action: "undo" }));
+ await sleep(100);
+ expect(stillRunning(newer)).toEqual([]);
+ // Again, to the end.
+ await changeRoute.POST(json("POST", { blocks: [restored.episode.script.blocks[0].id], part: "narration", narration: ["Rome was never one city for long."], apply: true }), params({ id: cloudId }));
+ const revoiced = await settled(cloudId);
+ expect(revoiced.episode.status).toBe("done");
+ const now = revoiced.episode.plan!.ids;
+ for (const k of Object.keys(keep).filter((k) => k.startsWith("clip-") || k.startsWith("still-") || k === "music" || k === "level")) expect(now[k], k).toBe(keep[k]);
+ for (const k of ["narration", "words", "mix", "captions"]) expect(now[k], k).not.toBe(keep[k]);
+ expect(gens.getGeneration(now.narration)!.request.prompt).toMatch(/^Rome was never one city for long\./);
},
300_000,
);
+
+ it("stops everything an episode or a channel still renders when it's deleted", async () => {
+ // An Explainer renders straight away: delete it a moment into the render.
+ const res = await explainerRoute.POST(json("POST", { prompt: "How lighthouses work", settings: { ...cloud, length: 30, music: true } }));
+ const ep: FacelessEpisode = await res.json();
+ await faceless.scriptWritten(ep.id);
+ const rendering = await view(ep.id);
+ expect(rendering.episode.status).toBe("rendering");
+ const made = Object.values(rendering.episode.plan!.ids);
+ expect(stillRunning(made).length).toBeGreaterThan(0);
+ const del = await episodeRoute.DELETE(json("DELETE"), params({ id: ep.id }));
+ expect(del.status).toBe(204);
+ expect(stillRunning(made)).toEqual([]);
+ await sleep(3000);
+ expect(stillRunning(made)).toEqual([]);
+ expect(faceless.listEpisodes({ kind: "explainer" }).map((e) => e.id)).not.toContain(ep.id);
+
+ // Deleting while the script is being written stops the writer: no row comes back.
+ const writing = faceless.createEpisode({ kind: "explainer", topic: "Why the sky is blue", settings: cloud, autoRender: true });
+ await faceless.deleteEpisode(writing.id);
+ await faceless.scriptWritten(writing.id);
+ expect(faceless.listEpisodes({ kind: "explainer", q: "sky is blue" })).toEqual([]);
+
+ // A channel takes its episodes' renders with it.
+ const doomed: FacelessChannel = await (await channelsRoute.POST(json("POST", { idea: "Channel about lighthouses", genre: "education", engine: "cloud" }))).json();
+ await faceless.channelReady(doomed.id);
+ const e2 = faceless.createEpisode({ kind: "faceless", channelId: doomed.id, topic: "The first lighthouse", settings: cloud });
+ await faceless.scriptWritten(e2.id);
+ faceless.renderEpisode(e2.id);
+ const ids = [...Object.values(faceless.episodeView(e2.id).episode.plan!.ids), faceless.getChannel(doomed.id)!.avatarJob].filter((x): x is string => !!x);
+ expect(stillRunning(ids).length).toBeGreaterThan(0);
+ expect((await channelRoute.DELETE(json("DELETE"), params({ id: doomed.id }))).status).toBe(204);
+ expect(stillRunning(ids)).toEqual([]);
+ expect(faceless.getChannel(doomed.id)).toBeNull();
+ });
+
+ it("marks a script that was being written when the server restarted as failed, with Try again", async () => {
+ const ep = faceless.createEpisode({ kind: "faceless", channelId: channel.id, topic: "The Silk Road", settings: cloud });
+ await faceless.scriptWritten(ep.id);
+ // As after a restart: the row says "writing", but no writer is running in this process.
+ db().prepare("UPDATE faceless_episodes SET status = 'writing' WHERE id = ?").run(ep.id);
+ const v = await view(ep.id);
+ expect(v.episode.status).toBe("write-failed");
+ expect(v.episode.error).toBe("Interrupted while writing the script — try again");
+ const again: EpisodeView = await (await actionRoute.POST(json("POST"), params({ id: ep.id, action: "rewrite" }))).json();
+ expect(again.episode.status).toBe("writing");
+ await faceless.scriptWritten(ep.id);
+ expect((await view(ep.id)).episode.status).toBe("review");
+ });
});
describe("Explainer", () => {
@@ -276,6 +413,23 @@ describe("Explainer", () => {
expect((await many.json()).error).toBe("Up to 3 sources per video — remove one to add another");
const none = await explainerRoute.POST(json("POST", { prompt: "", settings: cloud }));
expect((await none.json()).error).toBe("Add a prompt, or attach a file or link");
+ for (const length of [10, 601, 45.5]) {
+ const r = await explainerRoute.POST(json("POST", { prompt: "x", settings: { ...cloud, length } }));
+ expect(r.status).toBe(400);
+ expect((await r.json()).error).toBe("Duration must be Auto or a whole number of seconds between 15 and 600");
+ }
+ });
+
+ it("draws open pictures from the attached images", async () => {
+ const img = (await import("@/server/storage")).saveFile({ data: Buffer.from("x"), contentType: "image/png", name: "subject.png", source: "upload" }).url;
+ const ep = faceless.createEpisode({ kind: "explainer", topic: "Our new kettle", sources: [{ kind: "image", url: img }], settings: { ...open, length: 20 }, autoRender: true });
+ await faceless.scriptWritten(ep.id);
+ const v = await view(ep.id);
+ expect(v.episode.status).toBe("rendering");
+ const still = v.steps.find((s) => s.part === "still")!.generation!;
+ expect(still).toMatchObject({ modelId: "oss-qwen-edit", op: "edit" });
+ expect(still.request.inputs?.images).toEqual([img]);
+ await faceless.deleteEpisode(ep.id);
});
it("refuses links to this machine (SSRF-safe fetch)", async () => {
diff --git a/tests/faceless.test.ts b/tests/faceless.test.ts
index c9b86cf2..d626a794 100644
--- a/tests/faceless.test.ts
+++ b/tests/faceless.test.ts
@@ -41,9 +41,19 @@ import {
totalSeconds,
wordCount,
youtubeKind,
+ ANIMATION_MODES,
+ filmSeconds,
+ musicLength,
+ plannedTiming,
+ sceneSpans,
+ sceneTiming,
+ spokenTimes,
+ styleRefLimit,
+ withTiming,
type EpisodeSettings,
type GraphInput,
type ScriptBlock,
+ type TimedText,
} from "@/lib/catalog/faceless";
const research = JSON.parse(fs.readFileSync(path.join(__dirname, "../docs/research/higgsfield-marketing-agents.json"), "utf8"));
@@ -76,7 +86,7 @@ describe("research data", () => {
it("only uses models and voices the catalog has", () => {
for (const engine of ["cloud", "open"] as const) {
const m = ENGINE_MODELS[engine];
- for (const id of [m.still, m.styleStill, m.editStill, m.video, ...m.videoChoices, m.narration, m.cloneNarration, m.longNarration, m.music, m.join, m.mux, m.mixMusic, m.captions, m.write, m.transcribe].filter(Boolean)) {
+ for (const id of [m.still, m.styleStill, m.editStill, m.video, ...m.videoChoices, m.narration, m.cloneNarration, m.longNarration, m.music, m.join, m.mux, m.mixMusic, m.levelMusic, m.captions, m.align, m.sourceStill, m.upscale, m.write].filter(Boolean)) {
expect(getModel(id!), id).toBeTruthy();
}
}
@@ -145,6 +155,9 @@ describe("render graph", () => {
const mix = g.find((s) => s.key === "mix")!;
expect(mix.request.modelId).toBe("merge-audio-video");
expect(mix.after).toEqual(["join", "narration"]);
+ expect(mix.label).toBe("Mixing");
+ // ElevenLabs forced alignment reads the known script with the recording.
+ expect(g.find((s) => s.key === "words")!.request).toMatchObject({ modelId: "elevenlabs-align", op: "transcribe", prompt: narrationText(six) });
const narration = g.find((s) => s.key === "narration")!;
expect(narration.request).toMatchObject({ modelId: "elevenlabs-v4", op: "tts", params: { voice: "Xb7hH8MSUJpSbSDYk0k2" } });
expect(narration.request.prompt).toBe(narrationText(six));
@@ -177,11 +190,15 @@ describe("render graph", () => {
expect(joins.every((j) => j.request.modelId === "oss-join-clips")).toBe(true);
const narration = g.find((s) => s.key === "narration")!;
expect(narration.request).toMatchObject({ modelId: "oss-chatterbox", inputs: { voiceAudio: "/api/files/uploads/demo-voice.wav" } });
- expect(g.find((s) => s.key === "music")!.request).toMatchObject({ modelId: "oss-ace-step", op: "music", params: { duration: 60, extra: { lyrics: "[Instrumental]" } } });
+ // The bed is as long as the film (60 s of 5-second shots) plus a second.
+ expect(g.find((s) => s.key === "music")!.request).toMatchObject({ modelId: "oss-ace-step", op: "music", params: { duration: 61, extra: { lyrics: "[Instrumental]" } } });
const mix = g.find((s) => s.key === "mix")!;
expect(mix).toMatchObject({ after: ["join", "narration", "music"], chain: [{ slot: "video" }, { slot: "audio" }, { slot: "audio2" }] });
expect(mix.request).toMatchObject({ modelId: "oss-mux", params: { extra: { backgroundVolumeDb: -14 } } });
- expect(g.find((s) => s.key === "words")!.request).toMatchObject({ modelId: "oss-qwen3-asr", op: "transcribe" });
+ // Qwen3-ASR times the narration (the scenes are cut to it) and its lines are burned in.
+ const words = g.find((s) => s.key === "words")!;
+ expect(words).toMatchObject({ after: ["narration"], chain: [{ slot: "audio" }], request: { modelId: "oss-qwen3-asr", op: "transcribe" } });
+ expect(words.request.prompt).toBeUndefined();
expect(g.find((s) => s.key === "captions")).toMatchObject({ after: ["mix", "words"], chain: [{ slot: "video" }, { slot: "prompt" }], request: { modelId: "oss-captions-burnin" } });
expect(estimateGraph(g, getModel).total).toBe(0);
});
@@ -195,10 +212,20 @@ describe("render graph", () => {
expect(still.request.prompt).toMatch(/style of the reference images/);
const openRefs = graphFor({ engine: "open", styleRefs: ["/api/files/a.png", "/api/files/b.png", "/api/files/c.png"] }, six);
expect(openRefs.find((s) => s.part === "still")!.request).toMatchObject({ modelId: "oss-style-qwen-edit", inputs: { images: ["/api/files/a.png", "/api/files/b.png"] } });
- // A cloud episode with music mixes on the open mixer (the cloud tool takes one track).
+ // A cloud episode with music: the Sonilo bed (as long as the film) is levelled to -28 LUFS, then fal's
+ // compose lays the voice and the bed on the film in one pass — no ComfyUI needed.
const music = graphFor({ engine: "cloud", music: true }, six);
- expect(music.find((s) => s.key === "mix")!.request.modelId).toBe("oss-mux");
- expect(music.find((s) => s.key === "music")!.request).toMatchObject({ modelId: "sonilo-music", params: { duration: 60 } });
+ expect(music.find((s) => s.key === "music")!.request).toMatchObject({ modelId: "sonilo-music", params: { duration: 55 } });
+ expect(music.find((s) => s.key === "level")).toMatchObject({
+ part: "music",
+ after: ["music"],
+ chain: [{ slot: "audio" }],
+ request: { modelId: "ffmpeg-loudnorm", op: "level", params: { extra: { integrated_loudness: -28 } } },
+ });
+ const composed = music.find((s) => s.key === "mix")!;
+ expect(composed).toMatchObject({ label: "Mixing voice and music", after: ["join", "narration", "level"], chain: [{ slot: "video" }, { slot: "audio" }, { slot: "audio2" }] });
+ expect(composed.request).toMatchObject({ modelId: "ffmpeg-compose", op: "mux", params: { duration: 54 } });
+ expect(music.every((s) => getModel(s.request.modelId)!.engine === "cloud")).toBe(true);
// No subtitles: the mix is the final step and carries the title.
const plain = graphFor({ engine: "cloud", subtitles: false, music: false }, six);
expect(finalKey(plain)).toBe("mix");
@@ -249,7 +276,7 @@ describe("timeline re-runs and retries", () => {
expect(motion.rerun).not.toContain("still-b0");
expect(motion.rerun).toContain("clip-b0-1");
const voice = planRerun(g, changedKeys(g, ["b0"], "narration"));
- expect(voice.rerun).toEqual(["narration", "mix", "words", "captions"]);
+ expect(voice.rerun).toEqual(["narration", "words", "mix", "captions"]);
});
it("a retry redoes failed steps and what waits on them, and keeps what finished", () => {
@@ -280,8 +307,10 @@ describe("cost", () => {
const e = estimateGraph(g, getModel);
expect(e.parts.still).toBeCloseTo(0.9, 5);
expect(e.parts.clip).toBeCloseTo(6, 5);
- expect(e.total).toBeGreaterThan(6.9);
- expect(e.total).toBeLessThan(7.2);
+ // Forced alignment: $0.22 per started hour of audio.
+ expect(e.parts.words).toBeCloseTo(0.22, 5);
+ expect(e.total).toBeGreaterThan(7.1);
+ expect(e.total).toBeLessThan(7.4);
expect(e.unknown).toBe(false);
// Only what a change re-runs.
const one = estimateGraph(g, getModel, ["still-p0", "clip-p0-1"]);
@@ -337,3 +366,166 @@ describe("writing", () => {
expect(() => explainerSeconds(30.5)).toThrow(/whole number/);
});
});
+
+/** Word timings as a forced aligner gives them: every word at `pace` seconds a word, a pause between blocks. */
+function aligned(blocks: ScriptBlock[], pace: number, pause = 0.4, lead = 0.15): TimedText[] {
+ const cues: TimedText[] = [];
+ let t = lead;
+ for (const b of blocks) {
+ for (const w of b.narration.split(/\s+/).filter(Boolean)) {
+ cues.push({ start: t, end: t + pace * 0.9, text: w });
+ t += pace;
+ }
+ t += pause;
+ }
+ return cues;
+}
+
+describe("timing: every scene cut to its spoken lines", () => {
+ const six = Array.from({ length: 6 }, (_, i) => block(i));
+ const gemini = getModel("gemini-omni-flash");
+ const wan = getModel("oss-wan22-14b-fast");
+
+ it("finds where each block's lines start, from forced-alignment words or ASR phrases", () => {
+ const words = aligned(six, 0.5);
+ const t = spokenTimes(six, words)!;
+ expect(t.starts[0]).toBeCloseTo(0.15);
+ // 20 words × 0.5 s, then a 0.4 s pause, per block.
+ expect(t.starts[1]).toBeCloseTo(0.15 + 10.4);
+ expect(t.starts[5]).toBeCloseTo(0.15 + 5 * 10.4);
+ expect(t.end).toBeCloseTo(words[words.length - 1].end);
+ // Phrase cues (five words each, as ASR and caption grouping give them): the same starts, interpolated.
+ const phrases: TimedText[] = [];
+ for (let i = 0; i < words.length; i += 5) phrases.push({ start: words[i].start, end: words[i + 4].end, text: words.slice(i, i + 5).map((w) => w.text).join(" ") });
+ const p = spokenTimes(six, phrases)!;
+ six.forEach((_, i) => expect(Math.abs(p.starts[i]! - t.starts[i]!)).toBeLessThan(0.5));
+ // An ASR that mishears some words and hears one that isn't there still lines up.
+ const heard = words.map((w, i) => (i % 9 === 4 ? { ...w, text: "mmm," } : w));
+ heard.splice(30, 0, { start: heard[30].start, end: heard[30].start + 0.1, text: "uh" });
+ const asr = spokenTimes(six, heard)!;
+ six.forEach((_, i) => expect(Math.abs(asr.starts[i]! - t.starts[i]!)).toBeLessThan(0.6));
+ });
+
+ it("refuses timings that aren't this narration (a demo transcript, nothing)", () => {
+ const demo = [
+ { start: 0, end: 2.3, text: "This is a demo transcript." },
+ { start: 2.5, end: 4.8, text: "Connect a speech-to-text provider in Settings," },
+ { start: 5, end: 7.3, text: "or start ComfyUI, to transcribe your clip for real." },
+ ];
+ expect(spokenTimes(six, demo)).toBeNull();
+ expect(spokenTimes(six, [])).toBeNull();
+ });
+
+ it("cuts each scene to its lines, the next scene absorbing a shot's rounding (Gemini: any whole second)", () => {
+ // A slow narrator: about 11 s a block where 9 s were planned.
+ const t = spokenTimes(six, aligned(six, 0.53))!;
+ const timing = sceneTiming(six, t, gemini);
+ const secs = six.map((b) => timing[b.id]);
+ expect(secs.every((s) => Number.isInteger(s) && s >= 3)).toBe(true);
+ let film = 0;
+ six.forEach((b, i) => {
+ // Each scene starts in the film within a rounding of where its lines start.
+ if (i > 0) expect(Math.abs(film - t.starts[i]!)).toBeLessThan(0.75);
+ film += timing[b.id];
+ });
+ expect(film).toBeGreaterThanOrEqual(t.end);
+ expect(film).toBeLessThan(t.end + 2);
+ // The graph makes exactly those lengths (a scene over 10 s takes two shots), and the timeline shows them.
+ const g = graphFor({ engine: "cloud", music: false }, withTiming(six, timing));
+ expect(sceneSpans(g, 6).map((s) => s.seconds)).toEqual(secs);
+ expect(g.filter((s) => s.part === "clip").length).toBeGreaterThan(6);
+ expect(g.find((s) => s.key === "mix")!.seconds).toBe(film);
+ });
+
+ it("doesn't drift with Wan's 3- and 5-second shots either", () => {
+ const t = spokenTimes(six, aligned(six, 0.42))!;
+ const timing = sceneTiming(six, t, wan);
+ let film = 0;
+ six.forEach((b, i) => {
+ if (i > 0) expect(Math.abs(film - t.starts[i]!)).toBeLessThan(2.5);
+ film += timing[b.id];
+ });
+ expect(Math.abs(film - t.end)).toBeLessThan(3.5);
+ // Planned lengths as film: a 9-second block is 5 + 5 on Wan.
+ expect(plannedTiming(six, wan)).toEqual(Object.fromEntries(six.map((b) => [b.id, 10])));
+ });
+
+ it("gives a block the same shots planned or timed (the graph derives them from its length)", () => {
+ for (const m of [gemini, wan, getModel("seedance-2-5")]) {
+ for (let s = 3; s <= 25; s++) expect(blockShots(filmSeconds(s, m), m)).toEqual(blockShots(s, m));
+ }
+ });
+
+ it("keeps the scenes that moved a second or less when a narration change is re-timed", () => {
+ const before = sceneTiming(six, spokenTimes(six, aligned(six, 0.5))!, gemini);
+ // Scene 3's lines get twice as long; the new take reads the rest at nearly the same pace.
+ const changed = six.map((b, i) => (i === 2 ? { ...b, narration: `${b.narration} ${b.narration}` } : b));
+ const after = sceneTiming(changed, spokenTimes(changed, aligned(changed, 0.505))!, gemini, before);
+ expect(after.b0).toBe(before.b0);
+ expect(after.b1).toBe(before.b1);
+ expect(after.b2).toBeGreaterThan(before.b2 + 5);
+ expect(six.filter((b) => after[b.id] !== before[b.id]).length).toBeLessThanOrEqual(3);
+ });
+
+ it("lets a scene without lines keep its own length, out of the scene before it", () => {
+ const blocks = [block(0), { ...block(1, 0), seconds: 4 }, block(2)];
+ const t = spokenTimes(blocks, aligned(blocks, 0.5))!;
+ expect(t.starts[1]).toBeNull();
+ const timing = sceneTiming(blocks, t, gemini);
+ expect(timing.b1).toBe(4);
+ expect(Math.abs(timing.b0 + timing.b1 - t.starts[2]!)).toBeLessThan(1);
+ });
+});
+
+describe("pictures from sources, style references, music length, frame pricing", () => {
+ const six = Array.from({ length: 6 }, (_, i) => block(i));
+ const [a, b, c, x] = ["/api/files/uploads/a.png", "/api/files/uploads/b.png", "/api/files/uploads/c.png", "/api/files/uploads/x.png"];
+
+ it("draws open pictures from attached images with a multi-image edit model", () => {
+ const g = graphFor({ engine: "open", voice: null, sourceImages: [a, b] }, six);
+ const still = g.find((s) => s.part === "still")!;
+ expect(still.request).toMatchObject({ modelId: "oss-qwen-edit", op: "edit", inputs: { images: [a, b] } });
+ expect(still.request.prompt).toMatch(/attached source pictures/);
+ expect(still.request.prompt).toMatch(/Style: /);
+ // Style references win over the sources; the open style model reads two of them.
+ const refs = graphFor({ engine: "open", voice: null, styleRefs: [a, b, c], sourceImages: [x] }, six);
+ expect(refs.find((s) => s.part === "still")!.request).toMatchObject({ modelId: "oss-style-qwen-edit", inputs: { images: [a, b] } });
+ expect(styleRefLimit("open", getModel)).toBe(2);
+ expect(styleRefLimit("cloud", getModel)).toBe(3);
+ // The cloud picture model reads the references and the sources.
+ const cloud = graphFor({ engine: "cloud", styleRefs: [a], sourceImages: [x] }, six);
+ expect(cloud.find((s) => s.part === "still")!.request).toMatchObject({ modelId: "nano-banana-pro", inputs: { images: [a, x] } });
+ });
+
+ it("makes the music bed as long as the film, up to what the model makes", () => {
+ expect(musicLength(getModel("sonilo-music"), 300)).toBe(301);
+ expect(musicLength(getModel("sonilo-music"), 700)).toBe(600);
+ expect(musicLength(getModel("oss-ace-step"), 300)).toBe(240);
+ expect(musicLength(getModel("elevenlabs-music"), 50)).toBe(60);
+ });
+
+ it("makes Frame by frame cheaper with Seedance 2.5 too, and says what it saves on each engine", () => {
+ const priced = (animation: "animated" | "frames") => estimateGraph(graphFor({ engine: "cloud", music: false, videoModel: "seedance-2-5", animation }, placeholderBlocks(300)), getModel);
+ expect(priced("frames").parts.clip).toBeLessThan(priced("animated").parts.clip! * 0.6);
+ const frames = ANIMATION_MODES.find((m) => m.id === "frames")!;
+ expect(frames.copy).toMatch(/lighter on credits/);
+ expect(frames.openCopy).not.toMatch(/credits/);
+ });
+});
+
+describe("offline topic suggestions", () => {
+ it("brings new topics every round until the templates run out", () => {
+ for (const g of GENRES) {
+ const first = offlineTopics("Channel about volcanoes", g.id, 5);
+ const second = offlineTopics("Channel about volcanoes", g.id, 5, 1, first.map((t) => t.title));
+ expect(second).toHaveLength(5);
+ expect(second.filter((t) => first.some((f) => f.title === t.title))).toEqual([]);
+ const third = offlineTopics("Channel about volcanoes", g.id, 5, 2, [...first, ...second].map((t) => t.title));
+ expect(third).toHaveLength(5);
+ expect(third.filter((t) => ![...first, ...second].some((f) => f.title === t.title)).length).toBeGreaterThanOrEqual(2);
+ // Without the list of shown titles, rounds page through the templates.
+ const paged = offlineTopics("Channel about volcanoes", g.id, 5, 1);
+ expect(paged.filter((t) => first.some((f) => f.title === t.title))).toEqual([]);
+ }
+ });
+});