jessibuca-pro-talk-demo.js 22.6 KB
!function(t){"function"==typeof define&&define.amd?define(t):t()}(function(){"use strict";class t{on(t,e,i){const s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this}once(s,r,a){const o=this;function n(){o.off(s,n);for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];r.apply(a,e)}return n._=r,this.on(s,n,a)}emit(t){const e=((this.e||(this.e={}))[t]||[]).slice();for(var i=arguments.length,s=new Array(1<i?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];for(let t=0;t<e.length;t+=1)e[t].fn.apply(e[t].ctx,s);return this}off(t,i){const e=this.e||(this.e={});if(!t)return Object.keys(e).forEach(t=>{delete e[t]}),void delete this.e;const s=e[t],r=[];if(s&&i)for(let t=0,e=s.length;t<e;t+=1)s[t].fn!==i&&s[t].fn._!==i&&r.push(s[t]);return r.length?e[t]=r:delete e[t],this}}var e;function u(){return(new Date).getTime()}function i(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 o,e,n,i,s;o="undefined"!=typeof window&&void 0!==window.document?window.document:{},e=t.exports,n=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={};i<s;i++)if((t=e[i])&&t[1]in o){for(i=0;i<t.length;i++)r[e[0][i]]=t[i];return r}return!1}(),i={change:n.fullscreenchange,error:n.fullscreenerror},s={request:function(r,a){return new Promise(function(t,e){var i=function(){this.off("change",i),t()}.bind(this),s=(this.on("change",i),(r=r||o.documentElement)[n.requestFullscreen](a));s instanceof Promise&&s.then(i).catch(e)}.bind(this))},exit:function(){return new Promise(function(t,e){var i,s;this.isFullscreen?(i=function(){this.off("change",i),t()}.bind(this),this.on("change",i),(s=o[n.exitFullscreen]())instanceof Promise&&s.then(i).catch(e)):t()}.bind(this))},toggle:function(t,e){return this.isFullscreen?this.exit():this.request(t,e)},onchange:function(t){this.on("change",t)},onerror:function(t){this.on("error",t)},on:function(t,e){t=i[t];t&&o.addEventListener(t,e,!1)},off:function(t,e){t=i[t];t&&o.removeEventListener(t,e,!1)},raw:n},n?(Object.defineProperties(s,{isFullscreen:{get:function(){return Boolean(o[n.fullscreenElement])}},element:{enumerable:!0,get:function(){return o[n.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(o[n.fullscreenEnabled])}}}),e?t.exports=s:window.screenfull=s):e?t.exports={isEnabled:!1}:window.screenfull={isEnabled:!1}})(e={exports:{}}),e.exports.isEnabled;try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var s=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(s instanceof WebAssembly.Module)new WebAssembly.Instance(s),WebAssembly.Instance}}catch(t){}const o="debug",n="warn",r="talkGetUserMediaSuccess",a="talkGetUserMediaFail",l="talkGetUserMediaTimeout",h="talkStreamClose",c="talkStreamError",d="talkStreamInactive",p="talkFailedAndStop",f={talkStreamClose:h,talkStreamError:c,talkStreamInactive:d,talkGetUserMediaTimeout:l,talkFailedAndStop:p},g="open",m="g711a",k="g711u",b="rtp",w="worklet",_={encType:m,packetType:b,packetTcpSendType:"tcp",rtpSsrc:"0000000000",numberChannels:1,sampleRate:8e3,sampleBitsWidth:16,sendInterval:20,debug:!1,debugLevel:n,testMicrophone:!1,saveRtpToFile:!1,audioBufferLength:160,engine:w,checkGetUserMediaTimeout:!1,getUserMediaTimeout:1e4,audioConstraints:{latency:!0,noiseSuppression:!0,autoGainControl:!0,echoCancellation:!0,sampleRate:48e3,channelCount:1}};class T{constructor(t){var{fromSampleRate:t,toSampleRate:e,channels:i,inputBufferSize:s}=t;if(!t||!e||!i)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=i||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(e){try{return this.outputBuffer.subarray(0,e)}catch(t){try{return this.outputBuffer.length=e,this.outputBuffer}catch(t){return this.outputBuffer.slice(0,e)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch(t){this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e,i,s,r,a,o,n,l,h,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,o=0,n=0,l=this.outputBuffer;s<1;s+=i)for(a=s%1,r=1-a,this.lastWeight=s%1,h=0;h<this.channels;++h)l[n++]=this.lastOutput[h]*r+t[h]*a;for(--s,u-=c,o=Math.floor(s)*c;n<e&&o<u;){for(a=s%1,r=1-a,h=0;h<this.channels;++h)l[n++]=t[o+(0<h?h:0)]*r+t[o+(c+h)]*a;s+=i,o=Math.floor(s)*c}for(h=0;h<c;++h)this.lastOutput[h]=t[o++];return this.bufferSlice(n)}}multiTap(){this.resampler=t=>{let e,i,s,r,a,o,n,l,h,u,c,d=t.length,p=this.channels;if(d%p!=0)throw new Error("Buffer was of incorrect sample length.");if(d<=0)return[];for(e=this.outputBufferSize,i=[],s=this.ratioWeight,r=0,o=0,l=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,u=0,c=0,a=0;a<p;++a)i[a]=0;do{if(l)for(r=s,a=0;a<p;++a)i[a]=0;else{for(r=this.lastWeight,a=0;a<p;++a)i[a]=this.lastOutput[a];l=!0}for(;0<r&&o<d;){if(n=1+o-c,!(r>=n)){for(a=0;a<p;++a)i[a]+=t[o+(0<a?a:0)]*r;c+=r,r=0;break}for(a=0;a<p;++a)i[a]+=t[o++]*n;c=o,r-=n}if(0!==r){for(this.lastWeight=r,a=0;a<p;++a)this.lastOutput[a]=i[a];this.tailExists=!0;break}for(a=0;a<p;++a)h[u++]=i[a]/s}while(o<d&&u<e);return this.bufferSlice(u)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}}const v=[255,511,1023,2047,4095,8191,16383,32767];function y(e,i,s){for(let t=0;t<s;t++)if(e<=i[t])return t;return s}class S{constructor(a){this.log=function(t){if(a._opt.debug&&a._opt.debugLevel==o){for(var e=a._opt.debugUuid?`[${a._opt.debugUuid}]`:"",i=arguments.length,s=new Array(1<i?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];console.log(`JbPro${e}[✅✅✅][${t}]`,...s)}},this.warn=function(t){if(a._opt.debug&&(a._opt.debugLevel==o||a._opt.debugLevel==n)){for(var e=a._opt.debugUuid?`[${a._opt.debugUuid}]`:"",i=arguments.length,s=new Array(1<i?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];console.log(`JbPro${e}[❗❗❗][${t}]`,...s)}},this.error=function(t){for(var e=a._opt.debugUuid?`[${a._opt.debugUuid}]`:"",i=arguments.length,s=new Array(1<i?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];console.error(`JbPro${e}[❌❌❌][${t}]`,...s)}}}class M{constructor(t){this.destroys=[],this.proxy=this.proxy.bind(this),this.master=t}proxy(e,t,i){let s=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{};if(e){if(Array.isArray(t))return t.map(t=>this.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()),this.destroys=[]}}class U extends t{constructor(t){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},t=(super(),this._opt={},t&&(this.player=t),this.tag="talk",i(_));this._opt=Object.assign({},t,e),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="notConnect",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 M(this),this._initTalk(),this.player||(this.debug=new S(this)),this._opt.encType!==m&&this._opt.encType!==k||8e3===this._opt.sampleRate&&16===this._opt.sampleBitsWidth||this.warn(this.tag,`
            encType is ${this._opt.encType} and sampleBitsWidth is ${this._opt.sampleBitsWidth}, set sampleBitsWidth to ${this._opt.sampleBitsWidth}
            ${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(t=>{t.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===g&&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){const e=t.length+this.tempRtpBufferList.length,i=new Uint8Array(e);i.set(this.tempRtpBufferList,0),i.set(t,this.tempRtpBufferList.length),this.tempRtpBufferList=i}downloadRtpFile(){var t=new Blob([this.tempRtpBufferList]);try{const e=document.createElement("a");e.href=window.URL.createObjectURL(t),e.download=Date.now()+".rtp",e.click(),window.URL.revokeObjectURL(e.href)}catch(t){console.error("downloadRtpFile",t)}}calcAudioBufferLength(){var t=this._opt["sampleRate"];return 8*t*.02/8}get socketStatusOpen(){return this.socketStatus===g}log(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this._log("log",...e)}warn(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this._log("warn",...e)}error(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this._log("error",...e)}_log(t){for(var e=arguments.length,i=new Array(1<e?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];(this.player?this.player.debug:this.debug||console)[t](...i)}_getSequenceId(){return++this.sequenceId}_createWebSocket(){return new Promise((t,e)=>{const i=this.events.proxy;this.socket=new WebSocket(this.wsUrl),this.socket.binaryType="arraybuffer",this.emit("talkStreamStart"),i(this.socket,"open",()=>{this.socketStatus=g,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.warn(this.tag,"websocket close -> reject",t),this.emit(h),e(t)}),i(this.socket,"error",t=>{this.socketStatus="error",this.error(this.tag,"websocket error -> reject",t),this.emit(c,t),e(t)})})}_sendClose(){}_initTalk(){this._initMethods(),this._opt.engine===w?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 T({fromSampleRate:this.audioContext.sampleRate,toSampleRate:this._opt.sampleRate,channels:this._opt.numberChannels,inputBufferSize:this.bufferSize})}_initScriptProcessor(){const 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(){e=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<e[0][0].length;t++)this._cursor+=1,this._cursor===this._bufferSize&&(this._cursor=0,this.port.postMessage({eventType:"data",buffer:this._buffer})),this._buffer[this._cursor]=e[0][0][t];return!0}}registerProcessor("talk-processor",t)}.toString().trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1],e=new Blob([e],{type:"application/javascript"});const t=URL.createObjectURL(e);var e;this.audioContext.audioWorklet&&this.audioContext.audioWorklet.addModule(t).then(()=>{const 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}),this.clearWorkletUrlTimeout=setTimeout(()=>{URL.revokeObjectURL(t),this.clearWorkletUrlTimeout=null},1e4)}_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===m?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=y(t,v,8))?127^e:(s=i<<4,(s|=i<2?t>>4&15:t>>i+3&15)^e)}(t)}),i}(e):this._opt.encType===k?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=y(t,v,8);return 8<=i?127^e:(i<<4|t>>i+3&15)^e}(t)}),i}(e):"pcm"===this._opt.encType&&(t=e);const s=new Uint8Array(t);for(let t=0;t<s.length;t++){var i=this.audioBufferList.length;this.audioBufferList[+i]=s[t],this.audioBufferList.length===this._opt.audioBufferLength&&(this._sendTalkMsg(new Uint8Array(this.audioBufferList)),this.audioBufferList=[])}}}}_parseAudioMsg(t){let e=null;return this._opt.packetType!==b||this._opt.encType!==m&&this._opt.encType!==k?"empty"===this._opt.packetType&&(e=t):e=this.rtpPacket(t),e}rtpPacket(t){const e=[];let i=0,s,r;var a=this._opt.rtpSsrc,o=t.length;this._opt.encType===m?i=8:this._opt.encType===k?i=0:"opus"===this._opt.encType&&(i=98),this.startTimestamp||(this.startTimestamp=u()),r=u()-this.startTimestamp,s=this._getSequenceId();let n=0;if("tcp"===this._opt.packetTcpSendType){const t=o+12;e[n++]=255&t>>8,e[n++]=255&t>>0}e[n++]=128,e[n++]=128+i,e[n++]=s/256,e[n++]=s%256,e[n++]=r/65536/256,e[n++]=r/65536%256,e[n++]=r%65536/256,e[n++]=r%65536%256,e[n++]=a/65536/256,e[n++]=a/65536%256,e[n++]=a%65536/256,e[n++]=a%65536%256;let l=e.concat([...t]),h=new Uint8Array(l.length);for(let t=0;t<l.length;t++)h[t]=l[t];return h}opusPacket(t){return t}_sendTalkMsg(t){null===this.tempTimestamp&&(this.tempTimestamp=u());var e=u(),i=e-this.tempTimestamp,s=this._parseAudioMsg(t);this.log(this.tag,`'send talk msg and diff is ${i} and byteLength is ${s.byteLength} and length is ${s.length}, and g711 length is `+t.length),!0!==(i=this._opt.saveRtpToFile)&&"true"!==i||this._opt.packetType!==b||this.addRtpToBuffer(s),s&&(this.socketStatusOpen?this.socket.send(s.buffer):this.emit("tallWebsocketClosedByError")),this.tempTimestamp=e}_doTalk(){this._getUserMedia()}_getUserMedia(){this.log(this.tag,"getUserMedia"),void 0===window.navigator.mediaDevices&&(window.navigator.mediaDevices={}),void 0===window.navigator.mediaDevices.getUserMedia&&(this.log(this.tag,"window.navigator.mediaDevices.getUserMedia is undefined and init function"),window.navigator.mediaDevices.getUserMedia=function(i){var s=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;return s?new Promise(function(t,e){s.call(navigator,i,t,e)}):Promise.reject(new Error("getUserMedia is not implemented in this browser"))}),this._opt.checkGetUserMediaTimeout&&this._startCheckGetUserMediaTimeout(),window.navigator.mediaDevices.getUserMedia({audio:this._opt.audioConstraints,video:!1}).then(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(r),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.warn(this.tag,"stream oninactive",t),this.emit(d))}_startCheckGetUserMediaTimeout(){this._stopCheckGetUserMediaTimeout(),this.checkGetUserMediaTimeout=setTimeout(()=>{this.log(this.tag,"check getUserMedia timeout"),this.emit(l)},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)=>{if(!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}())return e("not support getUserMedia");if(this.wsUrl=i,this._opt.testMicrophone)this._doTalk();else{if(!this.wsUrl)return e("wsUrl is null");this._createWebSocket().catch(t=>{e(t)})}this.once(a,()=>{e("getUserMedia fail")}),this.once(r,()=>{t()})})}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 R extends t{constructor(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};super(),this.talk=null,this._opt=t,this.LOG_TAG="JessibucaProTalk",this.debug=new S(this),this.debug.log(this.LOG_TAG,"init",JSON.stringify(t))}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(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=(this.talk&&(this.debug.log(this.LOG_TAG,"_initTalk this.talk is not null and destroy"),this.talk.destroy(),this.talk=null),Object.assign({},i(this._opt),t));this.talk=new U(null,t),this.debug.log(this.LOG_TAG,"_initTalk",this.talk.getOption()),this._bindTalkEvents()}_bindTalkEvents(){Object.keys(f).forEach(e=>{this.talk.on(f[e],t=>{this.emit(e,t)})})}startTalk(i){let s=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return new Promise((t,e)=>{this.debug.log(this.LOG_TAG,"startTalk",i,JSON.stringify(s)),this._initTalk(s),this.talk.startTalk(i).then(()=>{t(),this.talk.once(h,()=>{this.debug.warn(this.LOG_TAG,"talkStreamClose -> stopTalk"),this.stopTalk().catch(t=>{this.debug.warn(this.LOG_TAG,"talkStreamClose stopTalk",t)}).finally(()=>{this.emit(p,h)})}),this.talk.once(c,t=>{this.debug.error(this.LOG_TAG,"talkStreamError -> stopTalk"),this.stopTalk().catch(t=>{this.debug.warn(this.LOG_TAG,"talkStreamError stopTalk",t)}).finally(()=>{this.emit(p,c)})}),this.talk.once(d,()=>{this.debug.warn(this.LOG_TAG,"talkStreamInactive -> stopTalk"),this.stopTalk().catch(t=>{this.debug.warn(this.LOG_TAG,"talkStreamInactive stopTalk",t)}).finally(()=>{this.emit(p,d)})}),this.talk.once(l,()=>{this.debug.warn(this.LOG_TAG,"talkGetUserMediaTimeout -> stopTalk"),this.stopTalk().catch(t=>{this.debug.warn(this.LOG_TAG,"talkGetUserMediaTimeout stopTalk",t)}).finally(()=>{this.emit(p,l)})})}).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(),this.talk=null,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")})}}R.EVENTS=f,window.JessibucaProTalk=R,window.WebPlayerProTalk=R});