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.
This commit is contained in:
dahyeon committed 2025-11-15 00:00:59 -08:00
1 parent b7307a7a41
commit c8be78de15
9 files changed
+139 -122

No files matched your search

+99 -90
View File
@@ -1,108 +1,117 @@
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';
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 type ImageFormat = 'avif' | 'webp' | 'jpeg';
export type ImageFormat = "avif" | "webp" | "jpeg";
export interface ConversionOptions {
width: number;
format: ImageFormat;
width: number;
format: ImageFormat;
}
export interface ConversionResult {
buffer: Buffer;
format: ImageFormat;
width: number;
buffer: Buffer;
format: ImageFormat;
width: number;
}
export class FFmpegConverter {
private getTempFilePath(ext: string): string {
const randomName = randomBytes(16).toString('hex');
return join(tmpdir(), `img-${randomName}.${ext}`);
private getTempFilePath(ext: string): string {
const randomName = randomBytes(16).toString("hex");
return join(tmpdir(), `img-${randomName}.${ext}`);
}
async convert(
inputBuffer: Buffer,
options: ConversionOptions
): Promise<ConversionResult> {
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 {}
}
}
async convert(
inputBuffer: Buffer,
options: ConversionOptions
): Promise<ConversionResult> {
const inputPath = this.getTempFilePath('tmp');
const outputPath = this.getTempFilePath(options.format);
private executeFFmpeg(args: string[]): Promise<void> {
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);
try {
// Write input buffer to temp file
await writeFile(inputPath, inputBuffer);
let stderr = "";
// Build FFmpeg command
const args = [
'-i', inputPath,
'-vf', `scale=${options.width}:-1`,
];
ffmpeg.stderr.on("data", (data: Buffer) => {
stderr += data.toString();
});
// 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 {}
ffmpeg.on("close", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`FFmpeg exited with code ${code}\n${stderr}`));
}
}
});
private executeFFmpeg(args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
const ffmpeg = spawn('ffmpeg', args);
ffmpeg.on("error", (err) => {
reject(new Error(`Failed to start FFmpeg: ${err.message}`));
});
});
}
let stderr = '';
ffmpeg.stderr.on('data', (data: Buffer) => {
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: ImageFormat): string {
const contentTypes: Record<ImageFormat, string> = {
avif: 'image/avif',
webp: 'image/webp',
jpeg: 'image/jpeg',
};
return contentTypes[format];
}
getContentType(format: ImageFormat): string {
const contentTypes: Record<ImageFormat, string> = {
avif: "image/avif",
webp: "image/webp",
jpeg: "image/jpeg",
};
return contentTypes[format];
}
}