File size: 12,724 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
// 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,
  };
}