File size: 12,775 Bytes
5c0175e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Layers 1-5: ffprobe wrapper — container, spatial, stream, alpha, mask-track detection.
//
// ffprobe is installed as a system package in the Dockerfile. For dev / mock mode
// where ffprobe is absent or the URL is unreachable, we synthesize plausible results
// based on filename intelligence so the rest of the pipeline stays demoable.

import { spawn, execSync } from "node:child_process";
import { ALPHA_PIXEL_FORMATS, LayerResult, MASK_FILENAMES } from "../types";

export interface FfprobeStream {
  index: number;
  codec_type: "video" | "audio" | "subtitle" | "data" | "attachment";
  codec_name?: string;
  pix_fmt?: string;
  width?: number;
  height?: number;
  r_frame_rate?: string;
  bit_rate?: string;
  duration?: string;
  tags?: Record<string, string>;
  side_data_list?: { side_data_type: string; [k: string]: unknown }[];
}

export interface FfprobeOutput {
  streams: FfprobeStream[];
  format: {
    filename: string;
    duration?: string;
    size?: string;
    bit_rate?: string;
    tags?: Record<string, string>;
  };
}

export interface ContainerAnalysis {
  ffprobeAvailable: boolean;
  title: string | null;
  author: string | null;
  codec: string | null;
  duration: number | null;
  creationDate: string | null;
  projectionType: string | null;
  stereoType: string | null;
  width: number | null;
  height: number | null;
  fps: number | null;
  bitrate: string | null;
  size: string | null;
  // Stream-level (Layer 3)
  videoStreamCount: number;
  audioStreamCount: number;
  subtitleStreamCount: number;
  dataStreamCount: number;
  extraVideoTracks: string[];
  // Alpha (Layer 4)
  hasAlpha: boolean;
  alphaPixelFormats: string[];
  // Mask track (Layer 5)
  hasMaskTrack: boolean;
  maskTrackNames: string[];
  // Raw ffprobe JSON
  raw: FfprobeOutput | null;
}

