@stacksjs/audio 0.75.674 → 0.75.685

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 CHANGED
@@ -71,4 +71,8 @@ The library player includes play, seek, time, mute, volume, speed, settings, wav
71
71
 
72
72
  ## Bounded speech uploads
73
73
 
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. Install FFmpeg in the server runtime; an absent decoder is an explicit error. The decoder reads and writes pipes, disables external input protocols, bounds both output streams, and keeps no temporary recording files. `decoderPath` is a deployment option, never HTTP input.
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
+
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.
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.
@@ -0,0 +1,4 @@
1
+ import type { SpeechDecodeLimits } from './speech-decode';
2
+ export declare interface SpeechDecodeJob extends SpeechDecodeLimits {
3
+ input: ArrayBuffer
4
+ }
@@ -0,0 +1 @@
1
+ import{decodeSpeech}from"./speech-decode";self.onmessage=async({data})=>{const result=await decodeSpeech(new Uint8Array(data.input),data).catch((error)=>({ok:false,failure:{kind:"undecodable",detail:error instanceof Error?error.message:String(error)}}));if(result.ok)self.postMessage(result,[result.audio.buffer]);else self.postMessage(result)};self.postMessage({ready:true});
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Decodes an upload to 16 kHz mono 16-bit WAV, refusing it if the decoded
3
+ * samples run past the limit, whatever its container claims. At most one
4
+ * second of audio past the limit is decoded.
5
+ *
6
+ * `signal` and `deadline` (a `performance.now()` time) serve the calling-thread
7
+ * fallback: they are checked between packets and stages, and throw the
8
+ * signal's reason or "Audio decoder timed out". A worker is stopped from
9
+ * outside instead and passes neither.
10
+ */
11
+ export declare function decodeSpeech(input: Uint8Array, limits: SpeechDecodeLimits, signal?: AbortSignal, deadline?: unknown): Promise<SpeechDecodeResult>;
12
+ export declare interface SpeechDecodeLimits {
13
+ maxBytes: number
14
+ maxDurationSeconds: number
15
+ }
16
+ export type SpeechDecodeFailure = | { kind: 'duration' }
17
+ | { kind: 'unsupported', format: string }
18
+ | { kind: 'sample-rate', rate: number }
19
+ | { kind: 'undecodable', detail?: string }
20
+ export type SpeechDecodeResult = | { ok: true, audio: Uint8Array, durationSeconds: number }
21
+ | { ok: false, failure: SpeechDecodeFailure }
@@ -0,0 +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(text(bytes,0,3)==="ID3")return"MP3";if(bytes[0]===255&&((bytes[1]??0)&224)===224)return((bytes[1]??0)&6)===0?"AAC in an ADTS stream":"MP3";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)}
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Decodes an upload to 16 kHz mono 16-bit WAV and refuses it if the decoded
3
+ * samples run past the limit, whatever its container claims.
4
+ *
5
+ * The decode runs in a worker thread, so the event loop stays free, and the
6
+ * deadline or `signal` terminates it mid-decode. Where the worker cannot load
7
+ * (an app bundled into one file, a runtime without `Worker`), it decodes on
8
+ * the calling thread instead, checking both between packets and stages.
9
+ */
1
10
  export declare function prepareSpeechAudio(input: Uint8Array, options?: SpeechAudioOptions): Promise<PreparedSpeechAudio>;
2
11
  /** Decode untrusted voice uploads before billing or sending them to a speech provider. */
3
12
  export declare interface SpeechAudioOptions {
@@ -1 +1 @@
1
- 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.length||input.length>maxBytes)throw new Error("Audio size exceeds the upload limit or is empty");options.signal?.throwIfAborted();const executable=options.decoderPath||Bun.which("ffmpeg");if(!executable)throw new Error("Speech audio preparation needs FFmpeg installed on the server");const child=Bun.spawn([executable,"-nostdin","-hide_banner","-v","error","-threads","1","-protocol_whitelist","cache,pipe","-read_ahead_limit",String(Math.min(maxBytes,2147483647)),"-i","cache:pipe:0","-map","0:a:0","-vn","-t",String(maxDuration+1),"-ac","1","-ar","16000","-c:a","pcm_s16le","-f","wav","pipe:1"],{stdin:new Blob([new Uint8Array(input)]),stdout:"pipe",stderr:"pipe"});let timedOut=false;const stop=()=>{if(child.exitCode===null)child.kill("SIGKILL")};const timer=setTimeout(()=>{timedOut=true;stop()},timeout);options.signal?.addEventListener("abort",stop,{once:true});async function bounded(stream,limit){const reader=stream.getReader();const chunks=[];let size=0;try{while(true){const item=await reader.read();if(item.done)break;size+=item.value.length;if(size>limit){stop();throw new Error("Audio decoder exceeded its output limit")}chunks.push(item.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length}return bytes}try{const[audio,,code]=await Promise.all([bounded(child.stdout,(maxDuration+1)*32000+4096),bounded(child.stderr,16384),child.exited]);options.signal?.throwIfAborted();if(timedOut)throw new Error("Audio decoder timed out");if(code!==0||audio.length<44)throw new Error("The uploaded audio could not be decoded");const view=new DataView(audio.buffer,audio.byteOffset,audio.byteLength);for(let offset=12;offset+8<=audio.length;){const size=view.getUint32(offset+4,true);if(String.fromCharCode(...audio.subarray(offset,offset+4))==="data"){const durationSeconds=(audio.length-offset-8)/32000;if(durationSeconds<=0||durationSeconds>maxDuration)throw new Error("Audio duration exceeds the recording limit or is empty");return{audio,mimeType:"audio/wav",durationSeconds}}offset+=8+size+size%2}throw new Error("Audio decoder returned an invalid WAV container")}finally{clearTimeout(timer);options.signal?.removeEventListener("abort",stop);stop()}}
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)}}}}
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.674",
5
+ "version": "0.75.685",
6
6
  "description": "Native audio delivery planning for Stacks.",
7
7
  "author": "Chris Breuer",
8
8
  "license": "MIT",
@@ -32,7 +32,8 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@ts-audio/core": "^0.1.2",
35
- "ts-video-player": "^0.1.6"
35
+ "ts-video-player": "^0.1.6",
36
+ "ts-videos": "^0.3.1"
36
37
  },
37
38
  "devDependencies": {
38
39
  "better-dx": "^0.2.39"