#!/usr/bin/env node import { createServer } from "node:http"; import { readFile } from "node:fs/promises"; import { closeSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; import { WebSocketServer } from "ws"; import { negotiateScreencastPortal } from "./portal.mjs"; import { assertUsocketAvailable } from "./dbus-fd.mjs"; import { buildPipeline, startGstreamer, defaultSourceForSession, pipewireSourceForChild, } from "./gstreamer.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); const VIEWER_PATH = join(__dirname, "..", "viewer", "index.html"); function parseArgs(argv) { const out = { host: "0.0.0.0", port: 9000, fps: 30, quality: 80, width: 1280, height: 720, source: null, verbose: false, }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "--host") out.host = argv[++i]; else if (a === "--port") out.port = Number(argv[++i]); else if (a === "--fps") out.fps = Number(argv[++i]); else if (a === "--quality") out.quality = Number(argv[++i]); else if (a === "--width") out.width = Number(argv[++i]); else if (a === "--height") out.height = Number(argv[++i]); else if (a === "--source") out.source = argv[++i]; else if (a === "--verbose" || a === "-v") out.verbose = true; else if (a === "--help" || a === "-h") { console.log(`Usage: node server/index.mjs [options] --host ADDR HTTP + WebSocket bind (default 0.0.0.0) --port N Viewer (HTTP) and WebSocket on same port (default 9000) --fps N Target framerate (default 30) --quality N JPEG 1-100 (default 80) --width N Scale output width (default 1280, 0 = source native) --height N Scale output height (default 720, 0 = source native) --source STR Override GStreamer source element chain (before ! videoconvert) --verbose Extra portal + pipeline debug (also NEBUCAST_VERBOSE=1) Environment: NEBUCAST_VERBOSE=1 Same as --verbose NEBUCAST_PORTAL_TRACE=0 Disable step-by-step [portal] logs NEBUCAST_PROCESS_DEBUG=1 Log beforeExit when the event loop drains `); process.exit(0); } } return out; } function installProcessDiagnostics(opts) { process.on("unhandledRejection", (reason, p) => { console.error("[nebucast] unhandledRejection:", reason); if (reason instanceof Error && reason.stack) console.error(reason.stack); console.error("[nebucast] promise:", p); }); process.on("uncaughtException", (err) => { console.error("[nebucast] uncaughtException:", err?.stack || err); }); if (opts.verbose || process.env.NEBUCAST_PROCESS_DEBUG === "1") { process.on("beforeExit", (code) => { console.error("[nebucast] beforeExit code=", code, "(event loop draining)"); }); } } async function main() { const opts = parseArgs(process.argv.slice(2)); installProcessDiagnostics(opts); const sessionType = process.env.XDG_SESSION_TYPE || ""; if (opts.verbose) { console.info("[nebucast] verbose on | XDG_SESSION_TYPE=%s", sessionType || "(unset)"); } function onEarlySigint() { console.error("\nInterrupted."); process.exit(130); } process.once("SIGINT", onEarlySigint); let portalBus = null; let pwFd = null; let source = opts.source; let stopGst = () => {}; /** @type {import('ws').WebSocketServer | null} */ let wss = null; let httpServer = null; let shuttingDown = false; function cleanupResources() { if (pwFd != null) { try { closeSync(pwFd); } catch { /* ignore */ } pwFd = null; } try { portalBus?.disconnect(); } catch { /* ignore */ } portalBus = null; } function shutdown(exitCode = 0) { if (shuttingDown) return; shuttingDown = true; console.error("[nebucast] shutdown() invoked, exitCode=", exitCode); if (opts.verbose) { console.error(new Error("[nebucast] shutdown trace").stack); } try { stopGst(); } catch { /* ignore */ } cleanupResources(); const finish = () => process.exit(exitCode); if (wss) { wss.close(() => { if (httpServer) { httpServer.close(finish); } else { finish(); } }); } else if (httpServer) { httpServer.close(finish); } else { finish(); } } try { const clients = new Set(); function broadcastFrame(frame) { for (const ws of clients) { if (ws.readyState !== ws.OPEN) continue; if (ws.bufferedAmount > 64 * 1024) continue; try { ws.send(frame, { binary: true }); } catch { clients.delete(ws); } } } function handleCaptureExit(code, signal, tag) { console.info("[%s] process exit: code=%s signal=%s", tag, code, signal ?? "(none)"); if (code !== 0 && code !== null) { console.error("[%s] non-zero exit", tag); } shutdown(code !== 0 && code !== null ? 1 : 0); } const viewerHtml = await readFile(VIEWER_PATH, "utf8"); try { httpServer = createServer((req, res) => { if (req.url === "/" || req.url?.startsWith("/index.html")) { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(viewerHtml); return; } res.writeHead(404); res.end(); }); httpServer.on("connection", (socket) => socket.setNoDelay(true)); wss = new WebSocketServer({ server: httpServer, path: "/ws", maxPayload: 4 * 1024 * 1024, perMessageDeflate: false, }); wss.on("connection", (ws) => { clients.add(ws); ws.on("close", () => clients.delete(ws)); ws.on("error", () => clients.delete(ws)); }); await new Promise((resolve, reject) => { let settled = false; httpServer.once("listening", () => { if (settled) return; settled = true; console.info( "Viewer: http://%s:%d/ | WebSocket: ws://%s:%d/ws", opts.host, opts.port, opts.host, opts.port, ); resolve(undefined); }); httpServer.once("error", (err) => { if (settled) return; settled = true; reject(err); }); httpServer.listen(opts.port, opts.host); }); } catch (err) { const code = err?.code; console.error("[ws]", err.message); if (code === "EADDRINUSE") { console.error( "[nebucast] Port %d is already in use. Use another port, e.g. npm start -- --port 9001", opts.port, ); console.error( "[nebucast] See what holds it: ss -tlnp | grep ':%d ' or fuser -v %d/tcp", opts.port, opts.port, ); } const done = () => process.exit(1); if (wss) { wss.close(() => httpServer?.close(done) ?? done()); } else if (httpServer) { httpServer.close(done); } else { done(); } } wss.on("error", (err) => { console.error("[ws]", err.message); shutdown(1); }); let child; if (!source && sessionType !== "x11") { console.info("Wayland (or non-X11) -- using XDG Desktop Portal for screen capture"); assertUsocketAvailable(); const p = await negotiateScreencastPortal({ verbose: opts.verbose }); portalBus = p.bus; pwFd = p.fd; const pipeSource = pipewireSourceForChild(p.nodeId); const pipeline = buildPipeline(pipeSource, { fps: opts.fps, quality: opts.quality, width: opts.width, height: opts.height, }); if (opts.verbose) console.info("[gstreamer] pipeline:", pipeline); const gst = startGstreamer({ pipeline, pipeWireFd: pwFd, onFrame: broadcastFrame, onSpawnError: (err) => console.error("[gstreamer]", err), onExit: (code, signal) => handleCaptureExit(code, signal, "gstreamer"), }); child = gst.child; stopGst = gst.stop; } else { if (!source) source = defaultSourceForSession(); const pipeline = buildPipeline(source, { fps: opts.fps, quality: opts.quality, width: opts.width, height: opts.height, }); if (opts.verbose) console.info("[gstreamer] pipeline:", pipeline); const gst = startGstreamer({ pipeline, pipeWireFd: undefined, onFrame: broadcastFrame, onSpawnError: (err) => console.error("[gstreamer]", err), onExit: (code, signal) => handleCaptureExit(code, signal, "gstreamer"), }); child = gst.child; stopGst = gst.stop; } if (!child) { cleanupResources(); wss.close(() => httpServer.close(() => process.exit(1))); return; } process.off("SIGINT", onEarlySigint); process.once("SIGINT", () => shutdown(0)); process.once("SIGTERM", () => shutdown(0)); } catch (err) { console.error(err.message || err); if (wss) { wss.close(() => { cleanupResources(); if (httpServer) { httpServer.close(() => process.exit(1)); } else { process.exit(1); } }); } else { cleanupResources(); process.exit(1); } } } main().catch((err) => { console.error(err?.stack || err?.message || err); process.exit(1); });