/** Returns true if ffprobe is installed on this system. */
export function isFfprobeAvailable(): boolean {
  try {
    execSync("which ffprobe", { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}

/**

 * Run ffprobe against a URL (supports HTTP Range). Returns parsed JSON or null on failure.

 * Honors a 12s timeout per call so a hung remote stream doesn't block the scan queue.

 */
export function runFfprobe(url: string): Promise<FfprobeOutput | null> {
  return new Promise((resolve) => {
    if (!isFfprobeAvailable()) {
      resolve(null);
      return;
    }
    const args = [
      "-v", "error",
      "-print_format", "json",
      "-show_format",
      "-show_streams",
      "-show_entries", "stream=index,codec_type,codec_name,pix_fmt,width,height,r_frame_rate,bit_rate,duration,tags,side_data_list",
      url,
    ];
    const proc = spawn("ffprobe", args, { timeout: 12000 });
    let stdout = "";
    let stderr = "";
    proc.stdout.on("data", (d) => (stdout += d.toString()));
    proc.stderr.on("data", (d) => (stderr += d.toString()));
    proc.on("error", () => resolve(null));
    proc.on("close", (code) => {
      if (code !== 0 || !stdout) {
        resolve(null);
        return;
      }
      try {
        resolve(JSON.parse(stdout) as FfprobeOutput);
      } catch {
        resolve(null);
      }
    });
  });
}

/**

 * Layers 1-5 combined: parse an ffprobe output into a ContainerAnalysis.

 * If ffprobeOutput is null (ffprobe missing / URL unreachable), returns a

 * best-effort empty analysis — the filename & folder layers will fill in the gaps.

 */
export function analyzeContainer(

  ffprobeOutput: FfprobeOutput | null,

  filename: string,

  folderPath: string

): { container: LayerResult; spatial: LayerResult; stream: LayerResult; alpha: LayerResult; mask: LayerResult } {
  const analysis: ContainerAnalysis = {
    ffprobeAvailable: !!ffprobeOutput,
    title: null,
    author: null,
    codec: null,
    duration: null,
    creationDate: null,
    projectionType: null,
    stereoType: null,
    width: null,
    height: null,
    fps: null,
    bitrate: null,
    size: null,
    videoStreamCount: 0,
    audioStreamCount: 0,
    subtitleStreamCount: 0,
    dataStreamCount: 0,
    extraVideoTracks: [],
    hasAlpha: false,
    alphaPixelFormats: [],
    hasMaskTrack: false,
    maskTrackNames: [],
    raw: ffprobeOutput,
  };

  if (ffprobeOutput) {
    const fmt = ffprobeOutput.format ?? {};
    const tags = fmt.tags ?? {};
    analysis.title = tags.title ?? null;
    analysis.author = tags.artist ?? tags.author ?? tags.comment ?? null;
    analysis.creationDate = tags.creation_time ?? null;
    analysis.duration = fmt.duration ? parseFloat(fmt.duration) : null;
    analysis.bitrate = fmt.bit_rate ?? null;
    analysis.size = fmt.size ?? null;

    // Spatial metadata — sometimes embedded as a single tag like "VR180" or "SBS".
    const projectionTag = (tags["projection"] ?? tags["projection-type"] ?? "").toLowerCase();
    const stereoTag = (tags["stereo"] ?? tags["stereo-mode"] ?? tags["stereomode"] ?? "").toLowerCase();
    if (projectionTag) analysis.projectionType = projectionTag;
    if (stereoTag) analysis.stereoType = stereoTag;

    // Streams
    const streams = ffprobeOutput.streams ?? [];
    const videoStreams: FfprobeStream[] = [];
    for (const s of streams) {
      if (s.codec_type === "video") {
        videoStreams.push(s);
        analysis.videoStreamCount++;
      } else if (s.codec_type === "audio") {
        analysis.audioStreamCount++;
      } else if (s.codec_type === "subtitle") {
        analysis.subtitleStreamCount++;
      } else if (s.codec_type === "data") {
        analysis.dataStreamCount++;
      }
    }

    // Use the first video stream as the primary.
    const primaryVideo = videoStreams[0];
    if (primaryVideo) {
      analysis.codec = primaryVideo.codec_name ?? null;
      analysis.width = primaryVideo.width ?? null;
      analysis.height = primaryVideo.height ?? null;
      if (primaryVideo.r_frame_rate) {
        const [n, d] = primaryVideo.r_frame_rate.split("/").map(Number);
        if (d && !isNaN(n)) analysis.fps = Math.round((n / d) * 100) / 100;
      }
      if (!analysis.bitrate && primaryVideo.bit_rate) analysis.bitrate = primaryVideo.bit_rate;

      // Alpha detection (Layer 4)
      if (primaryVideo.pix_fmt && ALPHA_PIXEL_FORMATS.includes(primaryVideo.pix_fmt)) {
        analysis.hasAlpha = true;
        analysis.alphaPixelFormats.push(primaryVideo.pix_fmt);
      }
      // Some streams also carry side_data indicating alpha (e.g. RPZA + alpha).
      const sideData = primaryVideo.side_data_list ?? [];
      for (const sd of sideData) {
        if (typeof sd.side_data_type === "string" && /alpha|transparen/i.test(sd.side_data_type)) {
          analysis.hasAlpha = true;
        }
      }
    }

    // Extra video tracks (Layer 3) — could be alpha/mask planes.
    if (videoStreams.length > 1) {
      for (let i = 1; i < videoStreams.length; i++) {
        const v = videoStreams[i];
        const tagTitle = v.tags?.title ?? v.tags?.handler_name ?? `track_${v.index}`;
        analysis.extraVideoTracks.push(tagTitle);
        // Mask track detection (Layer 5) — title matches mask/alpha/matte/transparency
        const lowerTitle = tagTitle.toLowerCase();
        if (MASK_FILENAMES.some((m) => lowerTitle.includes(m))) {
          analysis.hasMaskTrack = true;
          analysis.maskTrackNames.push(tagTitle);
        }
        // Alpha pixel format on any video track also counts.
        if (v.pix_fmt && ALPHA_PIXEL_FORMATS.includes(v.pix_fmt)) {
          analysis.hasAlpha = true;
          if (!analysis.alphaPixelFormats.includes(v.pix_fmt)) {
            analysis.alphaPixelFormats.push(v.pix_fmt);
          }
        }
      }
    }
  }

  // ---- Layer 1: Container Metadata ----
  const containerConfidence = analysis.ffprobeAvailable
    ? (analysis.title || analysis.duration || analysis.codec ? 0.9 : 0.5)
    : 0.0;

  const container: LayerResult = {
    layer: 1,
    name: "Container Metadata",
    confidence: containerConfidence,
    source: "ffprobe",
    data: {
      title: analysis.title,
      author: analysis.author,
      codec: analysis.codec,
      duration: analysis.duration,
      creationDate: analysis.creationDate,
      projectionType: analysis.projectionType,
      stereoType: analysis.stereoType,
      width: analysis.width,
      height: analysis.height,
      fps: analysis.fps,
      bitrate: analysis.bitrate,
      size: analysis.size,
    },
    notes: analysis.ffprobeAvailable ? "ffprobe parsed container tags" : "ffprobe unavailable",
  };

  // ---- Layer 2: Spatial Metadata ----
  const spatialConfidence = analysis.projectionType || analysis.stereoType ? 0.85 : 0.0;
  const spatial: LayerResult = {
    layer: 2,
    name: "Spatial Metadata",
    confidence: spatialConfidence,
    source: "ffprobe-tags",
    data: {
      projectionType: analysis.projectionType,
      stereoType: analysis.stereoType,
    },
    notes: analysis.projectionType || analysis.stereoType
      ? `Embedded: ${[analysis.projectionType, analysis.stereoType].filter(Boolean).join(" / ")}`
      : "No spatial tags embedded in container",
  };

  // ---- Layer 3: Stream-Level Detection ----
  const streamConfidence = analysis.ffprobeAvailable
    ? Math.min(0.5 + (analysis.videoStreamCount * 0.1) + (analysis.extraVideoTracks.length * 0.15), 0.95)
    : 0.0;
  const stream: LayerResult = {
    layer: 3,
    name: "Stream-Level Detection",
    confidence: streamConfidence,
    source: "ffprobe-streams",
    data: {
      videoStreamCount: analysis.videoStreamCount,
      audioStreamCount: analysis.audioStreamCount,
      subtitleStreamCount: analysis.subtitleStreamCount,
      dataStreamCount: analysis.dataStreamCount,
      extraVideoTracks: analysis.extraVideoTracks,
    },
    notes: analysis.extraVideoTracks.length > 0
      ? `Extra video tracks found: ${analysis.extraVideoTracks.join(", ")}`
      : `${analysis.videoStreamCount} video / ${analysis.audioStreamCount} audio`,
  };

  // ---- Layer 4: Alpha Channel Detection ----
  const alphaConfidence = analysis.hasAlpha ? 0.95 : 0.0;
  const alpha: LayerResult = {
    layer: 4,
    name: "Alpha Channel Detection",
    confidence: alphaConfidence,
    source: "ffprobe-pixfmt",
    data: {
      hasAlpha: analysis.hasAlpha,
      alphaPixelFormats: analysis.alphaPixelFormats,
    },
    notes: analysis.hasAlpha
      ? `Alpha pixel format(s): ${analysis.alphaPixelFormats.join(", ")}`
      : "No alpha pixel format detected",
  };

  // ---- Layer 5: Mask Track Detection ----
  // Also check if filename itself contains mask/alpha/matte keywords (e.g. video_mask.mp4).
  const lowerFilename = filename.toLowerCase();
  const lowerFolder = folderPath.toLowerCase();
  const filenameMaskHint = MASK_FILENAMES.some((m) => lowerFilename.includes(m));
  const folderMaskHint = MASK_FILENAMES.some((m) => lowerFolder.includes(m));
  const maskConfidence = analysis.hasMaskTrack ? 0.9 : (filenameMaskHint || folderMaskHint ? 0.5 : 0.0);
  const mask: LayerResult = {
    layer: 5,
    name: "Mask Track Detection",
    confidence: maskConfidence,
    source: "ffprobe-streams+filename",
    data: {
      hasMaskTrack: analysis.hasMaskTrack,
      maskTrackNames: analysis.maskTrackNames,
      filenameHint: filenameMaskHint,
      folderHint: folderMaskHint,
    },
    notes: analysis.hasMaskTrack
      ? `Mask track(s): ${analysis.maskTrackNames.join(", ")}`
      : filenameMaskHint
        ? "Filename suggests companion mask file"
        : "No mask track detected",
  };

  return { container, spatial, stream, alpha, mask };
}

/**

 * Derive a resolution tier from width/height. Stereo formats halve the effective

 * per-eye resolution, so we account for that: SBS splits width, OU splits height.

 */
export function deriveResolutionTier(

  width: number | null,

  height: number | null,

  stereo: string | null

): string | null {
  if (!width || !height) return null;
  // For SBS, per-eye width is width/2; for OU, per-eye height is height/2.
  const effW = stereo === "sbs" ? width / 2 : width;
  const effH = stereo === "ou" || stereo === "top_bottom" ? height / 2 : height;
  const longEdge = Math.max(effW, effH);
  if (longEdge >= 6000) return "8K";
  if (longEdge >= 5500) return "7K";
  if (longEdge >= 4500) return "6K";
  if (longEdge >= 3800) return "5K";
  if (longEdge >= 3000) return "4K";
  if (longEdge >= 1900) return "FHD";
  if (longEdge >= 1200) return "HD";
  return "SD";
}