@avoid.quest/audio 0.1.0 → 0.1.1-beta.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 (42) hide show
  1. package/README.md +32 -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 +63 -115
  15. package/dist/playback/index.js +906 -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 +18 -4
  41. package/types/hls-unavailable.d.ts +4 -0
  42. 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";
3
- import Hls, { HlsConfig } from "hls.js";
2
+ import { d as AudioWorkletError, n as AudioDecodeError, o as AudioPlaybackError, t as AudioCaptureError, u as AudioUnsupportedError } from "../errors-ChTQFwuZ.js";
3
+ import Hls, { HlsConfig } from "#hls-types";
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;
@@ -130,15 +75,12 @@ interface StallRecoveryConfig {
130
75
  readonly maxAttempts?: number;
131
76
  }
132
77
  interface MediaEngineLoadOptions {
78
+ /** Choose playback for URLs whose pathname does not identify their format. */
79
+ readonly protocol?: "hls" | "progressive";
133
80
  readonly startPositionSeconds?: number;
134
81
  readonly allowNativeHls?: boolean;
135
82
  readonly hlsConfig?: Partial<HlsConfig>;
136
83
  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
84
  readonly waitForReady?: boolean;
143
85
  readonly readyTimeoutMs?: number;
144
86
  }
@@ -182,58 +124,73 @@ interface MediaEngine {
182
124
  readonly getSnapshot: () => MediaEngineSnapshot;
183
125
  readonly dispose: () => Effect.Effect<void>;
184
126
  }
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
- */
127
+ export declare const clampPlaybackRate: (rate: number) => number;
192
128
  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
129
  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
- */
130
+ export declare const isWebKitBrowser: (ua?: string | undefined) => boolean;
205
131
  export declare function shouldUseNativeHls(element: Pick<HTMLMediaElement, "canPlayType">, allowNativeHls?: boolean, userAgent?: string): boolean;
132
+ export declare const computeStallBackoffMs: (attempt: number, base?: number, max?: number) => number;
133
+ export declare function createStallRecoverySchedule(config?: StallRecoveryConfig): Schedule.Schedule<number>;
134
+ export declare function createMediaEngine(options: MediaEngineOptions): Effect.Effect<MediaEngine, never, Scope.Scope>;
135
+ interface MediaElementSourceOptions {
136
+ /**
137
+ * Route the source to `context.destination` (default `true`). A captured
138
+ * element is only audible through the Web Audio graph, so disable this only
139
+ * when you route the node yourself; `false` also removes an edge created by
140
+ * an earlier call.
141
+ */
142
+ readonly connectToDestination?: boolean;
143
+ }
144
+ /** A raw media element or anything exposing one, such as a `MediaEngine`. */
145
+ type MediaElementSourceTarget = HTMLMediaElement | Pick<MediaEngine, "element">;
206
146
  /**
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.
147
+ * Returns the memoized `MediaElementAudioSourceNode` for a `MediaEngine` or
148
+ * media element (browsers allow only one per element), so live playback can
149
+ * feed `acquirePcmCapture`, meters, or effects. Requesting it for another
150
+ * `AudioContext` fails with `MEDIA_SOURCE_CONTEXT_MISMATCH`. Cross-origin
151
+ * media needs CORS + `crossOrigin: "anonymous"`, otherwise the graph is silent.
213
152
  */
