!function(t){"function"==typeof define&&define.amd?define(t):t()}(function(){"use strict";class t{on(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this}once(s,r,a){const n=this;function o(){n.off(s,o);for(var t=arguments.length,e=new Array(t),i=0;i{delete e[t]}),delete this.e}}const r="debug",n="warn",s="talkGetUserMediaSuccess",a="talkGetUserMediaFail",e="talkGetUserMediaTimeout",o="talkStreamClose",h="talkStreamError",l="talkStreamInactive",i={talkStreamClose:o,talkStreamError:h,talkStreamInactive:l,talkGetUserMediaTimeout:e},u="open",c="g711a",d="g711u",f="rtp",p="worklet",g={encType:c,packetType:f,rtpSsrc:"0000000000",numberChannels:1,sampleRate:8e3,sampleBitsWidth:16,debug:!1,debugLevel:n,testMicrophone:!1,audioBufferLength:160,engine:p,checkGetUserMediaTimeout:!1,getUserMediaTimeout:1e4};var m;function k(){return(new Date).getTime()}function b(e){let i="";if("object"==typeof e)try{i=JSON.stringify(e),i=JSON.parse(i)}catch(t){i=e}else i=e;return i}(function(t){var n,e,o,i,s;n="undefined"!=typeof window&&void 0!==window.document?window.document:{},e=t.exports,o=function(){for(var t,e=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,s=e.length,r={};it,this.ratioWeight=1):(this.fromSampleRate{let e,i,s,r,a,n,o,h,l,u=t.length,c=this.channels;if(u%c!=0)throw new Error("Buffer was of incorrect sample length.");if(u<=0)return[];for(e=this.outputBufferSize,i=this.ratioWeight,s=this.lastWeight,r=0,a=0,n=0,o=0,h=this.outputBuffer;s<1;s+=i)for(a=s%1,r=1-a,this.lastWeight=s%1,l=0;l{let e,i,s,r,a,n,o,h,l,u,c,d=t.length,f=this.channels;if(d%f!=0)throw new Error("Buffer was of incorrect sample length.");if(d<=0)return[];for(e=this.outputBufferSize,i=[],s=this.ratioWeight,r=0,n=0,h=!this.tailExists,this.tailExists=!1,l=this.outputBuffer,u=0,c=0,a=0;a=o)){for(a=0;athis.proxy(e,t,i,s));e.addEventListener(t,i,s);var r=()=>{"function"==typeof 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(t=>t())}}class M extends t{constructor(t){var e=1{t.stop()}),this.userMediaStream=null),this.mediaStreamSource&&(this.mediaStreamSource.disconnect(),this.mediaStreamSource=null),this.recorder&&(this.recorder.disconnect(),this.recorder.onaudioprocess=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===u&&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(t){var e=t.length+this.tempRtpBufferList.length,e=new Uint8Array(e);e.set(this.tempRtpBufferList,0),e.set(t,this.tempRtpBufferList.length),this.tempRtpBufferList=e}downloadRtpFile(){var t=new Blob([this.tempRtpBufferList]);try{var e=document.createElement("a");e.href=window.URL.createObjectURL(t),e.download=Date.now()+".rtp",e.click()}catch(t){console.error("downloadRtpFile",t)}}calcAudioBufferLength(){var t=this._opt["sampleRate"];return 8*t*.02/8}get socketStatusOpen(){return this.socketStatus===u}log(){for(var t=arguments.length,e=new Array(t),i=0;i{var i=this.events.proxy;this.socket=new WebSocket(this.wsUrl),this.socket.binaryType="arraybuffer",this.emit("talkStreamStart"),i(this.socket,"open",()=>{this.socketStatus=u,this.log(this.tag,"websocket open -> do talk"),this.emit("talkStreamOpen"),t(),this._doTalk()}),i(this.socket,"message",t=>{this.log(this.tag,"websocket message",t.data)}),i(this.socket,"close",t=>{this.socketStatus="close",this.log(this.tag,"websocket close"),this.emit(o),e(t)}),i(this.socket,"error",t=>{this.socketStatus="error",this.error(this.tag,"websocket error",t),this.emit(h,t),e(t)})})}_sendClose(){}_initTalk(){this._initMethods(),this._opt.engine===p?this._initWorklet():"script"===this._opt.engine&&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 v({fromSampleRate:this.audioContext.sampleRate,toSampleRate:this._opt.sampleRate,channels:this._opt.numberChannels,inputBufferSize:this.bufferSize})}_initScriptProcessor(){var t=this.audioContext.createScriptProcessor||this.audioContext.createJavaScriptNode;this.recorder=t.apply(this.audioContext,[this.bufferSize,this._opt.numberChannels,this._opt.numberChannels]),this.recorder.onaudioprocess=t=>this._onaudioprocess(t)}_initWorklet(){var t;this.audioContext.audioWorklet.addModule((t=function(){class t extends AudioWorkletProcessor{constructor(t){super(),this._cursor=0,this._bufferSize=t.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{var t=new AudioWorkletNode(this.audioContext,"talk-processor",{processorOptions:{bufferSize:this.bufferSize}});t.connect(this.gainNode),t.port.onmessage=t=>{"data"===t.data.eventType&&this._encodeAudioData(t.data.buffer)},this.workletRecorder=t})}_onaudioprocess(t){t=t.inputBuffer.getChannelData(0);this._encodeAudioData(new Float32Array(t))}_encodeAudioData(t){if(0===t[0]&&0===t[1])this.log(this.tag,"empty audio data");else{const s=this.resampler.resample(t);let e=s;if(16===this._opt.sampleBitsWidth?e=function(t){let e=t.length,i=new Int16Array(e);for(;e--;){var s=Math.max(-1,Math.min(1,t[e]));i[e]=s<0?32768*s:32767*s}return i}(s):8===this._opt.sampleBitsWidth&&(e=function(t){let e=t.length,i=new Int8Array(e);for(;e--;){var s=Math.max(-1,Math.min(1,t[e]));i[e]=parseInt(255/(65535/(32768+(s<0?32768*s:32767*s))),10)}return i}(s)),null!==e.buffer){let t=null;this._opt.encType===c?t=function(t){const i=[];return Array.prototype.slice.call(t).forEach((t,e)=>{i[e]=function(t){let e,i,s;return 0<=t?e=213:(e=85,(t=-t-1)<0&&(t=32767)),8<=(i=S(t,_,8))?127^e:(s=i<<4,(s|=i<2?t>>4&15:t>>i+3&15)^e)}(t)}),i}(e):this._opt.encType===d&&(t=function(t){const i=[];return Array.prototype.slice.call(t).forEach((t,e)=>{i[e]=function(t){let e=0;e=t<0?(t=132-t,127):(t+=132,255);var i=S(t,_,8);return 8<=i?127^e:(i<<4|t>>i+3&15)^e}(t)}),i}(e));const s=Uint8Array.from(t);for(let t=0;t>8,e[1]=255&n>>0,e[2]=128,e[3]=128+i,e[4]=s/256,e[5]=s%256,e[6]=r/65536/256,e[7]=r/65536%256,e[8]=r%65536/256,e[9]=r%65536%256,e[10]=a/65536/256,e[11]=a/65536%256,e[12]=a%65536/256,e[13]=a%65536%256,e.concat([...t])),h=new Uint8Array(o.length);for(let t=0;t{this.log(this.tag,"getUserMedia success"),this.userMediaStream=t,this.mediaStreamSource=this.audioContext.createMediaStreamSource(t),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===t.oninactive&&(t.oninactive=t=>{this._handleStreamInactive(t)})}).catch(t=>{this.error(this.tag,"getUserMedia error",t.toString()),this.emit(a,t.toString())}).finally(()=>{this.log(this.tag,"getUserMedia finally"),this._stopCheckGetUserMediaTimeout()})}_getUserMedia2(){this.log(this.tag,"getUserMedia"),navigator.mediaDevices?navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{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{var t=await navigator.mediaDevices.getUserMedia({audio:{latency:!0,noiseSuppression:!0,autoGainControl:!0,echoCancellation:!0,sampleRate:48e3,channelCount:1},video:!1});console.log("getUserMedia() got stream:",t),this.log(this.tag,"getUserMedia3 success")}catch(t){this.log(this.tag,"getUserMedia3 fail")}}_handleStreamInactive(t){this.userMediaStream&&(this.error(this.tag,"stream oninactive"),this.emit(l))}_startCheckGetUserMediaTimeout(){this._stopCheckGetUserMediaTimeout(),this.checkGetUserMediaTimeout=setTimeout(()=>{this.log(this.tag,"check getUserMedia timeout"),this.emit(e)},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");var t=[35,36,0,0,0,0,0,0],t=new Uint8Array(t);this.socket.send(t.buffer)},15e3)}_stopHeartInterval(){this.heartInterval&&(this.log(this.tag,"stop heart interval"),clearInterval(this.heartInterval),this.heartInterval=null)}startTalk(i){return new Promise((t,e)=>function(){let t=!1;var e=window.navigator;return t=e?(t=!(!e.mediaDevices||!e.mediaDevices.getUserMedia))||!!(e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia):t}()?(this.wsUrl=i,this._opt.testMicrophone?(this._doTalk(),t()):(this._createWebSocket().catch(t=>{e(t)}),this.once(a,()=>{e("getUserMedia fail")}),void this.once(s,()=>{t()}))):e("not support getUserMedia"))}setVolume(t){var e;t=parseFloat(t).toFixed(2),isNaN(t)||(e=t,t=Math.max(Math.min(e,Math.max(0,1)),Math.min(0,1)),this.gainNode.gain.value=t)}getOption(){return this._opt}get volume(){return this.gainNode?parseFloat(100*this.gainNode.gain.value).toFixed(0):null}}class U extends t{_opt={};constructor(){var t=0{this.talk.on(i[e],t=>{this.emit(e,t)})})}startTalk(i){let s=1{this.debug.log(this.LOG_TAG,"startTalk",i,JSON.stringify(s)),this._initTalk(s),this.talk.startTalk(i).then(()=>{t(),this.talk.once(o,()=>{this.debug.warn(this.LOG_TAG,"talkStreamClose"),this.stopTalk().catch(t=>{})}),this.talk.once(h,t=>{this.debug.error(this.LOG_TAG,"talkStreamError"),this.stopTalk().catch(t=>{})}),this.talk.once(l,()=>{this.debug.warn(this.LOG_TAG,"talkStreamInactive"),this.stopTalk().catch(t=>{})})}).catch(t=>{e(t)})})}stopTalk(){return new Promise((t,e)=>{this.debug.log(this.LOG_TAG,"stopTalk()"),this.talk||e("talk is not init"),this.talk.destroy(),t()})}getTalkVolume(){return new Promise((t,e)=>{this.talk||e("talk is not init"),t(this.talk.volume)})}setTalkVolume(i){return new Promise((t,e)=>{this.debug.log(this.LOG_TAG,"setTalkVolume",i),this.talk||e("talk is not init"),this.talk.setVolume(i/100),t()})}downloadTempRtpFile(){return new Promise((t,e)=>{this.talk?(this.talk.downloadRtpFile(),t()):e("talk is not init")})}}U.EVENTS=i,window.JessibucaProTalk=U,window.WebPlayerProTalk=U});