@avoid.quest/audio 0.1.0 → 0.1.1-beta.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.
Files changed (41) hide show
  1. package/README.md +30 -2
  2. package/dist/effects/index.d.ts +21 -72
  3. package/dist/effects/index.js +212 -505
  4. package/dist/effects/index.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/midi/index.d.ts +0 -24
  8. package/dist/midi/index.js +222 -258
  9. package/dist/midi/index.js.map +1 -1
  10. package/dist/native-Bern4_PB.js +172 -0
  11. package/dist/native-Bern4_PB.js.map +1 -0
  12. package/dist/pcm-buffer-DSzGHbon.js +436 -0
  13. package/dist/pcm-buffer-DSzGHbon.js.map +1 -0
  14. package/dist/playback/index.d.ts +60 -114
  15. package/dist/playback/index.js +899 -1062
  16. package/dist/playback/index.js.map +1 -1
  17. package/dist/queue/index.d.ts +8 -19
  18. package/dist/queue/index.js +461 -960
  19. package/dist/queue/index.js.map +1 -1
  20. package/dist/recognize/index.d.ts +37 -74
  21. package/dist/recognize/index.js +172 -2715
  22. package/dist/recognize/index.js.map +1 -1
  23. package/dist/routing/index.d.ts +3 -34
  24. package/dist/routing/index.js +413 -536
  25. package/dist/routing/index.js.map +1 -1
  26. package/dist/shazam-gBrX1NEY.d.ts +27 -0
  27. package/dist/sync/index.d.ts +9 -77
  28. package/dist/sync/index.js +320 -542
  29. package/dist/sync/index.js.map +1 -1
  30. package/dist/{worklet-loader-BvEW0oVO.d.ts → worklet-loader-BabwPALw.d.ts} +4 -7
  31. package/dist/{worklet-loader-S7R8ZAmP.js → worklet-loader-f741D1tk.js} +37 -52
  32. package/dist/worklet-loader-f741D1tk.js.map +1 -0
  33. package/dist/worklets/couch-live.js +110 -192
  34. package/dist/worklets/couch-live.js.map +1 -1
  35. package/dist/worklets/meter.js +14 -20
  36. package/dist/worklets/meter.js.map +1 -1
  37. package/dist/worklets/pcm-capture.d.ts +6 -0
  38. package/dist/worklets/pcm-capture.js +52 -0
  39. package/dist/worklets/pcm-capture.js.map +1 -0
  40. package/package.json +8 -3
  41. package/dist/worklet-loader-S7R8ZAmP.js.map +0 -1
@@ -1,6 +1,8 @@
1
1
  import { Context, Effect, Layer, Schedule, Scope } from "effect";
2
- import { n as AudioDecodeError, o as AudioPlaybackError, t as AudioCaptureError, u as AudioUnsupportedError } from "../errors-ChTQFwuZ.js";
2
+ import { d as AudioWorkletError, n as AudioDecodeError, o as AudioPlaybackError, t as AudioCaptureError, u as AudioUnsupportedError } from "../errors-ChTQFwuZ.js";
3
3
  import Hls, { HlsConfig } from "hls.js";
