@aivin-labs/cli 1.0.64 → 1.0.65

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,436 +1,479 @@
1
- /**
2
- * Desktop Cast WebRTC transport. Có `nonstandard.RTCVideoSource` (02/11/2026): hình đi video track — libwebrtc mã hoá VP8 liên khung, tự
3
- * chỉnh bitrate theo mạng; âm thanh hệ thống đi `nonstandard.RTCAudioSource` (Opus 48 kHz); kênh `aivin-desktop-frames` chỉ mang gói meta
4
- * (kích thước, màn hình) để FE quy đổi toạ độ. Không có: JPEG theo khung qua kênh dữ liệu không thứ tự (khung cũ không bao giờ xếp trước
5
- * khung mới). Quay màn hình + thu âm ở desktopCast.mjs; JPEG qua Socket.IO là đường lùi khi không có runtime native.
6
- */
7
-
8
- const MAX_BUFFERED_BYTES = 512 * 1024;
9
- /** Kênh thao tác chuột / phím người xem → máy: tin cậy + đúng thứ tự (nhả chuột không được đến trước nhấn), đi thẳng peer-to-peer. */
10
- export const INPUT_CHANNEL = 'aivin-desktop-input';
11
- const MAX_INPUT_MESSAGE_BYTES = 25 * 1024 * 1024;
12
- /** Kênh tệp người xem kéo thả / dán vào màn hình (castFileDrop.mjs): tin cậy + đúng thứ tự, tách khỏi kênh thao tác để tệp lớn không làm trễ chuột. */
13
- export const FILE_CHANNEL = 'aivin-desktop-files';
14
- const MAX_FILE_CHUNK_BYTES = 256 * 1024;
15
- /** Kênh riêng cho vị trí chuột: không gửi lại, không giữ thứ tự — mất một gói thì gói sau đè lên, không bắt các thao tác sau xếp hàng chờ như kênh tin cậy. */
16
- export const POINTER_CHANNEL = 'aivin-desktop-pointer';
17
- const MAX_POINTER_MESSAGE_BYTES = 512;
18
-
19
- const MAX_CURSOR_SHAPES = 64;
20
- /** Thử nối lại khi peer hỏng hẳn (`failed`): dựng peer mới, cùng người xem; hết lượt thì ở lại JPEG. Peer nối được thì đặt lại. */
21
- const RECONNECT_DELAYS_MS = [1000, 3000, 8000];
22
- /**
23
- * Báo người xem ước lượng băng thông của bộ gửi (`availableOutgoingBitrate`, kbps) theo nhịp này. FE dựa vào đó để lúc mở phiên nhảy thẳng
24
- * lên bậc nét mạng chịu được thay vì chờ QP: vài giây đầu QP còn ~105 cả trên mạng tốt, còn ước lượng lên trần sau ~2 s (đo trong máy
25
- * 11/11/2026); đường yếu thì ước lượng ở thấp, FE không nhảy.
26
- */
27
- const BWE_REPORT_MS = 1000;
28
-
29
- /** Ước lượng băng thông bộ gửi của cặp đường đang dùng (kbps), không có thì `null`. */
30
- export function outgoingBitrateKbps(report) {
31
- const stats = [];
32
- report?.forEach?.((s) => stats.push(s));
33
- const selected = stats.find(s => s.type === 'transport' && s.selectedCandidatePairId)?.selectedCandidatePairId;
34
- const pair = stats.find(s => s.type === 'candidate-pair' && s.id === selected && Number.isFinite(s.availableOutgoingBitrate))
35
- || stats.find(s => s.type === 'candidate-pair' && s.nominated && Number.isFinite(s.availableOutgoingBitrate));
36
- return pair && pair.availableOutgoingBitrate > 0 ? Math.round(pair.availableOutgoingBitrate / 1000) : null;
37
- }
38
-
39
- /**
40
- * Ghi băng thông video vào SDP answer (bên gửi đọc từ đây): mặc định libwebrtc trần ~2,5 Mbps, cuộn trang chữ 1440x810 chỉ còn ~7,5 khung/giây
41
- * (đo 03/11/2026). `{ start_kbps, min_kbps, max_kbps }` do BE gửi (`config/device_agent.json`); thiếu thì giữ nguyên SDP.
42
- */
43
- /**
44
- * Xếp codec hình trong offer theo `codecs` máy chủ gửi (vd `['AV1', 'VP8']`): người xem chọn codec đầu tiên trong danh sách mà nó giải mã được,
45
- * không được thì rơi về codec sau (Safari đời cũ không có AV1 → VP8). Đo 12/11/2026 (Chromium, đường giới hạn): AV1 cần khoảng nửa băng
46
- * thông VP8 ở cùng số khung/giây, đường 1 Mbps nét ở giây 3 thay vì 14; VP9 ở chế độ màn hình bị libwebrtc giới hạn 5 khung/giây nên không dùng.
47
- * Codec không có trong offer thì bỏ qua; danh sách rỗng thì giữ nguyên.
48
- */
49
- export function preferVideoCodecs(sdp, codecs) {
50
- if (!sdp || !Array.isArray(codecs) || !codecs.length) return sdp;
51
- const eol = sdp.includes('\r\n') ? '\r\n' : '\n';
52
- const lines = sdp.split(/\r?\n/);
53
- const wanted = [];
54
- for (const name of codecs) {
55
- if (typeof name !== 'string' || !/^[A-Za-z0-9]+$/.test(name)) continue;
56
- for (const line of lines) {
57
- const m = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line);
58
- if (m && m[2].toUpperCase() === name.toUpperCase() && !wanted.includes(m[1])) wanted.push(m[1]);
59
- }
60
- }
61
- if (!wanted.length) return sdp;
62
- return lines.map((line) => {
63
- if (!line.startsWith('m=video ')) return line;
64
- const parts = line.split(' ');
65
- const rest = parts.slice(3);
66
- return [...parts.slice(0, 3), ...wanted.filter((pt) => rest.includes(pt)), ...rest.filter((pt) => !wanted.includes(pt))].join(' ');
67
- }).join(eol);
68
- }
69
-
70
- export function withVideoBitrate(sdp, bitrate) {
71
- const params = [['x-google-start-bitrate', bitrate?.start_kbps], ['x-google-min-bitrate', bitrate?.min_kbps], ['x-google-max-bitrate', bitrate?.max_kbps]]
72
- .filter(([, v]) => Number.isFinite(v) && v > 0)
73
- .map(([k, v]) => `${k}=${Math.round(v)}`)
74
- .join(';');
75
- if (!params || typeof sdp !== 'string') return sdp;
76
- const eol = sdp.includes('\r\n') ? '\r\n' : '\n';
77
- const lines = sdp.split(eol);
78
- const out = [];
79
- for (const line of lines) {
80
- const vp8 = line.match(/^a=rtpmap:(\d+) VP8\/90000/i);
81
- out.push(line);
82
- if (!vp8) continue;
83
- const fmtp = lines.findIndex(l => l.startsWith(`a=fmtp:${vp8[1]} `));
84
- if (fmtp < 0) out.push(`a=fmtp:${vp8[1]} ${params}`);
85
- else lines[fmtp] = `${lines[fmtp]};${params}`;
86
- }
87
- return out.join(eol);
88
- }
89
-
90
- export function packDesktopFrame(frame) {
91
- const image = Buffer.from(String(frame?.image || ''), 'base64');
92
- const meta = Buffer.from(JSON.stringify({
93
- t: 'frame', sessionId: frame?.sessionId, seq: frame?.seq, ts: frame?.ts,
94
- width: frame?.width, height: frame?.height,
95
- screenWidth: frame?.screenWidth, screenHeight: frame?.screenHeight,
96
- screenX: frame?.screenX, screenY: frame?.screenY,
97
- monitor: frame?.monitor, screens: frame?.screens, stats: frame?.stats,
98
- ...(frame?.secureDesktop ? { secureDesktop: true } : {}),
99
- mime: 'image/jpeg', bytes: image.length,
100
- }) + '\n');
101
- return Buffer.concat([meta, image]);
102
- }
103
-
104
- export function unpackDesktopFrame(packet) {
105
- const buf = Buffer.isBuffer(packet) ? packet : Buffer.from(packet);
106
- const nl = buf.indexOf(0x0a);
107
- if (nl <= 0) return null;
108
- try {
109
- const meta = JSON.parse(buf.subarray(0, nl).toString('utf8'));
110
- const imageBytes = buf.subarray(nl + 1);
111
- return { meta, imageBytes, jpeg: imageBytes };
112
- } catch {
113
- return null;
114
- }
115
- }
116
-
117
- export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onFile = () => {}, onFileChunk = () => {}, onPeerReady = () => {}, onCursorMode = () => {}, loadRuntime } = {}) {
118
- const peers = new Map();
119
- /** Hình con trỏ đã thấy trong phiên — người xem nối sau vẫn nhận đủ (bộ quay chỉ gửi mỗi hình một lần). */
120
- const cursorShapes = new Map();
121
- let runtime = null;
122
- let sequence = 0;
123
- /**
124
- * Một nguồn video + một nguồn âm thanh dùng chung mọi người xem (một lần quay → nhiều track). Bẫy wrtc 0.10.0 (đo 02/11/2026): đã tạo
125
- * RTCVideoSource / RTCAudioSource thì tiến trình THOÁT TỰ NHIÊN (hết event loop) bị segfault lúc huỷ native — `process.exit()` thì sạch.
126
- * Daemon luôn thoát bằng `process.exit` (stopForGood / tín hiệu / tự cập nhật); thêm đường thoát mới phải giữ như vậy, không thì trình giữ chạy tưởng CLI sập.
127
- */
128
- let videoSource = null;
129
- let audioSource = null;
130
- // Không nhớ kết quả rỗng: runtime có thể vừa tải xong ở nền (webrtcRuntime.mjs) — phiên xem sau dùng được ngay, không cần khởi động lại.
131
- const load = async () => {
132
- if (runtime) return runtime;
133
- runtime = await (loadRuntime ? loadRuntime() : import('@roamhq/wrtc').catch(() => null));
134
- return runtime;
135
- };
136
-
137
- /** Peer hỏng hẳn: dựng lại sau một nhịp (BE chuyển offer mới, FE tự nối lại). Trong lúc chờ người xem nhận JPEG. */
138
- function scheduleReconnect(peer) {
139
- if (peer.retryTimer || peer.attempt >= RECONNECT_DELAYS_MS.length) return;
140
- peer.retryTimer = setTimeout(() => {
141
- if (peers.get(peer.viewerId) !== peer) return;
142
- start({ sessionId: peer.sessionId, viewerId: peer.viewerId, iceServers: peer.iceServers, videoBitrate: peer.videoBitrate, videoCodecs: peer.videoCodecs, audio: peer.audioEnabled, attempt: peer.attempt + 1 }).catch(() => false);
143
- }, RECONNECT_DELAYS_MS[peer.attempt]);
144
- peer.retryTimer.unref?.();
145
- }
146
-
147
- async function start({ sessionId, viewerId, iceServers = [], videoBitrate = null, videoCodecs = null, audio = true, attempt = 0 }) {
148
- close(viewerId);
149
- const wrtc = await load();
150
- const RTCPeerConnection = wrtc?.RTCPeerConnection || wrtc?.default?.RTCPeerConnection;
151
- if (!RTCPeerConnection) return false;
152
- const pc = new RTCPeerConnection({ iceServers });
153
- const channel = pc.createDataChannel('aivin-desktop-frames', { ordered: false, maxRetransmits: 0 });
154
- const inputChannel = pc.createDataChannel(INPUT_CHANNEL, { ordered: true });
155
- const fileChannel = pc.createDataChannel(FILE_CHANNEL, { ordered: true });
156
- const pointerChannel = pc.createDataChannel(POINTER_CHANNEL, { ordered: false, maxRetransmits: 0 });
157
- const VideoSource = wrtc?.nonstandard?.RTCVideoSource || wrtc?.default?.nonstandard?.RTCVideoSource;
158
- const AudioSource = wrtc?.nonstandard?.RTCAudioSource || wrtc?.default?.nonstandard?.RTCAudioSource;
159
- const MediaStream = wrtc?.MediaStream || wrtc?.default?.MediaStream;
160
- if (VideoSource && !videoSource) videoSource = new VideoSource({ isScreencast: true });
161
- if (AudioSource && !audioSource) audioSource = new AudioSource();
162
- const track = videoSource ? videoSource.createTrack() : null;
163
- const audioTrack = audioSource && audio !== false ? audioSource.createTrack() : null;
164
- const stream = MediaStream && (track || audioTrack) ? new MediaStream([track, audioTrack].filter(Boolean)) : null;
165
- if (track) stream ? pc.addTrack(track, stream) : pc.addTrack(track);
166
- if (audioTrack) stream ? pc.addTrack(audioTrack, stream) : pc.addTrack(audioTrack);
167
- const peer = {
168
- pc, channel, inputChannel, fileChannel, pointerChannel, pointerSeq: 0,
169
- track, video: !!track,
170
- audioTrack, audio: !!audioTrack, audioEnabled: audio !== false,
171
- sessionId, viewerId, iceServers, videoBitrate, videoCodecs, attempt, retryTimer: null, bweTimer: null, open: false, dropped: 0,
172
- };
173
- fileChannel.binaryType = 'arraybuffer';
174
- fileChannel.onmessage = ({ data }) => {
175
- if (typeof data !== 'string') {
176
- const bytes = Buffer.from(data);
177
- if (bytes.length <= MAX_FILE_CHUNK_BYTES) onFileChunk(viewerId, bytes);
178
- return;
179
- }
180
- if (data.length > MAX_INPUT_MESSAGE_BYTES) return;
181
- let msg;
182
- try { msg = JSON.parse(data); } catch { return; }
183
- // Mã phiên lấy từ peer như kênh thao tác.
184
- onFile(viewerId, msg, peer.sessionId);
185
- };
186
- inputChannel.onmessage = ({ data }) => {
187
- const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
188
- if (text.length > MAX_INPUT_MESSAGE_BYTES) return;
189
- let msg;
190
- try { msg = JSON.parse(text); } catch { return; }
191
- if (msg?.control === 'cursor') {
192
- peer.localCursor = msg.local === true;
193
- if (peer.localCursor) for (const shape of cursorShapes.values()) sendShape(peer, shape);
194
- onCursorMode();
195
- return;
196
- }
197
- if (msg?.control === 'audio') {
198
- peer.audioEnabled = msg.enabled !== false && msg.muted !== true;
199
- if (peer.audioTrack) peer.audioTrack.enabled = peer.audioEnabled;
200
- onCursorMode();
201
- return;
202
- }
203
- if (msg?.control === 'clipboard') {
204
- if (typeof msg.text === 'string' && msg.text) {
205
- onInput({ action: msg.paste === true ? 'paste' : 'clipboard', text: msg.text, session_id: peer.sessionId }, viewerId);
206
- }
207
- return;
208
- }
209
- // Mã phiên lấy từ peer (đã gắn lúc BE mời), không tin mã trong gói.
210
- onInput({ ...msg, session_id: peer.sessionId }, viewerId);
211
- };
212
- pointerChannel.onmessage = ({ data }) => {
213
- const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
214
- if (text.length > MAX_POINTER_MESSAGE_BYTES) return;
215
- let msg;
216
- try { msg = JSON.parse(text); } catch { return; }
217
- // Chỉ nhận di chuột: nhấn, nhả, phím phải đi kênh tin cậy. Gói đến muộn hơn gói mới nhất thì bỏ.
218
- if (msg?.action !== 'move' || !(msg.n > peer.pointerSeq)) return;
219
- peer.pointerSeq = msg.n;
220
- const { n: _n, ...cmd } = msg;
221
- onInput({ ...cmd, session_id: peer.sessionId }, viewerId);
222
- };
223
- peers.set(viewerId, peer);
224
- channel.binaryType = 'arraybuffer';
225
- const reportBwe = async () => {
226
- if (!peer.open || inputChannel.readyState !== 'open') return;
227
- const kbps = outgoingBitrateKbps(await pc.getStats().catch(() => null));
228
- if (kbps === null || peers.get(viewerId) !== peer || inputChannel.readyState !== 'open') return;
229
- try { inputChannel.send(JSON.stringify({ t: 'bwe', kbps })); } catch { /* kênh vừa đóng */ }
230
- };
231
- const markConnected = () => {
232
- peer.open = true;
233
- peer.attempt = 0;
234
- if (peer.video && !peer.bweTimer) {
235
- peer.bweTimer = setInterval(() => { void reportBwe(); }, BWE_REPORT_MS);
236
- peer.bweTimer.unref?.();
237
- }
238
- emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'connected', transport: 'webrtc', video: peer.video, audio: peer.audio });
239
- onPeerReady(viewerId);
240
- };
241
- channel.onopen = markConnected;
242
- // Kênh đóng trước khi peer báo `failed` (chạy thật: ~19 s): báo ngay để BE gửi JPEG, không để người xem đứng hình trong lúc đó.
243
- channel.onclose = () => {
244
- const wasOpen = peer.open;
245
- peer.open = false;
246
- if (wasOpen && peers.get(viewerId) === peer) emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'disconnected', transport: 'jpeg' });
247
- };
248
- pc.onicecandidate = ({ candidate }) => {
249
- emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'ice', candidate: candidate?.toJSON?.() || candidate || null });
250
- };
251
- pc.onconnectionstatechange = () => {
252
- if (peers.get(viewerId) !== peer) return;
253
- const state = pc.connectionState;
254
- if (['failed', 'closed', 'disconnected'].includes(state)) {
255
- const wasOpen = peer.open;
256
- peer.open = false;
257
- if (wasOpen || state !== 'disconnected') emitStatus({ session_id: sessionId, viewer_id: viewerId, state, transport: 'jpeg' });
258
- if (state === 'failed') scheduleReconnect(peer);
259
- } else if (state === 'connected' && !peer.open && channel.readyState === 'open') {
260
- // Mạng chập chờn: `disconnected` tự hồi về `connected` nhưng kênh không mở lại (onopen không chạy lần nữa) — không có nhánh này là kẹt JPEG.
261
- markConnected();
262
- }
263
- };
264
- const offer = await pc.createOffer();
265
- await pc.setLocalDescription({ type: 'offer', sdp: preferVideoCodecs(offer.sdp, videoCodecs) });
266
- emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'offer', sdp: pc.localDescription?.sdp, ice_servers: iceServers });
267
- return true;
268
- }
269
-
270
- async function signal(msg) {
271
- const peer = peers.get(String(msg?.viewer_id || ''));
272
- if (!peer || msg?.session_id !== peer.sessionId) return false;
273
- if (msg.type === 'answer' && msg.sdp) {
274
- await peer.pc.setRemoteDescription({ type: 'answer', sdp: withVideoBitrate(msg.sdp, peer.videoBitrate) });
275
- return true;
276
- }
277
- if (msg.type === 'ice') {
278
- await peer.pc.addIceCandidate(msg.candidate || null).catch(() => {});
279
- return true;
280
- }
281
- return false;
282
- }
283
-
284
- /** JPEG cho người xem chưa có video; người có video chỉ nhận gói meta (không ảnh). */
285
- function push(frame) {
286
- const packet = packDesktopFrame({ ...frame, seq: ++sequence });
287
- const metaPacket = packDesktopFrame({ ...frame, image: '', seq: sequence });
288
- let sent = 0;
289
- for (const peer of peers.values()) {
290
- if (!peer.open || peer.channel.readyState !== 'open') continue;
291
- if (peer.video) {
292
- try { peer.channel.send(metaPacket); } catch { /* kênh vừa đóng */ }
293
- continue;
294
- }
295
- if (peer.channel.bufferedAmount > MAX_BUFFERED_BYTES) { peer.dropped++; continue; }
296
- try { peer.channel.send(packet); sent++; } catch { peer.dropped++; }
297
- }
298
- return sent;
299
- }
300
-
301
- function sendShape(peer, shape) {
302
- if (peer.inputChannel?.readyState !== 'open') return;
303
- try { peer.inputChannel.send(JSON.stringify({ t: 'cursor_shape', ...shape })); } catch { /* kênh vừa đóng */ }
304
- }
305
-
306
- /** Vị trí con trỏ: kênh không gửi lại — mất một gói thì gói sau đè lên. Chỉ tới người xem đã báo tự vẽ con trỏ. */
307
- function pushCursor(cursor) {
308
- const packet = Buffer.from(JSON.stringify({ t: 'cursor', ...cursor }) + '\n');
309
- for (const peer of peers.values()) {
310
- if (!peer.localCursor || !peer.open || peer.channel.readyState !== 'open') continue;
311
- try { peer.channel.send(packet); } catch { /* kênh vừa đóng */ }
312
- }
313
- }
314
-
315
- /** Hình con trỏ: kênh tin cậy (kênh thao tác) vì chỉ gửi một lần. */
316
- function pushCursorShape(shape) {
317
- if (cursorShapes.size >= MAX_CURSOR_SHAPES) cursorShapes.delete(cursorShapes.keys().next().value);
318
- cursorShapes.set(shape.id, shape);
319
- for (const peer of peers.values()) if (peer.localCursor) sendShape(peer, shape);
320
- }
321
-
322
- /** Ô đang có tiêu điểm trên máy có phải ô nhập chữ không (sau cú nhấp của người xem) — trình duyệt điện thoại tự mở / đóng bàn phím ảo. */
323
- function pushInputFocus(focus) {
324
- const packet = JSON.stringify({ t: 'input_focus', editable: focus?.editable === true });
325
- for (const peer of peers.values()) {
326
- if (peer.inputChannel?.readyState !== 'open') continue;
327
- try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
328
- }
329
- }
330
-
331
- /** Nội dung Clipboard văn bản mới trên máy từ xa → gửi qua kênh điều khiển cho trình duyệt người xem. */
332
- function pushClipboard(clip) {
333
- const text = typeof clip?.text === 'string' ? clip.text : '';
334
- if (!text) return;
335
- const packet = JSON.stringify({ t: 'clipboard', text });
336
- for (const peer of peers.values()) {
337
- if (peer.inputChannel?.readyState !== 'open') continue;
338
- try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
339
- }
340
- }
341
-
342
- /** Báo máy từ xa vừa vào / thoát vùng màn hình bảo mật Windows (hộp thoại quyền quản trị UAC hoặc màn hình khóa). */
343
- function pushSecureDesktop(sec) {
344
- const packet = JSON.stringify({ t: 'secure_desktop', active: sec?.active === true });
345
- for (const peer of peers.values()) {
346
- if (peer.inputChannel?.readyState !== 'open') continue;
347
- try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
348
- }
349
- }
350
-
351
- /** Trả lời đúng người xem đang gửi tệp. */
352
- function replyFile(viewerId, msg) {
353
- const channel = peers.get(String(viewerId || ''))?.fileChannel;
354
- if (channel?.readyState !== 'open') return;
355
- try { channel.send(JSON.stringify(msg)); } catch { /* kênh vừa đóng */ }
356
- }
357
-
358
- /** Mọi người xem đều có video và tự vẽ con trỏ → bộ quay thôi lồng con trỏ vào khung. */
359
- function localCursor() {
360
- return peers.size > 0 && [...peers.values()].every(p => p.video && p.open && p.localCursor);
361
- }
362
-
363
- /** Khung thô I420 từ tiến trình quay → nguồn video (mọi track cùng nguồn). */
364
- function pushRaw(frame) {
365
- if (!videoSource || ![...peers.values()].some(p => p.video && p.open)) return false;
366
- try { videoSource.onFrame(frame); return true; } catch { return false; }
367
- }
368
-
369
- /** Khung âm thanh PCM 16-bit 10 ms từ tiến trình quay → nguồn âm thanh (mọi track cùng nguồn). */
370
- function pushAudio(audio) {
371
- if (!audioSource || !needsAudio()) return false;
372
- const sampleRate = audio?.sampleRate || 48000;
373
- const channelCount = audio?.channelCount || 2;
374
- const framesPer10ms = Math.floor(sampleRate / 100);
375
- const samplesPer10ms = framesPer10ms * channelCount;
376
- const samples = audio?.samples;
377
- if (!samples || samples.length < samplesPer10ms) return false;
378
- try {
379
- for (let off = 0; off + samplesPer10ms <= samples.length; off += samplesPer10ms) {
380
- const chunk = off === 0 && samples.length === samplesPer10ms ? samples : samples.subarray(off, off + samplesPer10ms);
381
- audioSource.onData({
382
- samples: chunk,
383
- sampleRate,
384
- bitsPerSample: audio.bitsPerSample || 16,
385
- channelCount,
386
- numberOfFrames: framesPer10ms,
387
- });
388
- }
389
- return true;
390
- } catch {
391
- return false;
392
- }
393
- }
394
-
395
- /** Còn người xem cần âm thanh (đã nối WebRTC + có audio track + chưa tắt tiếng). */
396
- function needsAudio() { return [...peers.values()].some(p => p.audio && p.open && p.audioEnabled !== false); }
397
- function hasAudio() { return [...peers.values()].some(p => p.audio); }
398
-
399
- /** Bật / tắt âm thanh cho toàn bộ người xem trong phiên. */
400
- function setAudio(enabled) {
401
- const next = enabled !== false;
402
- for (const peer of peers.values()) {
403
- peer.audioEnabled = next;
404
- if (peer.audioTrack) peer.audioTrack.enabled = next;
405
- }
406
- onCursorMode();
407
- }
408
-
409
- /** Còn người xem cần ảnh JPEG (chưa nối WebRTC, hoặc nối nhưng không có video). */
410
- function needsJpeg() { return needsFallback() || [...peers.values()].some(p => !p.video); }
411
- function hasVideo() { return [...peers.values()].some(p => p.video); }
412
-
413
- function anyOpen() { return [...peers.values()].some(p => p.open && p.channel.readyState === 'open'); }
414
- function needsFallback() { return peers.size === 0 || [...peers.values()].some(p => !p.open || p.channel.readyState !== 'open'); }
415
-
416
- function close(viewerId) {
417
- const peer = peers.get(String(viewerId || ''));
418
- if (!peer) return;
419
- peers.delete(String(viewerId));
420
- clearTimeout(peer.retryTimer);
421
- clearInterval(peer.bweTimer);
422
- try { peer.channel.close(); } catch { /* already closed */ }
423
- try { peer.inputChannel?.close(); } catch { /* already closed */ }
424
- try { peer.fileChannel?.close(); } catch { /* already closed */ }
425
- try { peer.pointerChannel?.close(); } catch { /* already closed */ }
426
- try { peer.track?.stop(); } catch { /* already stopped */ }
427
- try { peer.audioTrack?.stop(); } catch { /* already stopped */ }
428
- try { peer.pc.close(); } catch { /* already closed */ }
429
- }
430
-
431
- function closeAll() { for (const id of [...peers.keys()]) close(id); cursorShapes.clear(); }
432
- return {
433
- start, signal, push, pushRaw, pushAudio, pushCursor, pushCursorShape, pushInputFocus, pushClipboard, pushSecureDesktop, replyFile,
434
- localCursor, needsJpeg, hasVideo, needsAudio, hasAudio, setAudio, anyOpen, needsFallback, close, closeAll,
435
- };
436
- }
1
+ import os from 'os';
2
+ /**
3
+ * Desktop Cast WebRTC transport. Có `nonstandard.RTCVideoSource` (02/11/2026): hình đi video track — libwebrtc mã hoá VP8 liên khung, tự
4
+ * chỉnh bitrate theo mạng; âm thanh hệ thống đi `nonstandard.RTCAudioSource` (Opus 48 kHz); kênh `aivin-desktop-frames` chỉ mang gói meta
5
+ * (kích thước, màn hình) để FE quy đổi toạ độ. Không có: JPEG theo khung qua kênh dữ liệu không thứ tự (khung cũ không bao giờ xếp trước
6
+ * khung mới). Quay màn hình + thu âm ở desktopCast.mjs; JPEG qua Socket.IO là đường lùi khi không có runtime native.
7
+ */
8
+
9
+ const MAX_BUFFERED_BYTES = 512 * 1024;
10
+ /** Kênh thao tác chuột / phím người xem → máy: tin cậy + đúng thứ tự (nhả chuột không được đến trước nhấn), đi thẳng peer-to-peer. */
11
+ export const INPUT_CHANNEL = 'aivin-desktop-input';
12
+ const MAX_INPUT_MESSAGE_BYTES = 25 * 1024 * 1024;
13
+ /** Kênh tệp người xem kéo thả / dán vào màn hình (castFileDrop.mjs): tin cậy + đúng thứ tự, tách khỏi kênh thao tác để tệp lớn không làm trễ chuột. */
14
+ export const FILE_CHANNEL = 'aivin-desktop-files';
15
+ const MAX_FILE_CHUNK_BYTES = 256 * 1024;
16
+ /** Kênh riêng cho vị trí chuột: không gửi lại, không giữ thứ tự — mất một gói thì gói sau đè lên, không bắt các thao tác sau xếp hàng chờ như kênh tin cậy. */
17
+ export const POINTER_CHANNEL = 'aivin-desktop-pointer';
18
+ const MAX_POINTER_MESSAGE_BYTES = 512;
19
+
20
+ const MAX_CURSOR_SHAPES = 64;
21
+ /** Thử nối lại khi peer hỏng hẳn (`failed`): dựng peer mới, cùng người xem; hết lượt thì ở lại JPEG. Peer nối được thì đặt lại. */
22
+ const RECONNECT_DELAYS_MS = [1000, 3000, 8000];
23
+ /**
24
+ * Báo người xem ước lượng băng thông của bộ gửi (`availableOutgoingBitrate`, kbps) theo nhịp này. FE dựa vào đó để lúc mở phiên nhảy thẳng
25
+ * lên bậc nét mạng chịu được thay vì chờ QP: vài giây đầu QP còn ~105 cả trên mạng tốt, còn ước lượng lên trần sau ~2 s (đo trong máy
26
+ * 11/11/2026); đường yếu thì ước lượng ở thấp, FE không nhảy.
27
+ */
28
+ const BWE_REPORT_MS = 1000;
29
+
30
+ /** Ước lượng băng thông bộ gửi của cặp đường đang dùng (kbps), không có thì `null`. */
31
+ export function outgoingBitrateKbps(report) {
32
+ const stats = [];
33
+ report?.forEach?.((s) => stats.push(s));
34
+ const selected = stats.find(s => s.type === 'transport' && s.selectedCandidatePairId)?.selectedCandidatePairId;
35
+ const pair = stats.find(s => s.type === 'candidate-pair' && s.id === selected && Number.isFinite(s.availableOutgoingBitrate))
36
+ || stats.find(s => s.type === 'candidate-pair' && s.nominated && Number.isFinite(s.availableOutgoingBitrate));
37
+ return pair && pair.availableOutgoingBitrate > 0 ? Math.round(pair.availableOutgoingBitrate / 1000) : null;
38
+ }
39
+
40
+ /**
41
+ * Ghi băng thông video vào SDP answer (bên gửi đọc từ đây): mặc định libwebrtc trần ~2,5 Mbps, cuộn trang chữ 1440x810 chỉ còn ~7,5 khung/giây
42
+ * (đo 03/11/2026). `{ start_kbps, min_kbps, max_kbps }` do BE gửi (`config/device_agent.json`); thiếu thì giữ nguyên SDP.
43
+ */
44
+ /**
45
+ * Xếp codec hình trong offer theo `codecs` máy chủ gửi (vd `['AV1', 'VP8']`): người xem chọn codec đầu tiên trong danh sách mà nó giải mã được,
46
+ * không được thì rơi về codec sau (Safari đời cũ không có AV1 → VP8). Đo 12/11/2026 (Chromium, đường giới hạn): AV1 cần khoảng nửa băng
47
+ * thông VP8 ở cùng số khung/giây, đường 1 Mbps nét ở giây 3 thay vì 14; VP9 ở chế độ màn hình bị libwebrtc giới hạn 5 khung/giây nên không dùng.
48
+ * Codec không có trong offer thì bỏ qua; danh sách rỗng thì giữ nguyên.
49
+ */
50
+ export function preferVideoCodecs(sdp, codecs) {
51
+ if (!sdp || !Array.isArray(codecs) || !codecs.length) return sdp;
52
+ const eol = sdp.includes('\r\n') ? '\r\n' : '\n';
53
+ const lines = sdp.split(/\r?\n/);
54
+ const wanted = [];
55
+ for (const name of codecs) {
56
+ if (typeof name !== 'string' || !/^[A-Za-z0-9]+$/.test(name)) continue;
57
+ for (const line of lines) {
58
+ const m = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line);
59
+ if (m && m[2].toUpperCase() === name.toUpperCase() && !wanted.includes(m[1])) wanted.push(m[1]);
60
+ }
61
+ }
62
+ if (!wanted.length) return sdp;
63
+ return lines.map((line) => {
64
+ if (!line.startsWith('m=video ')) return line;
65
+ const parts = line.split(' ');
66
+ const rest = parts.slice(3);
67
+ return [...parts.slice(0, 3), ...wanted.filter((pt) => rest.includes(pt)), ...rest.filter((pt) => !wanted.includes(pt))].join(' ');
68
+ }).join(eol);
69
+ }
70
+
71
+ export function withVideoBitrate(sdp, bitrate) {
72
+ const params = [['x-google-start-bitrate', bitrate?.start_kbps], ['x-google-min-bitrate', bitrate?.min_kbps], ['x-google-max-bitrate', bitrate?.max_kbps]]
73
+ .filter(([, v]) => Number.isFinite(v) && v > 0)
74
+ .map(([k, v]) => `${k}=${Math.round(v)}`)
75
+ .join(';');
76
+ if (!params || typeof sdp !== 'string') return sdp;
77
+ const eol = sdp.includes('\r\n') ? '\r\n' : '\n';
78
+ const lines = sdp.split(eol);
79
+ const out = [];
80
+ for (const line of lines) {
81
+ const vp8 = line.match(/^a=rtpmap:(\d+) VP8\/90000/i);
82
+ out.push(line);
83
+ if (!vp8) continue;
84
+ const fmtp = lines.findIndex(l => l.startsWith(`a=fmtp:${vp8[1]} `));
85
+ if (fmtp < 0) out.push(`a=fmtp:${vp8[1]} ${params}`);
86
+ else lines[fmtp] = `${lines[fmtp]};${params}`;
87
+ }
88
+ return out.join(eol);
89
+ }
90
+
91
+ export function packDesktopFrame(frame) {
92
+ const image = Buffer.from(String(frame?.image || ''), 'base64');
93
+ const meta = Buffer.from(JSON.stringify({
94
+ t: 'frame', sessionId: frame?.sessionId, seq: frame?.seq, ts: frame?.ts,
95
+ width: frame?.width, height: frame?.height,
96
+ screenWidth: frame?.screenWidth, screenHeight: frame?.screenHeight,
97
+ screenX: frame?.screenX, screenY: frame?.screenY,
98
+ monitor: frame?.monitor, screens: frame?.screens, stats: frame?.stats,
99
+ ...(frame?.secureDesktop ? { secureDesktop: true } : {}),
100
+ mime: 'image/jpeg', bytes: image.length,
101
+ }) + '\n');
102
+ return Buffer.concat([meta, image]);
103
+ }
104
+
105
+ export function unpackDesktopFrame(packet) {
106
+ const buf = Buffer.isBuffer(packet) ? packet : Buffer.from(packet);
107
+ const nl = buf.indexOf(0x0a);
108
+ if (nl <= 0) return null;
109
+ try {
110
+ const meta = JSON.parse(buf.subarray(0, nl).toString('utf8'));
111
+ const imageBytes = buf.subarray(nl + 1);
112
+ return { meta, imageBytes, jpeg: imageBytes };
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ /** Địa chỉ đầu bên kia của cặp đường truyền đang dùng (từ `pc.getStats()`), hoặc null. */
119
+ export function selectedRemoteAddress(report) {
120
+ if (!report) return null;
121
+ const all = typeof report.values === 'function' ? [...report.values()] : Object.values(report);
122
+ const byId = new Map(all.filter((r) => r?.id).map((r) => [r.id, r]));
123
+ const transport = all.find((r) => r?.type === 'transport' && r.selectedCandidatePairId);
124
+ const pair = (transport && byId.get(transport.selectedCandidatePairId))
125
+ || all.find((r) => r?.type === 'candidate-pair' && (r.selected || (r.nominated && r.state === 'succeeded')));
126
+ const remote = pair && byId.get(pair.remoteCandidateId);
127
+ const address = remote?.address || remote?.ip || null;
128
+ return address ? { address: String(address), type: remote.candidateType || null } : null;
129
+ }
130
+
131
+ const stripZone = (ip) => String(ip || '').trim().toLowerCase().replace(/%.*$/, '').replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, '');
132
+
133
+ /**
134
+ * Đầu bên kia là CHÍNH máy này: loopback, hoặc trùng một địa chỉ của card mạng trên máy. Hai PC cùng mạng LAN có địa chỉ nội bộ khác nhau;
135
+ * cùng IP công cộng (srflx sau NAT) không tính — địa chỉ đó không thuộc card mạng nào của máy.
136
+ */
137
+ export function isOwnAddress(address, interfaces = os.networkInterfaces()) {
138
+ const a = stripZone(address);
139
+ if (!a || a.endsWith('.local')) return false;
140
+ if (a === '::1' || /^127\./.test(a)) return true;
141
+ return Object.values(interfaces || {}).flat().some((i) => i?.address && stripZone(i.address) === a);
142
+ }
143
+
144
+ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onFile = () => {}, onFileChunk = () => {}, onPeerReady = () => {}, onCursorMode = () => {}, loadRuntime, localViewerCheck = process.env.AIVIN_CAST_LOCAL_CHECK !== '0' } = {}) {
145
+ const peers = new Map();
146
+ /** Hình con trỏ đã thấy trong phiên — người xem nối sau vẫn nhận đủ (bộ quay chỉ gửi mỗi hình một lần). */
147
+ const cursorShapes = new Map();
148
+ let runtime = null;
149
+ let sequence = 0;
150
+ /**
151
+ * Một nguồn video + một nguồn âm thanh dùng chung mọi người xem (một lần quay → nhiều track). Bẫy wrtc 0.10.0 (đo 02/11/2026): đã tạo
152
+ * RTCVideoSource / RTCAudioSource thì tiến trình THOÁT TỰ NHIÊN (hết event loop) bị segfault lúc huỷ native — `process.exit()` thì sạch.
153
+ * Daemon luôn thoát bằng `process.exit` (stopForGood / tín hiệu / tự cập nhật); thêm đường thoát mới phải giữ như vậy, không thì trình giữ chạy tưởng CLI sập.
154
+ */
155
+ let videoSource = null;
156
+ let audioSource = null;
157
+ // Không nhớ kết quả rỗng: runtime có thể vừa tải xong ở nền (webrtcRuntime.mjs) — phiên xem sau dùng được ngay, không cần khởi động lại.
158
+ const load = async () => {
159
+ if (runtime) return runtime;
160
+ runtime = await (loadRuntime ? loadRuntime() : import('@roamhq/wrtc').catch(() => null));
161
+ return runtime;
162
+ };
163
+
164
+ /** Peer hỏng hẳn: dựng lại sau một nhịp (BE chuyển offer mới, FE tự nối lại). Trong lúc chờ người xem nhận JPEG. */
165
+ function scheduleReconnect(peer) {
166
+ if (peer.retryTimer || peer.attempt >= RECONNECT_DELAYS_MS.length) return;
167
+ peer.retryTimer = setTimeout(() => {
168
+ if (peers.get(peer.viewerId) !== peer) return;
169
+ start({ sessionId: peer.sessionId, viewerId: peer.viewerId, iceServers: peer.iceServers, videoBitrate: peer.videoBitrate, videoCodecs: peer.videoCodecs, audio: peer.audioEnabled, attempt: peer.attempt + 1 }).catch(() => false);
170
+ }, RECONNECT_DELAYS_MS[peer.attempt]);
171
+ peer.retryTimer.unref?.();
172
+ }
173
+
174
+ async function start({ sessionId, viewerId, iceServers = [], videoBitrate = null, videoCodecs = null, audio = true, attempt = 0 }) {
175
+ close(viewerId);
176
+ const wrtc = await load();
177
+ const RTCPeerConnection = wrtc?.RTCPeerConnection || wrtc?.default?.RTCPeerConnection;
178
+ if (!RTCPeerConnection) return false;
179
+ const pc = new RTCPeerConnection({ iceServers });
180
+ const channel = pc.createDataChannel('aivin-desktop-frames', { ordered: false, maxRetransmits: 0 });
181
+ const inputChannel = pc.createDataChannel(INPUT_CHANNEL, { ordered: true });
182
+ const fileChannel = pc.createDataChannel(FILE_CHANNEL, { ordered: true });
183
+ const pointerChannel = pc.createDataChannel(POINTER_CHANNEL, { ordered: false, maxRetransmits: 0 });
184
+ const VideoSource = wrtc?.nonstandard?.RTCVideoSource || wrtc?.default?.nonstandard?.RTCVideoSource;
185
+ const AudioSource = wrtc?.nonstandard?.RTCAudioSource || wrtc?.default?.nonstandard?.RTCAudioSource;
186
+ const MediaStream = wrtc?.MediaStream || wrtc?.default?.MediaStream;
187
+ if (VideoSource && !videoSource) videoSource = new VideoSource({ isScreencast: true });
188
+ if (AudioSource && !audioSource) audioSource = new AudioSource();
189
+ const track = videoSource ? videoSource.createTrack() : null;
190
+ const audioTrack = audioSource && audio !== false ? audioSource.createTrack() : null;
191
+ const stream = MediaStream && (track || audioTrack) ? new MediaStream([track, audioTrack].filter(Boolean)) : null;
192
+ if (track) stream ? pc.addTrack(track, stream) : pc.addTrack(track);
193
+ if (audioTrack) stream ? pc.addTrack(audioTrack, stream) : pc.addTrack(audioTrack);
194
+ const peer = {
195
+ pc, channel, inputChannel, fileChannel, pointerChannel, pointerSeq: 0,
196
+ track, video: !!track,
197
+ audioTrack, audio: !!audioTrack, audioEnabled: audio !== false,
198
+ sessionId, viewerId, iceServers, videoBitrate, videoCodecs, attempt, retryTimer: null, bweTimer: null, open: false, dropped: 0,
199
+ };
200
+ fileChannel.binaryType = 'arraybuffer';
201
+ fileChannel.onmessage = ({ data }) => {
202
+ if (typeof data !== 'string') {
203
+ const bytes = Buffer.from(data);
204
+ if (bytes.length <= MAX_FILE_CHUNK_BYTES) onFileChunk(viewerId, bytes);
205
+ return;
206
+ }
207
+ if (data.length > MAX_INPUT_MESSAGE_BYTES) return;
208
+ let msg;
209
+ try { msg = JSON.parse(data); } catch { return; }
210
+ // Mã phiên lấy từ peer như kênh thao tác.
211
+ onFile(viewerId, msg, peer.sessionId);
212
+ };
213
+ inputChannel.onmessage = ({ data }) => {
214
+ const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
215
+ if (text.length > MAX_INPUT_MESSAGE_BYTES) return;
216
+ let msg;
217
+ try { msg = JSON.parse(text); } catch { return; }
218
+ if (msg?.control === 'cursor') {
219
+ peer.localCursor = msg.local === true;
220
+ if (peer.localCursor) for (const shape of cursorShapes.values()) sendShape(peer, shape);
221
+ onCursorMode();
222
+ return;
223
+ }
224
+ if (msg?.control === 'audio') {
225
+ peer.audioEnabled = msg.enabled !== false && msg.muted !== true;
226
+ if (peer.audioTrack) peer.audioTrack.enabled = peer.audioEnabled;
227
+ onCursorMode();
228
+ return;
229
+ }
230
+ if (msg?.control === 'clipboard') {
231
+ if (typeof msg.text === 'string' && msg.text) {
232
+ onInput({ action: msg.paste === true ? 'paste' : 'clipboard', text: msg.text, session_id: peer.sessionId }, viewerId);
233
+ }
234
+ return;
235
+ }
236
+ // Mã phiên lấy từ peer (đã gắn lúc BE mời), không tin mã trong gói.
237
+ onInput({ ...msg, session_id: peer.sessionId }, viewerId);
238
+ };
239
+ pointerChannel.onmessage = ({ data }) => {
240
+ const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
241
+ if (text.length > MAX_POINTER_MESSAGE_BYTES) return;
242
+ let msg;
243
+ try { msg = JSON.parse(text); } catch { return; }
244
+ // Chỉ nhận di chuột: nhấn, nhả, phím phải đi kênh tin cậy. Gói đến muộn hơn gói mới nhất thì bỏ.
245
+ if (msg?.action !== 'move' || !(msg.n > peer.pointerSeq)) return;
246
+ peer.pointerSeq = msg.n;
247
+ const { n: _n, ...cmd } = msg;
248
+ onInput({ ...cmd, session_id: peer.sessionId }, viewerId);
249
+ };
250
+ peers.set(viewerId, peer);
251
+ channel.binaryType = 'arraybuffer';
252
+ const reportBwe = async () => {
253
+ if (!peer.open || inputChannel.readyState !== 'open') return;
254
+ const kbps = outgoingBitrateKbps(await pc.getStats().catch(() => null));
255
+ if (kbps === null || peers.get(viewerId) !== peer || inputChannel.readyState !== 'open') return;
256
+ try { inputChannel.send(JSON.stringify({ t: 'bwe', kbps })); } catch { /* kênh vừa đóng */ }
257
+ };
258
+ const markConnected = () => {
259
+ peer.open = true;
260
+ peer.attempt = 0;
261
+ if (peer.video && !peer.bweTimer) {
262
+ peer.bweTimer = setInterval(() => { void reportBwe(); }, BWE_REPORT_MS);
263
+ peer.bweTimer.unref?.();
264
+ }
265
+ emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'connected', transport: 'webrtc', video: peer.video, audio: peer.audio });
266
+ onPeerReady(viewerId);
267
+ void checkLocalViewer();
268
+ };
269
+ // Người xem đang ngồi ngay trên máy này (trình duyệt cùng máy → đường truyền đi qua loopback / card mạng của chính máy): xem tiếp là hình lặp
270
+ // vô tận. Báo máy chủ `local_viewer` (dừng người xem này, nhớ lại cho lần sau) và đóng kết nối — bắt được cả khi trang không gắn được mã vào
271
+ // tiêu đề (trình duyệt nhúng trong app khác). Cặp đường truyền đôi khi chưa chốt lúc kênh vừa mở → hỏi lại một lần.
272
+ const checkLocalViewer = async (retry = true) => {
273
+ if (!localViewerCheck || peer.localChecked || peers.get(viewerId) !== peer || typeof pc.getStats !== 'function') return;
274
+ const remote = selectedRemoteAddress(await Promise.resolve().then(() => pc.getStats()).catch(() => null));
275
+ if (!remote) {
276
+ if (retry) { const t = setTimeout(() => { void checkLocalViewer(false); }, 1000); t.unref?.(); }
277
+ return;
278
+ }
279
+ peer.localChecked = true;
280
+ if (!isOwnAddress(remote.address)) return;
281
+ emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'local_viewer', transport: 'none', candidate_type: remote.type });
282
+ close(viewerId);
283
+ };
284
+ channel.onopen = markConnected;
285
+ // Kênh đóng trước khi peer báo `failed` (chạy thật: ~19 s): báo ngay để BE gửi JPEG, không để người xem đứng hình trong lúc đó.
286
+ channel.onclose = () => {
287
+ const wasOpen = peer.open;
288
+ peer.open = false;
289
+ if (wasOpen && peers.get(viewerId) === peer) emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'disconnected', transport: 'jpeg' });
290
+ };
291
+ pc.onicecandidate = ({ candidate }) => {
292
+ emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'ice', candidate: candidate?.toJSON?.() || candidate || null });
293
+ };
294
+ pc.onconnectionstatechange = () => {
295
+ if (peers.get(viewerId) !== peer) return;
296
+ const state = pc.connectionState;
297
+ if (['failed', 'closed', 'disconnected'].includes(state)) {
298
+ const wasOpen = peer.open;
299
+ peer.open = false;
300
+ if (wasOpen || state !== 'disconnected') emitStatus({ session_id: sessionId, viewer_id: viewerId, state, transport: 'jpeg' });
301
+ if (state === 'failed') scheduleReconnect(peer);
302
+ } else if (state === 'connected' && !peer.open && channel.readyState === 'open') {
303
+ // Mạng chập chờn: `disconnected` tự hồi về `connected` nhưng kênh không mở lại (onopen không chạy lần nữa) — không có nhánh này là kẹt JPEG.
304
+ markConnected();
305
+ }
306
+ };
307
+ const offer = await pc.createOffer();
308
+ await pc.setLocalDescription({ type: 'offer', sdp: preferVideoCodecs(offer.sdp, videoCodecs) });
309
+ emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'offer', sdp: pc.localDescription?.sdp, ice_servers: iceServers });
310
+ return true;
311
+ }
312
+
313
+ async function signal(msg) {
314
+ const peer = peers.get(String(msg?.viewer_id || ''));
315
+ if (!peer || msg?.session_id !== peer.sessionId) return false;
316
+ if (msg.type === 'answer' && msg.sdp) {
317
+ await peer.pc.setRemoteDescription({ type: 'answer', sdp: withVideoBitrate(msg.sdp, peer.videoBitrate) });
318
+ return true;
319
+ }
320
+ if (msg.type === 'ice') {
321
+ await peer.pc.addIceCandidate(msg.candidate || null).catch(() => {});
322
+ return true;
323
+ }
324
+ return false;
325
+ }
326
+
327
+ /** JPEG cho người xem chưa có video; người có video chỉ nhận gói meta (không ảnh). */
328
+ function push(frame) {
329
+ const packet = packDesktopFrame({ ...frame, seq: ++sequence });
330
+ const metaPacket = packDesktopFrame({ ...frame, image: '', seq: sequence });
331
+ let sent = 0;
332
+ for (const peer of peers.values()) {
333
+ if (!peer.open || peer.channel.readyState !== 'open') continue;
334
+ if (peer.video) {
335
+ try { peer.channel.send(metaPacket); } catch { /* kênh vừa đóng */ }
336
+ continue;
337
+ }
338
+ if (peer.channel.bufferedAmount > MAX_BUFFERED_BYTES) { peer.dropped++; continue; }
339
+ try { peer.channel.send(packet); sent++; } catch { peer.dropped++; }
340
+ }
341
+ return sent;
342
+ }
343
+
344
+ function sendShape(peer, shape) {
345
+ if (peer.inputChannel?.readyState !== 'open') return;
346
+ try { peer.inputChannel.send(JSON.stringify({ t: 'cursor_shape', ...shape })); } catch { /* kênh vừa đóng */ }
347
+ }
348
+
349
+ /** Vị trí con trỏ: kênh không gửi lại — mất một gói thì gói sau đè lên. Chỉ tới người xem đã báo tự vẽ con trỏ. */
350
+ function pushCursor(cursor) {
351
+ const packet = Buffer.from(JSON.stringify({ t: 'cursor', ...cursor }) + '\n');
352
+ for (const peer of peers.values()) {
353
+ if (!peer.localCursor || !peer.open || peer.channel.readyState !== 'open') continue;
354
+ try { peer.channel.send(packet); } catch { /* kênh vừa đóng */ }
355
+ }
356
+ }
357
+
358
+ /** Hình con trỏ: kênh tin cậy (kênh thao tác) vì chỉ gửi một lần. */
359
+ function pushCursorShape(shape) {
360
+ if (cursorShapes.size >= MAX_CURSOR_SHAPES) cursorShapes.delete(cursorShapes.keys().next().value);
361
+ cursorShapes.set(shape.id, shape);
362
+ for (const peer of peers.values()) if (peer.localCursor) sendShape(peer, shape);
363
+ }
364
+
365
+ /** Ô đang có tiêu điểm trên máy có phải ô nhập chữ không (sau cú nhấp của người xem) — trình duyệt điện thoại tự mở / đóng bàn phím ảo. */
366
+ function pushInputFocus(focus) {
367
+ const packet = JSON.stringify({ t: 'input_focus', editable: focus?.editable === true });
368
+ for (const peer of peers.values()) {
369
+ if (peer.inputChannel?.readyState !== 'open') continue;
370
+ try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
371
+ }
372
+ }
373
+
374
+ /** Nội dung Clipboard văn bản mới trên máy từ xa → gửi qua kênh điều khiển cho trình duyệt người xem. */
375
+ function pushClipboard(clip) {
376
+ const text = typeof clip?.text === 'string' ? clip.text : '';
377
+ if (!text) return;
378
+ const packet = JSON.stringify({ t: 'clipboard', text });
379
+ for (const peer of peers.values()) {
380
+ if (peer.inputChannel?.readyState !== 'open') continue;
381
+ try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
382
+ }
383
+ }
384
+
385
+ /** Báo máy từ xa vừa vào / thoát vùng màn hình bảo mật Windows (hộp thoại quyền quản trị UAC hoặc màn hình khóa). */
386
+ function pushSecureDesktop(sec) {
387
+ const packet = JSON.stringify({ t: 'secure_desktop', active: sec?.active === true });
388
+ for (const peer of peers.values()) {
389
+ if (peer.inputChannel?.readyState !== 'open') continue;
390
+ try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
391
+ }
392
+ }
393
+
394
+ /** Trả lời đúng người xem đang gửi tệp. */
395
+ function replyFile(viewerId, msg) {
396
+ const channel = peers.get(String(viewerId || ''))?.fileChannel;
397
+ if (channel?.readyState !== 'open') return;
398
+ try { channel.send(JSON.stringify(msg)); } catch { /* kênh vừa đóng */ }
399
+ }
400
+
401
+ /** Mọi người xem đều có video và tự vẽ con trỏ → bộ quay thôi lồng con trỏ vào khung. */
402
+ function localCursor() {
403
+ return peers.size > 0 && [...peers.values()].every(p => p.video && p.open && p.localCursor);
404
+ }
405
+
406
+ /** Khung thô I420 từ tiến trình quay → nguồn video (mọi track cùng nguồn). */
407
+ function pushRaw(frame) {
408
+ if (!videoSource || ![...peers.values()].some(p => p.video && p.open)) return false;
409
+ try { videoSource.onFrame(frame); return true; } catch { return false; }
410
+ }
411
+
412
+ /** Khung âm thanh PCM 16-bit 10 ms từ tiến trình quay → nguồn âm thanh (mọi track cùng nguồn). */
413
+ function pushAudio(audio) {
414
+ if (!audioSource || !needsAudio()) return false;
415
+ const sampleRate = audio?.sampleRate || 48000;
416
+ const channelCount = audio?.channelCount || 2;
417
+ const framesPer10ms = Math.floor(sampleRate / 100);
418
+ const samplesPer10ms = framesPer10ms * channelCount;
419
+ const samples = audio?.samples;
420
+ if (!samples || samples.length < samplesPer10ms) return false;
421
+ try {
422
+ for (let off = 0; off + samplesPer10ms <= samples.length; off += samplesPer10ms) {
423
+ const chunk = off === 0 && samples.length === samplesPer10ms ? samples : samples.subarray(off, off + samplesPer10ms);
424
+ audioSource.onData({
425
+ samples: chunk,
426
+ sampleRate,
427
+ bitsPerSample: audio.bitsPerSample || 16,
428
+ channelCount,
429
+ numberOfFrames: framesPer10ms,
430
+ });
431
+ }
432
+ return true;
433
+ } catch {
434
+ return false;
435
+ }
436
+ }
437
+
438
+ /** Còn người xem cần âm thanh (đã nối WebRTC + có audio track + chưa tắt tiếng). */
439
+ function needsAudio() { return [...peers.values()].some(p => p.audio && p.open && p.audioEnabled !== false); }
440
+ function hasAudio() { return [...peers.values()].some(p => p.audio); }
441
+
442
+ /** Bật / tắt âm thanh cho toàn bộ người xem trong phiên. */
443
+ function setAudio(enabled) {
444
+ const next = enabled !== false;
445
+ for (const peer of peers.values()) {
446
+ peer.audioEnabled = next;
447
+ if (peer.audioTrack) peer.audioTrack.enabled = next;
448
+ }
449
+ onCursorMode();
450
+ }
451
+
452
+ /** Còn người xem cần ảnh JPEG (chưa nối WebRTC, hoặc nối nhưng không có video). */
453
+ function needsJpeg() { return needsFallback() || [...peers.values()].some(p => !p.video); }
454
+ function hasVideo() { return [...peers.values()].some(p => p.video); }
455
+
456
+ function anyOpen() { return [...peers.values()].some(p => p.open && p.channel.readyState === 'open'); }
457
+ function needsFallback() { return peers.size === 0 || [...peers.values()].some(p => !p.open || p.channel.readyState !== 'open'); }
458
+
459
+ function close(viewerId) {
460
+ const peer = peers.get(String(viewerId || ''));
461
+ if (!peer) return;
462
+ peers.delete(String(viewerId));
463
+ clearTimeout(peer.retryTimer);
464
+ clearInterval(peer.bweTimer);
465
+ try { peer.channel.close(); } catch { /* already closed */ }
466
+ try { peer.inputChannel?.close(); } catch { /* already closed */ }
467
+ try { peer.fileChannel?.close(); } catch { /* already closed */ }
468
+ try { peer.pointerChannel?.close(); } catch { /* already closed */ }
469
+ try { peer.track?.stop(); } catch { /* already stopped */ }
470
+ try { peer.audioTrack?.stop(); } catch { /* already stopped */ }
471
+ try { peer.pc.close(); } catch { /* already closed */ }
472
+ }
473
+
474
+ function closeAll() { for (const id of [...peers.keys()]) close(id); cursorShapes.clear(); }
475
+ return {
476
+ start, signal, push, pushRaw, pushAudio, pushCursor, pushCursorShape, pushInputFocus, pushClipboard, pushSecureDesktop, replyFile,
477
+ localCursor, needsJpeg, hasVideo, needsAudio, hasAudio, setAudio, anyOpen, needsFallback, close, closeAll,
478
+ };
479
+ }