Spaces:
Configuration error
Configuration error
Download src/ffmpeg/ffmpeg.js from UUUZCX/video-optimizer-bot: direct link, hf CLI and curl.
- Browser
- Download file 8.57 kB
-
https://huggingface.co/spaces/UUUZCX/video-optimizer-bot/resolve/main/src/ffmpeg/ffmpeg.js
- Command line
-
hf download hf://spaces/UUUZCX/video-optimizer-bot/src/ffmpeg/ffmpeg.js
-
curl -L -o ffmpeg.js https://huggingface.co/spaces/UUUZCX/video-optimizer-bot/resolve/main/src/ffmpeg/ffmpeg.js
8.57 kB
| 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 }; | |