diff options
Diffstat (limited to 'web/host.js')
| -rw-r--r-- | web/host.js | 22 |
1 files changed, 19 insertions, 3 deletions
diff --git a/web/host.js b/web/host.js index efc335d..32bdbfb 100644 --- a/web/host.js +++ b/web/host.js @@ -314,13 +314,16 @@ const gpu = { // Reads a buffer back; it reaches the sketch before a later frame. arrived: [], download(id, offset, size, key) { + gpu.read(id, offset, size, bytes => gpu.arrived.push({key, bytes})); + }, + read(id, offset, size, then) { const staging = gpu.spare.find(b => b.size >= size) ?? gpu.device.createBuffer({size: Math.max(size, 256), usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST}); gpu.spare = gpu.spare.filter(b => b !== staging); const commands = gpu.device.createCommandEncoder(); commands.copyBufferToBuffer(gpu.buffers[id], offset, staging, 0, size); gpu.device.queue.submit([commands.finish()]); staging.mapAsync(GPUMapMode.READ, 0, size).then(() => { - gpu.arrived.push({key, bytes: new Uint8Array(staging.getMappedRange(0, size)).slice()}); + then(new Uint8Array(staging.getMappedRange(0, size)).slice()); staging.unmap(); gpu.spare.push(staging); }, () => {}); @@ -392,7 +395,8 @@ const sound = { } }, queue(key) { - if (!sound.queues.has(key)) sound.queues.set(key, {chunks: [], at: 0, queued: 0}); + // `waiting`: GPU buffers on their way, in order (counted as queued). + if (!sound.queues.has(key)) sound.queues.set(key, {chunks: [], waiting: [], at: 0, queued: 0}); return sound.queues.get(key); }, listen() { @@ -660,9 +664,21 @@ const imports = { push(key, ptr, len, clear) { if (len) sound.hint(); const q = sound.queue(key); - if (clear) { q.chunks = []; q.at = 0; q.queued = 0; } + if (clear) { q.chunks = []; q.waiting = []; q.at = 0; q.queued = 0; } if (len) { q.chunks.push(new Float32Array(wasm.memory.buffer.slice(ptr, ptr + len * 4))); q.queued += len; } }, + buffer(key, id, offset, count) { + if (!gpu.buffers[id]) return; + sound.hint(); + const q = sound.queue(key); + const chunk = {samples: null}; + q.waiting.push(chunk); + q.queued += count; + gpu.read(id, offset, count * 4, bytes => { + chunk.samples = new Float32Array(bytes.buffer); + while (q.waiting.length && q.waiting[0].samples) q.chunks.push(q.waiting.shift().samples); + }); + }, queued: key => sound.queues.get(key)?.queued ?? 0, listen: () => sound.listen(), }, |
