!function(){"use strict";function getTagged(tag){return taggedLoggers.has(tag)||taggedLoggers.set(tag,new Logger(DEFAULT_LOG_LEVEL,tag)),taggedLoggers.get(tag)}function __async(g){return new Promise(function(s,j){function c(a,x){try{var r=g[x?"throw":"next"](a)}catch(e){return void j(e)}r.done?s(r.value):Promise.resolve(r.value).then(c,d)}function d(e){c(e,1)}c()})}function base64ToArrayBuffer(base64){for(var binary_string=window.atob(base64),len=binary_string.length,bytes=new Uint8Array(len),i=0;i>1,bufView=new Uint8Array(len),i=0;i>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function md5cmn(q,a,b,x,s,t){return safeAdd(function(num,cnt){return num<>>32-cnt}(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b)}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}function binlMD5(x,len){x[len>>5]|=128<>>9<<4)]=len;var i,olda,oldb,oldc,oldd,a=1732584193,b=-271733879,c=-1732584194,d=271733878;for(i=0;i>5]>>>i%32&255);return output}function rstr2binl(input){var i,output=[];for(output[(input.length>>2)-1]=void 0,i=0;i>5]|=(255&input.charCodeAt(i/8))<>>4&15)+"0123456789abcdef".charAt(15&x);return output}function str2rstrUTF8(input){return unescape(encodeURIComponent(input))}function rawMD5(s){return function(s){return binl2rstr(binlMD5(rstr2binl(s),8*s.length))}(str2rstrUTF8(s))}function rawHMACMD5(k,d){return function(key,data){var i,hash,bkey=rstr2binl(key),ipad=[],opad=[];for(ipad[15]=opad[15]=void 0,bkey.length>16&&(bkey=binlMD5(bkey,8*key.length)),i=0;i<16;i+=1)ipad[i]=909522486^bkey[i],opad[i]=1549556828^bkey[i];return hash=binlMD5(ipad.concat(rstr2binl(data)),512+8*data.length),binl2rstr(binlMD5(opad.concat(hash),640))}(str2rstrUTF8(k),str2rstrUTF8(d))}function md5(string,key,raw){return key?raw?rawHMACMD5(key,string):function(k,d){return rstr2hex(rawHMACMD5(k,d))}(key,string):raw?rawMD5(string):function(s){return rstr2hex(rawMD5(s))}(string)}function rng_get_byte(){if(null==rng_state){for(rng_state=new Arcfour;rng_pptr>>16)&&(x=t,r+=16),0!=(t=x>>8)&&(x=t,r+=8),0!=(t=x>>4)&&(x=t,r+=4),0!=(t=x>>2)&&(x=t,r+=2),0!=(t=x>>1)&&(x=t,r+=1),r}function op_and(x,y){return x&y}function op_or(x,y){return x|y}function op_xor(x,y){return x^y}function op_andnot(x,y){return x&~y}function lbit(x){if(0==x)return-1;var r=0;return 0==(65535&x)&&(x>>=16,r+=16),0==(255&x)&&(x>>=8,r+=8),0==(15&x)&&(x>>=4,r+=4),0==(3&x)&&(x>>=2,r+=2),0==(1&x)&&++r,r}function cbit(x){for(var r=0;0!=x;)x&=x-1,++r;return r}function NullExp(){}function nNop(x){return x}function Barrett(m){this.r2=nbi(),this.q3=nbi(),BigInteger.ONE.dlShiftTo(2*m.t,this.r2),this.mu=this.r2.divide(m),this.m=m}function parseBigInt(str,r){return new BigInteger(str,r)}function hex2b64(h){var i,c,ret="";for(i=0;i+3<=h.length;i+=3)c=parseInt(h.substring(i,i+3),16),ret+=b64map.charAt(c>>6)+b64map.charAt(63&c);for(i+1==h.length?(c=parseInt(h.substring(i,i+1),16),ret+=b64map.charAt(c<<2)):i+2==h.length&&(c=parseInt(h.substring(i,i+2),16),ret+=b64map.charAt(c>>2)+b64map.charAt((3&c)<<4));(3&ret.length)>0;)ret+=b64pad;return ret}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")},createClass=function(){function defineProperties(target,props){for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:DEFAULT_LOG_LEVEL,tag=arguments[1];classCallCheck(this,Logger),this.tag=tag,this.setLevel(level)}return createClass(Logger,[{key:"setLevel",value:function(level){this.level=level}},{key:"_log",value:function(lvl,args){args=Array.prototype.slice.call(args),this.tag&&args.unshift("["+this.tag+"]"),this.level>=lvl&&console[Logger.level_map[lvl]].apply(console,args)}},{key:"log",value:function(){this._log(LogLevel_Log,arguments)}},{key:"debug",value:function(){this._log(LogLevel_Debug,arguments)}},{key:"error",value:function(){this._log(LogLevel_Error,arguments)}},{key:"warn",value:function(){this._log(LogLevel_Warn,arguments)}}],[{key:"level_map",get:function(){var _ref;return _ref={},defineProperty(_ref,LogLevel_Debug,"log"),defineProperty(_ref,LogLevel_Log,"log"),defineProperty(_ref,LogLevel_Warn,"warn"),defineProperty(_ref,LogLevel_Error,"error"),_ref}}]),Logger}(),taggedLoggers=new Map,Log=new Logger,Url=function(){function Url(){classCallCheck(this,Url)}return createClass(Url,null,[{key:"parse",value:function(url){var ret={},result=/^([^:]+):\/\/([^\/]+)(.*)$/.exec(url);if(!result)throw new Error("bad url");ret.full=url,ret.protocol=result[1],ret.urlpath=result[3];var parts=ret.urlpath.split("/");ret.basename=parts.pop().split(/\?|#/)[0],ret.basepath=parts.join("/");var loginSplit=result[2].split("@"),hostport=loginSplit[0].split(":"),userpass=[null,null];return 2===loginSplit.length&&(userpass=loginSplit[0].split(":"),hostport=loginSplit[1].split(":")),ret.user=userpass[0],ret.pass=userpass[1],ret.host=hostport[0],ret.auth=ret.user&&ret.pass?ret.user+":"+ret.pass:"",ret.port=null==hostport[1]?Url.protocolDefaultPort(ret.protocol):hostport[1],ret.portDefined=null!=hostport[1],ret.location=ret.host+":"+ret.port,"unix"==ret.protocol&&(ret.socket=ret.port,ret.port=void 0),ret}},{key:"full",value:function(parsed){return parsed.protocol+"://"+(parsed.auth?parsed.auth+"@":"")+parsed.location+"/"+parsed.urlpath}},{key:"isAbsolute",value:function(url){return/^[^:]+:\/\//.test(url)}},{key:"protocolDefaultPort",value:function(protocol){switch(protocol){case"rtsp":return 554;case"http":return 80;case"https":return 443}return 0}}]),Url}(),listener=Symbol("event_listener"),listeners=Symbol("event_listeners"),DestructibleEventListener=function(){function DestructibleEventListener(eventListener){classCallCheck(this,DestructibleEventListener),this[listener]=eventListener,this[listeners]=new Map}return createClass(DestructibleEventListener,[{key:"clear",value:function(){if(this[listeners]){var _iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=this[listeners][Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var entry=_step.value,_iteratorNormalCompletion2=!0,_didIteratorError2=!1,_iteratorError2=void 0;try{for(var _step2,_iterator2=entry[1][Symbol.iterator]();!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=!0){var fn=_step2.value;this[listener].removeEventListener(entry[0],fn)}}catch(err){_didIteratorError2=!0,_iteratorError2=err}finally{try{!_iteratorNormalCompletion2&&_iterator2.return&&_iterator2.return()}finally{if(_didIteratorError2)throw _iteratorError2}}}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}}this[listeners].clear()}},{key:"destroy",value:function(){this.clear(),this[listeners]=null}},{key:"on",value:function(event,selector,fn){return void 0==fn&&(fn=selector,selector=null),selector?this.addEventListener(event,function(e){e.target.matches(selector)&&fn(e)}):this.addEventListener(event,fn)}},{key:"addEventListener",value:function(event,fn){return this[listeners].has(event)||this[listeners].set(event,new Set),this[listeners].get(event).add(fn),this[listener].addEventListener(event,fn,!1),fn}},{key:"removeEventListener",value:function(event,fn){if(this[listener].removeEventListener(event,fn,!1),this[listeners].has(event)){var ev=this[listeners].get(event);ev.delete(fn),ev.size||this[listeners].delete(event)}}},{key:"dispatchEvent",value:function(event){this[listener]&&this[listener].dispatchEvent(event)}}]),DestructibleEventListener}(),EventEmitter=function(){function EventEmitter(){var element=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;classCallCheck(this,EventEmitter),this[listener]=new DestructibleEventListener(element||document.createElement("div"))}return createClass(EventEmitter,[{key:"clear",value:function(){this[listener]&&this[listener].clear()}},{key:"destroy",value:function(){this[listener]&&(this[listener].destroy(),this[listener]=null)}},{key:"on",value:function(event,selector,fn){return this[listener]?this[listener].on(event,selector,fn):null}},{key:"addEventListener",value:function(event,fn){return this[listener]?this[listener].addEventListener(event,fn,!1):null}},{key:"removeEventListener",value:function(event,fn){this[listener]&&this[listener].removeEventListener(event,fn,!1)}},{key:"dispatchEvent",value:function(event,data){this[listener]&&this[listener].dispatchEvent(new CustomEvent(event,{detail:data}))}}]),EventEmitter}(),EventSourceWrapper=function(){function EventSourceWrapper(eventSource){classCallCheck(this,EventSourceWrapper),this.eventSource=eventSource,this[listeners]=new Map}return createClass(EventSourceWrapper,[{key:"on",value:function(event,selector,fn){this[listeners].has(event)||this[listeners].set(event,new Set);var listener=this.eventSource.on(event,selector,fn);listener&&this[listeners].get(event).add(listener)}},{key:"off",value:function(event,fn){this.eventSource.removeEventListener(event,fn)}},{key:"clear",value:function(){this.eventSource.clear(),this[listeners].clear()}},{key:"destroy",value:function(){this.eventSource.clear(),this[listeners]=null,this.eventSource=null}}]),EventSourceWrapper}(),MP4=function(){function MP4(){classCallCheck(this,MP4)}return createClass(MP4,null,[{key:"init",value:function(){MP4.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};var i;for(i in MP4.types)MP4.types.hasOwnProperty(i)&&(MP4.types[i]=[i.charCodeAt(0),i.charCodeAt(1),i.charCodeAt(2),i.charCodeAt(3)]);var videoHdlr=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audioHdlr=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={video:videoHdlr,audio:audioHdlr};var dref=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),stco=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=stco,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var majorBrand=new Uint8Array([105,115,111,109]),avc1Brand=new Uint8Array([97,118,99,49]),minorVersion=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,majorBrand,minorVersion,majorBrand,avc1Brand),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,dref))}},{key:"box",value:function(type){for(var _len=arguments.length,payload=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)payload[_key-1]=arguments[_key];for(var result,size=8,i=payload.length,len=i;i--;)size+=payload[i].byteLength;for((result=new Uint8Array(size))[0]=size>>24&255,result[1]=size>>16&255,result[2]=size>>8&255,result[3]=255&size,result.set(type,4),i=0,size=8;i>24&255,timescale>>16&255,timescale>>8&255,255×cale,duration>>24,duration>>16&255,duration>>8&255,255&duration,85,196,0,0]))}},{key:"mdia",value:function(track){return MP4.box(MP4.types.mdia,MP4.mdhd(track.timescale,track.duration),MP4.hdlr(track.type),MP4.minf(track))}},{key:"mfhd",value:function(sequenceNumber){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,sequenceNumber>>24,sequenceNumber>>16&255,sequenceNumber>>8&255,255&sequenceNumber]))}},{key:"minf",value:function(track){return"audio"===track.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(track)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(track))}},{key:"moof",value:function(sn,baseMediaDecodeTime,track){return MP4.box(MP4.types.moof,MP4.mfhd(sn),MP4.traf(track,baseMediaDecodeTime))}},{key:"moov",value:function(tracks,duration,timescale){for(var i=tracks.length,boxes=[];i--;)boxes[i]=MP4.trak(tracks[i]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(timescale,duration)].concat(boxes).concat(MP4.mvex(tracks)))}},{key:"mvex",value:function(tracks){for(var i=tracks.length,boxes=[];i--;)boxes[i]=MP4.trex(tracks[i]);return MP4.box.apply(null,[MP4.types.mvex].concat(boxes))}},{key:"mvhd",value:function(timescale,duration){var bytes=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,timescale>>24&255,timescale>>16&255,timescale>>8&255,255×cale,duration>>24&255,duration>>16&255,duration>>8&255,255&duration,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,bytes)}},{key:"sdtp",value:function(track){var flags,i,samples=track.samples||[],bytes=new Uint8Array(4+samples.length);for(i=0;i>>8&255),sps.push(255&len),sps=sps.concat(Array.prototype.slice.call(data));for(i=0;i>>8&255),pps.push(255&len),pps=pps.concat(Array.prototype.slice.call(data));var avcc=MP4.box(MP4.types.avcC,new Uint8Array([1,sps[3],sps[4],sps[5],255,224|track.sps.length].concat(sps).concat([track.pps.length]).concat(pps))),width=track.width,height=track.height;return MP4.box(MP4.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,width>>8&255,255&width,height>>8&255,255&height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,98,105,110,101,108,112,114,111,46,114,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),avcc,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])))}},{key:"esds",value:function(track){var configlen=track.config.byteLength,data=new Uint8Array(26+configlen+3);return data.set([0,0,0,0,3,23+configlen,0,1,0,4,15+configlen,64,21,0,0,0,0,0,0,0,0,0,0,0,5,configlen]),data.set(track.config,26),data.set([6,1,2],26+configlen),data}},{key:"mp4a",value:function(track){var audiosamplerate=track.audiosamplerate;return MP4.box(MP4.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,track.channelCount,0,16,0,0,0,0,audiosamplerate>>8&255,255&audiosamplerate,0,0]),MP4.box(MP4.types.esds,MP4.esds(track)))}},{key:"stsd",value:function(track){return"audio"===track.type?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(track)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(track))}},{key:"tkhd",value:function(track){var id=track.id,duration=track.duration,width=track.width,height=track.height,volume=track.volume;return MP4.box(MP4.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,id>>24&255,id>>16&255,id>>8&255,255&id,0,0,0,0,duration>>24,duration>>16&255,duration>>8&255,255&duration,0,0,0,0,0,0,0,0,0,0,0,0,volume>>0&255,volume%1*10>>0&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,width>>8&255,255&width,0,0,height>>8&255,255&height,0,0]))}},{key:"traf",value:function(track,baseMediaDecodeTime){var sampleDependencyTable=MP4.sdtp(track),id=track.id;return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,id>>24,id>>16&255,id>>8&255,255&id])),MP4.box(MP4.types.tfdt,new Uint8Array([0,0,0,0,baseMediaDecodeTime>>24,baseMediaDecodeTime>>16&255,baseMediaDecodeTime>>8&255,255&baseMediaDecodeTime])),MP4.trun(track,sampleDependencyTable.length+16+16+8+16+8+8),sampleDependencyTable)}},{key:"trak",value:function(track){return track.duration=track.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(track),MP4.mdia(track))}},{key:"trex",value:function(track){var id=track.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,id>>24,id>>16&255,id>>8&255,255&id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(track,offset){var i,sample,duration,size,flags,cts,samples=track.samples||[],len=samples.length,arraylen=12+16*len,array=new Uint8Array(arraylen);for(offset+=8+arraylen,array.set([0,0,15,1,len>>>24&255,len>>>16&255,len>>>8&255,255&len,offset>>>24&255,offset>>>16&255,offset>>>8&255,255&offset],0),i=0;i>>24&255,duration>>>16&255,duration>>>8&255,255&duration,size>>>24&255,size>>>16&255,size>>>8&255,255&size,flags.isLeading<<2|flags.dependsOn,flags.isDependedOn<<6|flags.hasRedundancy<<4|flags.paddingValue<<1|flags.isNonSync,61440&flags.degradPrio,15&flags.degradPrio,cts>>>24&255,cts>>>16&255,cts>>>8&255,255&cts],12+16*i);return MP4.box(MP4.types.trun,array)}},{key:"initSegment",value:function(tracks,duration,timescale){MP4.types||MP4.init();var result,movie=MP4.moov(tracks,duration,timescale);return(result=new Uint8Array(MP4.FTYP.byteLength+movie.byteLength)).set(MP4.FTYP),result.set(movie,MP4.FTYP.byteLength),result}}]),MP4}(),Log$4=getTagged("mse"),MSEBuffer=function(){function MSEBuffer(parent,codec){var _this=this;classCallCheck(this,MSEBuffer),this.mediaSource=parent.mediaSource,this.players=parent.players,this.cleaning=!1,this.parent=parent,this.queue=[],this.cleanResolvers=[],this.codec=codec,this.cleanRanges=[],Log$4.debug("Use codec: "+codec),this.sourceBuffer=this.mediaSource.addSourceBuffer(codec),this.eventSource=new EventEmitter(this.sourceBuffer),this.eventSource.addEventListener("updatestart",function(e){_this.cleaning&&Log$4.debug(_this.codec+" cleaning start")}),this.eventSource.addEventListener("update",function(e){_this.cleaning&&Log$4.debug(_this.codec+" cleaning update")}),this.eventSource.addEventListener("updateend",function(e){if(_this.cleaning){Log$4.debug(_this.codec+" cleaning end");try{_this.sourceBuffer.buffered.length&&_this.players[0].currentTime<_this.sourceBuffer.buffered.start(0)&&(_this.players[0].currentTime=_this.sourceBuffer.buffered.start(0))}catch(e){}for(;_this.cleanResolvers.length;){_this.cleanResolvers.shift()()}if(_this.cleaning=!1,_this.cleanRanges.length)return void _this.doCleanup()}_this.feedNext()}),this.eventSource.addEventListener("error",function(e){Log$4.debug("Source buffer error: "+_this.mediaSource.readyState),_this.mediaSource.sourceBuffers.length&&_this.mediaSource.removeSourceBuffer(_this.sourceBuffer),_this.parent.eventSource.dispatchEvent("error")}),this.eventSource.addEventListener("abort",function(e){Log$4.debug("Source buffer aborted: "+_this.mediaSource.readyState),_this.mediaSource.sourceBuffers.length&&_this.mediaSource.removeSourceBuffer(_this.sourceBuffer),_this.parent.eventSource.dispatchEvent("error")}),this.sourceBuffer.updating||this.feedNext()}return createClass(MSEBuffer,[{key:"destroy",value:function(){this.eventSource.destroy(),this.clear(),this.queue=[],this.mediaSource.removeSourceBuffer(this.sourceBuffer)}},{key:"clear",value:function(){var _this2=this;this.queue=[];for(var promises=[],_loop=function(i){_this2.cleaning=!0,promises.push(new Promise(function(resolve,reject){_this2.cleanResolvers.push(resolve),_this2.sourceBuffer.updating?_this2.sourceBuffer.onupdateend=function(){_this2.sourceBuffer&&_this2.sourceBuffer.remove(_this2.sourceBuffer.buffered.start(i),_this2.sourceBuffer.buffered.end(i)),resolve()}:(_this2.sourceBuffer.remove(_this2.sourceBuffer.buffered.start(i),_this2.sourceBuffer.buffered.end(i)),resolve())}))},i=0;i=removeStart?(Log$4.debug("Clear ["+removeStart+", "+removeBound+"), leave ["+removeBound+", "+removeEnd+"]"),(removeEnd=removeBound)!=removeStart&&this.cleanRanges.push([removeStart,removeEnd])):this.cleanRanges.push([removeStart,removeEnd]))}this.doCleanup()}}},{key:"doAppend",value:function(data){var err=this.players[0].error;if(err){Log$4.error("Error occured: "+MSE.ErrorNotes[err.code]);try{this.players.forEach(function(video){video.stop()}),this.mediaSource.endOfStream()}catch(e){}this.parent.eventSource.dispatchEvent("error")}else try{this.sourceBuffer.appendBuffer(data)}catch(e){if("QuotaExceededError"===e.name)return Log$4.debug(this.codec+" quota fail"),this.queue.unshift(data),void this.initCleanup();Log$4.error("Error occured while appending buffer. "+e.name+": "+e.message),this.parent.eventSource.dispatchEvent("error")}}},{key:"feed",value:function(data){this.queue=this.queue.concat(data),!this.sourceBuffer||this.sourceBuffer.updating||this.cleaning||this.feedNext()}}]),MSEBuffer}(),MSE=function(){function MSE(players){classCallCheck(this,MSE),this.players=players;var playing=this.players.map(function(video,idx){return video.onplaying=function(){playing[idx]=!0},video.onpause=function(){playing[idx]=!1},!video.paused});this.playing=playing,this.mediaSource=new MediaSource,this.eventSource=new EventEmitter(this.mediaSource),this.reset()}return createClass(MSE,null,[{key:"isSupported",value:function(codecs){return window.MediaSource&&window.MediaSource.isTypeSupported('video/mp4; codecs="'+codecs.join(",")+'"')}},{key:"ErrorNotes",get:function(){var _ref;return _ref={},defineProperty(_ref,MediaError.MEDIA_ERR_ABORTED,"fetching process aborted by user"),defineProperty(_ref,MediaError.MEDIA_ERR_NETWORK,"error occurred when downloading"),defineProperty(_ref,MediaError.MEDIA_ERR_DECODE,"error occurred when decoding"),defineProperty(_ref,MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,"audio/video not supported"),_ref}}]),createClass(MSE,[{key:"destroy",value:function(){this.reset(),this.eventSource.destroy(),this.mediaSource=null,this.eventSource=null}},{key:"play",value:function(){var _this3=this;this.players.forEach(function(video,idx){video.paused&&!_this3.playing[idx]&&(Log$4.debug("player "+idx+": play"),video.play())})}},{key:"setLive",value:function(is_live){for(var idx in this.buffers)this.buffers[idx].setLive(is_live);this.is_live=is_live}},{key:"resetBuffers",value:function(){var _this4=this;this.players.forEach(function(video,idx){!video.paused&&_this4.playing[idx]&&(video.pause(),video.currentTime=0)});var promises=[],_iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=this.buffers.values()[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var buffer=_step.value;promises.push(buffer.clear())}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}return Promise.all(promises).then(function(){_this4.mediaSource.endOfStream(),_this4.mediaSource.duration=0,_this4.mediaSource.clearLiveSeekableRange(),_this4.play()})}},{key:"clear",value:function(){var _this5=this;return this.reset(),this.players.forEach(function(video){video.src=URL.createObjectURL(_this5.mediaSource)}),this.setupEvents()}},{key:"setupEvents",value:function(){var _this6=this;return this.eventSource.clear(),this.resolved=!1,this.mediaReady=new Promise(function(resolve,reject){_this6._sourceOpen=function(){Log$4.debug("Media source opened: "+_this6.mediaSource.readyState),_this6.resolved||(_this6.resolved=!0,resolve())},_this6._sourceEnded=function(){Log$4.debug("Media source ended: "+_this6.mediaSource.readyState)},_this6._sourceClose=function(){Log$4.debug("Media source closed: "+_this6.mediaSource.readyState),_this6.resolved&&_this6.eventSource.dispatchEvent("sourceclosed")},_this6.eventSource.addEventListener("sourceopen",_this6._sourceOpen),_this6.eventSource.addEventListener("sourceended",_this6._sourceEnded),_this6.eventSource.addEventListener("sourceclose",_this6._sourceClose)}),this.mediaReady}},{key:"reset",value:function(){this.ready=!1;for(var track in this.buffers)this.buffers[track].destroy(),delete this.buffers[track];"open"==this.mediaSource.readyState&&(this.mediaSource.duration=0,this.mediaSource.endOfStream()),this.updating=!1,this.resolved=!1,this.buffers={}}},{key:"setCodec",value:function(track,mimeCodec){var _this7=this;return this.mediaReady.then(function(){_this7.buffers[track]=new MSEBuffer(_this7,mimeCodec),_this7.buffers[track].setLive(_this7.is_live)})}},{key:"feed",value:function(track,data){this.buffers[track]&&this.buffers[track].feed(data)}}]),MSE}(),Log$5=getTagged("remuxer:base"),track_id=1,BaseRemuxer=function(){function BaseRemuxer(timescale,scaleFactor,params){classCallCheck(this,BaseRemuxer),this.timeOffset=0,this.timescale=timescale,this.scaleFactor=scaleFactor,this.readyToDecode=!1,this.samples=[],this.seq=1,this.tsAlign=1}return createClass(BaseRemuxer,null,[{key:"getTrackID",value:function(){return track_id++}},{key:"MP4_TIMESCALE",get:function(){return 9e4}}]),createClass(BaseRemuxer,[{key:"scaled",value:function(timestamp){return timestamp/this.scaleFactor}},{key:"unscaled",value:function(timestamp){return timestamp*this.scaleFactor}},{key:"remux",value:function(unit){return!!unit&&(this.samples.push({unit:unit,pts:unit.pts,dts:unit.dts}),!0)}},{key:"setConfig",value:function(config){}},{key:"insertDscontinuity",value:function(){this.samples.push(null)}},{key:"init",value:function(initPTS,initDTS){var shouldInitialize=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.initPTS=Math.min(initPTS,this.samples[0].dts),this.initDTS=Math.min(initDTS,this.samples[0].dts),Log$5.debug("Initial pts="+this.initPTS+" dts="+this.initDTS+" offset="+this.unscaled(this.timeOffset)),this.initialized=shouldInitialize}},{key:"flush",value:function(){this.seq++,this.mp4track.len=0,this.mp4track.samples=[]}},{key:"getPayloadBase",value:function(sampleFunction,setupSample){return this.readyToDecode&&this.initialized&&this.samples.length?(this.samples.sort(BaseRemuxer.dtsSortFunc),!0):null}}],[{key:"toMS",value:function(timestamp){return timestamp/90}},{key:"dtsSortFunc",value:function(a,b){return a.dts-b.dts}}]),BaseRemuxer}(),Log$3=getTagged("remuxer:aac"),AACRemuxer=function(_BaseRemuxer){function AACRemuxer(timescale){var scaleFactor=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,params=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};classCallCheck(this,AACRemuxer);var _this=possibleConstructorReturn(this,(AACRemuxer.__proto__||Object.getPrototypeOf(AACRemuxer)).call(this,timescale,scaleFactor));return _this.codecstring=MSE.CODEC_AAC,_this.units=[],_this.initDTS=void 0,_this.nextAacPts=void 0,_this.lastPts=0,_this.firstDTS=0,_this.firstPTS=0,_this.duration=params.duration||1,_this.initialized=!1,_this.mp4track={id:BaseRemuxer.getTrackID(),type:"audio",fragmented:!0,channelCount:0,audiosamplerate:_this.timescale,duration:0,timescale:_this.timescale,volume:1,samples:[],config:"",len:0},params.config&&_this.setConfig(params.config),_this}return inherits(AACRemuxer,BaseRemuxer),createClass(AACRemuxer,[{key:"setConfig",value:function(config){this.mp4track.channelCount=config.channels,this.mp4track.audiosamplerate=config.samplerate,this.mp4track.duration||(this.mp4track.duration=(this.duration?this.duration:1)*config.samplerate),this.mp4track.timescale=config.samplerate,this.mp4track.config=config.config,this.mp4track.codec=config.codec,this.timescale=config.samplerate,this.scaleFactor=BaseRemuxer.MP4_TIMESCALE/config.samplerate,this.expectedSampleDuration=1024*this.scaleFactor,this.readyToDecode=!0}},{key:"remux",value:function(aac){get(AACRemuxer.prototype.__proto__||Object.getPrototypeOf(AACRemuxer.prototype),"remux",this).call(this,aac)&&(this.mp4track.len+=aac.getSize())}},{key:"getPayload",value:function(){if(!this.readyToDecode||!this.samples.length)return null;this.samples.sort(function(a,b){return a.dts-b.dts});for(var payload=new Uint8Array(this.mp4track.len),offset=0,samples=this.mp4track.samples,mp4Sample=void 0,lastDTS=void 0,pts=void 0,dts=void 0;this.samples.length;){var sample=this.samples.shift();if(null===sample){this.nextDts=void 0;break}var unit=sample.unit;if(pts=sample.pts-this.initDTS,dts=sample.dts-this.initDTS,void 0===lastDTS){if(this.nextDts){var delta=Math.round(this.scaled(pts-this.nextAacPts));if(Math.abs(delta)<600&&delta){if(delta>0)Log$3.log(delta+" ms hole between AAC samples detected,filling it");else if(delta<-12){Log$3.log(-delta+" ms overlapping between AAC samples detected, drop frame"),this.mp4track.len-=unit.getSize();continue}pts=dts=this.nextAacPts}}this.firstDTS=Math.max(0,dts)}mp4Sample={size:unit.getSize(),cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},payload.set(unit.getData(),offset),offset+=unit.getSize(),samples.push(mp4Sample),lastDTS=dts}return samples.length?(this.nextDts=pts+this.expectedSampleDuration,new Uint8Array(payload.buffer,0,this.mp4track.len)):null}}]),AACRemuxer}(),ExpGolomb=function(){function ExpGolomb(data){classCallCheck(this,ExpGolomb),this.data=data,this.bytesAvailable=this.data.byteLength,this.word=0,this.bitsAvailable=0}return createClass(ExpGolomb,[{key:"loadWord",value:function(){var position=this.data.byteLength-this.bytesAvailable,workingBytes=new Uint8Array(4),availableBytes=Math.min(4,this.bytesAvailable);if(0===availableBytes)throw new Error("no bytes available");workingBytes.set(this.data.subarray(position,position+availableBytes)),this.word=new DataView(workingBytes.buffer,workingBytes.byteOffset,workingBytes.byteLength).getUint32(0),this.bitsAvailable=8*availableBytes,this.bytesAvailable-=availableBytes}},{key:"skipBits",value:function(count){var skipBytes;this.bitsAvailable>count?(this.word<<=count,this.bitsAvailable-=count):(count-=this.bitsAvailable,count-=(skipBytes=count>>3)<<3,this.bytesAvailable-=skipBytes,this.loadWord(),this.word<<=count,this.bitsAvailable-=count)}},{key:"readBits",value:function(size){var bits=Math.min(this.bitsAvailable,size),valu=this.word>>>32-bits;return size>32&&Log.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=bits,this.bitsAvailable>0?this.word<<=bits:this.bytesAvailable>0&&this.loadWord(),(bits=size-bits)>0?valu<>>leadingZeroCount))return this.word<<=leadingZeroCount,this.bitsAvailable-=leadingZeroCount,leadingZeroCount;return this.loadWord(),leadingZeroCount+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var clz=this.skipLZ();return this.readBits(clz+1)-1}},{key:"readEG",value:function(){var valu=this.readUEG();return 1&valu?1+valu>>>1:-1*(valu>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}}]),ExpGolomb}(),BitArray=function(){function BitArray(src){classCallCheck(this,BitArray),this.src=new DataView(src.buffer,src.byteOffset,src.byteLength),this.bitpos=0,this.byte=this.src.getUint8(0),this.bytepos=0}return createClass(BitArray,[{key:"readBits",value:function(length){if(32<(0|length)||0==(0|length))throw new Error("too big");for(var result=0,i=length;i>0;--i)result=(0|result)<<1|(0|this.byte)>>8-++this.bitpos&1,(0|this.bitpos)>=8&&(this.byte=this.src.getUint8(++this.bytepos),this.bitpos&=7);return result}},{key:"skipBits",value:function(length){return this.bitpos+=7&(0|length),this.bytepos+=(0|length)>>>3,this.bitpos>7&&(this.bitpos&=7,++this.bytepos),this.finished()?this.bytepos-this.src.byteLength-this.src.bitpos:(this.byte=this.src.getUint8(this.bytepos),0)}},{key:"finished",value:function(){return this.bytepos>=this.src.byteLength}}]),BitArray}(),NALU=function(){function NALU(ntype,nri,data,dts,pts){classCallCheck(this,NALU),this.data=data,this.ntype=ntype,this.nri=nri,this.dts=dts,this.pts=pts||this.dts}return createClass(NALU,null,[{key:"type",value:function(nalu){return nalu.ntype in NALU.TYPES?NALU.TYPES[nalu.ntype]:"UNKNOWN"}},{key:"NDR",get:function(){return 1}},{key:"IDR",get:function(){return 5}},{key:"SEI",get:function(){return 6}},{key:"SPS",get:function(){return 7}},{key:"PPS",get:function(){return 8}},{key:"STAP_A",get:function(){return 24}},{key:"STAP_B",get:function(){return 25}},{key:"FU_A",get:function(){return 28}},{key:"FU_B",get:function(){return 29}},{key:"TYPES",get:function(){var _ref;return _ref={},defineProperty(_ref,NALU.IDR,"IDR"),defineProperty(_ref,NALU.SEI,"SEI"),defineProperty(_ref,NALU.SPS,"SPS"),defineProperty(_ref,NALU.PPS,"PPS"),defineProperty(_ref,NALU.NDR,"NDR"),_ref}}]),createClass(NALU,[{key:"appendData",value:function(idata){this.data=function(buffer1,buffer2){var tmp=new Uint8Array((0|buffer1.byteLength)+(0|buffer2.byteLength));return tmp.set(buffer1,0),tmp.set(buffer2,0|buffer1.byteLength),tmp}(this.data,idata)}},{key:"toString",value:function(){return NALU.type(this)+"("+this.data.byteLength+"): NRI: "+this.getNri()+", PTS: "+this.pts+", DTS: "+this.dts}},{key:"getNri",value:function(){return this.nri>>5}},{key:"type",value:function(){return this.ntype}},{key:"isKeyframe",value:function(){return this.ntype==NALU.IDR}},{key:"getSize",value:function(){return 5+this.data.byteLength}},{key:"getData",value:function(){var header=new Uint8Array(5+this.data.byteLength),view=new DataView(header.buffer);return view.setUint32(0,this.data.byteLength+1),view.setUint8(4,0|96&this.nri|31&this.ntype),header.set(this.data,5),header}}]),NALU}(),H264Parser=function(){function H264Parser(remuxer){classCallCheck(this,H264Parser),this.remuxer=remuxer,this.track=remuxer.mp4track}return createClass(H264Parser,[{key:"msToScaled",value:function(timestamp){return(timestamp-this.remuxer.timeOffset)*this.remuxer.scaleFactor}},{key:"parseSPS",value:function(sps){var config=H264Parser.readSPS(new Uint8Array(sps));this.track.width=config.width,this.track.height=config.height,this.track.sps=[new Uint8Array(sps)],this.track.codec="avc1.";for(var codecarray=new DataView(sps.buffer,sps.byteOffset+1,4),i=0;i<3;++i){var h=codecarray.getUint8(i).toString(16);h.length<2&&(h="0"+h),this.track.codec+=h}}},{key:"parsePPS",value:function(pps){this.track.pps=[new Uint8Array(pps)]}},{key:"parseNAL",value:function(unit){if(!unit)return!1;var push=!1;switch(unit.type()){case NALU.NDR:case NALU.IDR:push=!0;break;case NALU.PPS:this.track.pps||(this.parsePPS(unit.getData().subarray(4)),!this.remuxer.readyToDecode&&this.track.pps&&this.track.sps&&(this.remuxer.readyToDecode=!0));break;case NALU.SPS:this.track.sps||(this.parseSPS(unit.getData().subarray(4)),!this.remuxer.readyToDecode&&this.track.pps&&this.track.sps&&(this.remuxer.readyToDecode=!0));break;case NALU.SEI:}return unit.getNri()>0&&(push=!0),push}}],[{key:"skipScalingList",value:function(decoder,count){for(var lastScale=8,nextScale=8,j=0;j1&&void 0!==arguments[1]?arguments[1]:1,params=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};classCallCheck(this,H264Remuxer);var _this=possibleConstructorReturn(this,(H264Remuxer.__proto__||Object.getPrototypeOf(H264Remuxer)).call(this,timescale,scaleFactor));return _this.nextDts=void 0,_this.readyToDecode=!1,_this.initialized=!1,_this.firstDTS=0,_this.firstPTS=0,_this.lastDTS=void 0,_this.lastSampleDuration=0,_this.lastDurations=[],_this.tsAlign=Math.round(_this.timescale/60),_this.mp4track={id:BaseRemuxer.getTrackID(),type:"video",len:0,fragmented:!0,sps:"",pps:"",width:0,height:0,timescale:timescale,duration:timescale,samples:[]},_this.samples=[],_this.lastGopDTS=-99999999999999,_this.gop=[],_this.firstUnit=!0,_this.h264=new H264Parser(_this),params.sps&&_this.setSPS(new Uint8Array(params.sps)),params.pps&&_this.setPPS(new Uint8Array(params.pps)),_this.mp4track.pps&&_this.mp4track.sps&&(_this.readyToDecode=!0),_this}return inherits(H264Remuxer,BaseRemuxer),createClass(H264Remuxer,[{key:"_scaled",value:function(timestamp){return timestamp>>>this.scaleFactor}},{key:"_unscaled",value:function(timestamp){return timestamp<100&&this.lastDurations.shift(),mp4Sample.duration=sampleDuration}else{if(this.nextDts){var delta=dts-this.nextDts;if(Math.abs(Math.round(BaseRemuxer.toMS(delta)))<600)delta&&(dts=this.nextDts,pts=Math.max(pts-delta,dts));else if(delta<0){Log$6.log("skip frame from the past at DTS="+dts+" with expected DTS="+this.nextDts),this.mp4track.len-=unit.getSize();continue}}this.firstDTS=Math.max(0,dts)}var flags=(mp4Sample={size:unit.getSize(),duration:0,cts:this.scaled(pts-dts),flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0}}).flags;!0===sample.unit.isKeyframe()?(flags.dependsOn=2,flags.isNonSync=0):(flags.dependsOn=1,flags.isNonSync=1),payload.set(unit.getData(),offset),offset+=unit.getSize(),samples.push(mp4Sample),lastDTS=dts}if(!samples.length)return null;var avgDuration=this.lastDurations.reduce(function(a,b){return(0|a)+(0|b)},0)/(this.lastDurations.length||1)|0;if(samples.length>=2?(this.lastSampleDuration=avgDuration,mp4Sample.duration=avgDuration):mp4Sample.duration=this.lastSampleDuration,samples.length&&(!this.nextDts||navigator.userAgent.toLowerCase().indexOf("chrome")>-1)){var _flags=samples[0].flags;_flags.dependsOn=2,_flags.isNonSync=0}return this.nextDts=dts+this.unscaled(this.lastSampleDuration),new Uint8Array(payload.buffer,0,this.mp4track.len)}}]),H264Remuxer}(),PayloadType=(function(){function StreamType(){classCallCheck(this,StreamType)}createClass(StreamType,null,[{key:"VIDEO",get:function(){return 1}},{key:"AUDIO",get:function(){return 2}},{key:"map",get:function(){var _ref;return _ref={},defineProperty(_ref,StreamType.VIDEO,"video"),defineProperty(_ref,StreamType.AUDIO,"audio"),_ref}}])}(),function(){function PayloadType(){classCallCheck(this,PayloadType)}return createClass(PayloadType,null,[{key:"H264",get:function(){return 1}},{key:"AAC",get:function(){return 2}},{key:"map",get:function(){var _ref2;return _ref2={},defineProperty(_ref2,PayloadType.H264,"video"),defineProperty(_ref2,PayloadType.AAC,"audio"),_ref2}},{key:"string_map",get:function(){return{H264:PayloadType.H264,AAC:PayloadType.AAC,"MP4A-LATM":PayloadType.AAC,"MPEG4-GENERIC":PayloadType.AAC}}}]),PayloadType}()),Log$2=getTagged("remuxer"),Remuxer=function(){function Remuxer(mediaElement){classCallCheck(this,Remuxer),this.mse=new MSE([mediaElement]),this.eventSource=new EventEmitter,this.mseEventSource=new EventSourceWrapper(this.mse.eventSource),this.mse_ready=!0,this.reset(),this.errorListener=this.mseClose.bind(this),this.closeListener=this.mseClose.bind(this),this.eventSource.addEventListener("ready",this.init.bind(this))}return createClass(Remuxer,null,[{key:"TrackConverters",get:function(){var _ref;return _ref={},defineProperty(_ref,PayloadType.H264,H264Remuxer),defineProperty(_ref,PayloadType.AAC,AACRemuxer),_ref}},{key:"TrackScaleFactor",get:function(){var _ref2;return _ref2={},defineProperty(_ref2,PayloadType.H264,1),defineProperty(_ref2,PayloadType.AAC,0),_ref2}},{key:"TrackTimescale",get:function(){var _ref3;return _ref3={},defineProperty(_ref3,PayloadType.H264,9e4),defineProperty(_ref3,PayloadType.AAC,0),_ref3}}]),createClass(Remuxer,[{key:"initMSEHandlers",value:function(){this.mseEventSource.on("error",this.errorListener),this.mseEventSource.on("sourceclosed",this.closeListener)}},{key:"reset",value:function(){return __async(regeneratorRuntime.mark(function _callee(){return regeneratorRuntime.wrap(function(_context){for(;;)switch(_context.prev=_context.next){case 0:return this.tracks={},this.initialized=!1,this.initSegments={},this.codecs=[],this.streams={},this.enabled=!1,_context.next=8,this.mse.clear();case 8:this.initMSEHandlers();case 9:case"end":return _context.stop()}},_callee,this)}).call(this))}},{key:"destroy",value:function(){this.mseEventSource.destroy(),this.mse.destroy(),this.mse=null,this.detachClient(),this.eventSource.destroy()}},{key:"onTracks",value:function(tracks){Log$2.debug(tracks.detail);var _iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=tracks.detail[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var track=_step.value;this.tracks[track.type]=new Remuxer.TrackConverters[track.type](Remuxer.TrackTimescale[track.type],Remuxer.TrackScaleFactor[track.type],track.params),track.offset&&(this.tracks[track.type].timeOffset=track.offset),track.duration?(this.tracks[track.type].mp4track.duration=track.duration*(this.tracks[track.type].timescale||Remuxer.TrackTimescale[track.type]),this.tracks[track.type].duration=track.duration):this.tracks[track.type].duration=1}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}this.mse.setLive(!this.client.seekable)}},{key:"setTimeOffset",value:function(timeOffset,track){this.tracks[track.type]&&(this.tracks[track.type].timeOffset=timeOffset)}},{key:"init",value:function(){var _this=this,tracks=[];this.codecs=[];var initmse=[];for(var track_type in this.tracks){var track=this.tracks[track_type];if(!MSE.isSupported([track.mp4track.codec]))throw new Error(track.mp4track.type+" codec "+track.mp4track.codec+" is not supported");tracks.push(track.mp4track),this.codecs.push(track.mp4track.codec),track.init(1/0,1/0)}for(var _track_type in this.tracks){var _track=this.tracks[_track_type];this.initSegments[_track_type]=MP4.initSegment([_track.mp4track],_track.duration*_track.timescale,_track.timescale),initmse.push(this.initMSE(_track_type,_track.mp4track.codec))}return this.initialized=!0,Promise.all(initmse).then(function(){_this.enabled=!0})}},{key:"initMSE",value:function(track_type,codec){var _this2=this;if(MSE.isSupported(this.codecs))return this.mse.setCodec(track_type,PayloadType.map[track_type]+'/mp4; codecs="'+codec+'"').then(function(){_this2.mse.feed(track_type,_this2.initSegments[track_type])});throw new Error("Codecs are not supported")}},{key:"mseClose",value:function(){this.client.stop(),this.eventSource.dispatchEvent("stopped")}},{key:"flush",value:function(){if(this.onSamples(),this.initialized)for(var _track_type2 in this.tracks){var track=this.tracks[_track_type2],pay=track.getPayload();pay&&pay.byteLength&&(this.mse.feed(_track_type2,[MP4.moof(track.seq,track.scaled(track.firstDTS),track.mp4track),MP4.mdat(pay)]),track.flush())}else if(Object.keys(this.tracks).length){for(var track_type in this.tracks)if(!this.tracks[track_type].readyToDecode||!this.tracks[track_type].samples.length)return;this.eventSource.dispatchEvent("ready")}}},{key:"onSamples",value:function(ev){for(var qidx in this.client.sampleQueues)for(var queue=this.client.sampleQueues[qidx];queue.length;){var units=queue.shift(),_iteratorNormalCompletion2=!0,_didIteratorError2=!1,_iteratorError2=void 0;try{for(var _step2,_iterator2=units[Symbol.iterator]();!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=!0){var chunk=_step2.value;this.tracks[qidx].remux(chunk)}}catch(err){_didIteratorError2=!0,_iteratorError2=err}finally{try{!_iteratorNormalCompletion2&&_iterator2.return&&_iterator2.return()}finally{if(_didIteratorError2)throw _iteratorError2}}}}},{key:"onAudioConfig",value:function(ev){this.tracks[ev.detail.pay]&&this.tracks[ev.detail.pay].setConfig(ev.detail.config)}},{key:"attachClient",value:function(client){var _this3=this;this.detachClient(),this.client=client,this.clientEventSource=new EventSourceWrapper(this.client.eventSource),this.clientEventSource.on("samples",this.samplesListener),this.clientEventSource.on("audio_config",this.audioConfigListener),this.clientEventSource.on("tracks",this.onTracks.bind(this)),this.clientEventSource.on("flush",this.flush.bind(this)),this.clientEventSource.on("clear",function(){_this3.reset(),_this3.mse.clear().then(function(){_this3.initMSEHandlers()})})}},{key:"detachClient",value:function(){this.client&&(this.clientEventSource.destroy(),this.client=null)}}]),Remuxer}(),State=function(){function State(name,stateMachine){classCallCheck(this,State),this.stateMachine=stateMachine,this.transitions=new Set,this.name=name}return createClass(State,[{key:"activate",value:function(){return Promise.resolve(null)}},{key:"finishTransition",value:function(){}},{key:"failHandler",value:function(){}},{key:"deactivate",value:function(){return Promise.resolve(null)}}]),State}(),StateMachine=function(){function StateMachine(){classCallCheck(this,StateMachine),this.storage={},this.currentState=null,this.states=new Map}return createClass(StateMachine,[{key:"addState",value:function(name,_ref){var activate=_ref.activate,finishTransition=_ref.finishTransition,deactivate=_ref.deactivate,state=new State(name,this);return activate&&(state.activate=activate),finishTransition&&(state.finishTransition=finishTransition),deactivate&&(state.deactivate=deactivate),this.states.set(name,state),this}},{key:"addTransition",value:function(fromName,toName){if(!this.states.has(fromName))throw ReferenceError("No such state: "+fromName+" while connecting to "+toName);if(!this.states.has(toName))throw ReferenceError("No such state: "+toName+" while connecting from "+fromName);return this.states.get(fromName).transitions.add(toName),this}},{key:"_promisify",value:function(res){var promise=void 0;try{(promise=res).then||(promise=Promise.resolve(promise))}catch(e){promise=Promise.reject(e)}return promise}},{key:"transitionTo",value:function(stateName){var _this=this;if(null==this.currentState){var state=this.states.get(stateName);return this._promisify(state.activate.call(this)).then(function(data){return _this.currentState=state,data}).then(state.finishTransition.bind(this)).catch(function(e){throw state.failHandler(),e})}if(this.currentState.name==stateName)return Promise.resolve();if(this.currentState.transitions.has(stateName)){var _state=this.states.get(stateName);return this._promisify(_state.deactivate.call(this)).then(_state.activate.bind(this)).then(function(data){return _this.currentState=_state,data}).then(_state.finishTransition.bind(this)).catch(function(e){throw _state.failHandler(),e})}return Promise.reject("No such transition: "+this.currentState.name+" to "+stateName)}}]),StateMachine}(),Log$8=getTagged("parser:sdp"),SDPParser=function(){function SDPParser(){classCallCheck(this,SDPParser),this.version=-1,this.origin=null,this.sessionName=null,this.timing=null,this.sessionBlock={},this.media={},this.tracks={},this.mediaMap={}}return createClass(SDPParser,[{key:"parse",value:function(content){var _this=this;return Log$8.debug(content),new Promise(function(resolve,reject){var dataString=content,success=!0,currentMediaBlock=_this.sessionBlock,_iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=dataString.split("\n")[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var line=_step.value;if(0!==(line=line.replace(/\r/,"")).length){switch(line.charAt(0)){case"v":if(-1!==_this.version)return Log$8.log("Version present multiple times in SDP"),reject(),!1;success=success&&_this._parseVersion(line);break;case"o":if(null!==_this.origin)return Log$8.log("Origin present multiple times in SDP"),reject(),!1;success=success&&_this._parseOrigin(line);break;case"s":if(null!==_this.sessionName)return Log$8.log("Session Name present multiple times in SDP"),reject(),!1;success=success&&_this._parseSessionName(line);break;case"t":if(null!==_this.timing)return Log$8.log("Timing present multiple times in SDP"),reject(),!1;success=success&&_this._parseTiming(line);break;case"m":null!==currentMediaBlock&&_this.sessionBlock!==currentMediaBlock&&(_this.media[currentMediaBlock.type]=currentMediaBlock),(currentMediaBlock={}).rtpmap={},_this._parseMediaDescription(line,currentMediaBlock);break;case"a":SDPParser._parseAttribute(line,currentMediaBlock);break;default:Log$8.log("Ignored unknown SDP directive: "+line)}if(!success)return void reject()}}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}_this.media[currentMediaBlock.type]=currentMediaBlock,success?resolve():reject()})}},{key:"_parseVersion",value:function(line){var matches=line.match(/^v=([0-9]+)$/);return matches&&matches.length?(this.version=matches[1],0==this.version||(Log$8.log("Unsupported SDP version:"+this.version),!1)):(Log$8.log("'v=' (Version) formatted incorrectly: "+line),!1)}},{key:"_parseOrigin",value:function(line){var matches=line.match(/^o=([^ ]+) (-?[0-9]+) (-?[0-9]+) (IN) (IP4|IP6) ([^ ]+)$/);return matches&&matches.length?(this.origin={},this.origin.username=matches[1],this.origin.sessionid=matches[2],this.origin.sessionversion=matches[3],this.origin.nettype=matches[4],this.origin.addresstype=matches[5],this.origin.unicastaddress=matches[6],!0):(Log$8.log("'o=' (Origin) formatted incorrectly: "+line),!1)}},{key:"_parseSessionName",value:function(line){var matches=line.match(/^s=([^\r\n]+)$/);return matches&&matches.length?(this.sessionName=matches[1],!0):(Log$8.log("'s=' (Session Name) formatted incorrectly: "+line),!1)}},{key:"_parseTiming",value:function(line){var matches=line.match(/^t=([0-9]+) ([0-9]+)$/);return matches&&matches.length?(this.timing={},this.timing.start=matches[1],this.timing.stop=matches[2],!0):(Log$8.log("'t=' (Timing) formatted incorrectly: "+line),!1)}},{key:"_parseMediaDescription",value:function(line,media){var matches=line.match(/^m=([^ ]+) ([^ ]+) ([^ ]+)[ ]/);if(!matches||!matches.length)return Log$8.log("'m=' (Media) formatted incorrectly: "+line),!1;media.type=matches[1],media.port=matches[2],media.proto=matches[3],media.fmt=line.substr(matches[0].length).split(" ").map(function(fmt,index,array){return parseInt(fmt)});var _iteratorNormalCompletion2=!0,_didIteratorError2=!1,_iteratorError2=void 0;try{for(var _step2,_iterator2=media.fmt[Symbol.iterator]();!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=!0){var fmt=_step2.value;this.mediaMap[fmt]=media}}catch(err){_didIteratorError2=!0,_iteratorError2=err}finally{try{!_iteratorNormalCompletion2&&_iterator2.return&&_iterator2.return()}finally{if(_didIteratorError2)throw _iteratorError2}}return!0}},{key:"getSessionBlock",value:function(){return this.sessionBlock}},{key:"hasMedia",value:function(mediaType){return void 0!=this.media[mediaType]}},{key:"getMediaBlock",value:function(mediaType){return this.media[mediaType]}},{key:"getMediaBlockByPayloadType",value:function(pt){return this.mediaMap[pt]||null}},{key:"getMediaBlockList",value:function(){var res=[];for(var m in this.media)res.push(m);return res}}],[{key:"_parseAttribute",value:function(line,media){if(null===media)return!0;var matches,separator=line.indexOf(":");switch(line.substr(0,-1===separator?2147483647:separator)){case"a=recvonly":case"a=sendrecv":case"a=sendonly":case"a=inactive":media.mode=line.substr("a=".length);break;case"a=range":matches=line.match(/^a=range:\s*([a-zA-Z-]+)=([0-9.]+|now)\s*-\s*([0-9.]*)$/),media.range=[Number("now"==matches[2]?-1:matches[2]),Number(matches[3]),matches[1]];break;case"a=control":media.control=line.substr("a=control:".length);break;case"a=rtpmap":if(null===(matches=line.match(/^a=rtpmap:(\d+) (.*)$/)))return Log$8.log("Could not parse 'rtpmap' of 'a='"),!1;var payload=parseInt(matches[1]);media.rtpmap[payload]={};var attrs=matches[2].split("/");media.rtpmap[payload].name=attrs[0].toUpperCase(),media.rtpmap[payload].clock=attrs[1],void 0!==attrs[2]&&(media.rtpmap[payload].encparams=attrs[2]),media.ptype=PayloadType.string_map[attrs[0].toUpperCase()];break;case"a=fmtp":if(0===(matches=line.match(/^a=fmtp:(\d+) (.*)$/)).length)return Log$8.log("Could not parse 'fmtp' of 'a='"),!1;media.fmtp={};var _iteratorNormalCompletion3=!0,_didIteratorError3=!1,_iteratorError3=void 0;try{for(var _step3,_iterator3=matches[2].split(";")[Symbol.iterator]();!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=!0){var param=_step3.value,idx=param.indexOf("=");media.fmtp[param.substr(0,idx).toLowerCase().trim()]=param.substr(idx+1).trim()}}catch(err){_didIteratorError3=!0,_iteratorError3=err}finally{try{!_iteratorNormalCompletion3&&_iterator3.return&&_iterator3.return()}finally{if(_didIteratorError3)throw _iteratorError3}}}return!0}}]),SDPParser}(),Log$9=getTagged("rtsp:stream"),RTSPStream=function(){function RTSPStream(client,track){classCallCheck(this,RTSPStream),this.state=null,this.client=client,this.track=track,this.rtpChannel=1,this.stopKeepAlive(),this.keepaliveInterval=null}return createClass(RTSPStream,[{key:"reset",value:function(){this.stopKeepAlive(),this.client.forgetRTPChannel(this.rtpChannel),this.client=null,this.track=null}},{key:"start",value:function(){return this.sendSetup().then(this.sendPlay.bind(this))}},{key:"stop",value:function(){return this.sendTeardown()}},{key:"getSetupURL",value:function(track){var sessionBlock=this.client.sdp.getSessionBlock();return Url.isAbsolute(track.control)?track.control:Url.isAbsolute(""+sessionBlock.control+track.control)?""+sessionBlock.control+track.control:Url.isAbsolute(""+this.client.contentBase+track.control)?""+this.client.contentBase+track.control:track.control}},{key:"getControlURL",value:function(){var ctrl=this.client.sdp.getSessionBlock().control;return Url.isAbsolute(ctrl)?ctrl:ctrl&&"*"!==ctrl?""+this.client.contentBase+ctrl:this.client.contentBase}},{key:"sendKeepalive",value:function(){return this.client.methods.includes("GET_PARAMETER")?this.client.sendRequest("GET_PARAMETER",this.getSetupURL(this.track),{Session:this.session}):this.client.sendRequest("OPTIONS","*")}},{key:"stopKeepAlive",value:function(){clearInterval(this.keepaliveInterval)}},{key:"startKeepAlive",value:function(){var _this=this;this.keepaliveInterval=setInterval(function(){_this.sendKeepalive().catch(function(e){Log$9.error(e),e instanceof RTSPError&&501==Number(e.data.parsed.code)||_this.client.reconnect()})},3e4)}},{key:"sendRequest",value:function(_cmd){var _params=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},params={};return this.session&&(params.Session=this.session),Object.assign(params,_params),this.client.sendRequest(_cmd,this.getControlURL(),params)}},{key:"sendSetup",value:function(){var _this2=this;this.state=RTSPClientSM.STATE_SETUP,this.rtpChannel=this.client.interleaveChannelIndex;var interleavedChannels=this.client.interleaveChannelIndex+++"-"+this.client.interleaveChannelIndex++;return this.client.sendRequest("SETUP",this.getSetupURL(this.track),{Transport:"RTP/AVP/TCP;unicast;interleaved="+interleavedChannels,Date:(new Date).toUTCString()}).then(function(_data){_this2.session=_data.headers.session;var transport=_data.headers.transport;if(transport){var interleaved=transport.match(/interleaved=([0-9]+)-([0-9]+)/)[1];interleaved&&(_this2.rtpChannel=Number(interleaved))}_this2.startKeepAlive()})}},{key:"sendPlay",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return __async(regeneratorRuntime.mark(function _callee(){var params,range,data;return regeneratorRuntime.wrap(function(_context){for(;;)switch(_context.prev=_context.next){case 0:return this.state=RTSPStream.STATE_PLAY,params={},(range=this.client.sdp.sessionBlock.range)&&-1==range[0]&&(range[0]=0),this.client.useRTPChannel(this.rtpChannel),_context.next=7,this.sendRequest("PLAY",params);case 7:return data=_context.sent,this.state=RTSPClientSM.STATE_PLAYING,_context.abrupt("return",{track:this.track,data:data});case 10:case"end":return _context.stop()}},_callee,this)}).call(this))}},{key:"sendPause",value:function(){return __async(regeneratorRuntime.mark(function _callee2(){return regeneratorRuntime.wrap(function(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:if(this.client.supports("PAUSE")){_context2.next=2;break}return _context2.abrupt("return");case 2:return this.state=RTSPClientSM.STATE_PAUSE,_context2.next=5,this.sendRequest("PAUSE");case 5:this.state=RTSPClientSM.STATE_PAUSED;case 6:case"end":return _context2.stop()}},_callee2,this)}).call(this))}},{key:"sendTeardown",value:function(){return __async(regeneratorRuntime.mark(function _callee3(){return regeneratorRuntime.wrap(function(_context3){for(;;)switch(_context3.prev=_context3.next){case 0:if(this.state==RTSPClientSM.STATE_TEARDOWN){_context3.next=7;break}return this.client.forgetRTPChannel(this.rtpChannel),this.state=RTSPClientSM.STATE_TEARDOWN,this.stopKeepAlive(),_context3.next=6,this.sendRequest("TEARDOWN");case 6:Log$9.log("RTSPClient: STATE_TEARDOWN");case 7:case"end":return _context3.stop()}},_callee3,this)}).call(this))}}]),RTSPStream}(),RTP=function(){function RTP(pkt,sdp){classCallCheck(this,RTP);var bytes=new DataView(pkt.buffer,pkt.byteOffset,pkt.byteLength);this.version=bytes.getUint8(0)>>>6,this.padding=1&bytes.getUint8(0),this.has_extension=1&bytes.getUint8(0),this.csrc=15&bytes.getUint8(0),this.marker=bytes.getUint8(1)>>>7,this.pt=127&bytes.getUint8(1),this.sequence=bytes.getUint16(2),this.timestamp=bytes.getUint32(4),this.ssrc=bytes.getUint32(8),this.csrcs=[];var pktIndex=12;this.csrc>0&&(this.csrcs.push(bytes.getUint32(pktIndex)),pktIndex+=4),1==this.has_extension&&(this.extension=bytes.getUint16(pktIndex),this.ehl=bytes.getUint16(pktIndex+2),pktIndex+=4,this.header_data=pkt.slice(pktIndex,this.ehl),pktIndex+=this.ehl),this.headerLength=pktIndex;this.padding&&bytes.getUint8(pkt.byteLength-1),this.media=sdp.getMediaBlockByPayloadType(this.pt),null===this.media?Log.log("Media description for payload type: "+this.pt+" not provided."):this.type=this.media.ptype,this.data=pkt.subarray(pktIndex)}return createClass(RTP,[{key:"getPayload",value:function(){return this.data}},{key:"getTimestampMS",value:function(){return this.timestamp}},{key:"toString",value:function(){return"RTP(version:"+this.version+", padding:"+this.padding+", has_extension:"+this.has_extension+", csrc:"+this.csrc+", marker:"+this.marker+", pt:"+this.pt+", sequence:"+this.sequence+", timestamp:"+this.timestamp+", ssrc:"+this.ssrc+")"}},{key:"isVideo",value:function(){return"video"==this.media.type}},{key:"isAudio",value:function(){return"audio"==this.media.type}}]),RTP}(),RTPFactory=function(){function RTPFactory(sdp){classCallCheck(this,RTPFactory),this.tsOffsets={};for(var pay in sdp.media){var _iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=sdp.media[pay].fmt[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var pt=_step.value;this.tsOffsets[pt]={last:0,overflow:0}}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}}}return createClass(RTPFactory,[{key:"build",value:function(pkt,sdp){var rtp=new RTP(pkt,sdp),tsOffset=this.tsOffsets[rtp.pt];return tsOffset&&(rtp.timestamp+=tsOffset.overflow,tsOffset.last&&Math.abs(rtp.timestamp-tsOffset.last)>2147483647&&(console.log("\nlast ts: "+tsOffset.last+"\n\n new ts: "+rtp.timestamp+"\n\n new ts adjusted: "+(rtp.timestamp+4294967295)+"\n\n last overflow: "+tsOffset.overflow+"\n\n new overflow: "+(tsOffset.overflow+4294967295)+"\n\n "),tsOffset.overflow+=4294967295,rtp.timestamp+=4294967295),tsOffset.last=rtp.timestamp),rtp}}]),RTPFactory}(),RTSPMessage=function(){function RTSPMessage(_rtsp_version){classCallCheck(this,RTSPMessage),this.version=_rtsp_version}return createClass(RTSPMessage,null,[{key:"RTSP_1_0",get:function(){return"RTSP/1.0"}}]),createClass(RTSPMessage,[{key:"build",value:function(_cmd,_host){var _params=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},_payload=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,requestString=_cmd+" "+_host+" "+this.version+"\r\n";for(var param in _params)requestString+=param+": "+_params[param]+"\r\n";return _payload&&(requestString+="Content-Length: "+_payload.length+"\r\n"),requestString+="\r\n",_payload&&(requestString+=_payload),requestString}},{key:"parse",value:function(_data){var lines=_data.split("\r\n"),parsed={headers:{},body:null,code:0,statusLine:""},_lines$0$match=lines[0].match(new RegExp(this.version+"[ ]+([0-9]{3})[ ]+(.*)")),_lines$0$match2=slicedToArray(_lines$0$match,3);_lines$0$match2[0],parsed.code=_lines$0$match2[1],parsed.statusLine=_lines$0$match2[2],parsed.code=Number(parsed.code);for(var lineIdx=1;lines[lineIdx];){var _lines$lineIdx$split=lines[lineIdx].split(/:(.+)/),_lines$lineIdx$split2=slicedToArray(_lines$lineIdx$split,2),k=_lines$lineIdx$split2[0],v=_lines$lineIdx$split2[1];parsed.headers[k.toLowerCase()]=v.trim(),lineIdx++}return parsed.body=lines.slice(lineIdx).join("\n\r"),parsed}}]),RTSPMessage}(),MessageBuilder=new RTSPMessage(RTSPMessage.RTSP_1_0),NALUAsm=function(){function NALUAsm(){classCallCheck(this,NALUAsm),this.fragmented_nalu=null}return createClass(NALUAsm,[{key:"parseSingleNALUPacket",value:function(rawData,header,dts,pts){return new NALU(header.type,header.nri,rawData.subarray(0),dts,pts)}},{key:"parseAggregationPacket",value:function(rawData,header,dts,pts){var data=new DataView(rawData.buffer,rawData.byteOffset,rawData.byteLength),nal_start_idx=0;NALU.STAP_B===header.type&&(data.getUint16(nal_start_idx),nal_start_idx+=2);for(var ret=[];nal_start_idx>>7,is_end=(64&fu_header)>>>6,payload_type=31&fu_header,ret=null;nal_start_idx++;if(NALU.FU_B===header.type&&(data.getUint16(nal_start_idx),nal_start_idx+=2),is_start)this.fragmented_nalu=new NALU(payload_type,header.nri,rawData.subarray(nal_start_idx),dts,pts);else if(this.fragmented_nalu&&this.fragmented_nalu.ntype===payload_type&&(this.fragmented_nalu.appendData(rawData.subarray(nal_start_idx)),is_end))return ret=this.fragmented_nalu,this.fragmented_nalu=null,ret;return null}},{key:"onNALUFragment",value:function(rawData,dts,pts){var data=new DataView(rawData.buffer,rawData.byteOffset,rawData.byteLength),header=NALUAsm.parseNALHeader(data.getUint8(0)),unit=null;if(header.type>0&&header.type<24)unit=this.parseSingleNALUPacket(rawData.subarray(1),header,dts,pts);else{if(NALU.FU_A!==header.type&&NALU.FU_B!==header.type)return NALU.STAP_A===header.type||NALU.STAP_B===header.type?this.parseAggregationPacket(rawData.subarray(1),header,dts,pts):(Log.log("Undefined NAL unit, type: "+header.type),null);unit=this.parseFragmentationUnit(rawData.subarray(1),header,dts,pts)}return unit?[unit]:null}}],[{key:"parseNALHeader",value:function(hdr){return{nri:96&hdr,type:31&hdr}}}]),NALUAsm}(),AACFrame=function(){function AACFrame(data,dts,pts){classCallCheck(this,AACFrame),this.dts=dts,this.pts=pts||this.dts,this.data=data}return createClass(AACFrame,[{key:"getData",value:function(){return this.data}},{key:"getSize",value:function(){return this.data.byteLength}}]),AACFrame}(),AACAsm=function(){function AACAsm(){classCallCheck(this,AACAsm),this.config=null}return createClass(AACAsm,[{key:"onAACFragment",value:function(pkt){var rawData=pkt.getPayload();if(!pkt.media)return null;var data=new DataView(rawData.buffer,rawData.byteOffset,rawData.byteLength),sizeLength=Number(pkt.media.fmtp.sizelength||0),indexLength=Number(pkt.media.fmtp.indexlength||0),indexDeltaLength=Number(pkt.media.fmtp.indexdeltalength||0),CTSDeltaLength=Number(pkt.media.fmtp.ctsdeltalength||0),DTSDeltaLength=Number(pkt.media.fmtp.dtsdeltalength||0),RandomAccessIndication=Number(pkt.media.fmtp.randomaccessindication||0),StreamStateIndication=Number(pkt.media.fmtp.streamstateindication||0),AuxiliaryDataSizeLength=Number(pkt.media.fmtp.auxiliarydatasizelength||0),configHeaderLength=sizeLength+Math.max(indexLength,indexDeltaLength)+CTSDeltaLength+DTSDeltaLength+RandomAccessIndication+StreamStateIndication+AuxiliaryDataSizeLength,auHeadersLengthPadded=0,offset=0,ts=9e4*(Math.round(pkt.getTimestampMS()/1024)<<10)/this.config.samplerate;if(0!==configHeaderLength){var auHeadersLengthInBits=data.getUint16(0);auHeadersLengthPadded=2+(auHeadersLengthInBits>>>3)+(7&auHeadersLengthInBits?1:0);for(var frames=[],frameOffset=0,bits=new BitArray(rawData.subarray(2+offset)),cts=0,dts=0,_offset=0;_offset0&&void 0!==arguments[0]?arguments[0]:{flush:100};classCallCheck(this,BaseClient),this.options=options,this.eventSource=new EventEmitter,Object.defineProperties(this,{sourceUrl:{value:null,writable:!0},paused:{value:!0,writable:!0},seekable:{value:!1,writable:!0},connected:{value:!1,writable:!0}}),this._onData=function(){if(_this.connected)for(;_this.transport.dataQueue.length;)_this.onData(_this.transport.dataQueue.pop())},this._onConnect=this.onConnected.bind(this),this._onDisconnect=this.onDisconnected.bind(this)}return createClass(BaseClient,[{key:"destroy",value:function(){this.detachTransport()}},{key:"attachTransport",value:function(transport){this.transport&&this.detachTransport(),this.transport=transport,this.transport.eventSource.addEventListener("data",this._onData),this.transport.eventSource.addEventListener("connected",this._onConnect),this.transport.eventSource.addEventListener("disconnected",this._onDisconnect)}},{key:"detachTransport",value:function(){this.transport&&(this.transport.eventSource.removeEventListener("data",this._onData),this.transport.eventSource.removeEventListener("connected",this._onConnect),this.transport.eventSource.removeEventListener("disconnected",this._onDisconnect),this.transport=null)}},{key:"reset",value:function(){}},{key:"start",value:function(){Log.log("Client started"),this.paused=!1}},{key:"stop",value:function(){Log.log("Client paused"),this.paused=!0}},{key:"seek",value:function(timeOffset){}},{key:"setSource",value:function(source){this.stop(),this.endpoint=source,this.sourceUrl=source.urlpath}},{key:"startStreamFlush",value:function(){var _this2=this;this.flushInterval=setInterval(function(){_this2.paused||_this2.eventSource.dispatchEvent("flush")},this.options.flush)}},{key:"stopStreamFlush",value:function(){clearInterval(this.flushInterval)}},{key:"onData",value:function(data){}},{key:"onConnected",value:function(){this.seekable||(this.transport.dataQueue=[],this.eventSource.dispatchEvent("clear")),this.connected=!0}},{key:"onDisconnected",value:function(){this.connected=!1}},{key:"queryCredentials",value:function(){return Promise.resolve()}},{key:"setCredentials",value:function(user,password){this.endpoint.user=user,this.endpoint.pass=password,this.endpoint.auth=user+":"+password}}],[{key:"streamType",value:function(){return null}}]),BaseClient}(),AACParser=function(){function AACParser(){classCallCheck(this,AACParser)}return createClass(AACParser,null,[{key:"parseAudioSpecificConfig",value:function(bytesOrBits){var config=void 0,bitpos=(config=bytesOrBits.byteLength?new BitArray(bytesOrBits):bytesOrBits).bitpos+8*(config.src.byteOffset+config.bytepos),prof=config.readBits(5);this.codec="mp4a.40."+prof;var sfi=config.readBits(4);15==sfi&&config.skipBits(24);var channels=config.readBits(4);return{config:function(bytearray){for(var start=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,end=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8*bytearray.byteLength,byteLen=Math.ceil((end-start)/8),res=new Uint8Array(byteLen),startByte=start>>>3,endByte=(end>>>3)-1,bitOffset=7&start,nBitOffset=8-bitOffset,endOffset=8-end&7,i=0;i>nBitOffset,i==endByte-1&&endOffset<8&&(tail>>=endOffset,tail<<=endOffset)),res[i]=bytearray[startByte+i]<0&&void 0!==arguments[0]?arguments[0]:{flush:200};classCallCheck(this,RTSPClient);var _this=possibleConstructorReturn(this,(RTSPClient.__proto__||Object.getPrototypeOf(RTSPClient)).call(this,options));return _this.clientSM=new RTSPClientSM(_this),_this.clientSM.ontracks=function(tracks){_this.eventSource.dispatchEvent("tracks",tracks),_this.startStreamFlush()},_this.sampleQueues={},_this}return inherits(RTSPClient,BaseClient),createClass(RTSPClient,[{key:"setSource",value:function(url){get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"setSource",this).call(this,url),this.clientSM.setSource(url)}},{key:"attachTransport",value:function(transport){get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"attachTransport",this).call(this,transport),this.clientSM.transport=transport}},{key:"detachTransport",value:function(){get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"detachTransport",this).call(this),this.clientSM.transport=null}},{key:"reset",value:function(){get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"reset",this).call(this),this.sampleQueues={}}},{key:"destroy",value:function(){return this.clientSM.destroy(),get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"destroy",this).call(this)}},{key:"start",value:function(){var _this2=this;return get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"start",this).call(this),this.transport?this.transport.ready.then(function(){return _this2.clientSM.start()}):Promise.reject("no transport attached")}},{key:"onData",value:function(data){this.clientSM.onData(data)}},{key:"onConnected",value:function(){this.clientSM.onConnected(),get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"onConnected",this).call(this)}},{key:"onDisconnected",value:function(){get(RTSPClient.prototype.__proto__||Object.getPrototypeOf(RTSPClient.prototype),"onDisconnected",this).call(this),this.clientSM.onDisconnected()}}],[{key:"streamType",value:function(){return"rtsp"}}]),RTSPClient}(),AuthError=function(_Error){function AuthError(msg){return classCallCheck(this,AuthError),possibleConstructorReturn(this,(AuthError.__proto__||Object.getPrototypeOf(AuthError)).call(this,msg))}return inherits(AuthError,_Error),AuthError}(Error),RTSPError=function(_Error2){function RTSPError(data){classCallCheck(this,RTSPError);var _this4=possibleConstructorReturn(this,(RTSPError.__proto__||Object.getPrototypeOf(RTSPError)).call(this,data.msg));return _this4.data=data,_this4}return inherits(RTSPError,_Error2),RTSPError}(Error),RTSPClientSM=function(_StateMachine){function RTSPClientSM(parent){classCallCheck(this,RTSPClientSM);var _this5=possibleConstructorReturn(this,(RTSPClientSM.__proto__||Object.getPrototypeOf(RTSPClientSM)).call(this));return _this5.parent=parent,_this5.transport=null,_this5.payParser=new RTPPayloadParser,_this5.rtp_channels=new Set,_this5.ontracks=null,_this5.addState(RTSPClientSM.STATE_INITIAL,{}).addState(RTSPClientSM.STATE_OPTIONS,{activate:_this5.sendOptions,finishTransition:_this5.onOptions}).addState(RTSPClientSM.STATE_DESCRIBE,{activate:_this5.sendDescribe,finishTransition:_this5.onDescribe}).addState(RTSPClientSM.STATE_SETUP,{activate:_this5.sendSetup,finishTransition:_this5.onSetup}).addState(RTSPClientSM.STATE_STREAMS,{}).addState(RTSPClientSM.STATE_TEARDOWN,{activate:function(){_this5.started=!1},finishTransition:function(){return _this5.transitionTo(RTSPClientSM.STATE_INITIAL)}}).addTransition(RTSPClientSM.STATE_INITIAL,RTSPClientSM.STATE_OPTIONS).addTransition(RTSPClientSM.STATE_INITIAL,RTSPClientSM.STATE_TEARDOWN).addTransition(RTSPClientSM.STATE_OPTIONS,RTSPClientSM.STATE_DESCRIBE).addTransition(RTSPClientSM.STATE_DESCRIBE,RTSPClientSM.STATE_SETUP).addTransition(RTSPClientSM.STATE_SETUP,RTSPClientSM.STATE_STREAMS).addTransition(RTSPClientSM.STATE_TEARDOWN,RTSPClientSM.STATE_INITIAL).addTransition(RTSPClientSM.STATE_STREAMS,RTSPClientSM.STATE_TEARDOWN).addTransition(RTSPClientSM.STATE_SETUP,RTSPClientSM.STATE_TEARDOWN).addTransition(RTSPClientSM.STATE_DESCRIBE,RTSPClientSM.STATE_TEARDOWN).addTransition(RTSPClientSM.STATE_OPTIONS,RTSPClientSM.STATE_TEARDOWN),_this5.reset(),_this5.shouldReconnect=!1,_this5}return inherits(RTSPClientSM,StateMachine),createClass(RTSPClientSM,null,[{key:"USER_AGENT",get:function(){return"SFRtsp 0.3"}},{key:"STATE_INITIAL",get:function(){return 1}},{key:"STATE_OPTIONS",get:function(){return 2}},{key:"STATE_DESCRIBE",get:function(){return 4}},{key:"STATE_SETUP",get:function(){return 8}},{key:"STATE_STREAMS",get:function(){return 16}},{key:"STATE_TEARDOWN",get:function(){return 32}}]),createClass(RTSPClientSM,[{key:"destroy",value:function(){this.parent=null}},{key:"setSource",value:function(url){this.reset(),this.endpoint=url,this.url=url.full}},{key:"onConnected",value:function(){this.rtpFactory&&(this.rtpFactory=null),this.shouldReconnect&&this.start()}},{key:"onDisconnected",value:function(){return __async(regeneratorRuntime.mark(function _callee(){return regeneratorRuntime.wrap(function(_context){for(;;)switch(_context.prev=_context.next){case 0:return this.reset(),this.shouldReconnect=!0,_context.next=4,this.transitionTo(RTSPClientSM.STATE_TEARDOWN);case 4:return _context.next=6,this.transitionTo(RTSPClientSM.STATE_INITIAL);case 6:case"end":return _context.stop()}},_callee,this)}).call(this))}},{key:"start",value:function(){return this.currentState.name!==RTSPClientSM.STATE_STREAMS?this.transitionTo(RTSPClientSM.STATE_OPTIONS):Promise.resolve()}},{key:"onData",value:function(data){var channel=data[1];this.rtp_channels.has(channel)&&this.onRTP({packet:data.subarray(4),type:channel})}},{key:"useRTPChannel",value:function(channel){this.rtp_channels.add(channel)}},{key:"forgetRTPChannel",value:function(channel){this.rtp_channels.delete(channel)}},{key:"stop",value:function(){this.shouldReconnect=!1}},{key:"reset",value:function(){return __async(regeneratorRuntime.mark(function _callee2(){var stream;return regeneratorRuntime.wrap(function(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:this.authenticator="",this.methods=[],this.tracks=[],this.rtpBuffer={};for(stream in this.streams)this.streams[stream].reset();if(this.streams={},this.contentBase="",!this.currentState){_context2.next=15;break}if(this.currentState.name==RTSPClientSM.STATE_INITIAL){_context2.next=13;break}return _context2.next=11,this.transitionTo(RTSPClientSM.STATE_TEARDOWN);case 11:return _context2.next=13,this.transitionTo(RTSPClientSM.STATE_INITIAL);case 13:_context2.next=17;break;case 15:return _context2.next=17,this.transitionTo(RTSPClientSM.STATE_INITIAL);case 17:this.sdp=null,this.interleaveChannelIndex=0,this.session=null,this.timeOffset={},this.lastTimestamp={};case 22:case"end":return _context2.stop()}},_callee2,this)}).call(this))}},{key:"reconnect",value:function(){return __async(regeneratorRuntime.mark(function _callee3(){return regeneratorRuntime.wrap(function(_context3){for(;;)switch(_context3.prev=_context3.next){case 0:return _context3.next=2,this.reset();case 2:if(this.currentState.name==RTSPClientSM.STATE_INITIAL){_context3.next=8;break}return _context3.next=5,this.transitionTo(RTSPClientSM.STATE_TEARDOWN);case 5:case 8:return _context3.abrupt("return",this.transitionTo(RTSPClientSM.STATE_OPTIONS));case 9:case"end":return _context3.stop()}},_callee3,this)}).call(this))}},{key:"supports",value:function(method){return this.methods.includes(method)}},{key:"parse",value:function(_data){Log$7.debug(_data.payload);var d=_data.payload.split("\r\n\r\n"),parsed=MessageBuilder.parse(d[0]);if(Number(parsed.headers["content-length"])){var _d=_data.payload.split("\r\n\r\n");parsed.body=_d[1]}else parsed.body="";return parsed}},{key:"sendRequest",value:function(_cmd,_host){var _this6=this,_params=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},_payload=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return this.cSeq++,Object.assign(_params,{CSeq:this.cSeq,"User-Agent":RTSPClientSM.USER_AGENT}),this.authenticator&&(_params.Authorization=this.authenticator(_cmd)),this.send(MessageBuilder.build(_cmd,_host,_params,_payload),_cmd).catch(function(e){if(e instanceof AuthError)return _this6.sendRequest(_cmd,_host,_params,_payload);throw e})}},{key:"send",value:function(_data,_method){return __async(regeneratorRuntime.mark(function _callee4(){var response,parsed,auth,method,chunks,ep,parsedChunks,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,chunk,c,_c$split,_c$split2,k,v,_this7=this;return regeneratorRuntime.wrap(function(_context4){for(;;)switch(_context4.prev=_context4.next){case 0:if(!this.transport){_context4.next=63;break}return _context4.prev=1,_context4.next=4,this.transport.ready;case 4:_context4.next=10;break;case 6:throw _context4.prev=6,_context4.t0=_context4.catch(1),this.onDisconnected(),_context4.t0;case 10:return Log$7.debug(_data),_context4.next=13,this.transport.send(_data);case 13:if(response=_context4.sent,401!=(parsed=this.parse(response)).code){_context4.next=57;break}if(Log$7.debug(parsed.headers["www-authenticate"]),auth=parsed.headers["www-authenticate"],method=auth.substring(0,auth.indexOf(" ")),auth=auth.substr(method.length+1),chunks=auth.split(","),(ep=this.parent.endpoint).user&&ep.pass){_context4.next=31;break}return _context4.prev=23,_context4.next=26,this.parent.queryCredentials.call(this.parent);case 26:_context4.next=31;break;case 28:throw _context4.prev=28,_context4.t1=_context4.catch(23),new AuthError;case 31:if("digest"!=method.toLowerCase()){_context4.next=55;break}for(parsedChunks={},_iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0,_context4.prev=36,_iterator=chunks[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0)chunk=_step.value,c=chunk.trim(),_c$split=c.split("="),_c$split2=slicedToArray(_c$split,2),k=_c$split2[0],v=_c$split2[1],parsedChunks[k]=v.substr(1,v.length-2);_context4.next=44;break;case 40:_context4.prev=40,_context4.t2=_context4.catch(36),_didIteratorError=!0,_iteratorError=_context4.t2;case 44:_context4.prev=44,_context4.prev=45,!_iteratorNormalCompletion&&_iterator.return&&_iterator.return();case 47:if(_context4.prev=47,!_didIteratorError){_context4.next=50;break}throw _iteratorError;case 50:return _context4.finish(47);case 51:return _context4.finish(44);case 52:this.authenticator=function(_method){var ep=_this7.parent.endpoint,ha1=md5(ep.user+":"+parsedChunks.realm+":"+ep.pass),ha2=md5(_method+":"+ep.urlpath),response=md5(ha1+":"+parsedChunks.nonce+":"+ha2);return'Digest username="'+ep.user+'", nonce="'+parsedChunks.nonce+'", uri="'+ep.urlpath+'", response="'+response+'"'},_context4.next=56;break;case 55:this.authenticator=function(){return"Basic "+btoa(_this7.parent.endpoint.auth)};case 56:throw new AuthError(parsed);case 57:if(!(parsed.code>=300)){_context4.next=60;break}throw Log$7.error(parsed.statusLine),new RTSPError({msg:"RTSP error: "+parsed.code+" "+parsed.statusLine,parsed:parsed});case 60:return _context4.abrupt("return",parsed);case 63:return _context4.abrupt("return",Promise.reject("No transport attached"));case 64:case"end":return _context4.stop()}},_callee4,this,[[1,6],[23,28],[36,40,44,52],[45,,47,51]])}).call(this))}},{key:"sendOptions",value:function(){return this.reset(),this.started=!0,this.cSeq=0,this.sendRequest("OPTIONS","*",{})}},{key:"onOptions",value:function(data){this.methods=data.headers.public.split(",").map(function(e){return e.trim()}),this.transitionTo(RTSPClientSM.STATE_DESCRIBE)}},{key:"sendDescribe",value:function(){var _this8=this;return this.sendRequest("DESCRIBE",this.url,{Accept:"application/sdp"}).then(function(data){return _this8.sdp=new SDPParser,_this8.sdp.parse(data.body).catch(function(){throw new Error("Failed to parse SDP")}).then(function(){return data})})}},{key:"onDescribe",value:function(data){if(this.contentBase=data.headers["content-base"]||this.url,this.tracks=this.sdp.getMediaBlockList(),this.rtpFactory=new RTPFactory(this.sdp),Log$7.log("SDP contained "+this.tracks.length+" track(s). Calling SETUP for each."),data.headers.session&&(this.session=data.headers.session),!this.tracks.length)throw new Error("No tracks in SDP");this.transitionTo(RTSPClientSM.STATE_SETUP)}},{key:"sendSetup",value:function(){var _this9=this,streams=[],_iteratorNormalCompletion2=!0,_didIteratorError2=!1,_iteratorError2=void 0;try{for(var _step2,_iterator2=this.tracks[Symbol.iterator]();!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=!0){var track_type=_step2.value;Log$7.log("setup track: "+track_type);var track=this.sdp.getMediaBlock(track_type);if(PayloadType.string_map[track.rtpmap[track.fmt[0]].name]){this.streams[track_type]=new RTSPStream(this,track);var playPromise=this.streams[track_type].start();this.parent.sampleQueues[PayloadType.string_map[track.rtpmap[track.fmt[0]].name]]=[],this.rtpBuffer[track.fmt[0]]=[],streams.push(playPromise.then(function(_ref){var track=_ref.track,data=_ref.data;_this9.timeOffset[track.fmt[0]]=0;try{var rtp_info=data.headers["rtp-info"].split(";"),_iteratorNormalCompletion3=!0,_didIteratorError3=!1,_iteratorError3=void 0;try{for(var _step3,_iterator3=rtp_info[Symbol.iterator]();!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=!0){var _chunk$split=_step3.value.split("="),_chunk$split2=slicedToArray(_chunk$split,2),key=_chunk$split2[0],val=_chunk$split2[1];"rtptime"===key&&(_this9.timeOffset[track.fmt[0]]=Number(val))}}catch(err){_didIteratorError3=!0,_iteratorError3=err}finally{try{!_iteratorNormalCompletion3&&_iterator3.return&&_iterator3.return()}finally{if(_didIteratorError3)throw _iteratorError3}}}catch(e){}var params={timescale:0,scaleFactor:0};if(track.fmtp["sprop-parameter-sets"]){var sps_pps=track.fmtp["sprop-parameter-sets"].split(",");params={sps:base64ToArrayBuffer(sps_pps[0]),pps:base64ToArrayBuffer(sps_pps[1])}}else if(track.fmtp.config){var config=track.fmtp.config;_this9.has_config="0"!=track.fmtp.cpresent;"MPEG4-GENERIC"==track.rtpmap[track.fmt[0]].name?(params={config:AACParser.parseAudioSpecificConfig(hexToByteArray(config))},_this9.payParser.aacparser.setConfig(params.config)):config&&(params={config:AACParser.parseStreamMuxConfig(hexToByteArray(config))},_this9.payParser.aacparser.setConfig(params.config))}params.duration=_this9.sdp.sessionBlock.range?_this9.sdp.sessionBlock.range[1]-_this9.sdp.sessionBlock.range[0]:1,_this9.parent.seekable=params.duration>1;return{track:track,offset:_this9.timeOffset[track.fmt[0]],type:PayloadType.string_map[track.rtpmap[track.fmt[0]].name],params:params,duration:params.duration}}))}}}catch(err){_didIteratorError2=!0,_iteratorError2=err}finally{try{!_iteratorNormalCompletion2&&_iterator2.return&&_iterator2.return()}finally{if(_didIteratorError2)throw _iteratorError2}}return Promise.all(streams).then(function(tracks){_this9.ontracks&&_this9.ontracks(tracks)}).catch(function(){_this9.stop(),_this9.reset()})}},{key:"onSetup",value:function(){this.transitionTo(RTSPClientSM.STATE_STREAMS)}},{key:"onRTP",value:function(_data){if(this.rtpFactory){var rtp=this.rtpFactory.build(_data.packet,this.sdp);if(rtp.type){if(void 0===this.timeOffset[rtp.pt])return console.log(rtp.pt,this.timeOffset[rtp.pt]),void this.rtpBuffer[rtp.pt].push(rtp);void 0===this.lastTimestamp[rtp.pt]&&(this.lastTimestamp[rtp.pt]=rtp.timestamp-this.timeOffset[rtp.pt]);var queue=this.rtpBuffer[rtp.pt];for(queue.push(rtp);queue.length;){var _rtp=queue.shift();if(_rtp.timestamp=_rtp.timestamp-this.timeOffset[_rtp.pt]-this.lastTimestamp[_rtp.pt],_rtp.media){var pay=this.payParser.parse(_rtp);pay&&this.parent.sampleQueues[_rtp.type].push(pay)}}}}}}]),RTSPClientSM}(),DOM_tag=function(tagName,className){var t=document.createElement(tagName);return t.className=className,t},DOM_text=function(str){return document.createTextNode(str)},Stream=function(){function Stream(enc,pos){classCallCheck(this,Stream),enc instanceof Stream?(this.enc=enc.enc,this.pos=enc.pos):(this.enc=enc,this.pos=pos)}return createClass(Stream,null,[{key:"hexDigits",get:function(){return"0123456789ABCDEF"}},{key:"reTime",get:function(){return/^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/}}]),createClass(Stream,[{key:"get",value:function(pos){if(void 0===pos&&(pos=this.pos++),pos>=this.enc.length)throw"Requesting byte offset "+pos+" on a stream of length "+this.enc.length;return this.enc[pos]}},{key:"hexByte",value:function(b){return Stream.hexDigits.charAt(b>>4&15)+Stream.hexDigits.charAt(15&b)}},{key:"hexDump",value:function(start,end,raw){for(var s="",i=start;i191&&c<224?String.fromCharCode((31&c)<<6|63&this.get(i++)):String.fromCharCode((15&c)<<12|(63&this.get(i++))<<6|63&this.get(i++))}return s}},{key:"parseStringBMP",value:function(start,end){for(var str="",i=start;i4){len<<=3;var s=this.get(start);if(0===s)len-=8;else for(;s<128;)s<<=1,--len;return"("+len+" bit)"}for(var n=0,i=start;istart;--i){for(var b=this.get(i),j=skip;j<8;++j)s+=b>>j&1?"1":"0";skip=0}}return s}},{key:"parseOctetString",value:function(start,end){var len=end-start,s="("+len+" byte) ";len>100&&(end=start+100);for(var i=start;i100&&(s+="…"),s}},{key:"parseOID",value:function(start,end){for(var s="",n=0,bits=0,i=start;i=31?"bigint":n);n=bits=0}}return s}}]),Stream}(),ASN1=function(){function ASN1(stream,header,length,tag,sub){classCallCheck(this,ASN1),this.stream=stream,this.header=header,this.length=length,this.tag=tag,this.sub=sub}return createClass(ASN1,null,[{key:"reSeemsASCII",get:function(){return/^[ -~]+$/}}]),createClass(ASN1,[{key:"typeName",value:function(){if(void 0===this.tag)return"unknown";var tagClass=this.tag>>6,tagNumber=(this.tag,31&this.tag);switch(tagClass){case 0:switch(tagNumber){case 0:return"EOC";case 1:return"BOOLEAN";case 2:return"INTEGER";case 3:return"BIT_STRING";case 4:return"OCTET_STRING";case 5:return"NULL";case 6:return"OBJECT_IDENTIFIER";case 7:return"ObjectDescriptor";case 8:return"EXTERNAL";case 9:return"REAL";case 10:return"ENUMERATED";case 11:return"EMBEDDED_PDV";case 12:return"UTF8String";case 16:return"SEQUENCE";case 17:return"SET";case 18:return"NumericString";case 19:return"PrintableString";case 20:return"TeletexString";case 21:return"VideotexString";case 22:return"IA5String";case 23:return"UTCTime";case 24:return"GeneralizedTime";case 25:return"GraphicString";case 26:return"VisibleString";case 27:return"GeneralString";case 28:return"UniversalString";case 30:return"BMPString";default:return"Universal_"+tagNumber.toString(16)}case 1:return"Application_"+tagNumber.toString(16);case 2:return"["+tagNumber+"]";case 3:return"Private_"+tagNumber.toString(16)}}},{key:"content",value:function(){if(void 0===this.tag)return null;var tagClass=this.tag>>6,tagNumber=31&this.tag,content=this.posContent(),len=Math.abs(this.length);if(0!==tagClass){if(null!==this.sub)return"("+this.sub.length+" elem)";var s=this.stream.parseStringISO(content,content+Math.min(len,100));return ASN1.reSeemsASCII.test(s)?s.substring(0,200)+(s.length>200?"…":""):this.stream.parseOctetString(content,content+len)}switch(tagNumber){case 1:return 0===this.stream.get(content)?"false":"true";case 2:return this.stream.parseInteger(content,content+len);case 3:return this.sub?"("+this.sub.length+" elem)":this.stream.parseBitString(content,content+len);case 4:return this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(content,content+len);case 6:return this.stream.parseOID(content,content+len);case 16:case 17:return"("+this.sub.length+" elem)";case 12:return this.stream.parseStringUTF(content,content+len);case 18:case 19:case 20:case 21:case 22:case 26:return this.stream.parseStringISO(content,content+len);case 30:return this.stream.parseStringBMP(content,content+len);case 23:case 24:return this.stream.parseTime(content,content+len)}return null}},{key:"toString",value:function(){return this.typeName()+"@"+this.stream.pos+"[header:"+this.header+",length:"+this.length+",sub:"+(null===this.sub?"null":this.sub.length)+"]"}},{key:"print",value:function(indent){if(void 0===indent&&(indent=""),document.writeln(indent+this),null!==this.sub){indent+=" ";for(var i=0,max=this.sub.length;i=0&&(s+="+"),s+=this.length,32&this.tag?s+=" (constructed)":3!=this.tag&&4!=this.tag||null===this.sub||(s+=" (encapsulates)"),s+="\n",null!==this.sub){indent+=" ";for(var i=0,max=this.sub.length;i",s+="Length: "+this.header+"+",this.length>=0?s+=this.length:s+=-this.length+" (undefined)",32&this.tag?s+="
(constructed)":3!=this.tag&&4!=this.tag||null===this.sub||(s+="
(encapsulates)"),null!==content&&(s+="
Value:
"+content+"","object"===("undefined"==typeof oids?"undefined":_typeof(oids))&&6==this.tag)){var oid=oids[content];oid&&(oid.d&&(s+="
"+oid.d),oid.c&&(s+="
"+oid.c),oid.w&&(s+="
(warning!)"))}value.innerHTML=s,node.appendChild(value);var sub=DOM_tag("div","sub");if(null!==this.sub)for(var i=0,max=this.sub.length;i=end)){var sub=DOM_tag("span",className);sub.appendChild(DOM_text(stream.hexDump(start,end))),node.appendChild(sub)}}},{key:"toHexDOM",value:function(root){var node=DOM_tag("span","hex");if(void 0===root&&(root=node),this.head.hexNode=node,this.head.onmouseover=function(){this.hexNode.className="hexCurrent"},this.head.onmouseout=function(){this.hexNode.className="hex"},node.asn1=this,node.onmouseover=function(){var current=!root.selected;current&&(root.selected=this.asn1,this.className="hexCurrent"),this.asn1.fakeHover(current)},node.onmouseout=function(){var current=root.selected==this.asn1;this.asn1.fakeOut(current),current&&(root.selected=null,this.className="hex")},this.toHexDOM_sub(node,"tag",this.stream,this.posStart(),this.posStart()+1),this.toHexDOM_sub(node,this.length>=0?"dlen":"ulen",this.stream,this.posStart()+1,this.posContent()),null===this.sub)node.appendChild(DOM_text(this.stream.hexDump(this.posContent(),this.posEnd())));else if(this.sub.length>0){var first=this.sub[0],last=this.sub[this.sub.length-1];this.toHexDOM_sub(node,"intro",this.stream,this.posContent(),first.posStart());for(var i=0,max=this.sub.length;i3)throw"Length over 24 bits not supported at position "+(stream.pos-1);if(0===len)return-1;buf=0;for(var i=0;i4)return!1;var p=new Stream(stream);3==tag&&p.get();if(p.get()>>6&1)return!1;try{var subLength=ASN1.decodeLength(p);return p.pos-stream.pos+subLength==len}catch(exception){return!1}},ASN1.decode=function(stream){stream instanceof Stream||(stream=new Stream(stream,0));var streamStart=new Stream(stream),tag=stream.get(),len=ASN1.decodeLength(stream),header=stream.pos-streamStart.pos,sub=null;if(ASN1.hasContent(tag,len,stream)){var start=stream.pos;if(3==tag&&stream.get(),sub=[],len>=0){for(var end=start+len;stream.pos=256||rng_pptr>=rng_psize)window.removeEventListener?window.removeEventListener("mousemove",onMouseMoveListener,!1):window.detachEvent&&window.detachEvent("onmousemove",onMouseMoveListener);else try{var mouseCoordinates=ev.x+ev.y;rng_pool[rng_pptr++]=255&mouseCoordinates,this.count+=1}catch(e){}};window.addEventListener?window.addEventListener("mousemove",onMouseMoveListener,!1):window.attachEvent&&window.attachEvent("onmousemove",onMouseMoveListener)}var SecureRandom=function SecureRandom(){classCallCheck(this,SecureRandom)};SecureRandom.prototype.nextBytes=function(ba){var i;for(i=0;i>15;--n>=0;){var l=32767&this[i],h=this[i++]>>15,m=xh*l+h*xl;c=((l=xl*l+((32767&m)<<15)+w[j]+(1073741823&c))>>>30)+(m>>>15)+xh*h+(c>>>30),w[j++]=1073741823&l}return c},dbits=30):"Netscape"!=navigator.appName?(BigInteger.prototype.am=function(i,x,w,j,c,n){for(;--n>=0;){var v=x*this[i++]+w[j]+c;c=Math.floor(v/67108864),w[j++]=67108863&v}return c},dbits=26):(BigInteger.prototype.am=function(i,x,w,j,c,n){for(var xl=16383&x,xh=x>>14;--n>=0;){var l=16383&this[i],h=this[i++]>>14,m=xh*l+h*xl;c=((l=xl*l+((16383&m)<<14)+w[j]+c)>>28)+(m>>14)+xh*h,w[j++]=268435455&l}return c},dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<=0?x.mod(this.m):x},Classic.prototype.revert=function(x){return x},Classic.prototype.reduce=function(x){x.divRemTo(this.m,null,x)},Classic.prototype.mulTo=function(x,y,r){x.multiplyTo(y,r),this.reduce(r)},Classic.prototype.sqrTo=function(x,r){x.squareTo(r),this.reduce(r)};var Montgomery=function Montgomery(m){classCallCheck(this,Montgomery),this.m=m,this.mp=m.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(r,r),r},Montgomery.prototype.revert=function(x){var r=nbi();return x.copyTo(r),this.reduce(r),r},Montgomery.prototype.reduce=function(x){for(;x.t<=this.mt2;)x[x.t++]=0;for(var i=0;i>15)*this.mpl&this.um)<<15)&x.DM;for(x[j=i+this.m.t]+=this.m.am(0,u0,x,i,0,this.m.t);x[j]>=x.DV;)x[j]-=x.DV,x[++j]++}x.clamp(),x.drShiftTo(this.m.t,x),x.compareTo(this.m)>=0&&x.subTo(this.m,x)},Montgomery.prototype.mulTo=function(x,y,r){x.multiplyTo(y,r),this.reduce(r)},Montgomery.prototype.sqrTo=function(x,r){x.squareTo(r),this.reduce(r)},BigInteger.prototype.copyTo=function(r){for(var i=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t,r.s=this.s},BigInteger.prototype.fromInt=function(x){this.t=1,this.s=x<0?-1:0,x>0?this[0]=x:x<-1?this[0]=x+this.DV:this.t=0},BigInteger.prototype.fromString=function(s,b){var k;if(16==b)k=4;else if(8==b)k=3;else if(256==b)k=8;else if(2==b)k=1;else if(32==b)k=5;else{if(4!=b)return void this.fromRadix(s,b);k=2}this.t=0,this.s=0;for(var i=s.length,mi=!1,sh=0;--i>=0;){var x=8==k?255&s[i]:intAt(s,i);x<0?"-"==s.charAt(i)&&(mi=!0):(mi=!1,0==sh?this[this.t++]=x:sh+k>this.DB?(this[this.t-1]|=(x&(1<>this.DB-sh):this[this.t-1]|=x<=this.DB&&(sh-=this.DB))}8==k&&0!=(128&s[0])&&(this.s=-1,sh>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==c;)--this.t},BigInteger.prototype.dlShiftTo=function(n,r){var i;for(i=this.t-1;i>=0;--i)r[i+n]=this[i];for(i=n-1;i>=0;--i)r[i]=0;r.t=this.t+n,r.s=this.s},BigInteger.prototype.drShiftTo=function(n,r){for(var i=n;i=0;--i)r[i+ds+1]=this[i]>>cbs|c,c=(this[i]&bm)<=0;--i)r[i]=0;r[ds]=c,r.t=this.t+ds+1,r.s=this.s,r.clamp()},BigInteger.prototype.rShiftTo=function(n,r){r.s=this.s;var ds=Math.floor(n/this.DB);if(ds>=this.t)r.t=0;else{var bs=n%this.DB,cbs=this.DB-bs,bm=(1<>bs;for(var i=ds+1;i>bs;bs>0&&(r[this.t-ds-1]|=(this.s&bm)<>=this.DB;if(a.t>=this.DB;c+=this.s}else{for(c+=this.s;i>=this.DB;c-=a.s}r.s=c<0?-1:0,c<-1?r[i++]=this.DV+c:c>0&&(r[i++]=c),r.t=i,r.clamp()},BigInteger.prototype.multiplyTo=function(a,r){var x=this.abs(),y=a.abs(),i=x.t;for(r.t=i+y.t;--i>=0;)r[i]=0;for(i=0;i=0;)r[i]=0;for(i=0;i=x.DV&&(r[i+x.t]-=x.DV,r[i+x.t+1]=1)}r.t>0&&(r[r.t-1]+=x.am(i,x[i],r,2*i,0,1)),r.s=0,r.clamp()},BigInteger.prototype.divRemTo=function(m,q,r){var pm=m.abs();if(!(pm.t<=0)){var pt=this.abs();if(pt.t0?(pm.lShiftTo(nsh,y),pt.lShiftTo(nsh,r)):(pm.copyTo(y),pt.copyTo(r));var ys=y.t,y0=y[ys-1];if(0!=y0){var yt=y0*(1<1?y[ys-2]>>this.F2:0),d1=this.FV/yt,d2=(1<=0&&(r[r.t++]=1,r.subTo(t,r)),BigInteger.ONE.dlShiftTo(ys,t),t.subTo(y,y);y.t=0;){var qd=r[--i]==y0?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);if((r[i]+=y.am(0,qd,r,j,0,ys))0&&r.rShiftTo(nsh,r),ts<0&&BigInteger.ZERO.subTo(r,r)}}},BigInteger.prototype.invDigit=function(){if(this.t<1)return 0;var x=this[0];if(0==(1&x))return 0;var y=3&x;return y=y*(2-(15&x)*y)&15,y=y*(2-(255&x)*y)&255,y=y*(2-((65535&x)*y&65535))&65535,(y=y*(2-x*y%this.DV)%this.DV)>0?this.DV-y:-y},BigInteger.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},BigInteger.prototype.exp=function(e,z){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),r2=nbi(),g=z.convert(this),i=nbits(e)-1;for(g.copyTo(r);--i>=0;)if(z.sqrTo(r,r2),(e&1<0)z.mulTo(r2,g,r);else{var t=r;r=r2,r2=t}return z.revert(r)},BigInteger.prototype.toString=function(b){if(this.s<0)return"-"+this.negate().toString(b);var k;if(16==b)k=4;else if(8==b)k=3;else if(2==b)k=1;else if(32==b)k=5;else{if(4!=b)return this.toRadix(b);k=2}var d,km=(1<0)for(p>p)>0&&(m=!0,r=int2char(d));i>=0;)p>(p+=this.DB-k)):(d=this[i]>>(p-=k)&km,p<=0&&(p+=this.DB,--i)),d>0&&(m=!0),m&&(r+=int2char(d));return m?r:"0"},BigInteger.prototype.negate=function(){var r=nbi();return BigInteger.ZERO.subTo(this,r),r},BigInteger.prototype.abs=function(){return this.s<0?this.negate():this},BigInteger.prototype.compareTo=function(a){var r=this.s-a.s;if(0!=r)return r;var i=this.t;if(0!=(r=i-a.t))return this.s<0?-r:r;for(;--i>=0;)if(0!=(r=this[i]-a[i]))return r;return 0},BigInteger.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)},BigInteger.prototype.mod=function(a){var r=nbi();return this.abs().divRemTo(a,null,r),this.s<0&&r.compareTo(BigInteger.ZERO)>0&&a.subTo(r,r),r},BigInteger.prototype.modPowInt=function(e,m){var z;return z=e<256||m.isEven()?new Classic(m):new Montgomery(m),this.exp(e,z)},BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1),NullExp.prototype.convert=nNop,NullExp.prototype.revert=nNop,NullExp.prototype.mulTo=function(x,y,r){x.multiplyTo(y,r)},NullExp.prototype.sqrTo=function(x,r){x.squareTo(r)},Barrett.prototype.convert=function(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);if(x.compareTo(this.m)<0)return x;var r=nbi();return x.copyTo(r),this.reduce(r),r},Barrett.prototype.revert=function(x){return x},Barrett.prototype.reduce=function(x){for(x.drShiftTo(this.m.t-1,this.r2),x.t>this.m.t+1&&(x.t=this.m.t+1,x.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);x.compareTo(this.r2)<0;)x.dAddOffset(1,this.m.t+1);for(x.subTo(this.r2,x);x.compareTo(this.m)>=0;)x.subTo(this.m,x)},Barrett.prototype.mulTo=function(x,y,r){x.multiplyTo(y,r),this.reduce(r)},Barrett.prototype.sqrTo=function(x,r){x.squareTo(r),this.reduce(r)};var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=(1<<26)/lowprimes[lowprimes.length-1];BigInteger.prototype.chunkSize=function(r){return Math.floor(Math.LN2*this.DB/Math.log(r))},BigInteger.prototype.toRadix=function(b){if(null==b&&(b=10),0==this.signum()||b<2||b>36)return"0";var cs=this.chunkSize(b),a=Math.pow(b,cs),d=nbv(a),y=nbi(),z=nbi(),r="";for(this.divRemTo(d,y,z);y.signum()>0;)r=(a+z.intValue()).toString(b).substr(1)+r,y.divRemTo(d,y,z);return z.intValue().toString(b)+r},BigInteger.prototype.fromRadix=function(s,b){this.fromInt(0),null==b&&(b=10);for(var cs=this.chunkSize(b),d=Math.pow(b,cs),mi=!1,j=0,w=0,i=0;i=cs&&(this.dMultiply(d),this.dAddOffset(w,0),j=0,w=0))}j>0&&(this.dMultiply(Math.pow(b,j)),this.dAddOffset(w,0)),mi&&BigInteger.ZERO.subTo(this,this)},BigInteger.prototype.fromNumber=function(a,b,c){if("number"==typeof b)if(a<2)this.fromInt(1);else for(this.fromNumber(a,c),this.testBit(a-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(b);)this.dAddOffset(2,0),this.bitLength()>a&&this.subTo(BigInteger.ONE.shiftLeft(a-1),this);else{var x=[],t=7&a;x.length=1+(a>>3),b.nextBytes(x),t>0?x[0]&=(1<>=this.DB;if(a.t>=this.DB;c+=this.s}else{for(c+=this.s;i>=this.DB;c+=a.s}r.s=c<0?-1:0,c>0?r[i++]=c:c<-1&&(r[i++]=this.DV+c),r.t=i,r.clamp()},BigInteger.prototype.dMultiply=function(n){this[this.t]=this.am(0,n-1,this,0,0,this.t),++this.t,this.clamp()},BigInteger.prototype.dAddOffset=function(n,w){if(0!=n){for(;this.t<=w;)this[this.t++]=0;for(this[w]+=n;this[w]>=this.DV;)this[w]-=this.DV,++w>=this.t&&(this[this.t++]=0),++this[w]}},BigInteger.prototype.multiplyLowerTo=function(a,n,r){var i=Math.min(this.t+a.t,n);for(r.s=0,r.t=i;i>0;)r[--i]=0;var j;for(j=r.t-this.t;i=0;)r[i]=0;for(i=Math.max(n-this.t,0);i0)if(0==d)r=this[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this[i])%n;return r},BigInteger.prototype.millerRabin=function(t){var n1=this.subtract(BigInteger.ONE),k=n1.getLowestSetBit();if(k<=0)return!1;var r=n1.shiftRight(k);(t=t+1>>1)>lowprimes.length&&(t=lowprimes.length);for(var a=nbi(),i=0;i>24},BigInteger.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},BigInteger.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},BigInteger.prototype.toByteArray=function(){var i=this.t,r=[];r[0]=this.s;var d,p=this.DB-i*this.DB%8,k=0;if(i-- >0)for(p>p)!=(this.s&this.DM)>>p&&(r[k++]=d|this.s<=0;)p<8?(d=(this[i]&(1<>(p+=this.DB-8)):(d=this[i]>>(p-=8)&255,p<=0&&(p+=this.DB,--i)),0!=(128&d)&&(d|=-256),0==k&&(128&this.s)!=(128&d)&&++k,(k>0||d!=this.s)&&(r[k++]=d);return r},BigInteger.prototype.equals=function(a){return 0==this.compareTo(a)},BigInteger.prototype.min=function(a){return this.compareTo(a)<0?this:a},BigInteger.prototype.max=function(a){return this.compareTo(a)>0?this:a},BigInteger.prototype.and=function(a){var r=nbi();return this.bitwiseTo(a,op_and,r),r},BigInteger.prototype.or=function(a){var r=nbi();return this.bitwiseTo(a,op_or,r),r},BigInteger.prototype.xor=function(a){var r=nbi();return this.bitwiseTo(a,op_xor,r),r},BigInteger.prototype.andNot=function(a){var r=nbi();return this.bitwiseTo(a,op_andnot,r),r},BigInteger.prototype.not=function(){for(var r=nbi(),i=0;i=this.t?0!=this.s:0!=(this[j]&1<1){var g2=nbi();for(z.sqrTo(g[1],g2);n<=km;)g[n]=nbi(),z.mulTo(g2,g[n-2],g[n]),n+=2}var w,t,j=e.t-1,is1=!0,r2=nbi();for(i=nbits(e[j])-1;j>=0;){for(i>=k1?w=e[j]>>i-k1&km:(w=(e[j]&(1<0&&(w|=e[j-1]>>this.DB+i-k1)),n=k;0==(1&w);)w>>=1,--n;if((i-=n)<0&&(i+=this.DB,--j),is1)g[w].copyTo(r),is1=!1;else{for(;n>1;)z.sqrTo(r,r2),z.sqrTo(r2,r),n-=2;n>0?z.sqrTo(r,r2):(t=r,r=r2,r2=t),z.mulTo(r2,g[w],r)}for(;j>=0&&0==(e[j]&1<=0?(u.subTo(v,u),ac&&a.subTo(c,a),b.subTo(d,b)):(v.subTo(u,v),ac&&c.subTo(a,c),d.subTo(b,d))}return 0!=v.compareTo(BigInteger.ONE)?BigInteger.ZERO:d.compareTo(m)>=0?d.subtract(m):d.signum()<0?(d.addTo(m,d),d.signum()<0?d.add(m):d):d},BigInteger.prototype.pow=function(e){return this.exp(e,new NullExp)},BigInteger.prototype.gcd=function(a){var x=this.s<0?this.negate():this.clone(),y=a.s<0?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y,y=t}var i=x.getLowestSetBit(),g=y.getLowestSetBit();if(g<0)return x;for(i0&&(x.rShiftTo(g,x),y.rShiftTo(g,y));x.signum()>0;)(i=x.getLowestSetBit())>0&&x.rShiftTo(i,x),(i=y.getLowestSetBit())>0&&y.rShiftTo(i,y),x.compareTo(y)>=0?(x.subTo(y,x),x.rShiftTo(1,x)):(y.subTo(x,y),y.rShiftTo(1,y));return g>0&&y.lShiftTo(g,y),y},BigInteger.prototype.isProbablePrime=function(t){var i,x=this.abs();if(1==x.t&&x[0]<=lowprimes[lowprimes.length-1]){for(i=0;i0&&E.length>0?(this.n=parseBigInt(N,16),this.e=parseInt(E,16)):console.error("Invalid RSA public key")},RSAKey.prototype.encrypt=function(text){var m=function(s,n){if(n=0&&n>0;){var c=s.charCodeAt(i--);c<128?ba[--n]=c:c>127&&c<2048?(ba[--n]=63&c|128,ba[--n]=c>>6|192):(ba[--n]=63&c|128,ba[--n]=c>>6&63|128,ba[--n]=c>>12|224)}ba[--n]=0;for(var rng=new SecureRandom,x=[];n>2;){for(x[0]=0;0==x[0];)rng.nextBytes(x);ba[--n]=x[0]}return ba[--n]=2,ba[--n]=0,new BigInteger(ba)}(text,this.n.bitLength()+7>>3);if(null==m)return null;var c=this.doPublic(m);if(null==c)return null;var h=c.toString(16);return 0==(1&h.length)?h:"0"+h},RSAKey.prototype.doPrivate=function(x){if(null==this.p||null==this.q)return x.modPow(this.d,this.n);for(var xp=x.mod(this.p).modPow(this.dmp1,this.p),xq=x.mod(this.q).modPow(this.dmq1,this.q);xp.compareTo(xq)<0;)xp=xp.add(this.p);return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq)},RSAKey.prototype.setPrivate=function(N,E,D){null!=N&&null!=E&&N.length>0&&E.length>0?(this.n=parseBigInt(N,16),this.e=parseInt(E,16),this.d=parseBigInt(D,16)):console.error("Invalid RSA private key")},RSAKey.prototype.setPrivateEx=function(N,E,D,P,Q,DP,DQ,C){null!=N&&null!=E&&N.length>0&&E.length>0?(this.n=parseBigInt(N,16),this.e=parseInt(E,16),this.d=parseBigInt(D,16),this.p=parseBigInt(P,16),this.q=parseBigInt(Q,16),this.dmp1=parseBigInt(DP,16),this.dmq1=parseBigInt(DQ,16),this.coeff=parseBigInt(C,16)):console.error("Invalid RSA private key")},RSAKey.prototype.generate=function(B,E){var rng=new SecureRandom,qs=B>>1;this.e=parseInt(E,16);for(var ee=new BigInteger(E,16);;){for(;this.p=new BigInteger(B-qs,1,rng),0!=this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(qs,1,rng),0!=this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var t=this.p;this.p=this.q,this.q=t}var p1=this.p.subtract(BigInteger.ONE),q1=this.q.subtract(BigInteger.ONE),phi=p1.multiply(q1);if(0==phi.gcd(ee).compareTo(BigInteger.ONE)){this.n=this.p.multiply(this.q),this.d=ee.modInverse(phi),this.dmp1=this.d.mod(p1),this.dmq1=this.d.mod(q1),this.coeff=this.q.modInverse(this.p);break}}},RSAKey.prototype.decrypt=function(ctext){var c=parseBigInt(ctext,16),m=this.doPrivate(c);return null==m?null:function(d,n){for(var b=d.toByteArray(),i=0;i=b.length)return null;for(var ret="";++i191&&c<224?(ret+=String.fromCharCode((31&c)<<6|63&b[i+1]),++i):(ret+=String.fromCharCode((15&c)<<12|(63&b[i+1])<<6|63&b[i+2]),i+=2)}return ret}(m,this.n.bitLength()+7>>3)};var Base64={},decoder=void 0;Base64.decode=function(a){var i;if(void 0===decoder){var ignore="= \f\n\r\t \u2028\u2029";for(decoder=[],i=0;i<64;++i)decoder["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i)]=i;for(i=0;i=4?(out[out.length]=bits>>16,out[out.length]=bits>>8&255,out[out.length]=255&bits,bits=0,char_count=0):bits<<=6}}switch(char_count){case 1:throw"Base64 encoding incomplete: at least 2 bits missing";case 2:out[out.length]=bits>>10;break;case 3:out[out.length]=bits>>16,out[out.length]=bits>>8&255}return out},Base64.re=/-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,Base64.unarmor=function(a){var m=Base64.re.exec(a);if(m)if(m[1])a=m[1];else{if(!m[2])throw"RegExp out of sync";a=m[2]}return Base64.decode(a)};var Hex={},decoder$1=void 0;Hex.decode=function(a){var i;if(void 0===decoder$1){var hex="0123456789ABCDEF",ignore=" \f\n\r\t \u2028\u2029";for(decoder$1=[],i=0;i<16;++i)decoder$1[hex.charAt(i)]=i;for(hex=hex.toLowerCase(),i=10;i<16;++i)decoder$1[hex.charAt(i)]=i;for(i=0;i=2?(out[out.length]=bits,bits=0,char_count=0):bits<<=4}}if(char_count)throw"Hex encoding incomplete: 4 bits missing";return out};var JSX={};JSX.env=JSX.env||{};var L=JSX,OP=Object.prototype,ADD=["toString","valueOf"];JSX.env.parseUA=function(agent){var m,numberify=function(s){var c=0;return parseFloat(s.replace(/\./g,function(){return 1==c++?"":"."}))},nav=navigator,o={ie:0,opera:0,gecko:0,webkit:0,chrome:0,mobile:null,air:0,ipad:0,iphone:0,ipod:0,ios:null,android:0,webos:0,caja:nav&&nav.cajaVersion,secure:!1,os:null},ua=agent||navigator&&navigator.userAgent,loc=window&&window.location,href=loc&&loc.href;return o.secure=href&&0===href.toLowerCase().indexOf("https"),ua&&(/windows|win32/i.test(ua)?o.os="windows":/macintosh/i.test(ua)?o.os="macintosh":/rhino/i.test(ua)&&(o.os="rhino"),/KHTML/.test(ua)&&(o.webkit=1),(m=ua.match(/AppleWebKit\/([^\s]*)/))&&m[1]&&(o.webkit=numberify(m[1]),/ Mobile\//.test(ua)?(o.mobile="Apple",(m=ua.match(/OS ([^\s]*)/))&&m[1]&&(m=numberify(m[1].replace("_","."))),o.ios=m,o.ipad=o.ipod=o.iphone=0,(m=ua.match(/iPad|iPod|iPhone/))&&m[0]&&(o[m[0].toLowerCase()]=o.ios)):((m=ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/))&&(o.mobile=m[0]),/webOS/.test(ua)&&(o.mobile="WebOS",(m=ua.match(/webOS\/([^\s]*);/))&&m[1]&&(o.webos=numberify(m[1]))),/ Android/.test(ua)&&(o.mobile="Android",(m=ua.match(/Android ([^\s]*);/))&&m[1]&&(o.android=numberify(m[1])))),(m=ua.match(/Chrome\/([^\s]*)/))&&m[1]?o.chrome=numberify(m[1]):(m=ua.match(/AdobeAIR\/([^\s]*)/))&&(o.air=m[0])),o.webkit||((m=ua.match(/Opera[\s\/]([^\s]*)/))&&m[1]?(o.opera=numberify(m[1]),(m=ua.match(/Version\/([^\s]*)/))&&m[1]&&(o.opera=numberify(m[1])),(m=ua.match(/Opera Mini[^;]*/))&&(o.mobile=m[0])):(m=ua.match(/MSIE\s([^;]*)/))&&m[1]?o.ie=numberify(m[1]):(m=ua.match(/Gecko\/([^\s]*)/))&&(o.gecko=1,(m=ua.match(/rv:([^\s\)]*)/))&&m[1]&&(o.gecko=numberify(m[1]))))),o},JSX.env.ua=JSX.env.parseUA(),JSX.isFunction=function(o){return"function"==typeof o||"[object Function]"===OP.toString.apply(o)},JSX._IEEnumFix=JSX.env.ua.ie?function(r,s){var i,fname,f;for(i=0;i15)throw"ASN.1 length too long to represent by 8x: n = "+n.toString(16);return(128+hNlen).toString(16)+hN},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""}},KJUR.asn1.DERAbstractString=function(params){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);this.getString=function(){return this.s},this.setString=function(newS){this.hTLV=null,this.isModified=!0,this.s=newS,this.hV=stohex(this.s)},this.setStringHex=function(newHexString){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=newHexString},this.getFreshValueHex=function(){return this.hV},void 0!==params&&(void 0!==params.str?this.setString(params.str):void 0!==params.hex&&this.setStringHex(params.hex))},JSX.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(params){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);this.localDateToUTC=function(d){utc=d.getTime()+6e4*d.getTimezoneOffset();return new Date(utc)},this.formatDate=function(dateObject,type){var pad=this.zeroPadding,d=this.localDateToUTC(dateObject),year=String(d.getFullYear());"utc"==type&&(year=year.substr(2,2));return year+pad(String(d.getMonth()+1),2)+pad(String(d.getDate()),2)+pad(String(d.getHours()),2)+pad(String(d.getMinutes()),2)+pad(String(d.getSeconds()),2)+"Z"},this.zeroPadding=function(s,len){return s.length>=len?s:new Array(len-s.length+1).join("0")+s},this.getString=function(){return this.s},this.setString=function(newS){this.hTLV=null,this.isModified=!0,this.s=newS,this.hV=stohex(this.s)},this.setByDateValue=function(year,month,day,hour,min,sec){var dateObject=new Date(Date.UTC(year,month-1,day,hour,min,sec,0));this.setByDate(dateObject)},this.getFreshValueHex=function(){return this.hV}},JSX.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(params){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);this.setByASN1ObjectArray=function(asn1ObjectArray){this.hTLV=null,this.isModified=!0,this.asn1Array=asn1ObjectArray},this.appendASN1Object=function(asn1Object){this.hTLV=null,this.isModified=!0,this.asn1Array.push(asn1Object)},this.asn1Array=new Array,void 0!==params&&void 0!==params.array&&(this.asn1Array=params.array)},JSX.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV="0101ff"},JSX.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(params){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(bigIntegerValue){this.hTLV=null,this.isModified=!0,this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue)},this.setByInteger=function(intValue){var bi=new BigInteger(String(intValue),10);this.setByBigInteger(bi)},this.setValueHex=function(newHexString){this.hV=newHexString},this.getFreshValueHex=function(){return this.hV},void 0!==params&&(void 0!==params.bigint?this.setByBigInteger(params.bigint):void 0!==params.int?this.setByInteger(params.int):void 0!==params.hex&&this.setValueHex(params.hex))},JSX.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(params){KJUR.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(newHexStringIncludingUnusedBits){this.hTLV=null,this.isModified=!0,this.hV=newHexStringIncludingUnusedBits},this.setUnusedBitsAndHexValue=function(unusedBits,hValue){if(unusedBits<0||7>2),slop=3&v,k=1):1==k?(ret+=int2char(slop<<2|v>>4),slop=15&v,k=2):2==k?(ret+=int2char(slop),ret+=int2char(v>>2),slop=3&v,k=3):(ret+=int2char(slop<<2|v>>4),ret+=int2char(15&v),k=0))}return 1==k&&(ret+=int2char(slop<<2)),ret}(string))}catch(ex){return!1}},JSEncrypt.prototype.encrypt=function(string){try{return hex2b64(this.getKey().encrypt(string))}catch(ex){return!1}},JSEncrypt.prototype.getKey=function(cb){if(!this.key){if(this.key=new JSEncryptRSAKey,cb&&"[object Function]"==={}.toString.call(cb))return void this.key.generateAsync(this.default_key_size,this.default_public_exponent,cb);this.key.generate(this.default_key_size,this.default_public_exponent)}return this.key},JSEncrypt.prototype.getPrivateKey=function(){return this.getKey().getPrivateKey()},JSEncrypt.prototype.getPrivateKeyB64=function(){return this.getKey().getPrivateBaseKeyB64()},JSEncrypt.prototype.getPublicKey=function(){return this.getKey().getPublicKey()},JSEncrypt.prototype.getPublicKeyB64=function(){return this.getKey().getPublicBaseKeyB64()};!function(){function BaseRequest(data){classCallCheck(this,BaseRequest),this.data=data,this.before=function(data){return Promise.resolve(data)}}createClass(BaseRequest,[{key:"send",value:function(){return this.before(this.data)}},{key:"before",value:function(fn){return Promise.resolve}}])}();var BaseTransport=function(){function BaseTransport(endpoint,stream_type){arguments.length>2&&void 0!==arguments[2]&&arguments[2];classCallCheck(this,BaseTransport),this.stream_type=stream_type,this.endpoint=endpoint,this.eventSource=new EventEmitter,this.dataQueue=[]}return createClass(BaseTransport,[{key:"destroy",value:function(){this.eventSource.destroy()}},{key:"connect",value:function(){}},{key:"disconnect",value:function(){}},{key:"reconnect",value:function(){var _this=this;return this.disconnect().then(function(){return _this.connect()})}},{key:"setEndpoint",value:function(endpoint){return this.endpoint=endpoint,this.reconnect()}},{key:"send",value:function(data){}},{key:"prepare",value:function(data){}}],[{key:"canTransfer",value:function(stream_type){return BaseTransport.streamTypes().includes(stream_type)}},{key:"streamTypes",value:function(){return[]}}]),BaseTransport}(),Log$10=(/^((?!chrome|android).)*safari/i.test(navigator.userAgent),getTagged("transport:ws")),WebsocketTransport=function(_BaseTransport){function WebsocketTransport(endpoint,stream_type){var options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{socket:location.protocol.replace("http","ws")+"//"+location.host+"/ws/",workers:1};classCallCheck(this,WebsocketTransport);var _this=possibleConstructorReturn(this,(WebsocketTransport.__proto__||Object.getPrototypeOf(WebsocketTransport)).call(this,endpoint,stream_type));return _this.proxies=[],_this.currentProxy=0,_this.workers=1,_this.socket_url=options.socket,_this.ready=_this.connect(),_this}return inherits(WebsocketTransport,BaseTransport),createClass(WebsocketTransport,[{key:"destroy",value:function(){var _this2=this;return this.disconnect().then(function(){return get(WebsocketTransport.prototype.__proto__||Object.getPrototypeOf(WebsocketTransport.prototype),"destroy",_this2).call(_this2)})}},{key:"connect",value:function(){var _this3=this;return this.disconnect().then(function(){for(var promises=[],i=0;i<_this3.workers;++i){var proxy=new WebSocketProxy(_this3.socket_url,_this3.endpoint,_this3.stream_type);proxy.set_disconnect_handler(function(e){_this3.eventSource.dispatchEvent("disconnected",{code:e.code,reason:e.reason}),[1e3,1006,1013,1011].includes(e.code)&&setTimeout(function(){_this3.ready&&_this3.ready.reject&&_this3.ready.reject(),_this3.ready=_this3.connect()},3e3)}),proxy.set_data_handler(function(data){_this3.dataQueue.push(new Uint8Array(data)),_this3.eventSource.dispatchEvent("data")}),promises.push(proxy.connect().then(function(){_this3.eventSource.dispatchEvent("connected")}).catch(function(e){throw _this3.eventSource.dispatchEvent("error"),new Error(e)})),_this3.proxies.push(proxy)}return Promise.all(promises)})}},{key:"disconnect",value:function(){for(var promises=[],i=0;i2&&void 0!==arguments[2]?arguments[2]:"",data_str="";data.seq||(data.seq=++WSPProtocol.seq);for(var k in data)data_str+=k+": "+data[k]+"\r\n";return WSPProtocol.PROTO+"/"+this.ver+" "+cmd+"\r\n"+data_str+"\r\n"+payload}}],[{key:"parse",value:function(data){var payIdx=data.indexOf("\r\n\r\n"),lines=data.substr(0,payIdx).split("\r\n"),hdr=lines.shift().match(new RegExp(WSPProtocol.PROTO+"/"+WSPProtocol.V1_1+"\\s+(\\d+)\\s+(.+)"));if(hdr){for(var res={code:Number(hdr[1]),msg:hdr[2],data:{},payload:""};lines.length;){var line=lines.shift();if(!line)break;var _line$split=line.split(":"),_line$split2=slicedToArray(_line$split,2),k=_line$split2[0],v=_line$split2[1];res.data[k.trim()]=v.trim()}return res.payload=data.substr(payIdx+4),res}return null}}]),WSPProtocol}();WSPProtocol.seq=0;var WebSocketProxy=function(){function WebSocketProxy(wsurl,endpoint,stream_type){classCallCheck(this,WebSocketProxy),this.url=wsurl,this.stream_type=stream_type,this.endpoint=endpoint,this.data_handler=function(){},this.disconnect_handler=function(){},this.builder=new WSPProtocol(WSPProtocol.V1_1),this.awaitingPromises={},this.seq=0,this.encryptor=new JSEncrypt}return createClass(WebSocketProxy,null,[{key:"CHN_CONTROL",get:function(){return"control"}},{key:"CHN_DATA",get:function(){return"data"}}]),createClass(WebSocketProxy,[{key:"set_data_handler",value:function(handler){this.data_handler=handler}},{key:"set_disconnect_handler",value:function(handler){this.disconnect_handler=handler}},{key:"close",value:function(){var _this4=this;return Log$10.log("closing connection"),new Promise(function(resolve){_this4.ctrlChannel.onclose=function(){_this4.dataChannel?(_this4.dataChannel.onclose=function(){Log$10.log("closed"),resolve()},_this4.dataChannel.close()):(Log$10.log("closed"),resolve())},_this4.ctrlChannel.close()})}},{key:"onDisconnect",value:function(){this.ctrlChannel.onclose=null,this.ctrlChannel.close(),this.dataChannel&&(this.dataChannel.onclose=null,this.dataChannel.close()),this.disconnect_handler(this)}},{key:"initDataChannel",value:function(channel_id){var _this5=this;return new Promise(function(resolve,reject){_this5.dataChannel=new WebSocket(_this5.url,WebSocketProxy.CHN_DATA),_this5.dataChannel.binaryType="arraybuffer",_this5.dataChannel.onopen=function(){var msg=_this5.builder.build(WSPProtocol.CMD_JOIN,{channel:channel_id});Log$10.debug(msg),_this5.dataChannel.send(msg)},_this5.dataChannel.onmessage=function(ev){Log$10.debug("[data]\r\n"+ev.data);if(!WSPProtocol.parse(ev.data))return reject();_this5.dataChannel.onmessage=function(e){Log$10.debug("got data"),_this5.data_handler&&_this5.data_handler(e.data)},resolve()},_this5.dataChannel.onerror=function(e){Log$10.error("[data] "+e.type),_this5.dataChannel.close()},_this5.dataChannel.onclose=function(e){Log$10.error("[data] "+e.type+". code: "+e.code+", reason: "+(e.reason||"unknown reason")),_this5.onDisconnect(e)}})}},{key:"connect",value:function(){var _this6=this;return this.encryptionKey=null,new Promise(function(resolve,reject){_this6.ctrlChannel=new WebSocket(_this6.url,WebSocketProxy.CHN_CONTROL),_this6.connected=!1,_this6.ctrlChannel.onopen=function(){var headers={proto:_this6.stream_type};_this6.endpoint.socket?headers.socket=_this6.endpoint.socket:Object.assign(headers,{host:_this6.endpoint.host,port:_this6.endpoint.port});var msg=_this6.builder.build(WSPProtocol.CMD_INIT,headers);Log$10.debug(msg),_this6.ctrlChannel.send(msg)},_this6.ctrlChannel.onmessage=function(ev){Log$10.debug("[ctrl]\r\n"+ev.data);var res=WSPProtocol.parse(ev.data);return res?res.code>=300?(Log$10.error("[ctrl]\r\n"+res.code+": "+res.msg),reject()):(_this6.ctrlChannel.onmessage=function(e){var res=WSPProtocol.parse(e.data);Log$10.debug("[ctrl]\r\n"+e.data),res.data.seq in _this6.awaitingPromises&&(res.code<300?_this6.awaitingPromises[res.data.seq].resolve(res):_this6.awaitingPromises[res.data.seq].reject(res),delete _this6.awaitingPromises[res.data.seq])},_this6.encryptionKey=res.data.pubkey||null,_this6.encryptionKey&&_this6.encryptor.setPublicKey(_this6.encryptionKey),void _this6.initDataChannel(res.data.channel).then(resolve).catch(reject)):reject()},_this6.ctrlChannel.onerror=function(e){Log$10.error("[ctrl] "+e.type),_this6.ctrlChannel.close()},_this6.ctrlChannel.onclose=function(e){Log$10.error("[ctrl] "+e.type+". code: "+e.code+" "+(e.reason||"unknown reason")),_this6.onDisconnect(e)}})}},{key:"encrypt",value:function(msg){if(this.encryptionKey){var crypted=this.encryptor.encrypt(msg);if(!1===crypted)throw new Error("Encryption failed. Stopping");return crypted}return msg}},{key:"send",value:function(payload){var _this7=this;if(this.ctrlChannel.readyState!=WebSocket.OPEN)throw this.close(),new Error("disconnected");var data={contentLength:payload.length,seq:++WSPProtocol.seq};return{seq:data.seq,promise:new Promise(function(resolve,reject){_this7.awaitingPromises[data.seq]={resolve:resolve,reject:reject};var msg=_this7.builder.build(WSPProtocol.CMD_WRAP,data,payload);Log$10.debug(msg),_this7.ctrlChannel.send(_this7.encrypt(msg))})}}}]),WebSocketProxy}(),Log$1=getTagged("wsp"),StreamType=function(){function StreamType(){classCallCheck(this,StreamType)}return createClass(StreamType,null,[{key:"isSupported",value:function(type){return[StreamType.HLS,StreamType.RTSP].includes(type)}},{key:"fromUrl",value:function(url){var parsed=void 0;try{parsed=Url.parse(url)}catch(e){return null}switch(parsed.protocol){case"rtsp":return StreamType.RTSP;case"http":case"https":return url.indexOf(".m3u8")>=0?StreamType.HLS:null;default:return null}}},{key:"fromMime",value:function(mime){switch(mime){case"application/x-rtsp":return StreamType.RTSP;case"application/vnd.apple.mpegurl":case"application/x-mpegurl":return StreamType.HLS;default:return null}}},{key:"HLS",get:function(){return"hls"}},{key:"RTSP",get:function(){return"rtsp"}}]),StreamType}(),WSPlayer=function(){function WSPlayer(node,opts){var _this=this;classCallCheck(this,WSPlayer),(void 0===node?"undefined":_typeof(node))==_typeof("")?this.player=document.getElementById(node):this.player=node;var modules=opts.modules||{client:RTSPClient,transport:{constructor:WebsocketTransport}};this.errorHandler=opts.errorHandler||null,this.queryCredentials=opts.queryCredentials||null,this.modules={};var _iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=modules[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var module=_step.value,transport=module.transport||WebsocketTransport,client=module.client||RTSPClient;transport.constructor.canTransfer(client.streamType())?this.modules[client.streamType()]={client:client,transport:transport}:Log$1.warn("Client stream type "+client.streamType()+" is incompatible with transport types ["+transport.streamTypes().join(", ")+"]. Skip")}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}if(this.type=StreamType.RTSP,this.url=null,opts.url&&opts.type)this.url=opts.url,this.type=opts.type;else if(!this._checkSource(this.player))for(var i=0;i