gstreamer.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { spawn } from "node:child_process";
  2. import { createJpegFramer } from "./jpeg-framer.mjs";
  3. /** @param {{ fps: number; quality: number }} opts */
  4. export function buildPipeline(source, { fps, quality }) {
  5. return (
  6. `${source} ! videoconvert ! videoscale ! video/x-raw,width=1280,height=720 ! ` +
  7. `videorate ! video/x-raw,framerate=${fps}/1 ! jpegenc quality=${quality} ! ` +
  8. `fdsink fd=1 sync=false`
  9. );
  10. }
  11. /**
  12. * @param {object} opts
  13. * @param {string} opts.pipeline
  14. * @param {number | undefined} opts.pipeWireFd - if set, duplicated to child as fd 3
  15. * @param {(frame: Buffer) => void} opts.onFrame
  16. * @param {(err: Error) => void} [opts.onSpawnError]
  17. * @param {(code: number | null, signal?: string) => void} [opts.onExit]
  18. */
  19. export function startGstreamer(opts) {
  20. const { pipeline, pipeWireFd, onFrame, onSpawnError, onExit } = opts;
  21. const stdio =
  22. pipeWireFd !== undefined && pipeWireFd !== null
  23. ? ["ignore", "pipe", "pipe", pipeWireFd]
  24. : ["ignore", "pipe", "pipe"];
  25. const argv = ["-q", ...pipeline.trim().split(/\s+/)];
  26. const child = spawn("gst-launch-1.0", argv, {
  27. stdio,
  28. });
  29. if (!child.stdout) {
  30. onSpawnError?.(new Error("gstreamer: no stdout"));
  31. return { child: null, stop: () => {} };
  32. }
  33. const framer = createJpegFramer(onFrame);
  34. child.stdout.on("data", (chunk) => framer.push(chunk));
  35. child.stderr?.on("data", (d) => {
  36. const s = d.toString().trim();
  37. if (s) console.error("[gstreamer]", s);
  38. });
  39. child.on("error", (err) => onSpawnError?.(err));
  40. child.on("exit", (code, signal) => onExit?.(code, signal));
  41. function stop() {
  42. child.kill("SIGTERM");
  43. }
  44. return { child, stop };
  45. }
  46. export function defaultSourceForSession() {
  47. const session = process.env.XDG_SESSION_TYPE || "";
  48. if (session === "x11") {
  49. return "ximagesrc use-damage=0 show-pointer=true";
  50. }
  51. return "pipewiresrc do-timestamp=true keepalive-time=1000";
  52. }
  53. /** PipeWire fd is passed to the child as stdio fd 3 (see spawn stdio array). */
  54. export function pipewireSourceForChild(nodeId) {
  55. return `pipewiresrc fd=3 path=${nodeId} do-timestamp=true keepalive-time=1000`;
  56. }