Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

sprite walk: variable frame count + configurable playback speed, reprocessable from disk

[._.]/ Adam Eivye443d14ff06f
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 341f3f3217..04961a2436 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1093,6 +1093,13 @@ const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);
const spriteWalkRunIdSchema = z.string().regex(/^walk-[a-z-]+-[0-9a-f]{8}$/);
+// Walk-cycle authoring bounds. Mirror walkPostprocess.js WALK_MIN/MAX_* — kept
+// as literals here so the validation graph doesn't pull sharp/ffmpeg in via
+// walkPostprocess. The server re-clamps into the same range, so these are a
+// guard, not the source of truth: frame count 6–16, playback fps 4–24.
+const spriteWalkFrameCountSchema = z.number().int().min(6).max(16);
+const spriteWalkFpsSchema = z.number().int().min(4).max(24);
+
export const spriteWalkGenerateSchema = z.object({
direction: spriteWalkDirectionSchema,
// Clip length in seconds (see GROK_VIDEO_DURATIONS). Short clips are ample
@@ -1100,6 +1107,10 @@ export const spriteWalkGenerateSchema = z.object({
duration: z.union([
z.literal(1), z.literal(2), z.literal(3), z.literal(6), z.literal(10),
]).optional(),
+ // Deterministic-postprocess knobs (not grok's): how many frames the packed
+ // cycle holds and how fast it plays back. Omitted → service defaults.
+ frameCount: spriteWalkFrameCountSchema.optional(),
+ fps: spriteWalkFpsSchema.optional(),
});
export const spriteWalkApproveSchema = z.object({
@@ -1107,8 +1118,16 @@ export const spriteWalkApproveSchema = z.object({
runId: spriteWalkRunIdSchema,
});
+export const spriteWalkReopenSchema = z.object({
+ direction: spriteWalkDirectionSchema,
+});
+
export const spriteWalkPostprocessSchema = z.object({
runId: spriteWalkRunIdSchema,
+ // Reprocess the on-disk clip at a new count/fps without regenerating. Omitted
+ // fields keep the run's stored values.
+ frameCount: spriteWalkFrameCountSchema.optional(),
+ fps: spriteWalkFpsSchema.optional(),
});
// The trimmer targets ANY resolvable run, not just native `walk-<dir>-<hex>`
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 1c56fe4499..e9d2f35bb6 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -22,6 +22,7 @@ import {
spriteForkSchema,
spriteWalkGenerateSchema,
spriteWalkApproveSchema,
+ spriteWalkReopenSchema,
spriteWalkPostprocessSchema,
spriteWalkTrimSchema,
spritePublishBindingSchema,
@@ -42,6 +43,7 @@ import {
import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
+ reopenWalkDirection,
} from '../services/sprites/walk.js';
import { saveLoopTrim } from '../services/sprites/walkTrims.js';
import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';
@@ -171,6 +173,14 @@ router.post('/:id/walk/unlock', asyncHandler(async (req, res) => {
res.json(await unlockWalkSet(req.params.id));
}));
+// Re-open ONE approved direction (finer-grained than unlock) so it can be
+// regenerated/reprocessed/re-approved — the user noticed one walk is too fast
+// or wrong. Un-finalizes a frozen set but keeps other directions' approvals.
+router.post('/:id/walk/reopen', asyncHandler(async (req, res) => {
+ const body = validateRequest(spriteWalkReopenSchema, req.body);
+ res.json(await reopenWalkDirection(req.params.id, body));
+}));
+
// Re-run the deterministic postprocess for a run whose video already landed
// (crash recovery / determinism verification). No AI call involved.
router.post('/:id/walk/postprocess', asyncHandler(async (req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index daa0982379..dcaaf32585 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -32,6 +32,8 @@ vi.mock('../services/sprites/walk.js', () => ({
startWalkGeneration: vi.fn(async () => ({ jobId: 'v1', runId: 'walk-east-0a1b2c3d', direction: 'east', duration: 6 })),
approveWalkDirection: vi.fn(async () => ({ runs: [], selection: { status: 'in-progress' }, walkSet: null })),
rerunWalkPostprocess: vi.fn(async () => ({ id: 'walk-east-0a1b2c3d', status: 'candidate' })),
+ unlockWalkSet: vi.fn(async () => ({ runs: [], selection: { status: 'in-progress' }, walkSet: null })),
+ reopenWalkDirection: vi.fn(async () => ({ runs: [], selection: { status: 'in-progress' }, walkSet: null })),
}));
vi.mock('../services/sprites/walkTrims.js', () => ({
@@ -370,6 +372,28 @@ describe('sprites routes', () => {
.send({ direction: 'south' })).status).toBe(200);
});
+ it('POST /:id/walk/generate forwards frame count + fps and bounds them', async () => {
+ walk.startWalkGeneration.mockClear();
+ const r = await request(app).post('/api/sprites/pioneer/walk/generate')
+ .send({ direction: 'east', frameCount: 14, fps: 8 });
+ expect(r.status).toBe(200);
+ expect(walk.startWalkGeneration).toHaveBeenCalledWith('pioneer', { direction: 'east', frameCount: 14, fps: 8 });
+ // Out-of-range count / fps are rejected by the schema.
+ expect((await request(app).post('/api/sprites/pioneer/walk/generate')
+ .send({ direction: 'east', frameCount: 32 })).status).toBe(400);
+ expect((await request(app).post('/api/sprites/pioneer/walk/generate')
+ .send({ direction: 'east', fps: 99 })).status).toBe(400);
+ });
+
+ it('POST /:id/walk/reopen validates the direction and delegates', async () => {
+ const r = await request(app).post('/api/sprites/pioneer/walk/reopen')
+ .send({ direction: 'east' });
+ expect(r.status).toBe(200);
+ expect(walk.reopenWalkDirection).toHaveBeenCalledWith('pioneer', { direction: 'east' });
+ expect((await request(app).post('/api/sprites/pioneer/walk/reopen')
+ .send({ direction: 'up' })).status).toBe(400);
+ });
+
it('POST /:id/walk/approve validates the run id shape', async () => {
const r = await request(app).post('/api/sprites/pioneer/walk/approve')
.send({ direction: 'east', runId: 'walk-east-0a1b2c3d' });
@@ -381,11 +405,19 @@ describe('sprites routes', () => {
expect(walk.approveWalkDirection).toHaveBeenCalledOnce();
});
- it('POST /:id/walk/postprocess delegates the rerun', async () => {
+ it('POST /:id/walk/postprocess delegates the rerun (with optional reprocess count/fps)', async () => {
const r = await request(app).post('/api/sprites/pioneer/walk/postprocess')
.send({ runId: 'walk-east-0a1b2c3d' });
expect(r.status).toBe(200);
expect(walk.rerunWalkPostprocess).toHaveBeenCalledWith('pioneer', { runId: 'walk-east-0a1b2c3d' });
+
+ walk.rerunWalkPostprocess.mockClear();
+ const r2 = await request(app).post('/api/sprites/pioneer/walk/postprocess')
+ .send({ runId: 'walk-east-0a1b2c3d', frameCount: 16, fps: 6 });
+ expect(r2.status).toBe(200);
+ expect(walk.rerunWalkPostprocess).toHaveBeenCalledWith('pioneer', { runId: 'walk-east-0a1b2c3d', frameCount: 16, fps: 6 });
+ expect((await request(app).post('/api/sprites/pioneer/walk/postprocess')
+ .send({ runId: 'walk-east-0a1b2c3d', frameCount: 3 })).status).toBe(400);
});
it('POST /:id/walk/trim validates and 201s', async () => {
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 5395263ca3..963c9fdc6a 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -2,10 +2,13 @@
* Sprites — runtime atlas compiler (issue #2898, phase 4).
*
* Compiles the immutable runtime sprite-sheet from a finalized eight-direction
- * walk set: a 10-column × 8-row grid (idle, the 8 named gait phases, scanner ×
- * S/SE/E/NE/N/NW/W/SW) of fixed-size cells, each frame scaled once per
- * direction and translated so its silhouette centers on the pivot x and its
- * feet land exactly on the pivot ground line. Ports the source pipeline's
+ * walk set: an (idle + N walk phases + scanner)-column × 8-row grid (× S/SE/E/
+ * NE/N/NW/W/SW) of fixed-size cells, each frame scaled once per direction and
+ * translated so its silhouette centers on the pivot x and its feet land exactly
+ * on the pivot ground line. N (the walk frame count) is read from the approved
+ * run manifests — every direction must share it — so the atlas width tracks the
+ * authored count (historically 8; variable per #sprite-walk-variable-frames).
+ * Ports the source pipeline's
* `runtime_publish.py` compile stage; all math preserves Python semantics
* (banker's rounding via pyRound, exclusive-bbox bounds) so cell placement
* matches the production atlases the importer brought over.
@@ -36,7 +39,9 @@ import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS } from './prompts.js';
import { keyChannelSplit } from './chromaKey.js';
import {
- WALK_PHASES, pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,
+ WALK_PHASES, walkPhaseLabels, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT,
+ WALK_MIN_FPS, WALK_MAX_FPS, WALK_FPS,
+ pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,
sampleBorderKey, validateMeasuredKey, recoverAlphaFrame, despillKeyFrame,
alphaBbox, compositeOnto, sha256Buffer,
} from './walkPostprocess.js';
@@ -45,7 +50,15 @@ import { withWalkWriteTail, walkSetRelPath, isImportedWalkSet } from './walk.js'
// Player atlas contract (source pipeline runtime_publish.py): 96px cells,
// pivot (48,88) — silhouette centered on x=48, feet on the y=88 ground line —
// content bounded to 86×74 so nothing touches a cell edge.
-export const ATLAS_COLUMNS = ['idle', ...WALK_PHASES, 'scanner'];
+//
+// The runtime grid is `idle` + the N walk-phase columns + `scanner`. N is the
+// walk set's frame count (variable-frame walks: #sprite-walk-variable-frames);
+// it is read from the approved run manifests, not hardcoded, so the atlas width
+// grows/shrinks with the chosen count. ATLAS_COLUMNS is the historical 8-frame
+// layout, kept as the default/fallback; atlasColumns(labels) builds the actual
+// column list a given compile uses.
+export const atlasColumns = (walkLabels) => ['idle', ...walkLabels, 'scanner'];
+export const ATLAS_COLUMNS = atlasColumns(WALK_PHASES);
export const DEFAULT_ATLAS_GEOMETRY = {
cellSize: 96,
pivot: [48, 88],
@@ -219,6 +232,11 @@ export async function validateForCompile(recordId) {
}
const runs = {};
+ // Resolved from the first approved direction, then enforced identical across
+ // the rest (see the loop body). null until the first direction is read.
+ let frameCount = null;
+ let walkFps = null;
+ let walkLabels = null;
for (const direction of SPRITE_DIRECTIONS) {
const entry = walkSet.directions?.[direction];
if (!entry || entry.status !== 'approved') throw compileError(`Direction ${direction} is not approved`);
@@ -233,12 +251,38 @@ export async function validateForCompile(recordId) {
throw compileError(`Run manifest for ${direction} is unreadable or mislabeled`);
}
const frames = manifest.frames || [];
- if (frames.length !== WALK_PHASES.length) {
- throw compileError(`Direction ${direction} has ${frames.length} frames — expected ${WALK_PHASES.length}`);
+ // Frame count is variable, but every direction in ONE atlas MUST share it —
+ // the atlas is a rectangular grid, so a ragged set can't compile. The first
+ // approved direction sets N; the rest must match. N must also be in range and
+ // agree with the manifest's declared frameCount.
+ if (frameCount === null) {
+ frameCount = frames.length;
+ if (!Number.isInteger(frameCount)
+ || frameCount < WALK_MIN_FRAME_COUNT || frameCount > WALK_MAX_FRAME_COUNT) {
+ throw compileError(`Direction ${direction} has ${frames.length} frames — outside the supported ${WALK_MIN_FRAME_COUNT}–${WALK_MAX_FRAME_COUNT} range`);
+ }
+ walkLabels = walkPhaseLabels(frameCount);
+ } else if (frames.length !== frameCount) {
+ throw compileError(`Direction ${direction} has ${frames.length} frames but the set uses ${frameCount} — reprocess all directions to the same frame count before compiling`);
+ }
+ if (Number.isInteger(manifest.frameCount) && manifest.frameCount !== frames.length) {
+ throw compileError(`Direction ${direction} manifest declares ${manifest.frameCount} frames but carries ${frames.length}`);
+ }
+ // Playback fps likewise must agree across directions so the whole walk set
+ // animates at one speed. Range-checked; falls back to the legacy 12 for
+ // pre-fps manifests so older sets still compile.
+ const dirFps = Number.isFinite(manifest.frameRate) ? manifest.frameRate : WALK_FPS;
+ if (dirFps < WALK_MIN_FPS || dirFps > WALK_MAX_FPS) {
+ throw compileError(`Direction ${direction} playback fps ${dirFps} is outside the supported ${WALK_MIN_FPS}–${WALK_MAX_FPS} range`);
+ }
+ if (walkFps === null) {
+ walkFps = dirFps;
+ } else if (dirFps !== walkFps) {
+ throw compileError(`Direction ${direction} plays at ${dirFps} fps but the set uses ${walkFps} — reprocess all directions to the same speed before compiling`);
}
const frameBytes = [];
for (let i = 0; i < frames.length; i++) {
- if (frames[i].phase !== WALK_PHASES[i] || frames[i].outputIndex !== i) {
+ if (frames[i].phase !== walkLabels[i] || frames[i].outputIndex !== i) {
throw compileError(`Direction ${direction} frame ${i} is out of gait-phase order`);
}
frameBytes.push(await readVerified(frames[i].path, frames[i].sha256, `Direction ${direction} frame ${frames[i].phase}`));
@@ -254,6 +298,9 @@ export async function validateForCompile(recordId) {
chromaKey,
anchors,
runs,
+ walkFrameCount: frameCount,
+ walkFps,
+ walkLabels,
};
}
@@ -265,7 +312,7 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {
for (const bytes of frameBytes) {
walkSources.push(await transparentSource(bytes, split, validated.chromaKey));
}
- const dims = walkSources.map((f, i) => occupiedDimensions(f, ALPHA_THRESHOLD, `${direction}-${WALK_PHASES[i]}`));
+ const dims = walkSources.map((f, i) => occupiedDimensions(f, ALPHA_THRESHOLD, `${direction}-${manifest.frames[i].phase}`));
const directionScale = Math.min(
geometry.targetMaxHeight / Math.max(...dims.map((d) => d.height)),
geometry.targetMaxWidth / Math.max(...dims.map((d) => d.width)),
@@ -404,7 +451,9 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
}
const { cellSize } = geometry;
- const atlasWidth = cellSize * ATLAS_COLUMNS.length;
+ // Columns/width follow the set's actual frame count, not the historical 8.
+ const columns = atlasColumns(validated.walkLabels);
+ const atlasWidth = cellSize * columns.length;
const atlasHeight = cellSize * SPRITE_DIRECTIONS.length;
const atlas = { data: Buffer.alloc(atlasWidth * atlasHeight * 4), width: atlasWidth, height: atlasHeight };
for (let r = 0; r < rows.length; r++) {
@@ -477,7 +526,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
atlasPath: atlasRel,
atlasSha256,
geometry: {
- columns: ATLAS_COLUMNS,
+ columns,
directionOrder: SPRITE_DIRECTIONS,
rows: SPRITE_DIRECTIONS.length,
cellSize,
@@ -486,6 +535,10 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
targetMaxWidth: geometry.targetMaxWidth,
widthPx: atlasWidth,
heightPx: atlasHeight,
+ // Runtime playback metadata: the external game reads these to animate the
+ // walk row at the authored speed over the right number of columns.
+ walkFrameCount: validated.walkFrameCount,
+ walkFps: validated.walkFps,
},
directions: rows.map((row) => ({
direction: row.direction,
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index 247ac1b688..07d9e0685a 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -43,7 +43,7 @@ const records = await import('./records.js');
const { lockReference, loadManifest } = await import('./reference.js');
const { compileAtlas, getAtlasState, ATLAS_COLUMNS, DEFAULT_ATLAS_GEOMETRY } = await import('./atlas.js');
const { SPRITE_DIRECTIONS } = await import('./prompts.js');
-const { WALK_PHASES } = await import('./walkPostprocess.js');
+const { WALK_PHASES, walkPhaseLabels } = await import('./walkPostprocess.js');
let seq = 0;
const newId = () => `atlas-char-${++seq}`;
@@ -67,10 +67,11 @@ async function walkFramePng(path, tint) {
await sharp(buf, { raw: { width: w, height: h, channels: 4 } }).png().toFile(path);
}
-async function buildFinalizedWalkSet(recordId) {
+async function buildFinalizedWalkSet(recordId, { frameCount = WALK_PHASES.length, fps } = {}) {
const manifest = await loadManifest(recordId);
const chromaKey = manifest.chromaKey;
const dir = join(TEST_ROOT, 'sprites', recordId);
+ const labels = walkPhaseLabels(frameCount);
const selection = {
schemaVersion: 1,
kind: 'reviewed-directional-walk-selection',
@@ -82,13 +83,13 @@ async function buildFinalizedWalkSet(recordId) {
const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;
const generatedRel = `grok/${runId}/generated`;
const frames = [];
- for (let i = 0; i < WALK_PHASES.length; i++) {
- const name = `${String(i).padStart(2, '0')}-${WALK_PHASES[i]}.png`;
+ for (let i = 0; i < labels.length; i++) {
+ const name = `${String(i).padStart(2, '0')}-${labels[i]}.png`;
const rel = `${generatedRel}/frames/${name}`;
await walkFramePng(join(dir, rel), 20 + i * 8);
frames.push({
outputIndex: i,
- phase: WALK_PHASES[i],
+ phase: labels[i],
path: rel,
sha256: sha256(await readFile(join(dir, rel))),
});
@@ -99,6 +100,8 @@ async function buildFinalizedWalkSet(recordId) {
characterId: recordId,
direction,
chromaKey,
+ frameCount,
+ ...(fps != null ? { frameRate: fps } : {}),
frames,
};
const manifestRel = `${generatedRel}/${recordId}-walk-${direction}-manifest.json`;
@@ -186,6 +189,56 @@ describe('compileAtlas', () => {
expect(state.publications).toEqual([]);
});
+ it('compiles a variable-frame (12-frame) walk set into a wider atlas + geometry', async () => {
+ const id = newId();
+ await lockAllAnchors(id);
+ await buildFinalizedWalkSet(id, { frameCount: 12, fps: 8 });
+ const result = await compileAtlas(id);
+
+ const meta = await sharp(join(TEST_ROOT, 'sprites', id, result.atlasPath)).metadata();
+ // idle + 12 walk phases + scanner = 14 columns.
+ expect(meta.width).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * 14);
+ expect(meta.height).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * SPRITE_DIRECTIONS.length);
+
+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));
+ expect(manifest.geometry.columns).toEqual(['idle', ...walkPhaseLabels(12), 'scanner']);
+ expect(manifest.geometry.walkFrameCount).toBe(12);
+ expect(manifest.geometry.walkFps).toBe(8);
+ expect(manifest.geometry.widthPx).toBe(DEFAULT_ATLAS_GEOMETRY.cellSize * 14);
+ for (const row of manifest.directions) expect(row.cells).toHaveLength(14);
+ });
+
+ it('refuses to compile a set whose directions disagree on frame count', async () => {
+ const id = newId();
+ await lockAllAnchors(id);
+ await buildFinalizedWalkSet(id, { frameCount: 12, fps: 10 });
+ // Corrupt ONE direction's run manifest to carry 8 frames instead of 12, and
+ // re-hash the selection entry so the tamper check passes and the frame-count
+ // mismatch is what trips compile (not a broken evidence chain).
+ const dir = join(TEST_ROOT, 'sprites', id);
+ const selectionRel = `walk/${id}-walk-selection-v1.json`;
+ const selection = JSON.parse(await readFile(join(dir, selectionRel), 'utf8'));
+ const entry = selection.directions.east;
+ const eightFrames = walkPhaseLabels(8).map((phase, i) => ({
+ outputIndex: i, phase, path: `x/${i}.png`, sha256: 'deadbeef',
+ }));
+ const tampered = JSON.stringify({
+ schemaVersion: 1, kind: 'deterministically-packaged-grok-walk-video',
+ characterId: id, direction: 'east', chromaKey: '#FF00FF', frameCount: 8, frames: eightFrames,
+ });
+ await writeFile(join(dir, entry.runManifest), tampered);
+ entry.runManifestSha256 = sha256(Buffer.from(tampered));
+ const walkSetRel = `walk/${id}-walk-set-v1.json`;
+ const walkSet = JSON.parse(await readFile(join(dir, walkSetRel), 'utf8'));
+ walkSet.directions.east = entry;
+ const selectionBytes = JSON.stringify(selection);
+ await writeFile(join(dir, selectionRel), selectionBytes);
+ walkSet.selectionSha256 = sha256(Buffer.from(selectionBytes));
+ await writeFile(join(dir, walkSetRel), JSON.stringify(walkSet));
+
+ await expect(compileAtlas(id)).rejects.toMatchObject({ code: 'ATLAS_COMPILE_INVALID' });
+ });
+
it('is idempotent for the same finalized set — and versions on a changed one', async () => {
const id = await finalizedCharacter();
const first = await compileAtlas(id);
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 71fbbd205b..f749703454 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -35,7 +35,10 @@ import {
import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';
import {
- prepareWalkAnchorChromaInput, runWalkPostprocess, WALK_FPS, WALK_FRAME_COUNT, WALK_CELL_SIZE,
+ prepareWalkAnchorChromaInput, runWalkPostprocess, WALK_CELL_SIZE, WALK_FPS,
+ WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,
+ WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,
+ clampFrameCount, clampFps,
} from './walkPostprocess.js';
import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';
@@ -448,6 +451,13 @@ async function startWalkGenerationImpl(recordId, body) {
getSettings(),
]);
const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : WALK_DEFAULT_DURATION;
+ // Frame count + playback fps are the deterministic-postprocess knobs, not the
+ // grok clip's — grok animates the same clip regardless, and the packer
+ // resamples/labels the cycle afterward. Stored on the run so the completion
+ // hook's packageRun (and any later reprocess) applies the count/fps the user
+ // chose at generate time. Clamped here so a bad body can't reach the packer.
+ const frameCount = clampFrameCount(body.frameCount ?? WALK_DEFAULT_FRAME_COUNT);
+ const fps = clampFps(body.fps ?? WALK_DEFAULT_FPS);
const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey });
const videoAbs = join(generatedAbs, 'source-video.mp4');
const grokPath = settings.imageGen?.grok?.grokPath;
@@ -471,6 +481,8 @@ async function startWalkGenerationImpl(recordId, body) {
direction,
chromaKey,
duration,
+ frameCount,
+ fps,
anchorPath: anchor.path,
anchorSha256: anchor.sha256 || await sha256File(anchorAbs),
animationInputPath: `${runRel}/generated/input-anchor-chroma.png`,
@@ -572,9 +584,17 @@ export async function attachTuiWalkResult(recordId, runId, videoAbs) {
* the completion-hook attach and the manual rerun so the two can't drift.
* The caller persists the mutated record.
*/
-async function packageRun(recordId, run) {
+async function packageRun(recordId, run, overrides = {}) {
const runRel = runRelPath(run.id);
const runAbs = join(spriteDir(recordId), runRel);
+ // Frame count + playback fps: an explicit reprocess override wins, else the
+ // values stored at generate time, else the current defaults (older runs
+ // predate the fields). Clamped + stamped back onto the run so the record
+ // always reflects exactly what was packed and a later reprocess can reuse it.
+ const frameCount = clampFrameCount(overrides.frameCount ?? run.frameCount ?? WALK_DEFAULT_FRAME_COUNT);
+ const fps = clampFps(overrides.fps ?? run.fps ?? WALK_DEFAULT_FPS);
+ run.frameCount = frameCount;
+ run.fps = fps;
// Record-relative path to grok's raw clip, stamped BEFORE the (possibly
// failing) postprocess so a run that errors in packaging still surfaces the
// video grok actually produced in the UI, not just the error text. Set here
@@ -593,6 +613,8 @@ async function packageRun(recordId, run) {
anchorRel: anchor.path,
anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),
videoAbs: join(runAbs, 'generated', 'source-video.mp4'),
+ frameCount,
+ fps,
});
run.status = 'candidate';
run.postprocessManifest = result.manifestPath;
@@ -612,11 +634,11 @@ async function packageRun(recordId, run) {
* landed (crash recovery, or determinism verification). Approved/finalized
* runs are immutable.
*/
-export function rerunWalkPostprocess(recordId, { runId }) {
- return walkWriteTail(recordId, () => rerunWalkPostprocessImpl(recordId, runId));
+export function rerunWalkPostprocess(recordId, { runId, frameCount, fps }) {
+ return walkWriteTail(recordId, () => rerunWalkPostprocessImpl(recordId, runId, { frameCount, fps }));
}
-async function rerunWalkPostprocessImpl(recordId, runId) {
+async function rerunWalkPostprocessImpl(recordId, runId, overrides = {}) {
await requireCharacter(recordId);
await requireUnfinalized(recordId);
const run = await loadRunRecord(recordId, runId);
@@ -629,7 +651,13 @@ async function rerunWalkPostprocessImpl(recordId, runId) {
if (!await pathExists(videoAbs)) {
throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });
}
- await packageRun(recordId, run);
+ // Reprocess the SAME on-disk clip at a (possibly) new frame count / playback
+ // speed — no grok call, no regeneration. Only fields present in the override
+ // change; omitted ones fall through to the run's stored values in packageRun.
+ await packageRun(recordId, run, {
+ ...(overrides.frameCount != null ? { frameCount: overrides.frameCount } : {}),
+ ...(overrides.fps != null ? { fps: overrides.fps } : {}),
+ });
await saveRunRecord(recordId, run);
if (run.status === 'error') {
throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });
@@ -697,6 +725,53 @@ async function unlockWalkSetImpl(recordId) {
return getWalkState(recordId);
}
+/**
+ * Re-open ONE approved direction so it returns to the generate / regenerate /
+ * reprocess / approve flow — without disturbing the other directions' approvals.
+ *
+ * This is the finer-grained sibling of unlockWalkSet: the user notices one walk
+ * is too fast (or wrong) and wants to redo just that direction. Removing a
+ * direction's approval necessarily un-finalizes a frozen set (a walk set is
+ * "final" only when all 8 are approved), so when a walk-set file exists we drop
+ * it and downgrade the record status the same way unlock does — but we keep
+ * every OTHER direction's selection entry intact, so re-freezing is a single
+ * re-approval of the one direction rather than all eight. The rendered clip is
+ * preserved on disk, so the reopened direction can be reprocessed at a new
+ * speed/frame-count with no regeneration. Imported sets have no regenerable
+ * clips and are refused (mirrors unlock).
+ */
+export function reopenWalkDirection(recordId, { direction }) {
+ return walkWriteTail(recordId, () => reopenWalkDirectionImpl(recordId, direction));
+}
+
+async function reopenWalkDirectionImpl(recordId, direction) {
+ await requireCharacter(recordId);
+ const walkSet = await loadWalkSet(recordId);
+ if (walkSet && isImportedWalkSet(walkSet)) {
+ throw new ServerError(
+ 'This walk set was imported from the source pipeline and has no regenerable clips — reopening is not supported. Create a new character version to revise it.',
+ { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },
+ );
+ }
+ const selection = (await loadSelection(recordId)) || seedSelection(recordId);
+ if (selection.directions?.[direction]?.status !== 'approved') {
+ throw new ServerError(`Direction ${direction} is not approved`, { status: 409, code: 'DIRECTION_NOT_APPROVED' });
+ }
+ // If the set was finalized, un-finalize it FIRST (drop the canonical signal)
+ // so a crash mid-reopen can only leave a cosmetic stale record status, never a
+ // walk-complete record with a hole in its set. Other approvals are untouched.
+ if (walkSet) {
+ await rm(join(spriteDir(recordId), walkSetRelPath(recordId)), { force: true });
+ await updateRecord(recordId, { status: 'reference-complete' });
+ }
+ delete selection.directions[direction];
+ selection.status = 'in-progress';
+ await ensureDir(join(spriteDir(recordId), 'walk'));
+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), selection);
+ console.log(`🔓 sprite walk direction ${recordId}/${direction} reopened`);
+ return getWalkState(recordId);
+}
+
async function approveWalkDirectionImpl(recordId, { direction, runId }) {
await requireCharacter(recordId);
await requireUnfinalized(recordId);
@@ -709,10 +784,24 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });
}
// Tamper check: the packaged manifest and strip must still be on disk with
- // the packaged geometry before their approval is frozen into the selection.
+ // self-consistent geometry before their approval is frozen into the selection.
+ // Frame count / fps are no longer pinned to a single value (variable-frame
+ // walks) — instead they must fall inside the supported authoring range and the
+ // declared frameCount must match the actual packed frames. Cross-direction
+ // consistency (all approved directions sharing one count/fps) is enforced at
+ // atlas-compile time, where the whole set is visible at once.
const manifestAbs = resolveSpriteAssetPath(recordId, run.postprocessManifest);
const packaged = await readJSONFile(manifestAbs, null);
- if (!packaged || packaged.frameCount !== WALK_FRAME_COUNT || packaged.frameRate !== WALK_FPS
+ const frameCountValid = Number.isInteger(packaged?.frameCount)
+ && packaged.frameCount >= WALK_MIN_FRAME_COUNT && packaged.frameCount <= WALK_MAX_FRAME_COUNT
+ // If the manifest carries its frames[], they must agree with the declared
+ // count (deep per-frame validation happens at atlas compile). A minimal
+ // manifest that omits frames[] still approves — the strip sha below is the
+ // primary tamper check.
+ && (!Array.isArray(packaged.frames) || packaged.frames.length === packaged.frameCount);
+ const fpsValid = Number.isFinite(packaged?.frameRate)
+ && packaged.frameRate >= WALK_MIN_FPS && packaged.frameRate <= WALK_MAX_FPS;
+ if (!packaged || !frameCountValid || !fpsValid
|| packaged.direction !== direction || packaged.characterId !== recordId) {
throw new ServerError('Packaged run manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });
}
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index bfbe59a317..d6cdac8ec4 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -81,6 +81,7 @@ const { listSpriteAssets } = await import('./paths.js');
const { lockReference } = await import('./reference.js');
const {
getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
+ reopenWalkDirection,
} = await import('./walk.js');
const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');
@@ -195,6 +196,21 @@ describe('startWalkGeneration', () => {
expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 2 seconds');
});
+ it('stores the chosen frame count + fps on the run and passes them to the packer', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ executeTuiRun.mockImplementationOnce(async ({ workspacePath }) => {
+ await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');
+ });
+ const { runId } = await startWalkGeneration(id, { direction: 'east', frameCount: 14, fps: 8 });
+ await vi.waitFor(async () => {
+ const { runs } = await getWalkState(id);
+ expect(runs[0].status).toBe('candidate');
+ });
+ const { runs } = await getWalkState(id);
+ expect(runs[0]).toMatchObject({ id: runId, frameCount: 14, fps: 8 });
+ expect(runWalkPostprocess.mock.calls[0][0]).toMatchObject({ frameCount: 14, fps: 8 });
+ });
+
it('packages the candidate once grok writes the clip (full render→attach)', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
// Simulate grok saving the MP4 to the directed path, then finishing.
@@ -329,6 +345,19 @@ describe('rerunWalkPostprocess', () => {
await expect(rerunWalkPostprocess(id, { runId: approvedRun }))
.rejects.toMatchObject({ code: 'RUN_APPROVED' });
});
+
+ it('reprocesses the on-disk clip at a new frame count + fps (no regeneration)', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await startWalkGeneration(id, { direction: 'east', frameCount: 8, fps: 12 });
+ await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'landed');
+ runWalkPostprocess.mockClear();
+ const run = await rerunWalkPostprocess(id, { runId, frameCount: 16, fps: 6 });
+ // The override reaches the deterministic packer — same clip, new count/fps.
+ expect(runWalkPostprocess).toHaveBeenCalledOnce();
+ expect(runWalkPostprocess.mock.calls[0][0]).toMatchObject({ frameCount: 16, fps: 6 });
+ // …and is stamped back onto the run record so the card reflects the choice.
+ expect(run).toMatchObject({ frameCount: 16, fps: 6 });
+ });
});
describe('approveWalkDirection', () => {
@@ -451,6 +480,58 @@ describe('unlockWalkSet', () => {
});
});
+describe('reopenWalkDirection', () => {
+ async function finalizedCharacter() {
+ const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
+ for (const direction of SPRITE_DIRECTIONS) {
+ const { runId } = await makeCandidateRun(id, direction);
+ await approveWalkDirection(id, { direction, runId });
+ }
+ return id;
+ }
+
+ it('reopens ONE approved direction, un-finalizes the set, and keeps the others', async () => {
+ const id = await finalizedCharacter();
+ expect((await records.getRecord(id)).status).toBe('walk-complete');
+
+ const state = await reopenWalkDirection(id, { direction: 'east' });
+ // The frozen set is gone (a set is final only when all 8 are approved)…
+ expect(state.walkSet).toBeNull();
+ expect((await records.getRecord(id)).status).toBe('reference-complete');
+ // …east is editable again while every other direction stays approved.
+ expect(state.selection.directions.east).toBeUndefined();
+ expect(state.selection.directions.north.status).toBe('approved');
+ expect(state.selection.status).toBe('in-progress');
+
+ // Re-approving just east re-freezes the set with a single click.
+ const { runId } = await makeCandidateRun(id, 'east');
+ const reapproved = await approveWalkDirection(id, { direction: 'east', runId });
+ expect(reapproved.walkSet).not.toBeNull();
+ expect((await records.getRecord(id)).status).toBe('walk-complete');
+ });
+
+ it('409s a direction that is not approved', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await expect(reopenWalkDirection(id, { direction: 'east' }))
+ .rejects.toMatchObject({ code: 'DIRECTION_NOT_APPROVED' });
+ });
+
+ it('refuses to reopen a legacy source-pipeline import', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
+ await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-set-v1.json`), JSON.stringify({
+ schemaVersion: 1,
+ kind: 'finalized-eight-direction-walk-set',
+ characterId: id,
+ status: 'final',
+ selectionPath: `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`,
+ directions: { east: { status: 'approved' } },
+ }));
+ await expect(reopenWalkDirection(id, { direction: 'east' }))
+ .rejects.toMatchObject({ code: 'LEGACY_IMPORTED_WALK_SET' });
+ });
+});
+
describe('listSpriteAssets run-intermediate exclusion', () => {
it('omits raw extraction frames but keeps packaged frames and the review sheet', async () => {
const id = await characterWithLockedAnchors(newId(), []);
diff --git a/server/services/sprites/walkPostprocess.e2e.test.js b/server/services/sprites/walkPostprocess.e2e.test.js
index 017b171941..fbf0f16962 100644
--- a/server/services/sprites/walkPostprocess.e2e.test.js
+++ b/server/services/sprites/walkPostprocess.e2e.test.js
@@ -23,7 +23,10 @@ import { join } from 'path';
import sharp from 'sharp';
import { mkdir, readFile } from 'fs/promises';
import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
-import { runWalkPostprocess, WALK_PHASES, WALK_CELL_SIZE } from './walkPostprocess.js';
+import {
+ runWalkPostprocess, walkPhaseLabels, WALK_PHASES, WALK_CELL_SIZE,
+ WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,
+} from './walkPostprocess.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-walk-e2e-'));
afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
@@ -76,7 +79,7 @@ async function writeAnchor(dest) {
await sharp(buf, { raw: { width: w, height: h, channels: 3 } }).png().toFile(dest);
}
-async function runOnce(label, videoAbs, anchorAbs) {
+async function runOnce(label, videoAbs, anchorAbs, opts = {}) {
const runRel = 'grok/walk-east-fixture0';
const runAbs = join(TEST_ROOT, label, runRel);
await mkdir(join(runAbs, 'generated'), { recursive: true });
@@ -91,42 +94,45 @@ async function runOnce(label, videoAbs, anchorAbs) {
anchorRel: 'reference/fixture-hero-walk-east-v1.png',
anchorAbs,
videoAbs,
+ ...opts,
}),
};
}
describe.skipIf(!ffmpegBin)('runWalkPostprocess e2e (synthetic keyed walk video)', () => {
- it('packages the canonical strip geometry deterministically', async () => {
+ it('packages the default variable-frame strip geometry deterministically', async () => {
const videoAbs = join(TEST_ROOT, 'walk.mp4');
const anchorAbs = join(TEST_ROOT, 'anchor.png');
await synthesizeVideo(videoAbs);
await writeAnchor(anchorAbs);
+ const n = WALK_DEFAULT_FRAME_COUNT;
const { runAbs, result } = await runOnce('run-a', videoAbs, anchorAbs);
const { manifest } = result;
- // Geometry contract.
+ // Geometry contract — the new default packs N frames at the default fps,
+ // with positional frame-NN labels (named gait phases are the 8-frame case).
expect(manifest.kind).toBe('deterministically-packaged-grok-walk-video');
- expect(manifest.frameCount).toBe(8);
- expect(manifest.frameRate).toBe(12);
- expect(manifest.frames.map((f) => f.phase)).toEqual(WALK_PHASES);
+ expect(manifest.frameCount).toBe(n);
+ expect(manifest.frameRate).toBe(WALK_DEFAULT_FPS);
+ expect(manifest.frames.map((f) => f.phase)).toEqual(walkPhaseLabels(n));
expect(manifest.alignment.cellSize).toBe(WALK_CELL_SIZE);
expect(manifest.alignment.targetPivot).toEqual([192, 352]);
- expect(manifest.alignment.translations).toHaveLength(8);
+ expect(manifest.alignment.translations).toHaveLength(n);
expect(manifest.chromaKey).toBe(KEY);
- expect(manifest.validation.keyDominantPixels).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
- expect(manifest.cycleSelection.windowLength).toBeGreaterThanOrEqual(8);
+ expect(manifest.validation.keyDominantPixels).toEqual(Array(n).fill(0));
+ expect(manifest.cycleSelection.windowLength).toBeGreaterThanOrEqual(n);
const stripMeta = await sharp(join(runAbs, 'generated', 'fixture-hero-walk-east-strip.png')).metadata();
- expect(stripMeta.width).toBe(WALK_CELL_SIZE * 8);
+ expect(stripMeta.width).toBe(WALK_CELL_SIZE * n);
expect(stripMeta.height).toBe(WALK_CELL_SIZE);
const sheetMeta = await sharp(join(runAbs, 'generated', 'review', 'fixture-hero-walk-east-contrast-review.png')).metadata();
- expect(sheetMeta.width).toBe(1024);
+ expect(sheetMeta.width).toBe(128 * n);
expect(sheetMeta.height).toBe(384);
const preview = JSON.parse(await readFile(join(runAbs, 'generated', 'review-preview.json'), 'utf8'));
expect(preview).toEqual({
stripPath: 'grok/walk-east-fixture0/generated/fixture-hero-walk-east-strip.png',
- frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
+ frameCount: n, fps: WALK_DEFAULT_FPS, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
});
// Determinism: same video, second run → byte-identical manifest & strip.
@@ -134,6 +140,23 @@ describe.skipIf(!ffmpegBin)('runWalkPostprocess e2e (synthetic keyed walk video)
expect(second.result.manifest).toEqual(manifest);
expect(second.result.manifest.stripSha256).toBe(manifest.stripSha256);
}, 120000);
+
+ it('honors an explicit frame count + fps (back-compat 8-frame named-phase packing)', async () => {
+ const videoAbs = join(TEST_ROOT, 'walk8.mp4');
+ const anchorAbs = join(TEST_ROOT, 'anchor8.png');
+ await synthesizeVideo(videoAbs);
+ await writeAnchor(anchorAbs);
+
+ const { runAbs, result } = await runOnce('run-8', videoAbs, anchorAbs, { frameCount: 8, fps: 12 });
+ const { manifest } = result;
+ expect(manifest.frameCount).toBe(8);
+ expect(manifest.frameRate).toBe(12);
+ // The 8-frame packing keeps the named 2-beat gait phases for back-compat.
+ expect(manifest.frames.map((f) => f.phase)).toEqual(WALK_PHASES);
+ expect(manifest.alignment.translations).toHaveLength(8);
+ const stripMeta = await sharp(join(runAbs, 'generated', 'fixture-hero-walk-east-strip.png')).metadata();
+ expect(stripMeta.width).toBe(WALK_CELL_SIZE * 8);
+ }, 120000);
});
const parityRun = process.env.SPRITE_WALK_PARITY_RUN;
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index 7945dc13b4..bba9335baf 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -29,8 +29,26 @@ import { keyChannelSplit, keyness, keyShareFn, hexToRgb } from './chromaKey.js';
// Source pipeline constants (animation_postprocess.py) — values are part of
// the cross-install artifact contract (imported manifests carry them).
+// WALK_FPS is the source-EXTRACTION sampling rate (how densely we pull frames
+// out of grok's clip); it is ALSO the legacy playback-fps fallback for older
+// manifests that omit `frameRate`. Playback fps (how fast the packed cycle
+// animates) is now a separate, per-run value carried in the manifest.
export const WALK_FPS = 12;
+// Legacy default / fallback frame count for manifests (or clients) that omit it.
export const WALK_FRAME_COUNT = 8;
+// Configurable authoring range (#sprite-walk-variable-frames): native
+// generation now packs a fuller, slower cycle by default so a walk reads as a
+// walk, not a run. The packer resamples the detected gait window DOWN to
+// `frameCount` distinct source frames (it never upsamples — N is bounded by
+// the source frames available in one cycle), and playback fps is metadata
+// carried into the manifest/atlas. So a slower/smoother walk needs no
+// regeneration — only a reprocess of the on-disk clip at a new count/fps.
+export const WALK_DEFAULT_FRAME_COUNT = 12;
+export const WALK_DEFAULT_FPS = 10;
+export const WALK_MIN_FRAME_COUNT = 6;
+export const WALK_MAX_FRAME_COUNT = 16;
+export const WALK_MIN_FPS = 4;
+export const WALK_MAX_FPS = 24;
export const MAX_SOURCE_SECONDS = 8;
export const MAX_SOURCE_DIMENSION = 512;
export const WALK_CELL_SIZE = 384;
@@ -40,6 +58,33 @@ export const WALK_PHASES = [
'right-contact', 'right-down', 'right-passing', 'right-up',
];
+/**
+ * Column/phase labels for an N-frame packed strip. The historical 8-frame
+ * packing keeps its named 2-beat gait phases (so existing atlases and imported
+ * manifests round-trip byte-identically); any other length uses positional
+ * `frame-NN` labels. Postprocess (which writes them) and atlas.js (which
+ * asserts them) MUST derive labels through this one helper so they can never
+ * disagree on a column's identity.
+ */
+export function walkPhaseLabels(n) {
+ if (n === WALK_PHASES.length) return [...WALK_PHASES];
+ return Array.from({ length: n }, (_, i) => `frame-${String(i).padStart(2, '0')}`);
+}
+
+/** Clamp a requested frame count into the supported authoring range. */
+export function clampFrameCount(n) {
+ const v = Math.round(Number(n));
+ if (!Number.isFinite(v)) return WALK_DEFAULT_FRAME_COUNT;
+ return Math.max(WALK_MIN_FRAME_COUNT, Math.min(WALK_MAX_FRAME_COUNT, v));
+}
+
+/** Clamp a requested playback fps into the supported authoring range. */
+export function clampFps(n) {
+ const v = Math.round(Number(n));
+ if (!Number.isFinite(v)) return WALK_DEFAULT_FPS;
+ return Math.max(WALK_MIN_FPS, Math.min(WALK_MAX_FPS, v));
+}
+
// Border-key acceptance thresholds. The key channels must dominate the dark
// channels by ≥ KEY_DOMINANCE_MIN, and each channel group must be balanced
// within KEY_GROUP_SPREAD_MAX. The spread tolerance was 80 (tuned to the source
@@ -320,14 +365,17 @@ export function imageDistance(a, b) {
* resample it onto the 8 gait phases. `signatures` is one entry per recovered
* source frame.
*/
-export function selectCycleIndices(signatures) {
+export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {
const n = signatures.length;
- if (n < WALK_FRAME_COUNT + 1) {
- throw new Error(`Need at least ${WALK_FRAME_COUNT + 1} extracted frames, got ${n}`);
+ if (n < frameCount + 1) {
+ throw new Error(`Need at least ${frameCount + 1} extracted frames, got ${n}`);
}
let best = null; // [score, start, cycleLength, seam, motion]
- const maxLen = Math.min(18, n - 1);
- for (let cycleLength = WALK_FRAME_COUNT; cycleLength <= maxLen; cycleLength++) {
+ // The window must be at least `frameCount` long to yield that many distinct
+ // source frames (we never upsample). Widen the ceiling with frameCount so a
+ // larger requested count can still find a long-enough gait window.
+ const maxLen = Math.min(Math.max(18, frameCount + 6), n - 1);
+ for (let cycleLength = frameCount; cycleLength <= maxLen; cycleLength++) {
for (let start = 0; start < n - cycleLength; start++) {
const seam = imageDistance(signatures[start], signatures[start + cycleLength]);
const motionSamples = [];
@@ -343,9 +391,9 @@ export function selectCycleIndices(signatures) {
}
if (!best) throw new Error('No detectable moving walk cycle in the source video');
const [, start, cycleLength, seam, motion] = best;
- const indices = Array.from({ length: WALK_FRAME_COUNT }, (_, i) => start + pyRound((i * cycleLength) / WALK_FRAME_COUNT));
- if (new Set(indices).size !== WALK_FRAME_COUNT) {
- throw new Error('Cycle window too short to resample 8 distinct phases');
+ const indices = Array.from({ length: frameCount }, (_, i) => start + pyRound((i * cycleLength) / frameCount));
+ if (new Set(indices).size !== frameCount) {
+ throw new Error(`Cycle window too short to resample ${frameCount} distinct phases`);
}
return {
indices,
@@ -515,9 +563,9 @@ function keyDominantPixels(frame, split) {
* Validate the packed candidate: 8 distinct frames, tolerable loop seam,
* no visible key residue.
*/
-export async function validateFrames(frames, split) {
- if (frames.length !== WALK_FRAME_COUNT) {
- throw new Error(`Expected ${WALK_FRAME_COUNT} frames, got ${frames.length}`);
+export async function validateFrames(frames, split, frameCount = WALK_FRAME_COUNT) {
+ if (frames.length !== frameCount) {
+ throw new Error(`Expected ${frameCount} frames, got ${frames.length}`);
}
const hashes = frames.map((f) => sha256Buffer(f.data));
if (new Set(hashes).size !== frames.length) throw new Error('Duplicate frames in the packed cycle');
@@ -635,7 +683,11 @@ export async function prepareWalkAnchorChromaInput(anchorAbs, destAbs, chromaKey
*/
export async function runWalkPostprocess({
recordId, direction, chromaKey, runAbs, runRel, anchorRel, anchorAbs, videoAbs,
+ frameCount = WALK_DEFAULT_FRAME_COUNT, fps = WALK_DEFAULT_FPS,
}) {
+ const targetFrames = clampFrameCount(frameCount);
+ const playbackFps = clampFps(fps);
+ const phaseLabels = walkPhaseLabels(targetFrames);
const split = keyChannelSplit(chromaKey);
const generatedAbs = join(runAbs, 'generated');
const generatedRel = `${runRel}/generated`;
@@ -655,11 +707,11 @@ export async function runWalkPostprocess({
decoded.push({ frame, measured, usable: isUsableMeasuredKey(measured, split) });
}
const span = longestUsableSpan(decoded.map((d) => d.usable));
- if (span.length < WALK_FRAME_COUNT + 1) {
+ if (span.length < targetFrames + 1) {
const usableTotal = decoded.filter((d) => d.usable).length;
throw new Error(usableTotal === 0
? `No frame has a usable ${chromaKey} matte (measured e.g. [${decoded[0]?.measured?.join(',')}] across ${decoded.length} frames)`
- : `Only ${span.length} contiguous frames have a usable ${chromaKey} matte (need ${WALK_FRAME_COUNT + 1}); the ${chromaKey} background is unstable across the clip`);
+ : `Only ${span.length} contiguous frames have a usable ${chromaKey} matte (need ${targetFrames + 1}); the ${chromaKey} background is unstable across the clip`);
}
// span.start offsets every downstream lookup back into the raw source-%04d
// numbering, so the manifest's sourceFrameIndex/sourcePath stay correct.
@@ -669,18 +721,18 @@ export async function runWalkPostprocess({
const recovered = usable.map((d) => recoverAlphaFrame(d.frame, d.measured, split));
const signatures = await Promise.all(recovered.map(signatureOf));
- const { indices, cycle } = selectCycleIndices(signatures);
+ const { indices, cycle } = selectCycleIndices(signatures, targetFrames);
const selected = indices.map((i) => recovered[i]);
const { frames: aligned, alignment } = await alignFrames(selected);
const despilled = aligned.map((f) => despillKeyFrame(f, split));
- const validation = await validateFrames(despilled, split);
+ const validation = await validateFrames(despilled, split, targetFrames);
const framesDir = join(generatedAbs, 'frames');
await ensureDir(framesDir);
const frameRecords = [];
for (let i = 0; i < despilled.length; i++) {
- const phase = WALK_PHASES[i];
+ const phase = phaseLabels[i];
const name = `${String(i).padStart(2, '0')}-${phase}.png`;
frameRecords.push({
outputIndex: i,
@@ -718,8 +770,8 @@ export async function runWalkPostprocess({
sourceVideoSha256: await sha256File(videoAbs),
postprocessorPath: 'server/services/sprites/walkPostprocess.js',
manifestPath: `${generatedRel}/${manifestName}`,
- frameRate: WALK_FPS,
- frameCount: WALK_FRAME_COUNT,
+ frameRate: playbackFps,
+ frameCount: targetFrames,
cycleSelection: cycle,
chromaCleanup: {
method: 'measured-key-unmixing-plus-key-vector-despill',
@@ -739,8 +791,8 @@ export async function runWalkPostprocess({
const stripPreview = {
stripPath: `${generatedRel}/${stripName}`,
- frameCount: WALK_FRAME_COUNT,
- fps: WALK_FPS,
+ frameCount: targetFrames,
+ fps: playbackFps,
cellWidth: WALK_CELL_SIZE,
cellHeight: WALK_CELL_SIZE,
row: 0,