VR-MEDIA / src /lib /detection /classifier.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.7 kB
// Master detection pipeline + classifier.
// Runs all 11 layers in order, then applies weighted confidence scoring
// per the spec and produces the final Video classification.
//
// Pipeline:
// 1. Container (ffprobe) β€” Layer 1
// 2. Spatial (ffprobe tags) β€” Layer 2
// 3. Stream (ffprobe streams) β€” Layer 3
// 4. Alpha (ffprobe pixfmt) β€” Layer 4
// 5. Mask track (ffprobe + name) β€” Layer 5
// 6. Filename (regex) β€” Layer 6
// 7. Folder (regex) β€” Layer 7
// 8. Feed metadata (prior corrections) β€” Layer 8
// 9. Thumbnail (frame sample) β€” Layer 9
// 10. Frame (frame sample) β€” Layer 10
// 11. Depth (frame sample) β€” Layer 11
// β†’ Confidence engine β†’ Classification β†’ DEOVR validation
import { db } from "../db";
import { runFfprobe, analyzeContainer, deriveResolutionTier, type ContainerAnalysis } from "./ffprobe";
import { analyzeFilename } from "./filename";
import { analyzeFolder } from "./folder";
import { analyzeFrame } from "./frame";
import {
CONFIDENCE_WEIGHTS,
type ContentType,
type DetectionReport,
type LayerResult,
type LensType,
type Projection,
type ResolutionTier,
type Stereo,
} from "../types";
export interface DetectionInput {
videoId: string;
filename: string;
folderPath: string;
streamUrl: string;
duration: number | null;
}
export interface DetectionOutput {
report: DetectionReport;
classification: {
projection: Projection;
stereo: Stereo;
lensType: LensType;
resolutionTier: ResolutionTier | null;
contentType: ContentType;
passthrough: boolean;
};
container: ContainerAnalysis;
confidence: {
overall: number;
passthrough: number;
projection: number;
stereo: number;
};
feedValid: boolean;
feedErrors: string[];
questCompatible: boolean;
}
/**
* Run the full 11-layer detection pipeline against a single video.
* Side-effect-free: writes nothing to the DB. The caller persists the result.
*/
export async function runDetection(input: DetectionInput): Promise<DetectionOutput> {
// ---- Layer 1-5: ffprobe (best-effort; falls back gracefully) ----
const ffprobeOutput = await runFfprobe(input.streamUrl);
const { container, spatial, stream, alpha, mask } = analyzeContainer(
ffprobeOutput,
input.filename,
input.folderPath
);
// ---- Layer 6: Filename ----
const filename = analyzeFilename(input.filename);
// ---- Layer 7: Folder ----
const folder = analyzeFolder(input.folderPath);
// ---- Layer 8: Feed metadata (prior manual corrections on this video) ----
const priorCorrections = await db.correction.findMany({
where: { videoId: input.videoId },
orderBy: { createdAt: "desc" },
});
const feedMeta: LayerResult = {
layer: 8,
name: "Feed Metadata Detection",
confidence: priorCorrections.length > 0 ? 1.0 : 0.0,
source: "historical-corrections",
data: {
corrections: priorCorrections.map((c) => ({
field: c.field,
value: c.newValue,
reason: c.reason,
})),
},
notes:
priorCorrections.length > 0
? `${priorCorrections.length} prior correction(s) applied`
: "No prior corrections",
};
// ---- Layers 9, 10, 11: Frame analysis ----
const { thumbnail, frame, depth } = await analyzeFrame(
input.streamUrl,
input.duration,
input.filename
);
// ---- Classification ----
// Manual corrections override everything (Layer 8 with confidence 1.0).
// NOTE: we use `?? undefined` so that a missing correction yields `undefined`
// (not `false`), which lets the passthrough ternary below correctly fall
// through to the heuristic branch.
const manualProjection = priorCorrections.find((c) => c.field === "projection")?.newValue as Projection | undefined;
const manualStereo = priorCorrections.find((c) => c.field === "stereo")?.newValue as Stereo | undefined;
const passthroughCorrection = priorCorrections.find((c) => c.field === "passthrough");
const manualPassthrough: boolean | undefined = passthroughCorrection
? passthroughCorrection.newValue === "true"
: undefined;
// Projection β€” prefer manual > ffprobe spatial tag > filename > folder.
const projection: Projection =
manualProjection ||
(spatial.data as { projectionType: string | null }).projectionType as Projection ||
(filename.data as { projection: Projection | null }).projection ||
(folder.data as { projection: Projection | null }).projection ||
"unknown";
// Stereo β€” prefer manual > ffprobe > filename > folder. Default SBS for VR180 if unknown.
let stereo: Stereo =
manualStereo ||
(spatial.data as { stereoType: string | null }).stereoType as Stereo ||
(filename.data as { stereo: Stereo | null }).stereo ||
(folder.data as { stereo: Stereo | null }).stereo ||
"unknown";
// VR180 with no stereo info β†’ assume SBS (industry default).
if (stereo === "unknown" && (projection === "vr180" || projection === "vr360")) {
stereo = "sbs";
}
// Lens β€” prefer filename > folder > derived from projection.
const lens: LensType =
(filename.data as { lens: LensType | null }).lens ||
(folder.data as { lens: LensType | null }).lens ||
(projection === "fisheye" ? "fisheye" : projection === "dual_fisheye" ? "dual_fisheye" : "none");
// Resolution β€” prefer filename > derived from width/height.
const filenameRes = (filename.data as { resolution: ResolutionTier | null }).resolution;
const containerData = container.data as { width: number | null; height: number | null };
const resolutionTier: ResolutionTier | null =
filenameRes ||
(deriveResolutionTier(containerData.width, containerData.height, stereo) as ResolutionTier | null) ||
null;
// Passthrough β€” confidence-weighted vote across layers.
const alphaData = alpha.data as { hasAlpha: boolean; alphaPixelFormats?: string[] };
const maskData = mask.data as { hasMaskTrack: boolean; maskTrackNames?: string[] };
const frameData = frame.data as { foregroundSubjectLikelihood: number; backgroundRemovedLikelihood: number };
const filenameData = filename.data as { passthrough: boolean };
const folderData = folder.data as { passthrough: boolean };
// Raw signals (0 or 1).
const alphaSignal = alphaData.hasAlpha ? 1 : 0;
const maskSignal = maskData.hasMaskTrack ? 1 : 0;
const feedSignal = feedMeta.confidence > 0 && manualPassthrough !== undefined ? 1 : 0;
const frameSignal = frameData.backgroundRemovedLikelihood > 0.5 ? 1 : 0;
const filenameSignal = filenameData.passthrough ? 1 : 0;
const folderSignal = folderData.passthrough ? 1 : 0;
const passthroughScore =
alphaSignal * CONFIDENCE_WEIGHTS.alpha_channel +
maskSignal * CONFIDENCE_WEIGHTS.mask_track +
feedSignal * CONFIDENCE_WEIGHTS.feed_metadata +
frameSignal * CONFIDENCE_WEIGHTS.frame_analysis +
filenameSignal * CONFIDENCE_WEIGHTS.filename_intelligence +
folderSignal * CONFIDENCE_WEIGHTS.folder_intelligence;
// Determine passthrough. Per spec, the weighted score should hit 0.4 (i.e.,
// alpha or mask track must be present). But when ffprobe cannot reach the
// stream (mock mode, network error), alpha/mask are unknown β€” NOT confirmed
// absent. In that case we fall back to: keyword evidence (filename OR folder)
// is sufficient, optionally corroborated by frame analysis.
const hasStrongEvidence = !!(alphaSignal || maskSignal || feedSignal);
const hasKeywordEvidence = !!(filenameSignal || folderSignal);
const ffprobeRan = container.confidence > 0;
const passthrough: boolean =
manualPassthrough !== undefined
? manualPassthrough
: hasStrongEvidence
? true
: !!(hasKeywordEvidence && (!ffprobeRan || frameSignal));
// Content type β€” derived.
let contentType: ContentType = "standard_vr";
if (passthrough) {
const lowerName = input.filename.toLowerCase();
if (/\bar\b|augmented/.test(lowerName)) contentType = "ar";
else if (/\bmr\b|mixed/.test(lowerName)) contentType = "mixed_reality";
else contentType = "passthrough";
} else if (projection === "flat") {
contentType = "unknown";
}
// ---- Confidence engine ----
const projectionScore = Math.max(
spatial.confidence,
filename.confidence,
folder.confidence,
feedMeta.confidence
);
const stereoScore = Math.max(
spatial.confidence,
filename.confidence,
folder.confidence,
feedMeta.confidence
);
const overall = Math.round(
(passthroughScore * 0.4 +
projectionScore * 0.3 +
stereoScore * 0.3) *
100
) / 100;
// ---- DEOVR validation ----
const feedErrors: string[] = [];
if (projection === "unknown") feedErrors.push("Projection unknown β€” DEOVR will treat as flat");
if (stereo === "unknown") feedErrors.push("Stereo unknown β€” DEOVR will default to mono");
if (!input.duration || input.duration <= 0) feedErrors.push("Duration missing");
if (!input.streamUrl) feedErrors.push("Stream URL missing");
const feedValid = feedErrors.length === 0;
const questCompatible =
feedValid &&
["vr180", "vr360", "fisheye", "dual_fisheye", "flat"].includes(projection) &&
["sbs", "ou", "top_bottom", "mono"].includes(stereo);
// ---- Detection report ----
const report: DetectionReport = {
layers: [container, spatial, stream, alpha, mask, filename, folder, feedMeta, thumbnail, frame, depth],
classification: {
projection,
stereo,
lensType: lens,
resolutionTier: resolutionTier ?? "unknown",
contentType,
passthrough,
},
confidence: {
overall,
passthrough: Math.round(passthroughScore * 100) / 100,
projection: Math.round(projectionScore * 100) / 100,
stereo: Math.round(stereoScore * 100) / 100,
},
evidence: {
filenameMatch: filenameData.passthrough || (filename.data as { projection: Projection | null }).projection !== null,
folderMatch: folderData.passthrough || (folder.data as { projection: Projection | null }).projection !== null,
sbsDetected: stereo === "sbs",
fisheyeDetected: lens === "fisheye" || lens === "dual_fisheye",
alphaTrack: alphaData.hasAlpha,
maskTrack: maskData.hasMaskTrack,
feedMetadata: feedMeta.confidence > 0,
frameAnalysis: frame.confidence > 0,
depthAnalysis: depth.confidence > 0,
},
createdAt: new Date().toISOString(),
};
return {
report,
classification: {
projection,
stereo,
lensType: lens,
resolutionTier,
contentType,
passthrough,
},
container: {
...(container.data as Record<string, unknown>),
// surface back as ContainerAnalysis shape
ffprobeAvailable: (container.data as any).ffprobeAvailable ?? !!ffprobeOutput,
title: (container.data as any).title ?? null,
author: (container.data as any).author ?? null,
codec: (container.data as any).codec ?? null,
duration: (container.data as any).duration ?? null,
creationDate: (container.data as any).creationDate ?? null,
projectionType: (container.data as any).projectionType ?? null,
stereoType: (container.data as any).stereoType ?? null,
width: (container.data as any).width ?? null,
height: (container.data as any).height ?? null,
fps: (container.data as any).fps ?? null,
bitrate: (container.data as any).bitrate ?? null,
size: (container.data as any).size ?? null,
videoStreamCount: (stream.data as any).videoStreamCount ?? 0,
audioStreamCount: (stream.data as any).audioStreamCount ?? 0,
subtitleStreamCount: (stream.data as any).subtitleStreamCount ?? 0,
dataStreamCount: (stream.data as any).dataStreamCount ?? 0,
extraVideoTracks: (stream.data as any).extraVideoTracks ?? [],
hasAlpha: alphaData.hasAlpha,
alphaPixelFormats: alphaData.alphaPixelFormats ?? [],
hasMaskTrack: maskData.hasMaskTrack,
maskTrackNames: maskData.maskTrackNames ?? [],
raw: ffprobeOutput,
} as ContainerAnalysis,
confidence: {
overall,
passthrough: Math.round(passthroughScore * 100) / 100,
projection: Math.round(projectionScore * 100) / 100,
stereo: Math.round(stereoScore * 100) / 100,
},
feedValid,
feedErrors,
questCompatible,
};
}