1- import { Utils } from '@nativescript/core' ;
1+ import { File , Utils , knownFolders } from '@nativescript/core' ;
22import {
33 AnalyserOptions ,
44 AudioBufferCopyOptions ,
@@ -41,6 +41,10 @@ import {
4141 resolveNativePlayer ,
4242 throwInvalidMediaElement ,
4343} from './common' ;
44+ import { AUDIO_WORKLET_SCOPE } from './audio-worklet-scope' ;
45+ import { SHARED_RING_BRIDGE , createWorkletRing , workletRingLayout } from './audio-worklet-ring' ;
46+ import { AudioParamMap , AudioWorkletNodeOptions , AudioWorkletPort , WorkletHost , closeWithContext , domError , isWorkerSupported , loadWorkletModule , resolveWorkletNodeOptions } from './audio-worklet-host' ;
47+ export { AudioWorkletNodeOptions } ;
4448
4549type NativeBaseAudioContext = BaseAudioContext & { native : org . nativescript . audiocontext . AudioContextInstance } ;
4650
@@ -741,6 +745,153 @@ export class OfflineAudioContext extends BaseAudioContext {
741745 }
742746}
743747
748+ let workletScriptPath : string | null = null ;
749+
750+ function workletScript ( ) : string {
751+ if ( ! workletScriptPath ) {
752+ const file = knownFolders . temp ( ) . getFile ( 'ns-audio-worklet-scope.js' ) ;
753+ file . writeTextSync ( SHARED_RING_BRIDGE + '\n' + AUDIO_WORKLET_SCOPE ) ;
754+ workletScriptPath = file . path ;
755+ }
756+ return workletScriptPath ;
757+ }
758+
759+ function readWorkletModule ( source : string ) : Promise < string > {
760+ if ( source . startsWith ( 'data:' ) ) {
761+ const comma = source . indexOf ( ',' ) ;
762+ const data = source . slice ( comma + 1 ) ;
763+ return Promise . resolve ( / ; b a s e 6 4 $ / i. test ( source . slice ( 0 , comma ) ) ? atob ( data ) : decodeURIComponent ( data ) ) ;
764+ }
765+ if ( ! File . exists ( source ) ) return Promise . reject ( new Error ( `${ source } : no such file` ) ) ;
766+ return File . fromPath ( source ) . readText ( ) ;
767+ }
768+
769+ function workletPath ( path : string ) : string {
770+ if ( path . startsWith ( 'file://' ) ) path = decodeURIComponent ( path . slice ( 'file://' . length ) ) ;
771+ return path . startsWith ( '~/' ) ? knownFolders . currentApp ( ) . path + path . slice ( 1 ) : path ;
772+ }
773+
774+ // Header word the native side marks: tells a shared ring from a copy.
775+ const RING_NATIVE_MARK = 5 ;
776+ const RING_CLOSED = 3 ;
777+
778+ let nextWorkletNode = 1 ;
779+ // Connected nodes keep playing without a JS reference, as in browsers.
780+ const connectedWorkletNodes = new Set < AudioWorkletNode > ( ) ;
781+ // The native voice reads the ring until the render thread drops it, a callback after stop().
782+ const stopWorkletNode = ( held : { native : org . nativescript . audiocontext . WorkletSourceNode ; ring : SharedArrayBuffer } ) => {
783+ held . native . stop ( ) ;
784+ setTimeout ( ( ) => held . ring . byteLength , 2000 ) ;
785+ } ;
786+ const workletNodeRegistry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry ( stopWorkletNode ) : null ;
787+
788+ export class AudioWorklet {
789+ private [ context_ ] : AudioContext ;
790+ private _host : WorkletHost | null = null ;
791+
792+ constructor ( a ?: any , context ?: AudioContext ) {
793+ if ( a !== nativeCtor_ || ! context ) throw new TypeError ( 'Illegal constructor.' ) ;
794+ this [ context_ ] = context ;
795+ }
796+
797+ /** @internal */
798+ _scope ( create : boolean ) : WorkletHost | null {
799+ if ( ! this . _host && create ) {
800+ const context = this [ context_ ] ;
801+ this . _host = new WorkletHost ( workletScript ( ) , { scope : 0 , sampleRate : context . sampleRate , addon : '' } , { android : { priority : 'audio' } } ) ;
802+ closeWithContext ?. register ( context , this . _host ) ;
803+ }
804+ return this . _host ;
805+ }
806+
807+ addModule ( moduleURL : string | { href : string } , _options ?: { credentials ?: string } ) : Promise < void > {
808+ let host : WorkletHost ;
809+ try {
810+ if ( this [ context_ ] . state === 'closed' ) throw domError ( 'InvalidStateError' , 'The AudioContext is closed' ) ;
811+ host = this . _scope ( true ) ;
812+ } catch ( e ) {
813+ return Promise . reject ( e ) ;
814+ }
815+ const url = typeof moduleURL === 'string' ? moduleURL : String ( moduleURL ?. href ?? moduleURL ) ;
816+ return loadWorkletModule ( url , readWorkletModule , workletPath ) . then ( ( { source, url } ) => host . addModule ( source , url ) ) ;
817+ }
818+ }
819+
820+ export class AudioWorkletNode extends AudioNode {
821+ readonly port : AudioWorkletPort ;
822+ readonly parameters : AudioParamMap < AudioParam > ;
823+ [ native_ ] : org . nativescript . audiocontext . WorkletSourceNode ;
824+ private _ring : SharedArrayBuffer ;
825+ private _onprocessorerror : ( ( event : any ) => void ) | null = null ;
826+
827+ constructor ( context : AudioContext , name : string , options : AudioWorkletNodeOptions = { } ) {
828+ const worklet = context ?. audioWorklet ;
829+ const resolved = resolveWorkletNodeOptions ( worklet ?. _scope ( false ) , name , options ) ;
830+ const { host, descriptors, numberOfInputs, numberOfOutputs, outputChannelCount, parameterData } = resolved ;
831+ if ( numberOfInputs > 0 ) throw domError ( 'NotSupportedError' , 'AudioWorkletNode: inputs are not supported on Android' ) ;
832+ if ( numberOfOutputs !== 1 ) throw domError ( 'NotSupportedError' , 'AudioWorkletNode: Android supports one output' ) ;
833+ super ( context ) ;
834+ const channels = Math . min ( outputChannelCount ?. [ 0 ] ?? 1 , 8 ) ;
835+ const layout = workletRingLayout ( 0 , [ channels ] , descriptors . length ) ;
836+ const ring = createWorkletRing ( layout ) ;
837+ const offsets = ( Array as any ) . create ( 'int' , 6 ) ;
838+ [ layout . slotWords , layout . header , layout . outputCounts , layout . outputData [ 0 ] , layout . paramLengths , layout . paramData ] . forEach ( ( value , i ) => ( offsets [ i ] = value ) ) ;
839+ const defaults = ( Array as any ) . create ( 'double' , descriptors . length ) ;
840+ descriptors . forEach ( ( d , i ) => ( defaults [ i ] = parameterData ?. [ d . name ] ?? d . defaultValue ) ) ;
841+ const native = AudioContext . getInstance ( ) . createWorkletSource ( context . native , ring as any , channels , offsets , defaults ) ;
842+ if ( ! native ) throw domError ( 'NotSupportedError' , 'AudioWorkletNode: the audio engine is unavailable' ) ;
843+ const header = new Uint32Array ( ring , layout . header * 4 , 8 ) ;
844+ if ( Atomics . load ( header , RING_NATIVE_MARK ) !== 0x574b4c54 ) {
845+ native . stop ( ) ;
846+ throw domError ( 'NotSupportedError' , 'AudioWorkletNode: this runtime copies SharedArrayBuffers passed to native code' ) ;
847+ }
848+ this [ native_ ] = native ;
849+ this . _ring = ring ;
850+ this . parameters = new AudioParamMap ( new Map ( descriptors . map ( ( d , i ) => [ d . name , new AudioParam ( nativeCtor_ , native . getParam ( i ) ) ] ) ) ) ;
851+ const id = nextWorkletNode ++ ;
852+ this . port = new AudioWorkletPort ( host , id ) ;
853+ workletNodeRegistry ?. register ( this , { native, ring } , this ) ;
854+ host . create ( this , id , String ( name ) , { ...options , numberOfInputs, numberOfOutputs, outputChannelCount : [ channels ] , parameterData } , { buffer : ring , layout } ) ;
855+ }
856+
857+ get native ( ) {
858+ return this [ native_ ] ;
859+ }
860+
861+ connect ( node : any , output ?: number , input ?: number ) {
862+ connectedWorkletNodes . add ( this ) ;
863+ return super . connect ( node , output , input ) ;
864+ }
865+
866+ disconnect ( ...args : any [ ] ) {
867+ if ( args . length === 0 ) connectedWorkletNodes . delete ( this ) ;
868+ return ( super . disconnect as any ) ( ...args ) ;
869+ }
870+
871+ get onprocessorerror ( ) {
872+ return this . _onprocessorerror ;
873+ }
874+
875+ set onprocessorerror ( callback : ( ( event : any ) => void ) | null ) {
876+ if ( this . _onprocessorerror ) this . removeEventListener ( 'processorerror' , this . _onprocessorerror ) ;
877+ this . _onprocessorerror = typeof callback === 'function' ? callback : null ;
878+ if ( this . _onprocessorerror ) this . addEventListener ( 'processorerror' , this . _onprocessorerror ) ;
879+ }
880+
881+ /** @internal */
882+ _processorError ( message : string ) {
883+ this . dispatchEvent ( { type : 'processorerror' , message, error : new Error ( message ) , target : this } as any ) ;
884+ }
885+
886+ /** @internal */
887+ _stop ( ) {
888+ workletNodeRegistry ?. unregister ( this ) ;
889+ connectedWorkletNodes . delete ( this ) ;
890+ Atomics . store ( new Uint32Array ( this . _ring , this . _ring . byteLength - 32 , 8 ) , RING_CLOSED , 1 ) ;
891+ stopWorkletNode ( { native : this [ native_ ] , ring : this . _ring } ) ;
892+ }
893+ }
894+
744895let audioContextInstance : org . nativescript . audiocontext . AudioContext | null = null ;
745896
746897export class AudioContext extends BaseAudioContext {
@@ -763,6 +914,13 @@ export class AudioContext extends BaseAudioContext {
763914 this . _setState ( 'running' ) ;
764915 }
765916
917+ private _audioWorklet : AudioWorklet | null = null ;
918+
919+ get audioWorklet ( ) : AudioWorklet | undefined {
920+ if ( ! this . _audioWorklet && isWorkerSupported ( ) ) this . _audioWorklet = new AudioWorklet ( nativeCtor_ , this ) ;
921+ return this . _audioWorklet ?? undefined ;
922+ }
923+
766924 createMediaElementSource ( mediaElement : MediaElementLike ) : MediaElementAudioSourceNode {
767925 return new MediaElementAudioSourceNode ( this , mediaElement ) ;
768926 }
@@ -964,6 +1122,10 @@ export class AudioContext extends BaseAudioContext {
9641122
9651123 close ( ) : Promise < void > {
9661124 if ( this . _state === 'closed' ) return Promise . resolve ( ) ;
1125+ this . _audioWorklet ?. _scope ( false ) ?. close ( ) ;
1126+ connectedWorkletNodes . forEach ( ( node ) => {
1127+ if ( node . context === this ) node . _stop ( ) ;
1128+ } ) ;
9671129 return new Promise ( ( resolve , reject ) => {
9681130 const ref = new WeakRef ( this ) ;
9691131 AudioContext . getInstance ( ) . closeAsync (
0 commit comments