index.mjs 8.8 KB

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