Spaces:
Configuration error
Configuration error
File size: 8,568 Bytes
03b405b | 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 | const { spawn } = require("child_process");
const fs = require("fs");
const fsp = require("fs/promises");
const path = require("path");
const { config } = require("../config/env");
const { paths } = require("../config/paths");
const { run } = require("../utils/shell");
const { getPreset } = require("./presets");
const { detectCapabilities, getEncoderName } = require("./gpu.detector");
const { createLogger } = require("../monitoring/logger.js");
const logger = createLogger("FfmpegCompressor");
/**
* Builds the pipeline argument array for FFmpeg
*/
function buildPipelineArgs({
inputPath,
outputPath,
preset,
hwType,
encoder,
info,
width,
height,
fps,
keepAudio,
audioBitrate
}) {
const args = ["-hide_banner", "-y"];
// Hardware acceleration inputs
if (hwType === "nvidia") {
args.push("-hwaccel", "cuda", "-hwaccel_output_format", "cuda");
} else if (hwType === "qsv") {
args.push("-hwaccel", "qsv");
}
args.push("-i", inputPath);
// Video codec
args.push("-c:v", encoder);
// Video filtering (scaling & fps limits)
const vf = [];
const targetWidth = width || preset.maxWidth;
if (targetWidth && info.video && info.video.width > targetWidth) {
vf.push(`scale='min(${targetWidth},iw)':-2:flags=lanczos`);
} else {
// Ensure even dimensions
vf.push("scale='trunc(iw/2)*2':'trunc(ih/2)*2'");
}
const targetFps = fps || preset.fps;
if (targetFps && info.video && info.video.fps > targetFps) {
vf.push(`fps=${targetFps}`);
}
if (vf.length > 0) {
args.push("-vf", vf.join(","));
}
// Quality settings based on encoder type
const isHw = ["nvidia", "qsv", "amd"].includes(hwType);
if (isHw) {
args.push("-rc", "vbr", "-cq", String(preset.cq), "-b:v", "0");
} else {
args.push("-preset", preset.x264Preset || "medium", "-crf", String(preset.crf));
if (preset.tune) {
args.push("-tune", preset.tune);
}
}
// Keyframe intervals and profile settings
args.push("-g", "48", "-keyint_min", "24", "-sc_threshold", "40", "-pix_fmt", "yuv420p");
// Audio track settings
if (keepAudio && info.hasAudio) {
args.push("-c:a", "aac", "-b:a", audioBitrate || preset.audio || "96k", "-ac", "2");
} else {
args.push("-an");
}
// Meta stripping & web stream optimizing
args.push("-movflags", "+faststart", "-map_metadata", "-1", "-map_chapters", "-1");
// Outputs
args.push("-progress", "pipe:2", "-nostats");
args.push(outputPath);
return args;
}
/**
* Main spawn child process based compressor with real-time stderr progress parsing
*/
function compressVideo({
inputPath,
outputPath,
presetId = "balanced",
codec = "h264",
width = null,
height = null,
keepAudio = true,
audioBitrate = null,
fps = null,
onProgress = null,
info = {}
}) {
let ffmpegProcess = null;
let killedByUser = false;
const promise = (async () => {
logger.info(`Starting video compression: ${inputPath} -> ${outputPath}`);
await fsp.mkdir(path.dirname(outputPath), { recursive: true });
const totalDuration = info.duration || 0;
if (totalDuration <= 0) {
throw new Error("Invalid stream or duration. Cannot process video.");
}
// 1. Detect hardware GPU acceleration capabilities
const caps = await detectCapabilities();
const hwType = config.video.enableGpu ? caps.preferredHw : "cpu";
const preferredCodec = config.video.enableH265 ? "h265" : config.video.enableAv1 ? "av1" : codec;
const encoder = getEncoderName(hwType, preferredCodec);
// 2. Fetch the preset configuration
const preset = getPreset(presetId);
// 3. Build arguments list
const ffmpegArgs = buildPipelineArgs({
inputPath,
outputPath,
preset,
hwType,
encoder,
info,
width,
height,
fps,
keepAudio,
audioBitrate
});
const startTime = Date.now();
return new Promise((resolve, reject) => {
// 4. Spawn process
ffmpegProcess = spawn(config.video.ffmpegPath || "ffmpeg", ffmpegArgs);
logger.info(`Spawned FFmpeg process PID: ${ffmpegProcess.pid}`);
ffmpegProcess.stderr.setEncoding("utf8");
// Progress matching regular expressions
const timeRegex = /time=(\d{2}):(\d{2}):(\d{2})\.(\d{2})/;
const fpsRegex = /fps=\s*(\d+(\.\d+)?)/;
const speedRegex = /speed=\s*(\d+(\.\d+)?|\.\d+)x/;
const sizeRegex = /size=\s*(\d+)([a-zA-Z]+)/;
ffmpegProcess.stderr.on("data", (data) => {
const line = data.toString();
const timeMatch = line.match(timeRegex);
if (timeMatch && totalDuration > 0) {
const hours = parseInt(timeMatch[1], 10);
const minutes = parseInt(timeMatch[2], 10);
const seconds = parseInt(timeMatch[3], 10);
const centiseconds = parseInt(timeMatch[4], 10);
const elapsedSeconds = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
let percentage = (elapsedSeconds / totalDuration) * 100;
percentage = Math.min(100, Math.max(0, parseFloat(percentage.toFixed(2))));
const fpsMatch = line.match(fpsRegex);
const currentFps = fpsMatch ? parseFloat(fpsMatch[1]) : 0;
const speedMatch = line.match(speedRegex);
const speed = speedMatch ? parseFloat(speedMatch[1]) : 1.0;
const sizeMatch = line.match(sizeRegex);
const sizeStr = sizeMatch ? `${sizeMatch[1]}${sizeMatch[2]}` : "N/A";
let etaSeconds = 0;
const remainingSeconds = totalDuration - elapsedSeconds;
if (speed > 0.01) {
etaSeconds = remainingSeconds / speed;
} else {
const wallElapsedMs = Date.now() - startTime;
if (percentage > 0.5) {
const estimatedTotalWallMs = (wallElapsedMs / percentage) * 100;
etaSeconds = (estimatedTotalWallMs - wallElapsedMs) / 1000;
}
}
etaSeconds = Math.max(0, Math.round(etaSeconds));
if (onProgress && typeof onProgress === "function") {
onProgress({
percentage: Math.round(percentage),
currentFps,
speed,
sizeStr,
etaSeconds,
elapsedSeconds: Math.round(elapsedSeconds)
});
}
}
});
ffmpegProcess.on("error", (err) => {
logger.error(`FFmpeg process spawn error: ${err.message}`);
reject(err);
});
ffmpegProcess.on("close", async (code) => {
logger.info(`FFmpeg process closed with exit code ${code}`);
if (killedByUser) {
logger.warn("Video compression process was manually terminated.");
return reject(new Error("Compression cancelled by user."));
}
if (code !== 0) {
return reject(new Error(`FFmpeg failed with exit status code: ${code}`));
}
try {
const outStats = await fsp.stat(outputPath);
const finalSize = outStats.size;
const originalSize = info.format ? info.format.size : 0;
const ratio = originalSize > 0 ? (finalSize / originalSize) * 100 : 0;
const compressionRatio = parseFloat(ratio.toFixed(2));
resolve({
outputPath,
originalSize,
compressedSize: finalSize,
compressionRatio,
duration: totalDuration,
elapsedTimeMs: Date.now() - startTime
});
} catch (err) {
logger.error(`Failed to verify final compressed output file: ${err.message}`);
reject(new Error(`Failed to locate target compressed video: ${err.message}`));
}
});
});
})();
const kill = () => {
if (ffmpegProcess) {
logger.warn(`Manually sending SIGKILL to FFmpeg process ${ffmpegProcess.pid}...`);
killedByUser = true;
ffmpegProcess.kill("SIGKILL");
return true;
}
return false;
};
return { promise, kill };
}
/**
* Extract / copy video segment without re-encoding (very fast)
*/
async function copySegment(inputPath, outputPath, start, duration) {
await fsp.mkdir(path.dirname(outputPath), { recursive: true });
await run(config.video.ffmpegPath || "ffmpeg", [
"-hide_banner", "-y",
"-ss", String(start),
"-i", inputPath,
"-t", String(duration),
"-c", "copy",
"-avoid_negative_ts", "make_zero",
outputPath
], { timeoutMs: Math.max(10 * 60_000, duration * 4000) });
return outputPath;
}
module.exports = { compressVideo, copySegment };
|