VR-MEDIA / src /lib /detection /ffprobe.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
12.8 kB
// 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";
}