index.mjs 9.9 KB

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