@aivin-labs/cli 1.0.51 → 1.0.57

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.
@@ -1,443 +1,483 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import readline from 'readline';
4
- import { createHash, randomBytes } from 'crypto';
5
- import { spawn } from 'child_process';
6
- import { REMOTE_CONFIG_DIR } from '../constants.mjs';
7
- import { DESKTOP_CAST_CSHARP, DESKTOP_CAST_PS1 } from './desktopCastSource.mjs';
8
-
9
- const CAST_DIR = path.join(REMOTE_CONFIG_DIR, 'desktop-cast');
10
-
11
- function hostFiles(dir = CAST_DIR) {
12
- const hash = createHash('sha256').update(DESKTOP_CAST_CSHARP).update(DESKTOP_CAST_PS1).digest('hex').slice(0, 16);
13
- fs.mkdirSync(dir, { recursive: true });
14
- const src = path.join(dir, `cast-${hash}.cs`);
15
- const ps1 = path.join(dir, `cast-${hash}.ps1`);
16
- if (!fs.existsSync(src)) fs.writeFileSync(src, DESKTOP_CAST_CSHARP);
17
- if (!fs.existsSync(ps1)) fs.writeFileSync(ps1, DESKTOP_CAST_PS1);
18
- for (const name of fs.readdirSync(dir)) {
19
- if (name.startsWith('cast-') && !name.startsWith(`cast-${hash}`)) fs.rmSync(path.join(dir, name), { force: true });
20
- }
21
- return { src, ps1, dll: path.join(dir, `cast-${hash}.dll`) };
22
- }
23
-
24
- /** Chờ tiến trình quay tự thoát sau "stop" (nhả phím / nút, thả pipe) trước khi giết. */
25
- export const STOP_GRACE_MS = 3000;
26
-
27
- const RAW_HEADER_BYTES = 12;
28
- const MAX_RAW_FRAME_BYTES = 64 * 1024 * 1024;
29
-
30
- /**
31
- * Tách luồng khung thô từ named pipe:
32
- * - Video: [rộng > 0, cao > 0, độ dài] int32 LE + dữ liệu I420.
33
- * - Audio: [rộng = -số_kênh < 0, cao = tần_số_lấy_mẫu, độ dài] int32 LE + dữ liệu PCM 16-bit LE.
34
- * Độ dài vô lý → `onCorrupt` (đóng pipe, không cố đồng bộ lại).
35
- */
36
- export function createRawFrameReader(onFrame, onCorrupt = () => {}, onAudio = () => {}) {
37
- const header = Buffer.alloc(RAW_HEADER_BYTES);
38
- let headerFilled = 0;
39
- let frame = null;
40
- let filled = 0;
41
- return (chunk) => {
42
- let pos = 0;
43
- while (pos < chunk.length) {
44
- if (!frame) {
45
- const n = chunk.copy(header, headerFilled, pos, pos + RAW_HEADER_BYTES - headerFilled);
46
- headerFilled += n;
47
- pos += n;
48
- if (headerFilled < RAW_HEADER_BYTES) return;
49
- headerFilled = 0;
50
- const width = header.readInt32LE(0);
51
- const height = header.readInt32LE(4);
52
- const length = header.readInt32LE(8);
53
- if (width < 0) {
54
- const channelCount = -width;
55
- const sampleRate = height;
56
- const bytesPerFrame = channelCount * 2;
57
- if ((channelCount !== 1 && channelCount !== 2) || sampleRate < 8000 || sampleRate > 96000 || sampleRate % 100 !== 0 || length <= 0 || length > 192000 || length % bytesPerFrame !== 0) {
58
- onCorrupt();
59
- return;
60
- }
61
- frame = { audio: true, sampleRate, channelCount, numberOfFrames: length / bytesPerFrame, data: new Uint8Array(length) };
62
- filled = 0;
63
- } else {
64
- if (width <= 0 || height <= 0 || length !== width * height * 1.5 || length > MAX_RAW_FRAME_BYTES) {
65
- onCorrupt();
66
- return;
67
- }
68
- // Vùng nhớ riêng cho từng khung (bộ mã hoá giữ tham chiếu), chép thẳng từng khúc: khúc pipe 64 KB, ghép dần cả khung ăn luồng chính ~9 ms.
69
- frame = { width, height, data: new Uint8ClampedArray(length) };
70
- filled = 0;
71
- }
72
- }
73
- const piece = chunk.subarray(pos, pos + frame.data.length - filled);
74
- frame.data.set(piece, filled);
75
- filled += piece.length;
76
- pos += piece.length;
77
- if (filled === frame.data.length) {
78
- const done = frame;
79
- frame = null;
80
- if (done.audio) {
81
- onAudio({
82
- samples: new Int16Array(done.data.buffer, done.data.byteOffset, done.data.byteLength / 2),
83
- sampleRate: done.sampleRate,
84
- bitsPerSample: 16,
85
- channelCount: done.channelCount,
86
- numberOfFrames: done.numberOfFrames,
87
- });
88
- } else {
89
- onFrame(done);
90
- }
91
- }
92
- }
93
- };
94
- }
95
-
96
- export function isDesktopCastSupported(platform = process.platform) {
97
- return platform === 'win32';
98
- }
99
-
100
- /**
101
- * Quản lý phiên phát hình ảnh và điều khiển máy tính từ xa.
102
- */
103
- export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } = {}) {
104
- let activeSession = null;
105
- let prewarming = null;
106
-
107
- /** Biên dịch sẵn DLL C# ở nền khi daemon khởi động để lần mở phiên đầu tiên không mất ~800 ms chờ csc. */
108
- function prewarm() {
109
- if (!isDesktopCastSupported() || prewarming || activeSession) return prewarming;
110
- let files;
111
- try { files = hostFiles(dir); } catch { return null; }
112
- if (fs.existsSync(files.dll)) return null;
113
- prewarming = new Promise((resolve) => {
114
- try {
115
- const proc = spawnImpl('powershell.exe', [
116
- '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', files.ps1,
117
- ], {
118
- env: {
119
- ...process.env,
120
- AIVIN_CAST_SRC: files.src,
121
- AIVIN_CAST_DLL: files.dll,
122
- AIVIN_CAST_COMPILE_ONLY: '1',
123
- },
124
- stdio: 'ignore',
125
- windowsHide: true,
126
- });
127
- proc.on('exit', () => { prewarming = null; resolve(true); });
128
- proc.on('error', () => { prewarming = null; resolve(false); });
129
- proc.unref?.();
130
- } catch {
131
- prewarming = null;
132
- resolve(false);
133
- }
134
- });
135
- return prewarming;
136
- }
137
-
138
- function start({
139
- sessionId,
140
- maxFps = 15,
141
- maxWidth = 1366,
142
- quality = 65,
143
- monitor = -1,
144
- onFrame,
145
- onMeta,
146
- onCursor,
147
- onCursorShape,
148
- onInputFocus,
149
- onPasteFailed,
150
- onDropRefused,
151
- onClipboard,
152
- onSecureDesktop,
153
- onCapture,
154
- rawPipe = false,
155
- inputTag = null,
156
- onReady,
157
- onError,
158
- onStop,
159
- } = {}) {
160
- if (activeSession) {
161
- stop();
162
- }
163
-
164
- if (!isDesktopCastSupported()) {
165
- onError?.(new Error('Desktop cast is currently supported on Windows only'));
166
- return null;
167
- }
168
-
169
- const files = hostFiles(dir);
170
- // Có nơi nhận khung thô (nguồn video WebRTC ở tiến trình con webrtcWorker.mjs) → tiến trình quay mở named pipe gửi I420; không thì chỉ JPEG.
171
- const pipeName = rawPipe ? `aivin-cast-${process.pid}-${randomBytes(6).toString('hex')}` : '';
172
- const argsJson = JSON.stringify({
173
- max_fps: maxFps,
174
- max_width: maxWidth,
175
- quality,
176
- monitor,
177
- ...(pipeName ? { pipe: pipeName } : {}),
178
- // Dấu bí mật của phiên trên thao tác bơm vào (humanInput.mjs) — chuỗi để không mất chính xác qua JSON.
179
- ...(Number.isSafeInteger(inputTag) && inputTag > 0 ? { input_tag: String(inputTag) } : {}),
180
- });
181
-
182
- const child = spawnImpl('powershell.exe', [
183
- '-NoProfile',
184
- '-NonInteractive',
185
- '-ExecutionPolicy',
186
- 'Bypass',
187
- '-File',
188
- files.ps1,
189
- ], {
190
- env: {
191
- ...process.env,
192
- AIVIN_CAST_SRC: files.src,
193
- AIVIN_CAST_DLL: files.dll,
194
- AIVIN_CAST_ARGS: argsJson,
195
- },
196
- windowsHide: true,
197
- });
198
-
199
- // Ghi vào stdin lúc tiến trình đang thoát (ống đã đóng) báo lỗi bất đồng bộ — không để thành lỗi không ai bắt.
200
- child.stdin?.on?.('error', () => {});
201
- let rl = readline.createInterface({ input: child.stdout });
202
- let packetSeq = 0;
203
-
204
- rl.on('line', (line) => {
205
- let msg;
206
- try {
207
- msg = JSON.parse(line);
208
- } catch {
209
- return;
210
- }
211
-
212
- if (msg.t === 'ready') {
213
- onReady?.(msg);
214
- } else if (msg.t === 'frame') {
215
- onFrame?.({
216
- sessionId: session.sessionId,
217
- seq: ++packetSeq,
218
- image: msg.image,
219
- width: msg.width,
220
- height: msg.height,
221
- screenWidth: msg.screenWidth,
222
- screenHeight: msg.screenHeight,
223
- screenX: msg.screenX,
224
- screenY: msg.screenY,
225
- monitor: msg.monitor,
226
- screens: msg.screens,
227
- ts: msg.ts,
228
- stats: msg.stats,
229
- ...(msg.secureDesktop ? { secureDesktop: true } : {}),
230
- });
231
- } else if (msg.t === 'meta') {
232
- onMeta?.({
233
- sessionId: session.sessionId,
234
- seq: ++packetSeq,
235
- width: msg.width,
236
- height: msg.height,
237
- screenWidth: msg.screenWidth,
238
- screenHeight: msg.screenHeight,
239
- screenX: msg.screenX,
240
- screenY: msg.screenY,
241
- monitor: msg.monitor,
242
- screens: msg.screens,
243
- ts: msg.ts,
244
- stats: msg.stats,
245
- ...(msg.secureDesktop ? { secureDesktop: true } : {}),
246
- });
247
- } else if (msg.t === 'cursor') {
248
- onCursor?.({ x: msg.x, y: msg.y, visible: msg.visible, shape: msg.shape });
249
- } else if (msg.t === 'cursor_shape') {
250
- onCursorShape?.({ id: msg.id, png: msg.png, hotX: msg.hotX, hotY: msg.hotY });
251
- } else if (msg.t === 'drop_refused') {
252
- onDropRefused?.();
253
- } else if (msg.t === 'paste_failed') {
254
- onPasteFailed?.();
255
- } else if (msg.t === 'input_focus') {
256
- onInputFocus?.({ editable: msg.editable === true });
257
- } else if (msg.t === 'clipboard') {
258
- if (typeof msg.text === 'string' && msg.text) onClipboard?.({ text: msg.text });
259
- } else if (msg.t === 'secure_desktop') {
260
- onSecureDesktop?.({ active: msg.active === true });
261
- } else if (msg.t === 'capture') {
262
- onCapture?.({ mode: msg.mode, reason: msg.reason });
263
- } else if (msg.t === 'error') {
264
- onError?.(new Error(msg.error || 'Desktop cast error'));
265
- }
266
- });
267
-
268
- child.on('error', (err) => {
269
- onError?.(err);
270
- if (activeSession === session) activeSession = null;
271
- });
272
-
273
- child.on('close', () => {
274
- if (activeSession === session) activeSession = null;
275
- onStop?.();
276
- });
277
-
278
- function sendInput(inputCmd) {
279
- if (!child.stdin || child.stdin.destroyed) return;
280
- try {
281
- const payload = JSON.stringify({ ...inputCmd, op: 'input' });
282
- child.stdin.write(payload + '\n');
283
- } catch {
284
- // bỏ qua lỗi ghi stdin nếu tiến trình đang đóng
285
- }
286
- }
287
-
288
- function config(configCmd) {
289
- if (!child.stdin || child.stdin.destroyed) return;
290
- try {
291
- const payload = JSON.stringify({ ...configCmd, op: 'config' });
292
- child.stdin.write(payload + '\n');
293
- } catch {
294
- // bỏ qua
295
- }
296
- }
297
-
298
- /** Bật / tắt nén JPEG (chỉ cần khi còn người xem chưa có video WebRTC). */
299
- let jpegOn = true;
300
- function setJpeg(on) {
301
- if (!pipeName || jpegOn === on) return;
302
- jpegOn = on;
303
- config({ jpeg: on });
304
- }
305
-
306
- /** Con trỏ lồng vào khung hình (mặc định) hay gửi riêng để FE tự vẽ. */
307
- let cursorInFrame = true;
308
- function setCursorInFrame(on) {
309
- if (cursorInFrame === on) return;
310
- cursorInFrame = on;
311
- config({ cursor: on });
312
- }
313
-
314
- /** Bật / tắt thu âm thanh hệ thống qua WASAPI loopback. */
315
- let audioOn = false;
316
- function setAudio(on) {
317
- const next = on !== false;
318
- if (!pipeName || audioOn === next) return;
319
- audioOn = next;
320
- config({ audio: next });
321
- }
322
-
323
- /** Gửi ngay một khung (người xem mới nối, màn hình đang đứng yên). */
324
- function refresh() {
325
- if (!child.stdin || child.stdin.destroyed) return;
326
- try { child.stdin.write(JSON.stringify({ op: 'refresh' }) + '\n'); } catch { /* đang đóng */ }
327
- }
328
-
329
- /**
330
- * Dừng: gửi "stop" (tiến trình bỏ thao tác còn xếp hàng, nhả phím / nút đang giữ rồi tự thoát). Chỉ giết khi quá `STOP_GRACE_MS` — giết
331
- * sớm (trước đây 500 ms) giữa lúc kéo thả / tổ hợp phím là nút chuột, Ctrl / Shift kẹt xuống trên máy (TerminateProcess bỏ qua `finally`).
332
- */
333
- let killTimer = null;
334
- child.on('close', () => clearTimeout(killTimer));
335
- function stop() {
336
- if (activeSession === session) activeSession = null;
337
- if (killTimer) return;
338
- try {
339
- if (child.stdin && !child.stdin.destroyed) {
340
- child.stdin.write('stop\n');
341
- child.stdin.end();
342
- }
343
- } catch {
344
- // bỏ qua
345
- }
346
- killTimer = setTimeout(() => {
347
- try {
348
- child.kill();
349
- } catch {
350
- // bỏ qua
351
- }
352
- }, STOP_GRACE_MS);
353
- killTimer.unref?.();
354
- }
355
-
356
- const session = {
357
- sessionId,
358
- child,
359
- sendInput,
360
- config,
361
- setJpeg,
362
- setCursorInFrame,
363
- setAudio,
364
- refresh,
365
- stop,
366
- pipeName,
367
- };
368
- activeSession = session;
369
-
370
- return activeSession;
371
- }
372
-
373
- function setSessionId(sessionId) {
374
- if (activeSession && sessionId) {
375
- activeSession.sessionId = sessionId;
376
- }
377
- }
378
-
379
- function sendInput(inputCmd) {
380
- if (activeSession) {
381
- activeSession.sendInput(inputCmd);
382
- }
383
- }
384
-
385
- function config(configCmd) {
386
- if (activeSession) {
387
- activeSession.config(configCmd);
388
- }
389
- }
390
-
391
- function stop() {
392
- if (activeSession) {
393
- activeSession.stop();
394
- activeSession = null;
395
- }
396
- }
397
-
398
- function setJpeg(on) {
399
- activeSession?.setJpeg(on);
400
- }
401
-
402
- function setCursorInFrame(on) {
403
- activeSession?.setCursorInFrame(on);
404
- }
405
-
406
- function setAudio(on) {
407
- activeSession?.setAudio(on);
408
- }
409
-
410
- function refresh() {
411
- activeSession?.refresh();
412
- }
413
-
414
- /** Tên named pipe khung thô của phiên đang phát (rỗng khi không bật `rawPipe`). */
415
- function pipeName() {
416
- return activeSession?.pipeName || '';
417
- }
418
-
419
- function isActive() {
420
- return activeSession !== null;
421
- }
422
-
423
- /** Mã phiên đang phát (BE đặt) — lệnh / thao tác mang mã khác bị bỏ. */
424
- function sessionId() {
425
- return activeSession?.sessionId || null;
426
- }
427
-
428
- return {
429
- prewarm,
430
- start,
431
- setSessionId,
432
- sessionId,
433
- sendInput,
434
- config,
435
- setJpeg,
436
- setCursorInFrame,
437
- setAudio,
438
- refresh,
439
- pipeName,
440
- stop,
441
- isActive,
442
- };
443
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import readline from 'readline';
4
+ import { createHash, randomBytes } from 'crypto';
5
+ import { spawn } from 'child_process';
6
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
7
+ import { DESKTOP_CAST_CSHARP, DESKTOP_CAST_PS1 } from './desktopCastSource.mjs';
8
+
9
+ /**
10
+ * Trả bộ con trỏ chuẩn của Windows (SPI_SETCURSORS). Tiến trình điều khiển ẩn con trỏ trên máy trong lúc người xem thao tác
11
+ * (SystemCursorHider) và tự trả khi dừng; lệnh này là lưới cuối khi tiến trình đó chết lúc con trỏ còn ẩn (12/11/2026).
12
+ */
13
+ export const RESTORE_SYSTEM_CURSORS_PS = "$sig = '[DllImport(\"user32.dll\")] public static extern bool SystemParametersInfo(uint a, uint b, System.IntPtr c, uint d);'; "
14
+ + "$t = Add-Type -MemberDefinition $sig -Name AivinCursorRestore -Namespace Aivin -PassThru; [void]$t::SystemParametersInfo(0x57, 0, [System.IntPtr]::Zero, 0)";
15
+
16
+ export function restoreSystemCursors(spawnImpl = spawn) {
17
+ try {
18
+ const proc = spawnImpl('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', RESTORE_SYSTEM_CURSORS_PS], { windowsHide: true, stdio: 'ignore' });
19
+ proc?.on?.('error', () => {});
20
+ } catch {
21
+ // không có powershell: tiến trình điều khiển đầu phiên sau cũng tự trả
22
+ }
23
+ }
24
+
25
+ const CAST_DIR = path.join(REMOTE_CONFIG_DIR, 'desktop-cast');
26
+
27
+ function hostFiles(dir = CAST_DIR) {
28
+ const hash = createHash('sha256').update(DESKTOP_CAST_CSHARP).update(DESKTOP_CAST_PS1).digest('hex').slice(0, 16);
29
+ fs.mkdirSync(dir, { recursive: true });
30
+ const src = path.join(dir, `cast-${hash}.cs`);
31
+ const ps1 = path.join(dir, `cast-${hash}.ps1`);
32
+ if (!fs.existsSync(src)) fs.writeFileSync(src, DESKTOP_CAST_CSHARP);
33
+ if (!fs.existsSync(ps1)) fs.writeFileSync(ps1, DESKTOP_CAST_PS1);
34
+ for (const name of fs.readdirSync(dir)) {
35
+ if (!name.startsWith('cast-') || name.startsWith(`cast-${hash}`)) continue;
36
+ // DLL bản cũ còn bị một tiến trình quay khác giữ (máy đang có phiên của bản CLI trước, tiến trình chưa thoát): Windows từ chối xoá
37
+ // (EPERM). Trước 12/11/2026 lỗi này làm hỏng cả lần mở phiên mới; nay bỏ qua, lần sau dọn.
38
+ try { fs.rmSync(path.join(dir, name), { force: true }); } catch { /* đang bị giữ */ }
39
+ }
40
+ return { src, ps1, dll: path.join(dir, `cast-${hash}.dll`) };
41
+ }
42
+
43
+ /** Chờ tiến trình quay tự thoát sau "stop" (nhả phím / nút, thả pipe) trước khi giết. */
44
+ export const STOP_GRACE_MS = 3000;
45
+
46
+ const RAW_HEADER_BYTES = 12;
47
+ const MAX_RAW_FRAME_BYTES = 64 * 1024 * 1024;
48
+
49
+ /**
50
+ * Tách luồng khung thô từ named pipe:
51
+ * - Video: [rộng > 0, cao > 0, độ dài] int32 LE + dữ liệu I420.
52
+ * - Audio: [rộng = -số_kênh < 0, cao = tần_số_lấy_mẫu, độ dài] int32 LE + dữ liệu PCM 16-bit LE.
53
+ * Độ dài vô lý → `onCorrupt` (đóng pipe, không cố đồng bộ lại).
54
+ */
55
+ export function createRawFrameReader(onFrame, onCorrupt = () => {}, onAudio = () => {}) {
56
+ const header = Buffer.alloc(RAW_HEADER_BYTES);
57
+ let headerFilled = 0;
58
+ let frame = null;
59
+ let filled = 0;
60
+ return (chunk) => {
61
+ let pos = 0;
62
+ while (pos < chunk.length) {
63
+ if (!frame) {
64
+ const n = chunk.copy(header, headerFilled, pos, pos + RAW_HEADER_BYTES - headerFilled);
65
+ headerFilled += n;
66
+ pos += n;
67
+ if (headerFilled < RAW_HEADER_BYTES) return;
68
+ headerFilled = 0;
69
+ const width = header.readInt32LE(0);
70
+ const height = header.readInt32LE(4);
71
+ const length = header.readInt32LE(8);
72
+ if (width < 0) {
73
+ const channelCount = -width;
74
+ const sampleRate = height;
75
+ const bytesPerFrame = channelCount * 2;
76
+ if ((channelCount !== 1 && channelCount !== 2) || sampleRate < 8000 || sampleRate > 96000 || sampleRate % 100 !== 0 || length <= 0 || length > 192000 || length % bytesPerFrame !== 0) {
77
+ onCorrupt();
78
+ return;
79
+ }
80
+ frame = { audio: true, sampleRate, channelCount, numberOfFrames: length / bytesPerFrame, data: new Uint8Array(length) };
81
+ filled = 0;
82
+ } else {
83
+ if (width <= 0 || height <= 0 || length !== width * height * 1.5 || length > MAX_RAW_FRAME_BYTES) {
84
+ onCorrupt();
85
+ return;
86
+ }
87
+ // Vùng nhớ riêng cho từng khung (bộ mã hoá giữ tham chiếu), chép thẳng từng khúc: khúc pipe 64 KB, ghép dần cả khung ăn luồng chính ~9 ms.
88
+ frame = { width, height, data: new Uint8ClampedArray(length) };
89
+ filled = 0;
90
+ }
91
+ }
92
+ const piece = chunk.subarray(pos, pos + frame.data.length - filled);
93
+ frame.data.set(piece, filled);
94
+ filled += piece.length;
95
+ pos += piece.length;
96
+ if (filled === frame.data.length) {
97
+ const done = frame;
98
+ frame = null;
99
+ if (done.audio) {
100
+ onAudio({
101
+ samples: new Int16Array(done.data.buffer, done.data.byteOffset, done.data.byteLength / 2),
102
+ sampleRate: done.sampleRate,
103
+ bitsPerSample: 16,
104
+ channelCount: done.channelCount,
105
+ numberOfFrames: done.numberOfFrames,
106
+ });
107
+ } else {
108
+ onFrame(done);
109
+ }
110
+ }
111
+ }
112
+ };
113
+ }
114
+
115
+ /**
116
+ * Lệnh ảnh mở màn cho tiến trình quay từ `lead_in` máy chủ gửi kèm lệnh mở phiên (`{ max_width, quality }`). Thiếu / sai thì `null`
117
+ * (máy chủ cũ, mạng chưa biết là tốt). Tiến trình quay tự kẹp lần nữa và không vượt màn hình thật.
118
+ */
119
+ export function castLeadInConfig(leadIn) {
120
+ const width = Number(leadIn?.max_width);
121
+ const quality = Number(leadIn?.quality ?? 80);
122
+ if (!Number.isInteger(width) || width < 640 || width > 2560 || !Number.isInteger(quality) || quality < 10 || quality > 95) return null;
123
+ return { lead_in_width: width, lead_in_quality: quality };
124
+ }
125
+
126
+ export function isDesktopCastSupported(platform = process.platform) {
127
+ return platform === 'win32';
128
+ }
129
+
130
+ /**
131
+ * Quản lý phiên phát hình ảnh và điều khiển máy tính từ xa.
132
+ */
133
+ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } = {}) {
134
+ let activeSession = null;
135
+ let prewarming = null;
136
+
137
+ /** Biên dịch sẵn DLL C# ở nền khi daemon khởi động để lần mở phiên đầu tiên không mất ~800 ms chờ csc. */
138
+ function prewarm() {
139
+ if (!isDesktopCastSupported() || prewarming || activeSession) return prewarming;
140
+ let files;
141
+ try { files = hostFiles(dir); } catch { return null; }
142
+ if (fs.existsSync(files.dll)) return null;
143
+ prewarming = new Promise((resolve) => {
144
+ try {
145
+ const proc = spawnImpl('powershell.exe', [
146
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', files.ps1,
147
+ ], {
148
+ env: {
149
+ ...process.env,
150
+ AIVIN_CAST_SRC: files.src,
151
+ AIVIN_CAST_DLL: files.dll,
152
+ AIVIN_CAST_COMPILE_ONLY: '1',
153
+ },
154
+ stdio: 'ignore',
155
+ windowsHide: true,
156
+ });
157
+ proc.on('exit', () => { prewarming = null; resolve(true); });
158
+ proc.on('error', () => { prewarming = null; resolve(false); });
159
+ proc.unref?.();
160
+ } catch {
161
+ prewarming = null;
162
+ resolve(false);
163
+ }
164
+ });
165
+ return prewarming;
166
+ }
167
+
168
+ function start({
169
+ sessionId,
170
+ maxFps = 15,
171
+ maxWidth = 1366,
172
+ quality = 65,
173
+ monitor = -1,
174
+ onFrame,
175
+ onMeta,
176
+ onCursor,
177
+ onCursorShape,
178
+ onInputFocus,
179
+ onPasteFailed,
180
+ onDropRefused,
181
+ onClipboard,
182
+ onSecureDesktop,
183
+ onCapture,
184
+ rawPipe = false,
185
+ inputTag = null,
186
+ onReady,
187
+ onError,
188
+ onStop,
189
+ } = {}) {
190
+ if (activeSession) {
191
+ stop();
192
+ }
193
+
194
+ if (!isDesktopCastSupported()) {
195
+ onError?.(new Error('Desktop cast is currently supported on Windows only'));
196
+ return null;
197
+ }
198
+
199
+ const files = hostFiles(dir);
200
+ // Có nơi nhận khung thô (nguồn video WebRTC ở tiến trình con webrtcWorker.mjs) → tiến trình quay mở named pipe gửi I420; không thì chỉ JPEG.
201
+ const pipeName = rawPipe ? `aivin-cast-${process.pid}-${randomBytes(6).toString('hex')}` : '';
202
+ const argsJson = JSON.stringify({
203
+ max_fps: maxFps,
204
+ max_width: maxWidth,
205
+ quality,
206
+ monitor,
207
+ ...(pipeName ? { pipe: pipeName } : {}),
208
+ // Dấu bí mật của phiên trên thao tác bơm vào (humanInput.mjs) — chuỗi để không mất chính xác qua JSON.
209
+ ...(Number.isSafeInteger(inputTag) && inputTag > 0 ? { input_tag: String(inputTag) } : {}),
210
+ });
211
+
212
+ const child = spawnImpl('powershell.exe', [
213
+ '-NoProfile',
214
+ '-NonInteractive',
215
+ '-ExecutionPolicy',
216
+ 'Bypass',
217
+ '-File',
218
+ files.ps1,
219
+ ], {
220
+ env: {
221
+ ...process.env,
222
+ AIVIN_CAST_SRC: files.src,
223
+ AIVIN_CAST_DLL: files.dll,
224
+ AIVIN_CAST_ARGS: argsJson,
225
+ },
226
+ windowsHide: true,
227
+ });
228
+
229
+ // Ghi vào stdin lúc tiến trình đang thoát (ống đã đóng) báo lỗi bất đồng bộ — không để thành lỗi không ai bắt.
230
+ child.stdin?.on?.('error', () => {});
231
+ let rl = readline.createInterface({ input: child.stdout });
232
+ let packetSeq = 0;
233
+ let cursorHidden = false;
234
+
235
+ rl.on('line', (line) => {
236
+ let msg;
237
+ try {
238
+ msg = JSON.parse(line);
239
+ } catch {
240
+ return;
241
+ }
242
+
243
+ if (msg.t === 'ready') {
244
+ onReady?.(msg);
245
+ } else if (msg.t === 'frame') {
246
+ onFrame?.({
247
+ sessionId: session.sessionId,
248
+ seq: ++packetSeq,
249
+ image: msg.image,
250
+ width: msg.width,
251
+ height: msg.height,
252
+ screenWidth: msg.screenWidth,
253
+ screenHeight: msg.screenHeight,
254
+ screenX: msg.screenX,
255
+ screenY: msg.screenY,
256
+ monitor: msg.monitor,
257
+ screens: msg.screens,
258
+ ts: msg.ts,
259
+ stats: msg.stats,
260
+ ...(msg.secureDesktop ? { secureDesktop: true } : {}),
261
+ ...(msg.lead_in ? { lead_in: true } : {}),
262
+ ...(msg.iseq ? { iseq: msg.iseq, iseq_ms: msg.iseq_ms } : {}),
263
+ });
264
+ } else if (msg.t === 'meta') {
265
+ onMeta?.({
266
+ sessionId: session.sessionId,
267
+ seq: ++packetSeq,
268
+ width: msg.width,
269
+ height: msg.height,
270
+ screenWidth: msg.screenWidth,
271
+ screenHeight: msg.screenHeight,
272
+ screenX: msg.screenX,
273
+ screenY: msg.screenY,
274
+ monitor: msg.monitor,
275
+ screens: msg.screens,
276
+ ts: msg.ts,
277
+ stats: msg.stats,
278
+ ...(msg.secureDesktop ? { secureDesktop: true } : {}),
279
+ ...(msg.iseq ? { iseq: msg.iseq, iseq_ms: msg.iseq_ms } : {}),
280
+ });
281
+ } else if (msg.t === 'cursor') {
282
+ onCursor?.({ x: msg.x, y: msg.y, visible: msg.visible, shape: msg.shape });
283
+ } else if (msg.t === 'cursor_shape') {
284
+ onCursorShape?.({ id: msg.id, png: msg.png, hotX: msg.hotX, hotY: msg.hotY });
285
+ } else if (msg.t === 'drop_refused') {
286
+ onDropRefused?.();
287
+ } else if (msg.t === 'paste_failed') {
288
+ onPasteFailed?.();
289
+ } else if (msg.t === 'input_focus') {
290
+ onInputFocus?.({ editable: msg.editable === true });
291
+ } else if (msg.t === 'cursor_hidden') {
292
+ cursorHidden = msg.hidden === true;
293
+ } else if (msg.t === 'clipboard') {
294
+ if (typeof msg.text === 'string' && msg.text) onClipboard?.({ text: msg.text });
295
+ } else if (msg.t === 'secure_desktop') {
296
+ onSecureDesktop?.({ active: msg.active === true });
297
+ } else if (msg.t === 'capture') {
298
+ onCapture?.({ mode: msg.mode, reason: msg.reason });
299
+ } else if (msg.t === 'error') {
300
+ onError?.(new Error(msg.error || 'Desktop cast error'));
301
+ }
302
+ });
303
+
304
+ child.on('error', (err) => {
305
+ onError?.(err);
306
+ if (activeSession === session) activeSession = null;
307
+ });
308
+
309
+ child.on('close', () => {
310
+ if (cursorHidden) {
311
+ cursorHidden = false;
312
+ restoreSystemCursors(spawnImpl);
313
+ }
314
+ if (activeSession === session) activeSession = null;
315
+ onStop?.();
316
+ });
317
+
318
+ function sendInput(inputCmd) {
319
+ if (!child.stdin || child.stdin.destroyed) return;
320
+ try {
321
+ const payload = JSON.stringify({ ...inputCmd, op: 'input' });
322
+ child.stdin.write(payload + '\n');
323
+ } catch {
324
+ // bỏ qua lỗi ghi stdin nếu tiến trình đang đóng
325
+ }
326
+ }
327
+
328
+ function config(configCmd) {
329
+ if (!child.stdin || child.stdin.destroyed) return;
330
+ try {
331
+ const payload = JSON.stringify({ ...configCmd, op: 'config' });
332
+ child.stdin.write(payload + '\n');
333
+ } catch {
334
+ // bỏ qua
335
+ }
336
+ }
337
+
338
+ /** Bật / tắt nén JPEG (chỉ cần khi còn người xem chưa có video WebRTC). */
339
+ let jpegOn = true;
340
+ function setJpeg(on) {
341
+ if (!pipeName || jpegOn === on) return;
342
+ jpegOn = on;
343
+ config({ jpeg: on });
344
+ }
345
+
346
+ /** Con trỏ lồng vào khung hình (mặc định) hay gửi riêng để FE tự vẽ. */
347
+ let cursorInFrame = true;
348
+ function setCursorInFrame(on) {
349
+ if (cursorInFrame === on) return;
350
+ cursorInFrame = on;
351
+ config({ cursor: on });
352
+ }
353
+
354
+ /** Bật / tắt thu âm thanh hệ thống qua WASAPI loopback. */
355
+ let audioOn = false;
356
+ function setAudio(on) {
357
+ const next = on !== false;
358
+ if (!pipeName || audioOn === next) return;
359
+ audioOn = next;
360
+ config({ audio: next });
361
+ }
362
+
363
+ /** Gửi ngay một khung (người xem mới nối, màn hình đang đứng yên). */
364
+ function refresh() {
365
+ if (!child.stdin || child.stdin.destroyed) return;
366
+ try { child.stdin.write(JSON.stringify({ op: 'refresh' }) + '\n'); } catch { /* đang đóng */ }
367
+ }
368
+
369
+ /**
370
+ * Dừng: gửi "stop" (tiến trình bỏ thao tác còn xếp hàng, nhả phím / nút đang giữ rồi tự thoát). Chỉ giết khi quá `STOP_GRACE_MS` — giết
371
+ * sớm (trước đây 500 ms) giữa lúc kéo thả / tổ hợp phím là nút chuột, Ctrl / Shift kẹt xuống trên máy (TerminateProcess bỏ qua `finally`).
372
+ */
373
+ let killTimer = null;
374
+ child.on('close', () => clearTimeout(killTimer));
375
+ function stop() {
376
+ if (activeSession === session) activeSession = null;
377
+ if (killTimer) return;
378
+ try {
379
+ if (child.stdin && !child.stdin.destroyed) {
380
+ child.stdin.write('stop\n');
381
+ child.stdin.end();
382
+ }
383
+ } catch {
384
+ // bỏ qua
385
+ }
386
+ killTimer = setTimeout(() => {
387
+ try {
388
+ child.kill();
389
+ } catch {
390
+ // bỏ qua
391
+ }
392
+ }, STOP_GRACE_MS);
393
+ killTimer.unref?.();
394
+ }
395
+
396
+ const session = {
397
+ sessionId,
398
+ child,
399
+ sendInput,
400
+ config,
401
+ setJpeg,
402
+ setCursorInFrame,
403
+ setAudio,
404
+ refresh,
405
+ stop,
406
+ pipeName,
407
+ };
408
+ activeSession = session;
409
+
410
+ return activeSession;
411
+ }
412
+
413
+ function setSessionId(sessionId) {
414
+ if (activeSession && sessionId) {
415
+ activeSession.sessionId = sessionId;
416
+ }
417
+ }
418
+
419
+ function sendInput(inputCmd) {
420
+ if (activeSession) {
421
+ activeSession.sendInput(inputCmd);
422
+ }
423
+ }
424
+
425
+ function config(configCmd) {
426
+ if (activeSession) {
427
+ activeSession.config(configCmd);
428
+ }
429
+ }
430
+
431
+ function stop() {
432
+ if (activeSession) {
433
+ activeSession.stop();
434
+ activeSession = null;
435
+ }
436
+ }
437
+
438
+ function setJpeg(on) {
439
+ activeSession?.setJpeg(on);
440
+ }
441
+
442
+ function setCursorInFrame(on) {
443
+ activeSession?.setCursorInFrame(on);
444
+ }
445
+
446
+ function setAudio(on) {
447
+ activeSession?.setAudio(on);
448
+ }
449
+
450
+ function refresh() {
451
+ activeSession?.refresh();
452
+ }
453
+
454
+ /** Tên named pipe khung thô của phiên đang phát (rỗng khi không bật `rawPipe`). */
455
+ function pipeName() {
456
+ return activeSession?.pipeName || '';
457
+ }
458
+
459
+ function isActive() {
460
+ return activeSession !== null;
461
+ }
462
+
463
+ /** Mã phiên đang phát (BE đặt) — lệnh / thao tác mang mã khác bị bỏ. */
464
+ function sessionId() {
465
+ return activeSession?.sessionId || null;
466
+ }
467
+
468
+ return {
469
+ prewarm,
470
+ start,
471
+ setSessionId,
472
+ sessionId,
473
+ sendInput,
474
+ config,
475
+ setJpeg,
476
+ setCursorInFrame,
477
+ setAudio,
478
+ refresh,
479
+ pipeName,
480
+ stop,
481
+ isActive,
482
+ };
483
+ }