cesium-city3d/examples/js/streamedian.js

3 lines
167 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

!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<len;i++)bytes[i]=binary_string.charCodeAt(i);return bytes.buffer}function hexToByteArray(hex){for(var len=hex.length>>1,bufView=new Uint8Array(len),i=0;i<len;i++)bufView[i]=parseInt(hex.substr(i<<1,2),16);return bufView}function safeAdd(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function md5cmn(q,a,b,x,s,t){return safeAdd(function(num,cnt){return num<<cnt|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<<len%32,x[14+(len+64>>>9<<4)]=len;var i,olda,oldb,oldc,oldd,a=1732584193,b=-271733879,c=-1732584194,d=271733878;for(i=0;i<x.length;i+=16)olda=a,oldb=b,oldc=c,oldd=d,b=md5ii(b=md5ii(b=md5ii(b=md5ii(b=md5hh(b=md5hh(b=md5hh(b=md5hh(b=md5gg(b=md5gg(b=md5gg(b=md5gg(b=md5ff(b=md5ff(b=md5ff(b=md5ff(b,c=md5ff(c,d=md5ff(d,a=md5ff(a,b,c,d,x[i],7,-680876936),b,c,x[i+1],12,-389564586),a,b,x[i+2],17,606105819),d,a,x[i+3],22,-1044525330),c=md5ff(c,d=md5ff(d,a=md5ff(a,b,c,d,x[i+4],7,-176418897),b,c,x[i+5],12,1200080426),a,b,x[i+6],17,-1473231341),d,a,x[i+7],22,-45705983),c=md5ff(c,d=md5ff(d,a=md5ff(a,b,c,d,x[i+8],7,1770035416),b,c,x[i+9],12,-1958414417),a,b,x[i+10],17,-42063),d,a,x[i+11],22,-1990404162),c=md5ff(c,d=md5ff(d,a=md5ff(a,b,c,d,x[i+12],7,1804603682),b,c,x[i+13],12,-40341101),a,b,x[i+14],17,-1502002290),d,a,x[i+15],22,1236535329),c=md5gg(c,d=md5gg(d,a=md5gg(a,b,c,d,x[i+1],5,-165796510),b,c,x[i+6],9,-1069501632),a,b,x[i+11],14,643717713),d,a,x[i],20,-373897302),c=md5gg(c,d=md5gg(d,a=md5gg(a,b,c,d,x[i+5],5,-701558691),b,c,x[i+10],9,38016083),a,b,x[i+15],14,-660478335),d,a,x[i+4],20,-405537848),c=md5gg(c,d=md5gg(d,a=md5gg(a,b,c,d,x[i+9],5,568446438),b,c,x[i+14],9,-1019803690),a,b,x[i+3],14,-187363961),d,a,x[i+8],20,1163531501),c=md5gg(c,d=md5gg(d,a=md5gg(a,b,c,d,x[i+13],5,-1444681467),b,c,x[i+2],9,-51403784),a,b,x[i+7],14,1735328473),d,a,x[i+12],20,-1926607734),c=md5hh(c,d=md5hh(d,a=md5hh(a,b,c,d,x[i+5],4,-378558),b,c,x[i+8],11,-2022574463),a,b,x[i+11],16,1839030562),d,a,x[i+14],23,-35309556),c=md5hh(c,d=md5hh(d,a=md5hh(a,b,c,d,x[i+1],4,-1530992060),b,c,x[i+4],11,1272893353),a,b,x[i+7],16,-155497632),d,a,x[i+10],23,-1094730640),c=md5hh(c,d=md5hh(d,a=md5hh(a,b,c,d,x[i+13],4,681279174),b,c,x[i],11,-358537222),a,b,x[i+3],16,-722521979),d,a,x[i+6],23,76029189),c=md5hh(c,d=md5hh(d,a=md5hh(a,b,c,d,x[i+9],4,-640364487),b,c,x[i+12],11,-421815835),a,b,x[i+15],16,530742520),d,a,x[i+2],23,-995338651),c=md5ii(c,d=md5ii(d,a=md5ii(a,b,c,d,x[i],6,-198630844),b,c,x[i+7],10,1126891415),a,b,x[i+14],15,-1416354905),d,a,x[i+5],21,-57434055),c=md5ii(c,d=md5ii(d,a=md5ii(a,b,c,d,x[i+12],6,1700485571),b,c,x[i+3],10,-1894986606),a,b,x[i+10],15,-1051523),d,a,x[i+1],21,-2054922799),c=md5ii(c,d=md5ii(d,a=md5ii(a,b,c,d,x[i+8],6,1873313359),b,c,x[i+15],10,-30611744),a,b,x[i+6],15,-1560198380),d,a,x[i+13],21,1309151649),c=md5ii(c,d=md5ii(d,a=md5ii(a,b,c,d,x[i+4],6,-145523070),b,c,x[i+11],10,-1120210379),a,b,x[i+2],15,718787259),d,a,x[i+9],21,-343485551),a=safeAdd(a,olda),b=safeAdd(b,oldb),c=safeAdd(c,oldc),d=safeAdd(d,oldd);return[a,b,c,d]}function binl2rstr(input){var i,output="",length32=32*input.length;for(i=0;i<length32;i+=8)output+=String.fromCharCode(input[i>>5]>>>i%32&255);return output}function rstr2binl(input){var i,output=[];for(output[(input.length>>2)-1]=void 0,i=0;i<output.length;i+=1)output[i]=0;var length8=8*input.length;for(i=0;i<length8;i+=8)output[i>>5]|=(255&input.charCodeAt(i/8))<<i%32;return output}function rstr2hex(input){var x,i,output="";for(i=0;i<input.length;i+=1)x=input.charCodeAt(i),output+="0123456789abcdef".charAt(x>>>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<rng_psize;){var random=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=255&random}for(rng_state.init(rng_pool),rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0}return rng_state.next()}function nbi(){return new BigInteger(null)}function int2char(n){return BI_RM.charAt(n)}function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return null==c?-1:c}function nbv(i){var r=nbi();return r.fromInt(i),r}function nbits(x){var t,r=1;return 0!=(t=x>>>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;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),defineProperty=function(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj},get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0===desc){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if("value"in desc)return desc.value;var getter=desc.get;if(void 0!==getter)return getter.call(receiver)},inherits=function(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)},possibleConstructorReturn=function(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call},slicedToArray=function(){return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return function(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i.return&&_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),LogLevel_Error=0,LogLevel_Warn=1,LogLevel_Log=2,LogLevel_Debug=3,DEFAULT_LOG_LEVEL=LogLevel_Debug,Logger=function(){function Logger(){var level=arguments.length>0&&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<len;++i)result.set(payload[i],size),size+=payload[i].byteLength;return result}},{key:"hdlr",value:function(type){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[type])}},{key:"mdat",value:function(data){return MP4.box(MP4.types.mdat,data)}},{key:"mdhd",value:function(timescale,duration){return MP4.box(MP4.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,timescale>>24&255,timescale>>16&255,timescale>>8&255,255&timescale,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&timescale,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<samples.length;i++)flags=samples[i].flags,bytes[i+4]=flags.dependsOn<<4|flags.isDependedOn<<2|flags.hasRedundancy;return MP4.box(MP4.types.sdtp,bytes)}},{key:"stbl",value:function(track){return MP4.box(MP4.types.stbl,MP4.stsd(track),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}},{key:"avc1",value:function(track){var i,data,len,sps=[],pps=[];for(i=0;i<track.sps.length;i++)len=(data=track.sps[i]).byteLength,sps.push(len>>>8&255),sps.push(255&len),sps=sps.concat(Array.prototype.slice.call(data));for(i=0;i<track.pps.length;i++)len=(data=track.pps[i]).byteLength,pps.push(len>>>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<len;i++)duration=(sample=samples[i]).duration,size=sample.size,flags=sample.flags,cts=sample.cts,array.set([duration>>>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<this.sourceBuffer.buffered.length;++i)_loop(i);return Promise.all(promises)}},{key:"setLive",value:function(is_live){this.is_live=is_live}},{key:"feedNext",value:function(){this.sourceBuffer.updating||this.cleaning||!this.queue.length||this.doAppend(this.queue.shift())}},{key:"doCleanup",value:function(){if(!this.cleanRanges.length)return this.cleaning=!1,void this.feedNext();var range=this.cleanRanges.shift();Log$4.debug(this.codec+" remove range ["+range[0]+" - "+range[1]+"). \n \nUpdating: "+this.sourceBuffer.updating+"\n "),this.cleaning=!0,this.sourceBuffer.remove(range[0],range[1])}},{key:"initCleanup",value:function(){if(!this.sourceBuffer.buffered.length||this.sourceBuffer.updating||this.cleaning)this.feedNext();else{Log$4.debug(this.codec+" cleanup");for(var removeBound=this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)-2,i=0;i<this.sourceBuffer.buffered.length;++i){var removeStart=this.sourceBuffer.buffered.start(i),removeEnd=this.sourceBuffer.buffered.end(i);this.players[0].currentTime<=removeStart||removeBound<=removeStart||(removeBound<=removeEnd&&removeBound>=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<<bits|this.readBits(bits):valu}},{key:"skipLZ",value:function(){var leadingZeroCount;for(leadingZeroCount=0;leadingZeroCount<this.bitsAvailable;++leadingZeroCount)if(0!=(this.word&2147483648>>>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;j<count;j++)0!==nextScale&&(nextScale=(lastScale+decoder.readEG()+256)%256),lastScale=0===nextScale?lastScale:nextScale}},{key:"readSPS",value:function(data){var decoder=new ExpGolomb(data),frameCropLeftOffset=0,frameCropRightOffset=0,frameCropTopOffset=0,frameCropBottomOffset=0,sarScale=1,profileIdc=void 0,numRefFramesInPicOrderCntCycle=void 0,picWidthInMbsMinus1=void 0,picHeightInMapUnitsMinus1=void 0,frameMbsOnlyFlag=void 0,scalingListCount=void 0;if(decoder.readUByte(),profileIdc=decoder.readUByte(),decoder.readBits(5),decoder.skipBits(3),decoder.readUByte(),decoder.skipUEG(),100===profileIdc||110===profileIdc||122===profileIdc||244===profileIdc||44===profileIdc||83===profileIdc||86===profileIdc||118===profileIdc||128===profileIdc){var chromaFormatIdc=decoder.readUEG();if(3===chromaFormatIdc&&decoder.skipBits(1),decoder.skipUEG(),decoder.skipUEG(),decoder.skipBits(1),decoder.readBoolean()){scalingListCount=3!==chromaFormatIdc?8:12;for(var i=0;i<scalingListCount;++i)decoder.readBoolean()&&(i<6?H264Parser.skipScalingList(decoder,16):H264Parser.skipScalingList(decoder,64))}}decoder.skipUEG();var picOrderCntType=decoder.readUEG();if(0===picOrderCntType)decoder.readUEG();else if(1===picOrderCntType){decoder.skipBits(1),decoder.skipEG(),decoder.skipEG(),numRefFramesInPicOrderCntCycle=decoder.readUEG();for(var _i=0;_i<numRefFramesInPicOrderCntCycle;++_i)decoder.skipEG()}if(decoder.skipUEG(),decoder.skipBits(1),picWidthInMbsMinus1=decoder.readUEG(),picHeightInMapUnitsMinus1=decoder.readUEG(),0===(frameMbsOnlyFlag=decoder.readBits(1))&&decoder.skipBits(1),decoder.skipBits(1),decoder.readBoolean()&&(frameCropLeftOffset=decoder.readUEG(),frameCropRightOffset=decoder.readUEG(),frameCropTopOffset=decoder.readUEG(),frameCropBottomOffset=decoder.readUEG()),decoder.readBoolean()){if(decoder.readBoolean()){var sarRatio=void 0;switch(decoder.readUByte()){case 1:sarRatio=[1,1];break;case 2:sarRatio=[12,11];break;case 3:sarRatio=[10,11];break;case 4:sarRatio=[16,11];break;case 5:sarRatio=[40,33];break;case 6:sarRatio=[24,11];break;case 7:sarRatio=[20,11];break;case 8:sarRatio=[32,11];break;case 9:sarRatio=[80,33];break;case 10:sarRatio=[18,11];break;case 11:sarRatio=[15,11];break;case 12:sarRatio=[64,33];break;case 13:sarRatio=[160,99];break;case 14:sarRatio=[4,3];break;case 15:sarRatio=[3,2];break;case 16:sarRatio=[2,1];break;case 255:sarRatio=[decoder.readUByte()<<8|decoder.readUByte(),decoder.readUByte()<<8|decoder.readUByte()]}sarRatio&&(sarScale=sarRatio[0]/sarRatio[1])}if(decoder.readBoolean()&&decoder.skipBits(1),decoder.readBoolean()&&(decoder.skipBits(4),decoder.readBoolean()&&decoder.skipBits(24)),decoder.readBoolean()&&(decoder.skipUEG(),decoder.skipUEG()),decoder.readBoolean()){var unitsInTick=decoder.readUInt(),timeScale=decoder.readUInt(),fixedFrameRate=decoder.readBoolean(),frameDuration=timeScale/(2*unitsInTick);console.log("timescale: "+timeScale+"; unitsInTick: "+unitsInTick+"; fixedFramerate: "+fixedFrameRate+"; avgFrameDuration: "+frameDuration)}}return{width:Math.ceil((16*(picWidthInMbsMinus1+1)-2*frameCropLeftOffset-2*frameCropRightOffset)*sarScale),height:(2-frameMbsOnlyFlag)*(picHeightInMapUnitsMinus1+1)*16-(frameMbsOnlyFlag?2:4)*(frameCropTopOffset+frameCropBottomOffset)}}},{key:"readSliceType",value:function(decoder){return decoder.readUByte(),decoder.readUEG(),decoder.readUEG()}}]),H264Parser}(),Log$6=getTagged("remuxer:h264"),H264Remuxer=function(_BaseRemuxer){function H264Remuxer(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,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<<this.scaleFactor}},{key:"setSPS",value:function(sps){this.h264.parseSPS(sps)}},{key:"setPPS",value:function(pps){this.h264.parsePPS(pps)}},{key:"remux",value:function(nalu){if(this.lastGopDTS<nalu.dts){this.gop.sort(BaseRemuxer.dtsSortFunc);var _iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=this.gop[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var unit=_step.value;get(H264Remuxer.prototype.__proto__||Object.getPrototypeOf(H264Remuxer.prototype),"remux",this).call(this,unit)&&(this.mp4track.len+=unit.getSize())}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}this.gop=[],this.lastGopDTS=nalu.dts}this.h264.parseNAL(nalu)&&this.gop.push(nalu)}},{key:"getPayload",value:function(){if(!this.getPayloadBase())return null;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,dts=sample.dts,dts=Math.min(pts,dts),void 0!==lastDTS){var sampleDuration=this.scaled(dts-lastDTS);if(sampleDuration<0){Log$6.log("invalid AVC sample duration at PTS/DTS: "+pts+"/"+dts+"|lastDTS: "+lastDTS+":"+sampleDuration),this.mp4track.len-=unit.getSize();continue}this.lastDurations.push(sampleDuration),this.lastDurations.length>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<data.byteLength;){var size=data.getUint16(nal_start_idx);nal_start_idx+=2;var _header=NALUAsm.parseNALHeader(data.getInt8(nal_start_idx));nal_start_idx++;var nalu=this.parseSingleNALUPacket(rawData.subarray(nal_start_idx,nal_start_idx+size),_header,dts,pts);null!==nalu&&ret.push(nalu),nal_start_idx+=size}return ret}},{key:"parseFragmentationUnit",value:function(rawData,header,dts,pts){var data=new DataView(rawData.buffer,rawData.byteOffset,rawData.byteLength),nal_start_idx=0,fu_header=data.getUint8(nal_start_idx),is_start=(128&fu_header)>>>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;_offset<auHeadersLengthInBits;){var size=bits.readBits(sizeLength);bits.readBits(_offset?indexDeltaLength:indexLength);if(_offset+=sizeLength+(_offset?indexDeltaLength:indexLength),CTSDeltaLength){bits.readBits(1);cts=bits.readBits(CTSDeltaLength),_offset+=CTSDeltaLength}if(DTSDeltaLength){bits.readBits(1);dts=bits.readBits(DTSDeltaLength),_offset+=CTSDeltaLength}RandomAccessIndication&&(bits.skipBits(1),_offset+=1),StreamStateIndication&&(bits.skipBits(StreamStateIndication),_offset+=StreamStateIndication),frames.push(new AACFrame(rawData.subarray(auHeadersLengthPadded+frameOffset,auHeadersLengthPadded+frameOffset+size),ts+dts,ts+cts)),frameOffset+=size}return frames}for(var aacData=rawData.subarray(auHeadersLengthPadded);;){if(255!=aacData[offset])break;++offset}return++offset,[new AACFrame(rawData.subarray(auHeadersLengthPadded+offset),ts)]}}]),AACAsm}(),RTPPayloadParser=function(){function RTPPayloadParser(){classCallCheck(this,RTPPayloadParser),this.h264parser=new RTPH264Parser,this.aacparser=new RTPAACParser}return createClass(RTPPayloadParser,[{key:"parse",value:function(rtp){return"video"==rtp.media.type?this.h264parser.parse(rtp):"audio"==rtp.media.type?this.aacparser.parse(rtp):null}}]),RTPPayloadParser}(),RTPH264Parser=function(){function RTPH264Parser(){classCallCheck(this,RTPH264Parser),this.naluasm=new NALUAsm}return createClass(RTPH264Parser,[{key:"parse",value:function(rtp){return this.naluasm.onNALUFragment(rtp.getPayload(),rtp.getTimestampMS())}}]),RTPH264Parser}(),RTPAACParser=function(){function RTPAACParser(){classCallCheck(this,RTPAACParser),this.scale=1,this.asm=new AACAsm}return createClass(RTPAACParser,[{key:"setConfig",value:function(conf){this.asm.config=conf}},{key:"parse",value:function(rtp){return this.asm.onAACFragment(rtp)}}]),RTPAACParser}(),BaseClient=function(){function BaseClient(){var _this=this,options=arguments.length>0&&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<byteLen;++i){var tail=0;i<endByte&&(tail=bytearray[startByte+i+1]>>nBitOffset,i==endByte-1&&endOffset<8&&(tail>>=endOffset,tail<<=endOffset)),res[i]=bytearray[startByte+i]<<bitOffset|tail}return res}(new Uint8Array(config.src.buffer),bitpos,bitpos+16),codec:"mp4a.40."+prof,samplerate:AACParser.SampleRates[sfi],channels:channels}}},{key:"parseStreamMuxConfig",value:function(bytes){var config=new BitArray(bytes);if(!config.readBits(1))return config.skipBits(14),AACParser.parseAudioSpecificConfig(config)}},{key:"SampleRates",get:function(){return[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350]}}]),AACParser}(),Log$7=getTagged("client:rtsp"),RTSPClient=function(_BaseClient){function RTSPClient(){var options=arguments.length>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;i<end;++i)if(s+=this.hexByte(this.get(i)),!0!==raw)switch(15&i){case 7:s+=" ";break;case 15:s+="\n";break;default:s+=" "}return s}},{key:"parseStringISO",value:function(start,end){for(var s="",i=start;i<end;++i)s+=String.fromCharCode(this.get(i));return s}},{key:"parseStringUTF",value:function(start,end){for(var s="",i=start;i<end;){var c=this.get(i++);s+=c<128?String.fromCharCode(c):c>191&&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;i<end;i+=2){var high_byte=this.get(i),low_byte=this.get(i+1);str+=String.fromCharCode((high_byte<<8)+low_byte)}return str}},{key:"parseTime",value:function(start,end){var s=this.parseStringISO(start,end),m=Stream.reTime.exec(s);return m?(s=m[1]+"-"+m[2]+"-"+m[3]+" "+m[4],m[5]&&(s+=":"+m[5],m[6]&&(s+=":"+m[6],m[7]&&(s+="."+m[7]))),m[8]&&(s+=" UTC","Z"!=m[8]&&(s+=m[8],m[9]&&(s+=":"+m[9]))),s):"Unrecognized time: "+s}},{key:"parseInteger",value:function(start,end){var len=end-start;if(len>4){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;i<end;++i)n=n<<8|this.get(i);return n}},{key:"parseBitString",value:function(start,end){var unusedBit=this.get(start),lenBit=(end-start-1<<3)-unusedBit,s="("+lenBit+" bit)";if(lenBit<=20){var skip=unusedBit;s+=" ";for(var i=end-1;i>start;--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;i<end;++i)s+=this.hexByte(this.get(i));return len>100&&(s+="…"),s}},{key:"parseOID",value:function(start,end){for(var s="",n=0,bits=0,i=start;i<end;++i){var v=this.get(i);if(n=n<<7|127&v,bits+=7,!(128&v)){if(""===s){var m=n<80?n<40?0:1:2;s=m+"."+(n-40*m)}else s+="."+(bits>=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<max;++i)this.sub[i].print(indent)}}},{key:"toPrettyString",value:function(indent){void 0===indent&&(indent="");var s=indent+this.typeName()+" @"+this.stream.pos;if(this.length>=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<max;++i)s+=this.sub[i].toPrettyString(indent)}return s}},{key:"toDOM",value:function(){var node=DOM_tag("div","node");node.asn1=this;var head=DOM_tag("div","head"),s=this.typeName().replace(/_/g," ");head.innerHTML=s;var content=this.content();if(null!==content){content=String(content).replace(/</g,"&lt;");var preview=DOM_tag("span","preview");preview.appendChild(DOM_text(content)),head.appendChild(preview)}node.appendChild(head),this.node=node,this.head=head;var value=DOM_tag("div","value");if(s="Offset: "+this.stream.pos+"<br/>",s+="Length: "+this.header+"+",this.length>=0?s+=this.length:s+=-this.length+" (undefined)",32&this.tag?s+="<br/>(constructed)":3!=this.tag&&4!=this.tag||null===this.sub||(s+="<br/>(encapsulates)"),null!==content&&(s+="<br/>Value:<br/><b>"+content+"</b>","object"===("undefined"==typeof oids?"undefined":_typeof(oids))&&6==this.tag)){var oid=oids[content];oid&&(oid.d&&(s+="<br/>"+oid.d),oid.c&&(s+="<br/>"+oid.c),oid.w&&(s+="<br/>(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<max;++i)sub.appendChild(this.sub[i].toDOM());return node.appendChild(sub),head.onclick=function(){node.className="node collapsed"==node.className?"node":"node collapsed"},node}},{key:"posStart",value:function(){return this.stream.pos}},{key:"posContent",value:function(){return this.stream.pos+this.header}},{key:"posEnd",value:function(){return this.stream.pos+this.header+Math.abs(this.length)}},{key:"fakeHover",value:function(current){this.node.className+=" hover",current&&(this.head.className+=" hover")}},{key:"fakeOut",value:function(current){var re=/ ?hover/;this.node.className=this.node.className.replace(re,""),current&&(this.head.className=this.head.className.replace(re,""))}},{key:"toHexDOM_sub",value:function(node,className,stream,start,end){if(!(start>=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;i<max;++i)node.appendChild(this.sub[i].toHexDOM(root));this.toHexDOM_sub(node,"outro",this.stream,last.posEnd(),this.posEnd())}return node}},{key:"toHexString",value:function(root){return this.stream.hexDump(this.posStart(),this.posEnd(),!0)}}]),ASN1}();ASN1.decodeLength=function(stream){var buf=stream.get(),len=127&buf;if(len==buf)return len;if(len>3)throw"Length over 24 bits not supported at position "+(stream.pos-1);if(0===len)return-1;buf=0;for(var i=0;i<len;++i)buf=buf<<8|stream.get();return buf},ASN1.hasContent=function(tag,len,stream){if(32&tag)return!0;if(tag<3||tag>4)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<end;)sub[sub.length]=ASN1.decode(stream);if(stream.pos!=end)throw"Content size is not correct for container starting at offset "+start}else try{for(;;){var s=ASN1.decode(stream);if(0===s.tag)break;sub[sub.length]=s}len=start-stream.pos}catch(e){throw"Exception while decoding undefined length content: "+e}}else stream.pos+=len;return new ASN1(streamStart,header,len,tag,sub)},ASN1.test=function(){for(var test=[{value:[39],expected:39},{value:[129,201],expected:201},{value:[131,254,220,186],expected:16702650}],i=0,max=test.length;i<max;++i){var stream=new Stream(test[i].value,0),res=ASN1.decodeLength(stream);res!=test[i].expected&&document.write("In test["+i+"] expected "+test[i].expected+" got "+res+"\n")}};var Arcfour=function Arcfour(){classCallCheck(this,Arcfour),this.i=0,this.j=0,this.S=[]};Arcfour.prototype.init=function(key){var i,j,t;for(i=0;i<256;++i)this.S[i]=i;for(j=0,i=0;i<256;++i)j=j+this.S[i]+key[i%key.length]&255,t=this.S[i],this.S[i]=this.S[j],this.S[j]=t;this.i=0,this.j=0},Arcfour.prototype.next=function(){var t;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,t=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=t,this.S[t+this.S[this.i]&255]};var rng_state,rng_pool,rng_pptr,rng_psize=256;if(null==rng_pool){rng_pool=new Array,rng_pptr=0;var t;if(window.crypto&&window.crypto.getRandomValues){var z=new Uint32Array(256);for(window.crypto.getRandomValues(z),t=0;t<z.length;++t)rng_pool[rng_pptr++]=255&z[t]}var onMouseMoveListener=function onMouseMoveListener(ev){if(this.count=this.count||0,this.count>=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<ba.length;++i)ba[i]=rng_get_byte()};var dbits,BigInteger=function BigInteger(a,b,c){classCallCheck(this,BigInteger),null!=a&&("number"==typeof a?this.fromNumber(a,b,c):null==b&&"string"!=typeof a?this.fromString(a,256):this.fromString(a,b))};"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=function(i,x,w,j,c,n){for(var xl=32767&x,xh=x>>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<<dbits)-1,BigInteger.prototype.DV=1<<dbits;BigInteger.prototype.FV=Math.pow(2,52),BigInteger.prototype.F1=52-dbits,BigInteger.prototype.F2=2*dbits-52;var rr,vv,BI_RM="0123456789abcdefghijklmnopqrstuvwxyz",BI_RC=[];for(rr="0".charCodeAt(0),vv=0;vv<=9;++vv)BI_RC[rr++]=vv;for(rr="a".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;for(rr="A".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;var Classic=function Classic(m){classCallCheck(this,Classic),this.m=m};Classic.prototype.convert=function(x){return x.s<0||x.compareTo(this.m)>=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<<m.DB-15)-1,this.mt2=2*m.t};Montgomery.prototype.convert=function(x){var r=nbi();return x.abs().dlShiftTo(this.m.t,r),r.divRemTo(this.m,null,r),x.s<0&&r.compareTo(BigInteger.ZERO)>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<this.m.t;++i){var j=32767&x[i],u0=j*this.mpl+((j*this.mph+(x[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)-1)<<sh,this[this.t++]=x>>this.DB-sh):this[this.t-1]|=x<<sh,(sh+=k)>=this.DB&&(sh-=this.DB))}8==k&&0!=(128&s[0])&&(this.s=-1,sh>0&&(this[this.t-1]|=(1<<this.DB-sh)-1<<sh)),this.clamp(),mi&&BigInteger.ZERO.subTo(this,this)},BigInteger.prototype.clamp=function(){for(var c=this.s&this.DM;this.t>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<this.t;++i)r[i-n]=this[i];r.t=Math.max(this.t-n,0),r.s=this.s},BigInteger.prototype.lShiftTo=function(n,r){var i,bs=n%this.DB,cbs=this.DB-bs,bm=(1<<cbs)-1,ds=Math.floor(n/this.DB),c=this.s<<bs&this.DM;for(i=this.t-1;i>=0;--i)r[i+ds+1]=this[i]>>cbs|c,c=(this[i]&bm)<<bs;for(i=ds-1;i>=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)-1;r[0]=this[ds]>>bs;for(var i=ds+1;i<this.t;++i)r[i-ds-1]|=(this[i]&bm)<<cbs,r[i-ds]=this[i]>>bs;bs>0&&(r[this.t-ds-1]|=(this.s&bm)<<cbs),r.t=this.t-ds,r.clamp()}},BigInteger.prototype.subTo=function(a,r){for(var i=0,c=0,m=Math.min(a.t,this.t);i<m;)c+=this[i]-a[i],r[i++]=c&this.DM,c>>=this.DB;if(a.t<this.t){for(c-=a.s;i<this.t;)c+=this[i],r[i++]=c&this.DM,c>>=this.DB;c+=this.s}else{for(c+=this.s;i<a.t;)c-=a[i],r[i++]=c&this.DM,c>>=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<y.t;++i)r[i+x.t]=x.am(0,y[i],r,i,0,x.t);r.s=0,r.clamp(),this.s!=a.s&&BigInteger.ZERO.subTo(r,r)},BigInteger.prototype.squareTo=function(r){for(var x=this.abs(),i=r.t=2*x.t;--i>=0;)r[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x[i],r,2*i,0,1);(r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1))>=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.t<pm.t)return null!=q&&q.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=nbi());var y=nbi(),ts=this.s,ms=m.s,nsh=this.DB-nbits(pm[pm.t-1]);nsh>0?(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<<this.F1)+(ys>1?y[ys-2]>>this.F2:0),d1=this.FV/yt,d2=(1<<this.F1)/yt,e=1<<this.F2,i=r.t,j=i-ys,t=null==q?nbi():q;for(y.dlShiftTo(j,t),r.compareTo(t)>=0&&(r[r.t++]=1,r.subTo(t,r)),BigInteger.ONE.dlShiftTo(ys,t),t.subTo(y,y);y.t<ys;)y[y.t++]=0;for(;--j>=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))<qd)for(y.dlShiftTo(j,t),r.subTo(t,r);r[i]<--qd;)r.subTo(t,r)}null!=q&&(r.drShiftTo(ys,q),ts!=ms&&BigInteger.ZERO.subTo(q,q)),r.t=ys,r.clamp(),nsh>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<<i)>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<<k)-1,m=!1,r="",i=this.t,p=this.DB-i*this.DB%k;if(i-- >0)for(p<this.DB&&(d=this[i]>>p)>0&&(m=!0,r=int2char(d));i>=0;)p<k?(d=(this[i]&(1<<p)-1)<<k-p,d|=this[--i]>>(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<s.length;++i){var x=intAt(s,i);x<0?"-"==s.charAt(i)&&0==this.signum()&&(mi=!0):(w=b*w+x,++j>=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<<t)-1:x[0]=0,this.fromString(x,256)}},BigInteger.prototype.bitwiseTo=function(a,op,r){var i,f,m=Math.min(a.t,this.t);for(i=0;i<m;++i)r[i]=op(this[i],a[i]);if(a.t<this.t){for(f=a.s&this.DM,i=m;i<this.t;++i)r[i]=op(this[i],f);r.t=this.t}else{for(f=this.s&this.DM,i=m;i<a.t;++i)r[i]=op(f,a[i]);r.t=a.t}r.s=op(this.s,a.s),r.clamp()},BigInteger.prototype.changeBit=function(n,op){var r=BigInteger.ONE.shiftLeft(n);return this.bitwiseTo(r,op,r),r},BigInteger.prototype.addTo=function(a,r){for(var i=0,c=0,m=Math.min(a.t,this.t);i<m;)c+=this[i]+a[i],r[i++]=c&this.DM,c>>=this.DB;if(a.t<this.t){for(c+=a.s;i<this.t;)c+=this[i],r[i++]=c&this.DM,c>>=this.DB;c+=this.s}else{for(c+=this.s;i<a.t;)c+=a[i],r[i++]=c&this.DM,c>>=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<j;++i)r[i+this.t]=this.am(0,a[i],r,i,0,this.t);for(j=Math.min(a.t,n);i<j;++i)this.am(0,a[i],r,i,0,n-i);r.clamp()},BigInteger.prototype.multiplyUpperTo=function(a,n,r){--n;var i=r.t=this.t+a.t-n;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(n-this.t,0);i<a.t;++i)r[this.t+i-n]=this.am(n-i,a[i],r,0,0,this.t+i-n);r.clamp(),r.drShiftTo(1,r)},BigInteger.prototype.modInt=function(n){if(n<=0)return 0;var d=this.DV%n,r=this.s<0?n-1:0;if(this.t>0)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<t;++i){a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var y=a.modPow(r,this);if(0!=y.compareTo(BigInteger.ONE)&&0!=y.compareTo(n1)){for(var j=1;j++<k&&0!=y.compareTo(n1);)if(0==(y=y.modPowInt(2,this)).compareTo(BigInteger.ONE))return!1;if(0!=y.compareTo(n1))return!1}}return!0},BigInteger.prototype.clone=function(){var r=nbi();return this.copyTo(r),r},BigInteger.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},BigInteger.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>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<this.DB&&(d=this[i]>>p)!=(this.s&this.DM)>>p&&(r[k++]=d|this.s<<this.DB-p);i>=0;)p<8?(d=(this[i]&(1<<p)-1)<<8-p,d|=this[--i]>>(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;++i)r[i]=this.DM&~this[i];return r.t=this.t,r.s=~this.s,r},BigInteger.prototype.shiftLeft=function(n){var r=nbi();return n<0?this.rShiftTo(-n,r):this.lShiftTo(n,r),r},BigInteger.prototype.shiftRight=function(n){var r=nbi();return n<0?this.lShiftTo(-n,r):this.rShiftTo(n,r),r},BigInteger.prototype.getLowestSetBit=function(){for(var i=0;i<this.t;++i)if(0!=this[i])return i*this.DB+lbit(this[i]);return this.s<0?this.t*this.DB:-1},BigInteger.prototype.bitCount=function(){for(var r=0,x=this.s&this.DM,i=0;i<this.t;++i)r+=cbit(this[i]^x);return r},BigInteger.prototype.testBit=function(n){var j=Math.floor(n/this.DB);return j>=this.t?0!=this.s:0!=(this[j]&1<<n%this.DB)},BigInteger.prototype.setBit=function(n){return this.changeBit(n,op_or)},BigInteger.prototype.clearBit=function(n){return this.changeBit(n,op_andnot)},BigInteger.prototype.flipBit=function(n){return this.changeBit(n,op_xor)},BigInteger.prototype.add=function(a){var r=nbi();return this.addTo(a,r),r},BigInteger.prototype.subtract=function(a){var r=nbi();return this.subTo(a,r),r},BigInteger.prototype.multiply=function(a){var r=nbi();return this.multiplyTo(a,r),r},BigInteger.prototype.divide=function(a){var r=nbi();return this.divRemTo(a,r,null),r},BigInteger.prototype.remainder=function(a){var r=nbi();return this.divRemTo(a,null,r),r},BigInteger.prototype.divideAndRemainder=function(a){var q=nbi(),r=nbi();return this.divRemTo(a,q,r),new Array(q,r)},BigInteger.prototype.modPow=function(e,m){var k,z,i=e.bitLength(),r=nbv(1);if(i<=0)return r;k=i<18?1:i<48?3:i<144?4:i<768?5:6,z=i<8?new Classic(m):m.isEven()?new Barrett(m):new Montgomery(m);var g=[],n=3,k1=k-1,km=(1<<k)-1;if(g[1]=z.convert(this),k>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<<i+1)-1)<<k1-i,j>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<<i);)z.sqrTo(r,r2),t=r,r=r2,r2=t,--i<0&&(i=this.DB-1,--j)}return z.revert(r)},BigInteger.prototype.modInverse=function(m){var ac=m.isEven();if(this.isEven()&&ac||0==m.signum())return BigInteger.ZERO;for(var u=m.clone(),v=this.clone(),a=nbv(1),b=nbv(0),c=nbv(0),d=nbv(1);0!=u.signum();){for(;u.isEven();)u.rShiftTo(1,u),ac?(a.isEven()&&b.isEven()||(a.addTo(this,a),b.subTo(m,b)),a.rShiftTo(1,a)):b.isEven()||b.subTo(m,b),b.rShiftTo(1,b);for(;v.isEven();)v.rShiftTo(1,v),ac?(c.isEven()&&d.isEven()||(c.addTo(this,c),d.subTo(m,d)),c.rShiftTo(1,c)):d.isEven()||d.subTo(m,d),d.rShiftTo(1,d);u.compareTo(v)>=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(i<g&&(g=i),g>0&&(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;i<lowprimes.length;++i)if(x[0]==lowprimes[i])return!0;return!1}if(x.isEven())return!1;for(i=1;i<lowprimes.length;){for(var m=lowprimes[i],j=i+1;j<lowprimes.length&&m<lplim;)m*=lowprimes[j++];for(m=x.modInt(m);i<j;)if(m%lowprimes[i++]==0)return!1}return x.millerRabin(t)},BigInteger.prototype.square=function(){var r=nbi();return this.squareTo(r),r};var RSAKey=function RSAKey(){classCallCheck(this,RSAKey),this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null};RSAKey.prototype.doPublic=function(x){return x.modPowInt(this.e,this.n)},RSAKey.prototype.setPublic=function(N,E){null!=N&&null!=E&&N.length>0&&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<s.length+11)return console.error("Message too long for RSA"),null;for(var ba=[],i=s.length-1;i>=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&&0==b[i];)++i;if(b.length-i!=n-1||2!=b[i])return null;for(++i;0!=b[i];)if(++i>=b.length)return null;for(var ret="";++i<b.length;){var c=255&b[i];c<128?ret+=String.fromCharCode(c):c>191&&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<ignore.length;++i)decoder[ignore.charAt(i)]=-1}var out=[],bits=0,char_count=0;for(i=0;i<a.length;++i){var c=a.charAt(i);if("="==c)break;if(-1!=(c=decoder[c])){if(void 0===c)throw"Illegal character at offset "+i;bits|=c,++char_count>=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<ignore.length;++i)decoder$1[ignore.charAt(i)]=-1}var out=[],bits=0,char_count=0;for(i=0;i<a.length;++i){var c=a.charAt(i);if("="==c)break;if(-1!=(c=decoder$1[c])){if(void 0===c)throw"Illegal character at offset "+i;bits|=c,++char_count>=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;i<ADD.length;i+=1)f=s[fname=ADD[i]],L.isFunction(f)&&f!=OP[fname]&&(r[fname]=f)}:function(){},JSX.extend=function(subc,superc,overrides){if(!superc||!subc)throw new Error("extend failed, please check that all dependencies are included.");var i,F=function(){};if(F.prototype=superc.prototype,subc.prototype=new F,subc.prototype.constructor=subc,subc.superclass=superc.prototype,superc.prototype.constructor==OP.constructor&&(superc.prototype.constructor=superc),overrides){for(i in overrides)L.hasOwnProperty(overrides,i)&&(subc.prototype[i]=overrides[i]);L._IEEnumFix(subc.prototype,overrides)}};var KJUR={};void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(i){var h=i.toString(16);return h.length%2==1&&(h="0"+h),h},this.bigIntToMinTwosComplementsHex=function(bigIntegerValue){var h=bigIntegerValue.toString(16);if("-"!=h.substr(0,1))h.length%2==1?h="0"+h:h.match(/^[0-7]/)||(h="00"+h);else{var xorLen=h.substr(1).length;xorLen%2==1?xorLen+=1:h.match(/^[0-7]/)||(xorLen+=2);for(var hMask="",i=0;i<xorLen;i++)hMask+="f";h=new BigInteger(hMask,16).xor(bigIntegerValue).add(BigInteger.ONE).toString(16).replace(/^-/,"")}return h},this.getPEMStringFromHex=function(dataHex,pemHeader){var dataWA=CryptoJS.enc.Hex.parse(dataHex),pemBody=CryptoJS.enc.Base64.stringify(dataWA).replace(/(.{64})/g,"$1\r\n");return pemBody=pemBody.replace(/\r\n$/,""),"-----BEGIN "+pemHeader+"-----\r\n"+pemBody+"\r\n-----END "+pemHeader+"-----\r\n"}},KJUR.asn1.ASN1Object=function(){this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw"this.hV is null or undefined.";if(this.hV.length%2==1)throw"value hex must be even length: n="+"".length+",v="+this.hV;var n=this.hV.length/2,hN=n.toString(16);if(hN.length%2==1&&(hN="0"+hN),n<128)return hN;var hNlen=hN.length/2;if(hNlen>15)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<unusedBits)throw"unused bits shall be from 0 to 7: u = "+unusedBits;var hUnusedBits="0"+unusedBits;this.hTLV=null,this.isModified=!0,this.hV=hUnusedBits+hValue},this.setByBinaryString=function(binaryString){var unusedBits=8-(binaryString=binaryString.replace(/0+$/,"")).length%8;8==unusedBits&&(unusedBits=0);for(i=0;i<=unusedBits;i++)binaryString+="0";for(var h="",i=0;i<binaryString.length-1;i+=8){var b=binaryString.substr(i,8),x=parseInt(b,2).toString(16);1==x.length&&(x="0"+x),h+=x}this.hTLV=null,this.isModified=!0,this.hV="0"+unusedBits+h},this.setByBooleanArray=function(booleanArray){for(var s="",i=0;i<booleanArray.length;i++)1==booleanArray[i]?s+="1":s+="0";this.setByBinaryString(s)},this.newFalseArray=function(nLength){for(var a=new Array(nLength),i=0;i<nLength;i++)a[i]=!1;return a},this.getFreshValueHex=function(){return this.hV},void 0!==params&&(void 0!==params.hex?this.setHexValueIncludingUnusedBits(params.hex):void 0!==params.bin?this.setByBinaryString(params.bin):void 0!==params.array&&this.setByBooleanArray(params.array))},JSX.extend(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object),KJUR.asn1.DEROctetString=function(params){KJUR.asn1.DEROctetString.superclass.constructor.call(this,params),this.hT="04"},JSX.extend(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},JSX.extend(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object),KJUR.asn1.DERObjectIdentifier=function(params){var itox=function(i){var h=i.toString(16);return 1==h.length&&(h="0"+h),h},roidtox=function(roid){var h="",b=new BigInteger(roid,10).toString(2),padLen=7-b.length%7;7==padLen&&(padLen=0);for(var bPad="",i=0;i<padLen;i++)bPad+="0";b=bPad+b;for(i=0;i<b.length-1;i+=7){var b8=b.substr(i,7);i!=b.length-7&&(b8="1"+b8),h+=itox(parseInt(b8,2))}return h};KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(newHexString){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=newHexString},this.setValueOidString=function(oidString){if(!oidString.match(/^[0-9.]+$/))throw"malformed oid string: "+oidString;var h="",a=oidString.split("."),i0=40*parseInt(a[0])+parseInt(a[1]);h+=itox(i0),a.splice(0,2);for(var i=0;i<a.length;i++)h+=roidtox(a[i]);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=h},this.setValueName=function(oidName){if(void 0===KJUR.asn1.x509.OID.name2oidList[oidName])throw"DERObjectIdentifier oidName undefined: "+oidName;var oid=KJUR.asn1.x509.OID.name2oidList[oidName];this.setValueOidString(oid)},this.getFreshValueHex=function(){return this.hV},void 0!==params&&(void 0!==params.oid?this.setValueOidString(params.oid):void 0!==params.hex?this.setValueHex(params.hex):void 0!==params.name&&this.setValueName(params.name))},JSX.extend(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.DERUTF8String=function(params){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,params),this.hT="0c"},JSX.extend(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNumericString=function(params){KJUR.asn1.DERNumericString.superclass.constructor.call(this,params),this.hT="12"},JSX.extend(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERPrintableString=function(params){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,params),this.hT="13"},JSX.extend(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERTeletexString=function(params){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,params),this.hT="14"},JSX.extend(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERIA5String=function(params){KJUR.asn1.DERIA5String.superclass.constructor.call(this,params),this.hT="16"},JSX.extend(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERUTCTime=function(params){KJUR.asn1.DERUTCTime.superclass.constructor.call(this,params),this.hT="17",this.setByDate=function(dateObject){this.hTLV=null,this.isModified=!0,this.date=dateObject,this.s=this.formatDate(this.date,"utc"),this.hV=stohex(this.s)},void 0!==params&&(void 0!==params.str?this.setString(params.str):void 0!==params.hex?this.setStringHex(params.hex):void 0!==params.date&&this.setByDate(params.date))},JSX.extend(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERGeneralizedTime=function(params){KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this,params),this.hT="18",this.setByDate=function(dateObject){this.hTLV=null,this.isModified=!0,this.date=dateObject,this.s=this.formatDate(this.date,"gen"),this.hV=stohex(this.s)},void 0!==params&&(void 0!==params.str?this.setString(params.str):void 0!==params.hex?this.setStringHex(params.hex):void 0!==params.date&&this.setByDate(params.date))},JSX.extend(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERSequence=function(params){KJUR.asn1.DERSequence.superclass.constructor.call(this,params),this.hT="30",this.getFreshValueHex=function(){for(var h="",i=0;i<this.asn1Array.length;i++){h+=this.asn1Array[i].getEncodedHex()}return this.hV=h,this.hV}},JSX.extend(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERSet=function(params){KJUR.asn1.DERSet.superclass.constructor.call(this,params),this.hT="31",this.getFreshValueHex=function(){for(var a=new Array,i=0;i<this.asn1Array.length;i++){var asn1Obj=this.asn1Array[i];a.push(asn1Obj.getEncodedHex())}return a.sort(),this.hV=a.join(""),this.hV}},JSX.extend(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERTaggedObject=function(params){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this),this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(isExplicitFlag,tagNoHex,asn1Object){this.hT=tagNoHex,this.isExplicit=isExplicitFlag,this.asn1Object=asn1Object,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=asn1Object.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,tagNoHex),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},void 0!==params&&(void 0!==params.tag&&(this.hT=params.tag),void 0!==params.explicit&&(this.isExplicit=params.explicit),void 0!==params.obj&&(this.asn1Object=params.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},JSX.extend(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object);var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="=";ASN1.prototype.getHexStringValue=function(){var hexString=this.toHexString(),offset=2*this.header,length=2*this.length;return hexString.substr(offset,length)},RSAKey.prototype.parseKey=function(pem){try{var modulus=0,public_exponent=0,der=/^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/.test(pem)?Hex.decode(pem):Base64.unarmor(pem),asn1=ASN1.decode(der);if(3===asn1.sub.length&&(asn1=asn1.sub[2].sub[0]),9===asn1.sub.length){modulus=asn1.sub[1].getHexStringValue(),this.n=parseBigInt(modulus,16),public_exponent=asn1.sub[2].getHexStringValue(),this.e=parseInt(public_exponent,16);var private_exponent=asn1.sub[3].getHexStringValue();this.d=parseBigInt(private_exponent,16);var prime1=asn1.sub[4].getHexStringValue();this.p=parseBigInt(prime1,16);var prime2=asn1.sub[5].getHexStringValue();this.q=parseBigInt(prime2,16);var exponent1=asn1.sub[6].getHexStringValue();this.dmp1=parseBigInt(exponent1,16);var exponent2=asn1.sub[7].getHexStringValue();this.dmq1=parseBigInt(exponent2,16);var coefficient=asn1.sub[8].getHexStringValue();this.coeff=parseBigInt(coefficient,16)}else{if(2!==asn1.sub.length)return!1;var sequence=asn1.sub[1].sub[0];modulus=sequence.sub[0].getHexStringValue(),this.n=parseBigInt(modulus,16),public_exponent=sequence.sub[1].getHexStringValue(),this.e=parseInt(public_exponent,16)}return!0}catch(ex){return!1}},RSAKey.prototype.getPrivateBaseKey=function(){var options={array:[new KJUR.asn1.DERInteger({int:0}),new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e}),new KJUR.asn1.DERInteger({bigint:this.d}),new KJUR.asn1.DERInteger({bigint:this.p}),new KJUR.asn1.DERInteger({bigint:this.q}),new KJUR.asn1.DERInteger({bigint:this.dmp1}),new KJUR.asn1.DERInteger({bigint:this.dmq1}),new KJUR.asn1.DERInteger({bigint:this.coeff})]};return new KJUR.asn1.DERSequence(options).getEncodedHex()},RSAKey.prototype.getPrivateBaseKeyB64=function(){return hex2b64(this.getPrivateBaseKey())},RSAKey.prototype.getPublicBaseKey=function(){var options={array:[new KJUR.asn1.DERObjectIdentifier({oid:"1.2.840.113549.1.1.1"}),new KJUR.asn1.DERNull]},first_sequence=new KJUR.asn1.DERSequence(options);options={array:[new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e})]};options={hex:"00"+new KJUR.asn1.DERSequence(options).getEncodedHex()};options={array:[first_sequence,new KJUR.asn1.DERBitString(options)]};return new KJUR.asn1.DERSequence(options).getEncodedHex()},RSAKey.prototype.getPublicBaseKeyB64=function(){return hex2b64(this.getPublicBaseKey())},RSAKey.prototype.wordwrap=function(str,width){if(width=width||64,!str)return str;var regex="(.{1,"+width+"})( +|$\n?)|(.{1,"+width+"})";return str.match(RegExp(regex,"g")).join("\n")},RSAKey.prototype.getPrivateKey=function(){var key="-----BEGIN RSA PRIVATE KEY-----\n";return key+=this.wordwrap(this.getPrivateBaseKeyB64())+"\n",key+="-----END RSA PRIVATE KEY-----"},RSAKey.prototype.getPublicKey=function(){var key="-----BEGIN PUBLIC KEY-----\n";return key+=this.wordwrap(this.getPublicBaseKeyB64())+"\n",key+="-----END PUBLIC KEY-----"},RSAKey.prototype.hasPublicKeyProperty=function(obj){return(obj=obj||{}).hasOwnProperty("n")&&obj.hasOwnProperty("e")},RSAKey.prototype.hasPrivateKeyProperty=function(obj){return(obj=obj||{}).hasOwnProperty("n")&&obj.hasOwnProperty("e")&&obj.hasOwnProperty("d")&&obj.hasOwnProperty("p")&&obj.hasOwnProperty("q")&&obj.hasOwnProperty("dmp1")&&obj.hasOwnProperty("dmq1")&&obj.hasOwnProperty("coeff")},RSAKey.prototype.parsePropertiesFrom=function(obj){this.n=obj.n,this.e=obj.e,obj.hasOwnProperty("d")&&(this.d=obj.d,this.p=obj.p,this.q=obj.q,this.dmp1=obj.dmp1,this.dmq1=obj.dmq1,this.coeff=obj.coeff)};var JSEncryptRSAKey=function(_RSAKey){function JSEncryptRSAKey(key){classCallCheck(this,JSEncryptRSAKey);var _this=possibleConstructorReturn(this,(JSEncryptRSAKey.__proto__||Object.getPrototypeOf(JSEncryptRSAKey)).call(this));return key&&("string"==typeof key?_this.parseKey(key):(_this.hasPrivateKeyProperty(key)||_this.hasPublicKeyProperty(key))&&_this.parsePropertiesFrom(key)),_this}return inherits(JSEncryptRSAKey,RSAKey),JSEncryptRSAKey}(),JSEncrypt=function JSEncrypt(options){classCallCheck(this,JSEncrypt),options=options||{},this.default_key_size=parseInt(options.default_key_size)||1024,this.default_public_exponent=options.default_public_exponent||"010001",this.log=options.log||!1,this.key=null};JSEncrypt.prototype.setKey=function(key){this.log&&this.key&&console.warn("A key was already set, overriding existing."),this.key=new JSEncryptRSAKey(key)},JSEncrypt.prototype.setPrivateKey=function(privkey){this.setKey(privkey)},JSEncrypt.prototype.setPublicKey=function(pubkey){this.setKey(pubkey)},JSEncrypt.prototype.decrypt=function(string){try{return this.getKey().decrypt(function(s){var i,slop,ret="",k=0;for(i=0;i<s.length&&s.charAt(i)!=b64pad;++i){var v=b64map.indexOf(s.charAt(i));v<0||(0==k?(ret+=int2char(v>>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;i<this.proxies.length;++i)promises.push(this.proxies[i].close());return this.proxies=[],this.proxies.length?Promise.all(promises):Promise.resolve()}},{key:"socket",value:function(){return this.proxies[this.currentProxy++%this.proxies.length]}},{key:"send",value:function(_data,fn){var res=this.socket().send(_data);return fn&&fn(res.seq),res.promise}}],[{key:"canTransfer",value:function(stream_type){return WebsocketTransport.streamTypes().includes(stream_type)}},{key:"streamTypes",value:function(){return["hls","rtsp"]}}]),WebsocketTransport}(),WSPProtocol=function(){function WSPProtocol(ver){classCallCheck(this,WSPProtocol),this.ver=ver}return createClass(WSPProtocol,null,[{key:"PROTO",get:function(){return"WSP"}},{key:"V1_1",get:function(){return"1.1"}},{key:"CMD_INIT",get:function(){return"INIT"}},{key:"CMD_JOIN",get:function(){return"JOIN"}},{key:"CMD_WRAP",get:function(){return"WRAP"}}]),createClass(WSPProtocol,[{key:"build",value:function(cmd,data){var payload=arguments.length>2&&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<this.player.children.length&&!this._checkSource(this.player.children[i]);++i);this.url&&this.setSource(this.url,this.type),this.player.addEventListener("play",function(){_this.isPlaying()||_this.client.start()},!1),this.player.addEventListener("pause",function(){_this.client.stop()},!1)}return createClass(WSPlayer,[{key:"isPlaying",value:function(){return!(this.player.paused||this.client.paused)}},{key:"canPlayUrl",value:function(src){return StreamType.fromUrl(src)in this.modules}},{key:"_checkSource",value:function(src){return!(src.dataset.ignore||!src.src||this.player.canPlayType(src.type)||!StreamType.fromMime(src.type)&&!StreamType.fromUrl(src.src))&&(this.url=src.src,this.type=src.type?StreamType.fromMime(src.type):StreamType.fromUrl(src.src),!0)}},{key:"setSource",value:function(url,type){return __async(regeneratorRuntime.mark(function _callee(){var transport,lastType,client;return regeneratorRuntime.wrap(function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(!this.transport){_context.next=6;break}if(!this.client){_context.next=4;break}return _context.next=4,this.client.detachTransport();case 4:return _context.next=6,this.transport.destroy();case 6:_context.prev=6,this.endpoint=Url.parse(url),_context.next=13;break;case 10:return _context.prev=10,_context.t0=_context.catch(6),_context.abrupt("return");case 13:if(this.url=url,transport=this.modules[type].transport,this.transport=new transport.constructor(this.endpoint,this.type,transport.options),lastType=this.type,this.type=!!StreamType.isSupported(type)&&type||StreamType.fromMime(type),this.type){_context.next=20;break}throw new Error("Bad stream type");case 20:if(lastType==this.type&&this.client){_context.next=28;break}if(!this.client){_context.next=24;break}return _context.next=24,this.client.destroy();case 24:client=this.modules[type].client,this.client=new client,_context.next=29;break;case 28:this.client.reset();case 29:this.queryCredentials&&(this.client.queryCredentials=this.queryCredentials),this.remuxer&&(this.remuxer.destroy(),this.remuxer=null),this.remuxer=new Remuxer(this.player),this.remuxer.attachClient(this.client),this.client.attachTransport(this.transport),this.client.setSource(this.endpoint),this.player.autoplay&&this.start();case 36:case"end":return _context.stop()}},_callee,this,[[6,10]])}).call(this))}},{key:"start",value:function(){var _this2=this;this.client&&this.client.start().catch(function(e){_this2.errorHandler&&_this2.errorHandler(e)})}},{key:"stop",value:function(){this.client&&this.client.stop()}},{key:"destroy",value:function(){return __async(regeneratorRuntime.mark(function _callee2(){return regeneratorRuntime.wrap(function(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:if(!this.transport){_context2.next=6;break}if(!this.client){_context2.next=4;break}return _context2.next=4,this.client.detachTransport();case 4:return _context2.next=6,this.transport.destroy();case 6:if(!this.client){_context2.next=9;break}return _context2.next=9,this.client.destroy();case 9:this.remuxer&&(this.remuxer.destroy(),this.remuxer=null);case 10:case"end":return _context2.stop()}},_callee2,this)}).call(this))}}],[{key:"canPlayWithModules",value:function(mimeType,modules){var filteredModules={},_iteratorNormalCompletion2=!0,_didIteratorError2=!1,_iteratorError2=void 0;try{for(var _step2,_iterator2=modules[Symbol.iterator]();!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=!0){var module=_step2.value,transport=module.transport||WebsocketTransport,client=module.client||RTSPClient;transport.canTransfer(client.streamType())&&(filteredModules[client.streamType()]=!0)}}catch(err){_didIteratorError2=!0,_iteratorError2=err}finally{try{!_iteratorNormalCompletion2&&_iterator2.return&&_iterator2.return()}finally{if(_didIteratorError2)throw _iteratorError2}}for(var type in filteredModules)if(type==StreamType.fromMime(mimeType))return!0;return!1}},{key:"canPlay",value:function(resource){return StreamType.fromMime(resource.type)||StreamType.fromUrl(resource.src)}}]),WSPlayer}();!function(level){DEFAULT_LOG_LEVEL=level}(LogLevel_Error),window.Streamedian={logger:function(tag){return getTagged(tag)},player:function(node,opts){if(!opts.socket)throw new Error("socket parameter is not set");var _options={modules:[{client:RTSPClient,transport:{constructor:WebsocketTransport,options:{socket:opts.socket}}}],errorHandler:function(e){alert("Failed to start player: "+e.message)},queryCredentials:function(client){return new Promise(function(resolve,reject){var c=prompt("input credentials in format user:password");c?(client.setCredentials.apply(client,c.split(":")),resolve()):reject()})}};return new WSPlayer(node,_options)}}}();
//# sourceMappingURL=streamedian.min.js.map