Spaces:
Sleeping
Sleeping
File size: 16,539 Bytes
0f0d9a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | import { existsSync } from 'fs';
import { mkdir, readFile, rm, writeFile } from 'fs/promises';
import path from 'path';
import { spawn } from 'child_process';
type ClipFile = {
file?: File;
filePath?: string;
ext: string;
step?: number;
};
export type ServerRenderInput = {
videoClips: ClipFile[];
audioClips: ClipFile[];
};
export type ServerRenderResult = {
bytes: Buffer;
durationSeconds: number;
filename: string;
};
const WORK_DIR = path.join(process.cwd(), '.local-review-data', 'server-renders');
const VIDEO_WIDTH = 1080;
const VIDEO_HEIGHT = 1920;
const VIDEO_FPS = 24;
const MIN_VIDEO_CLIP_SECONDS = 5;
const MAX_VIDEO_CLIP_SECONDS = 7;
const MAX_AUDIO_CLIP_SECONDS = 12;
const FINAL_VIDEO_MAX_SECONDS = 17;
const STEP_VIDEO_MAX_SECONDS: Record<number, number> = {
1: 6,
2: 7,
3: 4,
};
type PreparedClip = {
path: string;
step: number;
duration: number;
hasAudio: boolean;
};
type VideoSegment = {
source: PreparedClip;
duration: number;
};
function resolveMediaCommand(command: 'ffmpeg' | 'ffprobe') {
const explicit =
command === 'ffmpeg' ? process.env.GRABBY_FFMPEG_PATH : process.env.GRABBY_FFPROBE_PATH;
if (explicit && existsSync(explicit)) return explicit;
const tempRoot = process.env.TEMP || process.env.TMP;
if (process.platform === 'win32' && tempRoot) {
const tempTools = path.join(tempRoot, 'grabby-media-tools', 'node_modules');
const candidate =
command === 'ffmpeg'
? path.join(tempTools, 'ffmpeg-static', 'ffmpeg.exe')
: path.join(tempTools, 'ffprobe-static', 'bin', 'win32', 'x64', 'ffprobe.exe');
if (existsSync(candidate)) return candidate;
}
return command;
}
function safeExt(ext: string) {
const normalized = ext.toLowerCase().replace(/[^a-z0-9]/g, '');
if (normalized === 'mp4' || normalized === 'mov' || normalized === 'webm') return normalized;
if (normalized === 'm4a' || normalized === 'mp3' || normalized === 'wav') return normalized;
return 'webm';
}
async function runCommand(command: string, args: string[], label: string) {
return await new Promise<void>((resolve, reject) => {
const child = spawn(resolveMediaCommand(command === 'ffprobe' ? 'ffprobe' : 'ffmpeg'), args, {
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe'],
});
const logs: string[] = [];
const collect = (chunk: Buffer) => {
const text = chunk.toString('utf8');
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (trimmed) logs.push(trimmed);
}
if (logs.length > 80) logs.splice(0, logs.length - 80);
};
child.stdout.on('data', collect);
child.stderr.on('data', collect);
child.on('error', (err) => {
reject(new Error(`${label} failed to start: ${err.message}`));
});
child.on('close', (code) => {
if (code === 0) {
resolve();
return;
}
reject(
new Error(
logs.length
? `${label} failed with exit code ${code}: ${logs.slice(-10).join(' | ')}`
: `${label} failed with exit code ${code}`,
),
);
});
});
}
async function writeClip(file: File, filePath: string) {
const bytes = Buffer.from(await file.arrayBuffer());
if (bytes.length <= 0) throw new Error('One of the clips was empty.');
await writeFile(filePath, bytes);
}
async function prepareClipSource(clip: ClipFile, fallbackPath: string) {
if (clip.filePath) return clip.filePath;
if (!clip.file) throw new Error('Clip source is missing.');
await writeClip(clip.file, fallbackPath);
return fallbackPath;
}
async function probeDuration(filePath: string) {
try {
const args = [
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=noprint_wrappers=1:nokey=1',
filePath,
];
const output = await new Promise<string>((resolve, reject) => {
const child = spawn(resolveMediaCommand('ffprobe'), args, {
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString('utf8');
});
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) resolve(stdout.trim());
else reject(new Error(`ffprobe exited with ${code}`));
});
});
const duration = Number(output);
return Number.isFinite(duration) ? Math.max(0, duration) : 0;
} catch {
return 0;
}
}
async function probeHasAudio(filePath: string) {
try {
const args = [
'-v',
'error',
'-select_streams',
'a',
'-show_entries',
'stream=index',
'-of',
'csv=p=0',
filePath,
];
const output = await new Promise<string>((resolve, reject) => {
const child = spawn(resolveMediaCommand('ffprobe'), args, {
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString('utf8');
});
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) resolve(stdout.trim());
else reject(new Error(`ffprobe exited with ${code}`));
});
});
return output.length > 0;
} catch {
return false;
}
}
function formatDuration(seconds: number) {
return seconds.toFixed(3).replace(/\.?0+$/, '');
}
function clamp(value: number, min: number, max: number) {
return Math.max(min, Math.min(max, value));
}
function inferClipStep(clip: ClipFile, index: number, fallbackStartStep: number) {
return Number.isInteger(clip.step) && clip.step! > 0 ? clip.step! : fallbackStartStep + index;
}
function clipByStep(clips: PreparedClip[], step: number) {
return clips.find((clip) => clip.step === step) ?? null;
}
function maxSecondsForStep(step: number) {
return STEP_VIDEO_MAX_SECONDS[step] ?? MAX_VIDEO_CLIP_SECONDS;
}
function addSegment(segments: VideoSegment[], source: PreparedClip | null, duration: number) {
if (!source || duration < 0.25) return;
segments.push({
source,
duration,
});
}
function buildLinearSegments(videoClips: PreparedClip[]) {
const segments: VideoSegment[] = [];
let remaining = FINAL_VIDEO_MAX_SECONDS;
for (const source of videoClips) {
if (remaining <= 0.25) break;
const stepMax = maxSecondsForStep(source.step);
const fallbackDuration = Math.min(MIN_VIDEO_CLIP_SECONDS, stepMax);
const sourceDuration =
source.duration > 0 ? Math.min(source.duration, stepMax) : fallbackDuration;
const duration = Math.min(sourceDuration, remaining);
addSegment(segments, source, duration);
remaining -= duration;
}
return segments;
}
function buildVoiceAwareSegments({
videoClips,
audioClips,
renderTargetSeconds,
}: {
videoClips: PreparedClip[];
audioClips: PreparedClip[];
renderTargetSeconds: number;
}) {
if (videoClips.length === 0) return [];
const closeShot = clipByStep(videoClips, 1) ?? videoClips[0]!;
const wideShot = clipByStep(videoClips, 2) ?? videoClips[1] ?? closeShot;
const actionShot = clipByStep(videoClips, 3) ?? videoClips[2] ?? wideShot;
const reactionShot =
videoClips.find((clip) => clip.step >= 6) ??
(videoClips.length > 3 ? videoClips[videoClips.length - 1]! : null);
const orderAudio = clipByStep(audioClips, 4) ?? audioClips[0] ?? null;
const likedAudio =
clipByStep(audioClips, 5) ??
audioClips.find((clip) => clip !== orderAudio) ??
null;
const targetSeconds = Math.max(1, renderTargetSeconds);
const reactionSeconds =
reactionShot && targetSeconds >= 10
? Math.min(3, reactionShot.duration > 0 ? reactionShot.duration : 3)
: 0;
const narrativeSeconds = Math.max(1, targetSeconds - reactionSeconds);
const fallbackOrderSeconds = likedAudio ? 7 : narrativeSeconds * 0.42;
const rawOrderSeconds = orderAudio?.duration && orderAudio.duration > 0
? orderAudio.duration
: fallbackOrderSeconds;
const minOrderSeconds = Math.min(2, narrativeSeconds);
const maxOrderSeconds = likedAudio ? Math.max(minOrderSeconds, narrativeSeconds - 2) : narrativeSeconds;
const orderSeconds = clamp(rawOrderSeconds, minOrderSeconds, maxOrderSeconds);
const likedSeconds = Math.max(0, narrativeSeconds - orderSeconds);
const segments: VideoSegment[] = [];
if (closeShot === wideShot || orderSeconds < 2.5) {
addSegment(segments, closeShot, orderSeconds);
} else {
const closeSeconds = clamp(orderSeconds * 0.58, 1.25, orderSeconds - 0.75);
addSegment(segments, closeShot, closeSeconds);
addSegment(segments, wideShot, orderSeconds - closeSeconds);
}
addSegment(segments, actionShot, likedSeconds);
addSegment(segments, reactionShot, reactionSeconds);
return segments.length > 0 ? segments : buildLinearSegments(videoClips);
}
export async function renderClipsOnServer(input: ServerRenderInput): Promise<ServerRenderResult> {
if (input.videoClips.length === 0) {
throw new Error('No video clips were uploaded.');
}
const runId = Math.random().toString(36).slice(2, 10);
const runDir = path.join(WORK_DIR, runId);
await mkdir(runDir, { recursive: true });
const videoPaths: Array<{ path: string; step: number }> = [];
const audioPaths: Array<{ path: string; step: number }> = [];
const outputPath = path.join(runDir, `matcha-server-${runId}.mp4`);
try {
for (let i = 0; i < input.videoClips.length; i++) {
const clip = input.videoClips[i]!;
const filePath = path.join(runDir, `video-${i}.${safeExt(clip.ext)}`);
videoPaths.push({
path: await prepareClipSource(clip, filePath),
step: inferClipStep(clip, i, 1),
});
}
for (let i = 0; i < input.audioClips.length; i++) {
const clip = input.audioClips[i]!;
const filePath = path.join(runDir, `audio-${i}.${safeExt(clip.ext)}`);
audioPaths.push({
path: await prepareClipSource(clip, filePath),
step: inferClipStep(clip, i, 4),
});
}
const [videoDurations, audioDurations, videoAudioFlags] = await Promise.all([
Promise.all(videoPaths.map((clip) => probeDuration(clip.path))),
Promise.all(audioPaths.map((clip) => probeDuration(clip.path))),
Promise.all(videoPaths.map((clip) => probeHasAudio(clip.path))),
]);
const preparedVideoClips = videoPaths.map((clip, index) => ({
path: clip.path,
step: clip.step,
duration: videoDurations[index] ?? 0,
hasAudio: videoAudioFlags[index] ?? false,
}));
const preparedAudioClips = audioPaths.map((clip, index) => ({
path: clip.path,
step: clip.step,
duration: audioDurations[index] ?? 0,
hasAudio: true,
}));
const hasVoiceover = audioPaths.length > 0;
const audioDurationSeconds = audioDurations.reduce((total, duration) => total + duration, 0);
const voiceoverTargetSeconds =
Math.max(
1,
Math.min(
FINAL_VIDEO_MAX_SECONDS,
audioDurationSeconds > 0
? audioDurationSeconds
: preparedAudioClips.length >= 2
? FINAL_VIDEO_MAX_SECONDS
: MAX_AUDIO_CLIP_SECONDS,
),
);
const videoSegments = hasVoiceover
? buildVoiceAwareSegments({
videoClips: preparedVideoClips,
audioClips: preparedAudioClips,
renderTargetSeconds: voiceoverTargetSeconds,
})
: buildLinearSegments(preparedVideoClips);
const renderTargetSeconds = hasVoiceover
? voiceoverTargetSeconds
: Math.max(
1,
Math.min(
FINAL_VIDEO_MAX_SECONDS,
videoSegments.reduce((total, segment) => total + segment.duration, 0),
),
);
if (videoSegments.length === 0) {
throw new Error('No usable video segments were uploaded.');
}
const inputArgs = [
...videoSegments.flatMap((segment) => [
'-stream_loop',
'-1',
'-t',
formatDuration(segment.duration),
'-i',
segment.source.path,
]),
...audioPaths.flatMap((clip) => [
'-t',
String(MAX_AUDIO_CLIP_SECONDS),
'-i',
clip.path,
]),
];
const videoFilters = videoSegments
.map((segment, i) => {
return (
`[${i}:v]trim=duration=${formatDuration(segment.duration)},setpts=PTS-STARTPTS,` +
`scale=${VIDEO_WIDTH}:${VIDEO_HEIGHT}:force_original_aspect_ratio=decrease,` +
`pad=${VIDEO_WIDTH}:${VIDEO_HEIGHT}:(ow-iw)/2:(oh-ih)/2,` +
`setsar=1,fps=${VIDEO_FPS},format=yuv420p[v${i}]`
);
})
.join(';');
const videoInputs = videoSegments.map((_, i) => `[v${i}]`).join('');
const audioOffset = videoSegments.length;
let filterComplex: string;
if (hasVoiceover) {
const videoConcat = `${videoInputs}concat=n=${videoSegments.length}:v=1:a=0[vcat]`;
const videoFinalize = `[vcat]trim=duration=${formatDuration(
renderTargetSeconds,
)},setpts=PTS-STARTPTS[v]`;
const audioFilters = audioPaths
.map((_, i) => {
return (
`[${audioOffset + i}:a]atrim=duration=${MAX_AUDIO_CLIP_SECONDS},` +
`aresample=48000,aformat=sample_rates=48000:channel_layouts=mono,` +
`asetpts=PTS-STARTPTS[a${i}]`
);
})
.join(';');
const audioInputs = audioPaths.map((_, i) => `[a${i}]`).join('');
const audioConcat = `${audioInputs}concat=n=${audioPaths.length}:v=0:a=1[acat]`;
const audioFinalize =
`[acat]atrim=duration=${formatDuration(renderTargetSeconds)},` +
`apad=whole_dur=${formatDuration(renderTargetSeconds)},asetpts=PTS-STARTPTS[a]`;
filterComplex = [
videoFilters,
videoConcat,
videoFinalize,
audioFilters,
audioConcat,
audioFinalize,
]
.filter(Boolean)
.join(';');
} else {
const embeddedAudioFilters = videoSegments
.map((segment, i) => {
if (segment.source.hasAudio) {
return (
`[${i}:a]atrim=duration=${formatDuration(segment.duration)},` +
`aresample=48000,aformat=sample_rates=48000:channel_layouts=mono,` +
`asetpts=PTS-STARTPTS[a${i}]`
);
}
return (
`anullsrc=r=48000:cl=mono,atrim=duration=${formatDuration(segment.duration)},` +
`aformat=sample_rates=48000:channel_layouts=mono,asetpts=PTS-STARTPTS[a${i}]`
);
})
.join(';');
const avInputs = videoSegments.map((_, i) => `[v${i}][a${i}]`).join('');
const avConcat = `${avInputs}concat=n=${videoSegments.length}:v=1:a=1[vcat][acat]`;
const videoFinalize = `[vcat]trim=duration=${formatDuration(
renderTargetSeconds,
)},setpts=PTS-STARTPTS[v]`;
const audioFinalize =
`[acat]atrim=duration=${formatDuration(renderTargetSeconds)},` +
`apad=whole_dur=${formatDuration(renderTargetSeconds)},asetpts=PTS-STARTPTS[a]`;
filterComplex = [
videoFilters,
embeddedAudioFilters,
avConcat,
videoFinalize,
audioFinalize,
]
.filter(Boolean)
.join(';');
}
// V3 records picture and speech together. Older voiceover renders still use
// separate audio clips, but both paths now emit one shared audio/video length.
const outputArgs = ['-map', '[v]', '-map', '[a]'];
await runCommand(
'ffmpeg',
[
'-y',
...inputArgs,
'-filter_complex',
filterComplex,
...outputArgs,
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-tune',
'zerolatency',
'-crf',
'30',
'-r',
String(VIDEO_FPS),
'-c:a',
'aac',
'-b:a',
'96k',
'-t',
formatDuration(renderTargetSeconds),
'-movflags',
'+faststart',
'-avoid_negative_ts',
'make_zero',
outputPath,
],
'Server clip render',
);
const bytes = await readFile(outputPath);
if (bytes.length <= 0) throw new Error('Server render produced an empty video.');
return {
bytes,
durationSeconds: Math.round(await probeDuration(outputPath)),
filename: `matcha-server-${runId}.mp4`,
};
} finally {
await rm(runDir, { recursive: true, force: true }).catch(() => undefined);
}
}
|