red5pro-webrtc-sdk
Version:
Red5 Pro HTML SDK
34 lines (33 loc) • 160 kB
JavaScript
/**
*
* red5pro-html-sdk - Red5 Pro HTML SDK
* Author: Infrared5 Inc.
* Version: 15.5.0
* Url: https://www.red5.net
*
* Copyright © 2015 Infrared5, Inc. All rights reserved.
*
* The accompanying code comprising examples for use solely in conjunction with Red5 Pro (the "Example Code")
* is licensed to you by Infrared5 Inc. in consideration of your agreement to the following
* license terms and conditions. Access, use, modification, or redistribution of the accompanying
* code constitutes your acceptance of the following license terms and conditions.
*
* Permission is hereby granted, free of charge, to you to use the Example Code and associated documentation
* files (collectively, the "Software") without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The Software shall be used solely in conjunction with Red5 Pro. Red5 Pro is licensed under a separate end
* user license agreement (the "EULA"), which must be executed with Infrared5, Inc.
* An example of the EULA can be found on our website at: https://account.red5.net/assets/LICENSE.txt.
*
* The above copyright notice and this license shall be included in all copies or portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL INFRARED5, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).red5prosdk={})}(this,(function(e){"use strict";var t,i,n,s;e.PlaybackAudioEncoder=void 0,(t=e.PlaybackAudioEncoder||(e.PlaybackAudioEncoder={})).OPUS="OPUS",t.NONE="NONE",e.PlaybackVideoEncoder=void 0,(i=e.PlaybackVideoEncoder||(e.PlaybackVideoEncoder={})).VP8="VP8",i.H264="H264",i.H265="H265",i.NONE="NONE",e.PlaybackState=void 0,(n=e.PlaybackState||(e.PlaybackState={}))[n.UNAVAILABLE=1e3]="UNAVAILABLE",n[n.AVAILABLE=0]="AVAILABLE",n[n.IDLE=1]="IDLE",n[n.PLAYING=2]="PLAYING",n[n.PAUSED=3]="PAUSED",function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(s||(s={}));const o={[e.PlaybackState.UNAVAILABLE]:s.UNAVAILABLE,[e.PlaybackState.AVAILABLE]:s.AVAILABLE,[e.PlaybackState.IDLE]:s.IDLE,[e.PlaybackState.PLAYING]:s.PLAYING,[e.PlaybackState.PAUSED]:s.PAUSED};var a,r,l;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(a||(a={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(r||(r={})),e.PublishAudioEncoder=void 0,(e.PublishAudioEncoder||(e.PublishAudioEncoder={})).OPUS="OPUS",e.PublishVideoEncoder=void 0,(l=e.PublishVideoEncoder||(e.PublishVideoEncoder={})).VP8="VP8",l.H264="H264",l.H265="H265";var h={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},d={};function c(e){return"string"==typeof e?h[e.toLowerCase()]:e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function p(e,t,i){return p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,i){var n=[null];n.push.apply(n,t);var s=new(Function.bind.apply(e,n));return i&&u(s,i.prototype),s},p.apply(null,arguments)}function _(e){if(null==e)return e;if(Array.isArray(e))return e.slice();if("object"==typeof e){var t={};return Object.keys(e).forEach((function(i){t[i]=e[i]})),t}return e}function g(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"[ "+e.map((function(e){return g(e)})).join(", ")+" ]":"object"==typeof e?JSON.stringify(e):"function"==typeof e?"[Function: "+e.name+"]":"boolean"==typeof e||"number"==typeof e?e:"'"+e.toString()+"'"}function v(e){if("string"!=typeof e){for(var t=new Array(arguments.length),i=0;i<arguments.length;i++)t[i]=g(arguments[i]);return t.join(" ")}for(var n=1,s=arguments,o=s.length,a=String(e).replace(/%[sdj%]/g,(function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(s[n++]);case"%d":return Number(s[n++]);case"%j":try{return JSON.stringify(s[n++])}catch(e){return"[Circular]"}default:return e}})),r=s[n];n<o;r=s[++n])a+=null===r||"object"!=typeof r?" "+r:" "+g(r);return a}Object.keys(h).forEach((function(e){d[h[e]]=e}));var m={};function E(e,t){if(t){if(m[t])return;m[t]=!0}console.error(e+"\n")}var S=function(){function e(){}return e.prototype.write=function(e){e.level<30?console.log(e):e.level<40?console.info(e):e.level<50?console.warn(e):console.error(e),e.err&&e.err.stack&&console.error(e.err.stack),e.obj&&console.log(e.obj)},e}(),b=function(){function e(t,i,n){var s,o,a,r,l=this;if(!(this instanceof e))return new e(t,i);if(void 0!==i&&(s=t,t=i,!(s instanceof e)))throw new TypeError("invalid Logger creation: do not pass a second arg");if(!t)throw new TypeError("options (object) is required");if(s){if(t.name)throw new TypeError("invalid options.name: child cannot set logger name")}else if(!t.name)throw new TypeError("options.name (string) is required");if(t.stream&&t.streams)throw new TypeError('cannot mix "streams" and "stream" options');if(t.streams&&!Array.isArray(t.streams))throw new TypeError("invalid options.streams: must be an array");if(t.serializers&&("object"!=typeof t.serializers||Array.isArray(t.serializers)))throw new TypeError("invalid options.serializers: must be an object");if(s&&n){this._level=s._level,this.streams=s.streams,this.serializers=s.serializers,this.src=s.src,o=this.fields={};var h=Object.keys(s.fields);for(r=0;r<h.length;r++)o[a=h[r]]=s.fields[a];var d=Object.keys(t);for(r=0;r<d.length;r++)o[a=d[r]]=t[a]}else{if(s){for(this._level=s._level,this.streams=[],r=0;r<s.streams.length;r++){var c=_(s.streams[r]);this.streams.push(c)}this.serializers=_(s.serializers),this.src=s.src,this.fields=_(s.fields),t.level&&this.level(t.level)}else this._level=Number.POSITIVE_INFINITY,this.streams=[],this.serializers=null,this.src=!1,this.fields={};t.stream?this.addStream({type:"stream",stream:t.stream,level:t.level}):t.streams?t.streams.forEach((function(e){l.addStream(e,t.level)})):s&&t.level?this.level(t.level):s||this.addStream({type:"raw",stream:new S,level:t.level}),t.serializers&&this.addSerializers(t.serializers),t.src&&(this.src=!0),delete(o=_(t)).stream,delete o.level,delete o.streams,delete o.serializers,delete o.src,this.serializers&&this._applySerializers(o),Object.keys(o).forEach((function(e){l.fields[e]=o[e]}))}}var t=e.prototype;return t.addStream=function(e,t){void 0===t&&(t=30),(e=_(e)).type="raw",e.level=c(e.level||t),e.level<this._level&&(this._level=e.level),this.streams.push(e),delete this.haveNonRawStreams},t.addSerializers=function(e){var t=this;this.serializers||(this.serializers={}),Object.keys(e).forEach((function(i){var n=e[i];if("function"!=typeof n)throw new TypeError(v('invalid serializer for "%s" field: must be a function',i));t.serializers[i]=n}))},t.child=function(e,t){return new this.constructor(this,e||{},t)},t.level=function(e){if(void 0===e)return this._level;for(var t=c(e),i=this.streams.length,n=0;n<i;n++)this.streams[n].level=t;this._level=t},t.levels=function(e,t){if(void 0===e)return this.streams.map((function(e){return e.level}));var i;if("number"==typeof e){if(void 0===(i=this.streams[e]))throw new Error("invalid stream index: "+e)}else{for(var n=this.streams.length,s=0;s<n;s++){var o=this.streams[s];if(o.name===e){i=o;break}}if(!i)throw new Error(v('no stream with name "%s"',e))}if(void 0===t)return i.level;var a=c(t);i.level=a,a<this._level&&(this._level=a)},t._applySerializers=function(e,t){var i=this;Object.keys(this.serializers).forEach((function(n){if(!(void 0===e[n]||t&&t[n]))try{e[n]=i.serializers[n](e[n])}catch(t){E(v('bunyan: ERROR: Exception thrown from the "%s" Bunyan serializer. This should never happen. This is a bugin that serializer function.\n%s',n,t.stack||t)),e[n]=v('(Error in Bunyan log "%s" serializer broke field. See stderr for details.)',n)}}))},t._emit=function(e,t){var i,n;if(void 0===this.haveNonRawStreams)for(this.haveNonRawStreams=!1,i=0;i<this.streams.length;i++)if(!this.streams[i].raw){this.haveNonRawStreams=!0;break}if(t||this.haveNonRawStreams)try{n=JSON.stringify(e,function(){var e=[];return function(t,i){return i&&"object"==typeof i?-1!==e.indexOf(i)?"[Circular]":(e.push(i),i):i}}())+"\n"}catch(t){var s=t.stack.split(/\n/g,2).join("\n");E('bunyan: ERROR: Exception in `JSON.stringify(rec)`. You can install the "safe-json-stringify" module to have Bunyan fallback to safer stringification. Record:\n'+function(e,t){return t||(t=" "),t+e.split(/\r?\n/g).join("\n"+t)}(v("%s\n%s",e,t.stack)),s),n=v("(Exception in JSON.stringify(rec): %j. See stderr for details.)\n",t.message)}if(t)return n;var o=e.level;for(i=0;i<this.streams.length;i++){var a=this.streams[i];a.level<=o&&a.stream.write(e)}return n},e}();function C(e){return function(){var t=this;var i=null,n=arguments,s=null;if(0===arguments.length)return this._level<=e;this._level>e||(s=function(s){var o;s[0]instanceof Error?(i={err:t.serializers&&t.serializers.err?t.serializers.err(s[0]):y.err(s[0])},o={err:!0},n=1===s.length?[i.err.message]:Array.prototype.slice.call(s,1)):"object"!=typeof s[0]&&null!==s[0]||Array.isArray(s[0])?(i=null,n=Array.prototype.slice.call(s)):(i=s[0],n=1===s.length&&i.err&&i.err instanceof Error?[i.err.message]:Array.prototype.slice.call(s,1));var a=_(t.fields);a.level=e;var r=i?_(i):null;if(r&&(t.serializers&&t._applySerializers(r,o),Object.keys(r).forEach((function(e){a[e]=r[e]}))),a.levelName=d[e],a.msg=n.length?v.apply(t,n):"",a.time||(a.time=new Date),t.src&&!a.src)try{throw new Error("call-stack-error")}catch(e){var l=e.stack?function(e,t){var i=e.split("\n");i[0]&&i[0].indexOf("call-stack-error")>=0&&i.shift();var n=i[t],s=null;if(n){var o=/^\s*(at|.*@)\s*(.+)?$/.exec(n);s=Array.isArray(o)&&o[2]?o[2]:n}return s}(e.stack,2):"";l||function(e){return m[e]}("src")||E("Unable to determine src line info","src"),a.src=l||""}return a.v=1,a}(n),this._emit(s))}}function T(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var i=e.cause();i&&(t+="\nCaused by: "+T(i))}return t}b.prototype.trace=C(10),b.prototype.debug=C(20),b.prototype.info=C(30),b.prototype.warn=C(40),b.prototype.error=C(50),b.prototype.fatal=C(60);var y={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:T(e),code:e.code,signal:e.signal}:e}};const f={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class A{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,f[e.level]||"UNKNOWN",e.msg)}}let w,P;const N=e=>(t,i)=>{var n;w&&"function"==typeof w[e]&&w[e]((n=t,e=>`(${n}) ${e}`)(i))},R={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},L=(e,t=!1,i)=>{const n=[{level:e,stream:new A,type:"raw"}];if(i){const t=i.map((t=>({...t,level:e})));n.push(...t)}t&&(P=[],n.push({level:e,stream:{write:t=>{const i=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==P||P.push(i)}},type:"raw"}));w=function(){return p(b,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:n})},I=()=>(w||L(R.INFO),w),D=()=>P||[];N(R.TRACE),N(R.INFO);const O=N(R.DEBUG),H=N(R.WARN),k=N(R.ERROR);N(R.FATAL);const M="RED5PRO";class U{constructor(){this._callbacks={},this._callbacks[M]=[]}_notify(e,t){let i;const n=e.length;for(i=0;i<n;i++)e[i](t)}on(e,t){"function"==typeof t&&("*"!==e?(void 0===this._callbacks[e]&&(this._callbacks[e]=[]),-1===this._callbacks[e].indexOf(t)&&this._callbacks[e].push(t)):this._callbacks[M].push(t))}off(e,t){let i=this._callbacks[e];if("*"===e&&(i=this._callbacks[M]),i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}trigger(e){const t=e.type;this._callbacks[t]&&this._notify(this._callbacks[t],e),this._notify(this._callbacks[M],e)}}const B=/['"](.*?)['"]:/gi,V=/:['"](.*?)['"]/gi,F=new WeakMap;function $(e,t,i){let n="",s=t;const o=t+i;do{n+=String.fromCharCode(e[s++])}while(s<o);return n}function G(e,t){try{return JSON.parse(e)[t]}catch(i){const n=B.exec(e);let s;return n&&n.length>1&&(s=V.exec(e),n[1]===t&&s&&s.length>1)?s[1]:void 0}}function x(e){const t=G(e,"orientation");if(t)return{orientation:parseInt(t)}}function W(e){const t=G(e,"streamingMode");if(t)return{streamingMode:t}}const K=e=>F.get(e),j=e=>{const t=e.textTracks;t&&(e.addTextTrack("metadata"),t.addEventListener("addtrack",(t=>{const i=t.track;i.mode="hidden",i.addEventListener("cuechange",(t=>{let n,s;for(t&&t.currentTarget?n=t.currentTarget.cues:(n=i.cues,n=n&&n.length>0?n:i.activeCues),n=n||[],s=0;s<n.length;s++){const t=n[s];if(t.value){const i="string"==typeof t.value.data?t.value.data:$(t.value.data,0,t.size),n=x(i),s=W(i),o=K(e);n&&o&&o.orientation&&o.orientation.forEach((e=>{e(n)})),s&&o&&o.streamingMode&&o.streamingMode.forEach((e=>{e(s)}))}}}))})))},z="BrowserEnvironment",J=e=>O(z,e),Y=e=>H(z,e);let q=[];const X=()=>{const e=screen.orientation?screen.orientation.angle:void 0,t=void 0===e?window.matchMedia("(orientation: portrait)").matches?0:90:e,i=q.length;J(`[window:onorientationchange]: orientation(${t}).`);for(let e=0;e<i;e++)q[e]((t+90)%360)};let Q=!1;const Z=[],ee=()=>{const e=document.createElement("video");return e.canPlayType("application/vnd.apple.mpegURL").length>0||e.canPlayType("application/x-mpegURL").length>0||e.canPlayType("audio/mpegurl").length>0||e.canPlayType("audio/x-mpegurl").length>0},te="undefined"!=typeof window&&window.adapter;var ie={gUM:async e=>navigator.mediaDevices.getUserMedia(e),createElement:e=>document.createElement(e),resolveElement:e=>document.getElementById(e),getElementId:e=>e.id,setVideoSource:(e,t,i)=>{if(e.srcObject=t,i)try{const t=e.play();t&&t.then((()=>J("[setVideoSource:action]: play (START)"))).catch((t=>{Y(`[setVideoSource:action]: play (CATCH::FAULT) ${t.message}`);try{e.setAttribute("autoplay","false"),e.pause()}catch(e){Y(`[setVideoSource:action]: pause (CATCH::FAULT) ${e.message}`)}}))}catch(e){Y(`[setVideoSource:action]: play (CATCH::FAULT) ${e.message}`)}},hasAttributeDefined:(e,t)=>e.hasAttribute(t),addOrientationChangeHandler:(e,t=!0)=>{"onorientationchange"in window&&(J("[window:orientation:addOrientationChangeHandler]: add"),q.push(e),t&&X()),1===q.length&&(J("[window:orientation:addOrientationChangeHandler]: add"),window.addEventListener("orientationchange",X))},removeOrientationChangeHandler:e=>{q=q.filter((t=>t!==e)),0===q.length&&window.removeEventListener("orientationchange",X)},toggleFullScreen:e=>{window.screenfull&&window.screenfull.enabled?window.screenfull.toggle(e):document.fullscreenEnabled&&(document.fullscreenElement&&document.fullscreenElement===e?document.exitFullscreen():e.requestFullscreen())},onFullScreenStateChange:e=>{var t;Z.push(e),t=window.screenfull,Q||(Q=!0,window.screenfull?window.screenfull.on("change",(()=>{Z.forEach((e=>e(t.isFullscreen)))})):document.fullscreenEnabled&&document.addEventListener("fullscreenchange",(()=>{Z.forEach((e=>e(null!==document.fullscreenElement)))})))},getOrGenerateFingerprint:()=>{const e=window.localStorage;if(e&&e.getItem("red5_fingerprint"))return e.getItem("red5_fingerprint");let t;try{t=window.crypto.randomUUID()}catch(e){t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(Number(e)^crypto.getRandomValues(new Uint8Array(1))[0]&15>>Number(e)/4).toString(16)))}return e.setItem("red5_fingerprint",t),t},getBrowserDetails:()=>{const e=void 0!==window.adapter,{navigator:t,adapter:i}=window,{appVersion:n,platform:s,userAgent:o,vendor:a}=t,r={appVersion:n,platform:s,userAgent:o,vendor:a};return e?{...i.browserDetails,...r}:r},supportsHLS:ee,onOrientationMetadata:(e,t)=>{const i=F.get(e);F.has(e)?Object.prototype.hasOwnProperty.call(i,"orientation")||(F.get(e).orientation=[]):(j(e),F.set(e,{orientation:[]})),F.get(e).orientation.push(t)},onStreamingModeMetadata:(e,t)=>{const i=F.get(e);F.has(e)?Object.prototype.hasOwnProperty.call(i,"streamingMode")||(F.get(e).streamingMode=[]):(j(e),F.set(e,{streamingMode:[]})),F.get(e).streamingMode.push(t)},isTouchEnabled:()=>"ontouchstart"in window,isPossiblySafari:()=>te?"safari"===window.adapter.browserDetails.browser.toLowerCase():ee(),findByQuerySelector:e=>document.querySelector(e),addGlobalEventListener:(e,t,i=document)=>{i.addEventListener(e,t)},removeGlobalEventListener:(e,t,i=document)=>{i.removeEventListener(e,t)},supportsNonNativeHLS:e=>{if(e)try{return e.isSupported()}catch(e){return Y("Could not access Hls.js."),!1}return!!window.Hls&&window.Hls.isSupported()},createHLSClient:(e={})=>new window.Hls(e),getHLSClientEventEnum:()=>window.Hls.Events,globalAssign:(e,t)=>{window[e]=t},globalUnassign:e=>{delete window[e]},getAssignedValue:e=>window[e]};const ne=(e,t,i)=>{const{liveSeek:{baseURL:n,fullURL:s}}=e,{host:o,protocol:a,port:r,app:l,streamName:h}=e;if(i||s)return i||s;const d=o,c="ws"===a?"http":"https",u=5080===r?5080:443,p=l,_=t||n;if(_){const e=_.length-1;return`${"/"===_.charAt(e)?_.substring(0,e):_}/${p}/${h}.m3u8`}return`${c}://${d}:${u}/${p}/${h}.m3u8`},se=e=>{const t=new URL(e),i=t.pathname.split("/").filter((e=>e.length>0)),n="https:"===t.protocol?"https":"http",s=t.hostname;return{protocol:n,port:t.port.length>0?t.port:443,app:i[0],host:s,streamName:i[i.length-1]}},oe=(e,t="whip")=>{var i;const{endpoint:n,proxy:s}=e;if(n)return n;{const{protocol:n,host:o,port:a,app:r,streamName:l}=e,h=n.match(/^http/)?n:"ws"===n?"http":"https";return(null==s?void 0:s.enabled)?`${h}://${o}:${a}/as/${null!==(i=s.version)&&void 0!==i?i:"v1"}/proxy/${t}/${r}/${l}`:`${h}://${o}:${a}/${r}/${t}/endpoint/${l}`}},ae=e=>{const t={audio:!1,video:!1},i={audio:!1,video:!1};return e.getTracks().forEach((e=>{"video"===e.kind?(i.video=e.getSettings(),t.video=e.getConstraints()):"audio"===e.kind&&(i.audio=e.getSettings(),t.audio=e.getConstraints())})),{requested:t,accepted:i}},re=e=>{const t=e.length;return function i(...n){return n.length>=t?e(...n):function(...e){return i(...n,...e)}}},le=re(((e,t)=>{let i=0;const n=t.length,s=[];for(;i<n;)e(t[i])&&(s[s.length]=t[i]),i+=1;return s}));var he,de,ce,ue,pe,_e;!function(e){e.UDP="udp",e.TCP="tcp"}(he||(he={})),function(e){e.ENCODED_FRAME="EncodedFrame",e.PACKET="Packet"}(de||(de={})),function(e){e.VIDEO="encodeVideo",e.AUDIO="encodeAudio"}(ce||(ce={})),function(e){e.VIDEO="decodeVideo",e.AUDIO="decodeAudio"}(ue||(ue={})),function(e){e[e.FAILED=400]="FAILED",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.GONE=410]="GONE"}(pe||(pe={})),e.StatsEndpointType=void 0,(_e=e.StatsEndpointType||(e.StatsEndpointType={})).DEV_NULL="dev/null",_e.DATA_CHANNEL="data-channel",_e.EVENT_TRANSPORT="event-transport";const ge={endpoint:e.StatsEndpointType.DATA_CHANNEL,interval:5e3,include:[]},ve={...{protocol:"https",port:443,app:"live",streamMode:r.LIVE,keyFramerate:3e3,mediaElementId:"red5pro-publisher",rtcConfiguration:{iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:he.UDP,bandwidth:{audio:56,video:750},clearMediaOnUnpublish:!1,reconnect:void 0,mediaConstraints:{audio:!0,video:{width:{min:640,max:1920},height:{min:360,max:1080},frameRate:{min:30,max:60}}},dataChannelConfiguration:{name:"red5pro"},signalingSocketOnly:!1,includeDataChannel:!0,forceVP8:!1,videoEncoding:void 0,audioEncoding:void 0,stats:ge,pubnub:void 0},signalingSocketOnly:!1,enableChannelSignaling:!1,includeDataChannel:!0,disableProxy:!0,trickleIce:!0,mungeOffer:void 0,mungeAnswer:void 0,offerSDPResolution:!1},me={enabled:!1,timeout:2e3,maxAttempts:10};class Ee extends U{constructor(e){super(),this._name=e||"MessageTransport",this._responseHandlers=[],this._asyncTickets=[]}getJsonFromSocketMessage(e){try{return"string"==typeof e.data?JSON.parse(e.data):e.data}catch(t){H(this._name,"Could not parse message as JSON. Message= "+e.data+". Error= "+t.message)}return null}addResponseHandler(e){this._responseHandlers.push(e)}respond(e){H(this._name,`respond() should be overriden. Unhandled message: ${e}`)}post(e){return H(this._name,`post() should be overriden. Unhandled request: ${e}`),Promise.resolve(!1)}postAsync(e){const t=function(){let e,t;return{promise:new Promise(((i,n)=>{e=i,t=n})),resolve:e,reject:t}}(),i=Math.floor(65536*Math.random()).toString(16);return e.id=i,e.async=!0,this._asyncTickets.push({id:i,promise:t}),this.post(e),t.promise}handleMessageResponse(e){let t,i;const n=this._responseHandlers.length;for(t=0;t<n;t++)if(i=this._responseHandlers[t],i.respond(e))return!0;return!1}}let Se=class{constructor(e,t){this._type=e,this._data=t}get type(){return this._type}get data(){return this._data}};class be extends Se{constructor(e,t,i){super(e,i),this._publisher=t}get publisher(){return this._publisher}}class Ce extends Se{constructor(e,t,i){super(e,i),this._subscriber=t}get subscriber(){return this._subscriber}}class Te extends Se{constructor(e,t,i){super(e,i),this._name=t}get name(){return this._name}}class ye extends Se{constructor(e,t,i){super(e,i),this._pubnub=t}get pubnub(){return this._pubnub}}class fe extends Se{constructor(e,t,i){super(e,i),this._messageChannel=t}get messageChannel(){return this._messageChannel}}var Ae,we,Pe,Ne,Re,Le,Ie;e.PublisherEventTypes=void 0,(Ae=e.PublisherEventTypes||(e.PublisherEventTypes={})).RECONNECT_START="Reconnect.Start",Ae.RECONNECT_FAILURE="Reconnect.Failure",Ae.RECONNECT_SUCCESS="Reconnect.Success",Ae.CONNECT_SUCCESS="Connect.Success",Ae.CONNECT_FAILURE="Connect.Failure",Ae.PUBLISH_START="Publish.Start",Ae.PUBLISH_FAIL="Publish.Fail",Ae.PUBLISH_INVALID_NAME="Publish.InvalidName",Ae.UNPUBLISH_SUCCESS="Unpublish.Success",Ae.PUBLISH_METADATA="Publish.Metadata",Ae.PUBLISH_STATUS="Publish.Status",Ae.PUBLISH_AVAILABLE="Publish.Available",Ae.PUBLISH_INSUFFICIENT_BANDWIDTH="Publish.InsufficientBW",Ae.PUBLISH_SUFFICIENT_BANDWIDTH="Publish.SufficientBW",Ae.PUBLISH_RECOVERING_BANDWIDTH="Publish.RecoveringBW",Ae.PUBLISH_SEND_INVOKE="Publish.Send.Invoke",Ae.CONNECTION_CLOSED="Publisher.Connection.Closed",Ae.DIMENSION_CHANGE="Publisher.Video.DimensionChange",Ae.STATISTICS_ENDPOINT_CHANGE="Publisher.StatisticsEndpoint.Change",e.RTCPublisherEventTypes=void 0,(we=e.RTCPublisherEventTypes||(e.RTCPublisherEventTypes={})).CONSTRAINTS_ACCEPTED="WebRTC.MediaConstraints.Accepted",we.CONSTRAINTS_REJECTED="WebRTC.MediaConstraints.Rejected",we.MEDIA_STREAM_AVAILABLE="WebRTC.MediaStream.Available",we.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",we.OFFER_START="WebRTC.Offer.Start",we.OFFER_END="WebRTC.Offer.End",we.CANDIDATE_CREATE="WebRTC.Candidate.Create",we.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",we.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",we.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",we.SOCKET_MESSAGE="WebRTC.Socket.Message",we.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",we.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",we.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",we.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",we.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",we.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",we.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",we.UNSUPPORTED_FEATURE="WebRTC.Unsupported.Feature",we.TRANSFORM_ERROR="WebRTC.Transform.Error",we.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",we.STATS_REPORT="WebRTC.Stats.Report",e.SubscriberEventTypes=void 0,(Pe=e.SubscriberEventTypes||(e.SubscriberEventTypes={})).RECONNECT_START="Reconnect.Start",Pe.RECONNECT_FAILURE="Reconnect.Failure",Pe.CONNECT_SUCCESS="Connect.Success",Pe.CONNECT_FAILURE="Connect.Failure",Pe.SUBSCRIBE_START="Subscribe.Start",Pe.SUBSCRIBE_STOP="Subscribe.Stop",Pe.SUBSCRIBE_FAIL="Subscribe.Fail",Pe.SUBSCRIBE_INVALID_NAME="Subscribe.InvalidName",Pe.SUBSCRIBE_METADATA="Subscribe.Metadata",Pe.SUBSCRIBE_STATUS="Subscribe.Status",Pe.SUBSCRIBE_SEND_INVOKE="Subscribe.Send.Invoke",Pe.SUBSCRIBE_PUBLISHER_CONGESTION="Subscribe.Publisher.NetworkCongestion",Pe.SUBSCRIBE_PUBLISHER_RECOVERY="Subscribe.Publisher.NetworkRecovery",Pe.PLAY_UNPUBLISH="Subscribe.Play.Unpublish",Pe.CONNECTION_CLOSED="Subscribe.Connection.Closed",Pe.ORIENTATION_CHANGE="Subscribe.Orientation.Change",Pe.STREAMING_MODE_CHANGE="Subscribe.StreamingMode.Change",Pe.VIDEO_DIMENSIONS_CHANGE="Subscribe.VideoDimensions.Change",Pe.LOADED_METADATA="Subscribe.LoadedMetadata",Pe.VOLUME_CHANGE="Subscribe.Volume.Change",Pe.SEEK_CHANGE="Subscribe.Seek.Change",Pe.PLAYBACK_TIME_UPDATE="Subscribe.Time.Update",Pe.PLAYBACK_STATE_CHANGE="Subscribe.Playback.Change",Pe.FULL_SCREEN_STATE_CHANGE="Subscribe.FullScreen.Change",Pe.AUTO_PLAYBACK_FAILURE="Subscribe.Autoplay.Failure",Pe.AUTO_PLAYBACK_MUTED="Subscribe.Autoplay.Muted",Pe.STATISTICS_ENDPOINT_CHANGE="Subscribe.StatisticsEndpoint.Change",e.RTCSubscriberEventTypes=void 0,(Ne=e.RTCSubscriberEventTypes||(e.RTCSubscriberEventTypes={})).PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",Ne.OFFER_START="WebRTC.Offer.Start",Ne.OFFER_END="WebRTC.Offer.End",Ne.ANSWER_START="WebRTC.Answer.Start",Ne.ANSWER_END="WebRTC.Answer.End",Ne.CANDIDATE_CREATE="WebRTC.Candidate.Create",Ne.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",Ne.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",Ne.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",Ne.SOCKET_MESSAGE="WebRTC.Socket.Message",Ne.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",Ne.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",Ne.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",Ne.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",Ne.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",Ne.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",Ne.ON_ADD_STREAM="WebRTC.Add.Stream",Ne.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",Ne.SUBSCRIBE_STREAM_SWITCH="WebRTC.Subscribe.StreamSwitch",Ne.TRANSFORM_ERROR="WebRTC.Transform.Error",Ne.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",Ne.STATS_REPORT="WebRTC.Stats.Report",e.MessageTransportStateEventTypes=void 0,(Re=e.MessageTransportStateEventTypes||(e.MessageTransportStateEventTypes={})).OPEN="MessageTransport.Open",Re.CLOSE="MessageTransport.Close",Re.CHANGE="MessageTransport.Change",Re.ERROR="MessageTransport.Error",function(e){e.CONNECTION_HEALTH_STALE_STATS="WebRTC.Connection.StaleStats",e.CONNECTION_HEALTH_STATE_REGRESSION="WebRTC.Connection.StateRegression",e.CONNECTION_HEALTH_EXCESSIVE_RTT="WebRTC.Connection.ExcessiveRTT",e.CONNECTION_HEALTH_ICE_TIMEOUT="WebRTC.Connection.IceTimeout"}(Le||(Le={})),e.MessageChannelEventTypes=void 0,(Ie=e.MessageChannelEventTypes||(e.MessageChannelEventTypes={})).OPEN="MessageChannel.Open",Ie.SEND="MessageChannel.Send",Ie.RECEIVE="MessageChannel.Receive",Ie.CLOSE="MessageChannel.Close",Ie.FAIL="MessageChannel.Fail",Ie.ERROR="MessageChannel.Error";const De=[{urls:"stun:stun2.l.google.com:19302"}];class Oe extends Ee{constructor(e,t="R5RTCPeerConnectionHelper"){super(t),this._responder=e}_removeDataChannelHandlers(e){e.onopen=null,e.onerror=null,e.onclose=null,e.onmessage=null}_addDataChannelHandlers(t){t.onerror=e=>{this._responder.onDataChannelError(t,e.error.message)},t.onmessage=e=>{this._onDataChannelMessage(e)},t.onopen=()=>{this._responder.onDataChannelOpen(t)},t.onclose=i=>{this._responder.onDataChannelClose(t),this.trigger(new Te(e.MessageTransportStateEventTypes.CLOSE,this._name,{socket:this,event:i}))}}_isStatsMessage(e){return!("stats-report"!==(null==e?void 0:e.type))}_isErrorMessage(e){return!("error"!==(null==e?void 0:e.type)||!(null==e?void 0:e.message)&&!(null==e?void 0:e.code))}_isStatusMessage(e){return!("status"!==(null==e?void 0:e.type))}_onDataChannelMessage(e){if(this.handleMessageResponse(e))return!0;const t=this.getJsonFromSocketMessage(e);return t?!!this._isStatsMessage(t)||(O(this._name,`[datachannel-response]: ${JSON.stringify(t,null,2)}`),this._handleMessageContent(t)):(H(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0)}_handleMessageContent(e){const{async:t,data:i,method:n,send:s,type:o,id:a}=e;if(this._isErrorMessage(i)){const e=(null==i?void 0:i.message)||(null==i?void 0:i.code);if(e)return this._responder.onDataChannelError(this._dataChannel,e),!0}if(n)return this._responder.onSendReceived(n,i),!0;if(s){const{senderName:t,dcLabel:i}=e,{data:n,method:o}=s,a={...n,senderName:t,dcLabel:i};return this._responder.onSendReceived(o,a),!0}return"metadata"===o&&i?(this._responder.onMetaData(i),!0):this._isStatusMessage(i)&&"NetConnection.Connect.Closed"===(null==i?void 0:i.code)?(this._responder.onConnectionClosed(),!0):!(!t||!a)&&this._handleAsyncResponse(a,e)}_handleAsyncResponse(e,t){const i=this._asyncTickets.find((t=>t.id===e));if(!i)return!1;const{promise:n}=i,{data:s}=t;if("error"===(null==s?void 0:s.type)){const e=s.message||s.code||"Unknown error";n.reject(new Error(e))}else n.resolve(s);return this._asyncTickets=this._asyncTickets.filter((t=>t.id!==e)),!0}async setUpWithPeerConfiguration(e,t){this.tearDown();(null==e?void 0:e.iceServers)&&e.iceServers.length>0||(e.iceServers=De);try{O(this._name,`[peerconnection:setUpWithPeerConfiguration]: ${JSON.stringify(e,null,2)}`);const i=new RTCPeerConnection(e);return t&&(this._dataChannel=i.createDataChannel(t.name,{ordered:!0}),this._addDataChannelHandlers(this._dataChannel)),this._addConnectionHandlers(i),this._peerConnection=i,i}catch(e){throw H(this._name,`Could not establish a PeerConnection. ${e.message}`),new Error(e.message)}}tearDown(){if(this._dataChannel){O(this._name,"[teardown:datachannel]"),this._removeDataChannelHandlers(this._dataChannel);try{this._dataChannel.close()}catch(e){H(this._name,`[datachannel.close] error: ${e.message}`)}finally{this._dataChannel=void 0}}if(this._peerConnection){O(this._name,"[teardown:peerconnection]"),this._removeConnectionHandlers(this._peerConnection);try{this._peerConnection.close()}catch(e){H(this._name,`[peerconnection.close] error: ${e.message}`)}finally{this._peerConnection=void 0}}}async setLocalDescription(e){var t;return O(this._name,"[setlocaldescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setLocalDescription(e)}async setRemoteDescription(e){var t;return O(this._name,"[setremotedescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setRemoteDescription(new RTCSessionDescription(e))}async addIceCandidate(e){var t;return O(this._name,"[addcandidate]"),null===(t=this._peerConnection)||void 0===t?void 0:t.addIceCandidate(e)}async waitToGatherIce(e=5e3){const t=this._peerConnection;return O(this._name,"[waittogatherice]"),new Promise((i=>{if("complete"===t.iceGatheringState)O(this._name,"[waittogatherice] ice gathering state complete."),t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{H(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}));else{O(this._name,"[waittogatherice] waiting...");const n=setTimeout((()=>{clearTimeout(n),t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{H(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}))}),e);t.onicegatheringstatechange=()=>{clearTimeout(n),O(this._name,"[waittogatherice] ice gathering state complete."),"complete"===t.iceGatheringState&&t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{H(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}))}}}))}post(e){if(this._dataChannel){const t="string"==typeof e?e:JSON.stringify(e,null,2);O(this._name,`[datachannel.send] message: ${t}`);try{return this._dataChannel.send(t),Promise.resolve(!0)}catch(e){k(this._name,e.message)}}return Promise.resolve(!1)}get connection(){return this._peerConnection}get dataChannel(){return this._dataChannel}}const He=[{label:"4K(UHD)",width:3840,height:2160},{label:"1080p(FHD)",width:1920,height:1080},{label:"UXGA",width:1600,height:1200},{label:"720p(HD)",width:1280,height:720},{label:"SVGA",width:800,height:600},{label:"VGA",width:640,height:480},{label:"360p(nHD)",width:640,height:360},{label:"CIF",width:352,height:288},{label:"QVGA",width:320,height:240},{label:"QCIF",width:176,height:144},{label:"QQVGA",width:160,height:120}],ke=e=>"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||e,Me=re(((e,t)=>{var i,n;if("boolean"==typeof e.video)return!0;const s=(null===(i=e.video)||void 0===i?void 0:i.width)?ke(e.video.width):0,o=(null===(n=e.video)||void 0===n?void 0:n.height)?ke(e.video.height):0,a=s===t.width&&o===t.height;return a&&O("[gum:isExact]",`Found matching resolution for ${t.width}, ${t.height}.`),a})),Ue=re(((e,t)=>{const i=le(Me(t))(e);return O("[gum:hasMatchingFormat]","Filtered list: "+JSON.stringify(i,null,2)),i.length>0})),Be=re(((e,t)=>{var i,n;if("boolean"==typeof e.video)return!0;const s=((null===(i=e.video)||void 0===i?void 0:i.width)?ke(e.video.width):0)*((null===(n=e.video)||void 0===n?void 0:n.height)?ke(e.video.height):0);return t.width*t.height<s})),Ve=re(((e,t)=>{const i=Be(t);return le(i)(e)})),Fe=async e=>{O("[gum:determineSupportedResolution]","Determine next neighbor based on constraints: "+JSON.stringify(e,null,2));const t=Ve(He)(e),i={...e};return await(async(e,t)=>{let i={...e};if(0==t.length)i.video;else{const n=t.shift();i={...e,video:{...e.video,width:{exact:n.width},height:{exact:n.height}}}}return{media:await ie.gUM(i),constraints:i}})(i,t)},$e=async e=>{let t;const i=Ue(He),n=async t=>{if(t){const e="string"==typeof t?t:[t.name,t.message].join(": ");O("[gum:getUserMedia]",`Failure in getUserMedia: ${e}. Attempting other resolution tests...`)}return await Fe(e)};if((e=>e.video&&"object"==typeof e.video&&(e.video.width||e.video.height))(e)){if(!i(e))return await n(void 0);{O("[gum:getUserMedia]","Found constraints in list. Checking quick support for faster setup with: "+JSON.stringify(e,null,2));const i=(e=>{var t,i;const n={...e};return"boolean"==typeof e.video||(n.video={...n.video},(null===(t=e.video)||void 0===t?void 0:t.width)&&(n.video.width={exact:ke(e.video.width)}),(null===(i=e.video)||void 0===i?void 0:i.height)&&(n.video.height={exact:ke(e.video.height)})),n})(e);try{return t=await ie.gUM(i),{media:t,constraints:i}}catch(e){return await n(e)}}}else try{return t=await ie.gUM(e),{media:t,constraints:e}}catch(e){return await n(e)}},Ge=(e,t,i)=>{const n="a=end-of-candidates",s=/^a=candidate:/,o=/^a=ice-ufrag:/,a=/^a=ice-pwd:/,r=/^m=(audio|video|application)\ /,l=e.split("\r\n");let h,d="",c="";const u=[];l.forEach((e=>{!h&&r.exec(e)?h=e:o.exec(e)?d=e:a.exec(e)?c=e:s.exec(e)&&(t&&-1!=e.indexOf(t)?u.push(e):t||u.push(e))})),i&&u[u.length-1]!==n&&u.push(n);return[d,c,h,"a=mid:0"].concat(u).join("\r\n")},xe="RTCPeerConnectionPublisher";class We extends Oe{constructor(e){super(e,xe)}_removeConnectionHandlers(e){e.onconnectionstatechange=null,e.oniceconnectionstatechange=null,e.onsignalingstatechange=null,e.onicecandidate=null,e.ontrack=null}_addConnectionHandlers(e){let t;e.onsignalingstatechange=()=>{const t=e.signalingState;O(xe,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(O(this._name,"[peerconnection:open]"),this._responder.onPeerConnectionOpen()):"failed"!==t&&"disconnected"!==t||(H(this._name,"[peerconnection:error]"),"failed"===t&&this._responder.onPeerConnectionFail())},e.oniceconnectionstatechange=i=>{const{iceConnectionState:n}=e;O(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionClose(i,pe.FAILED)):"disconnected"===n?t=setTimeout((()=>{O(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached. Closing PeerConnection."),clearTimeout(t),this._responder.onPeerConnectionClose(i,pe.GONE)}),3e3):t&&(O(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;O(this._name,`[peer.onicecandidate] - Peer Candidate: ${null==t?void 0:t.candidate}`),t&&this._responder.onIceCandidate(t)},e.ontrack=e=>{O(this._name,"[peer:ontrack]"),this._responder.onPeerConnectionTrackAdd(e.track)}}_onDataChannelMessage(e){const t=e;if(super._onDataChannelMessage(e))return!0;const i=this.getJsonFromSocketMessage(t);if(null===i)return H(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0;O(this._name,"[datachannel-response]: "+JSON.stringify(i,null,2));const{data:n}=i;return n&&"status"===n.type?"NetStream.Play.UnpublishNotify"===n.code?(this._responder.onUnpublish(),!0):"NetConnection.Publish.InsufficientBW"===n.code?(this._responder.onInsufficientBandwidth(n),!0):"NetConnection.Publish.SufficientBW"===n.code?(this._responder.onSufficientBandwidth(n),!0):"NetConnection.Publish.RecoveringBW"===n.code?(this._responder.onRecoveringBandwidth(n),!0):"Application.Statistics.Endpoint"===n.code?(this._responder.onStatisticsEndpointChange(n.statistics),!0):(O(xe,`[datachannel.message] status :: ${n.code}`),this._responder.onPublisherStatus(n),!0):(this._responder.onDataChannelMessage(this._dataChannel,t),!1)}addTrack(e){this._peerConnection?this._peerConnection.addTrack(e):H(xe,"PeerConnection not initialized. Cannot add track.")}async postUnpublish(e){const t=this.post({unpublish:e});return O(xe,`[peerconnection:unpublish] complete: ${t}`),t}async createOfferWithoutSetLocal(e=null){var t;O(xe,`[createoffer:withoutlocal]:: bandwidth request: ${JSON.stringify(e,null,2)}`);try{const i=await(null===(t=this._peerConnection)||void 0===t?void 0:t.createOffer());if(e){const t=((e,t)=>{const i=t.indexOf("m=audio");let n,s,o,a=t.indexOf("m=video"),r=t.indexOf("m=application");return i>-1&&e.audio&&(n=t.indexOf("\r\n",i),s=t.slice(0,n),o=t.slice(n+2,t.length),a=(t=[s,"b=AS:"+e.audio,o].join("\r\n")).indexOf("m=video"),r=t.indexOf("m=application")),a>-1&&e.video&&(n=t.indexOf("\r\n",a),s=t.slice(0,n),o=t.slice(n+2,t.length),r=(t=[s,"b=AS:"+e.video,o].join("\r\n")).indexOf("m=application")),r>-1&&e.dataChannel&&(n=t.indexOf("\r\n",r),s=t.slice(0,n),o=t.slice(n+2,t.length),t=[s,"b=AS:"+e.dataChannel,o].join("\r\n")),t})(e,i.sdp);i.sdp=t}return this._responder.onSDPSuccess(),i}catch(e){throw O(xe,"[createoffer:error]"),this._responder.onSDPError(e),e}}async updateBandwidthRequest(e=null){var t;O(xe,`[updatebandwidthrequest]:: bandwidth request: ${JSON.stringify(e,null,2)}`);try{const i=null===(t=this._peerConnection)||void 0===t?void 0:t.getSenders();if(e&&(null==i?void 0:i.length)&&i.length>0){const t=(e,t,i)=>new Promise(((n,s)=>{try{O(xe,`[updatebandwidthrequest:${i}]:: bandwidth(${t.encodings[0].maxBitrate})`),e.setParameters(t).then(n).catch(s)}catch(e){s(e)}})),n=[];null==i||i.forEach((async i=>{var s,o;if("video"===(null===(s=i.track)||void 0===s?void 0:s.kind)&&e.video){const e=i.getParameters();e.encodings||(e.encodings=[{}]),e.encodings[0].maxBitrate=75e4,e.encodings[0].maxFramerate=60,e.encodings[0].priority="high",n.push(t(i,e,"video"))}else if("audio"===(null===(o=i.track)||void 0===o?void 0:o.kind)&&e.audio){const e=i.getParameters();e.encodings||(e.encodings=[{}]),e.encodings[0].maxBitrate=128e3,n.push(t(i,e,"audio"))}})),await Promise.all(n).catch((e=>{k(xe,`[updatebandwidthrequest:error]:: ${e.message}`)}))}return!0}catch(e){k(xe,`[updatebandwidthrequest:error]:: ${e.message}`)}return!1}}class Ke extends Error{constructor(e){super(e),this.name="InvalidNameError"}}const je="WhipWhepSignalingHelper",ze=new Map;ze.set(400,"Invalid offer SDP."),ze.set(401,"Not authorized."),ze.set(404,"Scope resolver failed for the publish name and / or scope."),ze.set(405,"Remember to update the URL passed into the WHIP or WHEP client."),ze.set(406,"Scope connection rejected."),ze.set(409,"Session already initialized."),ze.set(412,"Invalid request body."),ze.set(417,"Session lookup or creation failure.");const Je=new Map;Je.set(400,"Offer already sent, double POST assumed."),Je.set(401,"Not authorized."),Je.set(404,"Scope resolver failed for the playback name and / or scope."),Je.set(406,"Playback failed due to an exception during creation."),Je.set(409,"Stream is not available to playback.");const Ye=["transcode"];var qe;!function(e){e.ICE_SERVER="ice-server",e.STATISTICS="statistics"}(qe||(qe={}));const Xe=e=>e&&(e=>{const t=/[?&](.*)=([^&#]*)/.exec(e);return t&&t.length>0})(e)?"&":"?",Qe=e=>e.split(";").map((e=>e.trim())).map((e=>"<"===e.charAt(0)?["url",e.substring(1,e.length-1)]:e.split("="))).reduce(((e,t)=>e.set(t[0].replaceAll('"',""),t[1].replaceAll('"',""))),new Map);class Ze{constructor(e,t=!1,i=!0,n=!1){O(je,`[whipwhep] ${e}`),this._url=e,this._origin=void 0,this._forceHost=i,this._reconnectEnabled=n,this._resource=void 0,this._enableSignalingChannel=t}async getOptions(e={}){let t=`${this._url}${Xe(this._url)}signal=${this._enableSignalingChannel}`;this._reconnectEnabled&&(t+=`&resilient=${this._reconnectEnabled}`),e&&Object.keys(e).forEach((i=>{t+=`&${i}=${e[i]}`})),O(je,`[whipwhep-options] ${t}`);try{const e=await fetch(t,{method:"OPTIONS",mode:"cors"}),{status:i,headers:n}=e;if(200===i||204===i){const e=/^(L|l)ink/,t=/^(S|s)ession-(H|h)ost/,i=[];let s;return n.forEach(((n,o)=>{if(t.exec(o)&&(this._origin=n),e.exec(o))if(n.indexOf(`rel="${qe.ICE_SERVER}"`)>-1){const e=Qe(n),t=e.get("url"),{protocol:s,host:o}=(e=>{const t=e.split(":");return t.length>1?{protocol:t[0],host:t[1]}:{protocol:void 0,host:e}})(t),a=e.get("username"),r=e.get("credential");s&&o&&a&&r?i.push({username:a,credential:r,urls:t}):t&&i.push({urls:t})}else if(n.indexOf(`rel="${qe.STATISTICS}"`)>-1){const e=Qe(n).get("url");e&&(s=e)}})),O(je,`[whipwhep-links]: ${JSON.stringify(i)}`),O(je,`[whipwhep-origin]: ${this._origin}`),{links:i.length>0?i:void 0,origin:this._origin,statisticsEndpoint:s}}throw new Error(`Failed to get options: ${i}`)}catch(e){throw k(je,e.message),e}}async postSDPOffer(e,t={},i=!0){let n=`${this._url}${Xe(this._url)}signal=${this._enableSignalingChannel}`;this._reconnectEnabled&&(n+=`&resilient=${this._reconnectEnabled}`),t&&Object.keys(t).forEach((e=>{-1===Ye.indexOf(e)&&(n+=`&${e}=${t[e]}`)})),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n+=`&host=${this._origin}`),O(je,`[whipwhep:post-offer] ${n}: `+JSON.stringify(e,null,2));try{const t={method:"POST",mode:"cors",headers:{"Content-Type":"application/sdp"}};e&&e.length>0&&(t.body=e);const s=await fetch(n,t),{status:o,headers:a}=s;if(a&&a.forEach(((e,t)=>{O(je,`[header] ${t}: ${e}`)})),o>=200&&o<300){const e=await s.text(),t=a.get("Location")||a.get("location");if(t){if(t.match(/^(http|https)/))this._resource=t;else{O(je,`[whipwhep-response] Location provided as relative path: ${t}`);const e=new URL(this._url);e.pathname=t.split("?")[0],this._resource=e.toString().replace(/\/endpoint\//,"/resource/")}return O(je,`[whipwhep-response] ${this._resource}: ${e}`),{sdp:e,location:this._resource}}return H(je,"Location not provided in header response to Offer."),this._resource=new URL(this._url).toString().replace(/\/endpoint\//,"/resource/"),{sdp:e,location:this._resource}}if(i&&ze.get(o)){if(O(je,ze.get(o)),404===o||409===o)throw new Ke(ze.get(o));throw new Error(ze.get(o))}if(!i&&Je.get(o)){if(O(je,Je.get(o)),404===o||409===o)throw new Ke(Je.get(o));throw new Error(Je.get(o))}{const e=await s.text();throw Error(e)}}catch(e){throw k(je,e.message),e}}async postSDPAnswer(e,t={}){O(je,`[whipwhep:post-answer] ${this._resource}: `+JSON.stringify(e,null,2));let i=this._resource,n=Xe(i);t&&Object.keys(t).forEach((e=>{-1===Ye.indexOf(e)&&(n=Xe(i),i+=`${n}${e}=${t[e]}`)})),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n=i.indexOf("?")>-1?"&":"?",i+=`${n}host=${this._origin}`);try{const t=await fetch(i,{method:"PATCH",mode:"cors",headers:{"Content-Type":"application/sdp"},body:e}),{status:n}=t;if(n>=200&&n<300)return{success:!0,code:n};if(Je.get(n))throw O(je,Je.get(n)),new Error(Je.get(n));{const e=await t.text();throw Error(e)}}catch(e){throw k(je,e.message),e}}async trickle(e,t={}){O(je,`[whipwhep-trickle] ${this._resource}: `+JSON.stringify(e,null,2));let i=this._resource,n=Xe(i);t&&Object.keys(t).forEach((e=>{-1===Ye.indexOf(e)&&(n=Xe(i),i+=`${n}${e}=${t[e]}`)})),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n=Xe(i),i+=`${n}host=${this._origin}`);try{const t=await fetch(i,{method:"PATCH",mode:"cors",headers:{"Content-Type":"application/trickle-ice-sdpfrag"},body:e}),{status:n}=t;if(n>=200&&n<300){const e=await t.text();return O(je,`[whipwhep-response] ${this._resource}: ${e}`),{candidate:e}}if(405===n)throw O(je,"Remember to update the URL passed into the WHIP or WHEP client"),new Error("Remember to update the URL passed into the WHIP or WHEP client");{const e=await t.text();throw Error(e)}}catch(e){throw k(je,e.message),e}}async tearDown(e={},t=!1){if(!this._resource)return;let i=this._resource,n=Xe(i);this._reconnectEnabled&&!t&&(n=Xe(i),i+=`${n}resilient=close`),e&&Object.keys(e).forEach((t=>{-1===Ye.indexOf(t)&&(n=Xe(i),i+=`${n}${t}=${e[t]}`)})),this._forceHost&&this._origin&&!(null==e?void 0:e.host)&&(n=Xe(i),i+=`${n}host=${this._origin}`),O(je,"[whipwhep-teardown]");try{await fetch(i,{method:"DELETE",mode:"cors"})}catch(e){if(k(je,e.message),!t)throw e}this._url=void 0,this._origin=void 0,this._resource=void 0,this._forceHost=!1,this._enableSignalingChannel=!1}async post(){return O(je,"[whipwhep:post] transport called."),Promise.resolve(!1)}async postAsync(){return O(je,"[whipwhep:postAsync] transport called."),Promise.resolve(null)}getUrl(){return this._url}}const et="R5ProPublishView";class tt{constructor(e="red5pro-publisher"){try{this._targetElement=ie.resolveElement(e)}catch(e){throw k(et,`Could not instantiate a new instance of PublishView. Reason: ${e.message}`),e}}preview(e){const t=this.isAutoplay;O(et,`[preview]: autoplay(${t})`),ie.setVideoSource(this._targetElement,e,t)}unpreview(){ie.setVideoSource(this._targetElement,null,this.isAutoplay)}get isAutoplay(){return ie.hasAttributeDefined(this._targetElement,"autoplay")}get view(){return this._targetElement}}var it,nt;!function(e){e.INBOUND="inbound-rtp",e.OUTBOUND="outbound-rtp",e.CODEC="codec",e.MEDIA_SOURCE="media-source",e.CANDIDATE_PAIR="candidate-pair",e.CERTIFICATE="certificate",e.DATA_CHANNEL="data-channel",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.PEER_CONNECTION="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport"}(it||(it={})),function(e){e.STALE_STATS="STALE_STATS",e.STATE_REGRESSION="STATE_REGRESSION",e.EXCESSIVE_RTT="EXCESSIVE_RTT",e.ICE_TIMEOUT="ICE_TIMEOUT"}(nt||(nt={}));class st{constructor(e,t,i,n){this._name="RTCStatsMonitor",this._queue=[],this._startTime=0,this._stopped=!1,this._interval=0,this._candidatePairHealth=new Map,this._name=e,this._renegotiationPolicy=n,this._config={...ge,...t},this._client=i,this._identifier={name:this._name,created:(new Date).getTime(),fingerprint:ie.getOrGenerateFingerprint(),device:ie.getBrowserDetails(),client:t}}_emptyStatsReportQueue(){for(var e;this._queue.length>0;){const t=this._queue.shift(),i=null===(e=this._client)||void 0===e?void 0:e.getMessageTransport();i?i.post(t):H(this._name,"Failed to post stats data to message transport. Message transport is not available.")}}_getStats(){const{_connection:e}=this;if(e)try{e.getStats(null).then((e=>{e.forEach((e=>{this._handleStatsReport(e)}))})).catch((e=>{k(this._name,`Failed to get stats report. ${e.message||e}`)}))}catch(e){k(this._name,`Failed to get stats report. ${e.message||e}`)}}_handleStatsReport(e){console.log(`[${this._name}]: ${JSON.stringify(e,null,2)}`)}_appendClientDetails(e){this._identifier.client={...this._identifier.client,...e}}async start(e){this._startTime=(new Date).getTime(),this._stopped=!1,this._connection=e,this.postAction("started"),this._getStats(),this._interval=setInterval((()=>{this._stopped||this._getStats()}),this._config.interval)}stop(){this._stopped=!0,clearInterval(this._interval),this.postAction("ended")}async post(t){const i={...this._identifier,type:"stats-report",timestamp:(new Date).getTime(),data:t},{endpoint:n,additionalHeaders:s}=this._config;if(n===e.StatsEndpointType.DEV_NULL)return;if(this._client&&this._client.onStatsReport&&(null===n||n===e.StatsEndpointType.EVENT_TRANSPORT))return void this._client.onStatsReport(this._connection,i);let o={"Content-Type":"application/json"};if(s&&(o={...o,...s}),n&&n.match(/^(http|https):\/\//))try{const e=await fetch(n,{method:"POST",headers:o,body:JSON.stringify(i)});e.status>=200&&e.status<300?O(this._name,`Posted stats data to endpoint: ${n}.`):k(this._name,`Failed to post stats data to endpoint: ${n}. ${e.status}`)}catch(e){k(this._name,`Failed to post stats data to endpoint: ${n}. ${e.message||e}`)}else if(this._client&&this._client.getMessageTransport()&&(void 0===n||n===e.StatsEndpointType.DATA_CHANNEL))try{let t=!1;const n=this._client.getMessageTransport();n&&(t=await n.post(i)),!t&&this._client&&(this._queue.push(i),this._client.on(e.MessageTransportStateEventTypes.CHANGE,(()=>{this._client&&this._client.off(e.MessageTransportStateEventTypes.CHANGE),this._emptyStatsReportQueue()})),H(this._name,"Failed to post stats data to message transport. Message transport is not available. Pushed to Queue."))}catch(e){k(this._name,`Failed to post stats data to message transport. ${e.message||e}`)}}async postAction(e,t=void 0){return this.post({action:{type:e,data:t,timestamp:(new Date).getTime()}})}async postEvent(e,t){return this.post({event:{type:e,data:t||void 0,timestamp:(new Date).getTime()}})}updateEndpoint(e,t=!0){const{endpoint:i}=this._config;t?this._config.endpoint=e:t||i||(this._confi