@puresignal/fetch-stream-audio 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Chris
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,190 @@
1
+ <img clear="both" align="left" width="200px" src="https://raw.githubusercontent.com/AnthumChris/fetch-stream-audio/1ef61f06d4a9210492cc475985e7c73904c0b110/src/favicon.ico" /><br>
2
+
3
+ # Demo
4
+
5
+ https://fetch-stream-audio.anthum.com/
6
+
7
+ <br><br>
8
+
9
+ # Background
10
+
11
+ This repo provides low-latency web audio playback examples for programatically decoding audio in chunks with the Web Audio API and the new Fetch &amp; Streams APIs. Traditionally, [`decodeAudioData()`](https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData) is used for programmatic decoding but requires the complete file to be downloaded, and chunk-based decoding is not supported. These Streams examples will show how to sidestep that limitation. Media Source Extensions could also be used to play audio and that example may be integrated here one day.
12
+
13
+ The examples demonstrate:
14
+
15
+ 1. **Opus Streaming** [`opus-stream-decoder`](https://github.com/AnthumChris/opus-stream-decoder) is used to decode an [Opus](http://opus-codec.org/) file in a Web Worker with WebAssembly. This simulates a real-world use case of streaming compressed audio over the web with the Web Audio API. (MP3 is old and outdated for those of us who grew up with WinPlay3. Opus is the new gold standard). This example is ideal because it allows for small, high-quality files with Opus.
16
+ 1. **WAV Streaming** A WAV file is streamed and decoded by a Web Worker. Chunks are scheduled into a read buffer before sending to encoder to ensure decoder receives complete, decodable chunks. JavaScript (not WebAssembly) is used for decoding. This example requires a much larger file.
17
+
18
+ # Opus Playback Tests
19
+
20
+ Opus file playback can be tested at throttled download speeds and varkous encoding/bitrate qualities ([Issue #14](https://github.com/AnthumChris/fetch-stream-audio/issues/14) will add to UI):
21
+
22
+ [opusBitrate = 96; throttle = nolimit](https://fetch-stream-audio.anthum.com/#opusBitrate=96;throttle=nolimit)<br>
23
+ [opusBitrate = 96; throttle = 1mbps](https://fetch-stream-audio.anthum.com/#opusBitrate=96;throttle=1mbps)<br>
24
+ [opusBitrate = 96; throttle = 104kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=96;throttle=104kbps)<br>
25
+ [opusBitrate = 96; throttle = 100kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=96;throttle=100kbps)<br>
26
+ [opusBitrate = 64; throttle = 72kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=64;throttle=72kbps)<br>
27
+ [opusBitrate = 60; throttle = 64kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=60;throttle=64kbps)<br>
28
+ [opusBitrate = 53; throttle = 56kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=53;throttle=56kbps)<br>
29
+ [opusBitrate = 32; throttle = 40kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=32;throttle=40kbps)<br>
30
+ [opusBitrate = 28; throttle = 32kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=28;throttle=32kbps)<br>
31
+ [opusBitrate = 12; throttle = 16kbps](https://fetch-stream-audio.anthum.com/#opusBitrate=12;throttle=16kbps)
32
+
33
+ # Back-End Nginx Server
34
+
35
+ To use the config files, create symblink `fetch-stream-audio`, e.g.:
36
+
37
+ ```
38
+ $ ln -s [LOCATION_TO_THIS_REPO]/.conf/nginx /etc/nginx/fetch-stream-audio
39
+ ```
40
+
41
+ Then, include this repo's nginx config file into your `server {}` block, e.g.:
42
+
43
+ ```nginx
44
+ server {
45
+ ...
46
+
47
+ disable_symlinks off;
48
+ include fetch-stream-audio/include-server.conf;
49
+ }
50
+ ```
51
+
52
+ ## Throttled Bandwidth Endpoints
53
+
54
+ All `/audio/*` URIs are configured to intentionally limit download speeds and control response packet sizes for testing the decoding behavior (defined in [include-server.conf](.conf/nginx/include-server.conf)). For example:
55
+
56
+ https://fetch-stream-audio.anthum.com/nolimit/opus/decode-test-64kbit.opus<br>
57
+ https://fetch-stream-audio.anthum.com/10mbps/opus/decode-test-64kbit.opus<br>
58
+ https://fetch-stream-audio.anthum.com/1.5mbps/opus/decode-test-64kbit.opus<br>
59
+ https://fetch-stream-audio.anthum.com/512kbps/opus/decode-test-64kbit.opus
60
+
61
+ <details>
62
+ <summary>All Throttled Endpoints</summary>
63
+
64
+ | Speed | Example URL |
65
+ | ----------- | ----------- |
66
+ | 16 kbps | https://fetch-stream-audio.anthum.com/16kbps/opus/decode-test-64kbit.opus |
67
+ | 24 kbps | https://fetch-stream-audio.anthum.com/24kbps/opus/decode-test-64kbit.opus |
68
+ | 32 kbps | https://fetch-stream-audio.anthum.com/32kbps/opus/decode-test-64kbit.opus |
69
+ | 40 kbps | https://fetch-stream-audio.anthum.com/32kbps/opus/decode-test-40kbit.opus |
70
+ | 56 kbps | https://fetch-stream-audio.anthum.com/32kbps/opus/decode-test-56kbit.opus |
71
+ | 64 kbps | https://fetch-stream-audio.anthum.com/64kbps/opus/decode-test-64kbit.opus |
72
+ | 72 kbps | https://fetch-stream-audio.anthum.com/72kbps/opus/decode-test-64kbit.opus |
73
+ | 80 kbps | https://fetch-stream-audio.anthum.com/80kbps/opus/decode-test-64kbit.opus |
74
+ | 88 kbps | https://fetch-stream-audio.anthum.com/88kbps/opus/decode-test-64kbit.opus |
75
+ | 96 kbps | https://fetch-stream-audio.anthum.com/96kbps/opus/decode-test-64kbit.opus |
76
+ | 100 kbps | https://fetch-stream-audio.anthum.com/100kbps/opus/decode-test-64kbit.opus |
77
+ | 104 kbps | https://fetch-stream-audio.anthum.com/104kbps/opus/decode-test-64kbit.opus |
78
+ | 112 kbps | https://fetch-stream-audio.anthum.com/112kbps/opus/decode-test-64kbit.opus |
79
+ | 120 kbps | https://fetch-stream-audio.anthum.com/120kbps/opus/decode-test-64kbit.opus |
80
+ | 128 kbps | https://fetch-stream-audio.anthum.com/128kbps/opus/decode-test-64kbit.opus |
81
+ | 160 kbps | https://fetch-stream-audio.anthum.com/160kbps/opus/decode-test-64kbit.opus |
82
+ | 192 kbps | https://fetch-stream-audio.anthum.com/192kbps/opus/decode-test-64kbit.opus |
83
+ | 256 kbps | https://fetch-stream-audio.anthum.com/256kbps/opus/decode-test-64kbit.opus |
84
+ | 384 kbps | https://fetch-stream-audio.anthum.com/384kbps/opus/decode-test-64kbit.opus |
85
+ | 512 kbps | https://fetch-stream-audio.anthum.com/512kbps/opus/decode-test-64kbit.opus |
86
+ | 768 kbps | https://fetch-stream-audio.anthum.com/768kbps/opus/decode-test-64kbit.opus |
87
+ | 1 mbps | https://fetch-stream-audio.anthum.com/1mbps/opus/decode-test-64kbit.opus |
88
+ | 4 mbps | https://fetch-stream-audio.anthum.com/4mbps/opus/decode-test-64kbit.opus |
89
+ | 5 mbps | https://fetch-stream-audio.anthum.com/5mbps/opus/decode-test-64kbit.opus |
90
+ | 2 mbps | https://fetch-stream-audio.anthum.com/2mbps/opus/decode-test-64kbit.opus |
91
+ | 3 mbps | https://fetch-stream-audio.anthum.com/3mbps/opus/decode-test-64kbit.opus |
92
+ | 4 mbps | https://fetch-stream-audio.anthum.com/4mbps/opus/decode-test-64kbit.opus |
93
+ | 5 mbps | https://fetch-stream-audio.anthum.com/5mbps/opus/decode-test-64kbit.opus |
94
+ | 6 mbps | https://fetch-stream-audio.anthum.com/6mbps/opus/decode-test-64kbit.opus |
95
+ | 7 mbps | https://fetch-stream-audio.anthum.com/7mbps/opus/decode-test-64kbit.opus |
96
+ | 8 mbps | https://fetch-stream-audio.anthum.com/8mbps/opus/decode-test-64kbit.opus |
97
+ | 9 mbps | https://fetch-stream-audio.anthum.com/9mbps/opus/decode-test-64kbit.opus |
98
+ | 10 mbps | https://fetch-stream-audio.anthum.com/10mbps/opus/decode-test-64kbit.opus |
99
+ | nolimit | https://fetch-stream-audio.anthum.com/nolimit/opus/decode-test-64kbit.opus<br>https://fetch-stream-audio.anthum.com/audio/opus/decode-test-64kbit.opus |
100
+
101
+ </details>
102
+
103
+ # Fork Notice
104
+
105
+ This is a fork of [AnthumChris/fetch-stream-audio](https://github.com/anthumchris/fetch-stream-audio). The original project is a proof-of-concept demo. This fork packages the core audio streaming logic as a publishable npm module so it can be used as a library in other projects.
106
+
107
+ > [!WARNING]
108
+ > This npm package was generated with the help of [Claude Code](https://claude.ai/code) and has not been tested beyond surface-level verification that the demo works. It is **not production-ready**. Use at your own risk and expect rough edges.
109
+
110
+ # npm Package
111
+
112
+ This fork is published as `@puresignal/fetch-stream-audio` on npm. Install it in any project with a bundler (webpack 5, Vite, esbuild, Rollup):
113
+
114
+ ```bash
115
+ npm install @puresignal/fetch-stream-audio
116
+ ```
117
+
118
+ ## Usage
119
+
120
+ ```js
121
+ import { FetchStreamAudio } from '@puresignal/fetch-stream-audio';
122
+
123
+ const player = new FetchStreamAudio(
124
+ 'https://example.com/audio.opus',
125
+ 1024 * 2, // read buffer size in bytes
126
+ 'OPUS' // or 'PCM' for WAV
127
+ );
128
+
129
+ player.onUpdateState = ({ playState, latency, bytesRead, skips }) => {
130
+ console.log(playState, latency, skips);
131
+ };
132
+
133
+ player.start();
134
+ // player.pause() / player.resume() / player.close()
135
+ ```
136
+
137
+ The consumer's bundler sees the `new URL('./worker.js', import.meta.url)` pattern inside the package and automatically copies the worker files into the build output with correct URLs — this is the W3C-standard approach supported by webpack 5, Vite, esbuild, and Rollup.
138
+
139
+ ### Script-tag / CDN (no bundler)
140
+
141
+ If you are not using a bundler, you must manually host the worker and WASM files and pass worker URLs explicitly:
142
+
143
+ ```js
144
+ const player = new FetchStreamAudio(url, 5120, 'OPUS', {
145
+ opusWorkerUrl: '/assets/worker-decoder-opus.js'
146
+ });
147
+ ```
148
+
149
+ ## Published Files
150
+
151
+ The npm package includes:
152
+
153
+ | File | Description |
154
+ | ---- | ----------- |
155
+ | `dist/fetch-stream-audio.mjs` | ESM library entry |
156
+ | `dist/fetch-stream-audio.cjs` | CJS library entry |
157
+ | `dist/worker-decoder-opus.js` | Bundled Opus decoder worker |
158
+ | `dist/worker-decoder-wav.js` | Bundled WAV decoder worker |
159
+ | `dist/opus-stream-decoder.wasm` | Opus WebAssembly binary |
160
+
161
+ # Development & Building
162
+
163
+ You'll need [Yarn](https://yarnpkg.com/getting-started) or [NodeJS](https://nodejs.org/en/) installed. [`app.js`](https://github.com/AnthumChris/fetch-stream-audio/blob/master/src/js/app.js) is the entry point for the demo app.
164
+
165
+ ```bash
166
+ # clone repo and install dependencies
167
+ $ git clone https://github.com/AnthumChris/fetch-stream-audio
168
+ $ cd fetch-stream-audio
169
+ $ yarn install
170
+ ```
171
+
172
+ ```bash
173
+ # run the development server with HMR
174
+ $ yarn dev
175
+ ```
176
+
177
+ ```bash
178
+ # build everything (library + demo)
179
+ $ yarn build
180
+
181
+ # or build separately
182
+ $ yarn build:lib # library + workers → dist/
183
+ $ yarn build:demo # demo app → dist/demo/
184
+ ```
185
+
186
+
187
+
188
+ # Acknowledgements
189
+
190
+ Thanks to [@bjornm](https://github.com/bjornm) for pointing me to [@mohayonao](https://github.com/mohayonao)'s WAV decoder: https://github.com/mohayonao/wav-decoder
@@ -0,0 +1 @@
1
+ "use strict";var Z=Object.defineProperty;var g=(h,e,t)=>e in h?Z(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t;var r=(h,e,t)=>g(h,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var u=typeof document<"u"?document.currentScript:null;class m{constructor(e,t){r(this,"onRead");r(this,"onBufferFull");r(this,"request");r(this,"buffer");r(this,"bufferPos",0);r(this,"isRunning");r(this,"abortController");if(!(parseInt(t)>0))throw Error("readBufferSize not provided");this.request=e,this.buffer=new Uint8Array(t)}abort(){this.abortController&&this.abortController.abort(),this.request=null}async read(){return this.isRunning?console.warn("cannot start - read in progess."):(this.isRunning=!0,this._start().catch(e=>{if(e.name!=="AbortError")throw this.abort(),e}).finally(e=>this.isRunning=!1))}async _start(){this.abortController="AbortController"in window?new AbortController:null;const e=this.abortController?this.abortController.signal:null,t=await fetch(this.request,{signal:e});if(!t.ok)throw Error(t.status+" "+t.statusText);if(!t.body)throw Error('ReadableStream not yet supported in this browser - <a href="https://developer.mozilla.org/en-US/docs/Web/API/Body/body#Browser_Compatibility">browser compatibility</a>');const s=t.body.getReader(),l=t.headers.get("content-length"),n=l?parseInt(l,10):0;let d=0;const o=async()=>{const{value:a,done:i}=await s.read(),c=a?a.byteLength:0;if(d+=c,this.onRead&&this.onRead({bytes:a,totalRead:d,totalBytes:n,done:i}),setTimeout(b=>this._readIntoBuffer({value:a,done:i,request:this.request})),!i)return o()};return o()}_requestIsAborted({request:e}){return this.request!==e}_flushBuffer({end:e,done:t,request:s}){this._requestIsAborted({request:s})||this.onBufferFull({bytes:this.buffer.slice(0,e),done:t})}_readIntoBuffer({value:e,done:t,request:s}){if(this._requestIsAborted({request:s}))return;if(t){this._flushBuffer({end:this.bufferPos,done:t,request:s});return}const l=e,n=l.byteLength,d=this.buffer.byteLength;let o=0,a=this.bufferPos;for(;o<n;){const i=Math.min(d-a,n-o),c=o+i;this.buffer.set(l.subarray(o,c),a),o+=i,a+=i,a===d&&(a=0,this._flushBuffer({end:1/0,done:t,request:s}))}this.bufferPos=a}}class C{constructor(e,t,s,l={}){r(this,"_worker");r(this,"_url");r(this,"_readBufferSize");r(this,"_sessionId");r(this,"_audioCtx");r(this,"_reader");r(this,"_audioSrcNodes");r(this,"_totalTimeScheduled");r(this,"_playStartedAt");r(this,"_abCreated");r(this,"_abEnded");r(this,"_skips");const{wavWorkerUrl:n,opusWorkerUrl:d}=l;switch(s){case"PCM":this._worker=new Worker(n||new URL("data:text/javascript;base64,aW1wb3J0IE1vaGF5b25hb1dhdkRlY29kZXIgZnJvbSAnLi9Nb2hheW9uYW9XYXZEZWNvZGVyLmpzJzsKCmNvbnN0IGRlY29kZXIgPSBuZXcgTW9oYXlvbmFvV2F2RGVjb2RlcigpOwpzZWxmLm9ubWVzc2FnZSA9IGV2ZW50ID0+IHsKICBjb25zdCB7IGRlY29kZSwgc2Vzc2lvbklkIH0gPSBldmVudC5kYXRhOwogIGlmIChkZWNvZGUpIHsKICAgIGNvbnN0IGRlY29kZWQgPSBkZWNvZGVyLmRlY29kZUNodW5rU3luYyhldmVudC5kYXRhLmRlY29kZSk7CiAgICBzZWxmLnBvc3RNZXNzYWdlKAogICAgICB7IGRlY29kZWQsIHNlc3Npb25JZCB9LAogICAgICBkZWNvZGVkLmNoYW5uZWxEYXRhLm1hcCgoeyBidWZmZXIgfSkgPT4gYnVmZmVyKQogICAgKTsKICB9Cn07Cg==",typeof document>"u"?require("url").pathToFileURL(__filename).href:u&&u.tagName.toUpperCase()==="SCRIPT"&&u.src||new URL("fetch-stream-audio.cjs",document.baseURI).href),{type:"module"});break;case"OPUS":this._worker=new Worker(d||new URL("data:text/javascript;base64,aW1wb3J0IE9wdXNTdHJlYW1EZWNvZGVyRmFjdG9yeSBmcm9tICdvcHVzLXN0cmVhbS1kZWNvZGVyL2Rpc3Qv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toUpperCase()==="SCRIPT"&&u.src||new URL("fetch-stream-audio.cjs",document.baseURI).href),{type:"module"});break;default:throw Error("Unsupported decoderName: "+s)}this._worker.onerror=o=>{this._updateState({error:o.message})},this._worker.onmessage=this._onWorkerMessage.bind(this),this._url=e,this._readBufferSize=t,this._reset()}_reset(){this._sessionId&&performance.clearMarks(this._downloadMarkKey),this._sessionId=null,this._audioCtx=null,this._reader=null,this._audioSrcNodes=[],this._totalTimeScheduled=0,this._playStartedAt=0,this._abCreated=0,this._abEnded=0,this._skips=0}close(){for(let e of this._audioSrcNodes)e.onended=null,e.disconnect(this._audioCtx.destination),e.stop();this._reader&&this._reader.abort(),this._audioCtx&&(this._audioCtx.suspend(),this._audioCtx.close()),this._reset()}start(){this._sessionId=performance.now(),performance.mark(this._downloadMarkKey),this._audioCtx=new(window.AudioContext||window.webkitAudioContext)({latencyHint:"interactive"});const e=new m(new Request(this._url),this._readBufferSize);e.onRead=this._downloadProgress.bind(this),e.onBufferFull=this._decode.bind(this),e.read().catch(t=>{this._updateState({error:t.toString()})}),this._reader=e,this.resume()}pause(){this._audioCtx.suspend().then(e=>this._updateState({playState:"paused"}))}resume(){this._audioCtx.resume().then(e=>this._updateState({playState:"playing"}))}_updateState(e){const t=this._abCreated?{abCreated:this._abCreated,abEnded:this._abEnded,abRemaining:this._abCreated-this._abEnded,skips:this._skips}:{},s=Object.assign(t,e);this.onUpdateState&&this.onUpdateState(s)}_decode({bytes:e,done:t}){const s=this._sessionId;this._worker.postMessage({decode:e.buffer,sessionId:s},[e.buffer])}_onWorkerMessage(e){const{decoded:t,sessionId:s}=e.data;if(t.channelData){if(!(this._sessionId&&this._sessionId===s)){console.log("race condition detected for closed session");return}this._schedulePlayback(t)}}_downloadProgress({bytes:e,totalRead:t,totalBytes:s,done:l}){this._updateState({bytesRead:t,bytesTotal:s,dlRate:t*8/(performance.now()-this._getDownloadStartTime())})}get _downloadMarkKey(){return`download-start-${this._sessionId}`}_getDownloadStartTime(){return performance.getEntriesByName(this._downloadMarkKey)[0].startTime}_schedulePlayback({channelData:e,length:t,numberOfChannels:s,sampleRate:l}){const n=this._audioCtx.createBufferSource(),d=this._audioCtx.createBuffer(s,t,l);n.onended=()=>{this._audioSrcNodes.shift(),this._abEnded++,this._updateState()},this._abCreated++,this._updateState(),this._audioSrcNodes.push(n);for(let i=0;i<s;i++)if(d.copyToChannel)d.copyToChannel(e[i],i);else{let c=d.getChannelData(i);for(let b=0;b<e[i].byteLength;b++)c[b]=e[i][b]}let o=0;this._playStartedAt||(o=100/1e3,this._playStartedAt=this._audioCtx.currentTime+o,this._updateState({latency:performance.now()-this._getDownloadStartTime()+o*1e3})),n.buffer=d,n.connect(this._audioCtx.destination);const a=this._playStartedAt+this._totalTimeScheduled;this._audioCtx.currentTime>=a&&(this._skips++,this._updateState()),n.start(a),this._totalTimeScheduled+=d.duration}}class f extends C{}exports.FetchStreamAudio=f;
@@ -0,0 +1,188 @@
1
+ var b = Object.defineProperty;
2
+ var Z = (h, t, e) => t in h ? b(h, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : h[t] = e;
3
+ var r = (h, t, e) => Z(h, typeof t != "symbol" ? t + "" : t, e);
4
+ class g {
5
+ constructor(t, e) {
6
+ r(this, "onRead");
7
+ // callback on every read. useful for speed calcs
8
+ r(this, "onBufferFull");
9
+ // callback when buffer fills or read completes
10
+ r(this, "request");
11
+ // HTTP request we're reading
12
+ r(this, "buffer");
13
+ // buffer we're filling
14
+ r(this, "bufferPos", 0);
15
+ // last filled position in buffer
16
+ r(this, "isRunning");
17
+ r(this, "abortController");
18
+ if (!(parseInt(e) > 0))
19
+ throw Error("readBufferSize not provided");
20
+ this.request = t, this.buffer = new Uint8Array(e);
21
+ }
22
+ abort() {
23
+ this.abortController && this.abortController.abort(), this.request = null;
24
+ }
25
+ async read() {
26
+ return this.isRunning ? console.warn("cannot start - read in progess.") : (this.isRunning = !0, this._start().catch((t) => {
27
+ if (t.name !== "AbortError")
28
+ throw this.abort(), t;
29
+ }).finally((t) => this.isRunning = !1));
30
+ }
31
+ async _start() {
32
+ this.abortController = "AbortController" in window ? new AbortController() : null;
33
+ const t = this.abortController ? this.abortController.signal : null, e = await fetch(this.request, { signal: t });
34
+ if (!e.ok) throw Error(e.status + " " + e.statusText);
35
+ if (!e.body) throw Error('ReadableStream not yet supported in this browser - <a href="https://developer.mozilla.org/en-US/docs/Web/API/Body/body#Browser_Compatibility">browser compatibility</a>');
36
+ const s = e.body.getReader(), l = e.headers.get("content-length"), n = l ? parseInt(l, 10) : 0;
37
+ let d = 0;
38
+ const o = async () => {
39
+ const { value: a, done: i } = await s.read(), u = a ? a.byteLength : 0;
40
+ if (d += u, this.onRead && this.onRead({ bytes: a, totalRead: d, totalBytes: n, done: i }), setTimeout((c) => this._readIntoBuffer({ value: a, done: i, request: this.request })), !i)
41
+ return o();
42
+ };
43
+ return o();
44
+ }
45
+ _requestIsAborted({ request: t }) {
46
+ return this.request !== t;
47
+ }
48
+ _flushBuffer({ end: t, done: e, request: s }) {
49
+ this._requestIsAborted({ request: s }) || this.onBufferFull({ bytes: this.buffer.slice(0, t), done: e });
50
+ }
51
+ /* read value into buffer and call onBufferFull when reached */
52
+ _readIntoBuffer({ value: t, done: e, request: s }) {
53
+ if (this._requestIsAborted({ request: s }))
54
+ return;
55
+ if (e) {
56
+ this._flushBuffer({ end: this.bufferPos, done: e, request: s });
57
+ return;
58
+ }
59
+ const l = t, n = l.byteLength, d = this.buffer.byteLength;
60
+ let o = 0, a = this.bufferPos;
61
+ for (; o < n; ) {
62
+ const i = Math.min(d - a, n - o), u = o + i;
63
+ this.buffer.set(l.subarray(o, u), a), o += i, a += i, a === d && (a = 0, this._flushBuffer({ end: 1 / 0, done: e, request: s }));
64
+ }
65
+ this.bufferPos = a;
66
+ }
67
+ }
68
+ class C {
69
+ // audio skipping caused by slow download
70
+ constructor(t, e, s, l = {}) {
71
+ // these shouldn't change once set
72
+ r(this, "_worker");
73
+ r(this, "_url");
74
+ r(this, "_readBufferSize");
75
+ // these are reset
76
+ r(this, "_sessionId");
77
+ // used to prevent race conditions between cancel/starts
78
+ r(this, "_audioCtx");
79
+ // Created/Closed when this player starts/stops audio
80
+ r(this, "_reader");
81
+ r(this, "_audioSrcNodes");
82
+ // Used to fix Safari Bug https://github.com/AnthumChris/fetch-stream-audio/issues/1
83
+ r(this, "_totalTimeScheduled");
84
+ // time scheduled of all AudioBuffers
85
+ r(this, "_playStartedAt");
86
+ // audioContext.currentTime of first sched
87
+ r(this, "_abCreated");
88
+ // AudioBuffers created
89
+ r(this, "_abEnded");
90
+ // AudioBuffers played/ended
91
+ r(this, "_skips");
92
+ const { wavWorkerUrl: n, opusWorkerUrl: d } = l;
93
+ switch (s) {
94
+ case "PCM":
95
+ this._worker = new Worker(n || new URL("data:text/javascript;base64,aW1wb3J0IE1vaGF5b25hb1dhdkRlY29kZXIgZnJvbSAnLi9Nb2hheW9uYW9XYXZEZWNvZGVyLmpzJzsKCmNvbnN0IGRlY29kZXIgPSBuZXcgTW9oYXlvbmFvV2F2RGVjb2RlcigpOwpzZWxmLm9ubWVzc2FnZSA9IGV2ZW50ID0+IHsKICBjb25zdCB7IGRlY29kZSwgc2Vzc2lvbklkIH0gPSBldmVudC5kYXRhOwogIGlmIChkZWNvZGUpIHsKICAgIGNvbnN0IGRlY29kZWQgPSBkZWNvZGVyLmRlY29kZUNodW5rU3luYyhldmVudC5kYXRhLmRlY29kZSk7CiAgICBzZWxmLnBvc3RNZXNzYWdlKAogICAgICB7IGRlY29kZWQsIHNlc3Npb25JZCB9LAogICAgICBkZWNvZGVkLmNoYW5uZWxEYXRhLm1hcCgoeyBidWZmZXIgfSkgPT4gYnVmZmVyKQogICAgKTsKICB9Cn07Cg==", import.meta.url), { type: "module" });
96
+ break;
97
+ case "OPUS":
98
+ this._worker = new Worker(d || new URL("data:text/javascript;base64,aW1wb3J0IE9wdXNTdHJlYW1EZWNvZGVyRmFjdG9yeSBmcm9tICdvcHVzLXN0cmVhbS1kZWNvZGVyL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:
101
+ throw Error("Unsupported decoderName: " + s);
102
+ }
103
+ this._worker.onerror = (o) => {
104
+ this._updateState({ error: o.message });
105
+ }, this._worker.onmessage = this._onWorkerMessage.bind(this), this._url = t, this._readBufferSize = e, this._reset();
106
+ }
107
+ _reset() {
108
+ this._sessionId && performance.clearMarks(this._downloadMarkKey), this._sessionId = null, this._audioCtx = null, this._reader = null, this._audioSrcNodes = [], this._totalTimeScheduled = 0, this._playStartedAt = 0, this._abCreated = 0, this._abEnded = 0, this._skips = 0;
109
+ }
110
+ close() {
111
+ for (let t of this._audioSrcNodes)
112
+ t.onended = null, t.disconnect(this._audioCtx.destination), t.stop();
113
+ this._reader && this._reader.abort(), this._audioCtx && (this._audioCtx.suspend(), this._audioCtx.close()), this._reset();
114
+ }
115
+ start() {
116
+ this._sessionId = performance.now(), performance.mark(this._downloadMarkKey), this._audioCtx = new (window.AudioContext || window.webkitAudioContext)({ latencyHint: "interactive" });
117
+ const t = new g(new Request(this._url), this._readBufferSize);
118
+ t.onRead = this._downloadProgress.bind(this), t.onBufferFull = this._decode.bind(this), t.read().catch((e) => {
119
+ this._updateState({ error: e.toString() });
120
+ }), this._reader = t, this.resume();
121
+ }
122
+ pause() {
123
+ this._audioCtx.suspend().then((t) => this._updateState({ playState: "paused" }));
124
+ }
125
+ resume() {
126
+ this._audioCtx.resume().then((t) => this._updateState({ playState: "playing" }));
127
+ }
128
+ _updateState(t) {
129
+ const e = this._abCreated ? {
130
+ abCreated: this._abCreated,
131
+ abEnded: this._abEnded,
132
+ abRemaining: this._abCreated - this._abEnded,
133
+ skips: this._skips
134
+ } : {}, s = Object.assign(e, t);
135
+ this.onUpdateState && this.onUpdateState(s);
136
+ }
137
+ _decode({ bytes: t, done: e }) {
138
+ const s = this._sessionId;
139
+ this._worker.postMessage({ decode: t.buffer, sessionId: s }, [t.buffer]);
140
+ }
141
+ // prevent race condition by checking sessionId
142
+ _onWorkerMessage(t) {
143
+ const { decoded: e, sessionId: s } = t.data;
144
+ if (e.channelData) {
145
+ if (!(this._sessionId && this._sessionId === s)) {
146
+ console.log("race condition detected for closed session");
147
+ return;
148
+ }
149
+ this._schedulePlayback(e);
150
+ }
151
+ }
152
+ _downloadProgress({ bytes: t, totalRead: e, totalBytes: s, done: l }) {
153
+ this._updateState({
154
+ bytesRead: e,
155
+ bytesTotal: s,
156
+ dlRate: e * 8 / (performance.now() - this._getDownloadStartTime())
157
+ });
158
+ }
159
+ get _downloadMarkKey() {
160
+ return `download-start-${this._sessionId}`;
161
+ }
162
+ _getDownloadStartTime() {
163
+ return performance.getEntriesByName(this._downloadMarkKey)[0].startTime;
164
+ }
165
+ _schedulePlayback({ channelData: t, length: e, numberOfChannels: s, sampleRate: l }) {
166
+ const n = this._audioCtx.createBufferSource(), d = this._audioCtx.createBuffer(s, e, l);
167
+ n.onended = () => {
168
+ this._audioSrcNodes.shift(), this._abEnded++, this._updateState();
169
+ }, this._abCreated++, this._updateState(), this._audioSrcNodes.push(n);
170
+ for (let i = 0; i < s; i++)
171
+ if (d.copyToChannel)
172
+ d.copyToChannel(t[i], i);
173
+ else {
174
+ let u = d.getChannelData(i);
175
+ for (let c = 0; c < t[i].byteLength; c++)
176
+ u[c] = t[i][c];
177
+ }
178
+ let o = 0;
179
+ this._playStartedAt || (o = 100 / 1e3, this._playStartedAt = this._audioCtx.currentTime + o, this._updateState({ latency: performance.now() - this._getDownloadStartTime() + o * 1e3 })), n.buffer = d, n.connect(this._audioCtx.destination);
180
+ const a = this._playStartedAt + this._totalTimeScheduled;
181
+ this._audioCtx.currentTime >= a && (this._skips++, this._updateState()), n.start(a), this._totalTimeScheduled += d.duration;
182
+ }
183
+ }
184
+ class m extends C {
185
+ }
186
+ export {
187
+ m as FetchStreamAudio
188
+ };
Binary file
@@ -0,0 +1 @@
1
+ var en=Object.defineProperty;var nn=(c,s,n)=>s in c?en(c,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):c[s]=n;var w=(c,s,n)=>nn(c,typeof s!="symbol"?s+"":s,n);var rn=function(){var c=import.meta.url;return function(n){n=n||{};var n=typeof n<"u"?n:{};n.locateFile=function(e){return R?__dirname+"/"+e:e};var g={},v;for(v in n)n.hasOwnProperty(v)&&(g[v]=n[v]);var y=!1,p=!1,R=!1,L=!1,Q=!1;y=typeof window=="object",p=typeof importScripts=="function",L=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",R=L&&!y&&!p,Q=!y&&!R&&!p;var b="";function we(e){return n.locateFile?n.locateFile(e,b):b+e}var W,H,z,x;R?(b=__dirname+"/",W=function(r,t){return z||(z=require("fs")),x||(x=require("path")),r=x.normalize(r),z.readFileSync(r,t?null:"utf8")},H=function(r){var t=W(r,!0);return t.buffer||(t=new Uint8Array(t)),X(t.buffer),t},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(e){if(!(e instanceof Je))throw e}),process.on("unhandledRejection",A),n.inspect=function(){return"[Emscripten Module object]"}):Q?(typeof read<"u"&&(W=function(r){return read(r)}),H=function(r){var t;return typeof readbuffer=="function"?new Uint8Array(readbuffer(r)):(t=read(r,"binary"),X(typeof t=="object"),t)},typeof scriptArgs<"u"&&scriptArgs,typeof print<"u"&&(typeof console>"u"&&(console={}),console.log=print,console.warn=console.error=typeof printErr<"u"?printErr:print)):(y||p)&&(p?b=self.location.href:document.currentScript&&(b=document.currentScript.src),c&&(b=c),b.indexOf("blob:")!==0?b=b.substr(0,b.lastIndexOf("/")+1):b="",W=function(r){var t=new XMLHttpRequest;return t.open("GET",r,!1),t.send(null),t.responseText},p&&(H=function(r){var t=new XMLHttpRequest;return t.open("GET",r,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}));var ee=n.print||console.log.bind(console),O=n.printErr||console.warn.bind(console);for(v in g)g.hasOwnProperty(v)&&(n[v]=g[v]);g=null,n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.quit&&n.quit;var k;n.wasmBinary&&(k=n.wasmBinary),n.noExitRuntime&&n.noExitRuntime,typeof WebAssembly!="object"&&O("no native wasm support detected");var q,Ee=new WebAssembly.Table({initial:7,maximum:7,element:"anyfunc"}),ne=!1;function X(e,r){e||A("Assertion failed: "+r)}function re(e){var r=n["_"+e];return X(r,"Cannot call unknown function "+e+", make sure it is exported"),r}function Re(e,r,t,l,f){var a={string:function(d){var F=0;if(d!=null&&d!==0){var G=(d.length<<2)+1;F=ye(G),Pe(d,F,G)}return F},array:function(d){var F=ye(d.length);return Se(d,F),F}};function i(d){return r==="string"?oe(d):r==="boolean"?!!d:d}var o=re(e),u=[],m=0;if(l)for(var _=0;_<l.length;_++){var D=a[t[_]];D?(m===0&&(m=$e()),u[_]=D(l[_])):u[_]=l[_]}var N=o.apply(null,u);return N=i(N),m!==0&&Ke(m),N}function E(e,r,t,l){t=t||[];var f=t.every(function(i){return i==="number"}),a=r!=="string";return a&&f&&!l?re(e):function(){return Re(e,r,t,arguments)}}var te=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function ie(e,r,t){for(var l=r+t,f=r;e[f]&&!(f>=l);)++f;if(f-r>16&&e.subarray&&te)return te.decode(e.subarray(r,f));for(var a="";r<f;){var i=e[r++];if(!(i&128)){a+=String.fromCharCode(i);continue}var o=e[r++]&63;if((i&224)==192){a+=String.fromCharCode((i&31)<<6|o);continue}var u=e[r++]&63;if((i&240)==224?i=(i&15)<<12|o<<6|u:i=(i&7)<<18|o<<12|u<<6|e[r++]&63,i<65536)a+=String.fromCharCode(i);else{var m=i-65536;a+=String.fromCharCode(55296|m>>10,56320|m&1023)}}return a}function oe(e,r){return e?ie(T,e,r):""}function Ae(e,r,t,l){if(!(l>0))return 0;for(var f=t,a=t+l-1,i=0;i<e.length;++i){var o=e.charCodeAt(i);if(o>=55296&&o<=57343){var u=e.charCodeAt(++i);o=65536+((o&1023)<<10)|u&1023}if(o<=127){if(t>=a)break;r[t++]=o}else if(o<=2047){if(t+1>=a)break;r[t++]=192|o>>6,r[t++]=128|o&63}else if(o<=65535){if(t+2>=a)break;r[t++]=224|o>>12,r[t++]=128|o>>6&63,r[t++]=128|o&63}else{if(t+3>=a)break;r[t++]=240|o>>18,r[t++]=128|o>>12&63,r[t++]=128|o>>6&63,r[t++]=128|o&63}}return r[t]=0,t-f}function Pe(e,r,t){return Ae(e,T,r,t)}typeof TextDecoder<"u"&&new TextDecoder("utf-16le");function Se(e,r){se.set(e,r)}var ae=65536,j,se,T,I,fe;function Fe(e){j=e,n.HEAP8=se=new Int8Array(e),n.HEAP16=new Int16Array(e),n.HEAP32=I=new Int32Array(e),n.HEAPU8=T=new Uint8Array(e),n.HEAPU16=new Uint16Array(e),n.HEAPU32=new Uint32Array(e),n.HEAPF32=fe=new Float32Array(e),n.HEAPF64=new Float64Array(e)}var Oe=5284544,Te=41504,Z=n.TOTAL_MEMORY||16777216;n.wasmMemory?q=n.wasmMemory:q=new WebAssembly.Memory({initial:Z/ae,maximum:Z/ae}),q&&(j=q.buffer),Z=j.byteLength,Fe(j),I[Te>>2]=Oe;function V(e){for(;e.length>0;){var r=e.shift();if(typeof r=="function"){r();continue}var t=r.func;typeof t=="number"?r.arg===void 0?n.dynCall_v(t):n.dynCall_vi(t,r.arg):t(r.arg===void 0?null:r.arg)}}var ue=[],ce=[],le=[],de=[];function Me(){if(n.preRun)for(typeof n.preRun=="function"&&(n.preRun=[n.preRun]);n.preRun.length;)Ne(n.preRun.shift());V(ue)}function Ce(){V(ce)}function De(){V(le)}function Ie(){if(n.postRun)for(typeof n.postRun=="function"&&(n.postRun=[n.postRun]);n.postRun.length;)He(n.postRun.shift());V(de)}function Ne(e){ue.unshift(e)}function Le(e){le.unshift(e)}function He(e){de.unshift(e)}var ke=Math.abs,M=0,B=null;function qe(e){M++,n.monitorRunDependencies&&n.monitorRunDependencies(M)}function Be(e){if(M--,n.monitorRunDependencies&&n.monitorRunDependencies(M),M==0&&B){var r=B;B=null,r()}}n.preloadedImages={},n.preloadedAudios={};function A(e){throw n.onAbort&&n.onAbort(e),e+="",ee(e),O(e),ne=!0,e="abort("+e+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(e)}var pe="data:application/octet-stream;base64,";function he(e){return String.prototype.startsWith?e.startsWith(pe):e.indexOf(pe)===0}var P="opus-stream-decoder.wasm";he(P)||(P=we(P));function me(){try{if(k)return new Uint8Array(k);if(H)return H(P);throw"both async and sync fetching of the wasm failed"}catch(e){A(e)}}function Ue(){return!k&&(y||p)&&typeof fetch=="function"?fetch(P,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+P+"'";return e.arrayBuffer()}).catch(function(){return me()}):new Promise(function(e,r){e(me())})}function We(){var e={env:ve,wasi_snapshot_preview1:ve};function r(i,o){var u=i.exports;n.asm=u,Be()}qe();function t(i){r(i.instance)}function l(i){return Ue().then(function(o){return WebAssembly.instantiate(o,e)}).then(i,function(o){O("failed to asynchronously prepare wasm: "+o),A(o)})}function f(){if(!k&&typeof WebAssembly.instantiateStreaming=="function"&&!he(P)&&typeof fetch=="function")fetch(P,{credentials:"same-origin"}).then(function(i){var o=WebAssembly.instantiateStreaming(i,e);return o.then(t,function(u){O("wasm streaming compile failed: "+u),O("falling back to ArrayBuffer instantiation"),l(t)})});else return l(t)}if(n.instantiateWasm)try{var a=n.instantiateWasm(e,r);return a}catch(i){return O("Module.instantiateWasm callback failed with error: "+i),!1}return f(),{}}ce.push({func:function(){Ze()}});var je=ke;function Ve(e,r,t){T.set(T.subarray(r,r+t),e)}function Ge(e){A("OOM")}function Ye(e){Ge()}var S={buffers:[null,[],[]],printChar:function(e,r){var t=S.buffers[e];r===0||r===10?((e===1?ee:O)(ie(t,0)),t.length=0):t.push(r)},varargs:0,get:function(e){S.varargs+=4;var r=I[S.varargs-4>>2];return r},getStr:function(){var e=oe(S.get());return e},get64:function(){var e=S.get();return S.get(),e},getZero:function(){S.get()}};function ze(e){try{return 0}catch(r){return(typeof FS>"u"||!(r instanceof FS.ErrnoError))&&A(r),r.errno}}function xe(e,r,t,l,f){try{return 0}catch(a){return(typeof FS>"u"||!(a instanceof FS.ErrnoError))&&A(a),a.errno}}function Xe(e,r,t,l){try{for(var f=0,a=0;a<t;a++){for(var i=I[r+a*8>>2],o=I[r+(a*8+4)>>2],u=0;u<o;u++)S.printChar(e,T[i+u]);f+=o}return I[l>>2]=f,0}catch(m){return(typeof FS>"u"||!(m instanceof FS.ErrnoError))&&A(m),m.errno}}var ve={a:je,c:Ve,d:Ye,f:ze,b:xe,e:Xe,memory:q,table:Ee},_e=We();n.asm=_e;var Ze=n.___wasm_call_ctors=function(){return n.asm.g.apply(null,arguments)};n._opus_chunkdecoder_version=function(){return n.asm.h.apply(null,arguments)},n._opus_chunkdecoder_enqueue=function(){return n.asm.i.apply(null,arguments)},n._opus_chunkdecoder_decode_float_stereo_deinterleaved=function(){return n.asm.j.apply(null,arguments)},n._opus_chunkdecoder_create=function(){return n.asm.k.apply(null,arguments)},n._malloc=function(){return n.asm.l.apply(null,arguments)},n._opus_chunkdecoder_free=function(){return n.asm.m.apply(null,arguments)},n._free=function(){return n.asm.n.apply(null,arguments)},n._opus_get_version_string=function(){return n.asm.o.apply(null,arguments)};var $e=n.stackSave=function(){return n.asm.p.apply(null,arguments)},ye=n.stackAlloc=function(){return n.asm.q.apply(null,arguments)},Ke=n.stackRestore=function(){return n.asm.r.apply(null,arguments)};n.asm=_e,n.cwrap=E;var U;n.then=function(e){if(U)e(n);else{var r=n.onRuntimeInitialized;n.onRuntimeInitialized=function(){r&&r(),e(n)}}return n};function Je(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}B=function e(){U||$(),U||(B=e)};function $(e){if(M>0||(Me(),M>0))return;function r(){U||(U=!0,!ne&&(Ce(),De(),n.onRuntimeInitialized&&n.onRuntimeInitialized(),Ie()))}n.setStatus?(n.setStatus("Running..."),setTimeout(function(){setTimeout(function(){n.setStatus("")},1),r()},1)):r()}if(n.run=$,n.preInit)for(typeof n.preInit=="function"&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();$(),n.OpusStreamDecoder=C,typeof global<"u"&&exports&&(module.exports.OpusStreamDecoder=C);function Qe(e,r,t){this.left=e,this.right=r,this.samplesDecoded=t,this.sampleRate=48e3}function C(e){if(typeof e.onDecode!="function")throw Error("onDecode callback is required.");Object.defineProperty(this,"onDecode",{value:e.onDecode})}return C.prototype.ready=new Promise(function(e,r){Le(function(){var t={malloc:E("malloc","number",["number"]),free:E("free",null,["number"]),HEAPU8:T,HEAPF32:fe,libopusVersion:E("opus_get_version_string","string",[]),decoderVersion:E("opus_chunkdecoder_version","string",[]),createDecoder:E("opus_chunkdecoder_create",null,[]),freeDecoder:E("opus_chunkdecoder_free",null,["number"]),enqueue:E("opus_chunkdecoder_enqueue",null,["number","number","number"]),decode:E("opus_chunkdecoder_decode_float_stereo_deinterleaved","number",["number","number","number","number"])};Object.freeze(t),Object.defineProperty(C.prototype,"api",{value:t}),e()})}),C.prototype.decode=function(e){if(!(e instanceof Uint8Array))throw Error("Data to decode must be Uint8Array");this._decoderPointer||(this._decoderPointer=this.api.createDecoder());var r,t,l,f,a,i,o;try{var u=11520;[t,l]=this.createOutputArray(u),[f,a]=this.createOutputArray(u/2),[i,o]=this.createOutputArray(u/2);var m=16*1024,_=0,D,N=e.byteLength;for(r=this.api.malloc(e.BYTES_PER_ELEMENT*m);_<N;){if(D=Math.min(m,N-_),this.api.HEAPU8.set(e.subarray(_,_+D),r),_+=D,!this.api.enqueue(this._decoderPointer,r,D))throw Error("Could not enqueue bytes for decoding. You may also have invalid Ogg Opus file.");for(var d,F=0;d=this.api.decode(this._decoderPointer,t,u,f,i);)F+=d,this.onDecode(new Qe(a.slice(0,d),o.slice(0,d),d))}}catch(G){throw G}finally{this.api.free(r),this.api.free(t),this.api.free(f),this.api.free(i)}},C.prototype.free=function(){this._decoderPointer&&this.api.freeDecoder(this._decoderPointer)},Object.defineProperty(C.prototype,"createOutputArray",{value:function(e){var r=this.api.malloc(Float32Array.BYTES_PER_ELEMENT*e),t=new Float32Array(this.api.HEAPF32.buffer,r,e);return[r,t]}}),n}}();const h=class h{constructor({onFlush:s}){w(this,"_bufferL",new Float32Array(h.maxFlushSize));w(this,"_bufferR",new Float32Array(h.maxFlushSize));w(this,"_bufferPos");w(this,"_onFlush");w(this,"_flushCount");if(typeof s!="function")throw Error("onFlush must be a function");this._onFlush=s,this.reset()}reset(){this._bufferPos=0,this._flushCount=0}add({left:s,right:n}){const g=s.length;let v,y=0,p=this._bufferPos;for(;y<g;){v=h.flushLength(this._flushCount);const R=Math.min(v-p,g-y),L=y+R;this._bufferL.set(s.slice(y,L),p),this._bufferR.set(n.slice(y,L),p),y+=R,p+=R,this._bufferPos=p,p===v&&(this.flush(p),p=0)}}flush(){const s=this._bufferPos;this._onFlush({left:this._bufferL.slice(0,s),right:this._bufferR.slice(0,s)}),this._flushCount++,this._bufferPos=0}};w(h,"maxFlushSize",1024*128),w(h,"maxGrows",50),w(h,"firstFlushLength",.02*48e3),w(h,"growFactor",Math.pow(h.maxFlushSize/4/h.firstFlushLength,1/(h.maxGrows-1))),w(h,"flushLength",s=>{const n=Math.min(s,h.maxGrows-1),g=Math.pow(h.growFactor,n);return Math.round(h.firstFlushLength*g)});let K=h;const tn=rn(),{OpusStreamDecoder:on}=tn,ge=new on({onDecode:sn}),J=new K({onFlush:fn});let Y,be;function an(c){Y&&Y===c||(Y=c,J.reset())}self.onmessage=async c=>{an(c.data.sessionId),await ge.ready,ge.decode(new Uint8Array(c.data.decode))};function sn({left:c,right:s,samplesDecoded:n,sampleRate:g}){n<0||(J.add({left:c,right:s}),un())}function fn({left:c,right:s}){const n={channelData:[c,s],length:c.length,numberOfChannels:2,sampleRate:48e3};self.postMessage({decoded:n,sessionId:Y},[n.channelData[0].buffer,n.channelData[1].buffer])}function un(){clearTimeout(be),be=setTimeout(c=>{J.flush()},100)}
@@ -0,0 +1 @@
1
+ function a(t){this.readerMeta=!1,this.opts=t||{}}a.prototype.decodeChunk=function(t){return new Promise(i=>{i(this.decodeChunkSync(t))})};a.prototype.decodeChunkSync=function(t){let i=new o(new DataView(t));this.readerMeta||this._init(i);let n=this._decodeData(i);if(n instanceof Error)throw n;return n};a.prototype._init=function(t){if(t.string(4)!=="RIFF")throw new TypeError("Invalid WAV file");if(t.uint32(),t.string(4)!=="WAVE")throw new TypeError("Invalid WAV file");let i=!1,n,e;do switch(n=t.string(4),e=t.uint32(),n){case"fmt ":if(this.readerMeta=this._decodeMetaInfo(t,e),this.readerMeta instanceof Error)throw this.readerMeta;break;case"data":i=!0;break;default:t.skip(e);break}while(!i)};a.prototype._decodeMetaInfo=function(t,i){const n={1:"lpcm",3:"lpcm"},e=t.uint16();if(!n.hasOwnProperty(e))return new TypeError("Unsupported format in WAV file: 0x"+e.toString(16));const s={formatId:e,floatingPoint:e===3,numberOfChannels:t.uint16(),sampleRate:t.uint32(),byteRate:t.uint32(),blockSize:t.uint16(),bitDepth:t.uint16()};t.skip(i-16);const p=s.floatingPoint?"f":this.opts.symmetric?"s":"";return s.readerMethodName="pcm"+s.bitDepth+p,t[s.readerMethodName]?s:new TypeError("Not supported bit depth: "+s.bitDepth)};a.prototype._decodeData=function(t){let i=t.remain(),n=Math.floor(i/this.readerMeta.blockSize),e=new Array(this.readerMeta.numberOfChannels);for(let r=0;r<this.readerMeta.numberOfChannels;r++)e[r]=new Float32Array(n);const s=t[this.readerMeta.readerMethodName].bind(t),p=this.readerMeta.numberOfChannels;for(let r=0;r<n;r++)for(let h=0;h<p;h++)e[h][r]=s();return{channelData:e,length:n,numberOfChannels:this.readerMeta.numberOfChannels,sampleRate:this.readerMeta.sampleRate}};function o(t){this.view=t,this.pos=0}o.prototype.remain=function(){return this.view.byteLength-this.pos},o.prototype.skip=function(t){this.pos+=t},o.prototype.uint8=function(){const t=this.view.getUint8(this.pos,!0);return this.pos+=1,t},o.prototype.int16=function(){const t=this.view.getInt16(this.pos,!0);return this.pos+=2,t},o.prototype.uint16=function(){const t=this.view.getUint16(this.pos,!0);return this.pos+=2,t},o.prototype.uint32=function(){const t=this.view.getUint32(this.pos,!0);return this.pos+=4,t},o.prototype.string=function(t){let i="";for(let n=0;n<t;n++)i+=String.fromCharCode(this.uint8());return i},o.prototype.pcm8=function(){const t=this.view.getUint8(this.pos)-128;return this.pos+=1,t<0?t/128:t/127},o.prototype.pcm8s=function(){const t=this.view.getUint8(this.pos)-127.5;return this.pos+=1,t/127.5},o.prototype.pcm16=function(){const t=this.view.getInt16(this.pos,!0);return this.pos+=2,t<0?t/32768:t/32767},o.prototype.pcm16s=function(){const t=this.view.getInt16(this.pos,!0);return this.pos+=2,t/32768},o.prototype.pcm24=function(){let t=this.view.getUint8(this.pos+0),i=this.view.getUint8(this.pos+1),n=this.view.getUint8(this.pos+2),e=t+(i<<8)+(n<<16),s=e>8388608?e-16777216:e;return this.pos+=3,s<0?s/8388608:s/8388607},o.prototype.pcm24s=function(){let t=this.view.getUint8(this.pos+0),i=this.view.getUint8(this.pos+1),n=this.view.getUint8(this.pos+2),e=t+(i<<8)+(n<<16),s=e>8388608?e-16777216:e;return this.pos+=3,s/8388608},o.prototype.pcm32=function(){const t=this.view.getInt32(this.pos,!0);return this.pos+=4,t<0?t/2147483648:t/2147483647},o.prototype.pcm32s=function(){const t=this.view.getInt32(this.pos,!0);return this.pos+=4,t/2147483648},o.prototype.pcm32f=function(){const t=this.view.getFloat32(this.pos,!0);return this.pos+=4,t},o.prototype.pcm64f=function(){const t=this.view.getFloat64(this.pos,!0);return this.pos+=8,t};const c=new a;self.onmessage=t=>{const{decode:i,sessionId:n}=t.data;if(i){const e=c.decodeChunkSync(t.data.decode);self.postMessage({decoded:e,sessionId:n},e.channelData.map(({buffer:s})=>s))}};
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@puresignal/fetch-stream-audio",
3
+ "version": "0.1.0",
4
+ "description": "Low-latency streaming audio playback using Fetch, Streams, and Web Audio APIs",
5
+ "type": "module",
6
+ "main": "./dist/fetch-stream-audio.cjs",
7
+ "module": "./dist/fetch-stream-audio.mjs",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/fetch-stream-audio.mjs",
11
+ "require": "./dist/fetch-stream-audio.cjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist/",
16
+ "!dist/demo"
17
+ ],
18
+ "scripts": {
19
+ "dev": "vite --config vite.demo.config.js",
20
+ "build": "yarn build:lib && yarn build:demo",
21
+ "build:lib": "vite build && vite build --config vite.workers.config.js",
22
+ "build:demo": "vite build --config vite.demo.config.js",
23
+ "clean": "rm -rf dist .vite",
24
+ "clean-all": "rm -rf dist .vite node_modules yarn.lock"
25
+ },
26
+ "devDependencies": {
27
+ "eslint": "10.0.3",
28
+ "vite": "^5.0.0",
29
+ "vite-plugin-static-copy": "3.3.0"
30
+ },
31
+ "dependencies": {
32
+ "lit-html": "^1.1.2",
33
+ "opus-stream-decoder": "^1.2.6"
34
+ },
35
+ "packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610"
36
+ }