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,456 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import FFmpegRunner from './ffmpeg-runner.mjs';
5
+
6
+ /**
7
+ * Run headless emulator. Exported so tests can inject a fake WebAssembly.instantiate.
8
+ * options: { argv?: string[], instantiateFn?: (wasmBinary, importObject) => Promise<{ instance }>, repoRoot?: string }
9
+ */
10
+ export async function runHeadless(options = {}) {
11
+ const argv = options.argv ?? process.argv.slice(2);
12
+ const repoRoot = options.repoRoot ?? path.resolve(new URL('../../', import.meta.url).pathname);
13
+
14
+ // parse args
15
+ let wasmArg = null;
16
+ let gameArg = null;
17
+ let noGame = false;
18
+ let verbose = false;
19
+ let frames = 300;
20
+ let fps = 60;
21
+ let verify = false;
22
+ let record = false;
23
+ let audio = false;
24
+ // Use fixed timestep by default to keep emulation timing stable.
25
+ let useFixedDt = true;
26
+ let raw = false;
27
+ let output = null;
28
+ let durationSec = 0; // 0 means no --duration was passed → stream forever when recording
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ if (a === '--wasm' || a === '-w') wasmArg = argv[++i];
32
+ else if (a === '--game' || a === '-g') gameArg = argv[++i];
33
+ else if (a === '--frames' || a === '-n') frames = Number(argv[++i]);
34
+ else if (a === '--verify') verify = true;
35
+ else if (a === '--record') record = true;
36
+ else if (a === '--audio') audio = true;
37
+ else if (a === '--raw') raw = true;
38
+ else if (a === '--output' || a === '-o') output = argv[++i];
39
+ else if (a === '--duration' || a === '-d') durationSec = Number(argv[++i]);
40
+ else if (a === '--no-game') noGame = true;
41
+ else if (a === '--verbose') verbose = true;
42
+ else if (a === '--fps') fps = Number(argv[++i]);
43
+ else if (a === '--use-fixed-dt') useFixedDt = true;
44
+ else if (a === '--use-wall-clock') useFixedDt = false;
45
+ else if (a === '--help' || a === '-h') {
46
+ return { ok: false, output: 'help' };
47
+ }
48
+ }
49
+
50
+ const defaultWasmPaths = [
51
+ path.join(repoRoot, 'public', 'c64.wasm'),
52
+ path.join(repoRoot, 'src', 'emulator', 'c64.wasm'),
53
+ ];
54
+ const defaultGamePaths = [
55
+ path.join(repoRoot, 'public', 'games', 'cartridges', 'legend-of-wilf.crt'),
56
+ ];
57
+
58
+ async function findFirstExisting(paths) {
59
+ for (const p of paths) {
60
+ try {
61
+ await fs.access(p);
62
+ return p;
63
+ } catch (_) {}
64
+ }
65
+ return null;
66
+ }
67
+
68
+ let wasmPath = wasmArg;
69
+ if (!wasmPath) {
70
+ const found = await findFirstExisting(defaultWasmPaths);
71
+ if (found) wasmPath = found;
72
+ }
73
+ if (!wasmPath) return { ok: false, err: 'no-wasm' };
74
+
75
+ let gamePath = gameArg ?? null;
76
+ // If the user requested no game, ensure we do not load any default cartridge
77
+ // even if one exists on disk.
78
+ if (noGame) {
79
+ gamePath = null;
80
+ } else if (!gamePath) {
81
+ const found = await findFirstExisting(defaultGamePaths);
82
+ if (found) gamePath = found;
83
+ }
84
+
85
+ const out = [];
86
+ out.push(`Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''));
87
+
88
+ const wasmBinary = await fs.readFile(wasmPath);
89
+ // runtime state placeholders
90
+ let exports = null;
91
+ let heap = null;
92
+ let wrapperUsed = false;
93
+
94
+ // If a test injected a fake instantiate function, prefer that path so
95
+ // tests can run without the compiled wrapper. Provide a minimal import
96
+ // object (memory) that the fake instantiate can use.
97
+ const instantiateFn = options.instantiateFn;
98
+ const wasmAb = wasmBinary.buffer.slice(
99
+ wasmBinary.byteOffset,
100
+ wasmBinary.byteOffset + wasmBinary.byteLength,
101
+ );
102
+ if (typeof instantiateFn === 'function') {
103
+ try {
104
+ const mem = new WebAssembly.Memory({ initial: 256 });
105
+ const importObject = { env: { memory: mem }, wasi_snapshot_preview1: {} };
106
+ const res = await instantiateFn(wasmAb, importObject);
107
+ const inst = res && (res.instance ?? res);
108
+ exports = inst.exports ?? inst;
109
+ // ensure exports.memory exists so later code can read/write
110
+ if (exports && !exports.memory) exports.memory = mem;
111
+ if (exports && exports.memory) {
112
+ const buf = exports.memory.buffer;
113
+ heap = { heapU8: new Uint8Array(buf), heapF32: new Float32Array(buf), heapU32: new Uint32Array(buf) };
114
+ }
115
+ if (exports && typeof exports.c64_init === 'function') exports.c64_init();
116
+ if (exports && typeof exports.sid_setSampleRate === 'function') exports.sid_setSampleRate(44100);
117
+ if (exports && typeof exports.debugger_set_speed === 'function') exports.debugger_set_speed(100);
118
+ if (exports && typeof exports.debugger_play === 'function') exports.debugger_play();
119
+ wrapperUsed = true;
120
+ } catch (e) {
121
+ console.error('[headless] instantiateFn failed:', e && e.message ? e.message : e);
122
+ }
123
+ }
124
+
125
+ // Prefer the minimal local wrapper shipped under src/headless so the
126
+ // CLI can run without a compiled dist-ts. This keeps the runtime files
127
+ // in the source tree (src/headless) and avoids postinstall scripts.
128
+ try {
129
+ let C64WASM = null;
130
+ try {
131
+ const localMod = await import(new URL('./c64-wasm.mjs', import.meta.url).href);
132
+ C64WASM = localMod.C64WASM ?? localMod.default ?? null;
133
+ if (C64WASM) console.error('[headless] using local C64WASM wrapper (src/headless)');
134
+ } catch (e) {
135
+ // ignore — will try fallback
136
+ }
137
+
138
+ if (!C64WASM) {
139
+ // Fallback to compiled dist-ts if present
140
+ try {
141
+ const wasmModuleUrl = new URL('../../dist-ts/emulator/c64-wasm.js', import.meta.url).href;
142
+ const wasmMod = await import(wasmModuleUrl);
143
+ C64WASM = wasmMod.C64WASM ?? wasmMod.default ?? null;
144
+ if (C64WASM) console.error('[headless] using C64WASM from dist-ts');
145
+ } catch (e) {
146
+ // final fallback failure — will be handled below
147
+ }
148
+ }
149
+
150
+ if (!C64WASM) throw new Error('C64WASM wrapper not found (src/headless or dist-ts)');
151
+
152
+ const wasmAb = wasmBinary.buffer.slice(
153
+ wasmBinary.byteOffset,
154
+ wasmBinary.byteOffset + wasmBinary.byteLength,
155
+ );
156
+ const c64wasm = new C64WASM();
157
+ await c64wasm.instantiate(wasmAb);
158
+
159
+ exports = c64wasm.exports;
160
+ heap = c64wasm.heap;
161
+
162
+ // Initialise emulator state — mirrors C64Emulator.init() + start()
163
+ exports.c64_init();
164
+ exports.sid_setSampleRate(44100);
165
+ exports.debugger_set_speed(100); // 100 = full speed (1% would be near-frozen)
166
+ exports.debugger_play();
167
+
168
+ if (gamePath) {
169
+ try {
170
+ const gameData = await fs.readFile(gamePath);
171
+ const ptr = c64wasm.allocAndWrite(new Uint8Array(gameData));
172
+ c64wasm.updateHeapViews();
173
+ heap = c64wasm.heap;
174
+ exports.c64_loadCartridge(ptr, gameData.length);
175
+ exports.free(ptr);
176
+ exports.c64_reset();
177
+ exports.debugger_play();
178
+ } catch (e) {
179
+ out.push(`Failed to load game: ${String(e)}`);
180
+ }
181
+ }
182
+
183
+ wrapperUsed = true;
184
+ } catch (e) {
185
+ console.error('[headless] C64WASM wrapper failed to load:', e && e.message ? e.message : e);
186
+ }
187
+ if (!wrapperUsed) {
188
+ out.push('ERROR: dist-ts wrapper failed to load — cannot run headless');
189
+ console.error('[headless] FATAL: dist-ts wrapper unavailable. Run: npx tsc -p tsconfig.build2.json');
190
+ return { ok: false, output: out };
191
+ }
192
+
193
+ // Run state and timing
194
+ let frameCount = 0;
195
+ let ffmpegDied = false; // set to true if ffmpeg exits unexpectedly and we give up
196
+ const targetFps = (typeof fps === 'number' && !Number.isNaN(fps) && fps > 0) ? fps : 60;
197
+
198
+ // ── Audio timing ──────────────────────────────────────────────────────────
199
+ const audioSampleRate = 44100;
200
+ const samplesPerFrame = Math.floor(audioSampleRate / targetFps); // 882 @ 50fps
201
+ let audioInterval = null;
202
+
203
+ // SID audio buffer is 4096 Float32 samples. debugger_update accumulates
204
+ // samples into it across multiple calls. sid_getAudioBuffer() must be
205
+ // called once per full 4096-sample fill — NOT once per video frame —
206
+ // to read the complete buffer and reset it for the next fill cycle.
207
+ //
208
+ // At 50fps: 882 samples/frame × ~4.65 frames = 4096 samples per SID buffer.
209
+ // We track accumulated samples and call sid_getAudioBuffer() each time
210
+ // the total crosses a 4096-sample boundary, sending the full 4096-sample
211
+ // chunk to ffmpeg at that point.
212
+ const SID_BUFFER_SIZE = 4096;
213
+ let sidSampleAccum = 0; // samples accumulated since last sid_getAudioBuffer call
214
+
215
+ // Resolve output path once — URL stays verbatim, file paths resolve to repoRoot
216
+ const outPathResolved = output
217
+ ? (/^[a-zA-Z]+:\/\//.test(output) ? output : path.resolve(repoRoot, output))
218
+ : path.join(repoRoot, 'temp', `c64-record-${Date.now()}.mp4`);
219
+ const isRtmpOutput = /^[a-zA-Z]+:\/\//.test(outPathResolved);
220
+
221
+ // Setup ffmpeg runner if recording requested
222
+ let ffmpegRunner = null;
223
+ let frameSize = 384 * 272 * 4;
224
+
225
+ // Helper: start (or restart) ffmpeg. Returns true on success.
226
+ async function startFfmpeg() {
227
+ ffmpegRunner = new FFmpegRunner();
228
+ const started = await ffmpegRunner.start({ output: outPathResolved, width: 384, height: 272, fps, duration: durationSec, raw, verbose, audio, sampleRate: audioSampleRate });
229
+ return started;
230
+ }
231
+
232
+ if (record) {
233
+ try {
234
+ const started = await startFfmpeg();
235
+ if (!started) {
236
+ const msg = 'ffmpeg-record-failed:start-failed';
237
+ out.push(msg);
238
+ console.error('[headless] ' + msg);
239
+ return { ok: false, output: out };
240
+ } else {
241
+ const msg = `Recording to ${outPathResolved} (${durationSec ? durationSec + 's' : 'endless'} @ ${fps}fps${audio ? ' +audio' : ''})`;
242
+ out.push(msg);
243
+ console.error('[headless] ' + msg);
244
+ }
245
+ } catch (e) {
246
+ out.push(`ffmpeg-record-failed: ${String(e)}`);
247
+ record = false;
248
+ }
249
+ }
250
+
251
+ // runStartTime is set AFTER ffmpeg starts so --duration counts from when
252
+ // recording actually begins (after any RTMP probe/stabilisation delay).
253
+ const runStartTime = Date.now();
254
+ // When recording without an explicit --duration, run forever (endTime = Infinity).
255
+ const endTime = record
256
+ ? (durationSec ? runStartTime + durationSec * 1000 : Infinity)
257
+ : null;
258
+ let lastTick = Date.now();
259
+ let windowStart = Date.now();
260
+ let windowCount = 0;
261
+
262
+ while (record ? Date.now() < endTime : frameCount < frames) {
263
+ // iteration start timestamp (declare in outer scope so it's available
264
+ // to the throttle logic even if the try block throws)
265
+ let iterStart = Date.now();
266
+ try {
267
+ if (verbose && frameCount % 50 === 0) console.error(`[headless] loop frameCount=${frameCount}`);
268
+ // Record iteration start time and compute deltaMs. Always update
269
+ // lastTick so the throttle calculation below works correctly for
270
+ // both fixed-dt and wall-clock modes.
271
+ iterStart = Date.now();
272
+ let deltaMs;
273
+ if (useFixedDt) {
274
+ deltaMs = Math.round(1000 / targetFps);
275
+ } else {
276
+ // wall-clock delta in milliseconds since last tick
277
+ deltaMs = iterStart - lastTick;
278
+ if (deltaMs <= 0) deltaMs = Math.round(1000 / targetFps);
279
+ // clamp to a single frame interval to avoid huge jumps
280
+ if (deltaMs > 1000) deltaMs = Math.round(1000 / targetFps);
281
+ }
282
+ lastTick = iterStart;
283
+ // Drive the emulator for one frame interval. One call to debugger_update
284
+ // with the target frame duration (20ms at 50fps) advances exactly one
285
+ // PAL frame worth of C64 cycles. Do NOT call it multiple times per loop
286
+ // iteration — that runs the emulator faster than real-time.
287
+ const stepMs = Math.round(1000 / targetFps); // 20ms at 50fps
288
+ try {
289
+ // Advance emulator one frame. Previously we logged dt/ret here for
290
+ // debugging; remove the per-frame diagnostic to avoid noisy output.
291
+ exports.debugger_update(stepMs);
292
+ } catch (e) {
293
+ if (verbose) console.error('[headless] debugger_update threw', e);
294
+ }
295
+
296
+ // Capture video frame and audio chunk, then write both atomically.
297
+ // await writeFrame() provides genuine backpressure: the loop waits for
298
+ // ffmpeg to consume each frame before advancing, so it can never run
299
+ // faster than ffmpeg can encode — no burst/spin behaviour possible.
300
+ if (record && ffmpegRunner) {
301
+ // Check if ffmpeg died before attempting to write
302
+ if (!ffmpegRunner.isAlive()) {
303
+ const code = ffmpegRunner._exitCode;
304
+ const errMsg = `ffmpeg process exited unexpectedly (code ${code}) after ${frameCount} frames`;
305
+ out.push(errMsg);
306
+ console.error(`[headless] ${errMsg}`);
307
+
308
+ // For URL/RTMP outputs, retry with backoff — transient connection failures are normal
309
+ if (isRtmpOutput) {
310
+ const retryDelaySec = 10;
311
+ console.error(`[headless] RTMP output — retrying ffmpeg in ${retryDelaySec}s...`);
312
+ await new Promise((r) => setTimeout(r, retryDelaySec * 1000));
313
+ try {
314
+ const restarted = await startFfmpeg();
315
+ if (restarted) {
316
+ console.error('[headless] ffmpeg restarted successfully');
317
+ } else {
318
+ console.error('[headless] ffmpeg restart failed — giving up');
319
+ ffmpegDied = true;
320
+ record = false;
321
+ break;
322
+ }
323
+ } catch (restartErr) {
324
+ console.error('[headless] ffmpeg restart threw:', restartErr && restartErr.message);
325
+ ffmpegDied = true;
326
+ record = false;
327
+ break;
328
+ }
329
+ } else {
330
+ ffmpegDied = true;
331
+ record = false;
332
+ break;
333
+ }
334
+ }
335
+ try {
336
+ const ptr = exports.c64_getPixelBuffer();
337
+ const videoFrame = heap.heapU8.subarray(ptr, ptr + frameSize);
338
+ let audioChunk = null;
339
+ if (audio && exports.sid_getAudioBuffer) {
340
+ // Accumulate samples. sid_getAudioBuffer() fills 4096 samples per
341
+ // cycle — call it exactly when the accumulator crosses that boundary,
342
+ // then send the full 4096-sample buffer. This matches the original
343
+ // ScriptProcessorNode pattern in c64.js (audioBufferLength = 4096).
344
+ sidSampleAccum += samplesPerFrame;
345
+ if (sidSampleAccum >= SID_BUFFER_SIZE) {
346
+ sidSampleAccum -= SID_BUFFER_SIZE;
347
+ try {
348
+ const sidPtr = exports.sid_getAudioBuffer();
349
+ const sidBase = sidPtr >> 2;
350
+ // Copy the full 4096-sample buffer so ffmpeg gets a consistent chunk
351
+ audioChunk = heap.heapF32.slice(sidBase, sidBase + SID_BUFFER_SIZE);
352
+ } catch (_) {}
353
+ }
354
+ }
355
+ await ffmpegRunner.writeFrame(videoFrame, audioChunk);
356
+ } catch (e) {
357
+ const errMsg = `ffmpeg write error after ${frameCount} frames: ${e && e.message ? e.message : String(e)}`;
358
+ out.push(errMsg);
359
+ console.error(`[headless] ${errMsg}`);
360
+ // For URL outputs, don't give up immediately — ffmpeg may have just died,
361
+ // the isAlive() check at the top of next iteration will handle the retry.
362
+ if (!isRtmpOutput) {
363
+ ffmpegDied = true;
364
+ record = false;
365
+ break;
366
+ }
367
+ }
368
+ }
369
+ } catch (_) {}
370
+ frameCount++;
371
+ // diagnostics
372
+ windowCount++;
373
+ if (windowCount >= 50) {
374
+ const now = Date.now();
375
+ const secs = (now - windowStart) / 1000;
376
+ const obsFps = windowCount / (secs || 1);
377
+ //console.error(`[headless] observed fps=${obsFps.toFixed(2)} over ${secs.toFixed(2)}s (frames ${frameCount - windowCount}..${frameCount})`);
378
+ windowStart = now;
379
+ windowCount = 0;
380
+ }
381
+ if (verify && frameCount % 60 === 0) {
382
+ const cycleCount = exports.c64_getCycleCount ? exports.c64_getCycleCount() : null;
383
+ out.push(JSON.stringify({ pid: process.pid, frame: frameCount, cycles: cycleCount }));
384
+ // Also emit a stderr heartbeat so interactive runs show progress.
385
+ try {
386
+ const pc = exports.c64_getPC ? exports.c64_getPC() : null;
387
+ console.error(`[headless] verify: frame=${frameCount} pc=${pc} cycles=${cycleCount}`);
388
+ } catch (_) {}
389
+ } else if (frameCount % 120 === 0) {
390
+ //out.push(`HEADLESS: frame=${frameCount}`);
391
+ }
392
+ // Throttle to target FPS: sleep for the remainder of the frame interval
393
+ const frameMs = Math.round(1000 / targetFps);
394
+ const iterElapsed = Date.now() - iterStart;
395
+ const sleepMs = Math.max(0, frameMs - iterElapsed);
396
+ await new Promise((r) => setTimeout(r, sleepMs));
397
+ }
398
+
399
+ const elapsed = (Date.now() - runStartTime) / 1000;
400
+ out.push(`Run complete. frames=${frameCount} elapsed=${elapsed.toFixed(2)}s`);
401
+ if (record && ffmpegRunner) {
402
+ // Clear audio interval if it was used (currently null/no-op)
403
+ if (audioInterval) {
404
+ clearInterval(audioInterval);
405
+ audioInterval = null;
406
+ }
407
+ try {
408
+ const saved = await ffmpegRunner.stop();
409
+ // Verify the file exists and is non-empty
410
+ try {
411
+ // If the saved path is a URL (rtmp://, rtmps://, srt://, etc.)
412
+ // there is no filesystem entry to stat — treat it as a published
413
+ // network output and report success.
414
+ if (typeof saved === 'string' && /^[a-zA-Z]+:\/\//.test(saved)) {
415
+ out.push(`Published: ${saved}`);
416
+ } else {
417
+ const stat = await fs.stat(saved);
418
+ if (stat.size > 0) out.push(`Saved: ${saved}`);
419
+ else out.push(`Saved-empty: ${saved}`);
420
+ }
421
+ } catch (e) {
422
+ out.push(`Saved-missing: ${saved} (${String(e)})`);
423
+ }
424
+ } catch (e) {
425
+ out.push(`ffmpeg-stop-failed: ${String(e)}`);
426
+ }
427
+ }
428
+ return { ok: !ffmpegDied, output: out };
429
+ }
430
+
431
+ export default runHeadless;
432
+
433
+ // If this file is executed directly, run the CLI.
434
+ try {
435
+ const thisFile = fileURLToPath(import.meta.url);
436
+ // Resolve argv[1] to an absolute path so running with a relative path
437
+ // (e.g. `node src/headless/headless-cli.mjs`) still matches.
438
+ const argv1Resolved = process.argv && process.argv[1] ? path.resolve(process.argv[1]) : null;
439
+ if (argv1Resolved && argv1Resolved === thisFile) {
440
+ (async () => {
441
+ const res = await runHeadless();
442
+ if (res) {
443
+ if (Array.isArray(res.output)) {
444
+ for (const line of res.output) console.log(line);
445
+ } else if (res.output) {
446
+ console.log(res.output);
447
+ }
448
+ if (!res.ok) process.exit(1);
449
+ }
450
+ process.exit(0);
451
+ })().catch((e) => { console.error(e); process.exit(1); });
452
+ }
453
+ } catch (e) {
454
+ // ignore errors in CLI wrapper detection
455
+ }
456
+
@@ -0,0 +1,18 @@
1
+ // Type declarations for the ESM CLI entrypoint used in tests.
2
+ // This declares the local relative module './headless-cli.mjs' so TypeScript
3
+ // can type-check imports from tests without requiring a typed build artifact.
4
+ declare module './headless-cli.mjs' {
5
+ export interface RunHeadlessOptions {
6
+ argv?: string[];
7
+ instantiateFn?: (
8
+ wasmBinary: ArrayBuffer | Uint8Array,
9
+ importObject: unknown,
10
+ ) => Promise<{ instance: { exports: unknown } }>;
11
+ repoRoot?: string;
12
+ }
13
+ export function runHeadless(
14
+ options?: RunHeadlessOptions,
15
+ ): Promise<{ ok: boolean; output: unknown[] | string }>;
16
+ }
17
+
18
+ export {};
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Remote input bridge (WebSocket → emulator)
3
+ * Allows remote players to control the emulator
4
+ */
5
+
6
+ import type { InputEvent } from '../types';
7
+
8
+ export class InputBridge {
9
+ onInput?: (event: InputEvent) => void;
10
+
11
+ /**
12
+ * Called when a remote input arrives (e.g., from WebSocket)
13
+ */
14
+ receiveRemoteInput(jsonString: string): void {
15
+ try {
16
+ const event: InputEvent = JSON.parse(jsonString);
17
+ if (this.onInput) {
18
+ this.onInput(event);
19
+ }
20
+ } catch (err) {
21
+ // Keep minimal dependency on console in headless mode
22
+
23
+ console.error('Failed to parse input:', err);
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Example: encode a keypress for transmission
29
+ */
30
+ static encodeKeypress(key: string): string {
31
+ return JSON.stringify({ type: 'key', key });
32
+ }
33
+
34
+ static encodeJoystick(port: 1 | 2, direction?: string, fire?: boolean): string {
35
+ return JSON.stringify({
36
+ type: 'joystick',
37
+ joystickPort: port,
38
+ direction,
39
+ fire,
40
+ });
41
+ }
42
+ }