@dotrino/remote-desktop-agent 0.2.0 → 0.3.1
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.
- package/desktop.js +25 -1
- package/index.js +70 -7
- package/package.json +2 -1
- package/raise.js +24 -6
- package/video.js +150 -0
package/desktop.js
CHANGED
|
@@ -46,6 +46,8 @@ export function makeDesktop (opts = {}) {
|
|
|
46
46
|
const watchers = new Set()
|
|
47
47
|
/** @type {Map<string, number>} el proceso de cada app, por su nombre en el bus */
|
|
48
48
|
const pids = new Map()
|
|
49
|
+
/** @type {Map<number, number>} el proceso de cada ventana sin accesibilidad (por su id de nodo) */
|
|
50
|
+
const synthPids = new Map()
|
|
49
51
|
/** @type {Set<string>} apps (su nombre en el bus) con algo nuevo */
|
|
50
52
|
const dirtyApps = new Set()
|
|
51
53
|
let fullDue = true
|
|
@@ -112,6 +114,8 @@ export function makeDesktop (opts = {}) {
|
|
|
112
114
|
// Cuál está activa lo dice el gestor de ventanas si se le puede preguntar: la accesibilidad
|
|
113
115
|
// la informa mal (una app de Electron se queda «activa» para siempre).
|
|
114
116
|
const real = await activeWindow()
|
|
117
|
+
/** @type {Node | null} la ventana activa cuando no publica accesibilidad */
|
|
118
|
+
let synth = null
|
|
115
119
|
if (real) {
|
|
116
120
|
for (const w of wins) {
|
|
117
121
|
let pid = pids.get(w.ref[0])
|
|
@@ -119,6 +123,13 @@ export function makeDesktop (opts = {}) {
|
|
|
119
123
|
w.active = pid === real.pid && w.name === real.title
|
|
120
124
|
}
|
|
121
125
|
wins.sort((a, b) => Number(a.active) - Number(b.active))
|
|
126
|
+
// UNA APP SIN ACCESIBILIDAD (la terminal de Dotrino, un juego) no sale en la lista: si es
|
|
127
|
+
// la activa, se enseña igual, como un hueco entero con su sitio y su título. Lleva vídeo.
|
|
128
|
+
if (!wins.some((w) => w.active) && real.w > 0 && real.h > 0) {
|
|
129
|
+
const id = reader.idOf([':x11', `/window/${real.window}`])
|
|
130
|
+
synthPids.set(id, real.pid)
|
|
131
|
+
synth = { id, p: 0, r: 'frame', n: real.title, x: real.x, y: real.y, w: real.w, h: real.h, s: 'a', hole: 1 }
|
|
132
|
+
}
|
|
122
133
|
}
|
|
123
134
|
const full = fullDue
|
|
124
135
|
fullDue = false
|
|
@@ -140,11 +151,13 @@ export function makeDesktop (opts = {}) {
|
|
|
140
151
|
/** @type {Node[]} */
|
|
141
152
|
const nodes = []
|
|
142
153
|
for (const w of wins) { const p = perWin.get(w.id); if (p) nodes.push(...p.nodes) }
|
|
154
|
+
if (synth) nodes.push(synth)
|
|
143
155
|
/** @type {Scene} */
|
|
144
156
|
const next = {
|
|
145
157
|
seq: scene.seq + 1,
|
|
146
158
|
screen: screenOf(wins),
|
|
147
|
-
wins: wins.map((w) => ({ id: w.id, app: w.app, name: w.name, active: w.active })),
|
|
159
|
+
wins: [...wins.map((w) => ({ id: w.id, app: w.app, name: w.name, active: w.active })),
|
|
160
|
+
...(synth ? [{ id: synth.id, app: synth.n || '', name: synth.n || '', active: true }] : [])],
|
|
148
161
|
nodes
|
|
149
162
|
}
|
|
150
163
|
const patch = diff(scene, next)
|
|
@@ -185,6 +198,17 @@ export function makeDesktop (opts = {}) {
|
|
|
185
198
|
get watching () { return watchers.size },
|
|
186
199
|
/** La escena de ahora (la última leída). */
|
|
187
200
|
get scene () { return scene },
|
|
201
|
+
/**
|
|
202
|
+
* El proceso de la app de un nodo: el de una ventana sin accesibilidad lo sabe el gestor de
|
|
203
|
+
* ventanas; el resto, el bus de accesibilidad.
|
|
204
|
+
* @param {number} id
|
|
205
|
+
*/
|
|
206
|
+
async pidOf (id) {
|
|
207
|
+
const p = synthPids.get(id)
|
|
208
|
+
if (p != null) return p
|
|
209
|
+
if (!reader) throw Object.assign(new Error('nobody is watching'), { code: 'not-watching' })
|
|
210
|
+
return reader.pidOf(id)
|
|
211
|
+
},
|
|
188
212
|
/** El lector, para actuar (clic, teclas). `null` si nadie mira. */
|
|
189
213
|
get reader () { return reader },
|
|
190
214
|
stop
|
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')
|
|
@@ -147,7 +203,7 @@ export function serveSession (session, desktop, { log = () => {} } = {}) {
|
|
|
147
203
|
if (!int(id)) return fail('bad-input', 'raise needs a window id')
|
|
148
204
|
const win = desktop.scene.wins.find((w) => w.id === id)
|
|
149
205
|
if (!win) return fail('window-not-found', `no window ${id} in the scene`)
|
|
150
|
-
await raiseWindow({ pid: await
|
|
206
|
+
await raiseWindow({ pid: await desktop.pidOf(id), title: win.name })
|
|
151
207
|
return
|
|
152
208
|
}
|
|
153
209
|
case 'key':
|
|
@@ -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, {
|
|
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.
|
|
3
|
+
"version": "0.3.1",
|
|
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/raise.js
CHANGED
|
@@ -50,19 +50,37 @@ export async function raiseWindow ({ pid, title, session = process.env.XDG_SESSI
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/**
|
|
53
|
-
* La ventana activa DE VERDAD, según el gestor de ventanas: `{ pid, title
|
|
54
|
-
* puede saber (Wayland, sin xdotool). La accesibilidad la informa mal: una app
|
|
55
|
-
* queda «activa» para siempre (visto el 2026-11-16 con dos ventanas activas a la
|
|
53
|
+
* La ventana activa DE VERDAD, según el gestor de ventanas: `{ pid, title, window, x, y, w, h }`,
|
|
54
|
+
* o `null` si no se puede saber (Wayland, sin xdotool). La accesibilidad la informa mal: una app
|
|
55
|
+
* de Electron se queda «activa» para siempre (visto el 2026-11-16 con dos ventanas activas a la
|
|
56
|
+
* vez), y una app sin accesibilidad (la terminal de Dotrino, hecha con iced) ni siquiera sale.
|
|
57
|
+
* Con la posición, el agente puede enseñar esa ventana como un hueco con vídeo.
|
|
56
58
|
* @param {{ session?: string, exec?: typeof run }} [o]
|
|
57
|
-
* @returns {Promise<{ pid: number, title: string } | null>}
|
|
59
|
+
* @returns {Promise<{ pid: number, title: string, window: string, x: number, y: number, w: number, h: number } | null>}
|
|
58
60
|
*/
|
|
59
61
|
export async function activeWindow ({ session = process.env.XDG_SESSION_TYPE || '', exec = run } = {}) {
|
|
60
62
|
if (session === 'wayland') return null
|
|
63
|
+
let out
|
|
61
64
|
try {
|
|
62
|
-
|
|
63
|
-
return pid.trim() ? { pid: Number(pid.trim()), title: title.trim() } : null
|
|
65
|
+
out = await exec('xdotool', ['getactivewindow', 'getwindowname', 'getwindowpid', 'getwindowgeometry', '--shell'])
|
|
64
66
|
} catch (_) {
|
|
65
67
|
// Sin xdotool, o sin ventana activa (el escritorio): no se sabe, y se usa la accesibilidad.
|
|
66
68
|
return null
|
|
67
69
|
}
|
|
70
|
+
return parseActive(out)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Lee lo que contesta `xdotool getactivewindow getwindowname getwindowpid getwindowgeometry --shell`.
|
|
75
|
+
* @param {string} out
|
|
76
|
+
*/
|
|
77
|
+
export function parseActive (out) {
|
|
78
|
+
const lines = out.split('\n')
|
|
79
|
+
const title = (lines[0] || '').trim()
|
|
80
|
+
const pid = Number((lines[1] || '').trim())
|
|
81
|
+
/** @type {Record<string, string>} */
|
|
82
|
+
const kv = {}
|
|
83
|
+
for (const l of lines.slice(2)) { const m = /^([A-Z]+)=(.*)$/.exec(l.trim()); if (m) kv[m[1]] = m[2] }
|
|
84
|
+
if (!pid || !kv.WINDOW) return null
|
|
85
|
+
return { pid, title, window: kv.WINDOW, x: Number(kv.X), y: Number(kv.Y), w: Number(kv.WIDTH), h: Number(kv.HEIGHT) }
|
|
68
86
|
}
|
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
|
+
|