c64-ready 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,128 @@
1
+ // Minimal, plain-JS C64WASM wrapper used by the headless CLI.
2
+ // This is a direct JS translation of the TypeScript wrapper in
3
+ // src/emulator/c64-wasm.ts so the CLI can instantiate the WASM
4
+ // binary without requiring the compiled `dist-ts` artifact.
5
+
6
+ export class C64WASM {
7
+ exports = null;
8
+ heap = null;
9
+ wasmMemory = null;
10
+
11
+ static DYNAMICTOP_PTR = 5583504;
12
+ static DYNAMIC_BASE = 10826544;
13
+ static INITIAL_PAGES = 256;
14
+
15
+ async instantiate(wasmBinary, extraEnv) {
16
+ const mem = new WebAssembly.Memory({ initial: C64WASM.INITIAL_PAGES });
17
+ this.wasmMemory = mem;
18
+
19
+ const importObject = {
20
+ env: { ...this.makeEnvImports(mem), ...(extraEnv ?? {}) },
21
+ wasi_snapshot_preview1: this.makeWasiImports(mem),
22
+ };
23
+
24
+ try {
25
+ const result = await WebAssembly.instantiate(wasmBinary, importObject);
26
+ this.exports = result.instance.exports;
27
+ this.updateHeapViews();
28
+
29
+ // Initialise the sbrk heap pointer so malloc knows where free memory starts
30
+ new DataView(mem.buffer).setUint32(C64WASM.DYNAMICTOP_PTR, C64WASM.DYNAMIC_BASE, true);
31
+
32
+ if (this.exports.__wasm_call_ctors) this.exports.__wasm_call_ctors();
33
+ } catch (err) {
34
+ throw new Error(`WASM instantiation failed: ${err}`);
35
+ }
36
+ }
37
+
38
+ allocAndWrite(data) {
39
+ if (!this.exports || !this.heap) throw new Error('WASM not ready');
40
+ const ptr = this.exports.malloc(data.length);
41
+ // malloc may have grown memory, so refresh views before writing
42
+ this.updateHeapViews();
43
+ this.heap.heapU8.set(data, ptr);
44
+ return ptr;
45
+ }
46
+
47
+ free(ptr) {
48
+ if (this.exports && this.exports.free) this.exports.free(ptr);
49
+ }
50
+
51
+ updateHeapViews() {
52
+ if (!this.wasmMemory) throw new Error('WASM memory not initialized');
53
+ const buffer = this.wasmMemory.buffer;
54
+ this.heap = {
55
+ heapU8: new Uint8Array(buffer),
56
+ heapF32: new Float32Array(buffer),
57
+ heapU32: new Uint32Array(buffer),
58
+ };
59
+ }
60
+
61
+ makeEnvImports(mem) {
62
+ return {
63
+ memory: mem,
64
+
65
+ emscripten_get_sbrk_ptr: () => C64WASM.DYNAMICTOP_PTR,
66
+
67
+ emscripten_resize_heap: (requestedSize) => {
68
+ const PAGE_MULTIPLE = 65536;
69
+ const maxHeapSize = 2147483648 - PAGE_MULTIPLE;
70
+ if (requestedSize > maxHeapSize) return 0;
71
+
72
+ const oldSize = mem.buffer.byteLength;
73
+ const minHeapSize = 16777216;
74
+ for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {
75
+ let overGrown = oldSize * (1 + 0.2 / cutDown);
76
+ overGrown = Math.min(overGrown, requestedSize + 100663296);
77
+ const newSize = Math.min(
78
+ maxHeapSize,
79
+ Math.ceil(Math.max(minHeapSize, requestedSize, overGrown) / PAGE_MULTIPLE) * PAGE_MULTIPLE,
80
+ );
81
+ try {
82
+ mem.grow((newSize - mem.buffer.byteLength + 65535) >>> 16);
83
+ this.updateHeapViews();
84
+ return 1;
85
+ } catch {
86
+ // retry with less aggressive growth
87
+ }
88
+ }
89
+ return 0;
90
+ },
91
+
92
+ emscripten_memcpy_big: (dest, src, num) => {
93
+ new Uint8Array(mem.buffer).copyWithin(dest, src, src + num);
94
+ return dest;
95
+ },
96
+
97
+ setTempRet0: (_val) => {},
98
+
99
+ emscripten_asm_const_iii: (_code, _sig, _val) => 0,
100
+
101
+ table: new WebAssembly.Table({ initial: 512, maximum: 512, element: 'anyfunc' }),
102
+ };
103
+ }
104
+
105
+ makeWasiImports(mem) {
106
+ return {
107
+ fd_write: (fd, iovs, iovs_len, nwritten) => {
108
+ const view = new DataView(mem.buffer);
109
+ const u8 = new Uint8Array(mem.buffer);
110
+ let written = 0;
111
+ for (let i = 0; i < iovs_len; i++) {
112
+ const ptr = view.getUint32(iovs + i * 8, true);
113
+ const len = view.getUint32(iovs + i * 8 + 4, true);
114
+ if (fd === 2) {
115
+ const text = new TextDecoder().decode(u8.subarray(ptr, ptr + len));
116
+ console.error(text);
117
+ }
118
+ written += len;
119
+ }
120
+ view.setUint32(nwritten, written, true);
121
+ return 0;
122
+ },
123
+ };
124
+ }
125
+ }
126
+
127
+ export default C64WASM;
128
+
@@ -0,0 +1,442 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'child_process';
3
+ import fs from 'fs/promises';
4
+ import fsSync from 'fs';
5
+ import path from 'path';
6
+ import net from 'net';
7
+
8
+ export class FFmpegRunner {
9
+ proc = null;
10
+ stdin = null;
11
+ outputPath = null;
12
+ _stderr = '';
13
+ _exitCode = null;
14
+ _audio = false;
15
+ _sampleRate = 44100;
16
+ _audioChunks = [];
17
+ _verbose = false;
18
+ _isUrl = false;
19
+ _outPath = null;
20
+ _fps = 50;
21
+ _width = 384;
22
+ _height = 272;
23
+ _videoTempPath = null;
24
+
25
+ // ── Live-audio (FIFO) state ───────────────────────────────────────────────
26
+ // Strategy B uses a named pipe (FIFO) for audio delivery.
27
+ // Node opens the write end; ffmpeg opens the read end via a file path.
28
+ // This is kernel-synchronised — no net.Server race, no unix socket.
29
+ _audioFifoPath = null; // path to the FIFO
30
+ _audioFifoFd = null; // write-end file descriptor (opened after ffmpeg starts)
31
+ _audioFifoStream = null; // WriteStream wrapping the fd
32
+ _liveAudio = false;
33
+
34
+ // ── Process health ────────────────────────────────────────────────────────
35
+ _diedResolve = null;
36
+ died = new Promise((resolve) => { this._diedResolve = resolve; });
37
+
38
+ async start(options = {}) {
39
+ const width = options.width || 384;
40
+ const height = options.height || 272;
41
+ const fps = options.fps || 60;
42
+ const verbose = !!options.verbose;
43
+ const audio = !!options.audio;
44
+ const sampleRate = options.sampleRate || 44100;
45
+
46
+ this._audio = audio;
47
+ this._sampleRate = sampleRate;
48
+ this._audioChunks = [];
49
+ this._verbose = verbose;
50
+ this._fps = fps;
51
+ this._width = width;
52
+ this._height = height;
53
+ this._liveAudio = false;
54
+ this._exitCode = null;
55
+ this._stderr = '';
56
+ this._audioFifoPath = null;
57
+ this._audioFifoFd = null;
58
+ this._audioFifoStream = null;
59
+
60
+ // Reset died promise for this run
61
+ this.died = new Promise((resolve) => { this._diedResolve = resolve; });
62
+
63
+ const isUrl = typeof options.output === 'string' && /^[a-zA-Z]+:\/\//.test(options.output);
64
+ const outPath = isUrl
65
+ ? options.output
66
+ : path.resolve(options.output || path.join(process.cwd(), 'temp', `c64-record-${Date.now()}.mp4`));
67
+
68
+ if (!isUrl) {
69
+ try { await fs.mkdir(path.dirname(outPath), { recursive: true }); } catch (e) {}
70
+ }
71
+
72
+ this._isUrl = isUrl;
73
+ this._outPath = outPath;
74
+
75
+ // ── Raw mode ─────────────────────────────────────────────────────────────
76
+ if (options.raw) {
77
+ try {
78
+ this._raw = true;
79
+ this.outputPath = outPath;
80
+ await fs.mkdir(path.dirname(outPath), { recursive: true });
81
+ this._stream = fsSync.createWriteStream(outPath, { flags: 'w' });
82
+ return true;
83
+ } catch (e) {
84
+ this._stderr = `raw-open-failed: ${String(e)}`;
85
+ return false;
86
+ }
87
+ }
88
+
89
+ // ── Strategy ──────────────────────────────────────────────────────────────
90
+ // A) No audio (file or URL):
91
+ // Single pass — video-only stdin pipe → output file/URL.
92
+ // For file output with --duration this is fine.
93
+ // For URL/RTMP without audio this is the simple path.
94
+ //
95
+ // B) With audio (file or URL):
96
+ // Single pass with FIFO audio — video on stdin, audio on named FIFO.
97
+ // ffmpeg reads both in real-time, encoding at exactly the rate frames
98
+ // arrive. This is the ONLY correct approach for keeping A/V in sync:
99
+ // the FIFO backpressure means ffmpeg never runs faster than Node feeds it.
100
+ // (Two-pass was previously used for file+audio but caused fast video
101
+ // because pass-1 encoded to a temp file at maximum speed.)
102
+
103
+ if (audio) {
104
+ // ── Strategy B: single-pass FIFO audio (file or URL) ─────────────────
105
+
106
+ // For RTMP outputs: verify host is TCP-reachable before spawning ffmpeg.
107
+ if (isUrl && /^rtmps?:\/\//i.test(outPath)) {
108
+ const rtmpMatch = outPath.match(/^rtmps?:\/\/([^/:]+):?(\d+)?/i);
109
+ if (rtmpMatch) {
110
+ const host = rtmpMatch[1];
111
+ const port = parseInt(rtmpMatch[2] || '1935', 10);
112
+ const maxWaitMs = 30000;
113
+ const probeIntervalMs = 1000;
114
+ let waited = 0;
115
+ if (verbose) console.error(`[ffmpeg-runner] probing RTMP host ${host}:${port}...`);
116
+ while (waited < maxWaitMs) {
117
+ const reachable = await new Promise((resolve) => {
118
+ const s = new net.Socket();
119
+ s.setTimeout(2000);
120
+ s.once('connect', () => { s.destroy(); resolve(true); });
121
+ s.once('error', () => { s.destroy(); resolve(false); });
122
+ s.once('timeout', () => { s.destroy(); resolve(false); });
123
+ s.connect(port, host);
124
+ });
125
+ if (reachable) {
126
+ if (verbose) console.error(`[ffmpeg-runner] RTMP host ${host}:${port} reachable — waiting 5s for NMS to stabilise`);
127
+ await new Promise((r) => setTimeout(r, 5000));
128
+ break;
129
+ }
130
+ if (verbose) console.error(`[ffmpeg-runner] RTMP host not ready, retrying in ${probeIntervalMs}ms...`);
131
+ await new Promise((r) => setTimeout(r, probeIntervalMs));
132
+ waited += probeIntervalMs;
133
+ }
134
+ if (waited >= maxWaitMs) {
135
+ console.error(`[ffmpeg-runner] RTMP host ${host}:${port} unreachable after ${maxWaitMs}ms`);
136
+ }
137
+ }
138
+ }
139
+
140
+ // Use /dev/fd/3 instead of a FIFO file.
141
+ // A true pipe (fd3) is non-seekable — ffmpeg can't seek it, so it won't
142
+ // try to re-read from the start after probing, avoiding the "no packets"
143
+ // error that occurs when using a FIFO path with file-based output.
144
+ const args = [];
145
+ if (!verbose) args.push('-hide_banner', '-nostats', '-loglevel', 'warning');
146
+ // Skip input probing — formats are fully specified so probing only adds latency.
147
+ args.push('-probesize', '32', '-analyzeduration', '0');
148
+ // For URL outputs (RTMP), -re reads the input at its native frame rate,
149
+ // pacing the stream output at exactly the target fps instead of encoding
150
+ // as fast as possible and bursting frames to the RTMP server.
151
+ if (isUrl) args.push('-re');
152
+ // Video input: stdin (fd0)
153
+ args.push(
154
+ '-thread_queue_size', '512',
155
+ '-f', 'rawvideo', '-pix_fmt', 'rgba',
156
+ '-s', `${width}x${height}`, '-r', String(fps),
157
+ '-i', 'pipe:0',
158
+ );
159
+ // Audio input: fd3 pipe
160
+ args.push(
161
+ '-thread_queue_size', '512',
162
+ '-f', 'f32le', '-ar', String(sampleRate), '-ac', '1',
163
+ '-i', 'pipe:3',
164
+ );
165
+ // Encoders
166
+ args.push(
167
+ '-pix_fmt', 'yuv420p',
168
+ '-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency',
169
+ '-g', String(Math.max(1, Math.round(fps))),
170
+ '-c:a', 'aac', '-b:a', '128k',
171
+ );
172
+ // Output format + destination
173
+ if (isUrl) {
174
+ args.push('-f', 'flv');
175
+ }
176
+ args.push('-y', outPath);
177
+
178
+ if (verbose) console.error(`[ffmpeg-runner] strategy B (pipe audio fd3, ${isUrl ? 'rtmp' : 'file'}):`, args.join(' '));
179
+
180
+ // Spawn with 4 stdio streams: [stdin, stdout, stderr, audioWrite]
181
+ this.proc = spawn('ffmpeg', args, { stdio: ['pipe', 'pipe', 'pipe', 'pipe'] });
182
+ this.stdin = this.proc.stdin;
183
+ this.outputPath = outPath;
184
+ this._liveAudio = true;
185
+
186
+ // fd3 is the audio pipe write end — store it as _audioFifoStream for writeFrame()
187
+ const audioWritePipe = this.proc.stdio[3];
188
+ if (audioWritePipe) {
189
+ audioWritePipe.on('error', () => {});
190
+ this._audioFifoStream = audioWritePipe;
191
+ if (verbose) console.error('[ffmpeg-runner] audio pipe fd3 ready');
192
+ }
193
+
194
+ // Clean up FIFO path tracking (not used for pipe mode)
195
+ this._audioFifoPath = null;
196
+ this._audioFifoFd = null;
197
+
198
+ this.proc.on('error', (err) => { this._stderr += `\nspawn error: ${String(err)}`; try { this.stdin = null; } catch (e) {} });
199
+ this.proc.stdin && this.proc.stdin.on('error', () => {});
200
+ try {
201
+ this.proc.stdout && this.proc.stdout.on('data', (d) => { this._stderr += String(d); if (verbose) process.stdout.write(d); });
202
+ this.proc.stderr && this.proc.stderr.on('data', (d) => { this._stderr += String(d); if (verbose) process.stderr.write(d); });
203
+ } catch (e) {}
204
+ this.proc.on('close', (code) => {
205
+ this._exitCode = code;
206
+ try { this.stdin = null; } catch (e) {}
207
+ if (this._diedResolve) { this._diedResolve(code); this._diedResolve = null; }
208
+ if (code !== 0 && code !== null) {
209
+ console.error(`[ffmpeg-runner] ffmpeg exited unexpectedly (code ${code}): ${this._stderr.slice(-400)}`);
210
+ }
211
+ // Audio pipe (fd3) is owned by the child process — just null the ref.
212
+ this._audioFifoStream = null;
213
+ this._audioFifoFd = null;
214
+ });
215
+ try { this.proc.stdin.setMaxListeners(100); } catch (e) {}
216
+
217
+ // No silent pre-prime needed: ffmpeg reads video (pipe:0) and audio
218
+ // (pipe:3) on independent threads, so neither blocks the other at
219
+ // startup. Previously 20 silent frames were written here, but that
220
+ // created a 20-frame audio lead that made audio_duration > video_duration
221
+ // in the output file, causing video to appear to play back too fast.
222
+
223
+ return !!this.proc && !!this.proc.pid;
224
+ }
225
+
226
+ // ── Strategy A: video-only single pass ────────────────────────────────
227
+ // No audio — simple stdin pipe to output. For file output the loop's
228
+ // FPS throttle (setTimeout) controls playback speed.
229
+ const args = [];
230
+ if (!verbose) args.push('-hide_banner', '-nostats', '-loglevel', 'warning');
231
+ args.push(
232
+ '-f', 'rawvideo', '-pix_fmt', 'rgba',
233
+ '-s', `${width}x${height}`, '-r', String(fps),
234
+ '-i', 'pipe:0',
235
+ '-pix_fmt', 'yuv420p',
236
+ '-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency',
237
+ '-g', String(Math.max(1, Math.round(fps))),
238
+ '-an',
239
+ );
240
+ if (isUrl) args.push('-f', 'flv');
241
+ args.push('-y', outPath);
242
+
243
+ if (verbose) console.error(`[ffmpeg-runner] strategy A (video-only, ${isUrl ? 'rtmp' : 'file'}):`, args.join(' '));
244
+
245
+ this.proc = spawn('ffmpeg', args, { stdio: ['pipe', 'pipe', 'pipe'] });
246
+ this.stdin = this.proc.stdin;
247
+ this.outputPath = outPath;
248
+ this._stderr = '';
249
+ this._exitCode = null;
250
+
251
+ this.proc.on('error', (err) => { this._stderr += `\nspawn error: ${String(err)}`; try { this.stdin = null; } catch (e) {} });
252
+ this.proc.stdin && this.proc.stdin.on('error', () => {});
253
+ try {
254
+ this.proc.stdout && this.proc.stdout.on('data', (d) => { this._stderr += String(d); if (verbose) process.stdout.write(d); });
255
+ this.proc.stderr && this.proc.stderr.on('data', (d) => { this._stderr += String(d); if (verbose) process.stderr.write(d); });
256
+ } catch (e) {}
257
+ this.proc.on('close', (code) => {
258
+ this._exitCode = code;
259
+ try { this.stdin = null; } catch (e) {}
260
+ if (this._diedResolve) { this._diedResolve(code); this._diedResolve = null; }
261
+ if (code !== 0 && code !== null) {
262
+ console.error(`[ffmpeg-runner] ffmpeg exited unexpectedly (code ${code}): ${this._stderr.slice(-400)}`);
263
+ }
264
+ });
265
+ try { this.proc.stdin.setMaxListeners(100); } catch (e) {}
266
+
267
+ return !!this.proc && !!this.proc.pid;
268
+ }
269
+
270
+ // ── Frame write ───────────────────────────────────────────────────────────
271
+
272
+ /** Returns true if the ffmpeg process is still running. */
273
+ isAlive() {
274
+ return !!(this.proc && this._exitCode === null);
275
+ }
276
+
277
+ writeFrame(videoFrame, audioChunk) {
278
+ if (this._raw) {
279
+ try {
280
+ if (this._stream && !this._stream.destroyed)
281
+ this._stream.write(Buffer.from(videoFrame.buffer, videoFrame.byteOffset, videoFrame.byteLength));
282
+ } catch (e) {}
283
+ return Promise.resolve(true);
284
+ }
285
+
286
+ // If ffmpeg process has exited, surface the error so the caller can abort
287
+ if (this.proc && this._exitCode !== null) {
288
+ return Promise.reject(new Error(`ffmpeg process exited (code ${this._exitCode})`));
289
+ }
290
+
291
+ // Audio handling — write BEFORE video so it's in the kernel pipe buffer
292
+ // when ffmpeg looks for matching audio to interleave with the video frame.
293
+ if (this._audio && audioChunk) {
294
+ if (this._liveAudio && this._audioFifoStream && !this._audioFifoStream.destroyed) {
295
+ try {
296
+ this._audioFifoStream.write(
297
+ Buffer.from(audioChunk.buffer, audioChunk.byteOffset, audioChunk.byteLength)
298
+ );
299
+ } catch (e) {}
300
+ } else if (!this._liveAudio) {
301
+ this._audioChunks.push(
302
+ Buffer.from(audioChunk.buffer, audioChunk.byteOffset, audioChunk.byteLength)
303
+ );
304
+ }
305
+ }
306
+
307
+ // Video: write to stdin.
308
+ //
309
+ // Strategy B (liveAudio): fire-and-forget for video.
310
+ // With two pipe inputs, awaiting drain deadlocks: ffmpeg's audio reader
311
+ // thread (pipe:3) is slow to open, so while we block on the video stdin
312
+ // drain the audio thread hasn't started reading yet. ffmpeg never drains
313
+ // video stdin → watchdog kills ffmpeg.
314
+ // Real-time pacing is enforced by:
315
+ // - RTMP: -re flag makes ffmpeg read at native frame rate
316
+ // - File: -r fps bakes correct timestamps; player decodes at real speed
317
+ // - Both: the headless loop's setTimeout throttle keeps us near target fps
318
+ //
319
+ // Strategy A (video-only): await drain — provides real backpressure.
320
+ return new Promise((resolve) => {
321
+ if (!this.stdin || this.stdin.destroyed) return resolve(false);
322
+ try {
323
+ const vBuf = Buffer.from(videoFrame.buffer, videoFrame.byteOffset, videoFrame.byteLength);
324
+ if (this._liveAudio) {
325
+ // Fire-and-forget: write and resolve immediately so the headless
326
+ // loop's setTimeout can throttle to target fps.
327
+ this.stdin.write(vBuf);
328
+ setImmediate(() => resolve(true));
329
+ return;
330
+ }
331
+ // Strategy A: drain-based backpressure
332
+ const flushed = this.stdin.write(vBuf);
333
+ if (!flushed) {
334
+ let resolved = false;
335
+ const done = (val) => {
336
+ if (resolved) return;
337
+ resolved = true;
338
+ clearInterval(poll);
339
+ clearTimeout(watchdog);
340
+ resolve(val);
341
+ };
342
+ const poll = setInterval(() => {
343
+ if (this._exitCode !== null) done(false);
344
+ }, 100);
345
+ const watchdog = setTimeout(() => {
346
+ if (this.proc && this._exitCode === null) {
347
+ if (this._verbose) console.error('[ffmpeg-runner] stdin drain timeout — killing ffmpeg');
348
+ try { this.proc.kill('SIGTERM'); } catch (e) {}
349
+ }
350
+ done(false);
351
+ }, 15000);
352
+ this.stdin.once('drain', () => done(true));
353
+ } else {
354
+ setImmediate(() => resolve(true));
355
+ }
356
+ } catch (e) { resolve(false); }
357
+ });
358
+ }
359
+
360
+ // ── Legacy helpers ───────────────────────────────────────────────────────
361
+
362
+ tryWrite(frame) {
363
+ if (this._raw) {
364
+ try {
365
+ if (!this._stream || this._stream.destroyed) return false;
366
+ this._stream.write(Buffer.from(frame.buffer ?? frame, frame.byteOffset, frame.byteLength));
367
+ return true;
368
+ } catch (e) { return false; }
369
+ }
370
+ if (!this.stdin || this.stdin.destroyed) return false;
371
+ try {
372
+ this.stdin.write(Buffer.from(frame.buffer ?? frame, frame.byteOffset, frame.byteLength));
373
+ return true;
374
+ } catch (e) { return false; }
375
+ }
376
+
377
+ tryWriteAudio(samples) {
378
+ if (!this._audio) return false;
379
+ if (this._liveAudio && this._audioFifoStream && !this._audioFifoStream.destroyed) {
380
+ try {
381
+ this._audioFifoStream.write(Buffer.from(samples.buffer, samples.byteOffset, samples.byteLength));
382
+ return true;
383
+ } catch (e) { return false; }
384
+ }
385
+ this._audioChunks.push(Buffer.from(samples.buffer, samples.byteOffset, samples.byteLength));
386
+ return true;
387
+ }
388
+
389
+ // ── Stop ─────────────────────────────────────────────────────────────────
390
+
391
+ async stop() {
392
+ if (this._raw) {
393
+ if (this._stream) {
394
+ return new Promise((resolve) => {
395
+ this._stream.end(() => {
396
+ this._stream = null;
397
+ const out = this.outputPath;
398
+ this.outputPath = null;
399
+ resolve(out);
400
+ });
401
+ });
402
+ }
403
+ return;
404
+ }
405
+
406
+ if (!this.proc) return;
407
+
408
+ // ── Strategy B cleanup ────────────────────────────────────────────────
409
+ if (this._liveAudio) {
410
+ // Audio pipe (fd3) is owned by the child — end it to signal EOF to ffmpeg.
411
+ try { if (this._audioFifoStream && !this._audioFifoStream.destroyed) this._audioFifoStream.end(); } catch (e) {}
412
+ this._audioFifoStream = null;
413
+ this._audioFifoFd = null;
414
+ }
415
+
416
+ // End video stdin
417
+ try { this.stdin.end(); } catch (e) {}
418
+
419
+ await new Promise((resolve, reject) => {
420
+ const onClose = () => {
421
+ const code = this._exitCode;
422
+ const stderr = this._stderr;
423
+ this.proc = null;
424
+ this.stdin = null;
425
+ if (code !== 0 && code !== null)
426
+ return reject(new Error(`ffmpeg exited ${code}: ${stderr.slice(0, 1000)}`));
427
+ resolve();
428
+ };
429
+ if (this._exitCode !== null) return onClose();
430
+ this.proc.once('close', onClose);
431
+ setTimeout(() => { if (this.proc) try { this.proc.kill('SIGTERM'); } catch (e) {} }, 10000);
432
+ });
433
+
434
+ if (this._liveAudio) return this._outPath;
435
+
436
+ // Strategy A (video-only): ffmpeg wrote directly to outPath, nothing more to do.
437
+ return this._outPath;
438
+ }
439
+ }
440
+
441
+ export default FFmpegRunner;
442
+
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Minimal FFmpeg runner stub for headless MVP.
3
+ *
4
+ * This file provides a very small wrapper around child_process.spawn to demonstrate
5
+ * how frames/audio could be piped to an ffmpeg process. For the MVP we expose a
6
+ * start/stop API but do not implement the full piping logic — this keeps the
7
+ * library safe to run in browser builds while remaining useful in Node.
8
+ */
9
+
10
+ import { spawn, type ChildProcess } from 'child_process';
11
+
12
+ export class FFmpegRunner {
13
+ private proc: ChildProcess | null = null;
14
+
15
+ /**
16
+ * Start ffmpeg with the provided args. Returns true if spawn succeeded.
17
+ * In browser builds this will be a no-op and return false.
18
+ */
19
+ start(args: string[]): boolean {
20
+ try {
21
+ // Use Node's spawn import directly. This module is only used in
22
+ // headless Node.js environments and should not be bundled into
23
+ // browser builds.
24
+
25
+ // If the user passed an RTMP (or similar) output URL, ensure we include
26
+ // streaming-friendly encoder options unless the caller already provided
27
+ // them. We look for a URL like rtmp:// and, if found, insert a sensible
28
+ // default encoder config for low-latency live streaming.
29
+ let finalArgs = args.slice();
30
+ const outputIndex = finalArgs.findIndex((a) => a.startsWith('rtmp://'));
31
+
32
+ if (outputIndex !== -1) {
33
+ const hasPreset = finalArgs.some(
34
+ (a) => a === '-preset' || a === '-tune' || a === '-g' || a === '-c:v',
35
+ );
36
+ if (!hasPreset) {
37
+ // Insert before the output position
38
+ const streamOpts = [
39
+ '-c:v',
40
+ 'libx264',
41
+ '-preset',
42
+ 'ultrafast',
43
+ '-tune',
44
+ 'zerolatency',
45
+ '-pix_fmt',
46
+ 'yuv420p',
47
+ '-g',
48
+ '50',
49
+ ];
50
+ finalArgs = finalArgs
51
+ .slice(0, outputIndex)
52
+ .concat(streamOpts)
53
+ .concat(finalArgs.slice(outputIndex));
54
+ }
55
+ }
56
+
57
+ // Spawn ffmpeg and show its stdout/stderr to aid debugging in Node.
58
+ // Use a pipe for stdin so callers can write frames to ffmpeg if needed.
59
+ this.proc = spawn('ffmpeg', finalArgs, { stdio: ['pipe', 'inherit', 'inherit'] });
60
+ return this.proc != null;
61
+ } catch (_err) {
62
+ // ignore spawn errors (ffmpeg missing or not available in environment)
63
+ console.debug('[ffmpeg-runner] spawn failed', String(_err));
64
+ return false;
65
+ }
66
+ }
67
+
68
+ stop(): void {
69
+ if (this.proc && typeof this.proc.kill === 'function') {
70
+ this.proc.kill('SIGINT');
71
+ }
72
+ this.proc = null;
73
+ }
74
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Frame capture for headless operation
3
+ */
4
+
5
+ import type { FrameBuffer } from '../types';
6
+
7
+ export class FrameCapture {
8
+ private latestFrame: Uint8Array | null = null;
9
+ private frameQueue: Uint8Array[] = [];
10
+
11
+ capture(frame: FrameBuffer): void {
12
+ // Store latest frame (copy to ensure consumer owns the buffer)
13
+ this.latestFrame = frame.data.slice();
14
+ this.frameQueue.push(this.latestFrame);
15
+ }
16
+
17
+ getLatest(): Uint8Array | null {
18
+ return this.latestFrame;
19
+ }
20
+
21
+ getQueued(): Uint8Array[] {
22
+ const q = this.frameQueue;
23
+ this.frameQueue = [];
24
+ return q;
25
+ }
26
+
27
+ clearQueue(): void {
28
+ this.frameQueue = [];
29
+ }
30
+ }
@@ -0,0 +1,16 @@
1
+ // Declaration for './headless-cli.mjs' to satisfy imports from tests.
2
+ declare module './headless-cli.mjs' {
3
+ export interface RunHeadlessOptions {
4
+ argv?: string[];
5
+ instantiateFn?: (
6
+ wasmBinary: ArrayBuffer | Uint8Array,
7
+ importObject: unknown,
8
+ ) => Promise<{ instance: { exports: unknown } }>;
9
+ repoRoot?: string;
10
+ }
11
+ export function runHeadless(
12
+ options?: RunHeadlessOptions,
13
+ ): Promise<{ ok: boolean; output: unknown[] | string }>;
14
+ }
15
+
16
+ export {};