!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";class e{on(e,t,i){const s=this.e||(this.e={});return(s[e]||(s[e]=[])).push({fn:t,ctx:i}),this}once(e,t,i){const s=this;function r(){s.off(e,r);for(var o=arguments.length,a=new Array(o),n=0;n1?i-1:0),r=1;r{delete i[e]})),void delete this.e;const s=i[e],r=[];if(s&&t)for(let e=0,i=s.length;e{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}})();class N{constructor(e){const{fromSampleRate:t,toSampleRate:i,channels:s,inputBufferSize:r}=e;if(!t||!i||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=i,this.channels=s||0,this.inputBufferSize=r,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=e=>e,this.ratioWeight=1):(this.fromSampleRate{let t,i,s,r,o,a,n,l,h,u=e.length,c=this.channels;if(u%c!=0)throw new Error("Buffer was of incorrect sample length.");if(u<=0)return[];for(t=this.outputBufferSize,i=this.ratioWeight,s=this.lastWeight,r=0,o=0,a=0,n=0,l=this.outputBuffer;s<1;s+=i)for(o=s%1,r=1-o,this.lastWeight=s%1,h=0;h0?h:0)]*r+e[a+(c+h)]*o;s+=i,a=Math.floor(s)*c}for(h=0;h{let t,i,s,r,o,a,n,l,h,u,c,d=e.length,p=this.channels;if(d%p!=0)throw new Error("Buffer was of incorrect sample length.");if(d<=0)return[];for(t=this.outputBufferSize,i=[],s=this.ratioWeight,r=0,a=0,n=0,l=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,u=0,c=0,o=0;o0&&a=n)){for(o=0;o0?o:0)]*r;c+=r,r=0;break}for(o=0;o{t[i]=function(e){let t,i,s;return e>=0?t=213:(t=85,(e=-e-1)<0&&(e=32767)),i=z(e,P,8),i>=8?127^t:(s=i<<4,s|=i<2?e>>4&15:e>>i+3&15,s^t)}(e)})),t}function $(e){const t=[];return Array.prototype.slice.call(e).forEach(((e,i)=>{t[i]=function(e){let t=0;e<0?(e=132-e,t=127):(e+=132,t=255);let i=z(e,P,8);return i>=8?127^t:(i<<4|e>>i+3&15)^t}(e)})),t}class H{constructor(e){this.log=function(i){if(e._opt.debug&&e._opt.debugLevel==t){const t=e._opt.debugUuid?`[${e._opt.debugUuid}]`:"";for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o1?r-1:0),a=1;a1?s-1:0),o=1;o3&&void 0!==arguments[3]?arguments[3]:{};if(!e)return;if(Array.isArray(t))return t.map((t=>this.proxy(e,t,i,s)));e.addEventListener(t,i,s);const r=()=>{(function(e){return"function"==typeof e})(e.removeEventListener)&&e.removeEventListener(t,i,s)};return this.destroys.push(r),r}destroy(){this.master.debug&&this.master.debug.log("Events","destroy"),this.destroys.forEach((e=>e())),this.destroys=[]}}class V extends e{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this._opt={},e&&(this.player=e),this.tag="talk";const i=D(F);this._opt=Object.assign({},i,t),this._opt.sampleRate=parseInt(this._opt.sampleRate,10),this._opt.sampleBitsWidth=parseInt(this._opt.sampleBitsWidth,10),this.audioContext=null,this.gainNode=null,this.recorder=null,this.workletRecorder=null,this.biquadFilter=null,this.userMediaStream=null,this.clearWorkletUrlTimeout=null,this.bufferSize=512,this._opt.audioBufferLength=this.calcAudioBufferLength(),this.audioBufferList=[],this.socket=null,this.socketStatus=f,this.mediaStreamSource=null,this.heartInterval=null,this.checkGetUserMediaTimeout=null,this.wsUrl=null,this.startTimestamp=0,this.sequenceId=0,this.tempTimestamp=null,this.tempRtpBufferList=[],this.events=new j(this),this._initTalk(),this.player||(this.debug=new H(this)),this._opt.encType!==w&&this._opt.encType!==b||8e3===this._opt.sampleRate&&16===this._opt.sampleBitsWidth||this.warn(this.tag,`\n encType is ${this._opt.encType} and sampleBitsWidth is ${this._opt.sampleBitsWidth}, set sampleBitsWidth to ${this._opt.sampleBitsWidth}。\n ${this._opt.encType} only support sampleRate 8000 and sampleBitsWidth 16`),this.log(this.tag,"init",JSON.stringify(this._opt))}destroy(){this.clearWorkletUrlTimeout&&(clearTimeout(this.clearWorkletUrlTimeout),this.clearWorkletUrlTimeout=null),this.userMediaStream&&(this.userMediaStream.getTracks&&this.userMediaStream.getTracks().forEach((e=>{e.stop()})),this.userMediaStream=null),this.mediaStreamSource&&(this.mediaStreamSource.disconnect(),this.mediaStreamSource=null),this.recorder&&(this.recorder.disconnect(),this.recorder.onaudioprocess=null,this.recorder=null),this.biquadFilter&&(this.biquadFilter.disconnect(),this.biquadFilter=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.workletRecorder&&(this.workletRecorder.disconnect(),this.workletRecorder=null),this.socket&&(this.socketStatus===m&&this._sendClose(),this.socket.close(),this.socket=null),this._stopHeartInterval(),this._stopCheckGetUserMediaTimeout(),this.audioContext=null,this.gainNode=null,this.recorder=null,this.audioBufferList=[],this.sequenceId=0,this.wsUrl=null,this.tempTimestamp=null,this.tempRtpBufferList=[],this.startTimestamp=0,this.log("talk","destroy")}addRtpToBuffer(e){const t=e.length+this.tempRtpBufferList.length,i=new Uint8Array(t);i.set(this.tempRtpBufferList,0),i.set(e,this.tempRtpBufferList.length),this.tempRtpBufferList=i}downloadRtpFile(){const e=new Blob([this.tempRtpBufferList]);try{const t=document.createElement("a");t.href=window.URL.createObjectURL(e),t.download=Date.now()+".rtp",t.click(),window.URL.revokeObjectURL(t.href)}catch(e){console.error("downloadRtpFile",e)}}calcAudioBufferLength(){const{sampleRate:e,sampleBitsWidth:t}=this._opt;return 8*e*.02/8}get socketStatusOpen(){return this.socketStatus===m}log(){for(var e=arguments.length,t=new Array(e),i=0;i1?t-1:0),s=1;s{const i=this.events.proxy;this.socket=new WebSocket(this.wsUrl),this.socket.binaryType="arraybuffer",this.emit(a),i(this.socket,C,(()=>{this.socketStatus=m,this.log(this.tag,"websocket open -> do talk"),this.emit(n),e(),this._doTalk()})),i(this.socket,A,(e=>{this.log(this.tag,"websocket message",e.data)})),i(this.socket,R,(e=>{this.socketStatus=g,this.warn(this.tag,"websocket close -> reject",e),this.emit(l),t(e)})),i(this.socket,B,(e=>{this.socketStatus=k,this.error(this.tag,"websocket error -> reject",e),this.emit(h,e),t(e)}))}))}_sendClose(){}_initTalk(){this._initMethods(),this._opt.engine===G?this._initWorklet():this._opt.engine===W&&this._initScriptProcessor(),this.log(this.tag,"audioContext samplerate",this.audioContext.sampleRate)}_initMethods(){this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:48e3}),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=1,this.biquadFilter=this.audioContext.createBiquadFilter(),this.biquadFilter.type="lowpass",this.biquadFilter.frequency.value=3e3,this.resampler=new N({fromSampleRate:this.audioContext.sampleRate,toSampleRate:this._opt.sampleRate,channels:this._opt.numberChannels,inputBufferSize:this.bufferSize})}_initScriptProcessor(){const e=this.audioContext.createScriptProcessor||this.audioContext.createJavaScriptNode;this.recorder=e.apply(this.audioContext,[this.bufferSize,this._opt.numberChannels,this._opt.numberChannels]),this.recorder.onaudioprocess=e=>this._onaudioprocess(e)}_initWorklet(){const e=function(e){const t=e.toString().trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1],i=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(i)}((function(){class e extends AudioWorkletProcessor{constructor(e){super(),this._cursor=0,this._bufferSize=e.processorOptions.bufferSize,this._buffer=new Float32Array(this._bufferSize)}process(e,t,i){if(!e.length||!e[0].length)return!0;for(let t=0;t{const e=new AudioWorkletNode(this.audioContext,"talk-processor",{processorOptions:{bufferSize:this.bufferSize}});e.connect(this.gainNode),e.port.onmessage=e=>{"data"===e.data.eventType&&this._encodeAudioData(e.data.buffer)},this.workletRecorder=e})),this.clearWorkletUrlTimeout=setTimeout((()=>{URL.revokeObjectURL(e),this.clearWorkletUrlTimeout=null}),1e4)}_onaudioprocess(e){const t=e.inputBuffer.getChannelData(0);this._encodeAudioData(new Float32Array(t))}_encodeAudioData(e){if(0===e[0]&&0===e[1])return void this.log(this.tag,"empty audio data");const t=this.resampler.resample(e);let i=t;if(16===this._opt.sampleBitsWidth?i=function(e){let t=e.length,i=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,e[t]));i[t]=s<0?32768*s:32767*s}return i}(t):8===this._opt.sampleBitsWidth&&(i=function(e){let t=e.length,i=new Int8Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,e[t]));const r=s<0?32768*s:32767*s;i[t]=parseInt(255/(65535/(32768+r)),10)}return i}(t)),null!==i.buffer){let e=null;this._opt.encType===w?e=q(i):this._opt.encType===b?e=$(i):this._opt.encType===S&&(e=i);const t=new Uint8Array(e);for(let e=0;e>8,t[n++]=255&e>>0}t[n++]=128,t[n++]=128+i,t[n++]=s/256,t[n++]=s%256,t[n++]=r/65536/256,t[n++]=r/65536%256,t[n++]=r%65536/256,t[n++]=r%65536%256,t[n++]=o/65536/256,t[n++]=o/65536%256,t[n++]=o%65536/256,t[n++]=o%65536%256;let l=t.concat([...e]),h=new Uint8Array(l.length);for(let e=0;e{this.log(this.tag,"getUserMedia success"),this.userMediaStream=e,this.mediaStreamSource=this.audioContext.createMediaStreamSource(e),this.mediaStreamSource.connect(this.biquadFilter),this.recorder?(this.biquadFilter.connect(this.recorder),this.recorder.connect(this.gainNode)):this.workletRecorder&&(this.biquadFilter.connect(this.workletRecorder),this.workletRecorder.connect(this.gainNode)),this.gainNode.connect(this.audioContext.destination),this.emit(s),null===e.oninactive&&(e.oninactive=e=>{this._handleStreamInactive(e)})})).catch((e=>{this.error(this.tag,"getUserMedia error",e.toString()),this.emit(r,e.toString())})).finally((()=>{this.log(this.tag,"getUserMedia finally"),this._stopCheckGetUserMediaTimeout()}))}_getUserMedia2(){this.log(this.tag,"getUserMedia"),navigator.mediaDevices?navigator.mediaDevices.getUserMedia({audio:!0}).then((e=>{this.log(this.tag,"getUserMedia2 success")})):navigator.getUserMedia({audio:!0},this.log(this.tag,"getUserMedia2 success"),this.log(this.tag,"getUserMedia2 fail"))}async _getUserMedia3(){this.log(this.tag,"getUserMedia3");try{const e=await navigator.mediaDevices.getUserMedia({audio:{latency:!0,noiseSuppression:!0,autoGainControl:!0,echoCancellation:!0,sampleRate:48e3,channelCount:1},video:!1});console.log("getUserMedia() got stream:",e),this.log(this.tag,"getUserMedia3 success")}catch(e){this.log(this.tag,"getUserMedia3 fail")}}_handleStreamInactive(e){this.userMediaStream&&(this.warn(this.tag,"stream oninactive",e),this.emit(u))}_startCheckGetUserMediaTimeout(){this._stopCheckGetUserMediaTimeout(),this.checkGetUserMediaTimeout=setTimeout((()=>{this.log(this.tag,"check getUserMedia timeout"),this.emit(o)}),this._opt.getUserMediaTimeout)}_stopCheckGetUserMediaTimeout(){this.checkGetUserMediaTimeout&&(this.log(this.tag,"stop checkGetUserMediaTimeout"),clearTimeout(this.checkGetUserMediaTimeout),this.checkGetUserMediaTimeout=null)}_startHeartInterval(){this.heartInterval=setInterval((()=>{this.log(this.tag,"heart interval");let e=[35,36,0,0,0,0,0,0];e=new Uint8Array(e),this.socket.send(e.buffer)}),15e3)}_stopHeartInterval(){this.heartInterval&&(this.log(this.tag,"stop heart interval"),clearInterval(this.heartInterval),this.heartInterval=null)}startTalk(e){return new Promise(((t,i)=>{if(!function(){let e=!1;const t=window.navigator;return t&&(e=!(!t.mediaDevices||!t.mediaDevices.getUserMedia),e||(e=!!(t.getUserMedia||t.webkitGetUserMedia||t.mozGetUserMedia||t.msGetUserMedia))),e}())return i("not support getUserMedia");if(this.wsUrl=e,this._opt.testMicrophone)this._doTalk();else{if(!this.wsUrl)return i("wsUrl is null");this._createWebSocket().catch((e=>{i(e)}))}this.once(r,(()=>{i("getUserMedia fail")})),this.once(s,(()=>{t()}))}))}setVolume(e){var t,i,s;(e=parseFloat(e).toFixed(2),isNaN(e))||(t=e,i=0,s=1,e=Math.max(Math.min(t,Math.max(i,s)),Math.min(i,s)),this.gainNode.gain.value=e)}getOption(){return this._opt}get volume(){return this.gainNode?parseFloat(100*this.gainNode.gain.value).toFixed(0):null}}class J extends e{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.talk=null,this._opt=e,this.LOG_TAG="JessibucaProTalk",this.debug=new H(this),this.debug.log(this.LOG_TAG,"init",JSON.stringify(e))}destroy(){this.debug.log(this.LOG_TAG,"destroy()"),this.off(),this.talk&&(this.talk.destroy(),this.talk=null),this.debug.log(this.LOG_TAG,"destroy")}_initTalk(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.talk&&(this.debug.log(this.LOG_TAG,"_initTalk this.talk is not null and destroy"),this.talk.destroy(),this.talk=null);const t=Object.assign({},D(this._opt),e);this.talk=new V(null,t),this.debug.log(this.LOG_TAG,"_initTalk",this.talk.getOption()),this._bindTalkEvents()}_bindTalkEvents(){Object.keys(d).forEach((e=>{this.talk.on(d[e],(t=>{this.emit(e,t)}))}))}startTalk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(((i,s)=>{this.debug.log(this.LOG_TAG,"startTalk",e,JSON.stringify(t)),this._initTalk(t),this.talk.startTalk(e).then((()=>{i(),this.talk.once(l,(()=>{this.debug.warn(this.LOG_TAG,"talkStreamClose -> stopTalk"),this.stopTalk().catch((e=>{this.debug.warn(this.LOG_TAG,"talkStreamClose stopTalk",e)})).finally((()=>{this.emit(c,l)}))})),this.talk.once(h,(e=>{this.debug.error(this.LOG_TAG,"talkStreamError -> stopTalk"),this.stopTalk().catch((e=>{this.debug.warn(this.LOG_TAG,"talkStreamError stopTalk",e)})).finally((()=>{this.emit(c,h)}))})),this.talk.once(u,(()=>{this.debug.warn(this.LOG_TAG,"talkStreamInactive -> stopTalk"),this.stopTalk().catch((e=>{this.debug.warn(this.LOG_TAG,"talkStreamInactive stopTalk",e)})).finally((()=>{this.emit(c,u)}))})),this.talk.once(o,(()=>{this.debug.warn(this.LOG_TAG,"talkGetUserMediaTimeout -> stopTalk"),this.stopTalk().catch((e=>{this.debug.warn(this.LOG_TAG,"talkGetUserMediaTimeout stopTalk",e)})).finally((()=>{this.emit(c,o)}))}))})).catch((e=>{s(e)}))}))}stopTalk(){return new Promise(((e,t)=>{this.debug.log(this.LOG_TAG,"stopTalk()"),this.talk||t("talk is not init"),this.talk.destroy(),this.talk=null,e()}))}getTalkVolume(){return new Promise(((e,t)=>{this.talk||t("talk is not init"),e(this.talk.volume)}))}setTalkVolume(e){return new Promise(((t,i)=>{this.debug.log(this.LOG_TAG,"setTalkVolume",e),this.talk||i("talk is not init"),this.talk.setVolume(e/100),t()}))}downloadTempRtpFile(){return new Promise(((e,t)=>{this.talk?(this.talk.downloadRtpFile(),e()):t("talk is not init")}))}}J.EVENTS=d,window.JessibucaProTalk=J,window.WebPlayerProTalk=J}));