-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathred5pro-sdk.esm.min.js
More file actions
34 lines (33 loc) · 154 KB
/
Copy pathred5pro-sdk.esm.min.js
File metadata and controls
34 lines (33 loc) · 154 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
*
* red5pro-html-sdk - Red5 Pro HTML SDK
* Author: Infrared5 Inc.
* Version: 15.6.1
* 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.
*
*/
var e,t,i,n;!function(e){e.OPUS="OPUS",e.NONE="NONE"}(e||(e={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.AV1="AV1",e.NONE="NONE"}(t||(t={})),function(e){e[e.UNAVAILABLE=1e3]="UNAVAILABLE",e[e.AVAILABLE=0]="AVAILABLE",e[e.IDLE=1]="IDLE",e[e.PLAYING=2]="PLAYING",e[e.PAUSED=3]="PAUSED"}(i||(i={})),function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(n||(n={}));const s={[i.UNAVAILABLE]:n.UNAVAILABLE,[i.AVAILABLE]:n.AVAILABLE,[i.IDLE]:n.IDLE,[i.PLAYING]:n.PLAYING,[i.PAUSED]:n.PAUSED};var o,a,r,l;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(o||(o={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(a||(a={})),function(e){e.OPUS="OPUS"}(r||(r={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.AV1="AV1"}(l||(l={}));var d={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},h={};function c(e){return"string"==typeof e?d[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 m(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(d).forEach(function(e){h[d[e]]=e});var v={};function E(e,t){if(t){if(v[t])return;v[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}(),C=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 d=Object.keys(s.fields);for(r=0;r<d.length;r++)o[a=d[r]]=s.fields[a];var h=Object.keys(t);for(r=0;r<h.length;r++)o[a=h[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(m('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(m('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(m('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]=m('(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)}(m("%s\n%s",e,t.stack)),s),n=m("(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 b(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]):T.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=h[e],a.msg=n.length?m.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 v[e]}("src")||E("Unable to determine src line info","src"),a.src=l||""}return a.v=1,a}(n),this._emit(s))}}function f(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var i=e.cause();i&&(t+="\nCaused by: "+f(i))}return t}C.prototype.trace=b(10),C.prototype.debug=b(20),C.prototype.info=b(30),C.prototype.warn=b(40),C.prototype.error=b(50),C.prototype.fatal=b(60);var T={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:f(e),code:e.code,signal:e.signal}:e}};const y={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class w{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,y[e.level]||"UNKNOWN",e.msg)}}let A,N;const P=e=>(t,i)=>{var n;A&&"function"==typeof A[e]&&A[e]((n=t,e=>`(${n}) ${e}`)(i))},L={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},R=(e,t=!1,i)=>{const n=[{level:e,stream:new w,type:"raw"}];if(i){const t=i.map(t=>({...t,level:e}));n.push(...t)}t&&(N=[],n.push({level:e,stream:{write:t=>{const i=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==N||N.push(i)}},type:"raw"}));A=function(){return p(C,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:n})},I=()=>(A||R(L.INFO),A),O=()=>N||[];P(L.TRACE),P(L.INFO);const D=P(L.DEBUG),H=P(L.WARN),k=P(L.ERROR);P(L.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 z=e=>F.get(e),K=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=z(e);n&&o&&o.orientation&&o.orientation.forEach(e=>{e(n)}),s&&o&&o.streamingMode&&o.streamingMode.forEach(e=>{e(s)})}}})}))},j="BrowserEnvironment",J=e=>D(j,e),Y=e=>H(j,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=[]):(K(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=[]):(K(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:d}=e;if(i||s)return i||s;const h=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}/${d}.m3u8`}return`${c}://${h}:${u}/${p}/${d}.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,d=n.match(/^http/)?n:"ws"===n?"http":"https";return(null==s?void 0:s.enabled)?`${d}://${o}:${a}/as/${null!==(i=s.version)&&void 0!==i?i:"v1"}/proxy/${t}/${r}/${l}`:`${d}://${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 de,he,ce,ue,pe,_e;!function(e){e.UDP="udp",e.TCP="tcp"}(de||(de={})),function(e){e.ENCODED_FRAME="EncodedFrame",e.PACKET="Packet"}(he||(he={})),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={})),function(e){e.DEV_NULL="dev/null",e.DATA_CHANNEL="data-channel",e.EVENT_TRANSPORT="event-transport"}(_e||(_e={}));const ge={endpoint:_e.DATA_CHANNEL,interval:5e3,include:[]},me={...{protocol:"https",port:443,app:"live",streamMode:a.LIVE,keyFramerate:3e3,mediaElementId:"red5pro-publisher",rtcConfiguration:{iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:de.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},ve={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 Ce extends Se{constructor(e,t,i){super(e,i),this._publisher=t}get publisher(){return this._publisher}}class be extends Se{constructor(e,t,i){super(e,i),this._subscriber=t}get subscriber(){return this._subscriber}}class fe extends Se{constructor(e,t,i){super(e,i),this._name=t}get name(){return this._name}}class Te extends Se{constructor(e,t,i){super(e,i),this._pubnub=t}get pubnub(){return this._pubnub}}class ye extends Se{constructor(e,t,i){super(e,i),this._messageChannel=t}get messageChannel(){return this._messageChannel}}var we,Ae,Ne,Pe,Le,Re,Ie;!function(e){e.RECONNECT_START="Reconnect.Start",e.RECONNECT_FAILURE="Reconnect.Failure",e.RECONNECT_SUCCESS="Reconnect.Success",e.CONNECT_SUCCESS="Connect.Success",e.CONNECT_FAILURE="Connect.Failure",e.PUBLISH_START="Publish.Start",e.PUBLISH_FAIL="Publish.Fail",e.PUBLISH_INVALID_NAME="Publish.InvalidName",e.UNPUBLISH_SUCCESS="Unpublish.Success",e.PUBLISH_METADATA="Publish.Metadata",e.PUBLISH_STATUS="Publish.Status",e.PUBLISH_AVAILABLE="Publish.Available",e.PUBLISH_INSUFFICIENT_BANDWIDTH="Publish.InsufficientBW",e.PUBLISH_SUFFICIENT_BANDWIDTH="Publish.SufficientBW",e.PUBLISH_RECOVERING_BANDWIDTH="Publish.RecoveringBW",e.PUBLISH_SEND_INVOKE="Publish.Send.Invoke",e.CONNECTION_CLOSED="Publisher.Connection.Closed",e.DIMENSION_CHANGE="Publisher.Video.DimensionChange",e.STATISTICS_ENDPOINT_CHANGE="Publisher.StatisticsEndpoint.Change"}(we||(we={})),function(e){e.CONSTRAINTS_ACCEPTED="WebRTC.MediaConstraints.Accepted",e.CONSTRAINTS_REJECTED="WebRTC.MediaConstraints.Rejected",e.MEDIA_STREAM_AVAILABLE="WebRTC.MediaStream.Available",e.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",e.OFFER_START="WebRTC.Offer.Start",e.OFFER_END="WebRTC.Offer.End",e.CANDIDATE_CREATE="WebRTC.Candidate.Create",e.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",e.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",e.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",e.SOCKET_MESSAGE="WebRTC.Socket.Message",e.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",e.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",e.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",e.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",e.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",e.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",e.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",e.UNSUPPORTED_FEATURE="WebRTC.Unsupported.Feature",e.TRANSFORM_ERROR="WebRTC.Transform.Error",e.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",e.STATS_REPORT="WebRTC.Stats.Report"}(Ae||(Ae={})),function(e){e.RECONNECT_START="Reconnect.Start",e.RECONNECT_FAILURE="Reconnect.Failure",e.CONNECT_SUCCESS="Connect.Success",e.CONNECT_FAILURE="Connect.Failure",e.SUBSCRIBE_START="Subscribe.Start",e.SUBSCRIBE_STOP="Subscribe.Stop",e.SUBSCRIBE_FAIL="Subscribe.Fail",e.SUBSCRIBE_INVALID_NAME="Subscribe.InvalidName",e.SUBSCRIBE_METADATA="Subscribe.Metadata",e.SUBSCRIBE_STATUS="Subscribe.Status",e.SUBSCRIBE_SEND_INVOKE="Subscribe.Send.Invoke",e.SUBSCRIBE_PUBLISHER_CONGESTION="Subscribe.Publisher.NetworkCongestion",e.SUBSCRIBE_PUBLISHER_RECOVERY="Subscribe.Publisher.NetworkRecovery",e.PLAY_UNPUBLISH="Subscribe.Play.Unpublish",e.CONNECTION_CLOSED="Subscribe.Connection.Closed",e.ORIENTATION_CHANGE="Subscribe.Orientation.Change",e.STREAMING_MODE_CHANGE="Subscribe.StreamingMode.Change",e.VIDEO_DIMENSIONS_CHANGE="Subscribe.VideoDimensions.Change",e.LOADED_METADATA="Subscribe.LoadedMetadata",e.VOLUME_CHANGE="Subscribe.Volume.Change",e.SEEK_CHANGE="Subscribe.Seek.Change",e.PLAYBACK_TIME_UPDATE="Subscribe.Time.Update",e.PLAYBACK_STATE_CHANGE="Subscribe.Playback.Change",e.FULL_SCREEN_STATE_CHANGE="Subscribe.FullScreen.Change",e.AUTO_PLAYBACK_FAILURE="Subscribe.Autoplay.Failure",e.AUTO_PLAYBACK_MUTED="Subscribe.Autoplay.Muted",e.STATISTICS_ENDPOINT_CHANGE="Subscribe.StatisticsEndpoint.Change"}(Ne||(Ne={})),function(e){e.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",e.OFFER_START="WebRTC.Offer.Start",e.OFFER_END="WebRTC.Offer.End",e.ANSWER_START="WebRTC.Answer.Start",e.ANSWER_END="WebRTC.Answer.End",e.CANDIDATE_CREATE="WebRTC.Candidate.Create",e.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",e.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",e.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",e.SOCKET_MESSAGE="WebRTC.Socket.Message",e.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",e.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",e.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",e.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",e.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",e.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",e.ON_ADD_STREAM="WebRTC.Add.Stream",e.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",e.SUBSCRIBE_STREAM_SWITCH="WebRTC.Subscribe.StreamSwitch",e.TRANSFORM_ERROR="WebRTC.Transform.Error",e.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",e.STATS_REPORT="WebRTC.Stats.Report"}(Pe||(Pe={})),function(e){e.OPEN="MessageTransport.Open",e.CLOSE="MessageTransport.Close",e.CHANGE="MessageTransport.Change",e.ERROR="MessageTransport.Error"}(Le||(Le={})),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"}(Re||(Re={})),function(e){e.OPEN="MessageChannel.Open",e.SEND="MessageChannel.Send",e.RECEIVE="MessageChannel.Receive",e.CLOSE="MessageChannel.Close",e.FAIL="MessageChannel.Fail",e.ERROR="MessageChannel.Error"}(Ie||(Ie={}));const Oe=[{urls:"stun:stun2.l.google.com:19302"}],De={ordered:!0},He=e=>{const t=["id","negotiated","ordered","maxPacketLifeTime","maxRetransmits","protocol"];return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))};class ke 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(e){e.onerror=t=>{this._responder.onDataChannelError(e,t.error.message)},e.onmessage=e=>{this._onDataChannelMessage(e)},e.onopen=()=>{this._responder.onDataChannelOpen(e)},e.onclose=t=>{this._responder.onDataChannelClose(e),this.trigger(new fe(Le.CLOSE,this._name,{socket:this,event:t}))}}_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)||(D(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=Oe);try{D(this._name,`[peerconnection:setUpWithPeerConfiguration]: ${JSON.stringify(e,null,2)}`);const i=new RTCPeerConnection(e);if(t){const e=t.name||t.label||"red5pro",n={...De,...He(t)};this._dataChannel=i.createDataChannel(e,n),D(this._name,`[peerconnection:createDataChannel:${e}]: ${JSON.stringify(n,null,2)}`),this._addDataChannelHandlers(this._dataChannel)}return 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){D(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){D(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 D(this._name,"[setlocaldescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setLocalDescription(e)}async setRemoteDescription(e){var t;return D(this._name,"[setremotedescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setRemoteDescription(new RTCSessionDescription(e))}async addIceCandidate(e){var t;return D(this._name,"[addcandidate]"),null===(t=this._peerConnection)||void 0===t?void 0:t.addIceCandidate(e)}async waitToGatherIce(e=5e3){const t=this._peerConnection;return D(this._name,"[waittogatherice]"),new Promise(i=>{if("complete"===t.iceGatheringState)D(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{D(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),D(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);D(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 Me=[{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}],Ue=e=>"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||e,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)?Ue(e.video.width):0,o=(null===(n=e.video)||void 0===n?void 0:n.height)?Ue(e.video.height):0,a=s===t.width&&o===t.height;return a&&D("[gum:isExact]",`Found matching resolution for ${t.width}, ${t.height}.`),a}),Ve=re((e,t)=>{const i=le(Be(t))(e);return D("[gum:hasMatchingFormat]","Filtered list: "+JSON.stringify(i,null,2)),i.length>0}),Fe=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)?Ue(e.video.width):0)*((null===(n=e.video)||void 0===n?void 0:n.height)?Ue(e.video.height):0);return t.width*t.height<s}),$e=re((e,t)=>{const i=Fe(t);return le(i)(e)}),Ge=async e=>{D("[gum:determineSupportedResolution]","Determine next neighbor based on constraints: "+JSON.stringify(e,null,2));const t=$e(Me)(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)},xe=async e=>{let t;const i=Ve(Me),n=async t=>{if(t){const e="string"==typeof t?t:[t.name,t.message].join(": ");D("[gum:getUserMedia]",`Failure in getUserMedia: ${e}. Attempting other resolution tests...`)}return await Ge(e)};if((e=>e.video&&"object"==typeof e.video&&(e.video.width||e.video.height))(e)){if(!i(e))return await n(void 0);{D("[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:Ue(e.video.width)}),(null===(i=e.video)||void 0===i?void 0:i.height)&&(n.video.height={exact:Ue(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)}},We=(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 d,h="",c="";const u=[];l.forEach(e=>{!d&&r.exec(e)?d=e:o.exec(e)?h=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[h,c,d,"a=mid:0"].concat(u).join("\r\n")},ze="RTCPeerConnectionPublisher";class Ke extends ke{constructor(e){super(e,ze)}_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;D(ze,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(D(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;D(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionClose(i,pe.FAILED)):"disconnected"===n?t=setTimeout(()=>{D(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached. Closing PeerConnection."),clearTimeout(t),this._responder.onPeerConnectionClose(i,pe.GONE)},3e3):t&&(D(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;D(this._name,`[peer.onicecandidate] - Peer Candidate: ${null==t?void 0:t.candidate}`),t&&this._responder.onIceCandidate(t)},e.ontrack=e=>{D(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;D(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):(D(ze,`[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(ze,"PeerConnection not initialized. Cannot add track.")}async postUnpublish(e){const t=this.post({unpublish:e});return D(ze,`[peerconnection:unpublish] complete: ${t}`),t}async createOfferWithoutSetLocal(e=null){var t;D(ze,`[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 D(ze,"[createoffer:error]"),this._responder.onSDPError(e),e}}async updateBandwidthRequest(e=null){var t;D(ze,`[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{D(ze,`[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(ze,`[updatebandwidthrequest:error]:: ${e.message}`)})}return!0}catch(e){k(ze,`[updatebandwidthrequest:error]:: ${e.message}`)}return!1}async setOptimizationParams(e,t){var i;if(D(ze,`[setoptimizationparams]:: optimization params: ${JSON.stringify(t,null,2)}`),t.contentHint)try{e.getTracks().forEach(e=>{"contentHint"in e&&(e.contentHint=t.contentHint,D(ze,`[setoptimizationparams:contenthint]:: track: ${e.kind} contentHint: ${e.contentHint}`))})}catch(e){H(ze,`[setoptimizationparams:error]:: ${e.message}`)}if(t.degradationPreference)try{const e=null===(i=this._peerConnection)||void 0===i?void 0:i.getSenders();(null==e?void 0:e.length)&&e.length>0&&e.forEach(async e=>{var i,n;if("video"===(null===(i=e.track)||void 0===i?void 0:i.kind))try{let i=e.getParameters();i.degradationPreference=t.degradationPreference,await e.setParameters(i)}catch(e){H(ze,`[setoptimizationparams:error]:: ${e.message}`)}finally{let t=e.getParameters();D(ze,`[setoptimizationparams:degradationpreference]:: sender: ${null===(n=e.track)||void 0===n?void 0:n.kind} degradationPreference: ${null==t?void 0:t.degradationPreference}`)}})}catch(e){k(ze,`[setoptimizationparams:error]:: ${e.message}`)}}}class je extends Error{constructor(e){super(e),this.name="InvalidNameError"}}const Je="WhipWhepSignalingHelper",Ye=new Map;Ye.set(400,"Invalid offer SDP."),Ye.set(401,"Not authorized."),Ye.set(404,"Scope resolver failed for the publish name and / or scope."),Ye.set(405,"Remember to update the URL passed into the WHIP or WHEP client."),Ye.set(406,"Scope connection rejected."),Ye.set(409,"Session already initialized."),Ye.set(412,"Invalid request body."),Ye.set(417,"Session lookup or creation failure.");const qe=new Map;qe.set(400,"Offer already sent, double POST assumed."),qe.set(401,"Not authorized."),qe.set(404,"Scope resolver failed for the playback name and / or scope."),qe.set(406,"Playback failed due to an exception during creation."),qe.set(409,"Stream is not available to playback.");const Xe=["transcode"];var Qe;!function(e){e.ICE_SERVER="ice-server",e.STATISTICS="statistics"}(Qe||(Qe={}));const Ze=e=>e&&(e=>{const t=/[?&](.*)=([^&#]*)/.exec(e);return t&&t.length>0})(e)?"&":"?",et=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 tt{constructor(e,t=!1,i=!0,n=!1){D(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}${Ze(this._url)}signal=${this._enableSignalingChannel}`;this._reconnectEnabled&&(t+=`&resilient=${this._reconnectEnabled}`),e&&Object.keys(e).forEach(i=>{t+=`&${i}=${e[i]}`}),D(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=et(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=et(n).get("url");e&&(s=e)}}),D(Je,`[whipwhep-links]: ${JSON.stringify(i)}`),D(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}${Ze(this._url)}signal=${this._enableSignalingChannel}`;this._reconnectEnabled&&(n+=`&resilient=${this._reconnectEnabled}`),t&&Object.keys(t).forEach(e=>{-1===Xe.indexOf(e)&&(n+=`&${e}=${t[e]}`)}),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n+=`&host=${this._origin}`),D(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)=>{D(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{D(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 D(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&&Ye.get(o)){if(D(Je,Ye.get(o)),404===o||409===o)throw new je(Ye.get(o));throw new Error(Ye.get(o))}if(!i&&qe.get(o)){if(D(Je,qe.get(o)),404===o||409===o)throw new je(qe.get(o));throw new Error(qe.get(o))}{const e=await s.text();throw Error(e)}}catch(e){throw k(Je,e.message),e}}async postSDPAnswer(e,t={}){D(Je,`[whipwhep:post-answer] ${this._resource}: `+JSON.stringify(e,null,2));let i=this._resource,n=Ze(i);t&&Object.keys(t).forEach(e=>{-1===Xe.indexOf(e)&&(n=Ze(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(qe.get(n))throw D(Je,qe.get(n)),new Error(qe.get(n));{const e=await t.text();throw Error(e)}}catch(e){throw k(Je,e.message),e}}async trickle(e,t={}){D(Je,`[whipwhep-trickle] ${this._resource}: `+JSON.stringify(e,null,2));let i=this._resource,n=Ze(i);t&&Object.keys(t).forEach(e=>{-1===Xe.indexOf(e)&&(n=Ze(i),i+=`${n}${e}=${t[e]}`)}),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n=Ze(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 D(Je,`[whipwhep-response] ${this._resource}: ${e}`),{candidate:e}}if(405===n)throw D(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=Ze(i);this._reconnectEnabled&&!t&&(n=Ze(i),i+=`${n}resilient=close`),e&&Object.keys(e).forEach(t=>{-1===Xe.indexOf(t)&&(n=Ze(i),i+=`${n}${t}=${e[t]}`)}),this._forceHost&&this._origin&&!(null==e?void 0:e.host)&&(n=Ze(i),i+=`${n}host=${this._origin}`),D(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 D(Je,"[whipwhep:post] transport called."),Promise.resolve(!1)}async postAsync(){return D(Je,"[whipwhep:postAsync] transport called."),Promise.resolve(null)}getUrl(){return this._url}}const it="R5ProPublishView";class nt{constructor(e="red5pro-publisher"){try{this._targetElement=ie.resolveElement(e)}catch(e){throw k(it,`Could not instantiate a new instance of PublishView. Reason: ${e.message}`),e}}preview(e){const t=this.isAutoplay;D(it,`[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 st,ot;!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"}(st||(st={})),function(e){e.STALE_STATS="STALE_STATS",e.STATE_REGRESSION="STATE_REGRESSION",e.EXCESSIVE_RTT="EXCESSIVE_RTT",e.ICE_TIMEOUT="ICE_TIMEOUT"}(ot||(ot={}));class at{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){clearInterval(this._interval),this._startTime=(new Date).getTime(),this._stopped=!1,this._connection=e,this._candidatePairHealth.clear(),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(e){const t={...this._identifier,type:"stats-report",timestamp:(new Date).getTime(),data:e},{endpoint:i,additionalHeaders:n}=this._config;if(i===_e.DEV_NULL)return;if(this._client&&this._client.onStatsReport&&(null===i||i===_e.EVENT_TRANSPORT))return void this._client.onStatsReport(this._connection,t);let s={"Content-Type":"application/json"};if(n&&(s={...s,...n}),i&&i.match(/^(http|https):\/\//))try{const e=await fetch(i,{method:"POST",headers:s,body:JSON.stringify(t)});e.status>=200&&e.status<300?D(this._name,`Posted stats data to endpoint: ${i}.`):k(this._name,`Failed to post stats data to endpoint: ${i}. ${e.status}`)}catch(e){k(this._name,`Failed to post stats data to endpoint: ${i}. ${e.message||e}`)}else if(this._client&&this._client.getMessageTransport()&&(void 0===i||i===_e.DATA_CHANNEL))try{let e=!1;const i=this._client.getMessageTransport();i&&(e=await i.post(t)),!e&&this._client&&(this._queue.push(t),this._client.on(Le.CHANGE,()=>{this._client&&this._client.off(Le.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._config.endpoint=e)}_checkCandidatePairHealth(e){var t,i;const{id:n,state:s,currentRoundTripTime:o,totalRoundTripTime:a}=e,r=null===(t=this._client)||void 0===t?void 0:t.getPeerConnection();if(!r)return void this.stop();const{iceConnectionState:l}=r,d="connected"===l||"completed"===l,h=(new Date).getTime();if(d&&"succeeded"!==s)return;this._candidatePairHealth.has(n)||this._candidatePairHealth.set(n,{id:n,staleSampleCount:0,stateTransitionTime:h,inProgressStartTime:"in-progress"===s?h:void 0});const c=this._candidatePairHealth.get(n);if(void 0!==c.previousRTT&&void 0!==c.previousTotalRTT&&void 0!==o&&void 0!==a&&(o===c.previousRTT&&a===c.previousTotalRTT?(c.staleSampleCount++,c.staleSampleCount>=3&&c.lastIssueReported!==ot.STALE_STATS&&(this._client.emit(Re.CONNECTION_HEALTH_STALE_STATS,{candidatePairId:n,currentState:s,frozenRTT:o,frozenTotalRTT:a,staleDurationSeconds:c.staleSampleCount,message:"RTT values frozen - connection may be dead"}),c.lastIssueReported=ot.STALE_STATS)):(c.staleSampleCount=0,c.lastIssueReported===ot.STALE_STATS&&(c.lastIssueReported=void 0))),"succeeded"!==c.previousState||"succeeded"===s||d||(this._client.emit(Re.CONNECTION_HEALTH_STATE_REGRESSION,{candidatePairId:n,previousState:c.previousState,currentState:s,message:`ICE candidate pair regressed from '${c.previousState}' to '${s}' - connection lost`}),c.lastIssueReported=ot.STATE_REGRESSION,c.stateTransitionTime=h),void 0!==o&&o>.2){const e=o>1?"critical":o>.6?"severe":o>.35?"poor":"degrading";(c.lastIssueReported!==ot.EXCESSIVE_RTT||c.lastRttSeverity!==e)&&(this._client.emit(Re.CONNECTION_HEALTH_EXCESSIVE_RTT,{candidatePairId:n,currentRTT:o,severity:e,message:`Elevated RTT detected (${e}): ${(1e3*o).toFixed(0)}ms`}),c.lastIssueReported=ot.EXCESSIVE_RTT,c.lastRttSeverity=e)}else void 0!==o&&o<=.2&&(c.lastIssueReported===ot.EXCESSIVE_RTT&&(c.lastIssueReported=void 0),c.lastRttSeverity=void 0);if("in-progress"===s){c.inProgressStartTime||(c.inProgressStartTime=h);const e=h-c.inProgressStartTime;e>((null===(i=this._renegotiationPolicy)||void 0===i?void 0:i.iceTimeoutInterval)||5e3)&&c.lastIssueReported!==ot.ICE_TIMEOUT&&(this._client.emit(Re.CONNECTION_HEALTH_ICE_TIMEOUT,{candidatePairId:n,currentState:s,durationSeconds:Math.floor(e/1e3),message:`ICE negotiation timeout - candidate pair stuck in 'in-progress' for ${Math.floor(e/1e3)}s`}),c.lastIssueReported=ot.ICE_TIMEOUT)}else c.inProgressStartTime=void 0,c.lastIssueReported===ot.ICE_TIMEOUT&&(c.lastIssueReported=void 0);s!==c.previousState&&(c.stateTransitionTime=h),c.previousState=s,c.previousRTT=o,c.previousTotalRTT=a}dispose(){D(this._name,"[dispose]"),this.stop(),this._candidatePairHealth.clear(),this._connection=void 0,this._client=void 0}}const rt=/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b) \d+ typ srflx/,lt=e=>{const t=e.match(rt);return t&&t.length>1?t[1]:null},dt=[we.PUBLISH_START,we.PUBLISH_FAIL,we.PUBLISH_INSUFFICIENT_BANDWIDTH,we.PUBLISH_SUFFICIENT_BANDWIDTH,we.PUBLISH_RECOVERING_BANDWIDTH,we.STATISTICS_ENDPOINT_CHANGE];class ht extends at{constructor(e,t){if(super("RTCPublisherStats",e,t),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=e=>{const{type:t,data:i}=e;if(dt.indexOf(t)>-1){if(t===we.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=i;this.updateEndpoint(e,!1)}this.postEvent(t)}},this._candidateCreateHandler=({data:{candidate:e}})=>{const{candidate:t}=e,i=lt(t);i&&(this._identifier.publicIP=i)},this._hostEndpointChangedHandler=({data:{endpoint:e,iceServers:t}})=>{this._appendClientDetails({node:e,iceServers:t})},this._client.on("*",this._eventHandler),this._client.on(Ae.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(Ae.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const e=({data:t})=>{this._client.off(Ae.PEER_CONNECTION_AVAILABLE,e),this.start(t)};this._client.on(Ae.PEER_CONNECTION_AVAILABLE,e)}}_handleStatsReport(e){const{type:t}=e,{include:i}=this._config,n=i&&i.length>0;if(n&&i.indexOf(t)>=-1)this.post(e);else if(!n)if(t===st.CODEC){const{id:i,clockRate:n,mimeType:s,payloadType:o}=e;this.post({id:i,type:t,clockRate:n,mimeType:s,payloadType:o})}else if(t===st.CANDIDATE_PAIR){const{availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o}=e;this._checkCandidatePairHealth(e),this.post({type:t,availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o})}else if(t===st.MEDIA_SOURCE){const{kind:i}=e;if("audio"===i)this.post({type:t,kind:i});else if("video"===i){const{framesPerSecond:n,height:s,width:o}=e;this.post({type:t,kind:i,framesPerSecond:n,height:s,width:o})}}else if([st.OUTBOUND,"outboundrtp"].indexOf(t)>-1){const{timestamp:i,kind:n,codecId:s,mediaType:o,active:a,bytesSent:r,packetsSent:l,totalPacketsSendDelay:d,retransmittedPacketsSent:h}=e,c={type:t,kind:n,codecId:s,mediaType:o,active:a,bytesSent:r,packetsSent:l,totalPacketsSendDelay:d,retransmittedPacketsSent:h};if("audio"===n){if(this.lastAudioReport){const{bytesSent:e,timestamp:t}=this.lastAudioReport,n=8*(r-e)/(i-t);this.estimatedAudioBitrate=n}this.post({...c,estimatedBitrate:Math.floor(this.estimatedAudioBitrate)}),this.lastAudioReport=e}else if("video"===n){const{firCount:t,pliCount:n,nackCount:s,frameWidth:o,frameHeight:a,framesEncoded:l,framesPerSecond:d,framesSent:h,keyFramesEncoded:u,qualityLimitationReason:p,qualityLimitationDurations:_}=e,g={...c,firCount:t,pliCount:n,nackCount:s,frameWidth:o,frameHeight:a,framesEncoded:l,framesPerSecond:d,framesSent:h,keyFramesEncoded:u,qualityLimitationReason:"none"!==p?p:void 0,qualityLimitationDurations:"none"!==p?_:void 0};if(this.lastVideoReport){const{bytesSent:e,timestamp:t}=this.lastVideoReport,n=8*(r-e)/(i-t);this.estimatedVideoBitrate=n}this.post({...g,estimatedBitrate:Math.floor(this.estimatedVideoBitrate)}),this.lastVideoReport=e}}}dispose(){this._client.off("*",this._eventHandler),this._client.off(Ae.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(Ae.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),super.dispose()}}const ct={pubnub:window.PubNub,userId:`user-${Math.floor(65536*Math.random()).toString(16)}`,publishKey:void 0,subscribeKey:void 0,authToken:void 0,cloudEndpoint:void 0,backendUrl:void 0,backendURL:void 0,expiryMinutes:120,channelId:"red5",logLevel:"trace"};var ut;!function(e){e.CONNECTED="PubNub.Connected",e.DISCONNECTED="PubNub.Disconnected",e.SUBSCRIBE_SUCCESS="PubNub.Subscribe.Success",e.SUBSCRIBE_FAILURE="PubNub.Subscribe.Failure",e.UNSUBSCRIBE_SUCCESS="PubNub.Unsubscribe.Success",e.UNSUBSCRIBE_FAILURE="PubNub.Unsubscribe.Failure",e.MESSAGE_RECEIVED="PubNub.Message.Received",e.MESSAGE_SEND_SUCCESS="PubNub.Message.Send.Success",e.MESSAGE_SEND_FAILURE="PubNub.Message.Send.Failure",e.AUTH_TOKEN_GENERATED="PubNub.AuthToken.Generated",e.AUTH_TOKEN_GENERATION_ERROR="PubNub.AuthToken.Generation.Error",e.STATUS="PubNub.Status",e.ERROR="PubNub.Error"}(ut||(ut={}));const pt="PubNubService";class _t{constructor(){}_decodeToken(e){const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}async getAuthTokenFromBackendService(e){var t;const{userId:i,backendUrl:n,backendURL:s,channelId:o="red5",expiryMinutes:a=120}=e;if(!n&&!s)throw new Error("Backend URL is required. Please provide a backend URL in the pubnub configuration.");const r={userId:i,channelId:o,read:!0,write:!0,ttlMinutes:a};try{const e=await fetch(n||s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok)throw new Error("Failed to generate auth token. Please try again later.");const t=await e.json(),{token:i}=t;return i}catch(e){throw new Error(null!==(t=e.message)&&void 0!==t?t:"Failed to generate auth token. Please try again later.")}}async getAuthTokenFromCloud(e){var t;const{userId:i,cloudEndpoint:n,publishKey:s,subscribeKey:o,channelId:a="red5",expiryMinutes:r=120}=e;if(!n)throw new Error("Cloud endpoint is required. Please provide a cloud endpoint in the pubnub configuration.");try{const e=n.match(/^https?:\/\//)?n:`https://${n}`,t=await fetch(`${e}/config-meetings/api/generate-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:i,channelId:a,expirationMinutes:r})});if(!t.ok)throw new Error("Failed to generate auth token. Please try again later.");const d=await t.json(),{success:h,token:c}=d;if(!h)throw new Error("Failed to generate auth token. Please try again later.");const u=this._decodeToken(c);if(!u)throw new Error("Failed to decode auth token. Please try again later.");l=`[${pt}] :: Decoded auth token: ${JSON.stringify(u)}`,D(pt,l);const{uid:p,roomId:_,pubnubPublishKey:g,pubnubSubscribeKey:m,pubnubToken:v}=u;if(p!==i||_!==a)throw new Error("Invalid auth token. Please try again later.");if(g!==s||m!==o)throw new Error("Invalid auth token. Please try again later.");return v}catch(e){throw new Error(null!==(t=e.message)&&void 0!==t?t:"Failed to generate auth token. Please try again later.")}var l}}const gt="PubNubClient",mt={receivePresenceEvents:!0,withPresence:!1},vt=e=>D(gt,e),Et=e=>H(gt,e),St=e=>k(gt,e);class Ct extends U{constructor(){super(),this._subscriptions={}}async _getAuthFromCloud(e){const t=new _t;return await t.getAuthTokenFromCloud(e)}async _getAuthFromBackend(e){const t=new _t;return await t.getAuthTokenFromBackendService(e)}async init(e){var t,i,n,s,o,a,r,l;if(this._config={...ct,...e},(null===(t=this._config)||void 0===t?void 0:t.cloudEndpoint)||(null===(i=this._config)||void 0===i?void 0:i.backendUrl)||(null===(n=this._config)||void 0===n?void 0:n.backendURL)){let e;try{if((null===(s=this._config)||void 0===s?void 0:s.cloudEndpoint)?e=await this._getAuthFromCloud(this._config):((null===(o=this._config)||void 0===o?void 0:o.backendUrl)||(null===(a=this._config)||void 0===a?void 0:a.backendURL))&&(e=await this._getAuthFromBackend(this._config)),!e)throw new Error("Failed to get auth token.");this._config.authToken=e,this.trigger(new Te(ut.AUTH_TOKEN_GENERATED,this,{authToken:e}))}catch(e){return St(null!==(r=e.message)&&void 0!==r?r:"Failed to get auth token."),this.trigger(new Te(ut.AUTH_TOKEN_GENERATION_ERROR,this,{error:e.message})),this}}const{pubnub:d,publishKey:h,subscribeKey:c,authToken:u,userId:p,logLevel:_}=this._config;if(!d){const e="PubNub library is not initialized. Please provide a PubNub library reference in the configuration.";throw this.trigger(new Te(ut.ERROR,this,{error:e})),St(e),new Error(e)}return vt(`Initializing PubNub client with options: ${JSON.stringify({...this._config,...(null===(l=this._config)||void 0===l?void 0:l.authToken)?{authToken:"********"}:{}})}`),this._pubnub=new d({userId:p,publishKey:h,subscribeKey:c,logLevel:_}),this._pubnub.setToken(u),this._pubnub.addListener({message:e=>{var t;vt(`Message received on channel ${e.channel}: ${e.message}`),this.trigger(new Te(ut.MESSAGE_RECEIVED,this,{...e,userId:null===(t=this._config)||void 0===t?void 0:t.userId}))},presence:e=>{vt(`Presence event on channel ${e.channel}: ${JSON.stringify(e)}`)},status:e=>{const{category:t,operation:i}=e;if(vt(`Status event ${t}`),this.trigger(new Te(ut.STATUS,this,e)),"PNConnectedCategory"===t)this.trigger(new Te(ut.CONNECTED,this,e)),"PNSubscribeOperation"===i&&this.trigger(new Te(ut.SUBSCRIBE_SUCCESS,this,e));else if("PNDisconnectedCategory"===t)this.trigger(new Te(ut.DISCONNECTED,this,e));else if("PNReconnectedCategory"===t);else if("PNAcknowledgmentCategory"===t)"PNUnsubscribeOperation"===i&&this.trigger(new Te(ut.UNSUBSCRIBE_SUCCESS,this,e));else if("PNBadRequestCategory"===t)this.trigger(new Te(ut.ERROR,this,e));else if("PNAccessDeniedCategory"===t){this.trigger(new Te(ut.ERROR,this,e));const{message:t,payload:i}=e;if((null==i?void 0:i.channels)&&(null==i?void 0:i.channels.length)>0)for(const e of i.channels)St(`Failed to subscribe to channel ${e}: ${t}.`),this.trigger(new Te(ut.SUBSCRIBE_FAILURE,this,{channel:e}))}}}),this}async publishMessage(e,t){var i,n;if(!this._pubnub)return St("PubNub client not initialized."),!1;try{const n=await this._pubnub.publish({channel:e,message:t});this.trigger(new Te(ut.MESSAGE_SEND_SUCCESS,this,{...n,channel:e,message:t,userId:null===(i=this._config)||void 0===i?void 0:i.userId}))}catch(i){return St(null!==(n=i.message)&&void 0!==n?n:`Failed to publish message to channel ${e}.`),this.trigger(new Te(ut.MESSAGE_SEND_FAILURE,this,{channel:e,message:t})),!1}return!0}async subscribe(e,t){var i;if(!this._pubnub)return St("PubNub client not initialized."),!1;if(this._subscriptions[e])return!0;try{const i=this._pubnub.channel(e),n=await i.subscription({...mt,...t});if(!n)throw new Error(`Failed to subscribe to channel ${e}.`);n.subscribe(),this._subscriptions[e]=n}catch(t){return St(null!==(i=t.message)&&void 0!==i?i:`Failed to subscribe to channel ${e}.`),this.trigger(new Te(ut.SUBSCRIBE_FAILURE,this,{channel:e})),!1}return!0}async unsubscribe(e){var t;if(!this._pubnub)return!0;if(!this._subscriptions[e])return Et(`Subscription ${e} not found.`),!1;try{await this._subscriptions[e].unsubscribe()}catch(i){St(null!==(t=i.message)&&void 0!==t?t:`Failed to unsubscribe from channel ${e}.`),this.trigger(new Te(ut.UNSUBSCRIBE_FAILURE,this,{channel:e}))}return delete this._subscriptions[e],!0}async destroy(){var e;if(this._pubnub)try{await this._pubnub.destroy()}catch(t){Et(null!==(e=t.message)&&void 0!==e?e:"Failed to destroy PubNub client.")}return this._subscriptions={},this._pubnub=void 0,this._config=void 0,!0}getOptions(){var e;return null!==(e=this._config)&&void 0!==e?e:{}}get config(){return this._config}get pubnub(){return this._pubnub}}const bt="WHIPClient",ft=me,Tt=e=>D(bt,e),yt=e=>k(bt,e),wt=e=>H(bt,e);class At extends U{constructor(e,t,i){super(),this._reconnectAttempts=0,this._reconnectTimeout=null;const n=e?se(e):ft,s=i||ft,o={...s,...n,endpoint:e,mediaElementId:t?t.id:s.mediaElementId};e&&this.internalInit(o),this._onOrientationChange=this._onOrientationChange.bind(this)}async internalInit(e){await this.init(e),await this.publish()}async generateMediaStream(e){var t,i;const{onGetUserMedia:n}=e;if(n){Tt("Requesting gUM from user-defined configuration:onGetUserMedia.");const e=await n();return this.trigger(new Ce(Ae.CONSTRAINTS_ACCEPTED,this,ae(e))),e}{const{mediaConstraints:n}=e;let s;Tt(`Requesting gUM using mediaConstraints: ${JSON.stringify(n,null,2)}`);let o=n;const a=await xe(o);return a&&a.media||(s=await ie.gUM(o)),s=null!==(t=null==a?void 0:a.media)&&void 0!==t?t:s,o=null!==(i=null==a?void 0:a.constraints)&&void 0!==i?i:n,Tt(`Constraints accepted: ${JSON.stringify(o,null,2)}`),this.trigger(new Ce(Ae.CONSTRAINTS_ACCEPTED,this,{constraints:o,...ae(s)})),s}}async getAndPreviewStreamIfAvailable(){var e;let t=this._mediaStream;if(!t){try{t=null!=t?t:await this.generateMediaStream(this._options)}catch(t){const i=null!==(e=t.message)&&void 0!==e?e:"Could not generate media stream.";throw this.trigger(new Ce(Ae.CONSTRAINTS_REJECTED,this,{constraints:this._options.mediaConstraints})),new Error(i)}if(!t)throw new Error("Could not generate media stream.")}return this.trigger(new Ce(Ae.MEDIA_STREAM_AVAILABLE,this,t)),this.preview(t),t}establishStatsMonitor(e){return new ht(e,{onStatsReport:this._onStatsReport.bind(this),getPeerConnection:this.getPeerConnection.bind(this),getMessageTransport:this.getMessageTransport.bind(this),on:this.on.bind(this),off:this.off.bind(this),trigger:this.trigger.bind(this),emit:this.emit.bind(this)})}postStatsMonitorEvent(e,t){this._statsMonitor&&this._statsMonitor.postEvent(e,t)}reorderCodecPreferences(e,t,i){e.getTransceivers().forEach(e=>{if(e.sender&&e.sender.track){const{kind:n}=e.sender.track;if(t&&"video"===n&&e.setCodecPreferences)try{const{codecs:i}=RTCRtpSender.getCapabilities("video"),n=i.findIndex(e=>e.mimeType===`video/${t}`);if(n>-1){const t=i.slice(0),s=i[n];t.splice(n,1),t.unshift(s),e.setCodecPreferences(t)}}catch(e){wt(`[videoEncoding] Could not set codec preferences for ${t}. ${e.message||e}`)}else if(i&&"audio"===n&&e.setCodecPreferences)try{const{codecs:t}=RTCRtpSender.getCapabilities("audio"),n=t.findIndex(e=>e.mimeType===`audio/${i}`);if(n>-1){const i=t[n];t.splice(n,1),t.unshift(i),e.setCodecPreferences(t)}}catch(e){wt(`[audioEncoding] Could not set codec preferences for ${i}. ${e.message||e}`)}}})}async postOffer(e){var t;try{const{sdp:i}=e;let{videoEncoding:n}=this._options;const{mungeOffer:s,streamMode:o,keyFramerate:a,iceTransport:r,connectionParams:d,mediaConstraints:h,forceVP8:c,audioEncoding:u,offerSDPResolution:p}=this._options;c&&!n&&(n=l.VP8);let _=i;s&&(Tt(`[MUNGE:before] offer: ${_}`),_=s(_),Tt(`[MUNGE:after] offer: ${_}`)),p&&(Tt(`[MUNGE] Setting resolution on offer: ${_}`),_=((e,t)=>{if(!t)return e;const{width:i,height:n}=t;if(!i||!n)return e;const s=`a=framesize:${i}-${n}`,o=e.split("\r\n");let a=o.length;const r=/^m=video/;for(;--a>-1;)if(r.exec(o[a])){for(;++a<o.length;)if(o[a].indexOf("a=mid")>-1){o.splice(a+1,0,s);break}break}return o.join("\r\n")})(_,((e,t)=>{let i;if(e)try{const t=e.getVideoTracks()&&e.getVideoTracks()[0];if(t){const e=t.getSettings();i={width:e.width,height:e.height}}}catch(e){H("[determineMediaResolution]",`Could not determine resolution from MediaStream. ${e.message||e}`)}if(!i)try{const e=t.video,{width:n,height:s}=e;if(n&&s)if("number"==typeof n&&"number"==typeof s)i={width:n,height:s};else{i={width:n.exact||n.min||n.max||n.ideal||640,height:s.exact||s.min||s.max||s.ideal||480}}}catch(e){H("[determineMediaResolution]",`Could not determine resolution from MediaConstraints. ${e.message||e}`)}return i&&D("[determineMediaResolution]",`constraints: ${JSON.stringify(i,null,2)}`),i})(this._mediaStream,h)),Tt(`[MUNGE:after] offer: ${_}`));const g={...d,mode:o,transport:r,keyFramerate:a};return n&&(g.videoEncoding=n),u&&(g.audioEncoding=u),await(null===(t=this._whipWhepService)||void 0===t?void 0:t.postSDPOffer(_,g))}catch(e){throw yt(e.message||e),e instanceof je&&this.trigger(new Ce(we.PUBLISH_INVALID_NAME,this)),e}}async postCandidateFragments(e){var t;const{connectionParams:i}=this._options,n=We(e,void 0,!0);return await(null===(t=this._whipWhepService)||void 0===t?void 0:t.trickle(n,i))}async initPubNub(e){var t;try{const t=new Ct;this._pubnubClient=t,this._pubnubClient.on("*",e=>{this.trigger(e)}),await t.init(e)}catch(e){return e(null!==(t=e.message)&&void 0!==t?t:"Failed to initialize PubNub."),!1}return!0}async deinitPubNub(){var e,t;try{await(null===(e=this._pubnubClient)||void 0===e?void 0:e.destroy()),this._pubnubClient=void 0}catch(e){return e(null!==(t=e.message)&&void 0!==t?t:"Failed to deinitialize PubNub."),!1}return!0}async init(e){var t,i,n,s;this._options={...ft,...e};const o=oe(this._options),{includeDataChannel:a,disableProxy:r,reconnect:l}=this._options;return l&&(this._options.reconnect={...ve,...l}),this._whipWhepService=new tt(o,a,r,null!==(i=null===(t=this._options.reconnect)||void 0===t?void 0:t.enabled)&&void 0!==i&&i),this._messageTransport=this._whipWhepService,(null===(n=this._options)||void 0===n?void 0:n.stats)&&this.monitorStats(this._options.stats),this._mediaStream=await this.getAndPreviewStreamIfAvailable(),(null===(s=this._options)||void 0===s?void 0:s.pubnub)&&await this.initPubNub(this._options.pubnub),this}async initWithStream(e,t){return this._mediaStream=t,this.init(e)}async publish(e){var t,i,n,s,o,a,r;e&&(this._options.streamName=e);const{forceVP8:d,audioEncoding:h,rtcConfiguration:c,dataChannelConfiguration:u,includeDataChannel:p,signalingSocketOnly:_,enableChannelSignaling:g,connectionParams:m,bandwidth:v,mungeAnswer:E}=this._options;let{videoEncoding:S}=this._options;d&&(S=l.VP8,this._options.videoEncoding=S),this._mediaStream||(this._mediaStream=await this.getAndPreviewStreamIfAvailable());try{const e=null!=m?m:{};if(m){const{transcode:t}=m;t&&(e.transcode=t)}const r=await(null===(t=this._whipWhepService)||void 0===t?void 0:t.getOptions(e)),l=!!(null===(i=this._options)||void 0===i?void 0:i.rtcConfiguration)&&Array.isArray(this._options.rtcConfiguration.iceServers)&&this._options.rtcConfiguration.iceServers.length>0;(null==r?void 0:r.links)&&!l&&(this._options.rtcConfiguration={...c,iceServers:r.links}),(null==r?void 0:r.origin)&&this.trigger(new Ce(Ae.HOST_ENDPOINT_CHANGED,this,{endpoint:r.origin})),(null==r?void 0:r.statisticsEndpoint)&&this._onStatisticsEndpointChange(r.statisticsEndpoint);const d=p||g||_?u:void 0;this._peerConnectionHelper=new Ke({onDataChannelError:this._onDataChannelError.bind(this),onSendReceived:this._onSendReceived.bind(this),onMetaData:this._onMetaData.bind(this),onConnectionClosed:this._onConnectionClosed.bind(this),onDataChannelOpen:this._onDataChannelOpen.bind(this),onDataChannelClose:this._onDataChannelClose.bind(this),onDataChannelMessage:this._onDataChannelMessage.bind(this),onPeerConnectionOpen:this._onPeerConnectionOpen.bind(this),onPeerConnectionFail:this._onPeerConnectionFail.bind(this),onPeerConnectionClose:this._onPeerConnectionClose.bind(this),onIceCandidate:this._onIceCandidate.bind(this),onSDPSuccess:this._onSDPSuccess.bind(this),onSDPError:this._onSDPError.bind(this),onStatisticsEndpointChange:this._onStatisticsEndpointChange.bind(this),onPublisherStatus:this._onPublisherStatus.bind(this),onPeerConnectionTrackAdd:this._onPeerConnectionTrackAdd.bind(this),onInsufficientBandwidth:this._onInsufficientBandwidth.bind(this),onSufficientBandwidth:this._onSufficientBandwidth.bind(this),onRecoveringBandwidth:this._onRecoveringBandwidth.bind(this),onUnpublish:this._onUnpublish.bind(this)}),await this._peerConnectionHelper.setUpWithPeerConfiguration(this._options.rtcConfiguration,d),this.trigger(new Ce(Ae.PEER_CONNECTION_AVAILABLE,this,this.getPeerConnection())),this._mediaStream&&this._mediaStream.getTracks().forEach(e=>{var t;null===(t=this.getPeerConnection())||void 0===t||t.addTransceiver(e,{direction:"sendonly"})}),this.reorderCodecPreferences(this.getPeerConnection(),S,h);const C=await(null===(n=this._peerConnectionHelper)||void 0===n?void 0:n.createOfferWithoutSetLocal(v));await this._peerConnectionHelper.setLocalDescription(C),this.trigger(new Ce(Ae.OFFER_START,this,C));const{sdp:b}=await this.postOffer(C);let f=b;if(E&&(Tt(`[MUNGE:before] answer: ${f}`),f=E(f),Tt(`[MUNGE:after] answer: ${f}`)),!this._peerConnectionHelper)throw new Error("SDP Exchange interrupted. Peer Connection Helper not available.");if(await(null===(s=this._peerConnectionHelper)||void 0===s?void 0:s.setRemoteDescription({type:"answer",sdp:f})),this.trigger(new Ce(Ae.OFFER_END,this,f)),!this._peerConnectionHelper)throw new Error("SDP Exchange interrupted. Peer Connection Helper not available.");const T=await(null===(o=this._peerConnectionHelper)||void 0===o?void 0:o.waitToGatherIce()),{sdp:y}=T;return await this.postCandidateFragments(y),this.trigger(new Ce(Ae.ICE_TRICKLE_COMPLETE,this)),ie.addOrientationChangeHandler(this._onOrientationChange),(null===(a=this._options)||void 0===a?void 0:a.includeDataChannel)||this.trigger(new Ce(we.PUBLISH_START,this)),this}catch(e){throw yt(null!==(r=e.message)&&void 0!==r?r:"Could not publish."),this.trigger(new Ce(we.CONNECT_FAILURE,this,e)),this.unpublish(!0),e}}async unpublish(e=!1,t=!1){var i;Tt("[unpublish]"),this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),t||(this._reconnectAttempts=0,this._reconnectTimeout=null),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,e),this._pubnubClient&&await this.deinitPubNub(),this._pubnubClient=void 0,(null===(i=this._options)||void 0===i?void 0:i.clearMediaOnUnpublish)&&!t&&this.unpreview(),t||(this._mediaStream=void 0),this.unmonitorStats(),this._peerConnectionHelper=void 0,this._whipWhepService=void 0,this._messageTransport=void 0,this._publishView=void 0,t||this.trigger(new Ce(we.UNPUBLISH_SUCCESS,this)),ie.removeOrientationChangeHandler(this._onOrientationChange)}async attemptReconnect(e){var t;if(Tt("[attemptReconnect]"),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),!e)return void yt("Reconnect configuration not provided.");const{enabled:i,timeout:n,maxAttempts:s}=e;if(i){if(this._reconnectAttempts>=s)return yt("Reconnect attempts exceeded maximum attempts."),void this.trigger(new Ce(we.RECONNECT_FAILURE,this,{error:"Reconnect attempts exceeded maximum attempts."}));try{await this.unpublish(!0,!0)}catch(e){yt(null!==(t=e.message)&&void 0!==t?t:"Could not unpublish for reconnect.")}return this._reconnectAttempts++,this._reconnectTimeout=setTimeout(()=>{this.reconnect(e)},n),this}yt("Reconnect is not enabled.")}async reconnect(e){var t,i;Tt("[reconnect]"),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this.trigger(new Ce(we.RECONNECT_START,this));try{await this.init(this._options),await this.publish(),this.trigger(new Ce(we.RECONNECT_SUCCESS,this)),this._reconnectAttempts=0,this._reconnectTimeout=null}catch(n){yt(null!==(t=n.message)&&void 0!==t?t:"Could not reconnect."),this.trigger(new Ce(we.RECONNECT_FAILURE,this,{error:null!==(i=n.message)&&void 0!==i?i:"Could not reconnect."})),this.attemptReconnect(e)}return this}preview(e){const{mediaElementId:t}=this._options;t&&(Tt("[preview]"),this._publishView=new nt(t),this._publishView.preview(e))}unpreview(){this._mediaStream&&this._mediaStream.getTracks().forEach(e=>{e.stop()}),this._publishView&&(Tt("[unpreview]"),this._publishView.unpreview()),this._publishView=void 0}monitorStats(e){Tt("[monitorStats]");const{host:t,endpoint:i,app:n,streamName:s,connectionParams:o}=this._options,a=null!=e?e:ge;return this._statisticsConfiguration={...a,host:t,hostEndpoint:i,app:n,streamName:s,connectionParams:o},this._statsMonitor?wt("Cannot monitor stats without a Peer Connection. Please call `init` before calling `monitorStats`."):this._statsMonitor=this.establishStatsMonitor(this._statisticsConfiguration),this}unmonitorStats(){return this._statsMonitor&&this._statsMonitor.dispose(),this._statsMonitor=void 0,this._statisticsConfiguration=void 0,this}muteAudio(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteAudio:!0}})}unmuteAudio(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteAudio:!1}})}muteVideo(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteVideo:!0}})}unmuteVideo(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteVideo:!1}})}updateOptimizationParams(e){var t,i;this._options.optimizationParams=e,this._mediaStream&&(null===(t=this._options)||void 0===t?void 0:t.optimizationParams)&&(null===(i=this._peerConnectionHelper)||void 0===i||i.setOptimizationParams(this._mediaStream,e))}async send(e,t){var i;let n=t;try{n="string"==typeof t?JSON.parse(t):t}catch(e){wt(`Could not parse data as JSON. Sending as message. Error: ${e.message||e}`),n={message:t}}return null===(i=this.getMessageTransport())||void 0===i?void 0:i.post({send:{method:e,data:n}})}async sendPubNub(e,t){return this._pubnubClient?await this._pubnubClient.publishMessage(e,t):(yt("PubNub client not initialized."),!1)}async subscribePubNub(e,t){return this._pubnubClient?await this._pubnubClient.subscribe(e,t):(yt("PubNub client not initialized."),!1)}async unsubscribePubNub(e){return this._pubnubClient?await this._pubnubClient.unsubscribe(e):(yt("PubNub client not initialized."),!1)}async callServer(e,t){var i;try{if(!this.getMessageTransport())throw new Error("Message transport not available");return null===(i=this.getMessageTransport())||void 0===i?void 0:i.postAsync({callAdapter:{method:e,arguments:t}})}catch(e){yt(e.message||e)}}sendLog(e,t){var i;try{const n=Object.keys(L).find(t=>t.toLowerCase()===e.toLowerCase())?e:L.DEBUG,s="string"==typeof t?t:JSON.stringify(t);null===(i=this.getMessageTransport())||void 0===i||i.post({log:n.toUpperCase(),message:s})}catch(e){const t=e.message||e;yt("Could not send log to server. Message parameter expected to be String or JSON-serializable object."),yt(t)}}get options(){return this._options}getOptions(){return this._options}getPeerConnection(){var e;return null===(e=this._peerConnectionHelper)||void 0===e?void 0:e.connection}getDataChannel(){var e;return null===(e=this._peerConnectionHelper)||void 0===e?void 0:e.dataChannel}getMediaStream(){return this._mediaStream}getMessageTransport(){return this._messageTransport}getPubNubClient(){return this._pubnubClient}_onDataChannelError(e,t){yt(`Data channel error: ${t}`),this.trigger(new Ce(Ae.DATA_CHANNEL_ERROR,this,{dataChannel:e,error:t}))}_onSendReceived(e,t){Tt(`Send received: ${e} ${JSON.stringify(t)}`),"onMetaData"===e?this._onMetaData(t):this.trigger(new Ce(we.PUBLISH_SEND_INVOKE,this,{methodName:e,data:t}))}_onMetaData(e){Tt(`Metadata received: ${JSON.stringify(e)}`),this.trigger(new Ce(we.PUBLISH_METADATA,this,e))}_onConnectionClosed(){Tt("Connection closed"),this.unpublish(),this.trigger(new Ce(we.CONNECTION_CLOSED,this))}_onDataChannelOpen(e){Tt(`Data channel opened: ${e.label}`),this.trigger(new Ce(Ae.DATA_CHANNEL_OPEN,this,{dataChannel:e})),this.trigger(new Ce(Ae.DATA_CHANNEL_AVAILABLE,this,{name:e.label,dataChannel:e})),this._messageTransport=this._peerConnectionHelper,this.trigger(new fe(Le.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new Ce(we.PUBLISH_START,this))}_onDataChannelClose(e){Tt(`Data channel closed: ${e.label}`),this.trigger(new Ce(Ae.DATA_CHANNEL_CLOSE,this,{dataChannel:e}))}_onDataChannelMessage(e,t){Tt(`Data channel message: ${t.data}`),this.trigger(new Ce(Ae.DATA_CHANNEL_MESSAGE,this,{dataChannel:e,message:t}))}_onPeerConnectionTrackAdd(e){Tt(`Peer connection track added: ${e.id}`),this.trigger(new Ce(Ae.TRACK_ADDED,this,{track:e}))}_onPeerConnectionOpen(){Tt("Peer connection opened"),this.trigger(new Ce(Ae.PEER_CONNECTION_OPEN,this,this.getPeerConnection()))}_onPeerConnectionFail(){yt("Peer connection failed"),this.trigger(new Ce(we.PUBLISH_FAIL,this))}_onPeerConnectionClose(e,t){var i,n,s;Tt(`Peer connection closed: ${e.type}`),this._peerConnectionHelper&&this._peerConnectionHelper.tearDown(),this.trigger(new Ce(we.CONNECTION_CLOSED,this,e)),!t||t!==pe.GONE&&t!==pe.FAILED||(null===(n=null===(i=this._options)||void 0===i?void 0:i.reconnect)||void 0===n?void 0:n.enabled)&&this.attemptReconnect(null===(s=this._options)||void 0===s?void 0:s.reconnect)}_onIceCandidate(e){Tt(`ICE candidate: ${JSON.stringify(e,null,2)}`),this.trigger(new Ce(Ae.CANDIDATE_CREATE,this,{candidate:e}))}_onUnpublish(){Tt("Unpublish received")}_onPublisherStatus(e){var t,i,n;Tt("[publisherstatus] - "+JSON.stringify(e,null,2)),e.code&&"NetStream.Publish.IsAvailable"===e.code?this.trigger(new Ce(we.PUBLISH_AVAILABLE,this,e)):(e.code&&"NetStream.Publish.Start"===e.code&&this._mediaStream&&(null===(t=this._options)||void 0===t?void 0:t.optimizationParams)&&(null===(i=this._peerConnectionHelper)||void 0===i||i.setOptimizationParams(this._mediaStream,null===(n=this._options)||void 0===n?void 0:n.optimizationParams)),this.trigger(new Ce(we.PUBLISH_STATUS,this,e)))}_onInsufficientBandwidth(e){this.trigger(new Ce(we.PUBLISH_INSUFFICIENT_BANDWIDTH,this,e))}_onSufficientBandwidth(e){this.trigger(new Ce(we.PUBLISH_SUFFICIENT_BANDWIDTH,this,e))}_onRecoveringBandwidth(e){this.trigger(new Ce(we.PUBLISH_RECOVERING_BANDWIDTH,this,e))}_onSDPSuccess(e=void 0){const t=e?": "+JSON.stringify(e,null,2):"";Tt(`[onsdpsuccess]:: ${t}`)}_onSDPError(e=void 0){this.trigger(new Ce(we.PUBLISH_FAIL,this));const t=e?": "+JSON.stringify(e,null,2):"";yt(`[onsdperror]:: ${t}`)}_onOrientationChange(e){const t=this.getMessageTransport();t&&t.post({send:{method:"onMetaData",data:{deviceOrientation:e}}})}_onStatisticsEndpointChange(e){Tt(`Statistics endpoint changed: ${e}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(e),this.trigger(new Ce(we.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:e}))}_onStatsReport(e,t){this.trigger(new Ce(Ae.STATS_REPORT,this,{connection:e,report:t}))}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}trigger(e){super.trigger(e)}emit(e,t){this.trigger(new Ce(e,this,t))}getType(){return"RTC"}}const Nt={...{protocol:"https",port:443,app:"live",autoLayoutOrientation:!0,mediaElementId:"red5pro-subscriber",rtcConfiguration:{iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:de.UDP,muteOnAutoplayRestriction:!0,maintainConnectionOnSubscribeErrors:!1,dataChannelConfiguration:{name:"red5pro"},signalingSocketOnly:!1,includeDataChannel:!0,maintainStreamVariant:!1,buffer:0,stats:ge,pubnub:void 0,renegotiationPolicy:void 0},signalingSocketOnly:!1,enableChannelSignaling:!1,includeDataChannel:!0,disableProxy:!0,trickleIce:!0,postEmptyOffer:!1,mungeOffer:void 0,mungeAnswer:void 0},Pt={protocol:"https",port:443,app:"live",mediaElementId:"red5pro-subscriber",muteOnAutoplayRestriction:!0},Lt={endpoint:_e.DEV_NULL,interval:3e3},Rt="R5ProPlaybackView";class It{constructor(e="red5pro-subscriber"){try{this._targetElement=ie.resolveElement(e)}catch(e){throw k(Rt,`Could not instantiate a new instance of Red5ProSubscriber. Reason: ${e.message||e}`),e}}attachStream(e){const t=this.isAutoplay;D(Rt,"[attachstream]"),ie.setVideoSource(this._targetElement,e,t)}detachStream(){D(Rt,"[detachstream]"),ie.setVideoSource(this._targetElement,null,this.isAutoplay)}get isAutoplay(){return ie.hasAttributeDefined(this._targetElement,"autoplay")}get view(){return this._targetElement}}const Ot="RTCPeerConnectionSubscriber";class Dt extends ke{constructor(e){super(e,Ot)}_removeConnectionHandlers(e){e.onconnectionstatechange=null,e.oniceconnectionstatechange=null,e.onicegatheringstatechange=null,e.onsignalingstatechange=null,e.onicecandidate=null,e.ontrack=null,e.onnegotiationneeded=null}_addConnectionHandlers(e){let t;e.onsignalingstatechange=()=>{const t=e.signalingState;D(Ot,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(D(this._name,"[peerconnection:open]"),this._responder.onPeerConnectionOpen()):"failed"===t||"disconnected"===t?(H(this._name,`[peerconnection:error]:: ${t}`),"failed"===t&&this._responder.onPeerConnectionFail()):D(this._name,`[peerconnection:state]:: ${t}`)},e.oniceconnectionstatechange=i=>{const{iceConnectionState:n}=e;D(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionFail(),this._responder.onPeerConnectionClose(i)):"disconnected"===n?t=setTimeout(()=>{D(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached."),clearTimeout(t),this._responder.onPeerConnectionClose(i)},3e3):t&&(D(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;D(this._name,`[peer.onicecandidate] - Peer Candidate: ${null==t?void 0:t.candidate}`),t&&this._responder.onIceCandidate(t)},e.onnegotiationneeded=()=>{D(this._name,"[peer.onnegotiationneeded]")},e.onicegatheringstatechange=()=>{const{iceGatheringState:t}=e;D(this._name,`[peer.onicegatheringstatechange] - State: ${t}`)}}_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;D(this._name,"[datachannel-response]: "+JSON.stringify(i,null,2));const{data:n}=i;if(n&&"status"===n.type)return"NetStream.Play.UnpublishNotify"===n.code?(this._responder.onUnpublish(),this._responder.onConnectionClosed(),!0):"Application.Statistics.Endpoint"===n.code?(this._responder.onStatisticsEndpointChange(n.statistics),!0):(D(Ot,`[datachannel.message] status :: ${n.code}`),this._responder.onSubscriberStatus(n),!0);if(n&&n.status&&"NetStream.Play.UnpublishNotify"===n.status)return this._responder.onUnpublish(),this._responder.onConnectionClosed(),!0;if(n&&"result"===n.type){const{message:e}=n;if("Stream switch: Success"===e)try{return this._responder.onStreamSwitchComplete(),!0}catch(e){}}return this._responder.onDataChannelMessage(this._dataChannel,t),!1}}var Ht;!function(e){e.EMPTY="Empty",e.VIDEO="Video",e.AUDIO="Audio",e.FULL="Video/Audio"}(Ht||(Ht={}));class kt extends U{trigger(e){super.trigger(e)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}class Mt extends kt{}const Ut=[Ne.SUBSCRIBE_START,Ne.SUBSCRIBE_STOP,Ne.SUBSCRIBE_FAIL,Ne.SUBSCRIBE_PUBLISHER_CONGESTION,Ne.SUBSCRIBE_PUBLISHER_RECOVERY,Ne.PLAY_UNPUBLISH,Ne.STREAMING_MODE_CHANGE,Ne.PLAYBACK_STATE_CHANGE,Ne.STATISTICS_ENDPOINT_CHANGE];class Bt extends at{constructor(e,t,n){if(super("RTCSubscriberStats",e,t,n),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=e=>{const{type:t,data:n}=e;if(Ut.indexOf(t)>-1)if(t===Ne.STREAMING_MODE_CHANGE){const{streamingMode:e,previousStreamingMode:i}=n;this.postEvent(t,{data:{streamingMode:e,previousStreamingMode:i}})}else if(t===Ne.PLAYBACK_STATE_CHANGE){const{code:e}=n;let t;e===i.AVAILABLE&&(t={timeToFirstFrameMS:(new Date).getTime()-this._startTime}),this.postEvent(s[e],t)}else{if(t===Ne.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=n;this.updateEndpoint(e,!1)}this.postEvent(t)}},this._candidateCreateHandler=({data:{candidate:e}})=>{const{candidate:t}=e,i=lt(t);i&&(this._identifier.publicIP=i)},this._hostEndpointChangedHandler=({data:{endpoint:e,iceServers:t}})=>{this._appendClientDetails({node:e,iceServers:t})},this._client.on("*",this._eventHandler),this._client.on(Pe.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(Pe.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const e=({data:t})=>{this._client.off(Pe.PEER_CONNECTION_AVAILABLE,e),this.start(t)};this._client.on(Pe.PEER_CONNECTION_AVAILABLE,e)}}_handleStatsReport(e){const{type:t}=e,{include:i}=this._config,n=i&&i.length>0;if(n&&i.indexOf(t)>=-1)this.post(e);else if(!n)if(t===st.CODEC){const{id:i,clockRate:n,mimeType:s,payloadType:o}=e;this.post({id:i,type:t,clockRate:n,mimeType:s,payloadType:o})}else if(t===st.CANDIDATE_PAIR){const{availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o}=e;this._checkCandidatePairHealth(e),this.post({type:t,availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o})}else if([st.INBOUND,"inboundrtp"].indexOf(t)>-1){const{timestamp:i,kind:n,codecId:s,jitter:o,packetsLost:a,packetsReceived:r,bytesReceived:l}=e,d={type:t,kind:n,codecId:s,jitter:o,packetsLost:a,packetsReceived:r,bytesReceived:l};if("audio"===n){const{packetsDiscarded:t}=e;if(this.lastAudioReport){const{bytesReceived:e,timestamp:t}=this.lastAudioReport,n=8*(l-e)/(i-t);this.estimatedAudioBitrate=n}this.post({...d,packetsDiscarded:t,estimatedBitrate:Math.floor(this.estimatedAudioBitrate)}),this.lastAudioReport=e}else if("video"===n){const{firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:a,framesPerSecond:r,framesReceived:h,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:g,totalFreezesDuration:m,totalPausesDuration:v}=e,E={...d,firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:a,framesPerSecond:r,framesReceived:h,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:g,totalFreezesDuration:m,totalPausesDuration:v};if(this.lastVideoReport){const{bytesReceived:e,timestamp:t}=this.lastVideoReport,n=8*(l-e)/(i-t);this.estimatedVideoBitrate=n}this.post({...E,estimatedBitrate:Math.floor(this.estimatedVideoBitrate)}),this.lastVideoReport=e}}}dispose(){this._client.off("*",this._eventHandler),this._client.off(Pe.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(Pe.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),super.dispose()}}class Vt extends Mt{constructor(e,t){super(),this._isVOD=!1,this._name=`SourceHandler-${t}`,this._view=e,this._playbackNotificationCenter=this._view,this.onCanPlay=this._onCanPlay.bind(this),this.onDurationChange=this._onDurationChange.bind(this),this.onEnded=this._onEnded.bind(this),this.onTimeUpdate=this._onTimeUpdate.bind(this),this.onPlay=this._onPlay.bind(this),this.onPause=this._onPause.bind(this),this.onVolumeChange=this._onVolumeChange.bind(this),this.onLoadedData=this._onLoadedData.bind(this),this.onLoadedMetadata=this._onLoadedMetadata.bind(this),this.onResize=this._onResize.bind(this),this.onLoadStart=this._onLoadStart.bind(this),this.onSuspend=this._onSuspend.bind(this),this.onStalled=this._onStalled.bind(this),this.onWaiting=this._onWaiting.bind(this),this.onError=this._onError.bind(this),this.onEncrypted=this._onEncrypted.bind(this),this._addPlaybackNotificationCenterHandlers(this._playbackNotificationCenter),ie.onFullScreenStateChange(this._handleFullScreenChange.bind(this))}_addPlaybackNotificationCenterHandlers(e){e.addEventListener("canplay",this.onCanPlay),e.addEventListener("durationchange",this.onDurationChange),e.addEventListener("ended",this.onEnded),e.addEventListener("timeupdate",this.onTimeUpdate),e.addEventListener("play",this.onPlay),e.addEventListener("pause",this.onPause),e.addEventListener("volumechange",this.onVolumeChange),e.addEventListener("loadeddata",this.onLoadedData),e.addEventListener("loadedmetadata",this.onLoadedMetadata),e.addEventListener("resize",this.onResize),e.addEventListener("loadstart",this.onLoadStart),e.addEventListener("suspend",this.onSuspend),e.addEventListener("stalled",this.onStalled),e.addEventListener("waiting",this.onWaiting),e.addEventListener("error",this.onError),e.addEventListener("encrypted",this.onEncrypted)}_removePlaybackNotificationCenterHandlers(e){e.removeEventListener("canplay",this.onCanPlay),e.removeEventListener("durationchange",this.onDurationChange),e.removeEventListener("ended",this.onEnded),e.removeEventListener("timeupdate",this.onTimeUpdate),e.removeEventListener("play",this.onPlay),e.removeEventListener("pause",this.onPause),e.removeEventListener("volumechange",this.onVolumeChange),e.removeEventListener("loadeddata",this.onLoadedData),e.removeEventListener("loadedmetadata",this.onLoadedMetadata),e.removeEventListener("resize",this.onResize),e.removeEventListener("loadstart",this.onLoadStart),e.removeEventListener("suspend",this.onSuspend),e.removeEventListener("stalled",this.onStalled),e.removeEventListener("waiting",this.onWaiting),e.removeEventListener("error",this.onError)}_handleFullScreenChange(e){var t,i;e?null===(t=this._view)||void 0===t||t.classList.add("red5pro-media-container-full-screen"):null===(i=this._view)||void 0===i||i.classList.remove("red5pro-media-container-full-screen"),this.trigger(new be(Ne.FULL_SCREEN_STATE_CHANGE,void 0,e))}_cleanup(){this._playbackNotificationCenter&&this._removePlaybackNotificationCenterHandlers(this._playbackNotificationCenter),this._playbackNotificationCenter=void 0,this._view=void 0}_onCanPlay(e){var t;D(this._name,"[videoelement:event] canplay");const s=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,o=this.getControls();o&&o.enable(!0),this.trigger(new be(Ne.PLAYBACK_STATE_CHANGE,void 0,{code:i.AVAILABLE,state:n.AVAILABLE})),this.trigger(new be(Ne.VOLUME_CHANGE,void 0,{volume:s.volume}))}_onDurationChange(e){var t;D(this._name,"[videoelement:event] durationchange");const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();n&&n.setPlaybackDuration(i.duration),!isNaN(i.duration)&&Number.isFinite(i.duration)&&(this._isVOD=!0)}_onEnded(){D(this._name,"[videoelement:event] ended");const e=this.getControls();e&&e.setState(i.IDLE),this.trigger(new be(Ne.PLAYBACK_STATE_CHANGE,void 0,{code:i.IDLE,state:n.IDLE}))}_onTimeUpdate(e){var t;const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();n&&n.setSeekTime(i.currentTime,this.isVOD()?i.duration:void 0),this.trigger(new be(Ne.PLAYBACK_TIME_UPDATE,void 0,{time:i.currentTime,duration:i.duration}))}_onPlay(){D(this._name,"[videoelement:event] play");const e=this.getControls();e&&e.setState(i.PLAYING),this.trigger(new be(Ne.PLAYBACK_STATE_CHANGE,void 0,{code:i.PLAYING,state:n.PLAYING}))}_onPause(){D(this._name,"[videoelement:event] pause");const e=this.getControls();e&&e.setState(i.PAUSED),this.trigger(new be(Ne.PLAYBACK_STATE_CHANGE,void 0,{code:i.PAUSED,state:n.PAUSED}))}_onVolumeChange(e){var t;D(this._name,"[videoelement:event] volumechange");const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();n&&n.getVolume()!==i.volume&&n.setVolume(i.volume),this.trigger(new be(Ne.VOLUME_CHANGE,void 0,{volume:i.volume}))}_onLoadedData(e){var t,i,n;D(this._name,"[videoelement:event] loadeddata");const s=null!==(t=this._view)&&void 0!==t?t:e.target;this.trigger(new be(Ne.VIDEO_DIMENSIONS_CHANGE,void 0,{width:null!==(i=s.videoWidth)&&void 0!==i?i:0,height:null!==(n=s.videoHeight)&&void 0!==n?n:0}))}_onLoadedMetadata(e){var t,i;D(this._name,"[videoelement:event] loadedmetadata");const n=null!==(t=this._view)&&void 0!==t?t:e.target;this.trigger(new be(Ne.LOADED_METADATA,void 0,{duration:null!==(i=n.duration)&&void 0!==i?i:0}))}_onResize(e){var t,i,n;D(this._name,"[videoelement:event] resize");const s=null!==(t=this._view)&&void 0!==t?t:e.target;this.trigger(new be(Ne.VIDEO_DIMENSIONS_CHANGE,void 0,{width:null!==(i=s.videoWidth)&&void 0!==i?i:0,height:null!==(n=s.videoHeight)&&void 0!==n?n:0}))}_onLoadStart(){D(this._name,"[videoelement:event] loadstart")}_onSuspend(){D(this._name,"[videoelement:event] suspend")}_onStalled(){D(this._name,"[videoelement:event] stalled")}_onWaiting(){D(this._name,"[videoelement:event] waiting")}_onEncrypted(){D(this._name,"[videoelement:event] encrypted")}_onError(e){D(this._name,"[videoelement:event] error"),this.trigger(new be(Ne.CONNECT_FAILURE,void 0,{error:e.message}))}async attemptAutoplay(e=!1){try{await this.play(),this.isMuted()&&this.trigger(new be(Ne.AUTO_PLAYBACK_MUTED,void 0,{element:this._view}))}catch(t){e?(this.mute(),this.attemptAutoplay(!1)):this.trigger(new be(Ne.AUTO_PLAYBACK_FAILURE,void 0,{error:t.message?t.message:t,element:this._view}))}}async play(){var e,t;if(D(this._name,"[videoelement:action] play"),!(null===(e=this._view)||void 0===e?void 0:e.paused))return D(this._name,"[videoelement:action] play (ALREADY PLAYING)"),!0;try{return await(null===(t=this._view)||void 0===t?void 0:t.play()),!0}catch(e){throw k(this._name,"[videoelement:action] play (FAULT) - "+e.message),e}}async pause(){var e;D(this._name,"[videoelement:action] pause");try{return await(null===(e=this._view)||void 0===e?void 0:e.pause()),!0}catch(e){H(this._name,"[videoelement:action] pause (CATCH::FAULT) - "+e.message)}return!1}async resume(){var e;D(this._name,"[videoelement:action] resume");try{return await(null===(e=this._view)||void 0===e?void 0:e.play()),!0}catch(e){H(this._name,"[videoelement:action] resume (CATCH::FAULT) - "+e.message)}return!1}async stop(){var e;D(this._name,"[videoelement:action] stop");try{return await(null===(e=this._view)||void 0===e?void 0:e.pause()),!0}catch(e){H(this._name,"[videoelement:action] stop (CATCH::FAULT) - "+e.message)}return!1}mute(){this._view&&(this._view.muted=!0);const e=this.getControls();e&&e.setMutedState(!0)}unmute(){this._view&&(this._view.muted=!1);const e=this.getControls();e&&e.setMutedState(!1)}setVolume(e){this.unmute(),this._view&&(this._view.volume=e)}getVolume(){var e,t;return null!==(t=null===(e=this._view)||void 0===e?void 0:e.volume)&&void 0!==t?t:0}seekTo(e,t=void 0){this._view&&(this._view.currentTime=t?e*t:e)}toggleFullScreen(e){try{(e||this._view)&&ie.toggleFullScreen(null!=e?e:this._view)}catch(e){}}async unpublish(){var e;try{await this.stop(),null===(e=this._view)||void 0===e||e.dispatchEvent(new Event("ended"))}catch(e){}}disconnect(){this._cleanup()}isVOD(){return this._isVOD}isMuted(){var e,t;return null!==(t=null===(e=this._view)||void 0===e?void 0:e.muted)&&void 0!==t&&t}getControls(){}}const Ft="WHEPClient",$t=Nt,Gt=e=>D(Ft,e),xt=e=>k(Ft,e),Wt=e=>H(Ft,e);class zt extends kt{constructor(e,t,i){super(),this._reconnecting=!1,this._videoMuted=!0,this._audioMuted=!0;const n=e?se(e):$t,s=i||$t,o={...s,...n,endpoint:e,mediaElementId:t?t.id:s.mediaElementId};this._videoUnmuteHandler=this._onVideoUnmute.bind(this),this._audioUnmuteHandler=this._onAudioUnmute.bind(this),e&&this.internalInit(o)}async internalInit(e){await this.init(e),await this.subscribe()}async _runMuteCheck(){var e,t,i;if(this.getPeerConnection())try{let n=this._videoMuted,s=this._audioMuted;const o=await(null===(e=this.getPeerConnection())||void 0===e?void 0:e.getStats());if(null==o||o.forEach(e=>{const{type:t,kind:i,bytesReceived:o}=e;"inbound-rtp"!==t&&"inboundrtp"!==t||("video"===i?n=o<=0:"audio"===i&&(s=o<=0))}),n===this._videoMuted&&s===this._audioMuted)return;this._videoMuted=n,this._audioMuted=s;const a={data:{streamingMode:(t=!this._videoMuted,i=!this._audioMuted,t&&i?Ht.FULL:t?Ht.VIDEO:i?Ht.AUDIO:Ht.EMPTY),method:"onMetaData"},type:"metadata",method:"onMetaData",eventTimestamp:(new Date).getTime()};this._onMetaData(a)}catch(e){xt(e.message||e)}}_onVideoUnmute(e){const t=e.target;null==t||t.removeEventListener("unmute",this._videoUnmuteHandler);const i=setTimeout(async()=>{clearTimeout(i),this._runMuteCheck()},1e3)}_onAudioUnmute(e){const t=e.target;null==t||t.removeEventListener("unmute",this._audioUnmuteHandler);const i=setTimeout(async()=>{clearTimeout(i),this._runMuteCheck()},1e3)}_attachSourceHandler(e){this._sourceHandler=new Vt(e,this.getType())}_glomTrigger(e){e.on("*",e=>{const{type:t,data:i}=e;this.trigger(new be(t,this,i))})}_playIfAutoplaySet(e,t){var i;if(e&&t){const{muteOnAutoplayRestriction:n}=e;ie.hasAttributeDefined(t,"autoplay")&&(null===(i=this._sourceHandler)||void 0===i||i.attemptAutoplay(n))}}addMediaStreamToPlayback(e,t){var i;!this._playbackView&&e&&(this._playbackView=new It(e)),null===(i=this._playbackView)||void 0===i||i.attachStream(t)}async requestOffer(i){var n;Gt("[requestoffer]");const{iceTransport:s,maintainStreamVariant:o,videoEncoding:a,audioEncoding:r,connectionParams:l,mungeOffer:d}=this._options;i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const h={transport:s,doNotSwitch:o};a&&a!==t.NONE&&(h.videoEncoding=a),r&&r!==e.NONE&&(h.audioEncoding=r);const c=null!=l?l:{},u=await i.createOffer(),p=await(null===(n=this._whipWhepService)||void 0===n?void 0:n.postSDPOffer(u.sdp,{...c,...h},!1));if(!p)throw xt("Failed to get offer from WHEP"),new Error("Failed to get offer from WHEP");const{sdp:_}=p;let g=_;return d&&(Gt(`[MUNGE:before] offer: ${g}`),g=d(g),Gt(`[MUNGE:after] offer: ${g}`)),g}async requestAnswer(e){const{mungeAnswer:t}=this._options;let i=(await e.createAnswer()).sdp;return t&&(Gt(`[MUNGE:before] answer: ${i}`),i=t(i),Gt(`[MUNGE:after] answer: ${i}`)),i}async sendAnswer(e){var t;const{connectionParams:i}=this._options;return await(null===(t=this._whipWhepService)||void 0===t?void 0:t.postSDPAnswer(e,i))}async postCandidateFragments(e){var t;const{connectionParams:i}=this._options,n=We(e,void 0,!0);return await(null===(t=this._whipWhepService)||void 0===t?void 0:t.trickle(n,i))}async initPubNub(e){var t;try{const t=new Ct;this._pubnubClient=t,this._pubnubClient.on("*",e=>{this.trigger(e)}),await t.init(e)}catch(e){return e(null!==(t=e.message)&&void 0!==t?t:"Failed to initialize PubNub."),!1}return!0}async deinitPubNub(){var e,t;try{await(null===(e=this._pubnubClient)||void 0===e?void 0:e.destroy()),this._pubnubClient=void 0}catch(e){return e(null!==(t=e.message)&&void 0!==t?t:"Failed to deinitialize PubNub."),!1}return!0}_evaluateRenegotiationPolicy(e,t){const{renegotiationPolicy:i}=this._options;if(i){const{type:n}=i,s=n.toLowerCase();if(Gt(`[evaluateRenegotiationPolicy] - Type: ${e}, Renegotiation Policy: ${i.type}`),e===Re.CONNECTION_HEALTH_STATE_REGRESSION&&"regression"===s)this._reconnect();else if(e===Re.CONNECTION_HEALTH_ICE_TIMEOUT&&"timeout"===s)this._reconnect();else if(e===Ne.CONNECTION_CLOSED&&"disconnect"===s)this._reconnect();else if(e===Re.CONNECTION_HEALTH_EXCESSIVE_RTT&&"excessive-rtt"===s){const{severity:e}=t;!e||"critical"!==e.toLowerCase()&&"severe"!==e.toLowerCase()||this._reconnect()}}}async _reconnect(){var e,t;if(this._reconnecting)Gt("[reconnect] - already in progress. Ignoring request.");else{this._reconnecting=!0,Gt("[reconnect]"),this.trigger(new be(Ne.RECONNECT_START,this));try{await this.unsubscribe(!0),await this.init(this._options),await this.subscribe()}catch(i){xt(null!==(e=i.message)&&void 0!==e?e:"Could not reconnect."),this.trigger(new be(Ne.RECONNECT_FAILURE,this,{error:null!==(t=i.message)&&void 0!==t?t:"Could not reconnect."}))}finally{this._reconnecting=!1}}}async init(e){var t,i,n;this._options={...$t,...e},this._options.subscriptionId=this._options.subscriptionId||`subscriber-${Math.floor(65536*Math.random()).toString(16)}`;const s=oe(this._options,"whep"),{includeDataChannel:o,disableProxy:a}=this._options;return this._whipWhepService=new tt(`${s}?requestId=${this._options.subscriptionId}`,o,a),this._messageTransport=this._whipWhepService,((null===(t=this._options)||void 0===t?void 0:t.stats)||(null===(i=this._options)||void 0===i?void 0:i.renegotiationPolicy))&&(!this._options.stats&&this._options.renegotiationPolicy&&(this._options.stats=Lt),this.monitorStats(this._options.stats,this._options.renegotiationPolicy)),(null===(n=this._options)||void 0===n?void 0:n.pubnub)&&await this.initPubNub(this._options.pubnub),this}async subscribe(){var e,t,i,n,s,o,a,r,l;const{connectionParams:d,rtcConfiguration:h,includeDataChannel:c,signalingSocketOnly:u,enableChannelSignaling:p,dataChannelConfiguration:_}=this._options;try{const l=d||{},m=await(null===(e=this._whipWhepService)||void 0===e?void 0:e.getOptions(l));this.trigger(new be(Ne.CONNECT_SUCCESS,this,null===(t=this._whipWhepService)||void 0===t?void 0:t.getUrl()));const v=!!(null===(i=this._options)||void 0===i?void 0:i.rtcConfiguration)&&Array.isArray(this._options.rtcConfiguration.iceServers)&&this._options.rtcConfiguration.iceServers.length>0;(null==m?void 0:m.links)&&!v&&(this._options.rtcConfiguration={...h,iceServers:m.links}),(null==m?void 0:m.origin)&&this.trigger(new be(Pe.HOST_ENDPOINT_CHANGED,this,{endpoint:m.origin})),(null==m?void 0:m.statisticsEndpoint)&&this._onStatisticsEndpointChange(m.statisticsEndpoint);const E=c||p||u?_:void 0;if(this._peerConnectionHelper=new Dt({onUnpublish:this._onUnpublish.bind(this),onStreamUnavailable:this._onStreamUnavailable.bind(this),onSubscriberStatus:this._onSubscriberStatus.bind(this),onStreamSwitchComplete:this._onStreamSwitchComplete.bind(this),onDataChannelError:this._onDataChannelError.bind(this),onSendReceived:this._onSendReceived.bind(this),onMetaData:this._onMetaData.bind(this),onConnectionClosed:this._onConnectionClosed.bind(this),onDataChannelOpen:this._onDataChannelOpen.bind(this),onDataChannelClose:this._onDataChannelClose.bind(this),onDataChannelMessage:this._onDataChannelMessage.bind(this),onPeerConnectionOpen:this._onPeerConnectionOpen.bind(this),onPeerConnectionFail:this._onPeerConnectionFail.bind(this),onPeerConnectionClose:this._onPeerConnectionClose.bind(this),onIceCandidate:this._onIceCandidate.bind(this),onSDPSuccess:this._onSDPSuccess.bind(this),onSDPError:this._onSDPError.bind(this),onStatisticsEndpointChange:this._onStatisticsEndpointChange.bind(this)}),await this._peerConnectionHelper.setUpWithPeerConfiguration(this._options.rtcConfiguration,E),null===(n=this.getPeerConnection())||void 0===n||n.addEventListener("track",e=>{const{buffer:t}=this._options;Gt("[peerconnection.ontrack]");const{streams:i,track:n,receiver:s,transceiver:o}=e;s.jitterBufferDelayHint=t,this.trigger(new be(Pe.TRACK_ADDED,this,{streams:i,track:n,receiver:s,transceiver:o})),this._mediaStream=i&&i.length>0?i[0]:void 0,"video"===n.kind?(this._videoMuted=n.muted,n.muted&&n.addEventListener("unmute",this._videoUnmuteHandler)):"audio"===n.kind&&(this._audioMuted=n.muted,n.muted&&n.addEventListener("unmute",this._audioUnmuteHandler)),this._runMuteCheck()}),this.trigger(new be(Pe.PEER_CONNECTION_AVAILABLE,this,this.getPeerConnection())),this.trigger(new be(Pe.OFFER_START,this)),!this.getPeerConnection())throw new Error("SDP Exchange interrupted. Peer Connection Helper not available.");const S=await this.requestOffer(this.getPeerConnection()),C=new RTCSessionDescription({type:"offer",sdp:S});if(!this.getPeerConnection())throw new Error("SDP Exchange interrupted. Peer Connection Helper not available.");await(null===(s=this.getPeerConnection())||void 0===s?void 0:s.setRemoteDescription(C)),this.trigger(new be(Pe.OFFER_END,this)),this.trigger(new be(Pe.ANSWER_START,this));const b=await this.requestAnswer(this.getPeerConnection()),f=(g=b).includes("stereo=1")?g:g.replace("useinbandfec=1","useinbandfec=1;stereo=1;sprop-stereo=1"),T=new RTCSessionDescription({type:"answer",sdp:f});await(null===(o=this.getPeerConnection())||void 0===o?void 0:o.setLocalDescription(T)),await this.sendAnswer(f),this.trigger(new be(Pe.ANSWER_END,this));const y=await this._peerConnectionHelper.waitToGatherIce(),{sdp:w}=y;return await this.postCandidateFragments(w),this.trigger(new be(Pe.ICE_TRICKLE_COMPLETE,this)),this._mediaStream&&(this.trigger(new be(Pe.ON_ADD_STREAM,this,this._mediaStream)),this.addMediaStreamToPlayback(this._options.mediaElementId,this._mediaStream)),(null===(a=this._playbackView)||void 0===a?void 0:a.view)&&this._attachSourceHandler(this._playbackView.view),this._sourceHandler&&this._glomTrigger(this._sourceHandler),this._playIfAutoplaySet(this._options,null===(r=this._playbackView)||void 0===r?void 0:r.view),this}catch(e){throw xt(null!==(l=e.message)&&void 0!==l?l:"Could not subscribe."),e instanceof je?this._onStreamUnavailable(e):this.trigger(new be(Ne.CONNECT_FAILURE,this,e)),this._options.maintainConnectionOnSubscribeErrors||this.unsubscribe(!0),e}var g}async unsubscribe(e=!1){var t;Gt("[unsubscribe]"),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,e),this._sourceHandler&&this._sourceHandler.disconnect(),this._pubnubClient&&await this.deinitPubNub(),this.unmonitorStats(),null===(t=this._playbackView)||void 0===t||t.detachStream(),this._playbackView=void 0,this._pubnubClient=void 0,this._whipWhepService=void 0,this._messageTransport=void 0,this._peerConnectionHelper=void 0,this._sourceHandler=void 0,this._mediaStream=void 0,this.trigger(new be(Ne.SUBSCRIBE_STOP,this))}async send(e,t){var i;let n=t;try{n="string"==typeof t?JSON.parse(t):t}catch(e){Wt(`Could not parse data as JSON. Sending as message. Error: ${e.message||e}`),n={message:t}}return null===(i=this.getMessageTransport())||void 0===i?void 0:i.post({send:{method:e,data:n}})}async sendPubNub(e,t){return this._pubnubClient?await this._pubnubClient.publishMessage(e,t):(xt("PubNub client not initialized."),!1)}async subscribePubNub(e,t){return this._pubnubClient?await this._pubnubClient.subscribe(e,t):(xt("PubNub client not initialized."),!1)}async unsubscribePubNub(e){return this._pubnubClient?await this._pubnubClient.unsubscribe(e):(xt("PubNub client not initialized."),!1)}async callServer(e,t){var i;const n="switchStreams"===e,{app:s,streamName:o}=this._options;if(n){const{path:i}=t[0];this._requestedStreamSwitch=i,Gt(`[callServer:switch]:: ${e}, ${s}/${o} -> ${i}`)}return null===(i=this.getMessageTransport())||void 0===i?void 0:i.postAsync({callAdapter:{method:e,arguments:t}})}sendLog(e,t){var i;try{const n=Object.keys(L).find(t=>t.toLowerCase()===e.toLowerCase())?e:L.DEBUG,s="string"==typeof t?t:JSON.stringify(t);null===(i=this.getMessageTransport())||void 0===i||i.post({log:n.toUpperCase(),message:s})}catch(e){const t=e.message||e;xt("Could not send log to server. Message parameter expected to be String or JSON-serializable object."),xt(t)}}enableStandby(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteAudio:!0,muteVideo:!0}})}disableStandby(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteAudio:!1,muteVideo:!1}})}muteAudio(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteAudio:!0}})}unmuteAudio(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteAudio:!1}})}muteVideo(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteVideo:!0}})}unmuteVideo(){var e;null===(e=this.getMessageTransport())||void 0===e||e.post({mute:{muteVideo:!1}})}get options(){return this._options}getOptions(){return this._options}getPeerConnection(){var e;return null===(e=this._peerConnectionHelper)||void 0===e?void 0:e.connection}getDataChannel(){var e;return null===(e=this._peerConnectionHelper)||void 0===e?void 0:e.dataChannel}getMediaStream(){return this._mediaStream}getMessageTransport(){return this._messageTransport}getPubNubClient(){return this._pubnubClient}getPlayer(){var e;return null===(e=this._playbackView)||void 0===e?void 0:e.view}play(){Gt("[play]"),this._sourceHandler?this._sourceHandler.play():Wt("Cannot play without a Source Handler.")}pause(){Gt("[pause]"),this._sourceHandler?this._sourceHandler.pause():Wt("Cannot pause without a Source Handler.")}resume(){Gt("[resume]"),this._sourceHandler?this._sourceHandler.resume():Wt("Cannot resume without a Source Handler.")}stop(){Gt("[stop]"),this._sourceHandler?this._sourceHandler.stop():Wt("Cannot stop without a Source Handler.")}setVolume(e){Gt("[setVolume]"),this._sourceHandler?this._sourceHandler.setVolume(e):Wt("Cannot set volume without a Source Handler.")}getVolume(){var e,t,i;return Gt("[getVolume]"),this._sourceHandler?this._sourceHandler.getVolume():(Wt("Cannot get volume without a Source Handler."),null!==(i=null===(t=null===(e=this._playbackView)||void 0===e?void 0:e.view)||void 0===t?void 0:t.volume)&&void 0!==i?i:0)}mute(){Gt("[mute]"),this._sourceHandler?this._sourceHandler.mute():Wt("Cannot mute without a Source Handler.")}unmute(){Gt("[unmute]"),this._sourceHandler?this._sourceHandler.unmute():Wt("Cannot unmute without a Source Handler.")}seekTo(e){Gt("[seekTo]"),this._sourceHandler?this._sourceHandler.seekTo(e):Wt("Cannot seek without a Source Handler.")}toggleFullScreen(){Gt("[toggleFullScreen]"),this._sourceHandler?this._sourceHandler.toggleFullScreen():Wt("Cannot toggle full screen without a Source Handler.")}monitorStats(e,t){Gt(`[monitorStats]:: Stats: ${e?JSON.stringify(e):"undefined"}`),Gt(`[monitorStats]:: Renegotiation Policy: ${t?JSON.stringify(t):"undefined"}`);const{host:i,endpoint:n,app:s,streamName:o,subscriptionId:a,connectionParams:r}=this._options,l=null!=e?e:ge;return this._statisticsConfiguration={...l,host:i,app:s,hostEndpoint:n,streamName:o,subscriptionId:a,connectionParams:r},this._statsMonitor?Wt("Cannot monitor stats without a Peer Connection. Please call `init` before calling `monitorStats`."):this._statsMonitor=new Bt(this._statisticsConfiguration,{onStatsReport:this._onStatsReport.bind(this),getPeerConnection:this.getPeerConnection.bind(this),getMessageTransport:this.getMessageTransport.bind(this),on:this.on.bind(this),off:this.off.bind(this),trigger:this.trigger.bind(this),emit:this.emit.bind(this)},t),this}unmonitorStats(){return this._statsMonitor&&this._statsMonitor.dispose(),this._statsMonitor=void 0,this._statisticsConfiguration=void 0,this}_onUnpublish(){Gt("[unpublish]"),this.trigger(new be(Ne.PLAY_UNPUBLISH,this)),this._sourceHandler&&this._sourceHandler.unpublish()}_onStreamUnavailable(e){Gt(`Stream ${this._options.streamName} does not exist.`),Gt("[onstreamunavailable]: "+JSON.stringify(e,null,2)),this.trigger(new be(Ne.SUBSCRIBE_INVALID_NAME,this))}_onDataChannelError(e,t){xt(`Data channel error: ${t}`),this.trigger(new be(Pe.DATA_CHANNEL_ERROR,this,{dataChannel:e,error:t}))}_onSendReceived(e,t){Gt(`Send received: ${e} ${JSON.stringify(t)}`),"onMetaData"===e?this._onMetaData(t):this.trigger(new be(Ne.SUBSCRIBE_SEND_INVOKE,this,{methodName:e,data:t}))}_onStreamSwitchComplete(){Gt("[streamswitch::complete]");const e=this._requestedStreamSwitch;this.trigger(new be(Pe.SUBSCRIBE_STREAM_SWITCH,this,{path:e})),this._requestedStreamSwitch=void 0}_onMetaData(e){const{orientation:t,streamingMode:i}=e,n=this._streamingMode;void 0!==t&&t!==this._orientation&&(this._orientation=t,this.trigger(new be(Ne.ORIENTATION_CHANGE,this,{orientation:parseInt(t,10),viewElement:this._playbackView?this._playbackView.view:void 0}))),i&&void 0!==i&&i!==n&&(this._streamingMode=i,this.trigger(new be(Ne.STREAMING_MODE_CHANGE,this,{streamingMode:i,previousStreamingMode:n,viewElement:this._playbackView?this._playbackView.view:void 0}))),this.trigger(new be(Ne.SUBSCRIBE_METADATA,this,e))}_onConnectionClosed(){Gt("Connection closed"),this.unsubscribe(!0),this.trigger(new be(Ne.CONNECTION_CLOSED,this))}_onDataChannelOpen(e){Gt(`Data channel opened: ${e.label}`),this.trigger(new be(Pe.DATA_CHANNEL_OPEN,this,{dataChannel:e})),this.trigger(new be(Pe.DATA_CHANNEL_AVAILABLE,this,{name:e.label,dataChannel:e})),this._messageTransport=this._peerConnectionHelper,this.trigger(new fe(Le.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new be(Ne.SUBSCRIBE_START,this))}_onDataChannelClose(e){Gt(`Data channel closed: ${e.label}`),this.trigger(new be(Pe.DATA_CHANNEL_CLOSE,this,{dataChannel:e}))}_onDataChannelMessage(e,t){Gt(`Data channel message: ${t.data}`),this.trigger(new be(Pe.DATA_CHANNEL_MESSAGE,this,{dataChannel:e,message:t}))}_onPeerConnectionOpen(){var e;Gt("Peer connection opened"),this.trigger(new be(Pe.PEER_CONNECTION_OPEN,this,this.getPeerConnection())),(null===(e=this._options)||void 0===e?void 0:e.includeDataChannel)||this.trigger(new be(Ne.SUBSCRIBE_START,this))}_onPeerConnectionFail(){xt("Peer connection failed"),this.trigger(new be(Ne.SUBSCRIBE_FAIL,this))}_onPeerConnectionClose(e){Gt(`Peer connection closed: ${e.type}`),this._evaluateRenegotiationPolicy(Ne.CONNECTION_CLOSED)}_onIceCandidate(e){Gt(`ICE candidate: ${e.candidate}`),this.trigger(new be(Pe.CANDIDATE_CREATE,this,{candidate:e}))}_onPeerConnectionTrackAdd(e){Gt(`Peer connection track added: ${e.id}`)}_onSubscriberStatus(e){Gt(`Subscriber status: ${JSON.stringify(e)}`)}_onSDPSuccess(){Gt("SDP success")}_onSDPError(e){xt(`SDP error: ${e}`)}_onStatisticsEndpointChange(e){Gt(`Statistics endpoint changed: ${e}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(e),this.trigger(new be(Ne.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:e}))}_onStatsReport(e,t){this.trigger(new be(Pe.STATS_REPORT,this,{connection:e,report:t}))}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}trigger(e){super.trigger(e)}emit(e,t){this.trigger(new be(e,this,t)),this._evaluateRenegotiationPolicy(e,t)}getType(){return"RTC"}}const Kt={stream:3,datachannel:4},jt=[Ie.OPEN,Ie.CLOSE,Ie.ERROR,Ie.FAIL,we.STATISTICS_ENDPOINT_CHANGE];class Jt extends at{constructor(e,t){if(super("MessageChannelStats",e,t),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=e=>{const{type:t,data:i}=e;if(jt.indexOf(t)>-1){if(t===we.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=i;this.updateEndpoint(e,!1)}this.postEvent(t)}else jt.indexOf(t)>-1&&this.postEvent(t)},this._candidateCreateHandler=({data:{candidate:e}})=>{const{candidate:t}=e,i=lt(t);i&&(this._identifier.publicIP=i)},this._hostEndpointChangedHandler=({data:{endpoint:e,iceServers:t}})=>{this._appendClientDetails({node:e,iceServers:t})},this._client.on("*",this._eventHandler),this._client.on(Ae.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(Ae.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const e=({data:t})=>{this._client.off(Ae.PEER_CONNECTION_AVAILABLE,e),this.start(t)};this._client.on(Ae.PEER_CONNECTION_AVAILABLE,e)}}_handleStatsReport(e){const{type:t}=e,{include:i}=this._config,n=i&&i.length>0;if(n&&i.indexOf(t)>=-1)this.post(e);else if(!n)if(t===st.CODEC){const{id:i,clockRate:n,mimeType:s,payloadType:o}=e;this.post({id:i,type:t,clockRate:n,mimeType:s,payloadType:o})}else if(t===st.CANDIDATE_PAIR){const{availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o}=e;this._checkCandidatePairHealth(e),this.post({type:t,availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o});const{timestamp:a,kind:r,codecId:l,mediaType:d,active:h,bytesSent:c,packetsSent:u,totalPacketsSendDelay:p}=e,_={type:t,kind:r,codecId:l,mediaType:d,active:h,bytesSent:c,packetsSent:u,timestamp:a,totalPacketsSendDelay:p};this.post(_)}else if(t===st.DATA_CHANNEL){const{id:t,timestamp:i,type:n,label:s,state:o,messagesSent:a,messagesReceived:r,bytesSent:l,bytesReceived:d}=e;this.post({id:t,timestamp:i,type:n,label:s,state:o,messagesSent:a,messagesReceived:r,bytesSent:l,bytesReceived:d})}}dispose(){this._client.off("*",this._eventHandler),this._client.off(Ae.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(Ae.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),super.dispose()}}const Yt="DataChannelClient",qt=e=>D(Yt,e),Xt=e=>k(Yt,e);class Qt extends At{constructor(e,t){super(e,void 0,t),this._inactivePingIntervalMS=3e4,this._inactivePingTimeout=null}async internalInit(e){await this.init(e),await this.open()}establishStatsMonitor(e){return new Jt(e,{onStatsReport:this._onStatsReport.bind(this),getPeerConnection:this.getPeerConnection.bind(this),getMessageTransport:this.getMessageTransport.bind(this),on:this.on.bind(this),off:this.off.bind(this),trigger:this.trigger.bind(this),emit:this.emit.bind(this)})}async init(e){const{connectionParams:t}=e;e={...e,mediaConstraints:{audio:!1,video:!1},mediaElementId:void 0,includeDataChannel:!0,connectionParams:{...null!=t?t:{},capabilities:Kt.datachannel}};const i=await super.init(e);return qt(`Initialized MessageChannel with options: ${JSON.stringify(e,null,2)}`),i}async getAndPreviewStreamIfAvailable(){}_startInactivePing(){this._stopInactivePing(),this._inactivePingTimeout=setTimeout(()=>{const e=(new Date).toISOString();super.send("ping",{timestamp:e}),this._startInactivePing()},this._inactivePingIntervalMS)}_stopInactivePing(){this._inactivePingTimeout&&(clearTimeout(this._inactivePingTimeout),this._inactivePingTimeout=null)}async open(e=1e4){return this._inactivePingIntervalMS=e,await super.publish()}async close(){return this._stopInactivePing(),this.postStatsMonitorEvent(Ie.CLOSE),await super.unpublish()}async publish(){return await this.open()}async unpublish(){return await this.close()}async send(e,t){let i=t;try{i="string"==typeof t?JSON.parse(t):t}catch(e){i={data:t}}return await this.sendMessage({...i,methodName:e})}async sendMessage(e){const t=this.getDataChannel(),{streamName:i}=this.options?this.options:{},n=i||"unknown";if(t){let i=e;try{i="string"==typeof e?JSON.parse(e):e}catch(t){i={message:e}}const s={...i,sender_id:n,send_timestamp:(new Date).toISOString()};try{return t.send(JSON.stringify(s)),qt(`Sent message: ${JSON.stringify(s)}`),this.trigger(new ye(Ie.SEND,this,s)),this._startInactivePing(),!0}catch(e){Xt(`Error sending message: ${e.message||e}`),this.trigger(new ye(Ie.ERROR,this,{error:e.message||e}))}}return!1}async sendData(e){const t=this.getDataChannel();if(t)try{return t.send(e),this.trigger(new ye(Ie.SEND,this,e)),this._startInactivePing(),!0}catch(e){Xt(`Error sending data: ${e.message||e}`),this.trigger(new ye(Ie.ERROR,this,{error:e.message||e}))}return!1}_onDataChannelOpen(e){super._onDataChannelOpen(e),this._startInactivePing()}_onDataChannelMessage(e,t){const{data:i}=t;qt(`Incoming Data channel message: ${i}`),this.trigger(new ye(Ie.RECEIVE,this,{dataChannel:e,message:t}))}_onDataChannelClose(e){this._stopInactivePing(),super._onDataChannelClose(e),this.trigger(new ye(Ie.CLOSE,this))}_onPeerConnectionFail(){Xt("Peer connection failed"),this.trigger(new ye(Ie.FAIL,this))}_onSDPError(e=void 0){this.trigger(new ye(Ie.ERROR,this));const t=e?": "+JSON.stringify(e,null,2):"";Xt(`[onsdperror]:: ${t}`)}trigger(e){if(e.type===we.PUBLISH_START)super.trigger(new ye(Ie.OPEN,this));else if(e.type===we.UNPUBLISH_SUCCESS)super.trigger(new ye(Ie.CLOSE,this));else{const{type:t,data:i}=e;super.trigger(new ye(t,this,i))}}getType(){return"DATA_CHANNEL"}}class Zt extends Vt{constructor(e,t){super(e,t),this._playingStarted=!1,this.onOrientation=this._onOrientationMetadata.bind(this),this.onStreamingMode=this._onStreamingModeMetadata.bind(this),ie.onOrientationMetadata(this._view,this.onOrientation),ie.onStreamingModeMetadata(this._view,this.onStreamingMode),this.onPlaying=this._onPlaying.bind(this),this.onSourceError=this._onSourceError.bind(this),this._view.addEventListener("playing",this.onPlaying)}addSource(e){this._source=ie.createElement("source"),this._source.type="application/x-mpegURL",this._source.src=e,this._view.firstChild?this._view.insertBefore(this._source,this._view.firstChild):this._view.appendChild(this._source),this._source.addEventListener("error",this.onSourceError)}_onPlaying(){this._playingStarted||this.trigger(new be(Ne.SUBSCRIBE_START,this._view)),this._playingStarted=!0}_onSourceError(e){D(this._name,"[source:event] error"),this.trigger(new be(Ne.CONNECT_FAILURE,void 0,e))}_onOrientationMetadata(e){const{orientation:t}=e,i=parseInt(t,10);t&&this._orientation!==i&&(D(this._name,"Metadata received: "+JSON.stringify(e,null,2)),this._orientation=i,this.trigger(new be(Ne.ORIENTATION_CHANGE,{orientation:this._orientation,viewElement:this._view})),this.trigger(new be(Ne.SUBSCRIBE_METADATA,void 0,e)))}_onStreamingModeMetadata(e){const{streamingMode:t}=e,i=this._streamingMode;t&&i!==t&&(D(this._name,"Metadata received: "+JSON.stringify(e,null,2)),this._streamingMode=t,this.trigger(new be(Ne.STREAMING_MODE_CHANGE,void 0,{streamingMode:this._streamingMode,previousStreamingMode:i,viewElement:this._view})),this.trigger(new be(Ne.SUBSCRIBE_METADATA,void 0,e)))}_cleanup(){this._view&&this._view.removeEventListener("playing",this.onPlaying),this._source&&(this._source.removeEventListener("error",this.onSourceError),this._view.removeChild(this._source),this._source=void 0),super._cleanup()}}const ei="HLSSubscriber",ti=e=>D(ei,e),ii=e=>H(ei,e);class ni extends kt{constructor(){super()}_glomTrigger(e){e.on("*",e=>{const{type:t,data:i}=e;this.trigger(new be(t,this,i))})}_playIfAutoplaySet(e,t){var i;if(e&&t){const{muteOnAutoplayRestriction:n}=e;ie.hasAttributeDefined(t,"autoplay")&&(null===(i=this._sourceHandler)||void 0===i||i.attemptAutoplay(n))}}async init(e){if(!ie.supportsHLS())throw new Error("Native HLS playback is not supported on this browser.");return this._options={...Pt,...e},this}async subscribe(){var e;try{const t=/^http(|s).*\.m3u8/g,{endpoint:i,mediaElementId:n}=this._options;return this._fileURL=i&&i.match(t)?i:(e=>{const{host:t,protocol:i,port:n,app:s,streamName:o,connectionParams:a}=e,r="ws"===i||"http"===i?"http":"https",l=`${r}://${t}:${n||("http"===r?5080:443)}/${s}/${o}.m3u8`;if(a)return`${l}?${Object.entries(a).map(([e,t])=>`${e}=${t}`).join("&")}`;return l})(this._options),!this._playbackView&&n&&(this._playbackView=new It(n),this._sourceHandler=new Zt(this._playbackView.view,this.getType()),this._sourceHandler.addSource(this._fileURL),this._glomTrigger(this._sourceHandler)),this.trigger(new be(Ne.CONNECT_SUCCESS,this,this._fileURL)),this._playIfAutoplaySet(this._options,null===(e=this._playbackView)||void 0===e?void 0:e.view),this}catch(e){throw e(e.message),this.trigger(new be(Ne.CONNECT_FAILURE,this,e.message)),e}}async unsubscribe(){var e;return this._sourceHandler&&this._sourceHandler.disconnect(),null===(e=this._playbackView)||void 0===e||e.detachStream(),this._playbackView=void 0,this._sourceHandler=void 0,this.trigger(new be(Ne.SUBSCRIBE_STOP,this)),this}play(){ti("[play]"),this._sourceHandler?this._sourceHandler.play():ii("Cannot play without a Source Handler.")}pause(){ti("[pause]"),this._sourceHandler?this._sourceHandler.pause():ii("Cannot pause without a Source Handler.")}resume(){ti("[resume]"),this._sourceHandler?this._sourceHandler.resume():ii("Cannot resume without a Source Handler.")}stop(){ti("[stop]"),this._sourceHandler?this._sourceHandler.stop():ii("Cannot stop without a Source Handler.")}setVolume(e){ti("[setVolume]"),this._sourceHandler?this._sourceHandler.setVolume(e):ii("Cannot set volume without a Source Handler.")}getVolume(){var e,t,i;return ti("[getVolume]"),this._sourceHandler?this._sourceHandler.getVolume():(ii("Cannot get volume without a Source Handler."),null!==(i=null===(t=null===(e=this._playbackView)||void 0===e?void 0:e.view)||void 0===t?void 0:t.volume)&&void 0!==i?i:0)}mute(){ti("[mute]"),this._sourceHandler?this._sourceHandler.mute():ii("Cannot mute without a Source Handler.")}unmute(){ti("[unmute]"),this._sourceHandler?this._sourceHandler.unmute():ii("Cannot unmute without a Source Handler.")}seekTo(e){ti("[seekTo]"),this._sourceHandler?this._sourceHandler.seekTo(e):ii("Cannot seek without a Source Handler.")}toggleFullScreen(){ti("[toggleFullScreen]"),this._sourceHandler?this._sourceHandler.toggleFullScreen():ii("Cannot toggle full screen without a Source Handler.")}getPlayer(){var e;return null===(e=this._playbackView)||void 0===e?void 0:e.view}get options(){return this._options}getOptions(){return this._options}get fileURL(){return this._fileURL}getFileURL(){return this._fileURL}getType(){return"HLS"}}const si={baseURL:void 0,fullURL:void 0,hlsjsRef:void 0,hlsElement:void 0,usePlaybackControlsUI:!0,options:{debug:!1,backBufferLength:0}},oi={...Nt,liveSeek:si};class ai extends U{trigger(e){super.trigger(e)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}var ri,li;!function(e){e.SEEK_START="Seek.Start",e.SEEK_END="Seek.End"}(ri||(ri={})),function(e){e.CHANGE="Slider.Change",e.CHANGE_START="Slider.Change.Start",e.CHANGE_COMPLETE="Slider.Change.Complete"}(li||(li={}));class di extends Se{constructor(e,t,i){super(e,i),this._slider=t}get slider(){return this._slider}}const{createElement:hi,addGlobalEventListener:ci,removeGlobalEventListener:ui,globalUnassign:pi,getAssignedValue:_i,globalAssign:gi}=ie,mi="ControlSlider",vi="r5_liveseek_event_owner";class Ei extends U{constructor(e){super(),this._value=0,this._disabled=!1,this._eventStartPosition=0,this.debug=e=>D(mi,e),this.warn=e=>H(mi,e),this.name=[mi,e].join("::"),this.debug("[init]"),this._container=hi("div"),this._button=this.createButton(),this._track=this.createTrack(),this._progressBar=this.createProgressBar(),this._container.appendChild(this._track),this._container.appendChild(this._progressBar),this._container.appendChild(this._button),this._layout(),this._mouseupHandler=this._mouseup.bind(this),this._mousedownHandler=this._mousedown.bind(this),this._mousemoveHandler=this._mousemove.bind(this),this._touchupHandler=this._touchproxy.bind(this),this._touchdownHandler=this._touchproxy.bind(this),this._touchmoveHandler=this._touchproxy.bind(this),this._updateHandlers(this._disabled)}_touchproxy(e){var t,i,n,s;const o=e;this.debug(`${o.type} touches: ${(null===(t=o.changedTouches)||void 0===t?void 0:t.length)||0}`);try{o.preventDefault()}catch(e){this.warn("Failed to prevent default on touch event.")}if(!o.touches||o.touches.length>1||"touchend"===o.type&&o.touches.length>0)return;let a,r="";const l=o.target||document.body;switch(o.type){case"touchstart":r="mousedown",a=null===(i=o.changedTouches)||void 0===i?void 0:i[0];break;case"touchmove":r="mousemove",a=null===(n=o.changedTouches)||void 0===n?void 0:n[0];break;case"touchend":r="mouseup",a=null===(s=o.changedTouches)||void 0===s?void 0:s[0]}if(a&&r){const e=new MouseEvent(r,{bubbles:!0,cancelable:!0,view:l.ownerDocument.defaultView,screenX:a.screenX,screenY:a.screenY,clientX:a.clientX,clientY:a.clientY,ctrlKey:o.ctrlKey,altKey:o.altKey,shiftKey:o.shiftKey,metaKey:o.metaKey,button:0,relatedTarget:null});l.dispatchEvent(e)}}_mouseup(){this._eventStartPosition=0,pi(vi),ui("mousemove",this._mousemoveHandler),ui("mouseup",this._mouseupHandler),ui("touchmove",this._touchmoveHandler),ui("touchend",this._touchupHandler),this.trigger(new di(li.CHANGE_COMPLETE,this))}_mousemove(e){if(_i(vi)!==this.name)return;this.debug(`[mousemove] ${this.name}`);const t=e.clientX-this._eventStartPosition,i=this._button.parentNode.getBoundingClientRect();let n=this._eventStartPosition+t-i.left;n=Math.max(0,n),n=Math.min(n,i.width);const s=n/i.width;this.trigger(new di(li.CHANGE,this,s))}_mousedown(e){this._eventStartPosition=e.clientX,this.trigger(new di(li.CHANGE_START,this)),gi(vi,this.name),ci("mousemove",this._mousemoveHandler),ci("mouseup",this._mouseupHandler),ci("touchmove",this._touchmoveHandler),ci("touchend",this._touchupHandler)}_updateHandlers(e){this._eventStartPosition=0,e?(this._track.removeEventListener("click",this._mousemoveHandler),this._progressBar.removeEventListener("click",this._mousemoveHandler),this._button.removeEventListener("mousedown",this._mousedownHandler),ui("mousemove",this._mousemoveHandler),ui("mouseup",this._mouseupHandler),ui("touchmove",this._touchmoveHandler),ui("touchend",this._touchupHandler),this._track.classList.add("red5pro-media-slider-disabled"),this._progressBar.classList.add("red5pro-media-slider-disabled"),this._button.classList.add("red5pro-media-slider-disabled")):(this._track.addEventListener("click",this._mousemoveHandler),this._progressBar.addEventListener("click",this._mousemoveHandler),this._button.addEventListener("mousedown",this._mousedownHandler),this._button.addEventListener("touchstart",this._touchdownHandler),this._track.classList.remove("red5pro-media-slider-disabled"),this._progressBar.classList.remove("red5pro-media-slider-disabled"),this._button.classList.remove("red5pro-media-slider-disabled"))}_layout(){const e=this._progressBar.parentNode.clientWidth*this._value;this._progressBar.style.width=e+"px",this._button.style.left=e-.5*this._button.clientWidth+"px"}createButton(){const e=hi("span");return e.classList.add("red5pro-media-slider-button"),e}createProgressBar(){const e=hi("span");return e.classList.add("red5pro-media-slider-progress"),e}createTrack(){const e=hi("span");return e.classList.add("red5pro-media-slider-track"),e}get value(){return this._value}set value(e){this._value=e,this._layout()}get disabled(){return this._disabled}set disabled(e){this._disabled=e,this._updateHandlers(e)}get view(){return this._container}}const{createElement:Si,isTouchEnabled:Ci,isPossiblySafari:bi}=ie,fi=e=>D("PlaybackControls",e);class Ti extends ai{constructor(e,t){super(),this._state=i.IDLE,this._mutedState=!1,this._resumeAfterSeek=!1,this._playbackDuration=0,this._volumeValue=1,this._player=e,this._container=t,this._onPlayPauseClickBound=this._onPlayPauseClick.bind(this),this._decorate(this._container)}_decorate(e){if(!e)return;fi("[decorate]");const t=Si("div");let n;t.classList.add("red5pro-media-control-bar"),this._playPauseButton=this._createPlayPauseButton(),this._muteButton=this._createMuteButton(),this._volumeField=this._createVolumeControl(),this._seekTimeField=this._createSeekControl(),this._timeField=this._createPlaybackTime(),this._fullScreenButton=this._createFullScreenToggle(),t.appendChild(this._playPauseButton),t.appendChild(this._timeField),t.appendChild(this._seekTimeField.view),t.appendChild(this._muteButton),t.appendChild(this._volumeField.view),t.appendChild(this._fullScreenButton),e.appendChild(t),this._controlbar=t;const s=()=>{clearTimeout(n),n=setTimeout(()=>{t.classList.remove("red5pro-media-control-bar-show")},6e3)};Ci()?(t.classList.add("red5pro-media-control-bar-show"),e.addEventListener("touchend",()=>{t.classList.toggle("red5pro-media-control-bar-show"),s()}),s()):(e.addEventListener("mouseover",()=>{t.classList.add("red5pro-media-control-bar-show")}),e.addEventListener("mouseout",()=>{t.classList.remove("red5pro-media-control-bar-show")})),this.setState(i.IDLE).onFullScreenChange(!1).setSeekTime(0).enable(!1)}_onPlayPauseClick(){return this.getState()===i.PLAYING?this._player.pause(!0):this.getState()===i.PAUSED?this._player.resume(!0):this._player.play(!0),this}_createPlayPauseButton(){const e=Si("button");return e.setAttribute("aria-label","Toggle Playback"),e.classList.add("red5pro-media-control-element"),e.classList.add("red5pro-media-element-button"),e.classList.add("red5pro-media-playpause-button"),e}_createMuteButton(){const e=Si("button");return e.setAttribute("aria-label","Toggle Mute Audio"),e.classList.add("red5pro-media-control-element"),e.classList.add("red5pro-media-element-button"),e.classList.add("red5pro-media-muteunmute-button"),e.addEventListener("click",()=>{this.getMutedState()?(this._player.unmute(),this.setMutedState(!1)):(this._player.mute(),this.setMutedState(!0))}),e}_createVolumeControl(){const e=new Ei("volume");return e.view.classList.add("red5pro-media-control-element"),e.view.classList.add("red5pro-media-volume-slider"),e.view.classList.add("red5pro-media-slider"),e.on(li.CHANGE,e=>{const t=Number(e.data);this._player.setVolume(t)}),e}_createSeekControl(){const e=new Ei("seek");return e.view.classList.add("red5pro-media-control-element"),e.view.classList.add("red5pro-media-seektime-slider"),e.view.classList.add("red5pro-media-slider"),e.on(li.CHANGE_START,()=>{this.getState()===i.PLAYING&&(this._resumeAfterSeek=!0,this._player.pause(!0,!0)),this.trigger(new Se(ri.SEEK_START))}),e.on(li.CHANGE,e=>{const t=Number(e.data);this._player.seekTo(t,0===this._playbackDuration?void 0:this._playbackDuration),this.setSeekTime(t*this._playbackDuration,this._playbackDuration)}),e.on(li.CHANGE_COMPLETE,()=>{this._resumeAfterSeek&&this.getState()===i.PAUSED&&(this._resumeAfterSeek=!1,this._player.resume(!0)),this.trigger(new Se(ri.SEEK_END))}),e}_createPlaybackTime(){const e=Si("span"),t=Si("text");return t.textContent="00:00",e.classList.add("red5pro-media-control-element"),e.classList.add("red5pro-media-time-field"),e.appendChild(t),e}_createFullScreenToggle(){const e=Si("button");return e.setAttribute("aria-label","Toggle Fullscreen"),e.classList.add("red5pro-media-control-element"),e.classList.add("red5pro-media-element-button"),e.classList.add("red5pro-media-fullscreen-button"),e.addEventListener("click",()=>{this._player.toggleFullScreen()}),e}_formatTime(e){const t=new Date(1e3*e);return`${String(t.getUTCHours()).padStart(2,"0")}:${String(t.getUTCMinutes()).padStart(2,"0")}:${String(t.getUTCSeconds()).padStart(2,"0")}`}onStateChange(e){var t,n,s,o;return e===i.PLAYING?(null===(t=this._playPauseButton)||void 0===t||t.classList.remove("red5pro-media-play-button"),null===(n=this._playPauseButton)||void 0===n||n.classList.add("red5pro-media-pause-button")):(null===(s=this._playPauseButton)||void 0===s||s.classList.add("red5pro-media-play-button"),null===(o=this._playPauseButton)||void 0===o||o.classList.remove("red5pro-media-pause-button")),this}onMutedStateChange(e){var t,i,n,s;return e?(null===(t=this._muteButton)||void 0===t||t.classList.add("red5pro-media-mute-button"),null===(i=this._muteButton)||void 0===i||i.classList.remove("red5pro-media-unmute-button"),this._volumeField&&(this._volumeField.value=0)):(null===(n=this._muteButton)||void 0===n||n.classList.remove("red5pro-media-mute-button"),null===(s=this._muteButton)||void 0===s||s.classList.add("red5pro-media-unmute-button"),this._volumeField&&(this._volumeField.value=this._volumeValue)),this}onFullScreenChange(e){var t,i,n,s;return e?(null===(t=this._fullScreenButton)||void 0===t||t.classList.add("red5pro-media-exit-fullscreen-button"),null===(i=this._fullScreenButton)||void 0===i||i.classList.remove("red5pro-media-fullscreen-button")):(null===(n=this._fullScreenButton)||void 0===n||n.classList.remove("red5pro-media-exit-fullscreen-button"),null===(s=this._fullScreenButton)||void 0===s||s.classList.add("red5pro-media-fullscreen-button")),this}enable(e){var t,i,n,s;return e?(null===(t=this._playPauseButton)||void 0===t||t.classList.remove("red5pro-media-element-button-disabled"),null===(i=this._playPauseButton)||void 0===i||i.addEventListener("click",this._onPlayPauseClickBound)):(null===(n=this._playPauseButton)||void 0===n||n.classList.add("red5pro-media-element-button-disabled"),null===(s=this._playPauseButton)||void 0===s||s.removeEventListener("click",this._onPlayPauseClickBound)),this}getVolume(){return this._volumeValue}setVolume(e){return this._volumeField&&(this._volumeField.value=e),this._volumeValue=e,0===e?this.setMutedState(!0):this.getMutedState()&&this.setMutedState(!1),this}setSeekTime(e,t=0){return this._seekTimeField&&(this._seekTimeField.value=0===t?0:e/t,0!==this._playbackDuration&&this._playbackDuration<=e&&(this._seekTimeField.value=1)),this._timeField&&(!isFinite(this._playbackDuration)&&bi()?this._timeField.innerText="Live Broadcast":this._timeField.innerText=this._formatTime(Math.floor(e))),this}setPlaybackDuration(e){return this._playbackDuration=e,this}getPlaybackDuration(){return this._playbackDuration}getState(){return this._state}setState(e){return fi(`[setState]: ${s[e]}`),this._state=e,this.onStateChange(this._state),this}setMutedState(e){return this._mutedState=e,this.onMutedStateChange(this._mutedState),this}getMutedState(){return"muted"in this._player?this._player.muted:this._mutedState}setAsVOD(e){return fi(`[setAsVOD]: ${e}`),this._seekTimeField&&(e?this._seekTimeField.disabled=!1:(this._seekTimeField.value=0,this._seekTimeField.disabled=!0)),this}detach(){this.enable(!1),this._controlbar&&this._controlbar.parentNode&&this._controlbar.parentNode.removeChild(this._controlbar),this._controlbar=void 0,this._container=void 0}}var yi,wi;!function(e){e[e.LIVE=0]="LIVE",e[e.VOD=1]="VOD"}(yi||(yi={})),function(e){e.LIVE="LiveSeek.LIVE",e.VOD="LiveSeek.VOD"}(wi||(wi={}));const Ai={[yi.LIVE]:wi.LIVE,[yi.VOD]:wi.VOD};var Ni;!function(e){e.LIVE_SEEK_UNSUPPORTED="WebRTC.LiveSeek.Unsupported",e.LIVE_SEEK_ERROR="WebRTC.LiveSeek.Error",e.LIVE_SEEK_ENABLED="WebRTC.LiveSeek.Enabled",e.LIVE_SEEK_DISABLED="WebRTC.LiveSeek.Disabled",e.LIVE_SEEK_LOADING="WebRTC.LiveSeek.FragmentLoading",e.LIVE_SEEK_LOADED="WebRTC.LiveSeek.FragmentLoaded",e.LIVE_SEEK_CHANGE="WebRTC.LiveSeek.Change"}(Ni||(Ni={}));const{createElement:Pi,findByQuerySelector:Li,createHLSClient:Ri,getHLSClientEventEnum:Ii}=ie,Oi="SourceHandlerSeekable",Di=e=>D(Oi,e),Hi=e=>k(Oi,e),ki=e=>H(Oi,e);class Mi extends Vt{constructor(e,t,i,n,s=!0){super(e,`${t}-Seekable`),this._hlsElementGenerated=!1,this._hlsRecoverFlop=!1,this._hlsRecoverAttempts=0,this._isFragLoading=!1,this._wallOffset=NaN,this._lastDurationUpdate=0,this._averageSegmentDuration=6,this._isSeekable=!1,this._isHLSPlaybackActive=!1,this._container=s?this._determineContainer(e):void 0,this._liveSeekConfig=i,this._hlsOptions=n,this._usePlaybackControls=s,this.onHLSDurationChange=this._onHLSDurationChange.bind(this),this.onHLSTimeUpdate=this._onHLSTimeUpdate.bind(this),this.onHLSPlay=this._onHLSPlay.bind(this),this.onHLSPause=this._onHLSPause.bind(this)}_determineContainer(e){if(e.parentNode&&e.parentNode.classList.contains("red5pro-media-container"))return e.classList.add("red5pro-media"),e.parentNode;{const t=e.parentNode,i=Pi("div");return i.classList.add("red5pro-media-container"),e.classList.add("red5pro-media"),t.insertBefore(i,e),t.removeChild(e),i.appendChild(e),i}}_generateHLSLivePlayback(e,t,i){const n=`${i}-hls-vod`;let s=Li(`#${n}`);return s||(s=Pi("video"),s.id=n,s.classList.add("red5pro-hls-vod"),s.classList.add("red5pro-media-background"),s.setAttribute("playsinline","playsinline"),s.style.width="100%",s.style.height="100%",s.style.display="none",e.insertBefore(s,t),this._hlsElementGenerated=!0),s}_onDurationChange(e){var t;Di("[videoelement:event] durationchange");const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();!this.isSeekable&&n&&n.setPlaybackDuration(i.duration)}_onTimeUpdate(e){var t;const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();if(this.isSeekable){if(!this._isHLSPlaybackActive){const e=this._hlsElement.duration,t=i.currentTime-this._lastDurationUpdate,s=isNaN(e)||0===e?i.currentTime:e+this._averageSegmentDuration+t;n&&n.setSeekTime(s,s),this.trigger(new be(Ne.PLAYBACK_TIME_UPDATE,void 0,{time:s,duration:s,action:"rtc time update (1)"}))}}else super._onTimeUpdate(e)}_onEnded(){this.isHLSPlaybackActive||super._onEnded()}_onHLSDurationChange(e){const t=e.target,i=e.duration||t.duration;isNaN(this._wallOffset)&&(this._wallOffset=i-this._view.currentTime),this._lastDurationUpdate=this._view.currentTime;const n=i+this._averageSegmentDuration;Di(`[HLS:videoelement:duration] ${i}, ${this._averageSegmentDuration}`);const s=this.getControls();s&&s.setPlaybackDuration(n),this._isHLSPlaybackActive?this.trigger(new be(Ne.PLAYBACK_TIME_UPDATE,void 0,{time:t.currentTime,duration:n,action:"hls time update"})):this.trigger(new be(Ne.PLAYBACK_TIME_UPDATE,void 0,{time:n,duration:n,action:"hls time update"}))}_onHLSTimeUpdate(e){const t=e.target,i=this.getControls();i&&i.setSeekTime(t.currentTime,i.getPlaybackDuration()),t.currentTime>=t.duration?this._showHLSLivePlayback(!1,this._hlsElement,this._view,this._container):!isNaN(t.duration)&&this._isHLSPlaybackActive&&this.trigger(new be(Ne.PLAYBACK_TIME_UPDATE,void 0,{time:t.currentTime,duration:t.duration+this._averageSegmentDuration,action:"hls time update"}))}_onHLSPlay(){Di("[HLS:videoelement:event] play");const e=this.getControls();e&&e.setState(i.PLAYING),this.trigger(new be(Ne.PLAYBACK_STATE_CHANGE,void 0,{code:i.PLAYING,state:s[i.PLAYING]}))}_onHLSPause(){Di("[HLS:videoelement:event] pause");const e=this.getControls();e&&e.setState(i.PAUSED),this.trigger(new be(Ne.PLAYBACK_STATE_CHANGE,void 0,{code:i.PAUSED,state:s[i.PAUSED]}))}_addSeekableHandlers(e,t,i){if(t){const i=Ii();t.on(i.ERROR,(i,n)=>{const{type:s,details:o,fatal:a,url:r}=n;if("networkerror"===s.toLowerCase()){if("levelemptyerror"===o.toLowerCase()){this.trigger(new be(Ni.LIVE_SEEK_DISABLED,void 0,{hlsElement:e,hlsControl:t})),this.isSeekable=!1,t.destroy();const i=setTimeout(()=>{clearTimeout(i),this.enableLiveSeek(r,this._subscriptionId,this._hlsElement,!1)},3e3);return}this.trigger(new be(Ni.LIVE_SEEK_ERROR,void 0,{hlsElement:e,hlsControl:t,error:n}))}else this.trigger(new be(Ni.LIVE_SEEK_ERROR,void 0,{hlsElement:e,hlsControl:t,error:n}));"mediaerror"===s.toLowerCase()&&(this._hlsRecoverFlop&&t.swapAudioCodec(),this._hlsRecoverFlop=!this._hlsRecoverFlop,this._hlsRecoverAttempts=this._hlsRecoverAttempts+1,t.recoverMediaError()),a&&"networkerror"===s.toLowerCase()&&t.startLoad()}),t.on(i.MANIFEST_PARSED,()=>{try{e.pause()}catch(e){Di(`Could not pause seekable live stream: ${e.message}`)}this.isSeekable=!0,this.trigger(new be(Ni.LIVE_SEEK_ENABLED,void 0,{hlsElement:e,hlsControl:t}))}),t.on(i.FRAG_LOADING,(i,n)=>{const{frag:{stats:{loaded:s,total:o}}}=n;this.trigger(new be(Ni.LIVE_SEEK_LOADING,void 0,{hlsElement:e,hlsControl:t,progress:s/o*100})),(this._isHLSPlaybackActive||this._isFragLoading)&&(this._isFragLoading=s/o>=1)}),t.on(i.FRAG_LOADED,(i,n)=>{this._isFragLoading=!1;const{frag:{endDTS:s,loader:o}}=n;if(!this._isHLSPlaybackActive&&!s)return;let a=6,r=0;if(o&&o.stats&&o.stats.segments){const e=o.stats.segments;for(let t=0;t<e.length;t++)r+=e[t].duration;a=r/e.length,this._averageSegmentDuration=a}Di(`fragload, [HLS:videoelement:duration] ${s} + ${a}`),this.trigger(new be(Ni.LIVE_SEEK_LOADED,void 0,{hlsElement:e,hlsControl:t}))}),t.on(i.FRAG_PARSED,(i,n)=>{this._isFragLoading=!1;const{frag:{endDTS:s,loader:o}}=n;if(!this._isHLSPlaybackActive&&!s)return;let a=6,r=0;if(o&&o.stats&&o.stats.segments){const e=o.stats.segments;for(let t=0;t<e.length;t++)r+=e[t].duration;a=r/e.length,this._averageSegmentDuration=a}Di(`fragparsed, [HLS:videoelement:duration] ${s} + ${a}`),this.trigger(new be(Ni.LIVE_SEEK_LOADED,void 0,{hlsElement:e,hlsControl:t}))})}i&&e.addEventListener("durationchange",this.onHLSDurationChange),e.addEventListener("timeupdate",this.onHLSTimeUpdate),e.addEventListener("play",this.onHLSPlay),e.addEventListener("pause",this.onHLSPause)}_removeSeekableHandlers(e,t){if(t){const e=Ii();t.off(e.ERROR),t.off(e.MANIFEST_PARSED),t.off(e.FRAG_LOADING),t.off(e.FRAG_LOADED),t.off(e.FRAG_PARSED)}e&&(e.removeEventListener("durationchange",this.onHLSDurationChange),e.removeEventListener("timeupdate",this.onHLSTimeUpdate),e.removeEventListener("play",this.onHLSPlay),e.removeEventListener("pause",this.onHLSPause))}_showHLSLivePlayback(e,t,i,n){if(this._isHLSPlaybackActive===e)return;this._isHLSPlaybackActive=e;const s=e?i.muted:t.muted;if(e){t.volume=i.volume,t.muted=s,i.muted=!0,t.style.display="inline-block",n.style.position="relative";try{i.paused?this.pause(!1):(this.pause(!0),this.play())}catch(e){ki(`Could not start playback: ${e.message}.`)}this._hlsElementGenerated&&(i.style.display="none")}else{i.volume=t.volume,t.muted=!0,i.muted=s,i.style.display="inline-block";try{t.paused?this.pause(!1):(this.pause(!0),this.play())}catch(e){ki(`Could not start playback: ${e.message}.`)}this._hlsElementGenerated&&(t.style.display="none")}const o=e?yi.VOD:yi.LIVE;this.trigger(new be(Ni.LIVE_SEEK_CHANGE,void 0,{code:o,state:Ai[o]}))}async _loadManifest(e,t){clearTimeout(this._manifestLoadTimeout);const i=/^#EXT-X-TARGETDURATION:(.*)/,n=/^.*_(.*)\.\.*/;try{const s=await fetch(e,{method:"GET",mode:"cors",cache:"no-cache",headers:{"Content-Type":"text/plain;charset=UTF-8"}}),o=(await s.text()).split("\r\n");if(!o)return void ki(`Could not find lines in manifest: ${e}`);const a=o.reverse().find(e=>n.test(e));if(!a)return void ki(`Could not find last segment in manifest: ${e}`);const r=o.find(e=>i.test(e));if(!r)return void ki(`Could not find duration line in manifest: ${e}`);const l=r.match(i);if(!l)return void ki(`Could not find duration in manifest: ${e}`);const d=l[1],h=parseFloat(d),c=a.match(n);if(!c)return void ki(`Could not find segment length in manifest: ${e}`);const u=c[1];let p=parseInt(u,10);isNaN(p)&&(p=1),p=p>1?p-1:p,this._averageSegmentDuration=h,this.isSeekable=!0,this.trigger(new be(Ni.LIVE_SEEK_ENABLED,void 0,{hlsElement:this._hlsElement,hlsControl:void 0})),this.onHLSDurationChange({target:t,duration:h*p}),this._manifestLoadTimeout=setTimeout(()=>{clearTimeout(this._manifestLoadTimeout),this._loadManifest(e,t)},1e3*h)}catch(e){Hi(`Could not load manifest: ${e.message}.`),this.trigger(new be(Ni.LIVE_SEEK_DISABLED,void 0,{hlsElement:t,hlsControl:void 0})),this.isSeekable=!1}}_cleanup(){this._removeSeekableHandlers(this._hlsElement,this._hlsjsRef),this._hlsjsRef&&(this._hlsjsRef.detachMedia(),this._hlsjsRef=void 0),this._hlsElement&&(this._hlsElement.parentNode&&this._hlsElementGenerated&&this._hlsElement.parentNode.removeChild(this._hlsElement),this._hlsElement=void 0),this._playbackControls&&(this._playbackControls.detach(),this._playbackControls=void 0),this._isVOD=!1,this._isSeekable=!1,this._isHLSPlaybackActive=!1,this._isFragLoading=!1,this._hlsRecoverFlop=!1,this._hlsRecoverAttempts=0,this._averageSegmentDuration=6,this._hlsElementGenerated=!1,this._wallOffset=NaN,this._lastDurationUpdate=0,this._manifestLoadTimeout&&(clearTimeout(this._manifestLoadTimeout),this._manifestLoadTimeout=void 0),super._cleanup()}addSource(){Di("[addSource]"),this._view.controls=!0,this._view.classList.add("red5pro-media");this._view.hasAttribute("controls")&&this._view.classList.contains("red5pro-media")&&(this._container=this._determineContainer(this._view));const e=this._view.hasAttribute("muted");this._usePlaybackControls?(this._playbackControls=new Ti(this,this._container),this._view.controls=!1,this._playbackControls.setAsVOD(this.isSeekable),this._playbackControls.setMutedState(e)):this._view.controls=!1}enableLiveSeek(e,t,i,n=!1){if(this.getControls()&&this.getControls().setSeekTime(1,1),this._url=e,this._subscriptionId=t,this._hlsElement=i||this._generateHLSLivePlayback(this._container,this._view,t),this._showHLSLivePlayback(this._isHLSPlaybackActive,this._hlsElement,this._view,this._container),n){this._addSeekableHandlers(this._hlsElement,void 0,!1);const t=Pi("source");t.src=e,this._hlsElement.appendChild(t),this._loadManifest(e,this._hlsElement)}else{const t=this._hlsOptions,{liveSeek:{hlsjsRef:i}}=this._liveSeekConfig,n=i?new i(t):Ri(t);this._addSeekableHandlers(this._hlsElement,n,!0),n.attachMedia(this._hlsElement,e),n.on(Ii().MEDIA_ATTACHED,()=>{n.loadSource(e)}),this._hlsjsRef=n}}switchLiveSeek(e){this._hlsjsRef&&(this._hlsjsRef.destroy(),this._hlsjsRef=void 0),this.enableLiveSeek(e,this._subscriptionId,this._hlsElement),this.seekTo(1);try{this._view.play()}catch(e){ki("[videoelement:action] play (FAULT) - "+e.message)}this._url=e}async play(e=!1){Di("[videoelement:action] play");try{return e&&this._hlsElement&&this._hlsElement.paused?(await this._hlsElement.play(),!0):super.play()}catch(e){ki("[videoelement:action] play (CATCH::FAULT) - "+e.message)}return!1}async pause(e=!1,t=!1){Di("[videoelement:action] pause");try{return e&&t&&this._hlsElement?(this._hlsElement.pause(),super.pause()):e&&this._hlsElement&&!this._hlsElement.paused?(this._hlsElement.pause(),!0):super.pause()}catch(e){ki("[videoelement:action] pause (CATCH::FAULT) - "+e.message)}return!1}async resume(e=!1){var t,i;Di("[videoelement:action] resume");try{const n=this._isHLSPlaybackActive&&this._hlsElement?this._hlsElement.play():null===(t=this._view)||void 0===t?void 0:t.play();if(e&&this._isHLSPlaybackActive)return await(null===(i=this._view)||void 0===i?void 0:i.play()),!0;n&&n.then(()=>Di("[videoelement:action] play (START)")).catch(e=>ki("[videoelement:action] play (CATCH::FAULT) "+(e.message?e.message:e)))}catch(e){ki("[videoelement:action] resume (CATCH::FAULT) - "+e.message)}return!1}async stop(){Di("[videoelement:action] stop");try{return this._hlsElement&&this._hlsElement.pause(),super.stop()}catch(e){ki("[videoelement:action] stop (CATCH::FAULT) - "+e.message)}return!1}mute(){this._hlsElement&&(this._hlsElement.muted=this._isHLSPlaybackActive),this._view&&(this._view.muted=!0);const e=this.getControls();e&&e.setMutedState(!0)}unmute(){this._hlsElement&&(this._hlsElement.muted=!this._isHLSPlaybackActive,this._view&&(this._view.muted=this._isHLSPlaybackActive)),this._view&&(this._view.muted=!1);const e=this.getControls();e&&e.setMutedState(!1)}setVolume(e){this.unmute(),this._hlsElement&&this._isHLSPlaybackActive?this._hlsElement.volume=e:this._view?this._view.volume=e:Hi("[videoelement:action] setVolume (CATCH::FAULT) - "+e)}seekTo(e,t=void 0){if(this.isSeekable)if(this.getControls()&&this.getControls().setSeekTime(e,t),this.trigger(new be(Ni.LIVE_SEEK_CHANGE,void 0,{seek:e,duration:t})),this._hlsElement&&e<1)try{this._hlsElement.classList.remove("hidden"),this._hlsElement.currentTime=this._hlsElement.duration*e,this._isFragLoading=!0,this._showHLSLivePlayback(!0,this._hlsElement,this._view,this._container),this._view.paused||(Di("[hlsvod:action] play (START) - (seekTo)"),this.play(!0))}catch(e){ki("[hlsvod:action] play (CATCH::FAULT) - "+e.message)}else this._hlsElement&&e>=1&&(this._isFragLoading=!1,this._showHLSLivePlayback(!1,this._hlsElement,this._view,this._container));else this._view.currentTime=t?e*t:e}toggleFullScreen(e){var t;this._container&&super.toggleFullScreen(null!==(t=this._container)&&void 0!==t?t:e)}getControls(){return this._playbackControls}get isSeekable(){return this._isSeekable}set isSeekable(e){this._isSeekable=e,this.getControls()&&this.getControls().setAsVOD(e)}get isHLSPlaybackActive(){return this._isHLSPlaybackActive}get url(){return this._url}}const{supportsHLS:Ui,supportsNonNativeHLS:Bi}=ie,Vi="WHEPLiveSeekClient",Fi=e=>k(Vi,e);class $i extends zt{constructor(e,t,i){super(e,t,i)}async init(e){const{liveSeek:t}=e;return t||(e.liveSeek=si),super.init(e)}_attachSourceHandler(e){var t;if((null===(t=this._playbackView)||void 0===t?void 0:t.view)&&!this._enableLiveSeek(this._playbackView.view))return H(Vi,"LiveSeek is not enabled, using default source handler"),void super._attachSourceHandler(e);this._startSeekableIfSeekableEnabled(this._options)}_enableLiveSeek(e){const{liveSeek:t}=this._options;if(t){const{hlsjsRef:i,usePlaybackControlsUI:n,options:s}=t;if(Ui()||Bi(i))return this._sourceHandler=new Mi(e,this.getType(),this._options,s,n),this._sourceHandler.addSource(),!0;Fi("Could not utilize the 'LiveSeek' request. This feature requires either native HLS playback or hls.js as a depenency."),this.trigger(new be(Ni.LIVE_SEEK_UNSUPPORTED,this,{feature:"Live Seek",message:"Live Seek requires integration with the HLS.JS plugin in order work properly. Most likely you are viewing this on a browser that does not support the use of HLS.JS."}))}return!1}_startSeekableIfSeekableEnabled(e){const{liveSeek:t,subscriptionId:i}=e;if(!t)return;const{hlsjsRef:n,hlsElement:s}=t;if(this._sourceHandler)try{if(!Ui()&&!Bi(n))throw new Error;{const t=ne(e);this._sourceHandler.enableLiveSeek(t,i,s,!Bi(n))}}catch(e){Fi("Could not utilize the 'LiveSeek' request. This feature requires either native HLS playback or hls.js as a depenency.")}}_onUnpublish(){super._onUnpublish();const{liveSeek:e}=this._options;e||this.unsubscribe(!0)}_onStreamSwitchComplete(){const e=this._requestedStreamSwitch,{liveSeek:t}=this._options;if(t&&e){const{baseURL:i,fullURL:n}=t,s=e.split("/"),o=s.pop(),a=s.join("/"),r={...this._options,app:a,streamName:o};let l=n;if(n){const e=/.*\/(.*)\.m3u8/.exec(n);if(e&&e.length>1){const t=`${e[1]}.m3u8`;l=n.replace(t,`${o}.m3u8`)}}const d=ne(r,i,l);this._sourceHandler&&this._sourceHandler.switchLiveSeek(d)}super._onStreamSwitchComplete()}}const Gi="15.6.1";R(L.ERROR);const xi=(e,t=!1)=>{Object.prototype.hasOwnProperty.call(L,e.toUpperCase())&&(R(e,t),console&&console.log(`Red5 Pro SDK Version ${Wi()}`))},Wi=()=>Gi;D("RED5",`Red5 Pro HTML SDK Version: ${Gi}`);var zi={version:Gi,LOG_LEVELS:L,getLogger:I,getRecordedLogs:O,setLogLevel:xi,getVersion:Wi,PlaybackVideoEncoder:t,PlaybackAudioEncoder:e,PlaybackState:i,PlaybackStateReadableMap:s,PublishVideoEncoder:l,PublishAudioEncoder:r,SubscriberEvent:be,PublisherEvent:Ce,MessageTransportStateEvent:fe,PubNubEvent:Te,MessageChannelEvent:ye,PublisherEventTypes:we,SubscriberEventTypes:Ne,RTCPublisherEventTypes:Ae,RTCSubscriberEventTypes:Pe,MessageTransportStateEventTypes:Le,MessageChannelEventTypes:Ie,WebRTCConnectionEventTypes:Re,PubNubEventTypes:ut,WHIPClient:At,WHEPClient:zt,HLSSubscriber:ni,LiveSeekClient:$i,PubNubClient:Ct,MessageChannel:Qt,Capability:Kt,defaultWhepSubscriberConfig:Nt,defaultWhipPublisherConfig:me,defaultStatsConfig:ge,StatsEndpointType:_e};export{Kt as Capability,Se as Event,U as EventEmitter,ni as HLSSubscriber,L as LOG_LEVELS,$i as LiveSeekClient,Qt as MessageChannel,ye as MessageChannelEvent,Ie as MessageChannelEventTypes,fe as MessageTransportStateEvent,Le as MessageTransportStateEventTypes,e as PlaybackAudioEncoder,kt as PlaybackController,ai as PlaybackControls,i as PlaybackState,s as PlaybackStateReadableMap,t as PlaybackVideoEncoder,Ct as PubNubClient,Te as PubNubEvent,ut as PubNubEventTypes,r as PublishAudioEncoder,l as PublishVideoEncoder,Ce as PublisherEvent,we as PublisherEventTypes,Ae as RTCPublisherEventTypes,Pe as RTCSubscriberEventTypes,Mt as SourceHandler,Vt as SourceHandlerImpl,_e as StatsEndpointType,be as SubscriberEvent,Ne as SubscriberEventTypes,zt as WHEPClient,At as WHIPClient,Re as WebRTCConnectionEventTypes,zi as default,Pt as defaultHLSSubscriberConfig,oi as defaultLiveSeekConfig,ge as defaultStatsConfig,Nt as defaultWhepSubscriberConfig,me as defaultWhipPublisherConfig,I as getLogger,O as getRecordedLogs,Wi as getVersion,xi as setLogLevel};