214
- export declare function createStallRecoverySchedule(config?: StallRecoveryConfig): Schedule.Schedule<number>;
153
+ export declare function getMediaElementSourceNode(context: AudioContext, target: MediaElementSourceTarget, options?: MediaElementSourceOptions): Effect.Effect<MediaElementAudioSourceNode, AudioPlaybackError>;
154
+ export declare const PCM_CAPTURE_PROCESSOR_NAME: "avoid-pcm-capture";
155
+ export declare const PCM_CAPTURE_DEFAULT_CHUNK_FRAMES = 2048;
156
+ type LoadPcmCaptureWorkletOptions = Omit<LoadAudioWorkletOptions, "processorName">;
157
+ interface PcmCaptureOptions {
158
+ /** Rolling window length in seconds (default 12 s, the Shazam maximum). */
159
+ readonly maxSeconds?: number;
160
+ /** Frames per worklet message (default 2048, clamped to `[128, 16384]`). */
161
+ readonly chunkFrames?: number;
162
+ readonly workletOptions?: LoadPcmCaptureWorkletOptions;
163
+ /** Raw mono chunk observer, called after the chunk is buffered. */
164
+ readonly onChunk?: (chunk: Float32Array) => void;
165
+ }
166
+ interface PcmCapture {
167
+ readonly node: AudioWorkletNode;
168
+ /** Sample rate of captured frames (`context.sampleRate`). */
169
+ readonly sampleRate: number;
170
+ readonly capacitySeconds: number;
171
+ readonly isActive: () => boolean;
172
+ readonly bufferedSeconds: () => number;
173
+ /** Copies the most recent `seconds` of mono PCM (default: whole window). */
174
+ readonly snapshot: (seconds?: number) => Float32Array;
175
+ /** Mono 16 kHz PCM16LE bytes ready for `generateShazamSignature`. */
176
+ readonly toShazamPcm: (seconds?: number) => Uint8Array;
177
+ /** Fingerprints the most recent `seconds` via `@avoid.quest/audio/recognize`. */
178
+ readonly fingerprint: (seconds?: number) => Effect.Effect<ShazamSignatureResult, AudioDecodeError>;
179
+ readonly clear: () => void;
180
+ }
181
+ /** Loads the standalone `@avoid.quest/audio/worklets/pcm-capture` module. */
182
+ export declare function loadPcmCaptureWorklet(context: BaseAudioContext, options?: LoadPcmCaptureWorkletOptions): Effect.Effect<void, AudioUnsupportedError | AudioWorkletError>;
215
183
  /**
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.
184
+ * Passively taps any `AudioNode` (e.g. from `getMediaElementSourceNode` or
185
+ * `acquireInputCapture`) into a rolling mono PCM window via the allocation-free
186
+ * `pcm-capture` AudioWorklet, so live audio can be fingerprinted with
187
+ * `capture.fingerprint()`. Fully torn down when the owning `Scope` closes.
220
188
  */
221
- export declare function createMediaEngine(options: MediaEngineOptions): Effect.Effect<MediaEngine, never, Scope.Scope>;
189
+ export declare function acquirePcmCapture(context: BaseAudioContext, source: AudioNode, options?: PcmCaptureOptions): Effect.Effect<PcmCapture, AudioCaptureError | AudioUnsupportedError | AudioWorkletError, Scope.Scope>;
222
190
  export declare const SILENT_WAV_SAMPLE_RATE = 8000;
223
191
  export declare const SILENT_WAV_DURATION_SECONDS = 10;
224
192
  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
193
  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
194
  export declare function createSilentWavBytes(durationSeconds?: number, sampleRate?: number): Uint8Array;
238
195
  export declare function createSilentWavBlob(durationSeconds?: number, sampleRate?: number): Blob;
239
196
  interface MediaSessionMetadataInput {
@@ -273,11 +230,6 @@ interface MediaSessionController {
273
230
  readonly stopKeepAlive: () => void;
274
231
  readonly dispose: () => void;
275
232
  }
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
233
  export declare function createMediaSessionController(options?: MediaSessionControllerOptions): Effect.Effect<MediaSessionController, never, Scope.Scope>;
282
234
  export declare const SAMPLE_MIME_TYPES: {
283
235
  readonly mp3: "audio/mpeg";
@@ -341,9 +293,5 @@ interface BufferSampler {
341
293
  readonly stopAll: () => void;
342
294
  readonly dispose: () => void;
343
295
  }
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
296
  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 };
297
+ 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 };