@quran-lab/tajweedformer 0.0.0-stage → 2.0.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +148 -0
  3. package/README.md +121 -2
  4. package/dist/tajweedformer-opus.mjs +2 -0
  5. package/dist/tajweedformer-opus.wasm +0 -0
  6. package/dist/tajweedformer-scorer.mjs +2 -0
  7. package/dist/tajweedformer-scorer.wasm +0 -0
  8. package/dist/tajweedformer.mjs +2 -0
  9. package/dist/tajweedformer.wasm +0 -0
  10. package/docs/api.md +167 -0
  11. package/examples/browser.html +69 -0
  12. package/examples/node.mjs +37 -0
  13. package/package.json +81 -6
  14. package/web/consent/copy.js +51 -0
  15. package/web/consent/decks.js +470 -0
  16. package/web/consent/element.js +170 -0
  17. package/web/consent/index.d.ts +128 -0
  18. package/web/consent/index.js +239 -0
  19. package/web/consent/state.js +162 -0
  20. package/web/consent/theme.js +31 -0
  21. package/web/consent/wording.js +126 -0
  22. package/web/index.d.ts +4 -0
  23. package/web/index.js +10 -0
  24. package/web/platform/client.js +484 -0
  25. package/web/platform/contributor-key.js +112 -0
  26. package/web/platform/index.d.ts +148 -0
  27. package/web/platform/index.js +8 -0
  28. package/web/platform/storage.js +50 -0
  29. package/web/platform/telemetry.js +314 -0
  30. package/web/platform/update-notice.js +60 -0
  31. package/web/scorer.d.ts +4 -0
  32. package/web/scorer.js +10 -0
  33. package/web/sharing/bitrate.js +69 -0
  34. package/web/sharing/encoder.js +176 -0
  35. package/web/sharing/index.d.ts +262 -0
  36. package/web/sharing/index.js +287 -0
  37. package/web/sharing/oggopus.js +325 -0
  38. package/web/sharing/outbox.js +670 -0
  39. package/web/sharing/resampler.js +122 -0
  40. package/web/sharing/uploader.js +178 -0
  41. package/web/tajweed/decode.js +213 -0
  42. package/web/tajweed/delivery.js +317 -0
  43. package/web/tajweed/engine.js +600 -0
  44. package/web/tajweed/heads.js +73 -0
  45. package/web/tajweed/index.d.ts +737 -0
  46. package/web/tajweed/index.js +12 -0
  47. package/web/tajweed/manifest.js +452 -0
  48. package/web/tajweed/node.d.ts +3 -0
  49. package/web/tajweed/node.js +59 -0
  50. package/web/tajweed/settings.js +483 -0
  51. package/web/tajweed/tajweedformer.js +369 -0