4
+ import { l as ShazamSignatureResult } from "../shazam-gBrX1NEY.js";
5
+ import { t as LoadAudioWorkletOptions } from "../worklet-loader-BabwPALw.js";
4
6
  interface AudioContextOptionsInput {
5
7
  readonly isMobile?: boolean;
6
8
  readonly isFirefox?: boolean;
@@ -20,65 +22,20 @@ interface AudioContextHandle {
20
22
  readonly close: () => Effect.Effect<void>;
21
23
  }
22
24
  interface AudioContextLayerOptions extends AudioContextOptionsInput {
23
- /**
24
- * Optional pre-created `AudioContext` instance to wrap instead of
25
- * constructing a new browser `AudioContext`.
26
- */
27
25
  readonly context?: AudioContext;
28
- /**
29
- * Optional custom `AudioContext` factory (useful in tests or custom hosts).
30
- */
31
26
  readonly createContext?: (options: AudioContextOptions) => AudioContext;
32
- /**
33
- * Whether closing the layer `Scope` closes the underlying `AudioContext`.
34
- * Defaults to `true` when constructed by the layer, and `false` when an
35
- * existing `context` is supplied.
36
- */
37
27
  readonly closeOnRelease?: boolean;
38
- /**
39
- * Automatically attach passive user-gesture unlock listeners while suspended.
40
- * Defaults to `true`.
41
- */
42
28
  readonly unlockOnGesture?: boolean;
43
- /**
44
- * Custom `EventTarget` for gesture unlock listeners (defaults to `window`).
45
- */
46
29
  readonly unlockTarget?: EventTarget;
47
30
  }
48
31
  declare const AudioContextService_base: Context.ServiceClass<AudioContextService, "@avoid.quest/audio/AudioContextService", AudioContextHandle>;
49
32
  export declare class AudioContextService extends AudioContextService_base {}
50
- /**
51
- * Computes browser-aware `AudioContextOptions`:
52
- * - Mobile uses a 128-frame latency hint (`128 / 48_000`) to avoid glitches.
53
- * - Firefox omits forced `sampleRate` because forcing 48 kHz breaks some device drivers.
54
- */
55
33
  export declare function createAudioContextOptions(options?: AudioContextOptionsInput): AudioContextOptions;
56
- /**
57
- * Normalizes Safari/iOS `"interrupted"` state to `"suspended"`.
58
- */
59
34
  export declare function normalizeAudioContextState(state: AudioContextState | "interrupted"): "suspended" | "running" | "closed";
60
35
  export declare function snapshotAudioContext(context: AudioContext): AudioContextSnapshot;
61
- /**
62
- * Deduplicates concurrent `AudioContext.resume()` calls and normalizes iOS `"interrupted"` state.
63
- */
64
36
  export declare function ensureAudioContextRunning(context: AudioContext): Effect.Effect<void, AudioPlaybackError>;
65
- /**
66
- * Attaches persistent passive user-gesture listeners to unlock a suspended
67
- * `AudioContext` (including iOS Safari, where `touchstart` or early gestures
68
- * may resolve without transitioning `state` to `"running"`). Listeners remain
69
- * active across gestures until `context.state === "running"` (or `"closed"`),
70
- * or until the returned cleanup callback is invoked.
71
- */
72
37
  export declare function attachGestureUnlock(context: AudioContext, target?: EventTarget | undefined): () => void;
73
- /**
74
- * Acquires a `Scope`-managed `AudioContextHandle`, optionally attaching
75
- * user-gesture unlock listeners and releasing listeners + closing owned
76
- * `AudioContext` instances when the `Scope` closes.
77
- */
78
38
  export declare function acquireAudioContext(options?: AudioContextLayerOptions): Effect.Effect<AudioContextHandle, AudioUnsupportedError, Scope.Scope>;
79
- /**
80
- * Builds a scoped Effect v4 `Layer` providing `AudioContextService`.
81
- */
82
39
  export declare function makeAudioContextLayer(options?: AudioContextLayerOptions): Layer.Layer<AudioContextService, AudioUnsupportedError>;
83
40
  interface ChannelSelection {
84
41
  readonly left: number;
@@ -105,19 +62,7 @@ interface LiveInputCapture {
105
62
  readonly outputChannelCount: 1 | 2;
106
63
  readonly stop: () => void;
107
64
  }
108
- /**
109
- * Requests browser tab audio via `getDisplayMedia` with Chromium self-capture
110
- * exclusion hints, abort/cancellation cleanup, and a feedback-loop guard
111
- * verifying `displaySurface === "browser"` and at least one live audio track.
112
- */
113
65
  export declare function requestDisplayAudio(options?: DisplayAudioOptions): Effect.Effect<MediaStream, AudioCaptureError>;
114
- /**
115
- * Acquires a live audio input (`getUserMedia` or a pre-acquired `MediaStream`),
116
- * wires optional channel selection routing into an output `GainNode`, supports
117
- * `AbortSignal` and `Scope`/fiber cancellation without leaking pending
118
- * `MediaStreamTrack`s, and automatically stops tracks + disconnects nodes when
119
- * the Effect `Scope` closes.
120
- */
121
66
  export declare function acquireInputCapture(context: AudioContext, options?: DeviceCaptureOptions): Effect.Effect<LiveInputCapture, AudioCaptureError, Scope.Scope>;
122
67
  export declare const MIN_PLAYBACK_RATE = 0.5;
123
68
  export declare const MAX_PLAYBACK_RATE = 2;
@@ -134,11 +79,6 @@ interface MediaEngineLoadOptions {
134
79
  readonly allowNativeHls?: boolean;
135
80
  readonly hlsConfig?: Partial<HlsConfig>;
136
81
  readonly crossOrigin?: "" | "anonymous" | "use-credentials" | null;
137
- /**
138
- * When `true`, `load()` waits for metadata/playable readiness
139
- * (`loadedmetadata` / `canplay` / `MANIFEST_PARSED`) and fails with
140
- * `MEDIA_READY_TIMEOUT` after `readyTimeoutMs` (default `DEFAULT_MEDIA_READY_TIMEOUT_MS`).
141
- */
142
82
  readonly waitForReady?: boolean;
143
83
  readonly readyTimeoutMs?: number;
144
84
  }
@@ -182,58 +122,73 @@ interface MediaEngine {
182
122
  readonly getSnapshot: () => MediaEngineSnapshot;
183
123
  readonly dispose: () => Effect.Effect<void>;
184
124
  }
185
- /**
186
- * Clamps playback speed into the supported `[0.5, 2.0]` range.
187
- */
188
- export declare function clampPlaybackRate(rate: number): number;
189
- /**
190
- * Sets pitch preservation on an `HTMLMediaElement`, including Safari < 17 `webkitPreservesPitch`.
191
- */
125
+ export declare const clampPlaybackRate: (rate: number) => number;
192
126
  export declare function applyPreservesPitch(element: HTMLMediaElement, preserve: boolean): boolean;
193
- /**
194
- * Detects `.m3u8` HLS streams, checking one level deep inside `?url=` proxy params.
195
- */
196
127
  export declare function isHlsUrl(url: string, depth?: number): boolean;
197
- /**
198
- * Returns true for Safari / Apple WebKit browsers (excluding Chrome/Edge/Firefox).
199
- */
200
- export declare function isWebKitBrowser(userAgent?: string | undefined): boolean;
201
- /**
202
- * Uses native HLS only on Safari/WebKit with `application/vnd.apple.mpegurl` support.
203
- * Chrome stays on `hls.js` because native Chrome HLS rejects certain MP3/AAC segments.
204
- */
128
+ export declare const isWebKitBrowser: (ua?: string | undefined) => boolean;
205
129
  export declare function shouldUseNativeHls(element: Pick<HTMLMediaElement, "canPlayType">, allowNativeHls?: boolean, userAgent?: string): boolean;
130
+ export declare const computeStallBackoffMs: (attempt: number, base?: number, max?: number) => number;
131
+ export declare function createStallRecoverySchedule(config?: StallRecoveryConfig): Schedule.Schedule<number>;
132
+ export declare function createMediaEngine(options: MediaEngineOptions): Effect.Effect<MediaEngine, never, Scope.Scope>;
133
+ interface MediaElementSourceOptions {
134
+ /**
135
+ * Route the source to `context.destination` (default `true`). A captured
136
+ * element is only audible through the Web Audio graph, so disable this only
137
+ * when you route the node yourself; `false` also removes an edge created by
138
+ * an earlier call.
139
+ */
140
+ readonly connectToDestination?: boolean;
141
+ }
142
+ /** A raw media element or anything exposing one, such as a `MediaEngine`. */
143
+ type MediaElementSourceTarget = HTMLMediaElement | Pick<MediaEngine, "element">;
206
144
  /**
207
- * Exponential backoff delay calculation matching Radio's recovery schedule:
208
- * `0ms` for attempt `<= 0`, then `1s, 2s, 4s, 8s, 16s, 30s` cap.
209
- */
210
- export declare function computeStallBackoffMs(attempt: number, baseDelayMs?: number, maxDelayMs?: number): number;
211
- /**
212
- * Builds an Effect v4 `Schedule` for bounded exponential stall/disconnect recovery.
145
+ * Returns the memoized `MediaElementAudioSourceNode` for a `MediaEngine` or
146
+ * media element (browsers allow only one per element), so live playback can
147
+ * feed `acquirePcmCapture`, meters, or effects. Requesting it for another
148
+ * `AudioContext` fails with `MEDIA_SOURCE_CONTEXT_MISMATCH`. Cross-origin
149
+ * media needs CORS + `crossOrigin: "anonymous"`, otherwise the graph is silent.
213
150
  */
214
- export declare function createStallRecoverySchedule(config?: StallRecoveryConfig): Schedule.Schedule<number>;
151
+ export declare function getMediaElementSourceNode(context: AudioContext, target: MediaElementSourceTarget, options?: MediaElementSourceOptions): Effect.Effect<MediaElementAudioSourceNode, AudioPlaybackError>;
152
+ export declare const PCM_CAPTURE_PROCESSOR_NAME: "avoid-pcm-capture";
153
+ export declare const PCM_CAPTURE_DEFAULT_CHUNK_FRAMES = 2048;
154
+ type LoadPcmCaptureWorkletOptions = Omit<LoadAudioWorkletOptions, "processorName">;
155
+ interface PcmCaptureOptions {
156
+ /** Rolling window length in seconds (default 12 s, the Shazam maximum). */
157
+ readonly maxSeconds?: number;
158
+ /** Frames per worklet message (default 2048, clamped to `[128, 16384]`). */
159
+ readonly chunkFrames?: number;
160
+ readonly workletOptions?: LoadPcmCaptureWorkletOptions;
161
+ /** Raw mono chunk observer, called after the chunk is buffered. */
162
+ readonly onChunk?: (chunk: Float32Array) => void;
163
+ }
164
+ interface PcmCapture {
165
+ readonly node: AudioWorkletNode;
166
+ /** Sample rate of captured frames (`context.sampleRate`). */
167
+ readonly sampleRate: number;
168
+ readonly capacitySeconds: number;
169
+ readonly isActive: () => boolean;
170
+ readonly bufferedSeconds: () => number;
171
+ /** Copies the most recent `seconds` of mono PCM (default: whole window). */
172
+ readonly snapshot: (seconds?: number) => Float32Array;
173
+ /** Mono 16 kHz PCM16LE bytes ready for `generateShazamSignature`. */
174
+ readonly toShazamPcm: (seconds?: number) => Uint8Array;
175
+ /** Fingerprints the most recent `seconds` via `@avoid.quest/audio/recognize`. */
176
+ readonly fingerprint: (seconds?: number) => Effect.Effect<ShazamSignatureResult, AudioDecodeError>;
177
+ readonly clear: () => void;
178
+ }
179
+ /** Loads the standalone `@avoid.quest/audio/worklets/pcm-capture` module. */
180
+ export declare function loadPcmCaptureWorklet(context: BaseAudioContext, options?: LoadPcmCaptureWorkletOptions): Effect.Effect<void, AudioUnsupportedError | AudioWorkletError>;
215
181
  /**
216
- * Creates a `Scope`-managed media/HLS playback engine supporting both
217
- * `HTMLAudioElement` and `HTMLVideoElement` with lazy dynamic `import("hls.js")`,
218
- * Safari native HLS detection, speed `0.5–2.0` + `preservesPitch`, URL renewal
219
- * reload, media-ready timeout & stall watchdog, and Effect `Schedule` stall recovery.
182
+ * Passively taps any `AudioNode` (e.g. from `getMediaElementSourceNode` or
183
+ * `acquireInputCapture`) into a rolling mono PCM window via the allocation-free
184
+ * `pcm-capture` AudioWorklet, so live audio can be fingerprinted with
185
+ * `capture.fingerprint()`. Fully torn down when the owning `Scope` closes.
220
186
  */
221
- export declare function createMediaEngine(options: MediaEngineOptions): Effect.Effect<MediaEngine, never, Scope.Scope>;
187
+ export declare function acquirePcmCapture(context: BaseAudioContext, source: AudioNode, options?: PcmCaptureOptions): Effect.Effect<PcmCapture, AudioCaptureError | AudioUnsupportedError | AudioWorkletError, Scope.Scope>;
222
188
  export declare const SILENT_WAV_SAMPLE_RATE = 8000;
223
189
  export declare const SILENT_WAV_DURATION_SECONDS = 10;
224
190
  export declare const SILENT_WAV_HEADER_BYTES = 44;
225
- /**
226
- * Sanitizes metadata strings for Bluetooth AVRCP car/headphone displays:
227
- * strips diacritics via NFKD, maps typographic punctuation to plain ASCII,
228
- * removes non-printable/non-ASCII chars, collapses whitespace, and falls back
229
- * to `fallback` (default `"Radio"`).
230
- */
231
191
  export declare function sanitizeForBluetooth(input: string | null | undefined, fallback?: string): string;
232
- /**
233
- * Generates an all-zero mono 16-bit PCM RIFF/WAVE binary buffer.
234
- * Defaults to Couch's exact 10 s @ 8 kHz keep-alive WAV (160,044 bytes total),
235
- * ensuring Chromium treats the element as real media (> 5 s) for OS Now Playing / MPRIS.
236
- */
237
192
  export declare function createSilentWavBytes(durationSeconds?: number, sampleRate?: number): Uint8Array;
238
193
  export declare function createSilentWavBlob(durationSeconds?: number, sampleRate?: number): Blob;
239
194
  interface MediaSessionMetadataInput {
@@ -273,11 +228,6 @@ interface MediaSessionController {
273
228
  readonly stopKeepAlive: () => void;
274
229
  readonly dispose: () => void;
275
230
  }
276
- /**
277
- * Merged MediaSession controller combining Radio's Bluetooth AVRCP sanitizer
278
- * and Couch's 10 s silent WAV keep-alive element (`loop: true, volume: 0`, unmuted)
279
- * with inert transport guards for live streams.
280
- */
281
231
  export declare function createMediaSessionController(options?: MediaSessionControllerOptions): Effect.Effect<MediaSessionController, never, Scope.Scope>;
282
232
  export declare const SAMPLE_MIME_TYPES: {
283
233
  readonly mp3: "audio/mpeg";
@@ -341,9 +291,5 @@ interface BufferSampler {
341
291
  readonly stopAll: () => void;
342
292
  readonly dispose: () => void;
343
293
  }
344
- /**
345
- * Creates a Web Audio buffer/slice `Sampler` (`AudioBufferSourceNode -> voiceGain -> masterGain -> destination`).
346
- * Supports Cwavasape random-slice playback, one-shot envelope triggering, and batched loading.
347
- */
348
294
  export declare function createSampler(context: BaseAudioContext, options?: SamplerOptions): BufferSampler;
349
- export type { ActiveSliceHandle, AudioContextHandle, AudioContextLayerOptions, AudioContextOptionsInput, AudioContextSnapshot, BufferSampler, ChannelSelection, DeviceCaptureOptions, DisplayAudioOptions, LiveInputCapture, MediaEngine, MediaEngineLoadOptions, MediaEngineOptions, MediaEngineSnapshot, MediaSessionController, MediaSessionControllerOptions, MediaSessionHandlers, MediaSessionMetadataInput, RandomSliceOptions, SampleBatchLoadResult, SampleLoadEntry, SamplerOptions, SlicePlaybackOptions, StallRecoveryConfig };
295
+ export type { ActiveSliceHandle, AudioContextHandle, AudioContextLayerOptions, AudioContextOptionsInput, AudioContextSnapshot, BufferSampler, ChannelSelection, DeviceCaptureOptions, DisplayAudioOptions, LiveInputCapture, LoadPcmCaptureWorkletOptions, MediaElementSourceOptions, MediaElementSourceTarget, MediaEngine, MediaEngineLoadOptions, MediaEngineOptions, MediaEngineSnapshot, MediaSessionController, MediaSessionControllerOptions, MediaSessionHandlers, MediaSessionMetadataInput, PcmCapture, PcmCaptureOptions, RandomSliceOptions, SampleBatchLoadResult, SampleLoadEntry, SamplerOptions, SlicePlaybackOptions, StallRecoveryConfig };