File size: 15,209 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
#!/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 <file|url> [options]

  node scripts/alpha-pack.mjs --input-dir <folder> [options]   # batch



Inputs (repeatable / batch):

  -i, --input <path|url>   Source file or direct URL (Offcloud stream ok).

                           Repeat -i to process several files.

      --input-dir <dir>    Process every video in a folder (skips *_ALPHA*).

      --output-dir <dir>   Where batch/derived outputs go (default: beside source).



Background removal:

  -c, --color <name|hex>   green, blue, cyan, magenta, red, yellow, orange,

                           purple, grey, black, white, or hex 0x808080/#808080.

      --keyer <mode>       auto | chromakey | colorkey | lumakey. auto = chromakey

                           for colored screens, colorkey for grey/black/white.

      --similarity <f>     Key tolerance (default 0.10 chroma / 0.15 colorkey).

      --blend <f>          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 <tok>   Add a fisheye token to the OUTPUT name if the source

                           has none (e.g. fisheye190, mkx200, rf52, vrca220).

      --stereo-tag <tok>   Add a stereo token if missing (SBS | TB | MONO).

      --from-equirect      Convert equirectangular -> fisheye first (experimental).

      --fov <deg>          Fisheye FOV for --from-equirect (default 190).

      --stereo <mode>      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 <mode>      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 <h264|h265>  Default h264. --crf <n> (default 18). --preset <name>.

      --luma-threshold/-tolerance <f>   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 <file|url> (repeatable) or --input-dir <folder>.\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()