@@ -0,0 +1,69 @@
1
+ // The adaptive Opus bitrate of shared sessions (SDK 2.0.1, the same ladder in every SDK; the shared vectors'
2
+ // bitrate_ladder.json is replayed by test/sharing_bitrate.test.mjs). One ladder per sharing pipeline (per page or
3
+ // process), in memory, starting at the top rung:
4
+ // uploadFailed() a network failure of an upload request (no connection, timeout, HTTP 408 or 5xx on
5
+ // POST /v1/uploads, POST /v1/uploads/{id}/urls or a segment PUT): one rung down
6
+ // uploadOk(backlogS) a segment PUT answered 2xx, backlogS seconds of closed audio still waiting after it:
7
+ // three in a row with backlogS <= 30 step one rung up
8
+ // segmentClosed(backlogS) a capture closed a segment, backlogS seconds of closed audio waiting (this segment
9
+ // included, every session of the outbox): at 120 or more, one rung down
10
+ // The encoder takes the ladder's bitrate when a segment opens (oggopus.js OggOpusWriter `bitrate`), so a
11
+ // segment has one bitrate, kept in its marker.
12
+ // Tried and rejected: changing the bitrate mid-segment (a segment would have no single bitrate to record);
13
+ // keeping the rung across page loads (a stale bad network would cost quality on a good one); a floor below
14
+ // 32 kbit/s (the log-mel features the model reads drift 1.60 dB at 24k and 2.48 at 16k against 1.17 at 32k,
15
+ // for about 0.07 MB a minute saved per step).
16
+
17
+ /** The rungs, bit/s, top first. */
18
+ export const BITRATE_RUNGS = Object.freeze([192000, 96000, 64000, 32000]);
19
+ /** Successes in a row that step one rung up. */
20
+ export const UP_STREAK = 3;
21
+ /** The most closed audio (s) still waiting that allows a step up. */
22
+ export const UP_MAX_BACKLOG_S = 30;
23
+ /** Closed audio (s) waiting when a segment closes that steps one rung down. */
24
+ export const DOWN_BACKLOG_S = 120;
25
+
26
+ export class BitrateLadder {
27
+ constructor() {
28
+ this.rung = 0;
29
+ this.streak = 0;
30
+ this.listeners = new Set();
31
+ }
32
+
33
+ /** The bit rate the next segment is encoded at. */
34
+ get bitrate() { return BITRATE_RUNGS[this.rung]; }
35
+
36
+ /** Called with the new bitrate whenever it changes; returns the unsubscribe function. */
37
+ onChange(f) { this.listeners.add(f); return () => this.listeners.delete(f); }
38
+
39
+ _set(rung) {
40
+ if (rung === this.rung) return;
41
+ this.rung = rung;
42
+ for (const f of this.listeners) { try { f(this.bitrate); } catch (_) { /* a listener's own problem */ } }
43
+ }
44
+
45
+ uploadFailed() {
46
+ this.streak = 0;
47
+ this._set(Math.min(this.rung + 1, BITRATE_RUNGS.length - 1));
48
+ }
49
+
50
+ uploadOk(backlogS) {
51
+ this.streak = Math.min(this.streak + 1, UP_STREAK);
52
+ if (this.streak >= UP_STREAK && backlogS <= UP_MAX_BACKLOG_S && this.rung > 0) {
53
+ this.streak = 0;
54
+ this._set(this.rung - 1);
55
+ }
56
+ }
57
+
58
+ segmentClosed(backlogS) {
59
+ if (backlogS >= DOWN_BACKLOG_S) {
60
+ this.streak = 0;
61
+ this._set(Math.min(this.rung + 1, BITRATE_RUNGS.length - 1));
62
+ }
63
+ }
64
+ }
65
+
66
+ /** Whether an upload request's answer is a network failure for the ladder: no answer (status 0: no
67
+ * connection, timeout, transport error), HTTP 408 or 5xx. Refusals (4xx, 429 volume limits, 403 on an
68
+ * expired URL) are not. */
69
+ export const isNetworkFailure = (status) => status === 0 || status === 408 || (status >= 500 && status <= 599);
@@ -0,0 +1,176 @@
1
+ // Opus from libopus 1.6.1 compiled to WebAssembly (dist/tajweedformer-opus, scripts/build_opus.sh),
2
+ // set up as the Swift SDK's LibOpusEncoder (Sharing/OpusEncoder.swift): the same settings, frame
3
+ // size, pre-skip and flush. The module is loaded only when sharing is on (loadOpus), so it never
4
+ // touches the first paint.
5
+
6
+ import { OPUS_SETTINGS } from './oggopus.js';
7
+
8
+ const RATES = [8000, 12000, 16000, 24000, 48000];
9
+ // libopus request codes (opus_defines.h)
10
+ export const OPUS_REQUEST = Object.freeze({
11
+ GET_APPLICATION: 4001, GET_BITRATE: 4003, GET_VBR: 4007, GET_BANDWIDTH: 4009, GET_COMPLEXITY: 4011,
12
+ GET_INBAND_FEC: 4013, GET_DTX: 4017, GET_VBR_CONSTRAINT: 4021, GET_SIGNAL: 4025, GET_LOOKAHEAD: 4027,
13
+ GET_SAMPLE_RATE: 4029, GET_LSB_DEPTH: 4037,
14
+ SET_BITRATE: 4002,
15
+ });
16
+
17
+ let modulePromise = null;
18
+ /**
19
+ * The libopus module, instantiated once per page or process. `factory` replaces the bundled module
20
+ * (tests, or an app that hosts the file elsewhere).
21
+ */
22
+ export function loadOpus(factory) {
23
+ if (factory) return factory();
24
+ if (!modulePromise) {
25
+ modulePromise = import('../../dist/tajweedformer-opus.mjs').then((m) => m.default());
26
+ }
27
+ return modulePromise;
28
+ }
29
+
30
+ /** "libopus 1.6.1". */
31
+ export function opusVersion(m) { return m.UTF8ToString(m._ow_version()); }
32
+
33
+ /** An Opus encoder: float PCM in at `sampleRate`, packets out. Non-finite samples are coded as
34
+ * silence. One instance per session; free() when done. */
35
+ export class OpusEncoder {
36
+ constructor(m, { sampleRate = 48000, channels = 1, settings = OPUS_SETTINGS } = {}) {
37
+ if (!RATES.includes(sampleRate)) throw new RangeError(`Opus encodes 8, 12, 16, 24 or 48 kHz, not ${sampleRate} Hz`);
38
+ if (channels !== 1 && channels !== 2) throw new RangeError(`Opus: 1 or 2 channels, not ${channels}`);
39
+ const size = sampleRate * settings.frameMs / 1000;
40
+ if (![2.5, 5, 10, 20, 40, 60].includes(settings.frameMs) || size !== Math.round(size)) {
41
+ throw new RangeError(`Opus frames are 2.5, 5, 10, 20, 40 or 60 ms, not ${settings.frameMs}`);
42
+ }
43
+ this.m = m;
44
+ const errp = m._malloc(4);
45
+ const enc = m._ow_enc_create(sampleRate, channels, settings.application, settings.bitrate, settings.complexity,
46
+ settings.vbr ? 1 : 0, settings.constrainedVbr ? 1 : 0, settings.bandwidth, settings.signal, 24, errp);
47
+ const err = m.HEAP32[errp >> 2];
48
+ m._free(errp);
49
+ if (!enc) throw new Error(`the Opus encoder is not available (${err})`);
50
+ const look = m._ow_enc_get(enc, OPUS_REQUEST.GET_LOOKAHEAD);
51
+ this.enc = enc;
52
+ this.sampleRate = sampleRate;
53
+ this.channels = channels;
54
+ this.settings = settings;
55
+ this.frameSize = size;
56
+ this.perFrame = size * channels;
57
+ // OpusHead pre-skip is in 48 kHz samples whatever the input rate (312 at 48 kHz)
58
+ this.preSkip = Math.trunc(look * 48000 / sampleRate);
59
+ this.framePtr = m._malloc(this.perFrame * 4);
60
+ this.outPtr = m._malloc(4000);
61
+ this.filled = 0;
62
+ this.samplesIn = 0;
63
+ this.nonFiniteSamples = 0;
64
+ this.finished = false;
65
+ this.bitrate = settings.bitrate;
66
+ // packets coded so far; beforeFrame(index), when set, runs before each packet is coded (the Ogg writer
67
+ // opens a segment there and sets its bitrate, so a change lands exactly on the segment's first packet)
68
+ this.packetCount = 0;
69
+ this.beforeFrame = null;
70
+ }
71
+
72
+ /** The bit rate of the packets coded from now on (OPUS_SET_BITRATE; any packet may change it, the
73
+ * stream needs no new header). */
74
+ setBitrate(bps) {
75
+ if (!(Number.isInteger(bps) && bps >= 6000 && bps <= 510000)) throw new RangeError(`Opus bitrate 6000 to 510000 bit/s, not ${bps}`);
76
+ if (bps === this.bitrate) return;
77
+ const e = this.m._ow_enc_set(this.enc, OPUS_REQUEST.SET_BITRATE, bps);
78
+ if (e !== 0) throw new Error(`the Opus encoder refused bitrate ${bps} (${e})`);
79
+ this.bitrate = bps;
80
+ }
81
+
82
+ /** The granule position of the last page: pre-skip plus the input in 48 kHz samples. */
83
+ get finalGranulePosition() { return this.preSkip + Math.trunc(this.samplesIn * 48000 / this.sampleRate); }
84
+
85
+ /** A GET request read back from libopus (OPUS_REQUEST.GET_*), for the tests. */
86
+ get(request) { const v = this.m._ow_enc_get(this.enc, request); return v === -2147483648 ? null : v; }
87
+
88
+ /** Encodes samples; returns the packets completed so far (possibly none), or hands each to `onPacket`
89
+ * as soon as it is coded (then the result is empty). */
90
+ encode(pcm, onPacket = null) {
91
+ if (this.finished) throw new Error('the Opus encoder was flushed');
92
+ const out = [];
93
+ const emit = onPacket || ((p) => out.push(p));
94
+ let i = 0;
95
+ while (i < pcm.length) {
96
+ const n = Math.min(this.perFrame - this.filled, pcm.length - i);
97
+ const f = this.m.HEAPF32.subarray((this.framePtr >> 2) + this.filled, (this.framePtr >> 2) + this.filled + n);
98
+ let bad = 0;
99
+ for (let k = 0; k < n; k++) {
100
+ const v = pcm[i + k];
101
+ if (Number.isFinite(v)) f[k] = v; else { f[k] = 0; bad++; }
102
+ }
103
+ this.nonFiniteSamples += bad;
104
+ this.filled += n;
105
+ i += n;
106
+ if (this.filled === this.perFrame) emit(this._frame());
107
+ }
108
+ this.samplesIn += Math.trunc(pcm.length / this.channels);
109
+ return out;
110
+ }
111
+
112
+ /** Encodes what is buffered and the lookahead, padded with silence to whole packets. The encoder
113
+ * cannot be used afterwards. */
114
+ flush(onPacket = null) {
115
+ if (this.finished) throw new Error('the Opus encoder was flushed');
116
+ this.finished = true;
117
+ const out = [];
118
+ const emit = onPacket || ((p) => out.push(p));
119
+ let owed = Math.trunc(this.filled / this.channels) + Math.trunc(this.preSkip * this.sampleRate / 48000);
120
+ while (owed > 0) {
121
+ this.m.HEAPF32.fill(0, (this.framePtr >> 2) + this.filled, (this.framePtr >> 2) + this.perFrame);
122
+ this.filled = this.perFrame;
123
+ emit(this._frame());
124
+ owed -= this.frameSize;
125
+ }
126
+ return out;
127
+ }
128
+
129
+ _frame() {
130
+ if (this.beforeFrame) this.beforeFrame(this.packetCount);
131
+ this.packetCount += 1;
132
+ const n = this.m._ow_enc_encode(this.enc, this.framePtr, this.frameSize, this.outPtr, 4000);
133
+ this.filled = 0;
134
+ if (n <= 0) throw new Error(`the Opus encoder failed (${n})`);
135
+ return this.m.HEAPU8.slice(this.outPtr, this.outPtr + n);
136
+ }
137
+
138
+ free() {
139
+ if (!this.enc) return;
140
+ this.m._ow_enc_destroy(this.enc);
141
+ this.m._free(this.framePtr);
142
+ this.m._free(this.outPtr);
143
+ this.enc = 0;
144
+ }
145
+ }
146
+
147
+ /** RFC 7845 decode of an Ogg Opus stream with the same libopus (tests): pre-skip dropped, the end
148
+ * trimmed to the last granule position. `pages` from oggopus.readPages. */
149
+ export function decodeOggOpus(m, pages) {
150
+ const head = pages[0].packets[0];
151
+ const preSkip = head[10] | (head[11] << 8);
152
+ const d = m._ow_dec_create(48000, 1);
153
+ const inp = m._malloc(8192), pcm = m._malloc(5760 * 4);
154
+ const parts = [];
155
+ let total = 0;
156
+ try {
157
+ for (const page of pages.slice(2)) {
158
+ for (const p of page.packets) {
159
+ m.HEAPU8.set(p, inp);
160
+ const n = m._ow_dec_decode(d, inp, p.length, pcm, 5760);
161
+ if (n <= 0) throw new Error(`decode failed (${n})`);
162
+ parts.push(m.HEAPF32.slice(pcm >> 2, (pcm >> 2) + n));
163
+ total += n;
164
+ }
165
+ }
166
+ } finally {
167
+ m._ow_dec_destroy(d);
168
+ m._free(inp);
169
+ m._free(pcm);
170
+ }
171
+ const all = new Float32Array(total);
172
+ let at = 0;
173
+ for (const p of parts) { all.set(p, at); at += p.length; }
174
+ const end = pages[pages.length - 1].granule;
175
+ return all.slice(preSkip, Math.min(end, all.length));
176
+ }
@@ -0,0 +1,262 @@
1
+ // Types for '@quran-lab/tajweedformer/sharing': whole-session recitation sharing (PLATFORM_CLIENT.md
2
+ // sections 9 and 10). See web/sharing/index.js.
3
+
4
+ export interface OpusSettings {
5
+ application: number; bitrate: number; complexity: number; vbr: boolean; constrainedVbr: boolean;
6
+ bandwidth: number; signal: number; frameMs: number;
7
+ }
8
+ export const OPUS_SETTINGS: Readonly<OpusSettings>;
9
+ export const CODED_RATE: 48000;
10
+ export const SEGMENT_PLAN: readonly number[];
11
+ export function segmentSeconds(n: number, plan?: readonly number[]): number;
12
+ export function segmentName(n: number): string;
13
+ export function packetFrames(s?: OpusSettings): number;
14
+ export function pagePackets(s?: OpusSettings): number;
15
+ export function oggCrc(bytes: Uint8Array): number;
16
+ export function opusHead(preSkip: number, inputRate: number): Uint8Array;
17
+ export function opusTags(vendor: string): Uint8Array;
18
+ export function oggPage(packets: Uint8Array[], o: { granule: number; serial: number; sequence: number; flags: number }): Uint8Array;
19
+ export interface OggPageInfo { flags: number; granule: number; serial: number; sequence: number; packets: Uint8Array[] }
20
+ export function readPages(bytes: Uint8Array): OggPageInfo[];
21
+ export function wholePages(bytes: Uint8Array): { keep: number; granule: number };
22
+
23
+ export interface OpusEncoding {
24
+ readonly preSkip: number;
25
+ readonly finalGranulePosition: number;
26
+ /** packets coded so far; or each handed to onPacket as it is coded */
27
+ encode(pcm: Float32Array, onPacket?: (p: Uint8Array) => void): Uint8Array[];
28
+ flush(onPacket?: (p: Uint8Array) => void): Uint8Array[];
29
+ /** the bit rate of the packets coded from now on (encoders that support it) */
30
+ setBitrate?(bps: number): void;
31
+ readonly bitrate?: number;
32
+ /** called before each packet is coded, with its index (encoders that support it) */
33
+ beforeFrame?: ((index: number) => void) | null;
34
+ }
35
+ export interface Resampling {
36
+ process(x: Float32Array, sink: (y: Float32Array) => void): void;
37
+ flush(sink: (y: Float32Array) => void): void;
38
+ }
39
+ export class OggOpusWriter {
40
+ constructor(o: {
41
+ encoder: OpusEncoding; resampler?: Resampling | null; inputRate: number; plan?: readonly number[];
42
+ settings?: OpusSettings; serial?: number; vendor?: string;
43
+ onPage: (segment: number, bytes: Uint8Array) => void;
44
+ onSegment?: (s: { n: number; granule: number; last: boolean; bitrate: number | null }) => void;
45
+ /** the bit rate of segment n, asked as it opens (its first packet); null keeps the current one */
46
+ bitrate?: ((n: number) => number | null) | null;
47
+ onSegmentOpen?: (s: { n: number; bitrate: number | null }) => void;
48
+ });
49
+ /** segment number -> the bit rate its packets were coded at */
50
+ readonly segmentBitrates: Map<number, number | null>;
51
+ readonly preSkip: number;
52
+ readonly duration: number;
53
+ readonly inputFrames: number;
54
+ readonly nonFiniteSamples: number;
55
+ readonly lastGranule: number;
56
+ append(samples: Float32Array): void;
57
+ finish(): number;
58
+ abandon(): void;
59
+ }
60
+
61
+ export interface OpusModule { [k: string]: any }
62
+ export function loadOpus(factory?: () => Promise<OpusModule>): Promise<OpusModule>;
63
+ export function opusVersion(m: OpusModule): string;
64
+ export const OPUS_REQUEST: Readonly<Record<string, number>>;
65
+ export class OpusEncoder implements OpusEncoding {
66
+ constructor(m: OpusModule, o?: { sampleRate?: number; channels?: number; settings?: OpusSettings });
67
+ readonly preSkip: number;
68
+ readonly finalGranulePosition: number;
69
+ get(request: number): number | null;
70
+ readonly bitrate: number;
71
+ readonly packetCount: number;
72
+ beforeFrame: ((index: number) => void) | null;
73
+ setBitrate(bps: number): void;
74
+ encode(pcm: Float32Array, onPacket?: (p: Uint8Array) => void): Uint8Array[];
75
+ flush(onPacket?: (p: Uint8Array) => void): Uint8Array[];
76
+ free(): void;
77
+ }
78
+ export function decodeOggOpus(m: OpusModule, pages: OggPageInfo[]): Float32Array;
79
+ export class ShareResampler implements Resampling {
80
+ constructor(inputRate: number);
81
+ process(x: Float32Array, sink: (y: Float32Array) => void): void;
82
+ flush(sink: (y: Float32Array) => void): void;
83
+ }
84
+
85
+ export type InputRoute = 'built_in' | 'wired' | 'usb' | 'bluetooth' | 'car' | 'continuity' | 'other' | 'unknown';
86
+ export const INPUT_ROUTES: readonly InputRoute[];
87
+ export const SDK_VERSION: string;
88
+ export function utcDay(ms?: number): string;
89
+ export function b64url(bytes: Uint8Array): string;
90
+ export function deletionMessage(f: { app: string; contributor: string; nonce: string; timestamp: number }): Uint8Array;
91
+ export function sessionJson(o: {
92
+ modelRevision?: string | null; backend?: 'neuralEngine' | 'exact' | 'mock'; weightsSha256?: string | null; sdkVersion?: string;
93
+ consentVersion?: string | null; consentTextSha256?: string | null; contributor: string; day: string; deviceClass: string; osMajor: number;
94
+ inputSampleRate?: number; inputRoute?: InputRoute; contributorKey?: string | null; recoveryHash?: string | null;
95
+ }): string;
96
+ export interface SegmentUrl { n: number; url: string; expiresAt: number }
97
+ export function parseUrls(body: unknown, id: string): SegmentUrl[] | null;
98
+ export function requestCounts(seconds: number, plan?: readonly number[]): { segments: number; workerCalls: number };
99
+
100
+ /** contributor_revoked / contributor_key_mismatch: make a new contributor, key and recovery code;
101
+ * volume_limit / capped_limit: retried after the next UTC midnight; segment_cap. */
102
+ export class SharingError extends Error {
103
+ readonly code: string;
104
+ readonly status: number;
105
+ }
106
+
107
+ export interface ApiReply { status: number; body: any; text: string; error?: string }
108
+ export class ContributionClient {
109
+ constructor(o: { api: string; fetch?: typeof fetch; headers?: Record<string, string> });
110
+ start(o: { id: string; session: string; token: string; turnstile?: string | null; signal?: AbortSignal }): Promise<ApiReply>;
111
+ urls(o: { id: string; from: number; contributor: string; token: string; signal?: AbortSignal }): Promise<ApiReply>;
112
+ put(o: { url: string; bytes: Uint8Array; signal?: AbortSignal }): Promise<ApiReply>;
113
+ deleteShared(o: { app: string; contributor: string; sign: (message: Uint8Array) => Promise<Uint8Array | ArrayBuffer> }): Promise<any>;
114
+ summary(o: { contributor: string; token: string }): Promise<ApiReply>;
115
+ }
116
+
117
+ export interface SharingStorage {
118
+ sessions(): Promise<string[]>;
119
+ list(id: string): Promise<string[]>;
120
+ read(id: string, name: string): Promise<Uint8Array | null>;
121
+ write(id: string, name: string, bytes: Uint8Array): Promise<void>;
122
+ append(id: string, name: string, bytes: Uint8Array): Promise<void>;
123
+ truncate(id: string, name: string, length: number): Promise<void>;
124
+ remove(id: string, name: string): Promise<void>;
125
+ removeSession(id: string): Promise<void>;
126
+ getGlobal(key: string): Promise<any>;
127
+ setGlobal(key: string, value: any): Promise<void>;
128
+ }
129
+ export class MemoryStorage implements SharingStorage {
130
+ constructor();
131
+ snapshot(): MemoryStorage;
132
+ sessions(): Promise<string[]>; list(id: string): Promise<string[]>; read(id: string, name: string): Promise<Uint8Array | null>;
133
+ write(id: string, name: string, bytes: Uint8Array): Promise<void>; append(id: string, name: string, bytes: Uint8Array): Promise<void>;
134
+ truncate(id: string, name: string, length: number): Promise<void>; remove(id: string, name: string): Promise<void>;
135
+ removeSession(id: string): Promise<void>; getGlobal(key: string): Promise<any>; setGlobal(key: string, value: any): Promise<void>;
136
+ }
137
+ export function dirStorage(root: string): Promise<SharingStorage>;
138
+ export function indexedDbStorage(dbName?: string, idb?: IDBFactory): Promise<SharingStorage>;
139
+ export function defaultStorage(): Promise<SharingStorage>;
140
+ export function recover(storage: SharingStorage, id: string): Promise<boolean>;
141
+ /** A closed segment's record (seg-NNNNN.json); bitrate is absent for segments recorded before 2.0.1. */
142
+ export interface SegmentMarker { n: number; bytes: number; sha256: string; granule: number; bitrate?: number }
143
+ export function markers(storage: SharingStorage, id: string): Promise<SegmentMarker[]>;
144
+ export function markerSeconds(markers: SegmentMarker[]): number[];
145
+ export function sha256Hex(bytes: Uint8Array): Promise<string>;
146
+ export const MAX_AGE_MS: number;
147
+ export const FILES: Readonly<{ session: string; capture: string; end: string; item: string }>;
148
+ export const activeCaptures: Set<string>;
149
+
150
+ export interface ContributionItem {
151
+ id: string; segments: number; bytes: number; durationMs: number; day: string; completed: boolean | null;
152
+ /** the bit rate each segment was coded at, in segment order (null for a segment recorded before 2.0.1) */
153
+ segmentBitrates: (number | null)[];
154
+ status: 'queued' | 'uploaded' | 'failed'; capped: boolean; failCode: string | null; failMessage: string | null;
155
+ attempts: number; lastError: string | null;
156
+ }
157
+ export interface Token { token: string; attested?: boolean }
158
+ export type TokenProvider = (() => Promise<Token>) & { invalidate?: () => Promise<void> };
159
+ export interface SharingFlags {
160
+ contributions?: boolean;
161
+ upload_trust?: Record<string, 'off' | 'capped' | 'attested'>;
162
+ capped_limits?: { turnstile_web?: boolean; [k: string]: unknown };
163
+ }
164
+ export class Outbox {
165
+ items(): Promise<ContributionItem[]>;
166
+ item(id: string): Promise<ContributionItem | null>;
167
+ pending(): Promise<ContributionItem[]>;
168
+ resume(): Promise<void>;
169
+ stop(): Promise<void>;
170
+ cancel(id: string): Promise<void>;
171
+ drain(o?: { ignoringBackoff?: boolean }): Promise<void>;
172
+ uploadAllowed(): { ok: boolean; why?: string; tier?: string };
173
+ /** seconds of audio in closed segments not yet uploaded, every session */
174
+ backlogSeconds(): number;
175
+ }
176
+
177
+ /** The adaptive Opus bitrate (SDK 2.0.1): 192, 96, 64, 32 kbit/s; one per pipeline, from the top. */
178
+ export const BITRATE_RUNGS: readonly number[];
179
+ export const UP_STREAK: 3;
180
+ export const UP_MAX_BACKLOG_S: 30;
181
+ export const DOWN_BACKLOG_S: 120;
182
+ export class BitrateLadder {
183
+ constructor();
184
+ /** the bit rate the next segment opens at */
185
+ readonly bitrate: number;
186
+ readonly rung: number;
187
+ readonly streak: number;
188
+ uploadFailed(): void;
189
+ uploadOk(backlogS: number): void;
190
+ segmentClosed(backlogS: number): void;
191
+ onChange(f: (bitrate: number) => void): () => void;
192
+ }
193
+ export function isNetworkFailure(status: number): boolean;
194
+
195
+ export interface SharingOptions {
196
+ api: string;
197
+ tokenProvider: TokenProvider;
198
+ flags?: SharingFlags | (() => SharingFlags | null) | null;
199
+ enabled?: () => boolean;
200
+ consentVersion?: string | null;
201
+ /** with an app's own wording: the hash of the text the learner agreed to (sent as consent_text_sha256) */
202
+ consentTextSha256?: string | null;
203
+ contributor?: string;
204
+ contributorKeyRaw?: Uint8Array;
205
+ recoveryHash?: string;
206
+ headers?: Record<string, string>;
207
+ storage?: SharingStorage;
208
+ fetch?: typeof fetch;
209
+ turnstile?: () => Promise<string | null>;
210
+ platform?: string;
211
+ device?: { deviceClass: string; osMajor: number };
212
+ onChange?: (item: ContributionItem | { id: string; status: 'dropped'; failCode: string }) => void;
213
+ onError?: (e: SharingError) => void;
214
+ opus?: () => Promise<OpusModule>;
215
+ clock?: () => number;
216
+ /** a fixed Opus bit/s in place of the adaptive ladder (tests and special cases) */
217
+ bitrate?: number;
218
+ }
219
+ export interface DecodeInfo { modelRevision?: string | null; backend?: 'neuralEngine' | 'exact' | 'mock'; weightsSha256?: string | null; sdkVersion?: string }
220
+ export interface SharedSession {
221
+ readonly id: string;
222
+ readonly duration: number;
223
+ /** Mono float samples at the session's input rate (synchronous: encodes at once). */
224
+ push(pcm: Float32Array): void;
225
+ /** The end of the session; resolves to the shared duration in ms (0 when nothing is shared). */
226
+ finish(o?: { completed?: boolean }): Promise<number>;
227
+ /** A cancelled or failed session. */
228
+ abort(): Promise<void>;
229
+ }
230
+ export interface Sharing {
231
+ storage: SharingStorage;
232
+ outbox: Outbox;
233
+ client: ContributionClient;
234
+ /** the adaptive bitrate of this pipeline */
235
+ ladder: BitrateLadder;
236
+ update(next: Partial<SharingOptions>): void;
237
+ contributorId(): Promise<string>;
238
+ resetContributor(): Promise<string>;
239
+ deleteShared(o: { app: string; sign: (message: Uint8Array) => Promise<Uint8Array | ArrayBuffer> }): Promise<any>;
240
+ summary(): Promise<any | null>;
241
+ stop(): Promise<void>;
242
+ startSession(o: { inputSampleRate: number; inputRoute?: InputRoute; decode?: DecodeInfo; serial?: number }): Promise<SharedSession>;
243
+ }
244
+ export function createSharing(o: SharingOptions): Promise<Sharing>;
245
+ export function createSharingSession(o: SharingOptions & { inputSampleRate: number; inputRoute?: InputRoute; decodeInfo?: DecodeInfo }):
246
+ Promise<SharedSession & { outbox: Outbox; sharing: Sharing }>;
247
+ /** The page's pipeline (made by the first createSharingSession or configure()). */
248
+ export const outbox: {
249
+ resume(): Promise<void>;
250
+ stop(): Promise<void>;
251
+ pending(): Promise<ContributionItem[]>;
252
+ items(): Promise<ContributionItem[]>;
253
+ configure(o: SharingOptions): Promise<Sharing>;
254
+ sharing(): Promise<Promise<Sharing> | null>;
255
+ };
256
+ export function resetSharingForTests(): void;
257
+ export function webDevice(): { deviceClass: string; osMajor: number };
258
+ export const MINIMUM_PARTIAL_S: number;
259
+ export class ShareCapture implements SharedSession {
260
+ readonly id: string; readonly duration: number;
261
+ push(pcm: Float32Array): void; finish(o?: { completed?: boolean }): Promise<number>; abort(): Promise<void>;
262
+ }