c64-ready 0.6.2 → 0.10.0

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,251 @@
1
+ /**
2
+ * webrtc-encoder.mjs
3
+ *
4
+ * Bridges the WASM pixel buffer (RGBA) → WebRTC video track
5
+ * and WASM F32 PCM audio → WebRTC audio track.
6
+ *
7
+ * Uses the @roamhq/wrtc nonstandard API:
8
+ * RTCVideoSource — push raw I420 frames into the WebRTC pipeline
9
+ * RTCAudioSource — push raw Int16 PCM into the WebRTC pipeline
10
+ * rgbaToI420 — fast RGBA → I420 colour-space conversion helper
11
+ *
12
+ * Both tracks are shared across all peer connections: every connected
13
+ * browser sees the same video/audio feed from the single emulator instance.
14
+ */
15
+
16
+ import wrtc from '@roamhq/wrtc';
17
+
18
+ const { RTCVideoSource, RTCAudioSource, rgbaToI420 } = wrtc.nonstandard;
19
+
20
+ const nowMonoMs = () => {
21
+ if (typeof globalThis.performance !== 'undefined' && typeof globalThis.performance.now === 'function') {
22
+ return globalThis.performance.now();
23
+ }
24
+ return Date.now();
25
+ };
26
+
27
+ export class WebRTCEncoder {
28
+ /** @type {import('@roamhq/wrtc').nonstandard.RTCVideoSource|null} */
29
+ videoSource = null;
30
+ /** @type {import('@roamhq/wrtc').nonstandard.RTCAudioSource|null} */
31
+ audioSource = null;
32
+ /** @type {MediaStreamTrack|null} */
33
+ videoTrack = null;
34
+ /** @type {MediaStreamTrack|null} */
35
+ audioTrack = null;
36
+
37
+ _width = 384;
38
+ _height = 272;
39
+ _sampleRate = 44100;
40
+
41
+ // Monotonic origin for video timestamps.
42
+ // Video timestamps are driven by (nowMonoMs() - _videoOriginMs) * 1000 µs so
43
+ // that after any gap (e.g. the ~1300ms c64_loadCartridge() blockage) the
44
+ // next frame's timestamp automatically jumps forward by the real elapsed
45
+ // time. This keeps the video RTP clock aligned with the audio RTP clock,
46
+ // which advances at the real-time rate even when no audio is pushed.
47
+ //
48
+ // Previous approach (frame-counter × frame-duration) was intended to hide
49
+ // the gap from the receiver, but it caused the video RTP timestamps to fall
50
+ // ~1300ms *behind* the audio clock after every cart load. The browser's
51
+ // AV sync logic then delayed video rendering until the audio clock "caught
52
+ // up", creating the observed ~1–30s of perceived input lag.
53
+ _videoOriginMs = 0; // set in init() to nowMonoMs()
54
+ _videoFrameDurationUs = 0; // microseconds per frame, set in setFps() (kept for compatibility)
55
+
56
+ // RTCAudioSource.onData() requires exactly (sampleRate / 100) samples per call —
57
+ // that is one 10 ms WebRTC audio processing frame. At 44100 Hz that is 441 samples.
58
+ // The SID buffer is 4096 samples, so we queue incoming audio and drain it in
59
+ // 441-sample chunks.
60
+ _audioChunkSize = 441; // recalculated in init()
61
+ // Pre-allocated audio ring buffer — large enough to hold several SID pulls
62
+ // without allocation. Using a ring avoids per-frame Float32Array allocs
63
+ // (which caused GC pauses and audio stuttering at 50fps).
64
+ _audioRing = null; // Float32Array, allocated in init()
65
+ _audioRingSize = 0;
66
+ _audioRingWrite = 0;
67
+ _audioRingRead = 0;
68
+ _audioRingCount = 0;
69
+ _audioInt16 = null; // Int16Array(chunkSize), allocated in init()
70
+ // Pre-allocated staging buffers — reused every frame to avoid GC pressure.
71
+ // rgbaToI420() validates data.byteLength === width*height*4, so we cannot
72
+ // pass a subarray of the WASM heap (whose byteLength = full heap size).
73
+ // Copying into _rgbaBuf each frame is one memcpy (~417 KB) — negligible.
74
+ _rgbaBuf = null; // Uint8ClampedArray(width*height*4)
75
+ _i420Buf = null; // Uint8ClampedArray(width*height * 3/2)
76
+
77
+ /**
78
+ * @param {{ width?: number, height?: number, sampleRate?: number }} opts
79
+ */
80
+ init({ width = 384, height = 272, sampleRate = 44100 } = {}) {
81
+ this._width = width;
82
+ this._height = height;
83
+ this._sampleRate = sampleRate;
84
+ this._audioChunkSize = Math.floor(sampleRate / 100); // 441 @ 44100, 480 @ 48000
85
+ // Audio ring: large enough for 8× the SID pull size (8×4096 = 32768 samples)
86
+ // so even bursts after a cart load never overflow.
87
+ this._audioRingSize = 4096 * 8;
88
+ this._audioRing = new Float32Array(this._audioRingSize);
89
+ this._audioRingWrite = 0;
90
+ this._audioRingRead = 0;
91
+ this._audioRingCount = 0;
92
+ this._audioInt16 = new Int16Array(this._audioChunkSize);
93
+ this._videoOriginMs = nowMonoMs();
94
+
95
+ // Staging buffers with exact byte sizes that rgbaToI420 expects
96
+ this._rgbaBuf = new Uint8ClampedArray(width * height * 4);
97
+ const i420Size = width * height + (width >> 1) * (height >> 1) * 2;
98
+ this._i420Buf = new Uint8ClampedArray(i420Size);
99
+
100
+ // isScreencast: true — tells libwebrtc this is screen/game content, not a camera.
101
+ // Effect: disables temporal noise filtering, prefers crisp frames over smooth
102
+ // motion estimation, and reduces encoder buffering latency.
103
+ this.videoSource = new RTCVideoSource({ isScreencast: true });
104
+ this.audioSource = new RTCAudioSource();
105
+
106
+ this.videoTrack = this.videoSource.createTrack();
107
+ this.audioTrack = this.audioSource.createTrack();
108
+ }
109
+
110
+ /**
111
+ * No-op retained for call-site compatibility.
112
+ */
113
+ resetVideoTimestamp() {
114
+ // intentional no-op
115
+ }
116
+
117
+ /**
118
+ * Push enough silence audio frames to cover a wall-clock gap.
119
+ *
120
+ * Root cause of post-load input lag
121
+ * ──────────────────────────────────
122
+ * RTCAudioSource is a *push* source: its RTP clock advances only when
123
+ * onData() is called. During the ~1300ms blockage of c64_loadCartridge()
124
+ * (and the shorter ~110ms blockage of c64_reset()/detach), the frame loop
125
+ * is frozen so no audio is pushed. The video track's RTP clock, however,
126
+ * is driven internally by @roamhq/wrtc using the wall clock and keeps
127
+ * ticking throughout the gap.
128
+ *
129
+ * Result: video RTP is 1300ms ahead of audio RTP when frames resume.
130
+ * The browser's AV sync logic holds video playback until the audio clock
131
+ * catches up — which is experienced as ~1–30s of input lag (the perceived
132
+ * lag is the browser waiting for audio to "fill" the 1300ms debt at the
133
+ * real-time audio rate of 441 samples / 10ms = 130 push calls to drain).
134
+ *
135
+ * Fix: immediately after any blocking WASM call, push silence audio frames
136
+ * totalling the measured wall-clock gap. This advances the audio RTP
137
+ * clock by the same amount the video RTP clock advanced during the gap,
138
+ * so both clocks re-align and the browser can render video without delay.
139
+ *
140
+ * @param {number} gapMs Wall-clock duration of the gap in milliseconds.
141
+ */
142
+ pushSilenceForGap(gapMs) {
143
+ if (!this.audioSource || gapMs <= 0) return;
144
+ const chunkSize = this._audioChunkSize; // 441 @ 44100 Hz
145
+ const sampleRate = this._sampleRate;
146
+ // Number of silence samples needed to cover the gap
147
+ const totalSamples = Math.round((gapMs / 1000) * sampleRate);
148
+ // Reuse _audioInt16 (already allocated, zero-filled on first use).
149
+ // It may still contain data from the last pushAudioFrame call, so zero it.
150
+ this._audioInt16.fill(0);
151
+ const int16 = this._audioInt16;
152
+ let pushed = 0;
153
+ while (pushed + chunkSize <= totalSamples) {
154
+ this.audioSource.onData({
155
+ samples: int16,
156
+ sampleRate: sampleRate,
157
+ bitsPerSample: 16,
158
+ channelCount: 1,
159
+ numberOfFrames: chunkSize,
160
+ });
161
+ pushed += chunkSize;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Set the frame rate used to compute video timestamps.
167
+ * Must be called after init() if the fps differs from the default 50.
168
+ * @param {number} fps
169
+ */
170
+ setFps(fps) {
171
+ this._videoFrameDurationUs = Math.round(1_000_000 / fps);
172
+ }
173
+
174
+ /**
175
+ * Push one RGBA video frame into the WebRTC pipeline.
176
+ *
177
+ * @param {Uint8Array} rgbaData - raw RGBA pixels, width*height*4 bytes
178
+ * (zero-copy subarray from WASM heap is fine — rgbaToI420 reads it synchronously)
179
+ */
180
+ pushVideoFrame(rgbaData) {
181
+ const width = this._width;
182
+ const height = this._height;
183
+
184
+ // Copy pixel data into the pre-sized staging buffer.
185
+ // This is necessary because rgbaToI420 checks data.byteLength strictly.
186
+ this._rgbaBuf.set(rgbaData.subarray(0, width * height * 4));
187
+
188
+ rgbaToI420(
189
+ { width, height, data: this._rgbaBuf },
190
+ { width, height, data: this._i420Buf },
191
+ );
192
+
193
+ // Drive timestamp from wall clock (microseconds elapsed since init()).
194
+ // After any gap (e.g. the ~1300ms c64_loadCartridge blockage) the timestamp
195
+ // automatically jumps forward by the real elapsed time, keeping the video
196
+ // RTP clock aligned with the audio RTP clock which advances at real-time
197
+ // rate regardless of whether audio frames are pushed.
198
+ const timestamp = (nowMonoMs() - this._videoOriginMs) * 1000;
199
+
200
+ this.videoSource.onFrame({ width, height, data: this._i420Buf, timestamp });
201
+ }
202
+
203
+ /**
204
+ * Push one block of Float32 PCM audio into the WebRTC pipeline.
205
+ *
206
+ * RTCAudioSource.onData() requires exactly (sampleRate / 100) Int16 samples
207
+ * per call (one 10 ms WebRTC audio frame — 441 @ 44100 Hz, 480 @ 48000 Hz).
208
+ * Incoming SID buffers are 882 samples/frame at 50fps, so we queue into a
209
+ * pre-allocated ring and drain in exact 441-sample chunks.
210
+ * Zero heap allocations per call — no GC pressure, no audio stuttering.
211
+ *
212
+ * @param {Float32Array} f32samples - SID output, sampleRate Hz mono
213
+ */
214
+ pushAudioFrame(f32samples) {
215
+ const chunkSize = this._audioChunkSize;
216
+ const ringSize = this._audioRingSize;
217
+ const ring = this._audioRing;
218
+
219
+ // Write incoming samples into the ring (wrap-around, drop on overflow)
220
+ for (let i = 0; i < f32samples.length; i++) {
221
+ if (this._audioRingCount < ringSize) {
222
+ ring[this._audioRingWrite] = f32samples[i];
223
+ this._audioRingWrite = (this._audioRingWrite + 1) % ringSize;
224
+ this._audioRingCount++;
225
+ }
226
+ // overflow: silently drop — should never happen with ring sized 8×SID_BUF
227
+ }
228
+
229
+ // Drain completed 10 ms chunks from the ring
230
+ const int16 = this._audioInt16;
231
+ while (this._audioRingCount >= chunkSize) {
232
+ for (let i = 0; i < chunkSize; i++) {
233
+ const s = ring[this._audioRingRead];
234
+ this._audioRingRead = (this._audioRingRead + 1) % ringSize;
235
+ const clamped = s < -1 ? -1 : s > 1 ? 1 : s;
236
+ int16[i] = clamped * 32767;
237
+ }
238
+ this._audioRingCount -= chunkSize;
239
+ this.audioSource.onData({
240
+ samples: int16,
241
+ sampleRate: this._sampleRate,
242
+ bitsPerSample: 16,
243
+ channelCount: 1,
244
+ numberOfFrames: chunkSize,
245
+ });
246
+ }
247
+ }
248
+
249
+ get width() { return this._width; }
250
+ get height() { return this._height; }
251
+ }