@dotrino/remote-desktop-agent 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +69 -6
  2. package/package.json +2 -1
  3. package/video.js +150 -0
package/index.js CHANGED
@@ -24,8 +24,12 @@
24
24
  * { type:'text', text } escribir un texto
25
25
  * { type:'key', keysym } una tecla especial, por su keysym de X (Intro, flechas…)
26
26
  * { type:'raise', id } traer al frente esa ventana (id de su nodo), con el foco
27
+ * { type:'video', id } vídeo de ese nodo (un hueco o una ventana sin contenido);
28
+ * `id: null` lo para. Sigue al nodo si se mueve.
27
29
  * agente → cliente:
28
30
  * { type:'scene', seq, screen, wins, nodes } · { type:'patch', seq, base, … } (scene.js)
31
+ * { type:'vframe', id, seq, key, rect, data } un cuadro H.264 (Annex B, base64) de ese rectángulo
32
+ * { type:'vwait', id, route } no hay vídeo por este camino (la red de Dotrino): espera al directo
29
33
  * { type:'fail', code, message }
30
34
  *
31
35
  * Quién puede: cualquier aparato de tu cuenta con `sign` en el acta, igual que la terminal
@@ -37,6 +41,7 @@ import { startRemoteAgent } from '@dotrino/remote-agent/agent'
37
41
  import { dataDir, loadLink, LABEL } from './link.js'
38
42
  import { makeDesktop } from './desktop.js'
39
43
  import { raiseWindow } from './raise.js'
44
+ import { makeVideo, evenRect } from './video.js'
40
45
 
41
46
  /** @typedef {Awaited<ReturnType<typeof startRemoteAgent>>} RemoteAgent */
42
47
 
@@ -69,9 +74,11 @@ const int = (v) => Number.isInteger(v)
69
74
  * Atiende una sesión de otro aparato. Exportada para las pruebas.
70
75
  * @param {SessionLike} session
71
76
  * @param {ReturnType<typeof makeDesktop>} desktop
72
- * @param {{ log?: (m: string) => void }} [opts]
77
+ * @param {{ log?: (m: string) => void, route?: () => Promise<string> }} [opts]
78
+ * `route`: por dónde va esta sesión ahora (`routeTo` del pilar). El vídeo solo sale por un
79
+ * camino que no es la red de Dotrino.
73
80
  */
