File size: 6,997 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
const path = require('path');
const { createLogger } = require('../monitoring/logger.js');
const { probe } = require('./ffprobe.js');

const logger = createLogger('VideoDetector');

/**
 * Automatically detects the video type (anime, camera, screen, ocr) 
 * using metadata heuristics and filename analysis.
 * 
 * @param {string} filePath - Absolute path to the video file
 * @param {Object} [preAnalyzedMeta] - Optional pre-existing analysis metadata to avoid duplicate ffprobe runs
 * @returns {Promise<{ type: string, confidence: number, reasoning: string }>}
 */
async function detectVideoType(filePath, preAnalyzedMeta = null) {
  logger.info(`Detecting video type for: ${path.basename(filePath)}`);

  try {
    const meta = preAnalyzedMeta || await probe(filePath);
    const fileName = path.basename(filePath).toLowerCase();

    const scores = {
      anime: 0,
      camera: 0,
      screen: 0,
      ocr: 0
    };

    const details = {
      anime: [],
      camera: [],
      screen: [],
      ocr: []
    };

    const animeKeywords = [
      'anime', 'ep', 'episode', 'season', 's0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9',
      'batch', 'ova', 'movie', 'hancodez', 'judas', 'doki', 'horriblesubs', 'subs', 'subbed', 'dubbed',
      'encodes', 'dual-audio', 'manga', 'eriraw', 'raws', 'hevc-10bit'
    ];

    const screenKeywords = [
      'screen', 'screencast', 'recording', 'tutorial', 'desktop', 'zoom', 'meet', 'teams', 'webinar',
      'obs', 'bandicam', 'camtasia', 'course', 'lecture', 'classroom', 'windows', 'macbook', 'linux',
      'terminal', 'github', 'coding', 'programming'
    ];

    const ocrKeywords = [
      'ocr', 'slide', 'presentation', 'powerpoint', 'pdf', 'book', 'text', 'document', 'page', 'scan',
      'read', 'readable', 'invoice', 'receipt', 'legible', 'sheet', 'board', 'whiteboard'
    ];

    const cameraKeywords = [
      'vlog', 'camera', 'phone', 'iphone', 'android', 'gopro', 'dji', 'trip', 'travel', 'movie',
      'film', 'nature', 'party', 'wedding', 'family', 'street', 'walk', 'run', 'live', 'concert',
      'vid_', 'dscn', 'img_', 'mov_'
    ];

    animeKeywords.forEach(kw => {
      if (fileName.includes(kw)) {
        scores.anime += 15;
        details.anime.push(`Filename contains keyword: ${kw}`);
      }
    });

    screenKeywords.forEach(kw => {
      if (fileName.includes(kw)) {
        scores.screen += 15;
        details.screen.push(`Filename contains keyword: ${kw}`);
      }
    });

    ocrKeywords.forEach(kw => {
      if (fileName.includes(kw)) {
        scores.ocr += 15;
        details.ocr.push(`Filename contains keyword: ${kw}`);
      }
    });

    cameraKeywords.forEach(kw => {
      if (fileName.includes(kw)) {
        scores.camera += 15;
        details.camera.push(`Filename contains keyword: ${kw}`);
      }
    });

    if (/\[[a-z0-9\s_-]+\]/i.test(fileName)) {
      scores.anime += 20;
      details.anime.push('Filename pattern matches fan-sub/release-group brackets "[Group]"');
    }

    if (meta.hasVideo && meta.video) {
      const v = meta.video;
      const totalBitrateKbps = (meta.format?.bitrate || 0) / 1000;
      
      if (v.fps > 0 && v.fps <= 12) {
        scores.ocr += 30;
        scores.screen += 20;
        details.ocr.push(`Extremely low frame rate (${v.fps} FPS) typical of scanned pages/OCR`);
        details.screen.push(`Low frame rate (${v.fps} FPS) typical of screen logs`);
      } else if (v.fps > 12 && v.fps <= 20) {
        scores.screen += 15;
        details.screen.push(`Moderately low frame rate (${v.fps} FPS) typical of screens`);
      }

      if (v.fps === 30 || v.fps === 60 || v.fps === 29.97 || v.fps === 59.94) {
        scores.camera += 10;
        scores.anime += 5;
        details.camera.push(`Standard broadcast frame rate (${v.fps} FPS)`);
      }

      if (v.fps === 23.976 || v.fps === 24) {
        scores.anime += 25;
        scores.camera += 10;
        details.anime.push(`Cinematic animation frame rate (${v.fps} FPS)`);
      }

      if (totalBitrateKbps > 0 && v.width && v.height) {
        const pixelCount = v.width * v.height;
        const fpsCoeff = v.fps || 24;
        const bitsPerPixelFrame = (meta.format.bitrate || 0) / (pixelCount * fpsCoeff);

        logger.debug(`Bits per pixel-frame: ${bitsPerPixelFrame.toFixed(4)}`);

        if (bitsPerPixelFrame < 0.03) {
          scores.screen += 30;
          scores.ocr += 15;
          details.screen.push(`Ultra-low bitrate density (${bitsPerPixelFrame.toFixed(4)} bppf) indicates heavy static frames`);
        } else if (bitsPerPixelFrame >= 0.03 && bitsPerPixelFrame < 0.08) {
          scores.anime += 15;
          scores.screen += 10;
          details.anime.push(`Moderate bitrate density (${bitsPerPixelFrame.toFixed(4)} bppf) typical of vector art/anime`);
        } else if (bitsPerPixelFrame > 0.15) {
          scores.camera += 25;
          details.camera.push(`High bitrate density (${bitsPerPixelFrame.toFixed(4)} bppf) indicates high noise/motion complexity`);
        }
      }

      if (meta.metadata && meta.metadata.encoder) {
        const encoder = meta.metadata.encoder.toLowerCase();
        if (encoder.includes('obs') || encoder.includes('captura') || encoder.includes('sharex') || encoder.includes('camtasia')) {
          scores.screen += 40;
          details.screen.push(`Created by screen recorder software: ${encoder}`);
        }
      }

      if (v.width && v.height) {
        const ratio = v.width / v.height;
        if (ratio < 0.8 || ratio > 2.5) {
          scores.ocr += 20;
          details.ocr.push(`Non-standard portrait/ultra-wide aspect ratio (${v.aspectRatio || (v.width + 'x' + v.height)}) typical of document scans`);
        }
      }
    }

    let detectedType = 'camera';
    let maxScore = 0;
    
    for (const [type, score] of Object.entries(scores)) {
      if (score > maxScore) {
        maxScore = score;
        detectedType = type;
      }
    }

    if (maxScore < 10) {
      detectedType = 'camera';
      maxScore = 10;
      details.camera.push('Low confidence heuristic triggers default fallback.');
    }

    const totalScore = Math.max(1, scores.anime + scores.camera + scores.screen + scores.ocr);
    const confidence = Math.min(100, Math.round((maxScore / totalScore) * 100));

    const finalReasoning = details[detectedType].join('; ') || 'Default fallback to camera settings.';

    logger.info(`Detection Result: type=${detectedType.toUpperCase()} confidence=${confidence}%`, {
      scores,
      reasoning: finalReasoning
    });

    return {
      type: detectedType,
      confidence,
      reasoning: finalReasoning
    };

  } catch (error) {
    logger.error(`Error during content type detection, defaulting to camera: ${error.message}`, { error });
    return {
      type: 'camera',
      confidence: 100,
      reasoning: `Detection error encountered: ${error.message}. Defaulted to generic camera.`
    };
  }
}

module.exports = { detectVideoType };