@stacksjs/audio 0.75.685 → 0.75.687
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/README.md +2 -2
- package/dist/speech-decode.js +1 -1
- package/dist/speech-input.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -73,6 +73,6 @@ The library player includes play, seek, time, mute, volume, speed, settings, wav
|
|
|
73
73
|
|
|
74
74
|
`prepareSpeechAudio(bytes, { maxBytes, maxDurationSeconds, timeoutMs, signal })` decodes an untrusted upload to mono 16 kHz PCM WAV, measures the decoded samples and refuses audio beyond the duration limit. Defaults are 12 MiB input, five minutes and a 30-second decoder deadline.
|
|
75
75
|
|
|
76
|
-
Decoding runs in-process with [ts-videos](https://github.com/stacksjs/ts-videos), in TypeScript, so the server needs no FFmpeg. It reads AAC from M4A or MP4 (HE-AAC as its AAC-LC core), Opus from Ogg, WebM or MP4, and PCM WAV: what phone, Safari, Chrome, Firefox and WhatsApp recorders produce. MP3, Vorbis, FLAC, AMR and other codecs are refused with an error that names the format. Gapless trimming drops encoder priming and padding.
|
|
76
|
+
Decoding runs in-process with [ts-videos](https://github.com/stacksjs/ts-videos), in TypeScript, so the server needs no FFmpeg. It reads AAC from M4A or MP4 (HE-AAC as its AAC-LC core), Opus from Ogg, WebM or MP4, and PCM WAV: what phone, Safari, Chrome, Firefox and WhatsApp recorders produce. It also reads MP3, constant or variable bitrate, with or without ID3 tags, the form a voice note takes when it is exported or shared as a file. Vorbis, FLAC, AMR, MPEG layers I and II and other codecs are refused with an error that names the format. Gapless trimming drops encoder priming and padding.
|
|
77
77
|
|
|
78
|
-
The work is bounded before it starts. Input is bytes only, never a path or URL, and nothing is fetched. At most one second of audio past the limit is decoded: an Ogg file's length is counted from its packets rather than its granule positions, which an upload can set to anything, and a source sample rate above 192 kHz is refused. Each decode runs in its own worker thread, so the event loop stays free: on an Apple-silicon Mac five minutes of speech takes about 0.4 s as AAC and 2 to 3 s as Opus, and starting the worker about 20 ms. The deadline and `signal` terminate the worker mid-decode; an abort rejects with the signal's own reason. Where the worker cannot load, because the app was bundled into one file and `speech-decode-worker.js` is not beside it or the runtime has no `Worker`, decoding falls back to the calling thread with the same limits, checks the deadline and `signal` only between packets and stages, and warns once. No temporary files are written. `decoderPath` is deprecated and ignored.
|
|
78
|
+
The work is bounded before it starts. Input is bytes only, never a path or URL, and nothing is fetched. At most one second of audio past the limit is decoded: an Ogg file's length is counted from its packets rather than its granule positions, which an upload can set to anything, and a source sample rate above 192 kHz is refused. Each decode runs in its own worker thread, so the event loop stays free: on an Apple-silicon Mac five minutes of speech takes about 0.4 s as AAC, 1.6 s as MP3 and 2 to 3 s as Opus, and starting the worker about 20 ms. The deadline and `signal` terminate the worker mid-decode; an abort rejects with the signal's own reason. Where the worker cannot load, because the app was bundled into one file and `speech-decode-worker.js` is not beside it or the runtime has no `Worker`, decoding falls back to the calling thread with the same limits, checks the deadline and `signal` only between packets and stages, and warns once. No temporary files are written. `decoderPath` is deprecated and ignored.
|
package/dist/speech-decode.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AudioTooLongError,decodeAudio,encodeWav,mixChannels,resampleAudio,UnsupportedAudioCodecError}from"ts-videos";const SPEECH_RATE=16000;const MAX_SOURCE_RATE=192000;export async function decodeSpeech(input,limits,signal,deadline=1/0){const{maxBytes,maxDurationSeconds:maxDuration}=limits;const checkpoint=()=>{signal?.throwIfAborted();if(performance.now()>deadline)throw new Error("Audio decoder timed out")};const fail=(failure)=>({ok:false,failure});const unsupported=unsupportedFormat(input);if(unsupported)return fail({kind:"unsupported",format:unsupported});const ogg=scanOgg(input);if(ogg&&ogg.codec!=="Opus")return fail({kind:"unsupported",format:ogg.codec});if(ogg&&ogg.seconds>maxDuration+1)return fail({kind:"duration"});checkpoint();let decoded;try{decoded=await decodeAudio(input,{maxBytes,maxDurationSeconds:maxDuration+1,signal})}catch(error){if(signal?.aborted)throw signal.reason;if(error instanceof AudioTooLongError)return fail({kind:"duration"});if(error instanceof UnsupportedAudioCodecError)return fail({kind:"unsupported",format:error.codec});return fail({kind:"undecodable",detail:error instanceof Error?error.message:String(error)})}checkpoint();if(!(decoded.sampleRate>0&&decoded.sampleRate<=MAX_SOURCE_RATE))return fail({kind:"sample-rate",rate:decoded.sampleRate});const samples=resampleAudio(mixChannels(decoded.channels,1),decoded.sampleRate,SPEECH_RATE);const durationSeconds=(samples[0]?.length??0)/SPEECH_RATE;if(durationSeconds<=0||durationSeconds>maxDuration)return fail({kind:"duration"});checkpoint();return{ok:true,audio:encodeWav(samples,SPEECH_RATE),durationSeconds}}function text(bytes,offset,length){return String.fromCharCode(...bytes.subarray(offset,offset+length))}function unsupportedFormat(bytes){if(text(bytes,0,4)==="fLaC")return"FLAC";if(text(bytes,0,5)==="#!AMR")return"AMR";if(
|
|
1
|
+
import{AudioTooLongError,decodeAudio,encodeWav,mixChannels,resampleAudio,UnsupportedAudioCodecError}from"ts-videos";const SPEECH_RATE=16000;const MAX_SOURCE_RATE=192000;export async function decodeSpeech(input,limits,signal,deadline=1/0){const{maxBytes,maxDurationSeconds:maxDuration}=limits;const checkpoint=()=>{signal?.throwIfAborted();if(performance.now()>deadline)throw new Error("Audio decoder timed out")};const fail=(failure)=>({ok:false,failure});const unsupported=unsupportedFormat(input);if(unsupported)return fail({kind:"unsupported",format:unsupported});const ogg=scanOgg(input);if(ogg&&ogg.codec!=="Opus")return fail({kind:"unsupported",format:ogg.codec});if(ogg&&ogg.seconds>maxDuration+1)return fail({kind:"duration"});checkpoint();let decoded;try{decoded=await decodeAudio(input,{maxBytes,maxDurationSeconds:maxDuration+1,signal})}catch(error){if(signal?.aborted)throw signal.reason;if(error instanceof AudioTooLongError)return fail({kind:"duration"});if(error instanceof UnsupportedAudioCodecError)return fail({kind:"unsupported",format:error.codec});return fail({kind:"undecodable",detail:error instanceof Error?error.message:String(error)})}checkpoint();if(!(decoded.sampleRate>0&&decoded.sampleRate<=MAX_SOURCE_RATE))return fail({kind:"sample-rate",rate:decoded.sampleRate});const samples=resampleAudio(mixChannels(decoded.channels,1),decoded.sampleRate,SPEECH_RATE);const durationSeconds=(samples[0]?.length??0)/SPEECH_RATE;if(durationSeconds<=0||durationSeconds>maxDuration)return fail({kind:"duration"});checkpoint();return{ok:true,audio:encodeWav(samples,SPEECH_RATE),durationSeconds}}function text(bytes,offset,length){return String.fromCharCode(...bytes.subarray(offset,offset+length))}function unsupportedFormat(bytes){if(text(bytes,0,4)==="fLaC")return"FLAC";if(text(bytes,0,5)==="#!AMR")return"AMR";if(bytes[0]===255&&((bytes[1]??0)&230)===224)return"AAC in an ADTS stream";return null}function scanOgg(bytes){if(text(bytes,0,4)!=="OggS")return null;const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);let serial;let codec="Ogg audio other than Opus";let preSkip=0;let samples=0;let packets=0;let start=-1;let length=0;for(let page=0;page+27<=bytes.length&&text(bytes,page,4)==="OggS";){const segments=bytes[page+26];let body=page+27+segments;if(body>bytes.length)break;serial??=view.getUint32(page+14,true);const ours=view.getUint32(page+14,true)===serial;for(let index=0;index<segments;index++){const size=bytes[page+27+index];if(ours){if(start<0)start=body;length+=Math.max(0,Math.min(size,bytes.length-body));if(size<255){if(packets===0){codec=oggCodec(bytes,start,length);if(codec==="Opus")preSkip=view.getUint16(start+10,true)}else if(packets>1){samples+=length?opusPacketSamples(bytes[start],length>1?bytes[start+1]:0):960}packets++;start=-1;length=0}}body+=size}page=body}return{codec,seconds:Math.max(0,samples-preSkip)/48000}}function oggCodec(bytes,start,length){if(length>=19&&text(bytes,start,8)==="OpusHead")return"Opus";if(bytes[start]===1&&text(bytes,start+1,6)==="vorbis")return"Vorbis";if(bytes[start]===127&&text(bytes,start+1,4)==="FLAC")return"FLAC";if(text(bytes,start,8)==="Speex ")return"Speex";return"Ogg audio other than Opus"}function opusPacketSamples(toc,second){const config=toc>>3;const frame=config<12?[480,960,1920,2880][config&3]:config<16?config&1?960:480:[120,240,480,960][config&3];const frames=(toc&3)===0?1:(toc&3)===3?second&63:2;return Math.min(5760,frame*frames)}
|
package/dist/speech-input.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeSpeech}from"./speech-decode";const DURATION_ERROR="Audio duration exceeds the recording limit or is empty";const UNDECODABLE="The uploaded audio could not be decoded";const SUPPORTED="Record AAC (M4A), Opus (WebM or Ogg) or WAV.";const TIMED_OUT="Audio decoder timed out";export async function prepareSpeechAudio(input,options={}){const maxBytes=options.maxBytes??12*1024*1024;const maxDuration=options.maxDurationSeconds??300;const timeout=options.timeoutMs??30000;if(![maxBytes,maxDuration,timeout].every((value)=>Number.isSafeInteger(value)&&value>0)||maxDuration>3600)throw new TypeError("Invalid speech audio limits");if(!(input instanceof Uint8Array))throw new TypeError("Speech audio must be the uploaded bytes");if(!input.length||input.length>maxBytes)throw new Error("Audio size exceeds the upload limit or is empty");options.signal?.throwIfAborted();const limits={maxBytes,maxDurationSeconds:maxDuration};const deadline=performance.now()+timeout;const result=await decodeInWorker(input,limits,timeout,options.signal)??await decodeOnCallingThread(input,limits,deadline,options.signal);if(!result.ok)throw failureError(result.failure);return{audio:result.audio,mimeType:"audio/wav",durationSeconds:result.durationSeconds}}function failureError(failure){switch(failure.kind){case"duration":return new Error(DURATION_ERROR);case"unsupported":return new Error(`${UNDECODABLE}: ${failure.format} is not supported. ${SUPPORTED}`);case"sample-rate":return new Error(`${UNDECODABLE}: a ${failure.rate} Hz sample rate is not supported`);case"undecodable":return new Error(UNDECODABLE,failure.detail?{cause:new Error(failure.detail)}:undefined)}}function decodeInWorker(input,limits,timeout,signal){return new Promise((resolve,reject)=>{let worker;try{if(typeof Worker!=="function")throw new TypeError("This runtime has no Worker");worker=new Worker(new URL("./speech-decode-worker.js",import.meta.url))}catch(error){resolve(unavailable(error));return}let ready=false;let settled=false;const settle=(finish)=>{if(settled)return;settled=true;clearTimeout(timer);signal?.removeEventListener("abort",onAbort);worker.terminate();finish()};const timer=setTimeout(()=>settle(()=>reject(new Error(TIMED_OUT))),timeout);const onAbort=()=>settle(()=>reject(signal.reason));signal?.addEventListener("abort",onAbort,{once:true});worker.addEventListener("message",({data})=>{if("ready"in data){ready=true;const copy=new Uint8Array(input);const job={input:copy.buffer,...limits};worker.postMessage(job,[copy.buffer]);return}settle(()=>resolve(data))});worker.addEventListener("error",(event)=>{event.preventDefault();settle(()=>resolve(ready?{ok:false,failure:{kind:"undecodable",detail:event.message}}:unavailable(event.message)))});worker.addEventListener("messageerror",()=>settle(()=>resolve({ok:false,failure:{kind:"undecodable",detail:"The decoder worker sent an unreadable result"}})));worker.addEventListener("close",()=>settle(()=>resolve(ready?{ok:false,failure:{kind:"undecodable",detail:"The decoder worker stopped without a result"}}:unavailable("it exited while loading"))))})}let warnedUnavailable=false;function unavailable(reason){if(!warnedUnavailable){warnedUnavailable=true;const detail=reason instanceof Error?reason.message:String(reason);console.warn(`@stacksjs/audio: the speech decoding worker could not start (${detail}). Speech uploads are decoded on the calling thread, which holds the event loop while they decode.`)}return null}async function decodeOnCallingThread(input,limits,deadline,signal){try{return await decodeSpeech(input,limits,signal,deadline)}catch(error){if(signal?.aborted)throw signal.reason;if(error instanceof Error&&error.message===TIMED_OUT)throw error;return{ok:false,failure:{kind:"undecodable",detail:error instanceof Error?error.message:String(error)}}}}
|
|
1
|
+
import{decodeSpeech}from"./speech-decode";const DURATION_ERROR="Audio duration exceeds the recording limit or is empty";const UNDECODABLE="The uploaded audio could not be decoded";const SUPPORTED="Record AAC (M4A), Opus (WebM or Ogg), MP3 or WAV.";const TIMED_OUT="Audio decoder timed out";export async function prepareSpeechAudio(input,options={}){const maxBytes=options.maxBytes??12*1024*1024;const maxDuration=options.maxDurationSeconds??300;const timeout=options.timeoutMs??30000;if(![maxBytes,maxDuration,timeout].every((value)=>Number.isSafeInteger(value)&&value>0)||maxDuration>3600)throw new TypeError("Invalid speech audio limits");if(!(input instanceof Uint8Array))throw new TypeError("Speech audio must be the uploaded bytes");if(!input.length||input.length>maxBytes)throw new Error("Audio size exceeds the upload limit or is empty");options.signal?.throwIfAborted();const limits={maxBytes,maxDurationSeconds:maxDuration};const deadline=performance.now()+timeout;const result=await decodeInWorker(input,limits,timeout,options.signal)??await decodeOnCallingThread(input,limits,deadline,options.signal);if(!result.ok)throw failureError(result.failure);return{audio:result.audio,mimeType:"audio/wav",durationSeconds:result.durationSeconds}}function failureError(failure){switch(failure.kind){case"duration":return new Error(DURATION_ERROR);case"unsupported":return new Error(`${UNDECODABLE}: ${failure.format} is not supported. ${SUPPORTED}`);case"sample-rate":return new Error(`${UNDECODABLE}: a ${failure.rate} Hz sample rate is not supported`);case"undecodable":return new Error(UNDECODABLE,failure.detail?{cause:new Error(failure.detail)}:undefined)}}function decodeInWorker(input,limits,timeout,signal){return new Promise((resolve,reject)=>{let worker;try{if(typeof Worker!=="function")throw new TypeError("This runtime has no Worker");worker=new Worker(new URL("./speech-decode-worker.js",import.meta.url))}catch(error){resolve(unavailable(error));return}let ready=false;let settled=false;const settle=(finish)=>{if(settled)return;settled=true;clearTimeout(timer);signal?.removeEventListener("abort",onAbort);worker.terminate();finish()};const timer=setTimeout(()=>settle(()=>reject(new Error(TIMED_OUT))),timeout);const onAbort=()=>settle(()=>reject(signal.reason));signal?.addEventListener("abort",onAbort,{once:true});worker.addEventListener("message",({data})=>{if("ready"in data){ready=true;const copy=new Uint8Array(input);const job={input:copy.buffer,...limits};worker.postMessage(job,[copy.buffer]);return}settle(()=>resolve(data))});worker.addEventListener("error",(event)=>{event.preventDefault();settle(()=>resolve(ready?{ok:false,failure:{kind:"undecodable",detail:event.message}}:unavailable(event.message)))});worker.addEventListener("messageerror",()=>settle(()=>resolve({ok:false,failure:{kind:"undecodable",detail:"The decoder worker sent an unreadable result"}})));worker.addEventListener("close",()=>settle(()=>resolve(ready?{ok:false,failure:{kind:"undecodable",detail:"The decoder worker stopped without a result"}}:unavailable("it exited while loading"))))})}let warnedUnavailable=false;function unavailable(reason){if(!warnedUnavailable){warnedUnavailable=true;const detail=reason instanceof Error?reason.message:String(reason);console.warn(`@stacksjs/audio: the speech decoding worker could not start (${detail}). Speech uploads are decoded on the calling thread, which holds the event loop while they decode.`)}return null}async function decodeOnCallingThread(input,limits,deadline,signal){try{return await decodeSpeech(input,limits,signal,deadline)}catch(error){if(signal?.aborted)throw signal.reason;if(error instanceof Error&&error.message===TIMED_OUT)throw error;return{ok:false,failure:{kind:"undecodable",detail:error instanceof Error?error.message:String(error)}}}}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/audio",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.687",
|
|
6
6
|
"description": "Native audio delivery planning for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"license": "MIT",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@ts-audio/core": "^0.1.2",
|
|
35
35
|
"ts-video-player": "^0.1.6",
|
|
36
|
-
"ts-videos": "^0.3.
|
|
36
|
+
"ts-videos": "^0.3.2"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"better-dx": "^0.2.39"
|