Version One
This commit is contained in:
53
src/lib/video.ts
Normal file
53
src/lib/video.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { mkdtemp, writeFile, readFile, readdir } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { execFile as _execFile } from 'node:child_process';
|
||||
|
||||
const execFile = promisify(_execFile);
|
||||
|
||||
export async function extractThumbnailsFromVideoBytes(
|
||||
videoBytes: Uint8Array,
|
||||
maxFrames: number | null = 8,
|
||||
fps = 2,
|
||||
): Promise<Uint8Array[]> {
|
||||
const tmpBase = await mkdtemp(join(tmpdir(), 'recipe-ai-'));
|
||||
const inputPath = join(tmpBase, 'input.mp4');
|
||||
await writeFile(inputPath, videoBytes);
|
||||
|
||||
const pattern = join(tmpBase, 'frame-%02d.jpg');
|
||||
try {
|
||||
// Extract frames at specified fps; if maxFrames <= 0 or null, extract full video
|
||||
const args = [
|
||||
'-hide_banner',
|
||||
'-loglevel', 'error',
|
||||
'-y',
|
||||
'-i', inputPath,
|
||||
'-vf', `fps=${fps}`,
|
||||
'-q:v', '2',
|
||||
];
|
||||
if (maxFrames && maxFrames > 0) {
|
||||
args.push('-vframes', String(maxFrames));
|
||||
}
|
||||
args.push(pattern);
|
||||
await execFile('ffmpeg', args, { timeout: 120_000 });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const files = (await readdir(tmpBase))
|
||||
.filter((f) => /^frame-\d+\.jpg$/i.test(f))
|
||||
.sort();
|
||||
const results: Uint8Array[] = [];
|
||||
for (const f of files) {
|
||||
const buf = await readFile(join(tmpBase, f));
|
||||
results.push(new Uint8Array(buf));
|
||||
}
|
||||
return results;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user