#!/usr/bin/env node // --------------------------------------------------------------------------- // DeoVR Alpha Packer (ffmpeg) - bakes "_ALPHA" passthrough into your videos. // // Takes a FISHEYE VR video with a solid-color background (grey/green/blue/...), // keys that background out OFFLINE, and packs it into a DeoVR alpha file so // DeoVR auto-enables passthrough on launch (no manual toggle, no in-headset // color picking). This is the SLR/WankzVR approach: transparency lives in the // file, not in the feed. // // Handles all the fisheye variations DeoVR supports and PRESERVES each file's // projection + stereo tokens in the output name (DeoVR reads those from the // filename), then inserts _ALPHA: // Projection (fisheye only): fisheye, fisheye190 / fish190, mkx200 (200), // vrca220 (220), rf52, or a bare 180/190/200/220. // Stereo: SBS / LR / 3DH (side-by-side) | TB / OU / 3DV (top-bottom) // MONO / 2D // Example: Clip_FISH190_SBS.mp4 -> Clip_FISH190_SBS_ALPHA.mp4 // // DeoVR alpha ONLY works on fisheye. Equirectangular/flat sources are warned // about; use --from-equirect (experimental) or convert to fisheye first. // // Layout note (see scripts/ALPHA-PACK.md): the color+alpha packing arrangement // must match what DeoVR expects. Default is vertical (color top / alpha bottom). // If it doesn't auto-key, try --layout horizontal and/or --alpha-first. // --------------------------------------------------------------------------- import { spawn } from "node:child_process" import fs from "node:fs" import path from "node:path" import process from "node:process" const NAMED_COLORS = { green: "0x00ff00", greenscreen: "0x00ff00", blue: "0x0000ff", bluescreen: "0x0000ff", cyan: "0x00ffff", magenta: "0xff00ff", pink: "0xff00ff", red: "0xff0000", yellow: "0xffff00", orange: "0xff8000", purple: "0x8000ff", grey: "0x808080", gray: "0x808080", black: "0x000000", white: "0xffffff", } const ACHROMATIC = new Set(["grey", "gray", "black", "white"]) const VIDEO_EXTS = new Set([".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi", ".ts"]) // --- DeoVR filename token detection --------------------------------------- // Projection tokens, most specific first. All are fisheye meshes. const FISHEYE_TOKENS = [ { re: /vrca220/i, fov: 220 }, { re: /mkx220/i, fov: 220 }, { re: /mkx200/i, fov: 200 }, { re: /rf52/i, fov: 200 }, { re: /fisheye190/i, fov: 190 }, { re: /fish190/i, fov: 190 }, { re: /fisheye/i, fov: 180 }, ] const STEREO_TOKENS = [ { re: /(?:^|[_\-. ])(sbs|lr|3dh)(?:$|[_\-. ])/i, stereo: "sbs" }, { re: /(?:^|[_\-. ])(tb|ou|3dv|overunder)(?:$|[_\-. ])/i, stereo: "tb" }, { re: /(?:^|[_\-. ])(mono|2d)(?:$|[_\-. ])/i, stereo: "mono" }, ] function detectTokens(name) { let fisheye = false let fov = null for (const t of FISHEYE_TOKENS) { if (t.re.test(name)) { fisheye = true; fov = t.fov; break } } // A bare FOV number can refine/indicate fisheye FOV. const bare = name.match(/(?:^|[_\-. ])(180|190|200|220)(?:$|[_\-. ])/) if (bare) { const n = parseInt(bare[1], 10) if (fov == null) fov = n // 190/200/220 basically only exist as fisheye meshes in DeoVR. if (n >= 190) fisheye = true } let stereo = null for (const s of STEREO_TOKENS) { if (s.re.test(name)) { stereo = s.stereo; break } } const alpha = /(?:^|[_\-. ])alpha(?:$|[_\-. ])/i.test(name) return { fisheye, fov, stereo, alpha } } function parseArgs(argv) { const args = { inputs: [], inputDir: null, output: null, outputDir: null, color: "green", keyer: "auto", similarity: null, blend: 0.1, layout: null, // auto-chosen from stereo if not set alphaFirst: false, projection: null, // optional tag to add if source lacks a fisheye token stereoTag: null, // optional stereo tag to add if missing fromEquirect: false, fov: 190, stereo: "sbs", // only used for --from-equirect mapping codec: "h264", crf: 18, preset: "medium", lumaThreshold: 0.1, lumaTolerance: 0.1, force: false, // proceed even if not detected as fisheye dryRun: false, } for (let i = 2; i < argv.length; i++) { const a = argv[i] const next = () => argv[++i] switch (a) { case "--input": case "-i": args.inputs.push(next()); break case "--input-dir": args.inputDir = next(); break case "--output": case "-o": args.output = next(); break case "--output-dir": args.outputDir = next(); break case "--color": case "-c": args.color = next(); break case "--keyer": args.keyer = next(); break case "--similarity": args.similarity = parseFloat(next()); break case "--blend": args.blend = parseFloat(next()); break case "--layout": args.layout = next(); break case "--alpha-first": args.alphaFirst = true; break case "--projection": args.projection = next(); break case "--stereo-tag": args.stereoTag = next(); break case "--from-equirect": args.fromEquirect = true; break case "--fov": args.fov = parseFloat(next()); break case "--stereo": args.stereo = next(); break case "--codec": args.codec = next(); break case "--crf": args.crf = parseInt(next(), 10); break case "--preset": args.preset = next(); break case "--luma-threshold": args.lumaThreshold = parseFloat(next()); break case "--luma-tolerance": args.lumaTolerance = parseFloat(next()); break case "--force": args.force = true; break case "--dry-run": args.dryRun = true; break case "--help": case "-h": printHelp(); process.exit(0); break default: console.error(`Unknown argument: ${a}`); printHelp(); process.exit(1) } } return args } function printHelp() { console.log(`DeoVR Alpha Packer - handles all fisheye variations Usage: node scripts/alpha-pack.mjs --input [options] node scripts/alpha-pack.mjs --input-dir [options] # batch Inputs (repeatable / batch): -i, --input Source file or direct URL (Offcloud stream ok). Repeat -i to process several files. --input-dir Process every video in a folder (skips *_ALPHA*). --output-dir Where batch/derived outputs go (default: beside source). Background removal: -c, --color green, blue, cyan, magenta, red, yellow, orange, purple, grey, black, white, or hex 0x808080/#808080. --keyer auto | chromakey | colorkey | lumakey. auto = chromakey for colored screens, colorkey for grey/black/white. --similarity Key tolerance (default 0.10 chroma / 0.15 colorkey). --blend Edge softness (default 0.10). Format / projection (DeoVR reads these from the filename; tokens are preserved): Detected automatically: fisheye, fisheye190/fish190, mkx200(200), vrca220(220), rf52, bare 180/190/200/220; stereo SBS/LR/3DH, TB/OU/3DV, MONO. --projection Add a fisheye token to the OUTPUT name if the source has none (e.g. fisheye190, mkx200, rf52, vrca220). --stereo-tag Add a stereo token if missing (SBS | TB | MONO). --from-equirect Convert equirectangular -> fisheye first (experimental). --fov Fisheye FOV for --from-equirect (default 190). --stereo sbs | tb | mono for --from-equirect mapping. --force Pack even if the source isn't detected as fisheye. Packing layout (match what DeoVR expects - see scripts/ALPHA-PACK.md): --layout vertical (color top/alpha bottom) | horizontal. Default: vertical for SBS/mono, horizontal for TB. --alpha-first Swap so the alpha matte comes first. Encoding: --codec Default h264. --crf (default 18). --preset . --luma-threshold/-tolerance lumakey tuning. --dry-run Print the ffmpeg command(s) and exit. Examples: node scripts/alpha-pack.mjs -i Clip_FISH190_SBS.mp4 -c grey node scripts/alpha-pack.mjs --input-dir /data/masters -c green node scripts/alpha-pack.mjs -i plain_fisheye.mp4 -c grey --stereo-tag SBS node scripts/alpha-pack.mjs -i clip_TB_mkx200.mp4 -c blue # auto horizontal `) } function resolveColor(input) { const key = String(input).toLowerCase().trim() if (NAMED_COLORS[key]) return { hex: NAMED_COLORS[key], name: key } let hex = key if (hex.startsWith("#")) hex = "0x" + hex.slice(1) if (/^[0-9a-f]{6}$/.test(hex)) hex = "0x" + hex if (!/^0x[0-9a-f]{6}$/.test(hex)) { console.error(`Invalid color: ${input}. Use a name or 6-digit hex.`) process.exit(1) } return { hex, name: hex } } function baseNameOf(input) { try { return path.basename(new URL(input).pathname) || "output.mp4" } catch { return path.basename(input) } } function dirNameOf(input) { try { new URL(input); return process.cwd() } // URL -> cwd catch { return path.dirname(input) } } function buildOutputPath(input, args, detected) { if (args.output && (args.inputs.length + (args.inputDir ? 0 : 0)) === 1 && !args.inputDir) { // explicit single-file output const ext = path.extname(args.output) let stem = args.output.slice(0, args.output.length - ext.length) if (!/_alpha$/i.test(stem)) stem += "_ALPHA" return stem + (ext || ".mp4") } const base = baseNameOf(input) const ext = path.extname(base) || ".mp4" let stem = base.slice(0, base.length - ext.length) // Add missing tokens if the user asked to tag them. if (args.projection && !detected.fisheye) stem += "_" + args.projection.toUpperCase() if (args.stereoTag && !detected.stereo) stem += "_" + args.stereoTag.toUpperCase() if (!/_alpha$/i.test(stem)) stem += "_ALPHA" const outDir = args.outputDir || dirNameOf(input) return path.join(outDir, stem + ".mp4") } function chooseLayout(args, detected) { if (args.layout) return args.layout // TB sources: pack alpha to the side to avoid clashing with the T/B split. if (detected.stereo === "tb") return "horizontal" return "vertical" } function buildFilterGraph(args, color, layout) { const parts = [] let src = "0:v" if (args.fromEquirect) { const inLayout = args.stereo === "sbs" ? "sbs" : args.stereo === "tb" ? "tb" : "2d" parts.push( `[${src}]v360=input=equirect:output=fisheye:d_fov=${args.fov}:` + `in_stereo=${inLayout}:out_stereo=${inLayout}[fe]`, ) src = "fe" } parts.push(`[${src}]split=2[c][k]`) let keyer = args.keyer if (keyer === "auto") { keyer = ACHROMATIC.has(String(args.color).toLowerCase()) ? "colorkey" : "chromakey" } const sim = args.similarity != null ? args.similarity : keyer === "colorkey" ? 0.15 : 0.1 if (keyer === "chromakey") { parts.push(`[k]chromakey=${color.hex}:${sim}:${args.blend},format=yuva420p,alphaextract,format=gray[matte]`) } else if (keyer === "colorkey") { parts.push(`[k]format=rgba,colorkey=${color.hex}:${sim}:${args.blend},format=rgba,alphaextract,format=gray[matte]`) } else if (keyer === "lumakey") { parts.push( `[k]format=rgba,lumakey=threshold=${args.lumaThreshold}:tolerance=${args.lumaTolerance}:` + `softness=${args.blend},format=rgba,alphaextract,format=gray[matte]`, ) } else { console.error(`Unknown keyer: ${keyer}`); process.exit(1) } parts.push(`[c]format=gbrp,format=yuv420p[color]`) const stack = layout === "horizontal" ? "hstack" : "vstack" const order = args.alphaFirst ? ["matte", "color"] : ["color", "matte"] parts.push(`[${order[0]}][${order[1]}]${stack}=inputs=2[packed]`) return { graph: parts.join(";"), keyer, sim } } function collectInputs(args) { const list = [...args.inputs] if (args.inputDir) { const entries = fs.readdirSync(args.inputDir) for (const e of entries) { const ext = path.extname(e).toLowerCase() if (!VIDEO_EXTS.has(ext)) continue if (/_alpha/i.test(e)) continue // skip already-packed list.push(path.join(args.inputDir, e)) } } return list } function packOne(input, args) { return new Promise((resolve) => { const color = resolveColor(args.color) const detected = detectTokens(baseNameOf(input)) const layout = chooseLayout(args, detected) const output = buildOutputPath(input, args, detected) const { graph, keyer, sim } = buildFilterGraph(args, color, layout) const vcodec = args.codec === "h265" ? "libx265" : "libx264" const fmt = [ detected.fisheye ? `fisheye${detected.fov ? detected.fov : ""}` : "NON-FISHEYE", detected.stereo || "stereo?", ].join(" / ") console.log(`\n=== ${baseNameOf(input)} ===`) console.log(` detected : ${fmt}`) console.log(` output : ${output}`) console.log(` color : ${args.color} (${color.hex}) keyer: ${keyer} sim=${sim} blend=${args.blend}`) console.log(` layout : ${layout}${args.alphaFirst ? " (alpha first)" : ""} codec: ${vcodec} crf=${args.crf}`) if (!detected.fisheye && !args.fromEquirect && !args.projection && !args.force) { console.warn( " !! Not detected as fisheye. DeoVR alpha only works on fisheye.\n" + " Add a token with --projection (e.g. fisheye190), convert with\n" + " --from-equirect, or pass --force to pack anyway. Skipping.", ) return resolve({ input, skipped: true }) } const ff = [ "-y", "-i", input, "-filter_complex", graph, "-map", "[packed]", "-map", "0:a?", "-c:v", vcodec, "-crf", String(args.crf), "-preset", args.preset, "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart", output, ] console.log(" ffmpeg " + ff.map((a) => (/[\s;]/.test(a) ? `'${a}'` : a)).join(" ")) if (args.dryRun) return resolve({ input, output, dryRun: true }) const child = spawn("ffmpeg", ff, { stdio: "inherit" }) child.on("error", (e) => { console.error(` ffmpeg failed to start: ${e.message}`); resolve({ input, error: true }) }) child.on("close", (code) => { if (code === 0) { console.log(` done -> ${output}`); resolve({ input, output }) } else { console.error(` ffmpeg exited ${code}`); resolve({ input, error: true }) } }) }) } async function main() { const args = parseArgs(process.argv) const inputs = collectInputs(args) if (inputs.length === 0) { console.error("Error: provide --input (repeatable) or --input-dir .\n") printHelp(); process.exit(1) } if (args.output && inputs.length > 1) { console.error("Error: --output is for a single input. Use --output-dir for batches.") process.exit(1) } console.log(`DeoVR Alpha Packer - ${inputs.length} file(s)`) const results = [] for (const input of inputs) results.push(await packOne(input, args)) // sequential = predictable CPU const ok = results.filter((r) => r.output && !r.dryRun && !r.skipped && !r.error).length const skipped = results.filter((r) => r.skipped).length const failed = results.filter((r) => r.error).length if (!args.dryRun) console.log(`\nSummary: ${ok} packed, ${skipped} skipped, ${failed} failed.`) if (failed) process.exit(1) } main()