Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | 50x 50x 4x 4x 2x 6x 6x 4x 2x | /**
* WebCodecs + Mediabunny backend of {@link GameplayRecorder}.
*
* `MediaRecorder` stamps every video frame and audio buffer with the wall-clock time the capture pipeline happened to
* receive it, and the audio path (Web Audio → `MediaStreamAudioDestinationNode` → track) is a few tens of milliseconds
* slower than the canvas path — so its recordings show the picture ~40-50 ms ahead of the sound, by an amount that
* varies per machine and output device. This backend stamps both tracks itself, on the clock the gameplay runs on:
*
* - Video frames carry the `AudioContext.currentTime` the scene was drawn at — the same value the gameplay reads to
* place its notes.
* - Audio is pulled out of the graph by an `AudioWorklet` that reports the context frame index of every block, so each
* sample sits exactly at the context time it was rendered for.
*
* Both tracks share one origin (the context time at `start`), so the encoded file is in sync by construction, and a
* dropped frame (overloaded encoder, busy main thread) only lowers the frame rate — it can never shift the picture
* against the sound. Encoded packets are muxed into MP4 or WebM by Mediabunny, which also writes the seek index.
*/
// Types only: the runtime module is imported on demand in `prepare`, so it stays out of the main bundle.
import type * as Mediabunny from 'mediabunny';
import type {
AudioSampleSource,
BufferTarget,
CanvasSource,
Mp4OutputFormat,
Output,
WebMOutputFormat,
} from 'mediabunny';
import {
DEFAULT_RECORDING_FORMAT,
recordingAudioCodecs,
recordingVideoCodecs,
type RecordingFormat,
} from './recording-format.ts';
/** Frames the worklet buffers before posting a chunk to the main thread (~85 ms at 48 kHz). */
const AUDIO_CHUNK_FRAMES = 4096;
/**
* The capture worklet. It copies every render block of its (stereo) input into a chunk buffer and posts the chunk with
* the context frame index of its first sample; a `flush` message posts the partial chunk and acknowledges.
*/
const CAPTURE_WORKLET_SOURCE = `
class BeMusicRecorderTap extends AudioWorkletProcessor {
constructor() {
super();
this.size = ${AUDIO_CHUNK_FRAMES};
this.reset();
this.port.onmessage = (event) => {
if (event.data === 'flush') {
this.post();
this.port.postMessage({ flushed: true });
}
};
}
reset() {
this.left = new Float32Array(this.size);
this.right = new Float32Array(this.size);
this.filled = 0;
this.startFrame = -1;
}
post() {
if (this.filled === 0) return;
const left = this.left.slice(0, this.filled);
const right = this.right.slice(0, this.filled);
this.port.postMessage({ startFrame: this.startFrame, left, right }, [left.buffer, right.buffer]);
this.reset();
}
process(inputs) {
const input = inputs[0];
const block = input && input[0] ? input[0].length : 128;
let offset = 0;
while (offset < block) {
if (this.filled === 0) this.startFrame = currentFrame + offset;
const count = Math.min(block - offset, this.size - this.filled);
if (input && input[0]) {
this.left.set(input[0].subarray(offset, offset + count), this.filled);
this.right.set((input[1] || input[0]).subarray(offset, offset + count), this.filled);
}
this.filled += count;
offset += count;
if (this.filled === this.size) this.post();
}
return true;
}
}
registerProcessor('be-music-recorder-tap', BeMusicRecorderTap);
`;
/**
* Where an audio chunk lands on the recording timeline. `startFrame` is the context frame of the chunk's first sample
* and `originFrame` the context frame recording started at; the part before the origin is cut off. Returns the number
* of leading frames to skip and the timestamp (seconds) of the first kept frame, or `undefined` when the whole chunk
* predates the recording.
*/
export function alignAudioChunk(
startFrame: number,
frameCount: number,
originFrame: number,
sampleRate: number,
): { skip: number; timestamp: number } | undefined {
const skip = Math.max(0, originFrame - startFrame);
if (skip >= frameCount) return undefined;
return { skip, timestamp: (startFrame + skip - originFrame) / sampleRate };
}
/**
* The timestamp (seconds) for a video frame drawn at context time `clockSeconds`, relative to the recording origin, or
* `undefined` when it must be skipped: before the origin, or not after the previous frame (the context is suspended
* while the game is paused, so its clock stands still and repeated frames would collide).
*/
export function resolveFrameTimestamp(
clockSeconds: number,
originSeconds: number,
lastTimestamp: number | undefined,
): number | undefined {
const timestamp = clockSeconds - originSeconds;
if (!Number.isFinite(timestamp) || timestamp < 0) return undefined;
if (lastTimestamp !== undefined && timestamp <= lastTimestamp) return undefined;
return timestamp;
}
function toError(error: unknown): Error {
return error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'WebCodecs capture failed');
}
/** Whether this browser exposes everything the WebCodecs backend needs. Codec support is probed separately. */
export function supportsWebCodecsRecording(audioContext: BaseAudioContext): boolean {
return (
typeof VideoEncoder !== 'undefined' &&
typeof AudioEncoder !== 'undefined' &&
typeof AudioWorkletNode !== 'undefined' &&
audioContext.audioWorklet !== undefined
);
}
export interface WebCodecsCaptureOptions {
/** Canvas the frames are read from (the scene canvas, or the scaled copy). */
canvas: HTMLCanvasElement;
audioContext: AudioContext;
audioOutput: AudioNode;
fps: number;
videoBitsPerSecond: number;
audioBitsPerSecond: number;
/** Container and preferred video codec; MP4 with H.264 by default. */
format?: RecordingFormat;
}
/**
* One WebCodecs recording session. {@link prepare} probes the codecs and loads the worklet (it rejects when no
* codec pair for the format's container is encodable, so the caller can fall back to `MediaRecorder`); {@link captureFrame}
* is called right after each scene render; {@link finish} flushes everything and returns the file.
*/
export class WebCodecsCapture {
private readonly options: WebCodecsCaptureOptions;
private readonly originSeconds: number;
private readonly originFrame: number;
private output: Output<WebMOutputFormat | Mp4OutputFormat, BufferTarget> | undefined;
private videoSource: CanvasSource | undefined;
private audioSource: AudioSampleSource | undefined;
/** Mediabunny, loaded by {@link prepare}. */
private mediabunny: typeof Mediabunny | undefined;
private tap: AudioWorkletNode | undefined;
private sink: GainNode | undefined;
/** Encode of the previous frame, still in flight; frames arriving meanwhile are dropped instead of queued. */
private pendingFrame: Promise<void> | undefined;
/** Audio samples are added strictly in order, each after the previous one was accepted. */
private audioChain: Promise<void> = Promise.resolve();
private lastFrameTimestamp: number | undefined;
private failure: Error | undefined;
private closed = false;
public constructor(options: WebCodecsCaptureOptions) {
this.options = options;
// Recording starts "now" on the gameplay clock. Both tracks are measured from here.
this.originSeconds = options.audioContext.currentTime;
this.originFrame = Math.round(this.originSeconds * options.audioContext.sampleRate);
}
public async prepare(): Promise<void> {
const { canvas, audioContext, fps } = this.options;
const mediabunny = await import('mediabunny');
const {
AudioSampleSource,
BufferTarget,
CanvasSource,
Mp4OutputFormat,
Output,
Quality,
WebMOutputFormat,
getFirstEncodableAudioCodec,
getFirstEncodableVideoCodec,
} = mediabunny;
const videoQuality = new Quality({ bitrate: Math.round(this.options.videoBitsPerSecond) });
const audioQuality = new Quality({ bitrate: Math.round(this.options.audioBitsPerSecond) });
const format = this.options.format ?? DEFAULT_RECORDING_FORMAT;
const [videoCodec, audioCodec] = await Promise.all([
getFirstEncodableVideoCodec(recordingVideoCodecs(format), {
width: canvas.width,
height: canvas.height,
quality: videoQuality,
}),
getFirstEncodableAudioCodec(recordingAudioCodecs(format.container), {
numberOfChannels: 2,
sampleRate: audioContext.sampleRate,
quality: audioQuality,
}),
]);
if (!videoCodec || !audioCodec) {
throw new Error(`WebCodecsCapture: no codec pair for ${format.container} is encodable`);
}
const moduleURL = URL.createObjectURL(new Blob([CAPTURE_WORKLET_SOURCE], { type: 'text/javascript' }));
try {
await audioContext.audioWorklet.addModule(moduleURL);
} finally {
URL.revokeObjectURL(moduleURL);
}
if (this.closed) return;
// MP4 keeps its index at the front (`fastStart: 'in-memory'`), so the file plays and seeks before it is fully read.
const output = new Output({
format: format.container === 'mp4' ? new Mp4OutputFormat({ fastStart: 'in-memory' }) : new WebMOutputFormat(),
target: new BufferTarget(),
});
const videoSource = new CanvasSource(canvas, {
codec: videoCodec,
quality: videoQuality,
// Realtime mode lets the encoder shed load instead of falling ever further behind on a slow machine.
latencyMode: 'realtime',
sizeChangeBehavior: 'contain',
});
const audioSource = new AudioSampleSource({ codec: audioCodec, quality: audioQuality });
output.addVideoTrack(videoSource, { frameRate: fps });
output.addAudioTrack(audioSource);
await output.start();
if (this.closed) {
await output.cancel();
return;
}
this.mediabunny = mediabunny;
this.output = output;
this.videoSource = videoSource;
this.audioSource = audioSource;
this.attachTap();
}
/** Encodes the canvas as it is now, stamped with the gameplay clock. Call right after the scene rendered. */
public captureFrame(): void {
const source = this.videoSource;
if (!source || this.closed || this.pendingFrame || this.failure !== undefined) return;
const timestamp = resolveFrameTimestamp(
this.options.audioContext.currentTime,
this.originSeconds,
this.lastFrameTimestamp,
);
if (timestamp === undefined) return;
this.lastFrameTimestamp = timestamp;
const pending = source
.add(timestamp, 1 / this.options.fps)
.catch((error: unknown) => {
this.failure ??= toError(error);
})
.finally(() => {
if (this.pendingFrame === pending) this.pendingFrame = undefined;
});
this.pendingFrame = pending;
}
/** Drains the worklet and the encoders and returns the finished file, or `undefined` if nothing was set up. */
public async finish(): Promise<Blob | undefined> {
if (this.closed) return undefined;
this.closed = true;
const output = this.output;
if (!output) return undefined;
await this.flushTap();
this.detachTap();
await this.pendingFrame;
await this.audioChain;
if (this.failure !== undefined) {
await output.cancel();
throw this.failure;
}
await output.finalize();
const buffer = output.target.buffer;
return buffer ? new Blob([buffer], { type: output.format.mimeType }) : undefined;
}
/** Abandons the session without producing a file. */
public dispose(): void {
if (this.closed) return;
this.closed = true;
this.detachTap();
void this.output?.cancel().catch(() => {});
}
private attachTap(): void {
const { audioContext, audioOutput } = this.options;
const tap = new AudioWorkletNode(audioContext, 'be-music-recorder-tap', {
numberOfInputs: 1,
numberOfOutputs: 1,
channelCount: 2,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
tap.port.onmessage = (event: MessageEvent<{ startFrame: number; left: Float32Array; right: Float32Array }>) => {
if ('startFrame' in event.data) this.pushAudio(event.data.startFrame, event.data.left, event.data.right);
};
// A muted path to the destination keeps the worklet pulled by the render graph in every browser.
const sink = audioContext.createGain();
sink.gain.value = 0;
audioOutput.connect(tap);
tap.connect(sink);
sink.connect(audioContext.destination);
this.tap = tap;
this.sink = sink;
}
private pushAudio(startFrame: number, left: Float32Array, right: Float32Array): void {
const source = this.audioSource;
const mediabunny = this.mediabunny;
if (!source || !mediabunny || this.failure !== undefined) return;
const { sampleRate } = this.options.audioContext;
const placement = alignAudioChunk(startFrame, left.length, this.originFrame, sampleRate);
if (!placement) return;
const frames = left.length - placement.skip;
const planar = new Float32Array(frames * 2);
planar.set(left.subarray(placement.skip), 0);
planar.set(right.subarray(placement.skip), frames);
const sample = new mediabunny.AudioSample({
data: planar,
format: 'f32-planar',
numberOfChannels: 2,
sampleRate,
timestamp: placement.timestamp,
});
this.audioChain = this.audioChain
.then(() => source.add(sample))
.catch((error: unknown) => {
this.failure ??= toError(error);
})
.finally(() => sample.close());
}
private flushTap(): Promise<void> {
const tap = this.tap;
if (!tap) return Promise.resolve();
return new Promise<void>((resolve) => {
// The worklet only answers while the context is running; don't hang on a suspended one.
const timer = setTimeout(resolve, 500);
tap.port.addEventListener('message', (event: MessageEvent<{ flushed?: boolean }>) => {
if (event.data.flushed) {
clearTimeout(timer);
resolve();
}
});
tap.port.postMessage('flush');
});
}
private detachTap(): void {
const { tap, sink } = this;
if (!tap) return;
try {
this.options.audioOutput.disconnect(tap);
} catch {
// Already disconnected.
}
tap.port.onmessage = null;
tap.disconnect();
sink?.disconnect();
this.tap = undefined;
this.sink = undefined;
}
}
|