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

fal lip sync: drop the voice clip after a published take, refuse out-of-window clips before paying

[._.]/ Adam Eivya616fcb12de0
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
index 129339209b..921bdc1db9 100644
--- a/server/services/videoGen/fal.js
+++ b/server/services/videoGen/fal.js
@@ -25,7 +25,7 @@
import { randomUUID } from 'crypto';
import { readFile, writeFile, unlink } from 'fs/promises';
-import { join } from 'path';
+import { join, relative, resolve, isAbsolute } from 'path';
import { ensureDir, PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { withAbortTimeout } from '../../lib/abortTimeout.js';
@@ -257,10 +257,18 @@ export async function generateVideo({
};
}
+const isStagedUpload = (path) => {
+ const rel = relative(PATHS.uploads, resolve(path));
+ return !!rel && !rel.startsWith('..') && !isAbsolute(rel);
+};
+
// The staged voice clip keeps its upload's extension (a performance slice is always WAV).
export function audioMimeType(path) {
const ext = String(path).toLowerCase().split('.').pop();
- return { mp3: 'audio/mpeg', m4a: 'audio/mp4', mp4: 'audio/mp4', aac: 'audio/aac', ogg: 'audio/ogg', flac: 'audio/flac' }[ext] || 'audio/wav';
+ return {
+ mp3: 'audio/mpeg', m4a: 'audio/mp4', mp4: 'audio/mp4', aac: 'audio/aac', ogg: 'audio/ogg', opus: 'audio/ogg',
+ flac: 'audio/flac', webm: 'audio/webm', aif: 'audio/aiff', aiff: 'audio/aiff',
+ }[ext] || 'audio/wav';
}
async function runFalVideo(job, jobId, {
@@ -332,6 +340,9 @@ async function runFalVideo(job, jobId, {
activeRequests.delete(jobId);
activeJobs.delete(jobId);
await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, ...measured }, actualSeed: null, mutateHistory: mutateVideoHistory, publication });
+ // The staged voice clip is spent once the take is published. The queue removes it on failure,
+ // cancel and restart; on success it is ours to drop (only a clip staged under data/uploads).
+ if (audioFilePath && isStagedUpload(audioFilePath)) await unlink(audioFilePath).catch(() => {});
closeJobAfterDelay(jobs, jobId);
} catch (err) {
// Best-effort: an unanticipated throw (e.g. from fetchFalResult or the
diff --git a/server/services/videoGen/fal.test.js b/server/services/videoGen/fal.test.js
index 4f2c869561..96d27d4ebc 100644
--- a/server/services/videoGen/fal.test.js
+++ b/server/services/videoGen/fal.test.js
@@ -12,6 +12,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
actual.PATHS.videos = FAKE_VIDEOS_DIR;
actual.PATHS.data = FAKE_DATA_DIR;
actual.PATHS.videoThumbnails = join(TEST_ROOT, 'thumbnails');
+ actual.PATHS.uploads = join(TEST_ROOT, 'uploads');
return {
...actual,
ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
@@ -684,5 +685,36 @@ describe('audioMimeType', () => {
expect(audioMimeType('/u/video-audio-1.M4A')).toBe('audio/mp4');
expect(audioMimeType('/u/slice.wav')).toBe('audio/wav');
expect(audioMimeType('/u/clip')).toBe('audio/wav');
+ expect(audioMimeType('/u/rec.webm')).toBe('audio/webm');
+ expect(audioMimeType('/u/rec.opus')).toBe('audio/ogg');
+ expect(audioMimeType('/u/take.aiff')).toBe('audio/aiff');
+ });
+});
+
+describe('standalone lip-sync take', () => {
+ it('drops the staged voice clip once the take is published, but never a file outside data/uploads', async () => {
+ const { PATHS } = await import('../../lib/fileUtils.js');
+ await mkdir(PATHS.uploads, { recursive: true });
+ const staged = join(PATHS.uploads, 'video-audio-test.wav');
+ const outside = join(TEST_ROOT, 'keep-me.wav');
+ const frame = join(TEST_ROOT, 'face.png');
+ await writeFile(staged, 'voice'); await writeFile(outside, 'voice'); await writeFile(frame, 'png');
+ const run = async (audioFilePath, requestId) => {
+ const statusUrl = `https://queue.fal.run/fal-ai/y/requests/${requestId}/status`;
+ const responseUrl = `https://queue.fal.run/fal-ai/y/requests/${requestId}`;
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ if (url === 'https://queue.fal.run/fal-ai/y') return jsonResponse({ request_id: requestId, status_url: statusUrl, response_url: responseUrl });
+ if (url === statusUrl) return jsonResponse({ status: 'COMPLETED' });
+ if (url === responseUrl) return jsonResponse({ video: { url: `https://cdn.fal.ai/${requestId}.mp4` } });
+ if (url === `https://cdn.fal.ai/${requestId}.mp4`) return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('mp4')).buffer };
+ throw new Error(`unexpected fetch: ${url}`);
+ }));
+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/y', sourceImagePath: frame, audioFilePath });
+ expect(await waitForTerminal(job.jobId)).toMatchObject({ type: 'completed' });
+ };
+ await run(staged, 'req-staged');
+ await expect(readFile(staged)).rejects.toMatchObject({ code: 'ENOENT' });
+ await run(outside, 'req-outside');
+ expect((await readFile(outside)).toString()).toBe('voice');
});
});
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index e508d0cfe6..da013579f1 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -748,8 +748,9 @@ async function resolvePreparedParams({
await cleanupStaged();
throw new ServerError(hosted.errorMessage, { status: 400, code: hosted.errorCode });
}
- // A standalone fal lip-sync take: stage the voice clip durably like the frame. The queue owns
- // and removes it with the job (uploadedTempPaths), as it does for the local a2v lane.
+ // A standalone fal lip-sync take: stage the voice clip durably like the frame. The queue removes
+ // it if the job fails, is cancelled or is lost to a restart (uploadedTempPaths); the fal worker
+ // removes it once the take is published.
let hostedAudioPath = null;
if (falLipSync && uploads.audioFile) {
if (!sourceImagePath) {
@@ -757,6 +758,20 @@ async function resolvePreparedParams({
throw new ServerError('A fal.ai lip-sync render needs a reference frame (sourceImage or sourceImageFile).', { status: 400, code: 'VALIDATION_ERROR' });
}
hostedAudioPath = await stageUploadDurable(uploads.audioFile, 'audio');
+ // A paid route: refuse a clip fal would reject (unreadable, or outside the model's window)
+ // before anything is submitted.
+ const window = getFalVideoModel(body.falModelId)?.audioInput || {};
+ const clipSec = await probeVideoDuration(hostedAudioPath).catch(() => null);
+ if (clipSec == null) {
+ await cleanupStaged();
+ throw new ServerError('Could not read the voice clip\'s duration. Upload a valid WAV, MP3, M4A, AAC, FLAC, OGG or WebM file.',
+ { status: 400, code: 'VIDEO_GEN_AUDIO_DURATION_UNREADABLE' });
+ }
+ if ((window.minSec != null && clipSec < window.minSec) || (window.maxSec != null && clipSec > window.maxSec)) {
+ await cleanupStaged();
+ throw new ServerError(`The voice clip is ${clipSec.toFixed(2)} s; this lip-sync model takes ${window.minSec}–${window.maxSec} s (pad a short line with silence).`,
+ { status: 400, code: 'VIDEO_GEN_AUDIO_LENGTH' });
+ }
}
return {
backend,
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index 4d75cfc616..48369237c6 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -737,6 +737,22 @@ describe('prepareVideoGenParams — standalone fal lip sync', () => {
)).rejects.toMatchObject({ status: 400, code: 'VIDEO_GEN_AUDIO_MODE_MISMATCH' });
});
+ it('refuses a voice clip fal would reject before anything is submitted', async () => {
+ getSettings.mockResolvedValueOnce(falSettings());
+ probeVideoDuration.mockResolvedValueOnce(3.2);
+ await expect(prepare(
+ { backend: 'fal', falModelId: LIPSYNC, mode: 'image', sourceImageFile: 'face.png' },
+ { audioFile: upload('audioFile', 'line.wav') },
+ )).rejects.toMatchObject({ status: 400, code: 'VIDEO_GEN_AUDIO_LENGTH' });
+ getSettings.mockResolvedValueOnce(falSettings());
+ probeVideoDuration.mockResolvedValueOnce(null);
+ await expect(prepare(
+ { backend: 'fal', falModelId: LIPSYNC, mode: 'image', sourceImageFile: 'face.png' },
+ { audioFile: upload('audioFile', 'line.wav') },
+ )).rejects.toMatchObject({ status: 400, code: 'VIDEO_GEN_AUDIO_DURATION_UNREADABLE' });
+ expect(unlinkMock).toHaveBeenCalled(); // the staged clip is rolled back
+ });
+
it('needs a reference frame for the lip sync', async () => {
getSettings.mockResolvedValueOnce(falSettings());
await expect(prepare({ backend: 'fal', falModelId: LIPSYNC, mode: 'text' }, { audioFile: upload('audioFile', 'line.wav') }))