index.mjs 9.3 KB

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