74
- export function serveSession (session, desktop, { log = () => {} } = {}) {
81
+ export function serveSession (session, desktop, { log = () => {}, route = async () => 'direct' } = {}) {
75
82
  /** @type {(() => void) | null} */
76
83
  let unwatch = null
77
84
  /** @type {(code: string, message: string) => void} */
@@ -82,6 +89,47 @@ export function serveSession (session, desktop, { log = () => {} } = {}) {
82
89
  fail(e?.code || 'desktop-error', e?.message || String(err))
83
90
  }
84
91
 
92
+ // EL VÍDEO DE UN HUECO (video.js): uno por sesión, el del nodo que pidió el cliente.
93
+ const video = makeVideo({ log })
94
+ /** @type {number | null} */
95
+ let videoId = null
96
+ let vseq = 0
97
+ // EL VÍDEO NO PASA POR LA RED DE DOTRINO (regla del dueño, 2026-11-01): su proxio y su TURN no
98
+ // llevan los bytes pesados de los usuarios, ni preguntando. Solo por un camino sin nadie en
99
+ // medio. Por el proxio el hueco dice que espera la conexión directa, y se mira cada poco.
100
+ const VIDEO_ROUTES = new Set(['direct', 'socket', 'bluetooth'])
101
+ /** @type {string | null} */
102
+ let videoRoute = null
103
+ /** @type {ReturnType<typeof setInterval> | null} */
104
+ let routeTimer = null
105
+ const checkRoute = async () => {
106
+ let r = 'proxy'
107
+ try { r = await route() } catch (_) {}
108
+ if (r === videoRoute) return
109
+ videoRoute = r
110
+ if (videoId == null) return
111
+ if (VIDEO_ROUTES.has(r)) syncVideo()
112
+ else { video.stop(); session.send({ type: 'vwait', id: videoId, route: r }) }
113
+ }
114
+ const watchRoute = (/** @type {boolean} */ on) => {
115
+ if (on && !routeTimer) { routeTimer = setInterval(() => { checkRoute() }, 3000); routeTimer.unref?.() }
116
+ if (!on && routeTimer) { clearInterval(routeTimer); routeTimer = null; videoRoute = null }
117
+ }
118
+
119
+ /** Arranca (o rehace, si el nodo se movió) la captura del nodo pedido. */
120
+ const syncVideo = () => {
121
+ if (videoId == null) { video.stop(); return }
122
+ if (!videoRoute || !VIDEO_ROUTES.has(videoRoute)) return
123
+ const scene = desktop.scene
124
+ const n = scene.nodes.find((x) => x.id === videoId)
125
+ const r = n ? evenRect(n, scene.screen) : null
126
+ if (!r) { video.stop(); return }
127
+ const id = videoId
128
+ video.start(r,
129
+ ({ key, data }) => { session.send({ type: 'vframe', id, seq: vseq++, key, rect: r, data: Buffer.from(data).toString('base64') }) },
130
+ (e) => { videoId = null; failWith(e) })
131
+ }
132
+
85
133
  /** El lector, o un fallo dicho: sin nadie mirando no hay a quién mandarle el clic. */
86
134
  const reader = () => {
87
135
  const r = desktop.reader
@@ -99,12 +147,20 @@ export function serveSession (session, desktop, { log = () => {} } = {}) {
99
147
  switch (msg.type) {
100
148
  case 'scene': {
101
149
  unwatch?.()
102
- const w = await desktop.watch((patch) => { session.send({ type: 'patch', ...patch }) })
150
+ const w = await desktop.watch((patch) => { session.send({ type: 'patch', ...patch }); if (videoId != null) syncVideo() })
103
151
  unwatch = w.unwatch
104
152
  session.send({ type: 'scene', ...w.scene })
105
153
  return
106
154
  }
107
- case 'leave': unwatch?.(); unwatch = null; return
155
+ case 'leave': unwatch?.(); unwatch = null; videoId = null; video.stop(); watchRoute(false); return
156
+ case 'video':
157
+ if (id !== null && !int(id)) return fail('bad-input', 'video needs a node id, or null to stop')
158
+ videoId = id
159
+ if (videoId == null) { video.stop(); watchRoute(false); return }
160
+ watchRoute(true)
161
+ videoRoute = null
162
+ await checkRoute()
163
+ return
108
164
  case 'click': {
109
165
  if (!num(x) || !num(y)) return fail('bad-input', 'click needs x and y')
110
166
  if (!int(button) || !BUTTONS.has(button)) return fail('bad-input', 'button must be 1, 2 or 3')
@@ -162,7 +218,7 @@ export function serveSession (session, desktop, { log = () => {} } = {}) {
162
218
  failWith(e)
163
219
  }
164
220
  })
165
- session.on('close', () => { unwatch?.(); unwatch = null })
221
+ session.on('close', () => { unwatch?.(); unwatch = null; videoId = null; video.stop(); watchRoute(false) })
166
222
  }
167
223
 
168
224
  /**
@@ -196,7 +252,14 @@ export async function startAgent (opts = {}) {
196
252
  quiet: opts.quiet,
197
253
  sessionTtlMs: SESSION_IDLE_MS,
198
254
  onRevoked: () => { desktop.stop().catch(() => {}); opts.onRevoked?.() },
199
- onSession: (session) => serveSession(session, desktop, { log })
255
+ onSession: (session) => serveSession(session, desktop, {
256
+ log,
257
+ route: async () => {
258
+ const c = /** @type {{ routeTo?: (t: string) => Promise<string> } | undefined} */ (remote?.client)
259
+ const from = /** @type {{ from?: string }} */ (session).from
260
+ return c?.routeTo && from ? c.routeTo(from) : 'proxy'
261
+ }
262
+ })
200
263
  })
201
264
  /** @type {ReturnType<typeof setInterval> | null} */
202
265
  let retry = null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/remote-desktop-agent",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Dotrino Remote Desktop: usa el escritorio de esta máquina desde los otros aparatos de tu cuenta. Lo dibuja a partir de su árbol de accesibilidad (ligero y nítido), cifrado punto a punto.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,6 +13,7 @@
