video-optimizer-bot / src /ffmpeg /quality.analyzer.js
Hugging Face Deployer
Deploy bot to Hugging Face Spaces
03b405b
Raw History Blame Contribute Delete
3.9 kB
const { exec } = require('child_process');
const { promisify } = require('util');
const { createLogger } = require('../monitoring/logger.js');
const { probe } = require('./ffprobe.js');
const execAsync = promisify(exec);
const logger = createLogger('QualityAnalyzer');
/**
* Compares a compressed (distorted) video against its original reference video
* to compute structural and fidelity quality scores.
*/
async function analyzeQuality(originalPath, compressedPath, options = {}) {
logger.info(`Starting quality analysis for compressed file: ${compressedPath}`);
try {
const origMeta = await probe(originalPath);
const compMeta = await probe(compressedPath);
if (!origMeta.hasVideo || !compMeta.hasVideo) {
throw new Error('Both original and compressed files must contain active video streams.');
}
const origW = origMeta.video.width;
const origH = origMeta.video.height;
const compW = compMeta.video.width;
const compH = compMeta.video.height;
logger.debug(`Original resolution: ${origW}x${origH}, Compressed resolution: ${compW}x${compH}`);
let filterComplex = '';
if (origW !== compW || origH !== compH) {
logger.warn(`Resolution mismatch detected. Dynamic scaling original video from ${origW}x${origH} to ${compW}x${compH} for metrics calculations.`);
filterComplex = `[1:v]scale=${compW}:${compH}[scaled_orig];[0:v][scaled_orig]ssim;[0:v][scaled_orig]psnr`;
} else {
filterComplex = '[0:v][1:v]ssim;[0:v][1:v]psnr';
}
if (options.vmafModelPath) {
logger.info(`Chaining VMAF calculation with model: ${options.vmafModelPath}`);
if (origW !== compW || origH !== compH) {
filterComplex += `;[1:v]scale=${compW}:${compH}[scaled_orig_vmaf];[0:v][scaled_orig_vmaf]libvmaf=model_path="${options.vmafModelPath}"`;
} else {
filterComplex += ';[0:v][1:v]libvmaf=model_path="' + options.vmafModelPath + '"';
}
}
const qualityCmd = [
'ffmpeg',
'-y',
'-i', `"${compressedPath}"`,
'-i', `"${originalPath}"`,
'-filter_complex', `"${filterComplex}"`,
'-f', 'null',
'-'
].join(' ');
logger.debug(`Executing quality metric command: ${qualityCmd}`);
let stdout, stderr;
try {
const result = await execAsync(qualityCmd);
stdout = result.stdout;
stderr = result.stderr;
} catch (execErr) {
if (execErr.stderr && (execErr.stderr.includes('SSIM') || execErr.stderr.includes('PSNR'))) {
stderr = execErr.stderr;
} else {
throw execErr;
}
}
const ssimMatch = stderr.match(/SSIM.*All:([0-9.]+)/i);
const psnrMatch = stderr.match(/PSNR.*average:([0-9.]+|inf)/i);
const vmafMatch = stderr.match(/VMAF score:\s*([0-9.]+)/i);
const ssim = ssimMatch ? parseFloat(ssimMatch[1]) : null;
let psnr = null;
if (psnrMatch) {
if (psnrMatch[1].toLowerCase() === 'inf') {
psnr = Infinity;
} else {
psnr = parseFloat(psnrMatch[1]);
}
}
const vmaf = vmafMatch ? parseFloat(vmafMatch[1]) : null;
let scoreRating = 'unknown';
if (ssim !== null) {
if (ssim >= 0.98) {
scoreRating = 'excellent';
} else if (ssim >= 0.95) {
scoreRating = 'good';
} else if (ssim >= 0.88) {
scoreRating = 'fair';
} else {
scoreRating = 'poor';
}
}
const metrics = {
ssim,
psnr,
vmaf,
scoreRating,
resolutionAligned: origW !== compW || origH !== compH,
rawStderr: stderr
};
logger.info(`Quality analysis completed. Rating: ${scoreRating.toUpperCase()} (SSIM=${ssim}, PSNR=${psnr === Infinity ? 'Infinity' : psnr}dB)`);
return metrics;
} catch (error) {
logger.error(`Quality analysis failed: ${error.message}`, { error });
throw error;
}
}
module.exports = { analyzeQuality };