index.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #!/usr/bin/env node
  2. import { createServer } from "node:http";
  3. import { readFile } from "node:fs/promises";
  4. import { closeSync } from "node:fs";
  5. import { fileURLToPath } from "node:url";
  6. import { dirname, join } from "node:path";
  7. import { WebSocketServer } from "ws";
  8. import { negotiateScreencastPortal } from "./portal.mjs";
  9. import { dbusUnixFdTransportAvailable } from "./dbus-fd.mjs";
  10. import { startPythonWaylandBridge } from "./wayland-python-bridge.mjs";
  11. import {
  12. buildPipeline,
  13. startGstreamer,
  14. defaultSourceForSession,
  15. pipewireSourceForChild,
  16. } from "./gstreamer.mjs";
  17. const __dirname = dirname(fileURLToPath(import.meta.url));
  18. const VIEWER_PATH = join(__dirname, "..", "viewer", "index.html");
  19. function parseArgs(argv) {
  20. const out = {
  21. host: "0.0.0.0",
  22. port: 9000,
  23. fps: 30,
  24. quality: 80,
  25. source: null,
  26. verbose: false,
  27. };
  28. for (let i = 0; i < argv.length; i++) {
  29. const a = argv[i];
  30. if (a === "--host") out.host = argv[++i];
  31. else if (a === "--port") out.port = Number(argv[++i]);
  32. else if (a === "--fps") out.fps = Number(argv[++i]);
  33. else if (a === "--quality") out.quality = Number(argv[++i]);
  34. else if (a === "--source") out.source = argv[++i];
  35. else if (a === "--verbose" || a === "-v") out.verbose = true;
  36. else if (a === "--help" || a === "-h") {
  37. console.log(`Usage: node server/index.mjs [options]
  38. --host ADDR HTTP + WebSocket bind (default 0.0.0.0)
  39. --port N Viewer (HTTP) and WebSocket on same port (default 9000)
  40. --fps N Target framerate (default 30)
  41. --quality N JPEG 1-100 (default 80)
  42. --source STR Override GStreamer source element chain (before ! videoconvert)
  43. --verbose Extra portal + pipeline debug (also NEBUCAST_VERBOSE=1)
  44. Environment:
  45. NEBUCAST_VERBOSE=1 Same as --verbose
  46. NEBUCAST_PORTAL_TRACE=0 Disable step-by-step [portal] logs
  47. NEBUCAST_PROCESS_DEBUG=1 Log beforeExit when the event loop drains
  48. NEBUCAST_FORCE_PYTHON_BRIDGE=1 Always use Python Wayland bridge (skip usocket path)
  49. `);
  50. process.exit(0);
  51. }
  52. }
  53. return out;
  54. }
  55. function installProcessDiagnostics(opts) {
  56. process.on("unhandledRejection", (reason, p) => {
  57. console.error("[nebucast] unhandledRejection:", reason);
  58. if (reason instanceof Error && reason.stack) console.error(reason.stack);
  59. console.error("[nebucast] promise:", p);
  60. });
  61. process.on("uncaughtException", (err) => {
  62. console.error("[nebucast] uncaughtException:", err?.stack || err);
  63. });
  64. if (opts.verbose || process.env.NEBUCAST_PROCESS_DEBUG === "1") {
  65. process.on("beforeExit", (code) => {
  66. console.error("[nebucast] beforeExit code=", code, "(event loop draining)");
  67. });
  68. }
  69. }
  70. async function main() {
  71. const opts = parseArgs(process.argv.slice(2));
  72. installProcessDiagnostics(opts);
  73. const sessionType = process.env.XDG_SESSION_TYPE || "";
  74. if (opts.verbose) {
  75. console.info("[nebucast] verbose on | XDG_SESSION_TYPE=%s", sessionType || "(unset)");
  76. }
  77. function onEarlySigint() {
  78. console.error("\nInterrupted.");
  79. process.exit(130);
  80. }
  81. process.once("SIGINT", onEarlySigint);
  82. let portalBus = null;
  83. let pwFd = null;
  84. let source = opts.source;
  85. let stopGst = () => {};
  86. /** @type {import('ws').WebSocketServer | null} */
  87. let wss = null;
  88. let httpServer = null;
  89. let shuttingDown = false;
  90. function cleanupResources() {
  91. if (pwFd != null) {
  92. try {
  93. closeSync(pwFd);
  94. } catch {
  95. /* ignore */
  96. }
  97. pwFd = null;
  98. }
  99. try {
  100. portalBus?.disconnect();
  101. } catch {
  102. /* ignore */
  103. }
  104. portalBus = null;
  105. }
  106. function shutdown(exitCode = 0) {
  107. if (shuttingDown) return;
  108. shuttingDown = true;
  109. console.error("[nebucast] shutdown() invoked, exitCode=", exitCode);
  110. if (opts.verbose) {
  111. console.error(new Error("[nebucast] shutdown trace").stack);
  112. }
  113. try {
  114. stopGst();
  115. } catch {
  116. /* ignore */
  117. }
  118. cleanupResources();
  119. const finish = () => process.exit(exitCode);
  120. if (wss) {
  121. wss.close(() => {
  122. if (httpServer) {
  123. httpServer.close(finish);
  124. } else {
  125. finish();
  126. }
  127. });
  128. } else if (httpServer) {
  129. httpServer.close(finish);
  130. } else {
  131. finish();
  132. }
  133. }
  134. try {
  135. const clients = new Set();
  136. function broadcastFrame(frame) {
  137. for (const ws of clients) {
  138. if (ws.readyState !== ws.OPEN) continue;
  139. if (ws.bufferedAmount > 8 * 1024 * 1024) continue;
  140. try {
  141. ws.send(frame, { binary: true });
  142. } catch {
  143. clients.delete(ws);
  144. }
  145. }
  146. }
  147. function handleCaptureExit(code, signal, tag) {
  148. console.info("[%s] process exit: code=%s signal=%s", tag, code, signal ?? "(none)");
  149. if (code !== 0 && code !== null) {
  150. console.error("[%s] non-zero exit", tag);
  151. }
  152. shutdown(code !== 0 && code !== null ? 1 : 0);
  153. }
  154. const viewerHtml = await readFile(VIEWER_PATH, "utf8");
  155. try {
  156. httpServer = createServer((req, res) => {
  157. if (req.url === "/" || req.url?.startsWith("/index.html")) {
  158. res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  159. res.end(viewerHtml);
  160. return;
  161. }
  162. res.writeHead(404);
  163. res.end();
  164. });
  165. wss = new WebSocketServer({
  166. server: httpServer,
  167. path: "/ws",
  168. maxPayload: 4 * 1024 * 1024,
  169. perMessageDeflate: false,
  170. });
  171. wss.on("connection", (ws) => {
  172. clients.add(ws);
  173. ws.on("close", () => clients.delete(ws));
  174. ws.on("error", () => clients.delete(ws));
  175. });
  176. await new Promise((resolve, reject) => {
  177. let settled = false;
  178. httpServer.once("listening", () => {
  179. if (settled) return;
  180. settled = true;
  181. console.info(
  182. "Viewer: http://%s:%d/ | WebSocket: ws://%s:%d/ws",
  183. opts.host,
  184. opts.port,
  185. opts.host,
  186. opts.port,
  187. );
  188. resolve(undefined);
  189. });
  190. httpServer.once("error", (err) => {
  191. if (settled) return;
  192. settled = true;
  193. reject(err);
  194. });
  195. httpServer.listen(opts.port, opts.host);
  196. });
  197. } catch (err) {
  198. const code = err?.code;
  199. console.error("[ws]", err.message);
  200. if (code === "EADDRINUSE") {
  201. console.error(
  202. "[nebucast] Port %d is already in use. Use another port, e.g. npm start -- --port 9001",
  203. opts.port,
  204. );
  205. console.error(
  206. "[nebucast] See what holds it: ss -tlnp | grep ':%d ' or fuser -v %d/tcp",
  207. opts.port,
  208. opts.port,
  209. );
  210. }
  211. const done = () => process.exit(1);
  212. if (wss) {
  213. wss.close(() => httpServer?.close(done) ?? done());
  214. } else if (httpServer) {
  215. httpServer.close(done);
  216. } else {
  217. done();
  218. }
  219. }
  220. wss.on("error", (err) => {
  221. console.error("[ws]", err.message);
  222. shutdown(1);
  223. });
  224. let child;
  225. if (!source && sessionType !== "x11") {
  226. console.info("Wayland (or non-X11) — using XDG Desktop Portal for screen capture");
  227. const useUsocket =
  228. process.env.NEBUCAST_FORCE_PYTHON_BRIDGE !== "1" && dbusUnixFdTransportAvailable();
  229. if (opts.verbose) {
  230. console.info("[nebucast] D-Bus Unix FD (usocket) available:", useUsocket);
  231. }
  232. if (useUsocket) {
  233. const p = await negotiateScreencastPortal({ verbose: opts.verbose });
  234. portalBus = p.bus;
  235. pwFd = p.fd;
  236. const pipeSource = pipewireSourceForChild(p.nodeId);
  237. const pipeline = buildPipeline(pipeSource, {
  238. fps: opts.fps,
  239. quality: opts.quality,
  240. });
  241. if (opts.verbose) console.info("[gstreamer] pipeline:", pipeline);
  242. const gst = startGstreamer({
  243. pipeline,
  244. pipeWireFd: pwFd,
  245. onFrame: broadcastFrame,
  246. onSpawnError: (err) => console.error("[gstreamer]", err),
  247. onExit: (code, signal) => handleCaptureExit(code, signal, "gstreamer"),
  248. });
  249. child = gst.child;
  250. stopGst = gst.stop;
  251. } else {
  252. console.warn(
  253. "[nebucast] The native `usocket` module is missing or failed to load. " +
  254. "Node’s D-Bus socket cannot receive PipeWire fds (OpenPipeWireRemote). " +
  255. "Falling back to Python: server/wayland-capture-bridge.py " +
  256. "(python3, dbus-python, PyGObject, GStreamer). " +
  257. "For pure Node on Wayland, install usocket (often works on Node 20–22).",
  258. );
  259. portalBus = null;
  260. pwFd = null;
  261. const py = startPythonWaylandBridge({
  262. fps: opts.fps,
  263. quality: opts.quality,
  264. onFrame: broadcastFrame,
  265. onSpawnError: (err) => console.error("[wayland-bridge]", err),
  266. onExit: (code, signal) => handleCaptureExit(code, signal, "wayland-bridge"),
  267. });
  268. child = py.child;
  269. stopGst = py.stop;
  270. }
  271. } else {
  272. if (!source) source = defaultSourceForSession();
  273. const pipeline = buildPipeline(source, {
  274. fps: opts.fps,
  275. quality: opts.quality,
  276. });
  277. if (opts.verbose) console.info("[gstreamer] pipeline:", pipeline);
  278. const gst = startGstreamer({
  279. pipeline,
  280. pipeWireFd: undefined,
  281. onFrame: broadcastFrame,
  282. onSpawnError: (err) => console.error("[gstreamer]", err),
  283. onExit: (code, signal) => handleCaptureExit(code, signal, "gstreamer"),
  284. });
  285. child = gst.child;
  286. stopGst = gst.stop;
  287. }
  288. if (!child) {
  289. cleanupResources();
  290. wss.close(() => httpServer.close(() => process.exit(1)));
  291. return;
  292. }
  293. process.off("SIGINT", onEarlySigint);
  294. process.once("SIGINT", () => shutdown(0));
  295. process.once("SIGTERM", () => shutdown(0));
  296. } catch (err) {
  297. console.error(err.message || err);
  298. if (wss) {
  299. wss.close(() => {
  300. cleanupResources();
  301. if (httpServer) {
  302. httpServer.close(() => process.exit(1));
  303. } else {
  304. process.exit(1);
  305. }
  306. });
  307. } else {
  308. cleanupResources();
  309. process.exit(1);
  310. }
  311. }
  312. }
  313. main().catch((err) => {
  314. console.error(err?.stack || err?.message || err);
  315. process.exit(1);
  316. });