Files
image-derivatives-generatio…/dist/ffmpeg.js
T
dahyeon c8be78de15 Updates FFmpeg handling for platform-aware execution
Switches to platform- and architecture-specific FFmpeg binaries and dynamically resolves executable paths to improve cross-platform compatibility.

Standardizes code style to use consistent double quotes.

Corrects naming inconsistencies and ensures executables have proper permissions on startup.

Enhances maintainability and reliability for image conversion across environments.
2025-11-15 00:00:59 -08:00

86 lines
3.1 KiB
JavaScript

import { spawn } from "child_process";
import { mkdir, writeFile, readFile, unlink } from "fs/promises";
import { join } from "path";
import { tmpdir, arch, platform } from "os";
import { randomBytes } from "crypto";
import { fileURLToPath } from "url";
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) {
const currentDirectory = fileURLToPath(import.meta.url);
const platformArchPrefix = `${platform()}-${arch()}`;
const ffmpegExecutable = join(currentDirectory, "..", "..", "bin", platformArchPrefix, platform() === "win32" ? "ffmpeg.exe" : "ffmpeg");
console.log(`Executing FFmpeg: ${ffmpegExecutable} ${args.join(" ")}`);
return new Promise((resolve, reject) => {
const ffmpeg = spawn(ffmpegExecutable, 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