@mindexec/cli 0.2.477 → 0.2.478

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +323 -323
  2. package/codex-model-catalog.js +202 -202
  3. package/codex-runtime.js +1608 -1608
  4. package/desktop-workspace-state.cjs +120 -120
  5. package/electron/main.cjs +517 -517
  6. package/electron/preload.cjs +17 -17
  7. package/electron/recurring-update-owner-smoke.mjs +55 -55
  8. package/electron/recurring-update-owner.cjs +97 -97
  9. package/electron/source-smoke.mjs +108 -108
  10. package/electron/update-feed-resolver.cjs +79 -79
  11. package/electron/update-feed.json +10 -10
  12. package/electron/update-manager-smoke.mjs +146 -146
  13. package/electron/update-manager.cjs +297 -297
  14. package/electron/windows-package-smoke.mjs +156 -156
  15. package/launch-bridge.cjs +236 -236
  16. package/lzo1x.js +110 -110
  17. package/mode4-atlas-worker.js +440 -440
  18. package/mode4-atlas.js +130 -130
  19. package/package.json +1 -1
  20. package/port-guard.cjs +285 -285
  21. package/remote-fast/osx-arm64/MacScreenCaptureKitH264.swift +339 -339
  22. package/remote-fast/osx-arm64/MacSystemAudioCapture.swift +214 -214
  23. package/remote-fast/osx-arm64/UnixRawCaptureHelper.mjs +80 -80
  24. package/remote-fast/osx-arm64/livedesk-raw-capture-resampler.mjs +73 -73
  25. package/remote-fast/osx-arm64/mindexec-remote-fast.dll +0 -0
  26. package/remote-fast/osx-x64/MacScreenCaptureKitH264.swift +339 -339
  27. package/remote-fast/osx-x64/MacSystemAudioCapture.swift +214 -214
  28. package/remote-fast/osx-x64/UnixRawCaptureHelper.mjs +80 -80
  29. package/remote-fast/osx-x64/livedesk-raw-capture-resampler.mjs +73 -73
  30. package/remote-fast/osx-x64/mindexec-remote-fast.dll +0 -0
  31. package/remote-fast/win-x64/mindexec-remote-fast.dll +0 -0
  32. package/remote-hub.js +3698 -3698
  33. package/scripts/auth-session-smoke.mjs +262 -262
  34. package/scripts/board-render-ownership-smoke.mjs +85 -85
  35. package/scripts/codex-model-catalog-smoke.mjs +150 -150
  36. package/scripts/codex-runtime-home-smoke.mjs +58 -58
  37. package/scripts/codex-sdk-image-live-smoke.mjs +43 -43
  38. package/scripts/codex-sdk-image-runtime-smoke.mjs +122 -122
  39. package/scripts/codex-sdk-runtime-smoke.mjs +89 -89
  40. package/scripts/desktop-update-publisher-smoke.mjs +89 -89
  41. package/scripts/desktop-update-worker-smoke.mjs +72 -72
  42. package/scripts/desktop-workspace-state-smoke.mjs +81 -81
  43. package/scripts/drive-installed-update-smoke.mjs +67 -67
  44. package/scripts/npm-fresh-install-smoke.mjs +216 -216
  45. package/scripts/publish-mindexec-desktop-updates.mjs +224 -224
  46. package/scripts/remote-agent-managed-smoke.mjs +318 -318
  47. package/scripts/remote-agent-package-smoke.mjs +64 -64
  48. package/scripts/remote-agent-ws-smoke.mjs +269 -269
  49. package/scripts/remote-fast-live-rate-smoke.mjs +343 -343
  50. package/scripts/remote-fast-mdm-browser-smoke.mjs +453 -453
  51. package/scripts/remote-fleet-render-smoke.mjs +1350 -1350
  52. package/scripts/remote-frame-ws-smoke.mjs +234 -234
  53. package/scripts/remote-http-smoke.mjs +592 -592
  54. package/scripts/remote-hub-identity-smoke.mjs +146 -146
  55. package/scripts/remote-hub-scale-smoke.mjs +124 -124
  56. package/scripts/remote-hub-smoke.mjs +699 -699
  57. package/scripts/remote-input-ws-smoke.mjs +263 -263
  58. package/scripts/remote-registry-follower-smoke.mjs +815 -815
  59. package/scripts/setup-tree-sitter-grammars.mjs +59 -59
  60. package/server.js +7690 -7690
  61. package/start-bridge.bat +32 -32
  62. package/start-bridge.sh +81 -81
  63. package/wwwroot/_content/MindExecution.Plugins.Admin/css/admin-dashboard.css +546 -546
  64. package/wwwroot/_content/MindExecution.Plugins.YouTube/css/youtube-search.css +251 -251
  65. package/wwwroot/_content/MindExecution.Shared/css/app.css +1 -1
  66. package/wwwroot/_content/MindExecution.Shared/css/mind-map-overrides.css +3789 -3789
  67. package/wwwroot/_content/MindExecution.Shared/js/agent-visualization.js +27 -27
  68. package/wwwroot/_content/MindExecution.Shared/js/background-themes.js +1449 -1449
  69. package/wwwroot/_content/MindExecution.Shared/js/code-master.js +8316 -8316
  70. package/wwwroot/_content/MindExecution.Shared/js/file-system-helper.js +338 -338
  71. package/wwwroot/_content/MindExecution.Shared/js/marked.min.js +69 -69
  72. package/wwwroot/_content/MindExecution.Shared/js/mind-map-animated-image-preview.js +270 -270
  73. package/wwwroot/_content/MindExecution.Shared/js/mind-map-automation-edge-motion.js +170 -170
  74. package/wwwroot/_content/MindExecution.Shared/js/mind-map-board-render-ownership.js +81 -81
  75. package/wwwroot/_content/MindExecution.Shared/js/mind-map-core.js +10506 -10506
  76. package/wwwroot/_content/MindExecution.Shared/js/mind-map-css3d-hotpath.js +902 -902
  77. package/wwwroot/_content/MindExecution.Shared/js/mind-map-css3d-manager.js +24637 -24637
  78. package/wwwroot/_content/MindExecution.Shared/js/mind-map-dev-guards.js +325 -325
  79. package/wwwroot/_content/MindExecution.Shared/js/mind-map-dnd.js +1491 -1491
  80. package/wwwroot/_content/MindExecution.Shared/js/mind-map-glow-shader.js +70 -70
  81. package/wwwroot/_content/MindExecution.Shared/js/mind-map-image-policy.js +218 -218
  82. package/wwwroot/_content/MindExecution.Shared/js/mind-map-interactions.js +7065 -7065
  83. package/wwwroot/_content/MindExecution.Shared/js/mind-map-lod-plan-worker.js +160 -160
  84. package/wwwroot/_content/MindExecution.Shared/js/mind-map-lod-renderer.js +9956 -9956
  85. package/wwwroot/_content/MindExecution.Shared/js/mind-map-lod-video-placeholder.js +107 -107
  86. package/wwwroot/_content/MindExecution.Shared/js/mind-map-logic-workers.js +1004 -1004
  87. package/wwwroot/_content/MindExecution.Shared/js/mind-map-menu-manager.js +1351 -1351
  88. package/wwwroot/_content/MindExecution.Shared/js/mind-map-multi-select.js +865 -865
  89. package/wwwroot/_content/MindExecution.Shared/js/mind-map-node-search-worker.js +554 -554
  90. package/wwwroot/_content/MindExecution.Shared/js/mind-map-nodes.js +4744 -4744
  91. package/wwwroot/_content/MindExecution.Shared/js/mind-map-normal-boundary-optimizer.js +624 -624
  92. package/wwwroot/_content/MindExecution.Shared/js/mind-map-object-manager.js +241 -241
  93. package/wwwroot/_content/MindExecution.Shared/js/mind-map-pipeline.js +2290 -2290
  94. package/wwwroot/_content/MindExecution.Shared/js/mind-map-remote-codecs.js +202 -202
  95. package/wwwroot/_content/MindExecution.Shared/js/mind-map-render-plan.js +1971 -1971
  96. package/wwwroot/_content/MindExecution.Shared/js/mind-map-text-lod-system.js +93 -93
  97. package/wwwroot/_content/MindExecution.Shared/js/mind-map-texture-factory.js +2391 -2391
  98. package/wwwroot/_content/MindExecution.Shared/js/mind-map-video-playback-controls.js +95 -95
  99. package/wwwroot/_content/MindExecution.Shared/js/mind-map-visibility-worker.js +895 -895
  100. package/wwwroot/_content/MindExecution.Shared/js/mindmap-toolbar.js +636 -636
  101. package/wwwroot/_content/MindExecution.Shared/js/native-drop-handler.js +45 -45
  102. package/wwwroot/_content/MindExecution.Shared/js/plan-master.js +117 -117
  103. package/wwwroot/_content/MindExecution.Shared/js/renderers/CSS3DRenderer.js +114 -114
  104. package/wwwroot/_content/MindExecution.Shared/js/texture-worker-manager.js +10 -10
  105. package/wwwroot/_content/MindExecution.Shared/js/three.min.js +6 -6
  106. package/wwwroot/_content/MindExecution.Shared/js/token-manager.js +7 -7
  107. package/wwwroot/_content/MindExecution.Shared/js/troika-bundle.js +6 -6
  108. package/wwwroot/_content/MindExecution.Shared/js/troika-bundle.js.map +2 -2
  109. package/wwwroot/_content/MindExecution.Shared/lib/font-awesome/css/all.min.css +8 -8
  110. package/wwwroot/_content/MindExecution.Shared/models/vocab.txt +30522 -30522
  111. package/wwwroot/_framework/{Google.Protobuf.9h59ukbel7.dll → Google.Protobuf.33g2gb5is0.dll} +0 -0
  112. package/wwwroot/_framework/{MindExecution.Core.ty1xewqp36.dll → MindExecution.Core.z100xo4mg0.dll} +0 -0
  113. package/wwwroot/_framework/{MindExecution.Kernel.h7rqjoo69o.dll → MindExecution.Kernel.i9cldrx8yc.dll} +0 -0
  114. package/wwwroot/_framework/{MindExecution.Plugins.Admin.wrfrcvhjde.dll → MindExecution.Plugins.Admin.48lzqddb0a.dll} +0 -0
  115. package/wwwroot/_framework/{MindExecution.Plugins.Business.csbcyjurdh.dll → MindExecution.Plugins.Business.7m8u1q142p.dll} +0 -0
  116. package/wwwroot/_framework/{MindExecution.Plugins.Concept.buomiysqjn.dll → MindExecution.Plugins.Concept.cl5wmr53od.dll} +0 -0
  117. package/wwwroot/_framework/{MindExecution.Plugins.Directory.7k00i2v769.dll → MindExecution.Plugins.Directory.slipi39041.dll} +0 -0
  118. package/wwwroot/_framework/{MindExecution.Plugins.PlanMaster.85i5ocraro.dll → MindExecution.Plugins.PlanMaster.qfge05l671.dll} +0 -0
  119. package/wwwroot/_framework/{MindExecution.Plugins.YouTube.nbolrfakte.dll → MindExecution.Plugins.YouTube.tn7v29ut77.dll} +0 -0
  120. package/wwwroot/_framework/{MindExecution.Shared.nqh4porv7x.dll → MindExecution.Shared.rjqlf0umjn.dll} +0 -0
  121. package/wwwroot/_framework/{MindExecution.Web.211q3bf4mr.dll → MindExecution.Web.rwawrxxk38.dll} +0 -0
  122. package/wwwroot/_framework/blazor.boot.json +23 -23
  123. package/wwwroot/_headers +40 -40
  124. package/wwwroot/_redirects +1 -1
  125. package/wwwroot/index.html +772 -772
  126. package/wwwroot/js/marketing-tool.js +180 -180
  127. package/wwwroot/manifest.webmanifest +23 -23
  128. package/wwwroot/service-worker-assets.js +78 -106
  129. package/wwwroot/service-worker.js +33 -33
  130. package/tree-sitter-grammars/README.md +0 -18
  131. package/tree-sitter-grammars/tree-sitter-c_sharp.wasm +0 -0
  132. package/tree-sitter-grammars/tree-sitter-go.wasm +0 -0
  133. package/tree-sitter-grammars/tree-sitter-java.wasm +0 -0
  134. package/tree-sitter-grammars/tree-sitter-javascript.wasm +0 -0
  135. package/tree-sitter-grammars/tree-sitter-python.wasm +0 -0
  136. package/tree-sitter-grammars/tree-sitter-rust.wasm +0 -0
  137. package/tree-sitter-grammars/tree-sitter-tsx.wasm +0 -0
  138. package/tree-sitter-grammars/tree-sitter-typescript.wasm +0 -0
  139. package/wwwroot/_content/MindExecution.Plugins.Directory/background.png +0 -0
  140. package/wwwroot/_content/MindExecution.Shared/fonts/NotoSansKR-Bold.ttf +0 -0
  141. package/wwwroot/_content/MindExecution.Shared/fonts/NotoSansKR-Regular.ttf +0 -0
  142. package/wwwroot/_content/MindExecution.Shared/js/mind-map-core.js.backup +0 -1059
  143. package/wwwroot/_content/MindExecution.Shared/js/mind-map-dnd.js.bak +0 -434
  144. package/wwwroot/_content/MindExecution.Shared/js/mind-map-object-manager.js.backup +0 -372
  145. package/wwwroot/_content/MindExecution.Shared/js/mind-map-texture-factory.js.backup +0 -1258
