dewdrop-sdk 0.5.6 → 0.6.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.
package/src/saves.js DELETED
@@ -1,254 +0,0 @@
1
- // `saves` on a developer's machine: the browser stands in for Dewdrop's
2
- // storage. The plugin's script empties `localStorage` and IndexedDB as
3
- // each page the dev server serves loads, as Dewdrop does each time a
4
- // player opens a game; `save` keeps what they hold in a database of the
5
- // browser's own that the game does not see, under the game dewdrop.json
6
- // names and the player the page's URL names, and `load` puts it back.
7
- // Calls run in the order they are made, and the checks and their messages
8
- // are Dewdrop's, so a call that fails here fails there the same way.
9
- import { gameHasBackend, joining } from './backend.js';
10
- import { SAVES_STATE } from './fresh.js';
11
- import { side } from './net.js';
12
- import { NO_SAVES } from './route.js';
13
-
14
- // The store of the saves' database, which holds one snapshot per game and
15
- // player.
16
- const SNAPSHOTS = 'snapshots';
17
-
18
- // The player the page's URL names, as the page joins its backend under.
19
- const player = joining(typeof location === 'undefined' ? '' : location.search).player;
20
-
21
- // The end of the calls made so far, which the next call runs after, and
22
- // the loads among them not yet done.
23
- let last = Promise.resolve();
24
- let loads = 0;
25
-
26
- // Runs `run` once every call made before has settled and the page's
27
- // storage has started empty; refused at once in a game with a backend —
28
- // its backend and its tabs alike, as on Dewdrop, where such a game keeps
29
- // no saves — and in a page without the plugin's script.
30
- function inOrder(op, run) {
31
- if (side.backend || gameHasBackend()) return Promise.reject(new DOMException('saves is unavailable in a game with a backend', 'NotSupportedError'));
32
- const state = globalThis[Symbol.for(SAVES_STATE)];
33
- if (state === undefined) return Promise.reject(new TypeError(`${op}: ${NO_SAVES}`));
34
- const call = last.then(() => state.ready).then(() => run(state));
35
- last = call.catch(() => {});
36
- return call;
37
- }
38
-
39
- // What `localStorage` holds, as a save keeps it.
40
- function readLocal() {
41
- const local = [];
42
- for (let i = 0; i < localStorage.length; i++) {
43
- const key = localStorage.key(i);
44
- local.push([key, localStorage.getItem(key)]);
45
- }
46
- return local;
47
- }
48
-
49
- // Keeps what `localStorage` holds and what IndexedDB has committed for
50
- // this game and player, and resolves once it is stored. `localStorage` is
51
- // read at the call, as Dewdrop snapshots it, unless a load is under way,
52
- // whose result it then keeps.
53
- export function save() {
54
- const early = loads === 0 && globalThis.localStorage !== undefined ? readLocal() : null;
55
- return inOrder('saves.save', async ({ game, database }) => {
56
- const local = early ?? readLocal();
57
- const kept = await Promise.all((await indexedDB.databases()).map(({ name }) => read(name)));
58
- const snapshot = { localStorage: local, databases: kept.filter((each) => each !== null) };
59
- const db = await openSaves(database);
60
- try {
61
- await new Promise((resolve, reject) => {
62
- const transaction = db.transaction(SNAPSHOTS, 'readwrite', { durability: 'strict' });
63
- transaction.addEventListener('complete', () => resolve());
64
- transaction.addEventListener('abort', () => reject(transaction.error ?? new DOMException('saves.save: the save was not stored', 'AbortError')));
65
- transaction.objectStore(SNAPSHOTS).put(snapshot, [game, player]);
66
- });
67
- } finally {
68
- db.close();
69
- }
70
- });
71
- }
72
-
73
- // Replaces `localStorage` and every IndexedDB database with what was saved
74
- // for this game and player and resolves true, or empties them and resolves
75
- // false when nothing was.
76
- export function load() {
77
- loads += 1;
78
- const done = () => { loads -= 1; };
79
- return inOrder('saves.load', async ({ game, database, connected }) => {
80
- const db = await openSaves(database);
81
- let snapshot;
82
- try {
83
- snapshot = await answer(db.transaction(SNAPSHOTS, 'readonly').objectStore(SNAPSHOTS).get([game, player]));
84
- } finally {
85
- db.close();
86
- }
87
- const names = (await indexedDB.databases()).map(({ name }) => name);
88
- // The check and the deletes in one go, so no open of the page's comes
89
- // between them.
90
- if (connected()) {
91
- throw new DOMException('saves.load: an IndexedDB database is open: call saves.load() before opening IndexedDB', 'InvalidStateError');
92
- }
93
- await Promise.all(names.map((name) => remove(name)));
94
- const saved = snapshot ?? { localStorage: [], databases: [] };
95
- await Promise.all(saved.databases.map((each) => recreate(each)));
96
- localStorage.clear();
97
- for (const [key, value] of saved.localStorage) localStorage.setItem(key, value);
98
- return snapshot !== undefined;
99
- }).finally(done);
100
- }
101
-
102
- // What a request answers, once it does.
103
- function answer(request) {
104
- return new Promise((resolve, reject) => {
105
- request.addEventListener('success', () => resolve(request.result));
106
- request.addEventListener('error', () => reject(request.error));
107
- });
108
- }
109
-
110
- // The saves' database, made on its first open.
111
- function openSaves(database) {
112
- const request = indexedDB.open(database, 1);
113
- request.addEventListener('upgradeneeded', () => request.result.createObjectStore(SNAPSHOTS));
114
- return answer(request).then((db) => {
115
- db.addEventListener('versionchange', () => db.close());
116
- return db;
117
- });
118
- }
119
-
120
- // One database as it is committed: its version, each store's key path,
121
- // key generator and indexes, and its records, read in one transaction; or
122
- // null when it was deleted since it was listed. A delete or an upgrade
123
- // asked for meanwhile waits only for the read.
124
- function read(name) {
125
- return new Promise((resolve, reject) => {
126
- const request = indexedDB.open(name);
127
- let gone = false;
128
- request.addEventListener('upgradeneeded', () => {
129
- gone = true;
130
- request.transaction.abort();
131
- });
132
- request.addEventListener('error', () => (gone ? resolve(null) : reject(request.error)));
133
- request.addEventListener('success', () => {
134
- const db = request.result;
135
- db.addEventListener('versionchange', () => db.close());
136
- const kept = { name, version: db.version, stores: [] };
137
- const names = [...db.objectStoreNames];
138
- if (names.length === 0) {
139
- db.close();
140
- resolve(kept);
141
- return;
142
- }
143
- const transaction = db.transaction(names, 'readonly');
144
- for (const storeName of names) {
145
- const store = transaction.objectStore(storeName);
146
- const indexes = [...store.indexNames].map((indexName) => {
147
- const index = store.index(indexName);
148
- return { name: indexName, keyPath: index.keyPath, unique: index.unique, multiEntry: index.multiEntry };
149
- });
150
- const entry = { name: storeName, keyPath: store.keyPath, autoIncrement: store.autoIncrement, indexes, keys: [], values: [] };
151
- kept.stores.push(entry);
152
- answer(store.getAllKeys()).then((keys) => { entry.keys = keys; }, () => {});
153
- answer(store.getAll()).then((values) => { entry.values = values; }, () => {});
154
- }
155
- transaction.addEventListener('complete', () => {
156
- // Each key generator's next key, which no read shows, kept beside
157
- // the records, as Dewdrop keeps it.
158
- const generators = kept.stores.filter((entry) => entry.autoIncrement);
159
- Promise.all(generators.map(async (entry) => { entry.next = await nextKey(db, entry.name); }))
160
- .then(() => {
161
- db.close();
162
- resolve(kept);
163
- }, (error) => {
164
- db.close();
165
- reject(error);
166
- });
167
- });
168
- transaction.addEventListener('abort', () => {
169
- db.close();
170
- reject(transaction.error);
171
- });
172
- });
173
- });
174
- }
175
-
176
- // The next key the key generator of `storeName` hands out. A browser shows
177
- // it to no read, so a record is added and the transaction aborted, which
178
- // takes back the record and the generator's step; null when the add fails.
179
- // The record is an empty object, which no index can take a key from but
180
- // one on the generator's own key path.
181
- function nextKey(db, storeName) {
182
- return new Promise((resolve) => {
183
- const transaction = db.transaction(storeName, 'readwrite');
184
- let next = null;
185
- const added = transaction.objectStore(storeName).add({});
186
- added.addEventListener('success', () => {
187
- next = added.result;
188
- transaction.abort();
189
- });
190
- added.addEventListener('error', (event) => event.preventDefault());
191
- transaction.addEventListener('abort', () => resolve(typeof next === 'number' ? next : null));
192
- transaction.addEventListener('complete', () => resolve(null));
193
- });
194
- }
195
-
196
- // A value holding `key` where `keyPath`, a key generator's, reads it, and
197
- // nothing an index could take another key from.
198
- function placeholder(keyPath, key) {
199
- const value = {};
200
- const names = keyPath.split('.');
201
- let at = value;
202
- for (const name of names.slice(0, -1)) at = at[name] = {};
203
- at[names[names.length - 1]] = key;
204
- return value;
205
- }
206
-
207
- // Deletes a database, refused while another tab of the dev server holds it
208
- // open: the browser deletes it once that tab lets go.
209
- function remove(name) {
210
- return new Promise((resolve, reject) => {
211
- const request = indexedDB.deleteDatabase(name);
212
- request.addEventListener('success', () => resolve());
213
- request.addEventListener('error', () => reject(request.error));
214
- request.addEventListener('blocked', () => reject(heldElsewhere(name)));
215
- });
216
- }
217
-
218
- // Makes a saved database again, at its version, with its stores, indexes
219
- // and records.
220
- function recreate({ name, version, stores }) {
221
- return new Promise((resolve, reject) => {
222
- const request = indexedDB.open(name, version);
223
- request.addEventListener('upgradeneeded', () => {
224
- const db = request.result;
225
- for (const { name: storeName, keyPath, autoIncrement, indexes, keys, values, next } of stores) {
226
- const store = db.createObjectStore(storeName, { keyPath, autoIncrement });
227
- for (const index of indexes) {
228
- store.createIndex(index.name, index.keyPath, { unique: index.unique, multiEntry: index.multiEntry });
229
- }
230
- for (let i = 0; i < keys.length; i++) {
231
- if (keyPath === null) store.put(values[i], keys[i]);
232
- else store.put(values[i]);
233
- }
234
- // The generator back where it was, past keys deleted since they
235
- // were handed out: a key just below its next, put and deleted,
236
- // moves it there.
237
- if (typeof next === 'number' && next > 1 && !keys.includes(next - 1)) {
238
- const put = keyPath === null ? store.put({}, next - 1) : store.put(placeholder(keyPath, next - 1));
239
- put.addEventListener('error', (event) => event.preventDefault());
240
- store.delete(next - 1);
241
- }
242
- }
243
- });
244
- request.addEventListener('blocked', () => reject(heldElsewhere(name)));
245
- answer(request).then((db) => {
246
- db.close();
247
- resolve();
248
- }, reject);
249
- });
250
- }
251
-
252
- function heldElsewhere(name) {
253
- return new DOMException(`saves.load: another tab holds the IndexedDB database ${JSON.stringify(name)} open`, 'InvalidStateError');
254
- }
package/src/serve.js DELETED
@@ -1,203 +0,0 @@
1
- // The dev server's backend host, its stand-in for Dewdrop. A thread runs
2
- // the project's backend.js for each room the tabs join, from the room's
3
- // first tab's join until five minutes after its last tab's leave, as on
4
- // Dewdrop, so a tab that comes back in that time rejoins it; a room seats
5
- // the players its first tab's page said, a player counted once however
6
- // many tabs they play from and an unnamed tab as one each, and refuses a
7
- // tab past them as Dewdrop refuses its connect; the tabs are
8
- // numbered from one per room, never twice while its thread runs; each
9
- // tab's frame of sends reaches its room's thread over the port
10
- // with the tab's number, and each of the thread's sends reaches the tab it
11
- // names, or every tab of the room, over the socket. An edit to the backend
12
- // restarts every room and reloads the tabs, which join afresh. A backend
13
- // that throws or ends on its own is stopped and the reason logged, and its
14
- // room stays stopped until the next edit: restarting it would only throw
15
- // again, and reloading the tabs at each throw would leave nothing to read
16
- // the error in.
17
- import { existsSync, readFileSync } from 'node:fs';
18
- import { dirname, resolve } from 'node:path';
19
- import { Worker } from 'node:worker_threads';
20
- import { DEFAULT_ROOM_PLAYERS, MAX_NET_CLIENTS, label } from './net.js';
21
-
22
- // How long a room's backend runs on after its last tab's leave, as on
23
- // Dewdrop.
24
- export const EMPTY_ROOM_MS = 5 * 60 * 1000;
25
-
26
- // The files an edit to which restarts the backend: the entry and what it
27
- // reaches through static relative imports.
28
- export function backendFiles(entry) {
29
- const files = new Set();
30
- const visit = (file) => {
31
- if (files.has(file) || !existsSync(file)) return;
32
- files.add(file);
33
- const text = readFileSync(file, 'utf8');
34
- for (const match of text.matchAll(/^\s*(?:import|export)\b[^;'"]*?from\s+['"](\.\.?\/[^'"]+)['"]/gm)) {
35
- visit(resolve(dirname(file), match[1]));
36
- }
37
- };
38
- visit(entry);
39
- return files;
40
- }
41
-
42
- // Runs the backends at `entry` for the tabs that join over `ws`, the dev
43
- // server's socket, one per room; `watcher` reports edits, `origin` is the
44
- // dev server's address for a backend's model calls, and `log` hears why a
45
- // backend ended.
46
- export function createBackendHost({ entry, ws, watcher, origin = () => '', log = console }) {
47
- // Read afresh at each start, so a file the backend imports since is watched too.
48
- let files = backendFiles(entry);
49
- // Each room's backend by the room's key, and each joined tab's room.
50
- const rooms = new Map();
51
- const tabs = new Map();
52
-
53
- // One room's backend, seating `capacity` players: its thread from the
54
- // room's first tab's join until EMPTY_ROOM_MS after its last tab's leave
55
- // with none joining since, its tabs by number from one with their
56
- // players' names.
57
- function createRoom(key, capacity) {
58
- const name = key === '' ? 'the backend' : `the backend of room ${JSON.stringify(key)}`;
59
- const members = new Map();
60
- const names = new Map();
61
- let worker = null;
62
- let next = 1;
63
- let broken = false;
64
- // While the room is empty, the timer that ends it.
65
- let idle = null;
66
-
67
- function deliver(sends) {
68
- for (const [client, number] of members) {
69
- const items = sends.filter((send) => send.to === 0 || send.to === number);
70
- if (items.length !== 0) client.send('dew:recv', { items });
71
- }
72
- }
73
-
74
- function start() {
75
- files = backendFiles(entry);
76
- worker = new Worker(new URL('./backend-host.js', import.meta.url), { workerData: { entry, origin: origin(), capacity } });
77
- const started = worker;
78
- started.on('message', (message) => {
79
- if (message.kind === 'send' && worker === started) deliver(message.sends);
80
- });
81
- started.on('error', (error) => {
82
- if (worker === started) broke(`${name} threw: ${error.stack ?? error}`);
83
- });
84
- started.on('exit', (code) => {
85
- if (worker === started) broke(`${name} ended with ${code}`);
86
- });
87
- }
88
-
89
- // Ends the thread and forgets every tab, which join afresh next time.
90
- function stop() {
91
- const ended = worker;
92
- worker = null;
93
- clearTimeout(idle);
94
- idle = null;
95
- for (const client of members.keys()) tabs.delete(client);
96
- members.clear();
97
- names.clear();
98
- next = 1;
99
- if (ended !== null) ended.terminate();
100
- }
101
-
102
- // A thread that threw or ended: stopped, said so, and not started
103
- // again for a join until an edit lands.
104
- function broke(reason) {
105
- log.error(`[dewdrop] ${reason}; ${name} is stopped until it is edited`);
106
- stop();
107
- broken = true;
108
- }
109
-
110
- // The room's players, each once: its tabs' names, and each unnamed tab.
111
- function seated() {
112
- const players = [...names.values()];
113
- return players.filter((player, at) => player === '' || players.indexOf(player) === at).length;
114
- }
115
-
116
- const room = {
117
- join(client, player) {
118
- if (broken) return;
119
- const returning = player !== '' && [...names.values()].includes(player);
120
- if (members.size >= MAX_NET_CLIENTS || (!returning && seated() >= capacity)) {
121
- log.error(`[dewdrop] a tab is refused ${name}: it seats ${capacity === 1 ? '1 player' : `${capacity} players`}`);
122
- client.send('dew:full', { capacity });
123
- return;
124
- }
125
- clearTimeout(idle);
126
- idle = null;
127
- const number = next++;
128
- members.set(client, number);
129
- names.set(client, player);
130
- tabs.set(client, room);
131
- if (worker === null) start();
132
- worker.postMessage([{ kind: 'join', client: number, player }]);
133
- client.socket.once('close', () => host.leave(client));
134
- },
135
- leave(client) {
136
- const number = members.get(client);
137
- if (number === undefined) return;
138
- members.delete(client);
139
- names.delete(client);
140
- tabs.delete(client);
141
- worker.postMessage([{ kind: 'leave', client: number }]);
142
- if (members.size === 0) {
143
- idle = setTimeout(() => {
144
- stop();
145
- rooms.delete(key);
146
- }, EMPTY_ROOM_MS);
147
- }
148
- },
149
- receive(client, items) {
150
- const number = members.get(client);
151
- if (number === undefined || worker === null) return;
152
- worker.postMessage(items.map((item) => ({ kind: 'message', client: number, ...item })));
153
- },
154
- stop,
155
- };
156
- return room;
157
- }
158
-
159
- // Ends every room's thread and forgets every tab.
160
- function close() {
161
- for (const room of rooms.values()) room.stop();
162
- rooms.clear();
163
- }
164
-
165
- // An edit: every room's backend ends and the tabs reload, joining
166
- // fresh ones.
167
- function restart(reason) {
168
- log.error(`[dewdrop] ${reason}; restarting the backend`);
169
- close();
170
- ws.send({ type: 'full-reload', path: '*' });
171
- }
172
-
173
- const host = {
174
- // A tab joins the room its page named under the name it gave, a room
175
- // it makes seating the players its page said; a page that named
176
- // neither joins the empty room unnamed, and one that named no size a
177
- // room seating DEFAULT_ROOM_PLAYERS, as a game's rooms on Dewdrop do.
178
- join(client, { room = '', player = '', players = DEFAULT_ROOM_PLAYERS } = {}) {
179
- if (tabs.has(client)) return;
180
- const key = typeof room === 'string' ? room : '';
181
- let it = rooms.get(key);
182
- if (it === undefined) {
183
- const capacity = Number.isInteger(players) && players >= 1 && players <= MAX_NET_CLIENTS ? players : DEFAULT_ROOM_PLAYERS;
184
- it = createRoom(key, capacity);
185
- rooms.set(key, it);
186
- }
187
- it.join(client, label(player));
188
- },
189
- leave(client) {
190
- tabs.get(client)?.leave(client);
191
- },
192
- receive(client, items) {
193
- tabs.get(client)?.receive(client, items);
194
- },
195
- close,
196
- };
197
- ws.on('dew:join', (data, client) => host.join(client, { room: data?.room, player: data?.player, players: data?.players }));
198
- ws.on('dew:send', (data, client) => host.receive(client, data.items ?? []));
199
- watcher.on('change', (file) => {
200
- if (files.has(resolve(file))) restart(`${file} changed`);
201
- });
202
- return host;
203
- }
package/src/session.js DELETED
@@ -1,50 +0,0 @@
1
- // `session` on a developer's machine. On Dewdrop a session can end ahead of
2
- // time — for maintenance, a newer version of its game published, its player
3
- // idle for fifteen minutes, its player away for ten — the page hidden, or
4
- // another game of theirs showing — or its player choosing to play in
5
- // another tab — and hears of it first, up to fifteen minutes before, a
6
- // minute for an idle or an away player, and as it ends for a player playing
7
- // elsewhere: `session.ending` is `{at, reason}`, `at` in milliseconds since
8
- // the epoch as `Date.now()` counts and `reason` `'restart'`, `'update'`,
9
- // `'idle'`, `'away'`, `'elsewhere'` or `'exit'`, and an `ending` event fires
10
- // each time it changes, its withdrawal to null included, so a game can save
11
- // and say so. A game ends its player's session itself with
12
- // `session.exit()`, which on Dewdrop takes the player back to Dewdrop's
13
- // home page while the room's other players play on, the game hearing
14
- // `'exit'` as it goes; a backend has no player to send anywhere, so there it
15
- // throws NotSupportedError. A game that lays itself out for either shape
16
- // calls `session.allowPortrait()`, after which Dewdrop turns its view
17
- // portrait whenever its player's page asks — a phone held upright — and the
18
- // game hears each turn as a `resize`, its window taking the view's new
19
- // shape; until then a session stays landscape, and a backend, which has no
20
- // view, throws NotSupportedError. `npm run dev` ends no session, so here
21
- // `ending` stays null and the event never fires, a game trying its handler
22
- // by calling it, and `exit()` ends nothing: the console says so, once. The
23
- // game here is the browser's own window, which already takes any shape and
24
- // fires its own `resize`, so `allowPortrait()` changes nothing and says
25
- // what it does on Dewdrop, once. `session.dev` is true in the game's dev
26
- // version and false once it is published, in a backend too; `npm run dev`
27
- // is development, so here it is true.
28
- import { defineHandlers, side } from './net.js';
29
-
30
- let told = false;
31
- let toldPortrait = false;
32
- class Session extends EventTarget {
33
- get ending() { return null; }
34
- get dev() { return true; }
35
- exit() {
36
- if (side.backend) throw new DOMException('session.exit is unavailable in a backend', 'NotSupportedError');
37
- if (told) return;
38
- told = true;
39
- console.info('[dewdrop] session.exit(): on Dewdrop this ends the session and takes the player back to Dewdrop’s home page; npm run dev keeps the game running');
40
- }
41
- allowPortrait() {
42
- if (side.backend) throw new DOMException('session.allowPortrait is unavailable in a backend', 'NotSupportedError');
43
- if (toldPortrait) return;
44
- toldPortrait = true;
45
- console.info('[dewdrop] session.allowPortrait(): on Dewdrop the view turns portrait whenever the player’s page is taller than wide, each turn a resize; npm run dev’s window already takes any shape');
46
- }
47
- }
48
- defineHandlers(Session.prototype, ['ending']);
49
-
50
- export const session = new Session();
package/src/voice.js DELETED
@@ -1,135 +0,0 @@
1
- // `voice` on a developer's machine: the player's microphone a chunk at a
2
- // time, as a game gets it on Dewdrop, where Dewdrop carries no voice
3
- // between players and plays none itself: a game sends what it captures
4
- // to its backend through its messages, the backend sends it on to the
5
- // players it chooses, and their games play it through their own audio
6
- // graphs. Here the browser's own audio worklet reads the microphone and
7
- // hands the game the same chunks, so a game captures in `npm run dev` as
8
- // it captures on Dewdrop.
9
-
10
- // The chunks as Dewdrop hands them to a game: the rate of their samples,
11
- // the samples in one chunk, 1/60 s, and the chunks that wait for a game
12
- // that reads late, the newest kept.
13
- export const SAMPLE_RATE = 48000;
14
- export const VOICE_CHUNK_SAMPLES = 800;
15
- export const VOICE_CHUNKS_HELD = 8;
16
-
17
- // The processor that reads the microphone in the browser's audio thread:
18
- // it takes the microphone's frames at the context's rate, steps through
19
- // them at SAMPLE_RATE, and posts each VOICE_CHUNK_SAMPLES of them as 16-bit
20
- // samples, the buffer handed over rather than copied. Its output is
21
- // silence, so it can hang off the destination, which is what has it run.
22
- export const CAPTURE_PROCESSOR = 'dew-voice-capture';
23
- export const CAPTURE_WORKLET = `
24
- class DewVoiceCapture extends AudioWorkletProcessor {
25
- constructor() {
26
- super();
27
- this.chunk = new Int16Array(${VOICE_CHUNK_SAMPLES});
28
- this.at = 0;
29
- // The microphone's frames per sample, and where in the block the next
30
- // sample falls.
31
- this.step = sampleRate / ${SAMPLE_RATE};
32
- this.phase = 0;
33
- }
34
- process(inputs) {
35
- const frames = inputs[0][0];
36
- if (frames === undefined) return true;
37
- while (this.phase < frames.length) {
38
- const i = Math.floor(this.phase);
39
- const next = i + 1 < frames.length ? frames[i + 1] : frames[i];
40
- const sample = frames[i] + (next - frames[i]) * (this.phase - i);
41
- const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;
42
- this.chunk[this.at++] = Math.round(clamped * 32767);
43
- if (this.at === this.chunk.length) {
44
- this.port.postMessage(this.chunk, [this.chunk.buffer]);
45
- this.chunk = new Int16Array(${VOICE_CHUNK_SAMPLES});
46
- this.at = 0;
47
- }
48
- this.phase += this.step;
49
- }
50
- this.phase -= frames.length;
51
- return true;
52
- }
53
- }
54
- registerProcessor('${CAPTURE_PROCESSOR}', DewVoiceCapture);
55
- `;
56
-
57
- // The capture under way, if any.
58
- let capturing = null;
59
-
60
- // A stream with a live audio track, as `getUserMedia` resolves one.
61
- function liveMicrophone(stream) {
62
- return stream !== null && typeof stream === 'object' && typeof stream.getAudioTracks === 'function'
63
- && stream.getAudioTracks().some((track) => track.readyState === 'live');
64
- }
65
-
66
- // The player's microphone, a chunk at a time: given the stream
67
- // `getUserMedia` resolved, while its track is live, hands back the
68
- // capture, whose `read()` returns the chunks that arrived since the last
69
- // read — each an Int16Array of VOICE_CHUNK_SAMPLES samples, mono, at
70
- // SAMPLE_RATE, in order, the newest VOICE_CHUNKS_HELD kept when the game
71
- // reads late — and whose `stop()` ends it, closing the context at once.
72
- // One at a time. The browser's own graph reads the stream: a context at
73
- // the sample rate where the browser allows one, the worklet between the
74
- // stream and the destination.
75
- function capture(stream) {
76
- if (!liveMicrophone(stream)) {
77
- throw new TypeError('voice.capture: stream is not a live microphone stream from navigator.mediaDevices.getUserMedia');
78
- }
79
- if (capturing !== null) throw new DOMException('voice.capture: the microphone is captured already; stop that first', 'InvalidStateError');
80
- if (typeof AudioContext === 'undefined' || typeof AudioWorkletNode === 'undefined') {
81
- throw new DOMException('voice.capture is unavailable here: the browser has no AudioWorklet', 'NotSupportedError');
82
- }
83
- let context;
84
- try {
85
- context = new AudioContext({ sampleRate: SAMPLE_RATE });
86
- } catch {
87
- context = new AudioContext();
88
- }
89
- let chunks = [];
90
- let live = true;
91
- const worklet = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: 'text/javascript' }));
92
- const ready = context.audioWorklet.addModule(worklet).then(() => {
93
- URL.revokeObjectURL(worklet);
94
- if (!live) return undefined;
95
- const node = new AudioWorkletNode(context, CAPTURE_PROCESSOR, {
96
- numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1], channelCount: 1, channelCountMode: 'explicit',
97
- });
98
- node.port.onmessage = ({ data }) => {
99
- if (!live) return;
100
- chunks.push(data);
101
- if (chunks.length > VOICE_CHUNKS_HELD) chunks.splice(0, chunks.length - VOICE_CHUNKS_HELD);
102
- };
103
- context.createMediaStreamSource(stream).connect(node).connect(context.destination);
104
- // A context the browser keeps suspended until the player's next
105
- // gesture starts then; nothing here waits on it.
106
- context.resume().catch(() => {});
107
- });
108
- // A worklet the browser refuses leaves the capture silent; the reason
109
- // goes to the console, where the developer is.
110
- ready.catch((error) => console.error('voice.capture: the microphone could not be read: ' + error.message));
111
- const mine = Object.freeze({
112
- read() {
113
- if (capturing !== mine || chunks.length === 0) return [];
114
- const read = chunks;
115
- chunks = [];
116
- return read;
117
- },
118
- stop() {
119
- if (capturing !== mine) return;
120
- capturing = null;
121
- live = false;
122
- chunks = [];
123
- // Closed at once, whether or not the worklet has loaded or the
124
- // context ever ran: a setup still to come finds `live` false and
125
- // makes nothing.
126
- context.close().catch(() => {});
127
- },
128
- });
129
- capturing = mine;
130
- return mine;
131
- }
132
-
133
- // SAMPLE_RATE is the chunks' rate, for the buffers a game plays them
134
- // through.
135
- export const voice = Object.freeze({ capture, SAMPLE_RATE });