13
13
  "files": [
14
14
  "index.js",
15
15
  "raise.js",
16
+ "video.js",
16
17
  "atspi.js",
17
18
  "desktop.js",
18
19
  "scene.js",
package/video.js ADDED
@@ -0,0 +1,150 @@
1
+ /**
2
+ * video.js — el VÍDEO DE UN HUECO: lo que no publica accesibilidad (Chrome, VS Code, una foto,
3
+ * un lienzo) se manda como vídeo, pero solo ese rectángulo, no la pantalla entera.
4
+ *
5
+ * Captura y codifica `ffmpeg` (x11grab → H.264 baseline, sin cuadros B, con un AUD delante de
6
+ * cada cuadro para poder separarlos sin entender el resto del flujo). El navegador lo decodifica
7
+ * con WebCodecs, que viene en él. Medido el 2026-11-16: una ventana de 1426×896 a 15 cuadros por
8
+ * segundo son ~100 KB/s; un cuadro mediano, 2,8 KB; uno completo, ~63 KB. Y quieta, nada:
9
+ * los cuadros iguales se descartan antes de codificar.
10
+ *
11
+ * Solo X11. En Wayland la pantalla se pide por el portal del escritorio (PipeWire), que es otra
12
+ * pieza: hasta entonces se dice con su `code` (`no-video`) y el hueco se queda como recuadro.
13
+ */
14
+ import { spawn as nodeSpawn } from 'node:child_process'
15
+
16
+ export const FPS = 15
17
+ /** Un cuadro completo cada GOP cuadros CAMBIADOS (con la pantalla quieta no sale ninguno). */
18
+ export const GOP = FPS * 2
19
+ /** Lo más pequeño que vale la pena mandar en vídeo. */
20
+ export const MIN_SIDE = 32
21
+
22
+ const AUD = [0, 0, 0, 1, 9]
23
+ /** Sin datos durante esto, lo pendiente es un cuadro entero (ver `flush`). */
24
+ const IDLE_MS = 40
25
+
26
+ /** @type {(code: string, message: string) => Error & { code: string }} */
27
+ const fail = (code, message) => Object.assign(new Error(message), { code })
28
+
29
+ /**
30
+ * El rectángulo que se puede codificar: H.264 con 4:2:0 quiere lados pares, y dentro de la
31
+ * pantalla. `null` si queda demasiado pequeño para que valga la pena.
32
+ * @param {{ x: number, y: number, w: number, h: number }} r
33
+ * @param {{ w: number, h: number }} screen
34
+ */
35
+ export function evenRect (r, screen) {
36
+ const x = Math.max(0, Math.round(r.x)); const y = Math.max(0, Math.round(r.y))
37
+ let w = Math.min(Math.round(r.w), screen.w - x); let h = Math.min(Math.round(r.h), screen.h - y)
38
+ w -= w % 2; h -= h % 2
39
+ return w >= MIN_SIDE && h >= MIN_SIDE ? { x, y, w, h } : null
40
+ }
41
+
42
+ /**
43
+ * Parte un flujo H.264 Annex B en cuadros, por los AUD. Devuelve los cuadros completos y lo
44
+ * que sobra (el principio del siguiente), que hay que volver a pasar con lo que llegue después.
45
+ * @param {Uint8Array} buf
46
+ * @returns {{ frames: Uint8Array[], rest: Uint8Array }}
47
+ */
48
+ export function splitFrames (buf) {
49
+ /** @type {number[]} */
50
+ const starts = []
51
+ for (let i = 0; i + 4 < buf.length; i++) {
52
+ if (buf[i] === 0 && buf[i + 1] === 0 && buf[i + 2] === 0 && buf[i + 3] === 1 && (buf[i + 4] & 0x1f) === 9) starts.push(i)
53
+ }
54
+ /** @type {Uint8Array[]} */
55
+ const frames = []
56
+ for (let k = 0; k + 1 < starts.length; k++) frames.push(buf.subarray(starts[k], starts[k + 1]))
57
+ const rest = starts.length ? buf.subarray(starts[starts.length - 1]) : buf
58
+ return { frames, rest }
59
+ }
60
+
61
+ /** ¿Es un cuadro completo (lleva un IDR, NAL tipo 5)? @param {Uint8Array} f */
62
+ export function isKey (f) {
63
+ for (let i = 0; i + 3 < f.length; i++) {
64
+ if (f[i] === 0 && f[i + 1] === 0 && f[i + 2] === 1 && (f[i + 3] & 0x1f) === 5) return true
65
+ }
66
+ return false
67
+ }
68
+
69
+ /** Los argumentos de ffmpeg para ese rectángulo. @param {{ x: number, y: number, w: number, h: number }} r @param {string} display */
70
+ export function ffmpegArgs (r, display) {
71
+ return [
72
+ '-hide_banner', '-loglevel', 'error', '-nostdin',
73
+ '-f', 'x11grab', '-framerate', String(FPS), '-video_size', `${r.w}x${r.h}`, '-i', `${display}+${r.x},${r.y}`,
74
+ // SOLO LO QUE CAMBIA (dueño, 2026-11-16): mpdecimate tira los cuadros iguales al anterior
75
+ // ANTES de codificar, y con vfr no se rellenan. Una pantalla quieta no manda nada.
76
+ '-vf', 'mpdecimate', '-fps_mode', 'vfr',
77
+ '-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency', '-profile:v', 'baseline',
78
+ '-pix_fmt', 'yuv420p', '-g', String(GOP), '-bf', '0', '-x264-params', 'aud=1',
79
+ '-b:v', '800k', '-maxrate', '1200k', '-bufsize', '600k',
80
+ '-f', 'h264', '-'
81
+ ]
82
+ }
83
+
84
+ /**
85
+ * Un emisor de vídeo: UN rectángulo a la vez. `start` con otro rectángulo rehace la captura (la
86
+ * ventana se movió, o se mira otra), y el primer cuadro de cada captura es completo.
87
+ *
88
+ * @param {{ log?: (m: string) => void, spawn?: typeof nodeSpawn, session?: string, display?: string }} [o]
89
+ */
90
+ export function makeVideo ({ log = () => {}, spawn = nodeSpawn, session = process.env.XDG_SESSION_TYPE || '', display = process.env.DISPLAY || ':0' } = {}) {
91
+ /** @type {import('node:child_process').ChildProcess | null} */
92
+ let proc = null
93
+ let current = ''
94
+
95
+ function stop () {
96
+ current = ''
97
+ if (proc) { try { proc.kill('SIGKILL') } catch (_) {} proc = null }
98
+ }
99
+
100
+ /**
101
+ * @param {{ x: number, y: number, w: number, h: number }} r ya par y dentro de la pantalla (evenRect)
102
+ * @param {(f: { key: boolean, data: Uint8Array }) => void} onFrame
103
+ * @param {(e: Error & { code: string }) => void} onError
104
+ */
105
+ function start (r, onFrame, onError) {
106
+ if (session === 'wayland') { onError(fail('no-video', 'video of a window is X11 only for now')); return }
107
+ const key = `${r.x},${r.y},${r.w},${r.h}`
108
+ if (proc && key === current) return
109
+ stop()
110
+ current = key
111
+ const p = spawn('ffmpeg', ffmpegArgs(r, display), { stdio: ['ignore', 'pipe', 'pipe'] })
112
+ proc = p
113
+ let pending = new Uint8Array(0)
114
+ let errText = ''
115
+ /** @type {ReturnType<typeof setTimeout> | null} */
116
+ let idle = null
117
+ // Un cuadro se da por terminado cuando empieza el siguiente... y con la pantalla quieta no
118
+ // hay siguiente: el último se quedaba sin salir (también el primero). ffmpeg escribe cada
119
+ // cuadro de una vez, así que si en IDLE_MS no llega nada más, lo pendiente es un cuadro entero.
120
+ const flush = () => {
121
+ idle = null
122
+ if (pending.length > AUD.length && AUD.every((b, i) => pending[i] === b)) onFrame({ key: isKey(pending), data: pending })
123
+ pending = new Uint8Array(0)
124
+ }
125
+ p.stdout?.on('data', (/** @type {Buffer} */ chunk) => {
126
+ if (idle) { clearTimeout(idle); idle = null }
127
+ const joined = new Uint8Array(pending.length + chunk.length)
128
+ joined.set(pending); joined.set(chunk, pending.length)
129
+ const { frames, rest } = splitFrames(joined)
130
+ pending = rest.slice()
131
+ for (const f of frames) onFrame({ key: isKey(f), data: f.slice() })
132
+ if (proc === p) idle = setTimeout(flush, IDLE_MS)
133
+ })
134
+ p.stderr?.on('data', (/** @type {Buffer} */ d) => { errText = (errText + d.toString()).slice(-500) })
135
+ p.on('error', (e) => {
136
+ if (proc !== p) return
137
+ proc = null; current = ''
138
+ const err = /** @type {NodeJS.ErrnoException} */ (e)
139
+ onError(err.code === 'ENOENT' ? fail('no-video', 'ffmpeg is not installed on this machine') : fail('video-failed', err.message))
140
+ })
141
+ p.on('exit', (code) => {
142
+ if (proc !== p) return
143
+ proc = null; current = ''
144
+ if (code) { log(`video: ffmpeg exited ${code}: ${errText.trim()}`); onError(fail('video-failed', `ffmpeg exited with ${code}`)) }
145
+ })
146
+ }
147
+
148
+ return { start, stop, get running () { return !!proc } }
149
+ }
150
+