@@ -1,440 +1,440 @@
1
- #!/usr/bin/env node
2
-
3
- import { spawn } from 'node:child_process';
4
- import { createRequire } from 'node:module';
5
- import { existsSync } from 'node:fs';
6
- import { decodeLzo1xBlock } from './lzo1x.js';
7
-
8
- const require = createRequire(import.meta.url);
9
- const DEFAULT_WIDTH = 1920;
10
- const DEFAULT_HEIGHT = 1080;
11
- const DEFAULT_FPS = 20;
12
- const MAX_DEVICES = 100;
13
- const FRAME_POOL_SIZE = 8;
14
- const MAX_TILE_WIDTH = 480;
15
- const MAX_TILE_HEIGHT = 270;
16
-
17
- const rgb565Red = new Uint8Array(65_536);
18
- const rgb565Green = new Uint8Array(65_536);
19
- const rgb565Blue = new Uint8Array(65_536);
20
- for (let pixel = 0; pixel < 65_536; pixel += 1) {
21
- rgb565Red[pixel] = (((pixel >> 11) & 0x1f) * 255 / 31) | 0;
22
- rgb565Green[pixel] = (((pixel >> 5) & 0x3f) * 255 / 63) | 0;
23
- rgb565Blue[pixel] = ((pixel & 0x1f) * 255 / 31) | 0;
24
- }
25
-
26
- let config = normalizeConfig({});
27
- let layoutVersion = 0;
28
- let layout = [];
29
- let latestTiles = new Map();
30
- let framePool = [];
31
- let encoder = null;
32
- let encoderCandidateIndex = 0;
33
- let encoderCandidates = [];
34
- let encoderOutputSeen = false;
35
- let encoderGeneration = 0;
36
- let encoderRestartTimer = null;
37
- let encoderStartupTimer = null;
38
- let inputWaitTimer = null;
39
- let outputBuffer = Buffer.alloc(0);
40
- let frameSeq = 0;
41
- let tickTimer = null;
42
- let nextTickAt = 0;
43
- let closed = false;
44
- let lastComposeMs = 0;
45
- let poolStarved = 0;
46
- const ENCODER_STARTUP_OUTPUT_TIMEOUT_MS = 8_000;
47
-
48
- function clamp(value, min, max, fallback) {
49
- const number = Number(value);
50
- return Number.isFinite(number) ? Math.max(min, Math.min(max, Math.round(number))) : fallback;
51
- }
52
-
53
- function normalizeConfig(value) {
54
- const deviceIds = [...new Set((Array.isArray(value?.deviceIds) ? value.deviceIds : [])
55
- .map(item => String(item || '').trim()).filter(Boolean))].slice(0, MAX_DEVICES);
56
- const maxWidth = clamp(value?.width, 640, 3840, DEFAULT_WIDTH);
57
- const maxHeight = clamp(value?.height, 360, 2160, DEFAULT_HEIGHT);
58
- const sharpTiles = Number(value?.tileWidth) >= 480 || Number(value?.tileHeight) >= 270;
59
- const sourceTileWidth = sharpTiles ? 480 : 320;
60
- const sourceTileHeight = sharpTiles ? 270 : 180;
61
- const count = Math.max(1, deviceIds.length);
62
- const columns = Math.max(1, Math.ceil(Math.sqrt(count)));
63
- const rows = Math.max(1, Math.ceil(count / columns));
64
- const tileWidth = Math.max(2, Math.min(sourceTileWidth, Math.floor(maxWidth / columns))) & ~1;
65
- const tileHeight = Math.max(2, Math.min(sourceTileHeight, Math.floor(maxHeight / rows))) & ~1;
66
- return {
67
- deviceIds,
68
- maxWidth,
69
- maxHeight,
70
- width: tileWidth * columns,
71
- height: tileHeight * rows,
72
- columns,
73
- rows,
74
- tileWidth,
75
- tileHeight,
76
- sourceTileWidth,
77
- sourceTileHeight,
78
- fps: clamp(value?.fps, 1, 30, DEFAULT_FPS)
79
- };
80
- }
81
-
82
- function send(message) {
83
- if (process.connected) process.send?.(message);
84
- }
85
-
86
- function resolveFfmpegPaths() {
87
- const paths = [];
88
- const add = value => {
89
- const path = String(value || '').trim();
90
- if (!path || paths.includes(path)) return;
91
- if (path === 'ffmpeg' || existsSync(path)) paths.push(path);
92
- };
93
- add(process.env.LIVEDESK_FFMPEG);
94
- try { add(require('@ffmpeg-installer/ffmpeg')?.path); } catch {}
95
- try { add(require('ffmpeg-static')); } catch {}
96
- add('ffmpeg');
97
- return paths;
98
- }
99
-
100
- function buildEncoderCandidates() {
101
- const codecCandidates = process.platform === 'win32'
102
- ? [
103
- ['windows-nvenc', ['-c:v', 'h264_nvenc', '-preset', 'llhp', '-profile:v', 'baseline', '-rc:v', 'cbr_ld_hq', '-b:v', '6M', '-maxrate', '6M', '-bufsize', '1M', '-rc-lookahead', '0', '-zerolatency', '1', '-g', String(config.fps), '-bf', '0']],
104
- ['windows-qsv', ['-c:v', 'h264_qsv', '-preset', 'veryfast', '-global_quality', '28', '-look_ahead', '0', '-g', String(config.fps), '-bf', '0']],
105
- ['windows-amf', ['-c:v', 'h264_amf', '-quality', 'speed', '-usage', 'lowlatency', '-rc', 'cqp', '-qp_i', '25', '-qp_p', '28', '-g', String(config.fps), '-bf', '0']]
106
- ]
107
- : process.platform === 'darwin'
108
- ? [['macos-videotoolbox', ['-c:v', 'h264_videotoolbox', '-realtime', '1', '-allow_sw', '0', '-b:v', '6M', '-g', String(config.fps), '-bf', '0']]]
109
- : [['linux-nvenc', ['-c:v', 'h264_nvenc', '-preset', 'llhp', '-profile:v', 'baseline', '-rc-lookahead', '0', '-zerolatency', '1', '-g', String(config.fps), '-bf', '0']]];
110
- codecCandidates.push(['software-x264', [
111
- '-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency',
112
- '-profile:v', 'baseline', '-crf', '28', '-g', String(config.fps),
113
- '-keyint_min', String(config.fps), '-sc_threshold', '0', '-bf', '0',
114
- '-x264-params', 'aud=1:repeat-headers=1'
115
- ]]);
116
- return resolveFfmpegPaths().flatMap(path => codecCandidates.map(([name, args]) => ({ path, name, args })));
117
- }
118
-
119
- function startEncoder() {
120
- if (closed || encoder || encoderCandidates.length === 0) return;
121
- if (encoderCandidateIndex >= encoderCandidates.length) {
122
- send({ type: 'status', state: 'error', error: 'No Mode 4 H.264 encoder is available.' });
123
- return;
124
- }
125
- const candidate = encoderCandidates[encoderCandidateIndex++];
126
- encoderGeneration += 1;
127
- const args = [
128
- '-hide_banner', '-loglevel', 'warning',
129
- '-f', 'rawvideo', '-pixel_format', 'rgb24',
130
- '-video_size', `${config.width}x${config.height}`,
131
- '-framerate', String(config.fps), '-i', 'pipe:0', '-an',
132
- ...candidate.args,
133
- '-bsf:v', 'h264_metadata=aud=insert', '-f', 'h264', 'pipe:1'
134
- ];
135
- const child = spawn(candidate.path, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
136
- encoder = { child, candidate, inputSeen: false };
137
- encoderOutputSeen = false;
138
- outputBuffer = Buffer.alloc(0);
139
- child.stdout.on('data', appendEncodedBytes);
140
- child.stdin.on('error', error => {
141
- if (encoder?.child === child && !isClosedPipeError(error)) {
142
- send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name} input: ${error.message}` });
143
- }
144
- });
145
- child.stderr.on('data', chunk => {
146
- const message = String(chunk || '').trim();
147
- if (message) send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name}: ${message.slice(0, 600)}` });
148
- });
149
- child.on('error', error => send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name}: ${error.message}` }));
150
- child.on('exit', code => {
151
- clearTimeout(encoderStartupTimer);
152
- encoderStartupTimer = null;
153
- const wasCurrent = encoder?.child === child;
154
- if (wasCurrent) encoder = null;
155
- flushEncodedUnit();
156
- if (closed) return;
157
- send({ type: 'status', state: 'encoder-restart', encoder: candidate.name, code, emitted: encoderOutputSeen });
158
- clearTimeout(encoderRestartTimer);
159
- encoderRestartTimer = setTimeout(startEncoder, encoderOutputSeen ? 800 : 120);
160
- });
161
- send({ type: 'status', state: 'encoder-starting', encoder: candidate.name });
162
- }
163
-
164
- function isClosedPipeError(error) {
165
- const code = String(error?.code || '').toUpperCase();
166
- const message = String(error?.message || '').toLowerCase();
167
- return code === 'EPIPE' || code === 'EOF' || code === 'ERR_STREAM_DESTROYED'
168
- || message.includes('write eof') || message.includes('broken pipe');
169
- }
170
-
171
- function armEncoderStartupTimer(child, candidate) {
172
- clearTimeout(encoderStartupTimer);
173
- encoderStartupTimer = setTimeout(() => {
174
- if (encoder?.child === child && encoder.inputSeen && !encoderOutputSeen) {
175
- send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name}: no output after receiving input; trying the next encoder.` });
176
- try { child.kill(); } catch {}
177
- }
178
- }, ENCODER_STARTUP_OUTPUT_TIMEOUT_MS);
179
- }
180
-
181
- function stopEncoder() {
182
- clearTimeout(encoderRestartTimer);
183
- encoderRestartTimer = null;
184
- clearTimeout(encoderStartupTimer);
185
- encoderStartupTimer = null;
186
- const child = encoder?.child;
187
- encoder = null;
188
- if (!child) return;
189
- try { child.stdin.end(); } catch {}
190
- setTimeout(() => { try { child.kill(); } catch {} }, 250).unref?.();
191
- }
192
-
193
- function findStartCodes(buffer) {
194
- const starts = [];
195
- for (let index = 0; index + 3 < buffer.length; index += 1) {
196
- if (buffer[index] !== 0 || buffer[index + 1] !== 0) continue;
197
- if (buffer[index + 2] === 1) {
198
- starts.push({ offset: index, header: index + 3 });
199
- index += 2;
200
- } else if (buffer[index + 2] === 0 && buffer[index + 3] === 1) {
201
- starts.push({ offset: index, header: index + 4 });
202
- index += 3;
203
- }
204
- }
205
- return starts;
206
- }
207
-
208
- function appendEncodedBytes(chunk) {
209
- outputBuffer = outputBuffer.length ? Buffer.concat([outputBuffer, chunk]) : Buffer.from(chunk);
210
- while (true) {
211
- const auds = findStartCodes(outputBuffer).filter(start => (outputBuffer[start.header] & 0x1f) === 9);
212
- if (auds.length < 2) break;
213
- const boundary = auds[1].offset;
214
- emitEncodedUnit(outputBuffer.subarray(0, boundary));
215
- outputBuffer = outputBuffer.subarray(boundary);
216
- }
217
- }
218
-
219
- function flushEncodedUnit() {
220
- if (outputBuffer.length > 0) emitEncodedUnit(outputBuffer);
221
- outputBuffer = Buffer.alloc(0);
222
- }
223
-
224
- function emitEncodedUnit(payload) {
225
- if (!payload?.length) return;
226
- const starts = findStartCodes(payload);
227
- const isKeyFrame = starts.some(start => (payload[start.header] & 0x1f) === 5);
228
- encoderOutputSeen = true;
229
- clearTimeout(encoderStartupTimer);
230
- encoderStartupTimer = null;
231
- frameSeq += 1;
232
- send({
233
- type: 'frame',
234
- payload: Buffer.from(payload),
235
- metadata: {
236
- frameSeq,
237
- streamFrameSeq: frameSeq,
238
- width: config.width,
239
- height: config.height,
240
- fps: config.fps,
241
- durationUs: Math.round(1_000_000 / config.fps),
242
- timestampUs: Math.round(frameSeq * 1_000_000 / config.fps),
243
- isKeyFrame,
244
- chunkType: isKeyFrame ? 'key' : 'delta',
245
- hardwareEncoder: encoder?.candidate?.name || '',
246
- encoderGeneration,
247
- layoutVersion,
248
- composeMs: lastComposeMs,
249
- poolStarved,
250
- readyTileCount: latestTiles.size,
251
- tileCount: config.deviceIds.length
252
- }
253
- });
254
- }
255
-
256
- function rebuildLayout() {
257
- const { columns, rows, tileWidth, tileHeight } = config;
258
- layoutVersion += 1;
259
- layout = config.deviceIds.map((deviceId, index) => ({
260
- deviceId,
261
- index,
262
- column: index % columns,
263
- row: Math.floor(index / columns),
264
- x: (index % columns) * tileWidth,
265
- y: Math.floor(index / columns) * tileHeight,
266
- width: tileWidth,
267
- height: tileHeight
268
- }));
269
- for (const tile of latestTiles.values()) tile.rendered = null;
270
- framePool = Array.from({ length: FRAME_POOL_SIZE }, () => Buffer.alloc(config.width * config.height * 3));
271
- send({ type: 'layout', layoutVersion, width: config.width, height: config.height, columns, rows, tiles: layout });
272
- }
273
-
274
- function renderTile(tileState, tileLayout) {
275
- const sourceWidth = tileState.width;
276
- const sourceHeight = tileState.height;
277
- const scale = Math.min(tileLayout.width / sourceWidth, tileLayout.height / sourceHeight);
278
- const width = Math.max(1, Math.floor(sourceWidth * scale));
279
- const height = Math.max(1, Math.floor(sourceHeight * scale));
280
- const pixels = Buffer.allocUnsafe(width * height * 3);
281
- let target = 0;
282
- if (width === sourceWidth && height === sourceHeight) {
283
- for (let source = 0; source < tileState.rgb565.length; source += 2) {
284
- const pixel = tileState.rgb565[source] | (tileState.rgb565[source + 1] << 8);
285
- pixels[target++] = rgb565Red[pixel];
286
- pixels[target++] = rgb565Green[pixel];
287
- pixels[target++] = rgb565Blue[pixel];
288
- }
289
- } else {
290
- for (let y = 0; y < height; y += 1) {
291
- const sourceY = Math.min(sourceHeight - 1, Math.floor((y + 0.5) * sourceHeight / height));
292
- for (let x = 0; x < width; x += 1) {
293
- const sourceX = Math.min(sourceWidth - 1, Math.floor((x + 0.5) * sourceWidth / width));
294
- const source = (sourceY * sourceWidth + sourceX) * 2;
295
- const pixel = tileState.rgb565[source] | (tileState.rgb565[source + 1] << 8);
296
- pixels[target++] = rgb565Red[pixel];
297
- pixels[target++] = rgb565Green[pixel];
298
- pixels[target++] = rgb565Blue[pixel];
299
- }
300
- }
301
- }
302
- tileState.rendered = {
303
- pixels,
304
- width,
305
- height,
306
- x: tileLayout.x + Math.floor((tileLayout.width - width) / 2),
307
- y: tileLayout.y + Math.floor((tileLayout.height - height) / 2),
308
- layoutVersion
309
- };
310
- }
311
-
312
- function ingestFrame(message) {
313
- const deviceId = String(message.deviceId || '');
314
- if (!deviceId || !config.deviceIds.includes(deviceId)) return;
315
- const width = clamp(message.width, 1, config.sourceTileWidth, 0);
316
- const height = clamp(message.height, 1, config.sourceTileHeight, 0);
317
- const expectedLength = width * height * 2;
318
- if (!width || !height || Number(message.uncompressedByteLength) !== expectedLength) return;
319
- try {
320
- const compressed = Buffer.isBuffer(message.payload) ? message.payload : Buffer.from(message.payload || []);
321
- const rgb565 = decodeLzo1xBlock(new Uint8Array(compressed), expectedLength);
322
- const tileState = { width, height, rgb565, rendered: null, frameSeq: Number(message.frameSeq || 0) };
323
- latestTiles.set(deviceId, tileState);
324
- if (!encoder && encoderCandidates.length > 0) startEncoder();
325
- if (config.deviceIds.length > 0 && config.deviceIds.every(id => latestTiles.has(id))) {
326
- clearTimeout(inputWaitTimer);
327
- inputWaitTimer = null;
328
- }
329
- const tileLayout = layout.find(item => item.deviceId === deviceId);
330
- if (tileLayout) renderTile(tileState, tileLayout);
331
- } catch (error) {
332
- send({ type: 'log', level: 'warn', message: `Mode 4 frame rejected for ${deviceId}: ${error.message}` });
333
- }
334
- }
335
-
336
- function writeAtlasFrame() {
337
- if (latestTiles.size === 0) return;
338
- if (!encoder) {
339
- startEncoder();
340
- return;
341
- }
342
- const composeStartedAt = performance.now();
343
- const target = framePool.pop();
344
- const stdin = encoder?.child?.stdin;
345
- if (!target || !stdin || stdin.destroyed || !stdin.writable) {
346
- if (!target) poolStarved += 1;
347
- return;
348
- }
349
- target.fill(0);
350
- for (const tileLayout of layout) {
351
- const tileState = latestTiles.get(tileLayout.deviceId);
352
- if (!tileState) continue;
353
- if (!tileState.rendered || tileState.rendered.layoutVersion !== layoutVersion) renderTile(tileState, tileLayout);
354
- const rendered = tileState.rendered;
355
- for (let row = 0; row < rendered.height; row += 1) {
356
- const sourceStart = row * rendered.width * 3;
357
- const targetStart = ((rendered.y + row) * config.width + rendered.x) * 3;
358
- rendered.pixels.copy(target, targetStart, sourceStart, sourceStart + rendered.width * 3);
359
- }
360
- }
361
- lastComposeMs = Math.max(0, performance.now() - composeStartedAt);
362
- try {
363
- const encoderEntry = encoder;
364
- if (!encoderEntry.inputSeen) {
365
- encoderEntry.inputSeen = true;
366
- armEncoderStartupTimer(encoderEntry.child, encoderEntry.candidate);
367
- }
368
- stdin.write(target, error => {
369
- framePool.push(target);
370
- if (error && encoder?.child === encoderEntry.child && !isClosedPipeError(error)) {
371
- send({ type: 'log', level: 'warn', message: `Mode 4 encoder write: ${error.message}` });
372
- }
373
- });
374
- } catch (error) {
375
- framePool.push(target);
376
- if (!isClosedPipeError(error)) send({ type: 'log', level: 'warn', message: `Mode 4 encoder write: ${error.message}` });
377
- }
378
- }
379
-
380
- function startComposeClock() {
381
- clearTimeout(tickTimer);
382
- const intervalMs = 1000 / config.fps;
383
- nextTickAt = performance.now() + intervalMs;
384
- const tick = () => {
385
- if (closed) return;
386
- writeAtlasFrame();
387
- const now = performance.now();
388
- nextTickAt += intervalMs;
389
- if (nextTickAt < now - intervalMs) nextTickAt = now + intervalMs;
390
- tickTimer = setTimeout(tick, Math.max(0, nextTickAt - performance.now()));
391
- };
392
- tickTimer = setTimeout(tick, intervalMs);
393
- }
394
-
395
- function configure(value) {
396
- const next = normalizeConfig(value);
397
- const encoderChanged = next.width !== config.width || next.height !== config.height || next.fps !== config.fps;
398
- config = next;
399
- latestTiles = new Map([...latestTiles].filter(([deviceId]) => config.deviceIds.includes(deviceId)));
400
- clearTimeout(inputWaitTimer);
401
- inputWaitTimer = config.deviceIds.length > 0 ? setTimeout(() => {
402
- const missing = config.deviceIds.filter(deviceId => !latestTiles.has(deviceId));
403
- if (missing.length > 0) {
404
- send({
405
- type: 'log',
406
- level: 'warn',
407
- message: `Mode 4 waiting for Mode 2 input from ${missing.length}/${config.deviceIds.length} devices: ${missing.slice(0, 8).join(', ')}`
408
- });
409
- }
410
- }, 3000) : null;
411
- rebuildLayout();
412
- if (encoderChanged || !encoder) {
413
- stopEncoder();
414
- encoderCandidates = buildEncoderCandidates();
415
- encoderCandidateIndex = 0;
416
- if (latestTiles.size > 0) startEncoder();
417
- }
418
- startComposeClock();
419
- }
420
-
421
- process.on('message', message => {
422
- if (message?.type === 'configure') configure(message);
423
- else if (message?.type === 'frame') ingestFrame(message);
424
- else if (message?.type === 'close') shutdown();
425
- });
426
-
427
- function shutdown() {
428
- if (closed) return;
429
- closed = true;
430
- clearTimeout(tickTimer);
431
- clearTimeout(inputWaitTimer);
432
- stopEncoder();
433
- setTimeout(() => process.exit(0), 50).unref?.();
434
- }
435
-
436
- process.on('disconnect', shutdown);
437
- process.on('SIGTERM', shutdown);
438
- process.on('SIGINT', shutdown);
439
- send({ type: 'status', state: 'ready' });
440
-
1
+ #!/usr/bin/env node
2
+
3
+ import { spawn } from 'node:child_process';
4
+ import { createRequire } from 'node:module';
5
+ import { existsSync } from 'node:fs';
6
+ import { decodeLzo1xBlock } from './lzo1x.js';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const DEFAULT_WIDTH = 1920;
10
+ const DEFAULT_HEIGHT = 1080;
11
+ const DEFAULT_FPS = 20;
12
+ const MAX_DEVICES = 100;
13
+ const FRAME_POOL_SIZE = 8;
14
+ const MAX_TILE_WIDTH = 480;
15
+ const MAX_TILE_HEIGHT = 270;
16
+
17
+ const rgb565Red = new Uint8Array(65_536);
18
+ const rgb565Green = new Uint8Array(65_536);
19
+ const rgb565Blue = new Uint8Array(65_536);
20
+ for (let pixel = 0; pixel < 65_536; pixel += 1) {
21
+ rgb565Red[pixel] = (((pixel >> 11) & 0x1f) * 255 / 31) | 0;
22
+ rgb565Green[pixel] = (((pixel >> 5) & 0x3f) * 255 / 63) | 0;
23
+ rgb565Blue[pixel] = ((pixel & 0x1f) * 255 / 31) | 0;
24
+ }
25
+
26
+ let config = normalizeConfig({});
27
+ let layoutVersion = 0;
28
+ let layout = [];
29
+ let latestTiles = new Map();
30
+ let framePool = [];
31
+ let encoder = null;
32
+ let encoderCandidateIndex = 0;
33
+ let encoderCandidates = [];
34
+ let encoderOutputSeen = false;
35
+ let encoderGeneration = 0;
36
+ let encoderRestartTimer = null;
37
+ let encoderStartupTimer = null;
38
+ let inputWaitTimer = null;
39
+ let outputBuffer = Buffer.alloc(0);
40
+ let frameSeq = 0;
41
+ let tickTimer = null;
42
+ let nextTickAt = 0;
43
+ let closed = false;
44
+ let lastComposeMs = 0;
45
+ let poolStarved = 0;
46
+ const ENCODER_STARTUP_OUTPUT_TIMEOUT_MS = 8_000;
47
+
48
+ function clamp(value, min, max, fallback) {
49
+ const number = Number(value);
50
+ return Number.isFinite(number) ? Math.max(min, Math.min(max, Math.round(number))) : fallback;
51
+ }
52
+
53
+ function normalizeConfig(value) {
54
+ const deviceIds = [...new Set((Array.isArray(value?.deviceIds) ? value.deviceIds : [])
55
+ .map(item => String(item || '').trim()).filter(Boolean))].slice(0, MAX_DEVICES);
56
+ const maxWidth = clamp(value?.width, 640, 3840, DEFAULT_WIDTH);
57
+ const maxHeight = clamp(value?.height, 360, 2160, DEFAULT_HEIGHT);
58
+ const sharpTiles = Number(value?.tileWidth) >= 480 || Number(value?.tileHeight) >= 270;
59
+ const sourceTileWidth = sharpTiles ? 480 : 320;
60
+ const sourceTileHeight = sharpTiles ? 270 : 180;
61
+ const count = Math.max(1, deviceIds.length);
62
+ const columns = Math.max(1, Math.ceil(Math.sqrt(count)));
63
+ const rows = Math.max(1, Math.ceil(count / columns));
64
+ const tileWidth = Math.max(2, Math.min(sourceTileWidth, Math.floor(maxWidth / columns))) & ~1;
65
+ const tileHeight = Math.max(2, Math.min(sourceTileHeight, Math.floor(maxHeight / rows))) & ~1;
66
+ return {
67
+ deviceIds,
68
+ maxWidth,
69
+ maxHeight,
70
+ width: tileWidth * columns,
71
+ height: tileHeight * rows,
72
+ columns,
73
+ rows,
74
+ tileWidth,
75
+ tileHeight,
76
+ sourceTileWidth,
77
+ sourceTileHeight,
78
+ fps: clamp(value?.fps, 1, 30, DEFAULT_FPS)
79
+ };
80
+ }
81
+
82
+ function send(message) {
83
+ if (process.connected) process.send?.(message);
84
+ }
85
+
86
+ function resolveFfmpegPaths() {
87
+ const paths = [];
88
+ const add = value => {
89
+ const path = String(value || '').trim();
90
+ if (!path || paths.includes(path)) return;
91
+ if (path === 'ffmpeg' || existsSync(path)) paths.push(path);
92
+ };
93
+ add(process.env.LIVEDESK_FFMPEG);
94
+ try { add(require('@ffmpeg-installer/ffmpeg')?.path); } catch {}
95
+ try { add(require('ffmpeg-static')); } catch {}
96
+ add('ffmpeg');
97
+ return paths;
98
+ }
99
+
100
+ function buildEncoderCandidates() {
101
+ const codecCandidates = process.platform === 'win32'
102
+ ? [
103
+ ['windows-nvenc', ['-c:v', 'h264_nvenc', '-preset', 'llhp', '-profile:v', 'baseline', '-rc:v', 'cbr_ld_hq', '-b:v', '6M', '-maxrate', '6M', '-bufsize', '1M', '-rc-lookahead', '0', '-zerolatency', '1', '-g', String(config.fps), '-bf', '0']],
104
+ ['windows-qsv', ['-c:v', 'h264_qsv', '-preset', 'veryfast', '-global_quality', '28', '-look_ahead', '0', '-g', String(config.fps), '-bf', '0']],
105
+ ['windows-amf', ['-c:v', 'h264_amf', '-quality', 'speed', '-usage', 'lowlatency', '-rc', 'cqp', '-qp_i', '25', '-qp_p', '28', '-g', String(config.fps), '-bf', '0']]
106
+ ]
107
+ : process.platform === 'darwin'
108
+ ? [['macos-videotoolbox', ['-c:v', 'h264_videotoolbox', '-realtime', '1', '-allow_sw', '0', '-b:v', '6M', '-g', String(config.fps), '-bf', '0']]]
109
+ : [['linux-nvenc', ['-c:v', 'h264_nvenc', '-preset', 'llhp', '-profile:v', 'baseline', '-rc-lookahead', '0', '-zerolatency', '1', '-g', String(config.fps), '-bf', '0']]];
110
+ codecCandidates.push(['software-x264', [
111
+ '-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency',
112
+ '-profile:v', 'baseline', '-crf', '28', '-g', String(config.fps),
113
+ '-keyint_min', String(config.fps), '-sc_threshold', '0', '-bf', '0',
114
+ '-x264-params', 'aud=1:repeat-headers=1'
115
+ ]]);
116
+ return resolveFfmpegPaths().flatMap(path => codecCandidates.map(([name, args]) => ({ path, name, args })));
117
+ }
118
+
119
+ function startEncoder() {
120
+ if (closed || encoder || encoderCandidates.length === 0) return;
121
+ if (encoderCandidateIndex >= encoderCandidates.length) {
122
+ send({ type: 'status', state: 'error', error: 'No Mode 4 H.264 encoder is available.' });
123
+ return;
124
+ }
125
+ const candidate = encoderCandidates[encoderCandidateIndex++];
126
+ encoderGeneration += 1;
127
+ const args = [
128
+ '-hide_banner', '-loglevel', 'warning',
129
+ '-f', 'rawvideo', '-pixel_format', 'rgb24',
130
+ '-video_size', `${config.width}x${config.height}`,
131
+ '-framerate', String(config.fps), '-i', 'pipe:0', '-an',
132
+ ...candidate.args,
133
+ '-bsf:v', 'h264_metadata=aud=insert', '-f', 'h264', 'pipe:1'
134
+ ];
135
+ const child = spawn(candidate.path, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
136
+ encoder = { child, candidate, inputSeen: false };
137
+ encoderOutputSeen = false;
138
+ outputBuffer = Buffer.alloc(0);
139
+ child.stdout.on('data', appendEncodedBytes);
140
+ child.stdin.on('error', error => {
141
+ if (encoder?.child === child && !isClosedPipeError(error)) {
142
+ send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name} input: ${error.message}` });
143
+ }
144
+ });
145
+ child.stderr.on('data', chunk => {
146
+ const message = String(chunk || '').trim();
147
+ if (message) send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name}: ${message.slice(0, 600)}` });
148
+ });
149
+ child.on('error', error => send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name}: ${error.message}` }));
150
+ child.on('exit', code => {
151
+ clearTimeout(encoderStartupTimer);
152
+ encoderStartupTimer = null;
153
+ const wasCurrent = encoder?.child === child;
154
+ if (wasCurrent) encoder = null;
155
+ flushEncodedUnit();
156
+ if (closed) return;
157
+ send({ type: 'status', state: 'encoder-restart', encoder: candidate.name, code, emitted: encoderOutputSeen });
158
+ clearTimeout(encoderRestartTimer);
159
+ encoderRestartTimer = setTimeout(startEncoder, encoderOutputSeen ? 800 : 120);
160
+ });
161
+ send({ type: 'status', state: 'encoder-starting', encoder: candidate.name });
162
+ }
163
+
164
+ function isClosedPipeError(error) {
165
+ const code = String(error?.code || '').toUpperCase();
166
+ const message = String(error?.message || '').toLowerCase();
167
+ return code === 'EPIPE' || code === 'EOF' || code === 'ERR_STREAM_DESTROYED'
168
+ || message.includes('write eof') || message.includes('broken pipe');
169
+ }
170
+
171
+ function armEncoderStartupTimer(child, candidate) {
172
+ clearTimeout(encoderStartupTimer);
173
+ encoderStartupTimer = setTimeout(() => {
174
+ if (encoder?.child === child && encoder.inputSeen && !encoderOutputSeen) {
175
+ send({ type: 'log', level: 'warn', message: `Mode 4 ${candidate.name}: no output after receiving input; trying the next encoder.` });
176
+ try { child.kill(); } catch {}
177
+ }
178
+ }, ENCODER_STARTUP_OUTPUT_TIMEOUT_MS);
179
+ }
180
+
181
+ function stopEncoder() {
182
+ clearTimeout(encoderRestartTimer);
183
+ encoderRestartTimer = null;
184
+ clearTimeout(encoderStartupTimer);
185
+ encoderStartupTimer = null;
186
+ const child = encoder?.child;
187
+ encoder = null;
188
+ if (!child) return;
189
+ try { child.stdin.end(); } catch {}
190
+ setTimeout(() => { try { child.kill(); } catch {} }, 250).unref?.();
191
+ }
192
+
193
+ function findStartCodes(buffer) {
194
+ const starts = [];
195
+ for (let index = 0; index + 3 < buffer.length; index += 1) {
196
+ if (buffer[index] !== 0 || buffer[index + 1] !== 0) continue;
197
+ if (buffer[index + 2] === 1) {
198
+ starts.push({ offset: index, header: index + 3 });
199
+ index += 2;
200
+ } else if (buffer[index + 2] === 0 && buffer[index + 3] === 1) {
201
+ starts.push({ offset: index, header: index + 4 });
202
+ index += 3;
203
+ }
204
+ }
205
+ return starts;
206
+ }
207
+
208
+ function appendEncodedBytes(chunk) {
209
+ outputBuffer = outputBuffer.length ? Buffer.concat([outputBuffer, chunk]) : Buffer.from(chunk);
210
+ while (true) {
211
+ const auds = findStartCodes(outputBuffer).filter(start => (outputBuffer[start.header] & 0x1f) === 9);
212
+ if (auds.length < 2) break;
213
+ const boundary = auds[1].offset;
214
+ emitEncodedUnit(outputBuffer.subarray(0, boundary));
215
+ outputBuffer = outputBuffer.subarray(boundary);
216
+ }
217
+ }
218
+
219
+ function flushEncodedUnit() {
220
+ if (outputBuffer.length > 0) emitEncodedUnit(outputBuffer);
221
+ outputBuffer = Buffer.alloc(0);
222
+ }
223
+
224
+ function emitEncodedUnit(payload) {
225
+ if (!payload?.length) return;
226
+ const starts = findStartCodes(payload);
227
+ const isKeyFrame = starts.some(start => (payload[start.header] & 0x1f) === 5);
228
+ encoderOutputSeen = true;
229
+ clearTimeout(encoderStartupTimer);
230
+ encoderStartupTimer = null;
231
+ frameSeq += 1;
232
+ send({
233
+ type: 'frame',
234
+ payload: Buffer.from(payload),
235
+ metadata: {
236
+ frameSeq,
237
+ streamFrameSeq: frameSeq,
238
+ width: config.width,
239
+ height: config.height,
240
+ fps: config.fps,
241
+ durationUs: Math.round(1_000_000 / config.fps),
242
+ timestampUs: Math.round(frameSeq * 1_000_000 / config.fps),
243
+ isKeyFrame,
244
+ chunkType: isKeyFrame ? 'key' : 'delta',
245
+ hardwareEncoder: encoder?.candidate?.name || '',
246
+ encoderGeneration,
247
+ layoutVersion,
248
+ composeMs: lastComposeMs,
249
+ poolStarved,
250
+ readyTileCount: latestTiles.size,
251
+ tileCount: config.deviceIds.length
252
+ }
253
+ });
254
+ }
255
+
256
+ function rebuildLayout() {
257
+ const { columns, rows, tileWidth, tileHeight } = config;
258
+ layoutVersion += 1;
259
+ layout = config.deviceIds.map((deviceId, index) => ({
260
+ deviceId,
261
+ index,
262
+ column: index % columns,
263
+ row: Math.floor(index / columns),
264
+ x: (index % columns) * tileWidth,
265
+ y: Math.floor(index / columns) * tileHeight,
266
+ width: tileWidth,
267
+ height: tileHeight
268
+ }));
269
+ for (const tile of latestTiles.values()) tile.rendered = null;
270
+ framePool = Array.from({ length: FRAME_POOL_SIZE }, () => Buffer.alloc(config.width * config.height * 3));
271
+ send({ type: 'layout', layoutVersion, width: config.width, height: config.height, columns, rows, tiles: layout });
272
+ }
273
+
274
+ function renderTile(tileState, tileLayout) {
275
+ const sourceWidth = tileState.width;
276
+ const sourceHeight = tileState.height;
277
+ const scale = Math.min(tileLayout.width / sourceWidth, tileLayout.height / sourceHeight);
278
+ const width = Math.max(1, Math.floor(sourceWidth * scale));
279
+ const height = Math.max(1, Math.floor(sourceHeight * scale));
280
+ const pixels = Buffer.allocUnsafe(width * height * 3);
281
+ let target = 0;
282
+ if (width === sourceWidth && height === sourceHeight) {
283
+ for (let source = 0; source < tileState.rgb565.length; source += 2) {
284
+ const pixel = tileState.rgb565[source] | (tileState.rgb565[source + 1] << 8);
285
+ pixels[target++] = rgb565Red[pixel];
286
+ pixels[target++] = rgb565Green[pixel];
287
+ pixels[target++] = rgb565Blue[pixel];
288
+ }
289
+ } else {
290
+ for (let y = 0; y < height; y += 1) {
291
+ const sourceY = Math.min(sourceHeight - 1, Math.floor((y + 0.5) * sourceHeight / height));
292
+ for (let x = 0; x < width; x += 1) {
293
+ const sourceX = Math.min(sourceWidth - 1, Math.floor((x + 0.5) * sourceWidth / width));
294
+ const source = (sourceY * sourceWidth + sourceX) * 2;
295
+ const pixel = tileState.rgb565[source] | (tileState.rgb565[source + 1] << 8);
296
+ pixels[target++] = rgb565Red[pixel];
297
+ pixels[target++] = rgb565Green[pixel];
298
+ pixels[target++] = rgb565Blue[pixel];
299
+ }
300
+ }
301
+ }
302
+ tileState.rendered = {
303
+ pixels,
304
+ width,
305
+ height,
306
+ x: tileLayout.x + Math.floor((tileLayout.width - width) / 2),
307
+ y: tileLayout.y + Math.floor((tileLayout.height - height) / 2),
308
+ layoutVersion
309
+ };
310
+ }
311
+
312
+ function ingestFrame(message) {
313
+ const deviceId = String(message.deviceId || '');
314
+ if (!deviceId || !config.deviceIds.includes(deviceId)) return;
315
+ const width = clamp(message.width, 1, config.sourceTileWidth, 0);
316
+ const height = clamp(message.height, 1, config.sourceTileHeight, 0);
317
+ const expectedLength = width * height * 2;
318
+ if (!width || !height || Number(message.uncompressedByteLength) !== expectedLength) return;
319
+ try {
320
+ const compressed = Buffer.isBuffer(message.payload) ? message.payload : Buffer.from(message.payload || []);
321
+ const rgb565 = decodeLzo1xBlock(new Uint8Array(compressed), expectedLength);
322
+ const tileState = { width, height, rgb565, rendered: null, frameSeq: Number(message.frameSeq || 0) };
323
+ latestTiles.set(deviceId, tileState);
324
+ if (!encoder && encoderCandidates.length > 0) startEncoder();
325
+ if (config.deviceIds.length > 0 && config.deviceIds.every(id => latestTiles.has(id))) {
326
+ clearTimeout(inputWaitTimer);
327
+ inputWaitTimer = null;
328
+ }
329
+ const tileLayout = layout.find(item => item.deviceId === deviceId);
330
+ if (tileLayout) renderTile(tileState, tileLayout);
331
+ } catch (error) {
332
+ send({ type: 'log', level: 'warn', message: `Mode 4 frame rejected for ${deviceId}: ${error.message}` });
333
+ }
334
+ }
335
+
336
+ function writeAtlasFrame() {
337
+ if (latestTiles.size === 0) return;
338
+ if (!encoder) {
339
+ startEncoder();
340
+ return;
341
+ }
342
+ const composeStartedAt = performance.now();
343
+ const target = framePool.pop();
344
+ const stdin = encoder?.child?.stdin;
345
+ if (!target || !stdin || stdin.destroyed || !stdin.writable) {
346
+ if (!target) poolStarved += 1;
347
+ return;
348
+ }
349
+ target.fill(0);
350
+ for (const tileLayout of layout) {
351
+ const tileState = latestTiles.get(tileLayout.deviceId);
352
+ if (!tileState) continue;
353
+ if (!tileState.rendered || tileState.rendered.layoutVersion !== layoutVersion) renderTile(tileState, tileLayout);
354
+ const rendered = tileState.rendered;
355
+ for (let row = 0; row < rendered.height; row += 1) {
356
+ const sourceStart = row * rendered.width * 3;
357
+ const targetStart = ((rendered.y + row) * config.width + rendered.x) * 3;
358
+ rendered.pixels.copy(target, targetStart, sourceStart, sourceStart + rendered.width * 3);
359
+ }
360
+ }
361
+ lastComposeMs = Math.max(0, performance.now() - composeStartedAt);
362
+ try {
363
+ const encoderEntry = encoder;
364
+ if (!encoderEntry.inputSeen) {
365
+ encoderEntry.inputSeen = true;
366
+ armEncoderStartupTimer(encoderEntry.child, encoderEntry.candidate);
367
+ }
368
+ stdin.write(target, error => {
369
+ framePool.push(target);
370
+ if (error && encoder?.child === encoderEntry.child && !isClosedPipeError(error)) {
371
+ send({ type: 'log', level: 'warn', message: `Mode 4 encoder write: ${error.message}` });
372
+ }
373
+ });
374
+ } catch (error) {
375
+ framePool.push(target);
376
+ if (!isClosedPipeError(error)) send({ type: 'log', level: 'warn', message: `Mode 4 encoder write: ${error.message}` });
377
+ }
378
+ }
379
+
380
+ function startComposeClock() {
381
+ clearTimeout(tickTimer);
382
+ const intervalMs = 1000 / config.fps;
383
+ nextTickAt = performance.now() + intervalMs;
384
+ const tick = () => {
385
+ if (closed) return;
386
+ writeAtlasFrame();
387
+ const now = performance.now();
388
+ nextTickAt += intervalMs;
389
+ if (nextTickAt < now - intervalMs) nextTickAt = now + intervalMs;
390
+ tickTimer = setTimeout(tick, Math.max(0, nextTickAt - performance.now()));
391
+ };
392
+ tickTimer = setTimeout(tick, intervalMs);
393
+ }
394
+
395
+ function configure(value) {
396
+ const next = normalizeConfig(value);
397
+ const encoderChanged = next.width !== config.width || next.height !== config.height || next.fps !== config.fps;
398
+ config = next;
399
+ latestTiles = new Map([...latestTiles].filter(([deviceId]) => config.deviceIds.includes(deviceId)));
400
+ clearTimeout(inputWaitTimer);
401
+ inputWaitTimer = config.deviceIds.length > 0 ? setTimeout(() => {
402
+ const missing = config.deviceIds.filter(deviceId => !latestTiles.has(deviceId));
403
+ if (missing.length > 0) {
404
+ send({
405
+ type: 'log',
406
+ level: 'warn',
407
+ message: `Mode 4 waiting for Mode 2 input from ${missing.length}/${config.deviceIds.length} devices: ${missing.slice(0, 8).join(', ')}`
408
+ });
409
+ }
410
+ }, 3000) : null;
411
+ rebuildLayout();
412
+ if (encoderChanged || !encoder) {
413
+ stopEncoder();
414
+ encoderCandidates = buildEncoderCandidates();
415
+ encoderCandidateIndex = 0;
416
+ if (latestTiles.size > 0) startEncoder();
417
+ }
418
+ startComposeClock();
419
+ }
420
+
421
+ process.on('message', message => {
422
+ if (message?.type === 'configure') configure(message);
423
+ else if (message?.type === 'frame') ingestFrame(message);
424
+ else if (message?.type === 'close') shutdown();
425
+ });
426
+
427
+ function shutdown() {
428
+ if (closed) return;
429
+ closed = true;
430
+ clearTimeout(tickTimer);
431
+ clearTimeout(inputWaitTimer);
432
+ stopEncoder();
433
+ setTimeout(() => process.exit(0), 50).unref?.();
434
+ }
435
+
436
+ process.on('disconnect', shutdown);
437
+ process.on('SIGTERM', shutdown);
438
+ process.on('SIGINT', shutdown);
439
+ send({ type: 'status', state: 'ready' });
440
+