| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329 |
- #!/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);
- });
|