File size: 3,904 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
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 };