84 lines
2.7 KiB
JavaScript
84 lines
2.7 KiB
JavaScript
import { spawn } from 'child_process';
|
|
import { mkdir, writeFile, readFile, unlink } from 'fs/promises';
|
|
import { join } from 'path';
|
|
import { tmpdir } from 'os';
|
|
import { randomBytes } from 'crypto';
|
|
export class FFmpegConverter {
|
|
getTempFilePath(ext) {
|
|
const randomName = randomBytes(16).toString('hex');
|
|
return join(tmpdir(), `img-${randomName}.${ext}`);
|
|
}
|
|
async convert(inputBuffer, options) {
|
|
const inputPath = this.getTempFilePath('tmp');
|
|
const outputPath = this.getTempFilePath(options.format);
|
|
try {
|
|
// Write input buffer to temp file
|
|
await writeFile(inputPath, inputBuffer);
|
|
// Build FFmpeg command
|
|
const args = [
|
|
'-i', inputPath,
|
|
'-vf', `scale=${options.width}:-1`,
|
|
];
|
|
// Format-specific options
|
|
if (options.format === 'avif') {
|
|
args.push('-c:v', 'libaom-av1', '-crf', '30');
|
|
}
|
|
else if (options.format === 'webp') {
|
|
args.push('-c:v', 'libwebp', '-quality', '80');
|
|
}
|
|
else if (options.format === 'jpeg') {
|
|
args.push('-q:v', '5');
|
|
}
|
|
args.push('-y', outputPath);
|
|
// Execute FFmpeg
|
|
await this.executeFFmpeg(args);
|
|
// Read output file
|
|
const outputBuffer = await readFile(outputPath);
|
|
return {
|
|
buffer: outputBuffer,
|
|
format: options.format,
|
|
width: options.width,
|
|
};
|
|
}
|
|
finally {
|
|
// Clean up temp files
|
|
try {
|
|
await unlink(inputPath);
|
|
}
|
|
catch { }
|
|
try {
|
|
await unlink(outputPath);
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
executeFFmpeg(args) {
|
|
return new Promise((resolve, reject) => {
|
|
const ffmpeg = spawn('ffmpeg', args);
|
|
let stderr = '';
|
|
ffmpeg.stderr.on('data', (data) => {
|
|
stderr += data.toString();
|
|
});
|
|
ffmpeg.on('close', (code) => {
|
|
if (code === 0) {
|
|
resolve();
|
|
}
|
|
else {
|
|
reject(new Error(`FFmpeg exited with code ${code}\n${stderr}`));
|
|
}
|
|
});
|
|
ffmpeg.on('error', (err) => {
|
|
reject(new Error(`Failed to start FFmpeg: ${err.message}`));
|
|
});
|
|
});
|
|
}
|
|
getContentType(format) {
|
|
const contentTypes = {
|
|
avif: 'image/avif',
|
|
webp: 'image/webp',
|
|
jpeg: 'image/jpeg',
|
|
};
|
|
return contentTypes[format];
|
|
}
|
|
}
|
|
//# sourceMappingURL=ffmpeg.js.map
|