-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathred5pro-sdk.min.js
More file actions
34 lines (33 loc) · 159 KB
/
Copy pathred5pro-sdk.min.js
File metadata and controls
34 lines (33 loc) · 159 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.
*
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).red5prosdk={})}(this,function(e){"use strict";var t,i,n,s;e.PlaybackAudioEncoder=void 0,(t=e.PlaybackAudioEncoder||(e.PlaybackAudioEncoder={})).OPUS="OPUS",t.NONE="NONE",e.PlaybackVideoEncoder=void 0,(i=e.PlaybackVideoEncoder||(e.PlaybackVideoEncoder={})).VP8="VP8",i.H264="H264",i.H265="H265",i.AV1="AV1",i.NONE="NONE",e.PlaybackState=void 0,(n=e.PlaybackState||(e.PlaybackState={}))[n.UNAVAILABLE=1e3]="UNAVAILABLE",n[n.AVAILABLE=0]="AVAILABLE",n[n.IDLE=1]="IDLE",n[n.PLAYING=2]="PLAYING",n[n.PAUSED=3]="PAUSED",function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(s||(s={}));const o={[e.PlaybackState.UNAVAILABLE]:s.UNAVAILABLE,[e.PlaybackState.AVAILABLE]:s.AVAILABLE,[e.PlaybackState.IDLE]:s.IDLE,[e.PlaybackState.PLAYING]:s.PLAYING,[e.PlaybackState.PAUSED]:s.PAUSED};var a,r,l;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(a||(a={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(r||(r={})),e.PublishAudioEncoder=void 0,(e.PublishAudioEncoder||(e.PublishAudioEncoder={})).OPUS="OPUS",e.PublishVideoEncoder=void 0,(l=e.PublishVideoEncoder||(e.PublishVideoEncoder={})).VP8="VP8",l.H264="H264",l.H265="H265",l.AV1="AV1";var h={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},d={};function c(e){return"string"==typeof e?h[e.toLowerCase()]:e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function p(e,t,i){return p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,i){var n=[null];n.push.apply(n,t);var s=new(Function.bind.apply(e,n));return i&&u(s,i.prototype),s},p.apply(null,arguments)}function _(e){if(null==e)return e;if(Array.isArray(e))return e.slice();if("object"==typeof e){var t={};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t}return e}function g(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"[ "+e.map(function(e){return g(e)}).join(", ")+" ]":"object"==typeof e?JSON.stringify(e):"function"==typeof e?"[Function: "+e.name+"]":"boolean"==typeof e||"number"==typeof e?e:"'"+e.toString()+"'"}function v(e){if("string"!=typeof e){for(var t=new Array(arguments.length),i=0;i<arguments.length;i++)t[i]=g(arguments[i]);return t.join(" ")}for(var n=1,s=arguments,o=s.length,a=String(e).replace(/%[sdj%]/g,function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(s[n++]);case"%d":return Number(s[n++]);case"%j":try{return JSON.stringify(s[n++])}catch(e){return"[Circular]"}default:return e}}),r=s[n];n<o;r=s[++n])a+=null===r||"object"!=typeof r?" "+r:" "+g(r);return a}Object.keys(h).forEach(function(e){d[h[e]]=e});var m={};function E(e,t){if(t){if(m[t])return;m[t]=!0}console.error(e+"\n")}var b=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}(),S=function(){function e(t,i,n){var s,o,a,r,l=this;if(!(this instanceof e))return new e(t,i);if(void 0!==i&&(s=t,t=i,!(s instanceof e)))throw new TypeError("invalid Logger creation: do not pass a second arg");if(!t)throw new TypeError("options (object) is required");if(s){if(t.name)throw new TypeError("invalid options.name: child cannot set logger name")}else if(!t.name)throw new TypeError("options.name (string) is required");if(t.stream&&t.streams)throw new TypeError('cannot mix "streams" and "stream" options');if(t.streams&&!Array.isArray(t.streams))throw new TypeError("invalid options.streams: must be an array");if(t.serializers&&("object"!=typeof t.serializers||Array.isArray(t.serializers)))throw new TypeError("invalid options.serializers: must be an object");if(s&&n){this._level=s._level,this.streams=s.streams,this.serializers=s.serializers,this.src=s.src,o=this.fields={};var h=Object.keys(s.fields);for(r=0;r<h.length;r++)o[a=h[r]]=s.fields[a];var d=Object.keys(t);for(r=0;r<d.length;r++)o[a=d[r]]=t[a]}else{if(s){for(this._level=s._level,this.streams=[],r=0;r<s.streams.length;r++){var c=_(s.streams[r]);this.streams.push(c)}this.serializers=_(s.serializers),this.src=s.src,this.fields=_(s.fields),t.level&&this.level(t.level)}else this._level=Number.POSITIVE_INFINITY,this.streams=[],this.serializers=null,this.src=!1,this.fields={};t.stream?this.addStream({type:"stream",stream:t.stream,level:t.level}):t.streams?t.streams.forEach(function(e){l.addStream(e,t.level)}):s&&t.level?this.level(t.level):s||this.addStream({type:"raw",stream:new b,level:t.level}),t.serializers&&this.addSerializers(t.serializers),t.src&&(this.src=!0),delete(o=_(t)).stream,delete o.level,delete o.streams,delete o.serializers,delete o.src,this.serializers&&this._applySerializers(o),Object.keys(o).forEach(function(e){l.fields[e]=o[e]})}}var t=e.prototype;return t.addStream=function(e,t){void 0===t&&(t=30),(e=_(e)).type="raw",e.level=c(e.level||t),e.level<this._level&&(this._level=e.level),this.streams.push(e),delete this.haveNonRawStreams},t.addSerializers=function(e){var t=this;this.serializers||(this.serializers={}),Object.keys(e).forEach(function(i){var n=e[i];if("function"!=typeof n)throw new TypeError(v('invalid serializer for "%s" field: must be a function',i));t.serializers[i]=n})},t.child=function(e,t){return new this.constructor(this,e||{},t)},t.level=function(e){if(void 0===e)return this._level;for(var t=c(e),i=this.streams.length,n=0;n<i;n++)this.streams[n].level=t;this._level=t},t.levels=function(e,t){if(void 0===e)return this.streams.map(function(e){return e.level});var i;if("number"==typeof e){if(void 0===(i=this.streams[e]))throw new Error("invalid stream index: "+e)}else{for(var n=this.streams.length,s=0;s<n;s++){var o=this.streams[s];if(o.name===e){i=o;break}}if(!i)throw new Error(v('no stream with name "%s"',e))}if(void 0===t)return i.level;var a=c(t);i.level=a,a<this._level&&(this._level=a)},t._applySerializers=function(e,t){var i=this;Object.keys(this.serializers).forEach(function(n){if(!(void 0===e[n]||t&&t[n]))try{e[n]=i.serializers[n](e[n])}catch(t){E(v('bunyan: ERROR: Exception thrown from the "%s" Bunyan serializer. This should never happen. This is a bugin that serializer function.\n%s',n,t.stack||t)),e[n]=v('(Error in Bunyan log "%s" serializer broke field. See stderr for details.)',n)}})},t._emit=function(e,t){var i,n;if(void 0===this.haveNonRawStreams)for(this.haveNonRawStreams=!1,i=0;i<this.streams.length;i++)if(!this.streams[i].raw){this.haveNonRawStreams=!0;break}if(t||this.haveNonRawStreams)try{n=JSON.stringify(e,function(){var e=[];return function(t,i){return i&&"object"==typeof i?-1!==e.indexOf(i)?"[Circular]":(e.push(i),i):i}}())+"\n"}catch(t){var s=t.stack.split(/\n/g,2).join("\n");E('bunyan: ERROR: Exception in `JSON.stringify(rec)`. You can install the "safe-json-stringify" module to have Bunyan fallback to safer stringification. Record:\n'+function(e,t){return t||(t=" "),t+e.split(/\r?\n/g).join("\n"+t)}(v("%s\n%s",e,t.stack)),s),n=v("(Exception in JSON.stringify(rec): %j. See stderr for details.)\n",t.message)}if(t)return n;var o=e.level;for(i=0;i<this.streams.length;i++){var a=this.streams[i];a.level<=o&&a.stream.write(e)}return n},e}();function C(e){return function(){var t=this;var i=null,n=arguments,s=null;if(0===arguments.length)return this._level<=e;this._level>e||(s=function(s){var o;s[0]instanceof Error?(i={err:t.serializers&&t.serializers.err?t.serializers.err(s[0]):y.err(s[0])},o={err:!0},n=1===s.length?[i.err.message]:Array.prototype.slice.call(s,1)):"object"!=typeof s[0]&&null!==s[0]||Array.isArray(s[0])?(i=null,n=Array.prototype.slice.call(s)):(i=s[0],n=1===s.length&&i.err&&i.err instanceof Error?[i.err.message]:Array.prototype.slice.call(s,1));var a=_(t.fields);a.level=e;var r=i?_(i):null;if(r&&(t.serializers&&t._applySerializers(r,o),Object.keys(r).forEach(function(e){a[e]=r[e]})),a.levelName=d[e],a.msg=n.length?v.apply(t,n):"",a.time||(a.time=new Date),t.src&&!a.src)try{throw new Error("call-stack-error")}catch(e){var l=e.stack?function(e,t){var i=e.split("\n");i[0]&&i[0].indexOf("call-stack-error")>=0&&i.shift();var n=i[t],s=null;if(n){var o=/^\s*(at|.*@)\s*(.+)?$/.exec(n);s=Array.isArray(o)&&o[2]?o[2]:n}return s}(e.stack,2):"";l||function(e){return m[e]}("src")||E("Unable to determine src line info","src"),a.src=l||""}return a.v=1,a}(n),this._emit(s))}}function T(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var i=e.cause();i&&(t+="\nCaused by: "+T(i))}return t}S.prototype.trace=C(10),S.prototype.debug=C(20),S.prototype.info=C(30),S.prototype.warn=C(40),S.prototype.error=C(50),S.prototype.fatal=C(60);var y={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:T(e),code:e.code,signal:e.signal}:e}};const f={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class A{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,f[e.level]||"UNKNOWN",e.msg)}}let w,P;const N=e=>(t,i)=>{var n;w&&"function"==typeof w[e]&&w[e]((n=t,e=>`(${n}) ${e}`)(i))},R={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},L=(e,t=!1,i)=>{const n=[{level:e,stream:new A,type:"raw"}];if(i){const t=i.map(t=>({...t,level:e}));n.push(...t)}t&&(P=[],n.push({level:e,stream:{write:t=>{const i=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==P||P.push(i)}},type:"raw"}));w=function(){return p(S,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:n})},I=()=>(w||L(R.INFO),w),O=()=>P||[];N(R.TRACE),N(R.INFO);const D=N(R.DEBUG),k=N(R.WARN),H=N(R.ERROR);N(R.FATAL);const M="RED5PRO";class U{constructor(){this._callbacks={},this._callbacks[M]=[]}_notify(e,t){let i;const n=e.length;for(i=0;i<n;i++)e[i](t)}on(e,t){"function"==typeof t&&("*"!==e?(void 0===this._callbacks[e]&&(this._callbacks[e]=[]),-1===this._callbacks[e].indexOf(t)&&this._callbacks[e].push(t)):this._callbacks[M].push(t))}off(e,t){let i=this._callbacks[e];if("*"===e&&(i=this._callbacks[M]),i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}trigger(e){const t=e.type;this._callbacks[t]&&this._notify(this._callbacks[t],e),this._notify(this._callbacks[M],e)}}const B=/['"](.*?)['"]:/gi,V=/:['"](.*?)['"]/gi,F=new WeakMap;function $(e,t,i){let n="",s=t;const o=t+i;do{n+=String.fromCharCode(e[s++])}while(s<o);return n}function G(e,t){try{return JSON.parse(e)[t]}catch(i){const n=B.exec(e);let s;return n&&n.length>1&&(s=V.exec(e),n[1]===t&&s&&s.length>1)?s[1]:void 0}}function x(e){const t=G(e,"orientation");if(t)return{orientation:parseInt(t)}}function W(e){const t=G(e,"streamingMode");if(t)return{streamingMode:t}}const 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=>k(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:h}=e;if(i||s)return i||s;const d=o,c="ws"===a?"http":"https",u=5080===r?5080:443,p=l,_=t||n;if(_){const e=_.length-1;return`${"/"===_.charAt(e)?_.substring(0,e):_}/${p}/${h}.m3u8`}return`${c}://${d}:${u}/${p}/${h}.m3u8`},se=e=>{const t=new URL(e),i=t.pathname.split("/").filter(e=>e.length>0),n="https:"===t.protocol?"https":"http",s=t.hostname;return{protocol:n,port:t.port.length>0?t.port:443,app:i[0],host:s,streamName:i[i.length-1]}},oe=(e,t="whip")=>{var i;const{endpoint:n,proxy:s}=e;if(n)return n;{const{protocol:n,host:o,port:a,app:r,streamName:l}=e,h=n.match(/^http/)?n:"ws"===n?"http":"https";return(null==s?void 0:s.enabled)?`${h}://${o}:${a}/as/${null!==(i=s.version)&&void 0!==i?i:"v1"}/proxy/${t}/${r}/${l}`:`${h}://${o}:${a}/${r}/${t}/endpoint/${l}`}},ae=e=>{const t={audio:!1,video:!1},i={audio:!1,video:!1};return e.getTracks().forEach(e=>{"video"===e.kind?(i.video=e.getSettings(),t.video=e.getConstraints()):"audio"===e.kind&&(i.audio=e.getSettings(),t.audio=e.getConstraints())}),{requested:t,accepted:i}},re=e=>{const t=e.length;return function i(...n){return n.length>=t?e(...n):function(...e){return i(...n,...e)}}},le=re((e,t)=>{let i=0;const n=t.length,s=[];for(;i<n;)e(t[i])&&(s[s.length]=t[i]),i+=1;return s});var he,de,ce,ue,pe,_e;!function(e){e.UDP="udp",e.TCP="tcp"}(he||(he={})),function(e){e.ENCODED_FRAME="EncodedFrame",e.PACKET="Packet"}(de||(de={})),function(e){e.VIDEO="encodeVideo",e.AUDIO="encodeAudio"}(ce||(ce={})),function(e){e.VIDEO="decodeVideo",e.AUDIO="decodeAudio"}(ue||(ue={})),function(e){e[e.FAILED=400]="FAILED",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.GONE=410]="GONE"}(pe||(pe={})),e.StatsEndpointType=void 0,(_e=e.StatsEndpointType||(e.StatsEndpointType={})).DEV_NULL="dev/null",_e.DATA_CHANNEL="data-channel",_e.EVENT_TRANSPORT="event-transport";const ge={endpoint:e.StatsEndpointType.DATA_CHANNEL,interval:5e3,include:[]},ve={...{protocol:"https",port:443,app:"live",streamMode:r.LIVE,keyFramerate:3e3,mediaElementId:"red5pro-publisher",rtcConfiguration:{iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:he.UDP,bandwidth:{audio:56,video:750},clearMediaOnUnpublish:!1,reconnect:void 0,mediaConstraints:{audio:!0,video:{width:{min:640,max:1920},height:{min:360,max:1080},frameRate:{min:30,max:60}}},dataChannelConfiguration:{name:"red5pro"},signalingSocketOnly:!1,includeDataChannel:!0,forceVP8:!1,videoEncoding:void 0,audioEncoding:void 0,stats:ge,pubnub:void 0},signalingSocketOnly:!1,enableChannelSignaling:!1,includeDataChannel:!0,disableProxy:!0,trickleIce:!0,mungeOffer:void 0,mungeAnswer:void 0,offerSDPResolution:!1},me={enabled:!1,timeout:2e3,maxAttempts:10};class Ee extends U{constructor(e){super(),this._name=e||"MessageTransport",this._responseHandlers=[],this._asyncTickets=[]}getJsonFromSocketMessage(e){try{return"string"==typeof e.data?JSON.parse(e.data):e.data}catch(t){k(this._name,"Could not parse message as JSON. Message= "+e.data+". Error= "+t.message)}return null}addResponseHandler(e){this._responseHandlers.push(e)}respond(e){k(this._name,`respond() should be overriden. Unhandled message: ${e}`)}post(e){return k(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 be=class{constructor(e,t){this._type=e,this._data=t}get type(){return this._type}get data(){return this._data}};class Se extends be{constructor(e,t,i){super(e,i),this._publisher=t}get publisher(){return this._publisher}}class Ce extends be{constructor(e,t,i){super(e,i),this._subscriber=t}get subscriber(){return this._subscriber}}class Te extends be{constructor(e,t,i){super(e,i),this._name=t}get name(){return this._name}}class ye extends be{constructor(e,t,i){super(e,i),this._pubnub=t}get pubnub(){return this._pubnub}}class fe extends be{constructor(e,t,i){super(e,i),this._messageChannel=t}get messageChannel(){return this._messageChannel}}var Ae,we,Pe,Ne,Re,Le,Ie;e.PublisherEventTypes=void 0,(Ae=e.PublisherEventTypes||(e.PublisherEventTypes={})).RECONNECT_START="Reconnect.Start",Ae.RECONNECT_FAILURE="Reconnect.Failure",Ae.RECONNECT_SUCCESS="Reconnect.Success",Ae.CONNECT_SUCCESS="Connect.Success",Ae.CONNECT_FAILURE="Connect.Failure",Ae.PUBLISH_START="Publish.Start",Ae.PUBLISH_FAIL="Publish.Fail",Ae.PUBLISH_INVALID_NAME="Publish.InvalidName",Ae.UNPUBLISH_SUCCESS="Unpublish.Success",Ae.PUBLISH_METADATA="Publish.Metadata",Ae.PUBLISH_STATUS="Publish.Status",Ae.PUBLISH_AVAILABLE="Publish.Available",Ae.PUBLISH_INSUFFICIENT_BANDWIDTH="Publish.InsufficientBW",Ae.PUBLISH_SUFFICIENT_BANDWIDTH="Publish.SufficientBW",Ae.PUBLISH_RECOVERING_BANDWIDTH="Publish.RecoveringBW",Ae.PUBLISH_SEND_INVOKE="Publish.Send.Invoke",Ae.CONNECTION_CLOSED="Publisher.Connection.Closed",Ae.DIMENSION_CHANGE="Publisher.Video.DimensionChange",Ae.STATISTICS_ENDPOINT_CHANGE="Publisher.StatisticsEndpoint.Change",e.RTCPublisherEventTypes=void 0,(we=e.RTCPublisherEventTypes||(e.RTCPublisherEventTypes={})).CONSTRAINTS_ACCEPTED="WebRTC.MediaConstraints.Accepted",we.CONSTRAINTS_REJECTED="WebRTC.MediaConstraints.Rejected",we.MEDIA_STREAM_AVAILABLE="WebRTC.MediaStream.Available",we.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",we.OFFER_START="WebRTC.Offer.Start",we.OFFER_END="WebRTC.Offer.End",we.CANDIDATE_CREATE="WebRTC.Candidate.Create",we.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",we.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",we.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",we.SOCKET_MESSAGE="WebRTC.Socket.Message",we.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",we.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",we.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",we.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",we.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",we.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",we.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",we.UNSUPPORTED_FEATURE="WebRTC.Unsupported.Feature",we.TRANSFORM_ERROR="WebRTC.Transform.Error",we.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",we.STATS_REPORT="WebRTC.Stats.Report",e.SubscriberEventTypes=void 0,(Pe=e.SubscriberEventTypes||(e.SubscriberEventTypes={})).RECONNECT_START="Reconnect.Start",Pe.RECONNECT_FAILURE="Reconnect.Failure",Pe.CONNECT_SUCCESS="Connect.Success",Pe.CONNECT_FAILURE="Connect.Failure",Pe.SUBSCRIBE_START="Subscribe.Start",Pe.SUBSCRIBE_STOP="Subscribe.Stop",Pe.SUBSCRIBE_FAIL="Subscribe.Fail",Pe.SUBSCRIBE_INVALID_NAME="Subscribe.InvalidName",Pe.SUBSCRIBE_METADATA="Subscribe.Metadata",Pe.SUBSCRIBE_STATUS="Subscribe.Status",Pe.SUBSCRIBE_SEND_INVOKE="Subscribe.Send.Invoke",Pe.SUBSCRIBE_PUBLISHER_CONGESTION="Subscribe.Publisher.NetworkCongestion",Pe.SUBSCRIBE_PUBLISHER_RECOVERY="Subscribe.Publisher.NetworkRecovery",Pe.PLAY_UNPUBLISH="Subscribe.Play.Unpublish",Pe.CONNECTION_CLOSED="Subscribe.Connection.Closed",Pe.ORIENTATION_CHANGE="Subscribe.Orientation.Change",Pe.STREAMING_MODE_CHANGE="Subscribe.StreamingMode.Change",Pe.VIDEO_DIMENSIONS_CHANGE="Subscribe.VideoDimensions.Change",Pe.LOADED_METADATA="Subscribe.LoadedMetadata",Pe.VOLUME_CHANGE="Subscribe.Volume.Change",Pe.SEEK_CHANGE="Subscribe.Seek.Change",Pe.PLAYBACK_TIME_UPDATE="Subscribe.Time.Update",Pe.PLAYBACK_STATE_CHANGE="Subscribe.Playback.Change",Pe.FULL_SCREEN_STATE_CHANGE="Subscribe.FullScreen.Change",Pe.AUTO_PLAYBACK_FAILURE="Subscribe.Autoplay.Failure",Pe.AUTO_PLAYBACK_MUTED="Subscribe.Autoplay.Muted",Pe.STATISTICS_ENDPOINT_CHANGE="Subscribe.StatisticsEndpoint.Change",e.RTCSubscriberEventTypes=void 0,(Ne=e.RTCSubscriberEventTypes||(e.RTCSubscriberEventTypes={})).PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",Ne.OFFER_START="WebRTC.Offer.Start",Ne.OFFER_END="WebRTC.Offer.End",Ne.ANSWER_START="WebRTC.Answer.Start",Ne.ANSWER_END="WebRTC.Answer.End",Ne.CANDIDATE_CREATE="WebRTC.Candidate.Create",Ne.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",Ne.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",Ne.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",Ne.SOCKET_MESSAGE="WebRTC.Socket.Message",Ne.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",Ne.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",Ne.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",Ne.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",Ne.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",Ne.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",Ne.ON_ADD_STREAM="WebRTC.Add.Stream",Ne.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",Ne.SUBSCRIBE_STREAM_SWITCH="WebRTC.Subscribe.StreamSwitch",Ne.TRANSFORM_ERROR="WebRTC.Transform.Error",Ne.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",Ne.STATS_REPORT="WebRTC.Stats.Report",e.MessageTransportStateEventTypes=void 0,(Re=e.MessageTransportStateEventTypes||(e.MessageTransportStateEventTypes={})).OPEN="MessageTransport.Open",Re.CLOSE="MessageTransport.Close",Re.CHANGE="MessageTransport.Change",Re.ERROR="MessageTransport.Error",e.WebRTCConnectionEventTypes=void 0,(Le=e.WebRTCConnectionEventTypes||(e.WebRTCConnectionEventTypes={})).CONNECTION_HEALTH_STALE_STATS="WebRTC.Connection.StaleStats",Le.CONNECTION_HEALTH_STATE_REGRESSION="WebRTC.Connection.StateRegression",Le.CONNECTION_HEALTH_EXCESSIVE_RTT="WebRTC.Connection.ExcessiveRTT",Le.CONNECTION_HEALTH_ICE_TIMEOUT="WebRTC.Connection.IceTimeout",e.MessageChannelEventTypes=void 0,(Ie=e.MessageChannelEventTypes||(e.MessageChannelEventTypes={})).OPEN="MessageChannel.Open",Ie.SEND="MessageChannel.Send",Ie.RECEIVE="MessageChannel.Receive",Ie.CLOSE="MessageChannel.Close",Ie.FAIL="MessageChannel.Fail",Ie.ERROR="MessageChannel.Error";const Oe=[{urls:"stun:stun2.l.google.com:19302"}],De={ordered:!0},ke=e=>{const t=["id","negotiated","ordered","maxPacketLifeTime","maxRetransmits","protocol"];return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))};class He extends Ee{constructor(e,t="R5RTCPeerConnectionHelper"){super(t),this._responder=e}_removeDataChannelHandlers(e){e.onopen=null,e.onerror=null,e.onclose=null,e.onmessage=null}_addDataChannelHandlers(t){t.onerror=e=>{this._responder.onDataChannelError(t,e.error.message)},t.onmessage=e=>{this._onDataChannelMessage(e)},t.onopen=()=>{this._responder.onDataChannelOpen(t)},t.onclose=i=>{this._responder.onDataChannelClose(t),this.trigger(new Te(e.MessageTransportStateEventTypes.CLOSE,this._name,{socket:this,event:i}))}}_isStatsMessage(e){return!("stats-report"!==(null==e?void 0:e.type))}_isErrorMessage(e){return!("error"!==(null==e?void 0:e.type)||!(null==e?void 0:e.message)&&!(null==e?void 0:e.code))}_isStatusMessage(e){return!("status"!==(null==e?void 0:e.type))}_onDataChannelMessage(e){if(this.handleMessageResponse(e))return!0;const t=this.getJsonFromSocketMessage(e);return t?!!this._isStatsMessage(t)||(D(this._name,`[datachannel-response]: ${JSON.stringify(t,null,2)}`),this._handleMessageContent(t)):(k(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,...ke(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 k(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){k(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){k(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=>{k(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=>{k(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=>{k(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){H(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 h,d="",c="";const u=[];l.forEach(e=>{!h&&r.exec(e)?h=e:o.exec(e)?d=e:a.exec(e)?c=e:s.exec(e)&&(t&&-1!=e.indexOf(t)?u.push(e):t||u.push(e))}),i&&u[u.length-1]!==n&&u.push(n);return[d,c,h,"a=mid:0"].concat(u).join("\r\n")},ze="RTCPeerConnectionPublisher";class Ke extends He{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||(k(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 k(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):k(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=>{H(ze,`[updatebandwidthrequest:error]:: ${e.message}`)})}return!0}catch(e){H(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){k(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){k(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){H(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 H(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 k(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 H(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 H(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 H(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(H(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 H(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):k(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=>{H(this._name,`Failed to get stats report. ${e.message||e}`)})}catch(e){H(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(t){const i={...this._identifier,type:"stats-report",timestamp:(new Date).getTime(),data:t},{endpoint:n,additionalHeaders:s}=this._config;if(n===e.StatsEndpointType.DEV_NULL)return;if(this._client&&this._client.onStatsReport&&(null===n||n===e.StatsEndpointType.EVENT_TRANSPORT))return void this._client.onStatsReport(this._connection,i);let o={"Content-Type":"application/json"};if(s&&(o={...o,...s}),n&&n.match(/^(http|https):\/\//))try{const e=await fetch(n,{method:"POST",headers:o,body:JSON.stringify(i)});e.status>=200&&e.status<300?D(this._name,`Posted stats data to endpoint: ${n}.`):H(this._name,`Failed to post stats data to endpoint: ${n}. ${e.status}`)}catch(e){H(this._name,`Failed to post stats data to endpoint: ${n}. ${e.message||e}`)}else if(this._client&&this._client.getMessageTransport()&&(void 0===n||n===e.StatsEndpointType.DATA_CHANNEL))try{let t=!1;const n=this._client.getMessageTransport();n&&(t=await n.post(i)),!t&&this._client&&(this._queue.push(i),this._client.on(e.MessageTransportStateEventTypes.CHANGE,()=>{this._client&&this._client.off(e.MessageTransportStateEventTypes.CHANGE),this._emptyStatsReportQueue()}),k(this._name,"Failed to post stats data to message transport. Message transport is not available. Pushed to Queue."))}catch(e){H(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(t){var i,n;const{id:s,state:o,currentRoundTripTime:a,totalRoundTripTime:r}=t,l=null===(i=this._client)||void 0===i?void 0:i.getPeerConnection();if(!l)return void this.stop();const{iceConnectionState:h}=l,d="connected"===h||"completed"===h,c=(new Date).getTime();if(d&&"succeeded"!==o)return;this._candidatePairHealth.has(s)||this._candidatePairHealth.set(s,{id:s,staleSampleCount:0,stateTransitionTime:c,inProgressStartTime:"in-progress"===o?c:void 0});const u=this._candidatePairHealth.get(s);if(void 0!==u.previousRTT&&void 0!==u.previousTotalRTT&&void 0!==a&&void 0!==r&&(a===u.previousRTT&&r===u.previousTotalRTT?(u.staleSampleCount++,u.staleSampleCount>=3&&u.lastIssueReported!==ot.STALE_STATS&&(this._client.emit(e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_STALE_STATS,{candidatePairId:s,currentState:o,frozenRTT:a,frozenTotalRTT:r,staleDurationSeconds:u.staleSampleCount,message:"RTT values frozen - connection may be dead"}),u.lastIssueReported=ot.STALE_STATS)):(u.staleSampleCount=0,u.lastIssueReported===ot.STALE_STATS&&(u.lastIssueReported=void 0))),"succeeded"!==u.previousState||"succeeded"===o||d||(this._client.emit(e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_STATE_REGRESSION,{candidatePairId:s,previousState:u.previousState,currentState:o,message:`ICE candidate pair regressed from '${u.previousState}' to '${o}' - connection lost`}),u.lastIssueReported=ot.STATE_REGRESSION,u.stateTransitionTime=c),void 0!==a&&a>.2){const t=a>1?"critical":a>.6?"severe":a>.35?"poor":"degrading";(u.lastIssueReported!==ot.EXCESSIVE_RTT||u.lastRttSeverity!==t)&&(this._client.emit(e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_EXCESSIVE_RTT,{candidatePairId:s,currentRTT:a,severity:t,message:`Elevated RTT detected (${t}): ${(1e3*a).toFixed(0)}ms`}),u.lastIssueReported=ot.EXCESSIVE_RTT,u.lastRttSeverity=t)}else void 0!==a&&a<=.2&&(u.lastIssueReported===ot.EXCESSIVE_RTT&&(u.lastIssueReported=void 0),u.lastRttSeverity=void 0);if("in-progress"===o){u.inProgressStartTime||(u.inProgressStartTime=c);const t=c-u.inProgressStartTime;t>((null===(n=this._renegotiationPolicy)||void 0===n?void 0:n.iceTimeoutInterval)||5e3)&&u.lastIssueReported!==ot.ICE_TIMEOUT&&(this._client.emit(e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_ICE_TIMEOUT,{candidatePairId:s,currentState:o,durationSeconds:Math.floor(t/1e3),message:`ICE negotiation timeout - candidate pair stuck in 'in-progress' for ${Math.floor(t/1e3)}s`}),u.lastIssueReported=ot.ICE_TIMEOUT)}else u.inProgressStartTime=void 0,u.lastIssueReported===ot.ICE_TIMEOUT&&(u.lastIssueReported=void 0);o!==u.previousState&&(u.stateTransitionTime=c),u.previousState=o,u.previousRTT=a,u.previousTotalRTT=r}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},ht=[e.PublisherEventTypes.PUBLISH_START,e.PublisherEventTypes.PUBLISH_FAIL,e.PublisherEventTypes.PUBLISH_INSUFFICIENT_BANDWIDTH,e.PublisherEventTypes.PUBLISH_SUFFICIENT_BANDWIDTH,e.PublisherEventTypes.PUBLISH_RECOVERING_BANDWIDTH,e.PublisherEventTypes.STATISTICS_ENDPOINT_CHANGE];class dt extends at{constructor(t,i){if(super("RTCPublisherStats",t,i),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=t=>{const{type:i,data:n}=t;if(ht.indexOf(i)>-1){if(i===e.PublisherEventTypes.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=n;this.updateEndpoint(e,!1)}this.postEvent(i)}},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(e.RTCPublisherEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(e.RTCPublisherEventTypes.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const t=({data:i})=>{this._client.off(e.RTCPublisherEventTypes.PEER_CONNECTION_AVAILABLE,t),this.start(i)};this._client.on(e.RTCPublisherEventTypes.PEER_CONNECTION_AVAILABLE,t)}}_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:h,retransmittedPacketsSent:d}=e,c={type:t,kind:n,codecId:s,mediaType:o,active:a,bytesSent:r,packetsSent:l,totalPacketsSendDelay:h,retransmittedPacketsSent:d};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:h,framesSent:d,keyFramesEncoded:u,qualityLimitationReason:p,qualityLimitationDurations:_}=e,g={...c,firCount:t,pliCount:n,nackCount:s,frameWidth:o,frameHeight:a,framesEncoded:l,framesPerSecond:h,framesSent:d,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(e.RTCPublisherEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(e.RTCPublisherEventTypes.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;e.PubNubEventTypes=void 0,(ut=e.PubNubEventTypes||(e.PubNubEventTypes={})).CONNECTED="PubNub.Connected",ut.DISCONNECTED="PubNub.Disconnected",ut.SUBSCRIBE_SUCCESS="PubNub.Subscribe.Success",ut.SUBSCRIBE_FAILURE="PubNub.Subscribe.Failure",ut.UNSUBSCRIBE_SUCCESS="PubNub.Unsubscribe.Success",ut.UNSUBSCRIBE_FAILURE="PubNub.Unsubscribe.Failure",ut.MESSAGE_RECEIVED="PubNub.Message.Received",ut.MESSAGE_SEND_SUCCESS="PubNub.Message.Send.Success",ut.MESSAGE_SEND_FAILURE="PubNub.Message.Send.Failure",ut.AUTH_TOKEN_GENERATED="PubNub.AuthToken.Generated",ut.AUTH_TOKEN_GENERATION_ERROR="PubNub.AuthToken.Generation.Error",ut.STATUS="PubNub.Status",ut.ERROR="PubNub.Error";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 h=await t.json(),{success:d,token:c}=h;if(!d)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:v,pubnubToken:m}=u;if(p!==i||_!==a)throw new Error("Invalid auth token. Please try again later.");if(g!==s||v!==o)throw new Error("Invalid auth token. Please try again later.");return m}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",vt={receivePresenceEvents:!0,withPresence:!1},mt=e=>D(gt,e),Et=e=>k(gt,e),bt=e=>H(gt,e);class St 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(t){var i,n,s,o,a,r,l,h;if(this._config={...ct,...t},(null===(i=this._config)||void 0===i?void 0:i.cloudEndpoint)||(null===(n=this._config)||void 0===n?void 0:n.backendUrl)||(null===(s=this._config)||void 0===s?void 0:s.backendURL)){let t;try{if((null===(o=this._config)||void 0===o?void 0:o.cloudEndpoint)?t=await this._getAuthFromCloud(this._config):((null===(a=this._config)||void 0===a?void 0:a.backendUrl)||(null===(r=this._config)||void 0===r?void 0:r.backendURL))&&(t=await this._getAuthFromBackend(this._config)),!t)throw new Error("Failed to get auth token.");this._config.authToken=t,this.trigger(new ye(e.PubNubEventTypes.AUTH_TOKEN_GENERATED,this,{authToken:t}))}catch(t){return bt(null!==(l=t.message)&&void 0!==l?l:"Failed to get auth token."),this.trigger(new ye(e.PubNubEventTypes.AUTH_TOKEN_GENERATION_ERROR,this,{error:t.message})),this}}const{pubnub:d,publishKey:c,subscribeKey:u,authToken:p,userId:_,logLevel:g}=this._config;if(!d){const t="PubNub library is not initialized. Please provide a PubNub library reference in the configuration.";throw this.trigger(new ye(e.PubNubEventTypes.ERROR,this,{error:t})),bt(t),new Error(t)}return mt(`Initializing PubNub client with options: ${JSON.stringify({...this._config,...(null===(h=this._config)||void 0===h?void 0:h.authToken)?{authToken:"********"}:{}})}`),this._pubnub=new d({userId:_,publishKey:c,subscribeKey:u,logLevel:g}),this._pubnub.setToken(p),this._pubnub.addListener({message:t=>{var i;mt(`Message received on channel ${t.channel}: ${t.message}`),this.trigger(new ye(e.PubNubEventTypes.MESSAGE_RECEIVED,this,{...t,userId:null===(i=this._config)||void 0===i?void 0:i.userId}))},presence:e=>{mt(`Presence event on channel ${e.channel}: ${JSON.stringify(e)}`)},status:t=>{const{category:i,operation:n}=t;if(mt(`Status event ${i}`),this.trigger(new ye(e.PubNubEventTypes.STATUS,this,t)),"PNConnectedCategory"===i)this.trigger(new ye(e.PubNubEventTypes.CONNECTED,this,t)),"PNSubscribeOperation"===n&&this.trigger(new ye(e.PubNubEventTypes.SUBSCRIBE_SUCCESS,this,t));else if("PNDisconnectedCategory"===i)this.trigger(new ye(e.PubNubEventTypes.DISCONNECTED,this,t));else if("PNReconnectedCategory"===i);else if("PNAcknowledgmentCategory"===i)"PNUnsubscribeOperation"===n&&this.trigger(new ye(e.PubNubEventTypes.UNSUBSCRIBE_SUCCESS,this,t));else if("PNBadRequestCategory"===i)this.trigger(new ye(e.PubNubEventTypes.ERROR,this,t));else if("PNAccessDeniedCategory"===i){this.trigger(new ye(e.PubNubEventTypes.ERROR,this,t));const{message:i,payload:n}=t;if((null==n?void 0:n.channels)&&(null==n?void 0:n.channels.length)>0)for(const t of n.channels)bt(`Failed to subscribe to channel ${t}: ${i}.`),this.trigger(new ye(e.PubNubEventTypes.SUBSCRIBE_FAILURE,this,{channel:t}))}}}),this}async publishMessage(t,i){var n,s;if(!this._pubnub)return bt("PubNub client not initialized."),!1;try{const s=await this._pubnub.publish({channel:t,message:i});this.trigger(new ye(e.PubNubEventTypes.MESSAGE_SEND_SUCCESS,this,{...s,channel:t,message:i,userId:null===(n=this._config)||void 0===n?void 0:n.userId}))}catch(n){return bt(null!==(s=n.message)&&void 0!==s?s:`Failed to publish message to channel ${t}.`),this.trigger(new ye(e.PubNubEventTypes.MESSAGE_SEND_FAILURE,this,{channel:t,message:i})),!1}return!0}async subscribe(t,i){var n;if(!this._pubnub)return bt("PubNub client not initialized."),!1;if(this._subscriptions[t])return!0;try{const e=this._pubnub.channel(t),n=await e.subscription({...vt,...i});if(!n)throw new Error(`Failed to subscribe to channel ${t}.`);n.subscribe(),this._subscriptions[t]=n}catch(i){return bt(null!==(n=i.message)&&void 0!==n?n:`Failed to subscribe to channel ${t}.`),this.trigger(new ye(e.PubNubEventTypes.SUBSCRIBE_FAILURE,this,{channel:t})),!1}return!0}async unsubscribe(t){var i;if(!this._pubnub)return!0;if(!this._subscriptions[t])return Et(`Subscription ${t} not found.`),!1;try{await this._subscriptions[t].unsubscribe()}catch(n){bt(null!==(i=n.message)&&void 0!==i?i:`Failed to unsubscribe from channel ${t}.`),this.trigger(new ye(e.PubNubEventTypes.UNSUBSCRIBE_FAILURE,this,{channel:t}))}return delete this._subscriptions[t],!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 Ct="WHIPClient",Tt=ve,yt=e=>D(Ct,e),ft=e=>H(Ct,e),At=e=>k(Ct,e);class wt extends U{constructor(e,t,i){super(),this._reconnectAttempts=0,this._reconnectTimeout=null;const n=e?se(e):Tt,s=i||Tt,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(t){var i,n;const{onGetUserMedia:s}=t;if(s){yt("Requesting gUM from user-defined configuration:onGetUserMedia.");const t=await s();return this.trigger(new Se(e.RTCPublisherEventTypes.CONSTRAINTS_ACCEPTED,this,ae(t))),t}{const{mediaConstraints:s}=t;let o;yt(`Requesting gUM using mediaConstraints: ${JSON.stringify(s,null,2)}`);let a=s;const r=await xe(a);return r&&r.media||(o=await ie.gUM(a)),o=null!==(i=null==r?void 0:r.media)&&void 0!==i?i:o,a=null!==(n=null==r?void 0:r.constraints)&&void 0!==n?n:s,yt(`Constraints accepted: ${JSON.stringify(a,null,2)}`),this.trigger(new Se(e.RTCPublisherEventTypes.CONSTRAINTS_ACCEPTED,this,{constraints:a,...ae(o)})),o}}async getAndPreviewStreamIfAvailable(){var t;let i=this._mediaStream;if(!i){try{i=null!=i?i:await this.generateMediaStream(this._options)}catch(i){const n=null!==(t=i.message)&&void 0!==t?t:"Could not generate media stream.";throw this.trigger(new Se(e.RTCPublisherEventTypes.CONSTRAINTS_REJECTED,this,{constraints:this._options.mediaConstraints})),new Error(n)}if(!i)throw new Error("Could not generate media stream.")}return this.trigger(new Se(e.RTCPublisherEventTypes.MEDIA_STREAM_AVAILABLE,this,i)),this.preview(i),i}establishStatsMonitor(e){return new dt(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){At(`[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){At(`[audioEncoding] Could not set codec preferences for ${i}. ${e.message||e}`)}}})}async postOffer(t){var i;try{const{sdp:n}=t;let{videoEncoding:s}=this._options;const{mungeOffer:o,streamMode:a,keyFramerate:r,iceTransport:l,connectionParams:h,mediaConstraints:d,forceVP8:c,audioEncoding:u,offerSDPResolution:p}=this._options;c&&!s&&(s=e.PublishVideoEncoder.VP8);let _=n;o&&(yt(`[MUNGE:before] offer: ${_}`),_=o(_),yt(`[MUNGE:after] offer: ${_}`)),p&&(yt(`[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){k("[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){k("[determineMediaResolution]",`Could not determine resolution from MediaConstraints. ${e.message||e}`)}return i&&D("[determineMediaResolution]",`constraints: ${JSON.stringify(i,null,2)}`),i})(this._mediaStream,d)),yt(`[MUNGE:after] offer: ${_}`));const g={...h,mode:a,transport:l,keyFramerate:r};return s&&(g.videoEncoding=s),u&&(g.audioEncoding=u),await(null===(i=this._whipWhepService)||void 0===i?void 0:i.postSDPOffer(_,g))}catch(t){throw ft(t.message||t),t instanceof je&&this.trigger(new Se(e.PublisherEventTypes.PUBLISH_INVALID_NAME,this)),t}}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 St;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={...Tt,...e};const o=oe(this._options),{includeDataChannel:a,disableProxy:r,reconnect:l}=this._options;return l&&(this._options.reconnect={...me,...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(t){var i,n,s,o,a,r,l;t&&(this._options.streamName=t);const{forceVP8:h,audioEncoding:d,rtcConfiguration:c,dataChannelConfiguration:u,includeDataChannel:p,signalingSocketOnly:_,enableChannelSignaling:g,connectionParams:v,bandwidth:m,mungeAnswer:E}=this._options;let{videoEncoding:b}=this._options;h&&(b=e.PublishVideoEncoder.VP8,this._options.videoEncoding=b),this._mediaStream||(this._mediaStream=await this.getAndPreviewStreamIfAvailable());try{const t=null!=v?v:{};if(v){const{transcode:e}=v;e&&(t.transcode=e)}const l=await(null===(i=this._whipWhepService)||void 0===i?void 0:i.getOptions(t)),h=!!(null===(n=this._options)||void 0===n?void 0:n.rtcConfiguration)&&Array.isArray(this._options.rtcConfiguration.iceServers)&&this._options.rtcConfiguration.iceServers.length>0;(null==l?void 0:l.links)&&!h&&(this._options.rtcConfiguration={...c,iceServers:l.links}),(null==l?void 0:l.origin)&&this.trigger(new Se(e.RTCPublisherEventTypes.HOST_ENDPOINT_CHANGED,this,{endpoint:l.origin})),(null==l?void 0:l.statisticsEndpoint)&&this._onStatisticsEndpointChange(l.statisticsEndpoint);const S=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,S),this.trigger(new Se(e.RTCPublisherEventTypes.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(),b,d);const C=await(null===(s=this._peerConnectionHelper)||void 0===s?void 0:s.createOfferWithoutSetLocal(m));await this._peerConnectionHelper.setLocalDescription(C),this.trigger(new Se(e.RTCPublisherEventTypes.OFFER_START,this,C));const{sdp:T}=await this.postOffer(C);let y=T;if(E&&(yt(`[MUNGE:before] answer: ${y}`),y=E(y),yt(`[MUNGE:after] answer: ${y}`)),!this._peerConnectionHelper)throw new Error("SDP Exchange interrupted. Peer Connection Helper not available.");if(await(null===(o=this._peerConnectionHelper)||void 0===o?void 0:o.setRemoteDescription({type:"answer",sdp:y})),this.trigger(new Se(e.RTCPublisherEventTypes.OFFER_END,this,y)),!this._peerConnectionHelper)throw new Error("SDP Exchange interrupted. Peer Connection Helper not available.");const f=await(null===(a=this._peerConnectionHelper)||void 0===a?void 0:a.waitToGatherIce()),{sdp:A}=f;return await this.postCandidateFragments(A),this.trigger(new Se(e.RTCPublisherEventTypes.ICE_TRICKLE_COMPLETE,this)),ie.addOrientationChangeHandler(this._onOrientationChange),(null===(r=this._options)||void 0===r?void 0:r.includeDataChannel)||this.trigger(new Se(e.PublisherEventTypes.PUBLISH_START,this)),this}catch(t){throw ft(null!==(l=t.message)&&void 0!==l?l:"Could not publish."),this.trigger(new Se(e.PublisherEventTypes.CONNECT_FAILURE,this,t)),this.unpublish(!0),t}}async unpublish(t=!1,i=!1){var n;yt("[unpublish]"),this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),i||(this._reconnectAttempts=0,this._reconnectTimeout=null),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,t),this._pubnubClient&&await this.deinitPubNub(),this._pubnubClient=void 0,(null===(n=this._options)||void 0===n?void 0:n.clearMediaOnUnpublish)&&!i&&this.unpreview(),i||(this._mediaStream=void 0),this.unmonitorStats(),this._peerConnectionHelper=void 0,this._whipWhepService=void 0,this._messageTransport=void 0,this._publishView=void 0,i||this.trigger(new Se(e.PublisherEventTypes.UNPUBLISH_SUCCESS,this)),ie.removeOrientationChangeHandler(this._onOrientationChange)}async attemptReconnect(t){var i;if(yt("[attemptReconnect]"),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),!t)return void ft("Reconnect configuration not provided.");const{enabled:n,timeout:s,maxAttempts:o}=t;if(n){if(this._reconnectAttempts>=o)return ft("Reconnect attempts exceeded maximum attempts."),void this.trigger(new Se(e.PublisherEventTypes.RECONNECT_FAILURE,this,{error:"Reconnect attempts exceeded maximum attempts."}));try{await this.unpublish(!0,!0)}catch(e){ft(null!==(i=e.message)&&void 0!==i?i:"Could not unpublish for reconnect.")}return this._reconnectAttempts++,this._reconnectTimeout=setTimeout(()=>{this.reconnect(t)},s),this}ft("Reconnect is not enabled.")}async reconnect(t){var i,n;yt("[reconnect]"),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this.trigger(new Se(e.PublisherEventTypes.RECONNECT_START,this));try{await this.init(this._options),await this.publish(),this.trigger(new Se(e.PublisherEventTypes.RECONNECT_SUCCESS,this)),this._reconnectAttempts=0,this._reconnectTimeout=null}catch(s){ft(null!==(i=s.message)&&void 0!==i?i:"Could not reconnect."),this.trigger(new Se(e.PublisherEventTypes.RECONNECT_FAILURE,this,{error:null!==(n=s.message)&&void 0!==n?n:"Could not reconnect."})),this.attemptReconnect(t)}return this}preview(e){const{mediaElementId:t}=this._options;t&&(yt("[preview]"),this._publishView=new nt(t),this._publishView.preview(e))}unpreview(){this._mediaStream&&this._mediaStream.getTracks().forEach(e=>{e.stop()}),this._publishView&&(yt("[unpreview]"),this._publishView.unpreview()),this._publishView=void 0}monitorStats(e){yt("[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?At("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){At(`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):(ft("PubNub client not initialized."),!1)}async subscribePubNub(e,t){return this._pubnubClient?await this._pubnubClient.subscribe(e,t):(ft("PubNub client not initialized."),!1)}async unsubscribePubNub(e){return this._pubnubClient?await this._pubnubClient.unsubscribe(e):(ft("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){ft(e.message||e)}}sendLog(e,t){var i;try{const n=Object.keys(R).find(t=>t.toLowerCase()===e.toLowerCase())?e:R.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;ft("Could not send log to server. Message parameter expected to be String or JSON-serializable object."),ft(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(t,i){ft(`Data channel error: ${i}`),this.trigger(new Se(e.RTCPublisherEventTypes.DATA_CHANNEL_ERROR,this,{dataChannel:t,error:i}))}_onSendReceived(t,i){yt(`Send received: ${t} ${JSON.stringify(i)}`),"onMetaData"===t?this._onMetaData(i):this.trigger(new Se(e.PublisherEventTypes.PUBLISH_SEND_INVOKE,this,{methodName:t,data:i}))}_onMetaData(t){yt(`Metadata received: ${JSON.stringify(t)}`),this.trigger(new Se(e.PublisherEventTypes.PUBLISH_METADATA,this,t))}_onConnectionClosed(){yt("Connection closed"),this.unpublish(),this.trigger(new Se(e.PublisherEventTypes.CONNECTION_CLOSED,this))}_onDataChannelOpen(t){yt(`Data channel opened: ${t.label}`),this.trigger(new Se(e.RTCPublisherEventTypes.DATA_CHANNEL_OPEN,this,{dataChannel:t})),this.trigger(new Se(e.RTCPublisherEventTypes.DATA_CHANNEL_AVAILABLE,this,{name:t.label,dataChannel:t})),this._messageTransport=this._peerConnectionHelper,this.trigger(new Te(e.MessageTransportStateEventTypes.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new Se(e.PublisherEventTypes.PUBLISH_START,this))}_onDataChannelClose(t){yt(`Data channel closed: ${t.label}`),this.trigger(new Se(e.RTCPublisherEventTypes.DATA_CHANNEL_CLOSE,this,{dataChannel:t}))}_onDataChannelMessage(t,i){yt(`Data channel message: ${i.data}`),this.trigger(new Se(e.RTCPublisherEventTypes.DATA_CHANNEL_MESSAGE,this,{dataChannel:t,message:i}))}_onPeerConnectionTrackAdd(t){yt(`Peer connection track added: ${t.id}`),this.trigger(new Se(e.RTCPublisherEventTypes.TRACK_ADDED,this,{track:t}))}_onPeerConnectionOpen(){yt("Peer connection opened"),this.trigger(new Se(e.RTCPublisherEventTypes.PEER_CONNECTION_OPEN,this,this.getPeerConnection()))}_onPeerConnectionFail(){ft("Peer connection failed"),this.trigger(new Se(e.PublisherEventTypes.PUBLISH_FAIL,this))}_onPeerConnectionClose(t,i){var n,s,o;yt(`Peer connection closed: ${t.type}`),this._peerConnectionHelper&&this._peerConnectionHelper.tearDown(),this.trigger(new Se(e.PublisherEventTypes.CONNECTION_CLOSED,this,t)),!i||i!==pe.GONE&&i!==pe.FAILED||(null===(s=null===(n=this._options)||void 0===n?void 0:n.reconnect)||void 0===s?void 0:s.enabled)&&this.attemptReconnect(null===(o=this._options)||void 0===o?void 0:o.reconnect)}_onIceCandidate(t){yt(`ICE candidate: ${JSON.stringify(t,null,2)}`),this.trigger(new Se(e.RTCPublisherEventTypes.CANDIDATE_CREATE,this,{candidate:t}))}_onUnpublish(){yt("Unpublish received")}_onPublisherStatus(t){var i,n,s;yt("[publisherstatus] - "+JSON.stringify(t,null,2)),t.code&&"NetStream.Publish.IsAvailable"===t.code?this.trigger(new Se(e.PublisherEventTypes.PUBLISH_AVAILABLE,this,t)):(t.code&&"NetStream.Publish.Start"===t.code&&this._mediaStream&&(null===(i=this._options)||void 0===i?void 0:i.optimizationParams)&&(null===(n=this._peerConnectionHelper)||void 0===n||n.setOptimizationParams(this._mediaStream,null===(s=this._options)||void 0===s?void 0:s.optimizationParams)),this.trigger(new Se(e.PublisherEventTypes.PUBLISH_STATUS,this,t)))}_onInsufficientBandwidth(t){this.trigger(new Se(e.PublisherEventTypes.PUBLISH_INSUFFICIENT_BANDWIDTH,this,t))}_onSufficientBandwidth(t){this.trigger(new Se(e.PublisherEventTypes.PUBLISH_SUFFICIENT_BANDWIDTH,this,t))}_onRecoveringBandwidth(t){this.trigger(new Se(e.PublisherEventTypes.PUBLISH_RECOVERING_BANDWIDTH,this,t))}_onSDPSuccess(e=void 0){const t=e?": "+JSON.stringify(e,null,2):"";yt(`[onsdpsuccess]:: ${t}`)}_onSDPError(t=void 0){this.trigger(new Se(e.PublisherEventTypes.PUBLISH_FAIL,this));const i=t?": "+JSON.stringify(t,null,2):"";ft(`[onsdperror]:: ${i}`)}_onOrientationChange(e){const t=this.getMessageTransport();t&&t.post({send:{method:"onMetaData",data:{deviceOrientation:e}}})}_onStatisticsEndpointChange(t){yt(`Statistics endpoint changed: ${t}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(t),this.trigger(new Se(e.PublisherEventTypes.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:t}))}_onStatsReport(t,i){this.trigger(new Se(e.RTCPublisherEventTypes.STATS_REPORT,this,{connection:t,report:i}))}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 Se(e,this,t))}getType(){return"RTC"}}const Pt={...{protocol:"https",port:443,app:"live",autoLayoutOrientation:!0,mediaElementId:"red5pro-subscriber",rtcConfiguration:{iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:he.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},Nt={protocol:"https",port:443,app:"live",mediaElementId:"red5pro-subscriber",muteOnAutoplayRestriction:!0},Rt={endpoint:e.StatsEndpointType.DEV_NULL,interval:3e3},Lt="R5ProPlaybackView";class It{constructor(e="red5pro-subscriber"){try{this._targetElement=ie.resolveElement(e)}catch(e){throw H(Lt,`Could not instantiate a new instance of Red5ProSubscriber. Reason: ${e.message||e}`),e}}attachStream(e){const t=this.isAutoplay;D(Lt,"[attachstream]"),ie.setVideoSource(this._targetElement,e,t)}detachStream(){D(Lt,"[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 He{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?(k(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 k(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 kt;!function(e){e.EMPTY="Empty",e.VIDEO="Video",e.AUDIO="Audio",e.FULL="Video/Audio"}(kt||(kt={}));class Ht extends U{trigger(e){super.trigger(e)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}class Mt extends Ht{}const Ut=[e.SubscriberEventTypes.SUBSCRIBE_START,e.SubscriberEventTypes.SUBSCRIBE_STOP,e.SubscriberEventTypes.SUBSCRIBE_FAIL,e.SubscriberEventTypes.SUBSCRIBE_PUBLISHER_CONGESTION,e.SubscriberEventTypes.SUBSCRIBE_PUBLISHER_RECOVERY,e.SubscriberEventTypes.PLAY_UNPUBLISH,e.SubscriberEventTypes.STREAMING_MODE_CHANGE,e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,e.SubscriberEventTypes.STATISTICS_ENDPOINT_CHANGE];class Bt extends at{constructor(t,i,n){if(super("RTCSubscriberStats",t,i,n),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=t=>{const{type:i,data:n}=t;if(Ut.indexOf(i)>-1)if(i===e.SubscriberEventTypes.STREAMING_MODE_CHANGE){const{streamingMode:e,previousStreamingMode:t}=n;this.postEvent(i,{data:{streamingMode:e,previousStreamingMode:t}})}else if(i===e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE){const{code:t}=n;let i;t===e.PlaybackState.AVAILABLE&&(i={timeToFirstFrameMS:(new Date).getTime()-this._startTime}),this.postEvent(o[t],i)}else{if(i===e.SubscriberEventTypes.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=n;this.updateEndpoint(e,!1)}this.postEvent(i)}},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(e.RTCSubscriberEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(e.RTCSubscriberEventTypes.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const t=({data:i})=>{this._client.off(e.RTCSubscriberEventTypes.PEER_CONNECTION_AVAILABLE,t),this.start(i)};this._client.on(e.RTCSubscriberEventTypes.PEER_CONNECTION_AVAILABLE,t)}}_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,h={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({...h,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:d,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:g,totalFreezesDuration:v,totalPausesDuration:m}=e,E={...h,firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:a,framesPerSecond:r,framesReceived:d,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:g,totalFreezesDuration:v,totalPausesDuration:m};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(e.RTCSubscriberEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(e.RTCSubscriberEventTypes.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(t){var i,n;t?null===(i=this._view)||void 0===i||i.classList.add("red5pro-media-container-full-screen"):null===(n=this._view)||void 0===n||n.classList.remove("red5pro-media-container-full-screen"),this.trigger(new Ce(e.SubscriberEventTypes.FULL_SCREEN_STATE_CHANGE,void 0,t))}_cleanup(){this._playbackNotificationCenter&&this._removePlaybackNotificationCenterHandlers(this._playbackNotificationCenter),this._playbackNotificationCenter=void 0,this._view=void 0}_onCanPlay(t){var i;D(this._name,"[videoelement:event] canplay");const n=null!==(i=this._playbackNotificationCenter)&&void 0!==i?i:t.target,o=this.getControls();o&&o.enable(!0),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.AVAILABLE,state:s.AVAILABLE})),this.trigger(new Ce(e.SubscriberEventTypes.VOLUME_CHANGE,void 0,{volume:n.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 t=this.getControls();t&&t.setState(e.PlaybackState.IDLE),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.IDLE,state:s.IDLE}))}_onTimeUpdate(t){var i;const n=null!==(i=this._playbackNotificationCenter)&&void 0!==i?i:t.target,s=this.getControls();s&&s.setSeekTime(n.currentTime,this.isVOD()?n.duration:void 0),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:n.currentTime,duration:n.duration}))}_onPlay(){D(this._name,"[videoelement:event] play");const t=this.getControls();t&&t.setState(e.PlaybackState.PLAYING),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PLAYING,state:s.PLAYING}))}_onPause(){D(this._name,"[videoelement:event] pause");const t=this.getControls();t&&t.setState(e.PlaybackState.PAUSED),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PAUSED,state:s.PAUSED}))}_onVolumeChange(t){var i;D(this._name,"[videoelement:event] volumechange");const n=null!==(i=this._playbackNotificationCenter)&&void 0!==i?i:t.target,s=this.getControls();s&&s.getVolume()!==n.volume&&s.setVolume(n.volume),this.trigger(new Ce(e.SubscriberEventTypes.VOLUME_CHANGE,void 0,{volume:n.volume}))}_onLoadedData(t){var i,n,s;D(this._name,"[videoelement:event] loadeddata");const o=null!==(i=this._view)&&void 0!==i?i:t.target;this.trigger(new Ce(e.SubscriberEventTypes.VIDEO_DIMENSIONS_CHANGE,void 0,{width:null!==(n=o.videoWidth)&&void 0!==n?n:0,height:null!==(s=o.videoHeight)&&void 0!==s?s:0}))}_onLoadedMetadata(t){var i,n;D(this._name,"[videoelement:event] loadedmetadata");const s=null!==(i=this._view)&&void 0!==i?i:t.target;this.trigger(new Ce(e.SubscriberEventTypes.LOADED_METADATA,void 0,{duration:null!==(n=s.duration)&&void 0!==n?n:0}))}_onResize(t){var i,n,s;D(this._name,"[videoelement:event] resize");const o=null!==(i=this._view)&&void 0!==i?i:t.target;this.trigger(new Ce(e.SubscriberEventTypes.VIDEO_DIMENSIONS_CHANGE,void 0,{width:null!==(n=o.videoWidth)&&void 0!==n?n:0,height:null!==(s=o.videoHeight)&&void 0!==s?s: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(t){D(this._name,"[videoelement:event] error"),this.trigger(new Ce(e.SubscriberEventTypes.CONNECT_FAILURE,void 0,{error:t.message}))}async attemptAutoplay(t=!1){try{await this.play(),this.isMuted()&&this.trigger(new Ce(e.SubscriberEventTypes.AUTO_PLAYBACK_MUTED,void 0,{element:this._view}))}catch(i){t?(this.mute(),this.attemptAutoplay(!1)):this.trigger(new Ce(e.SubscriberEventTypes.AUTO_PLAYBACK_FAILURE,void 0,{error:i.message?i.message:i,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 H(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){k(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){k(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){k(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=Pt,Gt=e=>D(Ft,e),xt=e=>H(Ft,e),Wt=e=>k(Ft,e);class zt extends Ht{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?kt.FULL:t?kt.VIDEO:i?kt.AUDIO:kt.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 Ce(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(t){var i;Gt("[requestoffer]");const{iceTransport:n,maintainStreamVariant:s,videoEncoding:o,audioEncoding:a,connectionParams:r,mungeOffer:l}=this._options;t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});const h={transport:n,doNotSwitch:s};o&&o!==e.PlaybackVideoEncoder.NONE&&(h.videoEncoding=o),a&&a!==e.PlaybackAudioEncoder.NONE&&(h.audioEncoding=a);const d=null!=r?r:{},c=await t.createOffer(),u=await(null===(i=this._whipWhepService)||void 0===i?void 0:i.postSDPOffer(c.sdp,{...d,...h},!1));if(!u)throw xt("Failed to get offer from WHEP"),new Error("Failed to get offer from WHEP");const{sdp:p}=u;let _=p;return l&&(Gt(`[MUNGE:before] offer: ${_}`),_=l(_),Gt(`[MUNGE:after] offer: ${_}`)),_}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 St;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(t,i){const{renegotiationPolicy:n}=this._options;if(n){const{type:s}=n,o=s.toLowerCase();if(Gt(`[evaluateRenegotiationPolicy] - Type: ${t}, Renegotiation Policy: ${n.type}`),t===e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_STATE_REGRESSION&&"regression"===o)this._reconnect();else if(t===e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_ICE_TIMEOUT&&"timeout"===o)this._reconnect();else if(t===e.SubscriberEventTypes.CONNECTION_CLOSED&&"disconnect"===o)this._reconnect();else if(t===e.WebRTCConnectionEventTypes.CONNECTION_HEALTH_EXCESSIVE_RTT&&"excessive-rtt"===o){const{severity:e}=i;!e||"critical"!==e.toLowerCase()&&"severe"!==e.toLowerCase()||this._reconnect()}}}async _reconnect(){var t,i;if(this._reconnecting)Gt("[reconnect] - already in progress. Ignoring request.");else{this._reconnecting=!0,Gt("[reconnect]"),this.trigger(new Ce(e.SubscriberEventTypes.RECONNECT_START,this));try{await this.unsubscribe(!0),await this.init(this._options),await this.subscribe()}catch(n){xt(null!==(t=n.message)&&void 0!==t?t:"Could not reconnect."),this.trigger(new Ce(e.SubscriberEventTypes.RECONNECT_FAILURE,this,{error:null!==(i=n.message)&&void 0!==i?i:"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=Rt),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 t,i,n,s,o,a,r,l,h;const{connectionParams:d,rtcConfiguration:c,includeDataChannel:u,signalingSocketOnly:p,enableChannelSignaling:_,dataChannelConfiguration:g}=this._options;try{const h=d||{},m=await(null===(t=this._whipWhepService)||void 0===t?void 0:t.getOptions(h));this.trigger(new Ce(e.SubscriberEventTypes.CONNECT_SUCCESS,this,null===(i=this._whipWhepService)||void 0===i?void 0:i.getUrl()));const E=!!(null===(n=this._options)||void 0===n?void 0:n.rtcConfiguration)&&Array.isArray(this._options.rtcConfiguration.iceServers)&&this._options.rtcConfiguration.iceServers.length>0;(null==m?void 0:m.links)&&!E&&(this._options.rtcConfiguration={...c,iceServers:m.links}),(null==m?void 0:m.origin)&&this.trigger(new Ce(e.RTCSubscriberEventTypes.HOST_ENDPOINT_CHANGED,this,{endpoint:m.origin})),(null==m?void 0:m.statisticsEndpoint)&&this._onStatisticsEndpointChange(m.statisticsEndpoint);const b=u||_||p?g: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,b),null===(s=this.getPeerConnection())||void 0===s||s.addEventListener("track",t=>{const{buffer:i}=this._options;Gt("[peerconnection.ontrack]");const{streams:n,track:s,receiver:o,transceiver:a}=t;o.jitterBufferDelayHint=i,this.trigger(new Ce(e.RTCSubscriberEventTypes.TRACK_ADDED,this,{streams:n,track:s,receiver:o,transceiver:a})),this._mediaStream=n&&n.length>0?n[0]:void 0,"video"===s.kind?(this._videoMuted=s.muted,s.muted&&s.addEventListener("unmute",this._videoUnmuteHandler)):"audio"===s.kind&&(this._audioMuted=s.muted,s.muted&&s.addEventListener("unmute",this._audioUnmuteHandler)),this._runMuteCheck()}),this.trigger(new Ce(e.RTCSubscriberEventTypes.PEER_CONNECTION_AVAILABLE,this,this.getPeerConnection())),this.trigger(new Ce(e.RTCSubscriberEventTypes.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===(o=this.getPeerConnection())||void 0===o?void 0:o.setRemoteDescription(C)),this.trigger(new Ce(e.RTCSubscriberEventTypes.OFFER_END,this)),this.trigger(new Ce(e.RTCSubscriberEventTypes.ANSWER_START,this));const T=await this.requestAnswer(this.getPeerConnection()),y=(v=T).includes("stereo=1")?v:v.replace("useinbandfec=1","useinbandfec=1;stereo=1;sprop-stereo=1"),f=new RTCSessionDescription({type:"answer",sdp:y});await(null===(a=this.getPeerConnection())||void 0===a?void 0:a.setLocalDescription(f)),await this.sendAnswer(y),this.trigger(new Ce(e.RTCSubscriberEventTypes.ANSWER_END,this));const A=await this._peerConnectionHelper.waitToGatherIce(),{sdp:w}=A;return await this.postCandidateFragments(w),this.trigger(new Ce(e.RTCSubscriberEventTypes.ICE_TRICKLE_COMPLETE,this)),this._mediaStream&&(this.trigger(new Ce(e.RTCSubscriberEventTypes.ON_ADD_STREAM,this,this._mediaStream)),this.addMediaStreamToPlayback(this._options.mediaElementId,this._mediaStream)),(null===(r=this._playbackView)||void 0===r?void 0:r.view)&&this._attachSourceHandler(this._playbackView.view),this._sourceHandler&&this._glomTrigger(this._sourceHandler),this._playIfAutoplaySet(this._options,null===(l=this._playbackView)||void 0===l?void 0:l.view),this}catch(t){throw xt(null!==(h=t.message)&&void 0!==h?h:"Could not subscribe."),t instanceof je?this._onStreamUnavailable(t):this.trigger(new Ce(e.SubscriberEventTypes.CONNECT_FAILURE,this,t)),this._options.maintainConnectionOnSubscribeErrors||this.unsubscribe(!0),t}var v}async unsubscribe(t=!1){var i;Gt("[unsubscribe]"),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,t),this._sourceHandler&&this._sourceHandler.disconnect(),this._pubnubClient&&await this.deinitPubNub(),this.unmonitorStats(),null===(i=this._playbackView)||void 0===i||i.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 Ce(e.SubscriberEventTypes.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(R).find(t=>t.toLowerCase()===e.toLowerCase())?e:R.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 Ce(e.SubscriberEventTypes.PLAY_UNPUBLISH,this)),this._sourceHandler&&this._sourceHandler.unpublish()}_onStreamUnavailable(t){Gt(`Stream ${this._options.streamName} does not exist.`),Gt("[onstreamunavailable]: "+JSON.stringify(t,null,2)),this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_INVALID_NAME,this))}_onDataChannelError(t,i){xt(`Data channel error: ${i}`),this.trigger(new Ce(e.RTCSubscriberEventTypes.DATA_CHANNEL_ERROR,this,{dataChannel:t,error:i}))}_onSendReceived(t,i){Gt(`Send received: ${t} ${JSON.stringify(i)}`),"onMetaData"===t?this._onMetaData(i):this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_SEND_INVOKE,this,{methodName:t,data:i}))}_onStreamSwitchComplete(){Gt("[streamswitch::complete]");const t=this._requestedStreamSwitch;this.trigger(new Ce(e.RTCSubscriberEventTypes.SUBSCRIBE_STREAM_SWITCH,this,{path:t})),this._requestedStreamSwitch=void 0}_onMetaData(t){const{orientation:i,streamingMode:n}=t,s=this._streamingMode;void 0!==i&&i!==this._orientation&&(this._orientation=i,this.trigger(new Ce(e.SubscriberEventTypes.ORIENTATION_CHANGE,this,{orientation:parseInt(i,10),viewElement:this._playbackView?this._playbackView.view:void 0}))),n&&void 0!==n&&n!==s&&(this._streamingMode=n,this.trigger(new Ce(e.SubscriberEventTypes.STREAMING_MODE_CHANGE,this,{streamingMode:n,previousStreamingMode:s,viewElement:this._playbackView?this._playbackView.view:void 0}))),this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_METADATA,this,t))}_onConnectionClosed(){Gt("Connection closed"),this.unsubscribe(!0),this.trigger(new Ce(e.SubscriberEventTypes.CONNECTION_CLOSED,this))}_onDataChannelOpen(t){Gt(`Data channel opened: ${t.label}`),this.trigger(new Ce(e.RTCSubscriberEventTypes.DATA_CHANNEL_OPEN,this,{dataChannel:t})),this.trigger(new Ce(e.RTCSubscriberEventTypes.DATA_CHANNEL_AVAILABLE,this,{name:t.label,dataChannel:t})),this._messageTransport=this._peerConnectionHelper,this.trigger(new Te(e.MessageTransportStateEventTypes.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_START,this))}_onDataChannelClose(t){Gt(`Data channel closed: ${t.label}`),this.trigger(new Ce(e.RTCSubscriberEventTypes.DATA_CHANNEL_CLOSE,this,{dataChannel:t}))}_onDataChannelMessage(t,i){Gt(`Data channel message: ${i.data}`),this.trigger(new Ce(e.RTCSubscriberEventTypes.DATA_CHANNEL_MESSAGE,this,{dataChannel:t,message:i}))}_onPeerConnectionOpen(){var t;Gt("Peer connection opened"),this.trigger(new Ce(e.RTCSubscriberEventTypes.PEER_CONNECTION_OPEN,this,this.getPeerConnection())),(null===(t=this._options)||void 0===t?void 0:t.includeDataChannel)||this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_START,this))}_onPeerConnectionFail(){xt("Peer connection failed"),this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_FAIL,this))}_onPeerConnectionClose(t){Gt(`Peer connection closed: ${t.type}`),this._evaluateRenegotiationPolicy(e.SubscriberEventTypes.CONNECTION_CLOSED)}_onIceCandidate(t){Gt(`ICE candidate: ${t.candidate}`),this.trigger(new Ce(e.RTCSubscriberEventTypes.CANDIDATE_CREATE,this,{candidate:t}))}_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(t){Gt(`Statistics endpoint changed: ${t}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(t),this.trigger(new Ce(e.SubscriberEventTypes.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:t}))}_onStatsReport(t,i){this.trigger(new Ce(e.RTCSubscriberEventTypes.STATS_REPORT,this,{connection:t,report:i}))}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)),this._evaluateRenegotiationPolicy(e,t)}getType(){return"RTC"}}const Kt={stream:3,datachannel:4},jt=[e.MessageChannelEventTypes.OPEN,e.MessageChannelEventTypes.CLOSE,e.MessageChannelEventTypes.ERROR,e.MessageChannelEventTypes.FAIL,e.PublisherEventTypes.STATISTICS_ENDPOINT_CHANGE];class Jt extends at{constructor(t,i){if(super("MessageChannelStats",t,i),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=t=>{const{type:i,data:n}=t;if(jt.indexOf(i)>-1){if(i===e.PublisherEventTypes.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=n;this.updateEndpoint(e,!1)}this.postEvent(i)}else jt.indexOf(i)>-1&&this.postEvent(i)},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(e.RTCPublisherEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(e.RTCPublisherEventTypes.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const t=({data:i})=>{this._client.off(e.RTCPublisherEventTypes.PEER_CONNECTION_AVAILABLE,t),this.start(i)};this._client.on(e.RTCPublisherEventTypes.PEER_CONNECTION_AVAILABLE,t)}}_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:h,active:d,bytesSent:c,packetsSent:u,totalPacketsSendDelay:p}=e,_={type:t,kind:r,codecId:l,mediaType:h,active:d,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:h}=e;this.post({id:t,timestamp:i,type:n,label:s,state:o,messagesSent:a,messagesReceived:r,bytesSent:l,bytesReceived:h})}}dispose(){this._client.off("*",this._eventHandler),this._client.off(e.RTCPublisherEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(e.RTCPublisherEventTypes.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),super.dispose()}}const Yt="DataChannelClient",qt=e=>D(Yt,e),Xt=e=>H(Yt,e);class Qt extends wt{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(e.MessageChannelEventTypes.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(t){const i=this.getDataChannel(),{streamName:n}=this.options?this.options:{},s=n||"unknown";if(i){let n=t;try{n="string"==typeof t?JSON.parse(t):t}catch(e){n={message:t}}const o={...n,sender_id:s,send_timestamp:(new Date).toISOString()};try{return i.send(JSON.stringify(o)),qt(`Sent message: ${JSON.stringify(o)}`),this.trigger(new fe(e.MessageChannelEventTypes.SEND,this,o)),this._startInactivePing(),!0}catch(t){Xt(`Error sending message: ${t.message||t}`),this.trigger(new fe(e.MessageChannelEventTypes.ERROR,this,{error:t.message||t}))}}return!1}async sendData(t){const i=this.getDataChannel();if(i)try{return i.send(t),this.trigger(new fe(e.MessageChannelEventTypes.SEND,this,t)),this._startInactivePing(),!0}catch(t){Xt(`Error sending data: ${t.message||t}`),this.trigger(new fe(e.MessageChannelEventTypes.ERROR,this,{error:t.message||t}))}return!1}_onDataChannelOpen(e){super._onDataChannelOpen(e),this._startInactivePing()}_onDataChannelMessage(t,i){const{data:n}=i;qt(`Incoming Data channel message: ${n}`),this.trigger(new fe(e.MessageChannelEventTypes.RECEIVE,this,{dataChannel:t,message:i}))}_onDataChannelClose(t){this._stopInactivePing(),super._onDataChannelClose(t),this.trigger(new fe(e.MessageChannelEventTypes.CLOSE,this))}_onPeerConnectionFail(){Xt("Peer connection failed"),this.trigger(new fe(e.MessageChannelEventTypes.FAIL,this))}_onSDPError(t=void 0){this.trigger(new fe(e.MessageChannelEventTypes.ERROR,this));const i=t?": "+JSON.stringify(t,null,2):"";Xt(`[onsdperror]:: ${i}`)}trigger(t){if(t.type===e.PublisherEventTypes.PUBLISH_START)super.trigger(new fe(e.MessageChannelEventTypes.OPEN,this));else if(t.type===e.PublisherEventTypes.UNPUBLISH_SUCCESS)super.trigger(new fe(e.MessageChannelEventTypes.CLOSE,this));else{const{type:e,data:i}=t;super.trigger(new fe(e,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 Ce(e.SubscriberEventTypes.SUBSCRIBE_START,this._view)),this._playingStarted=!0}_onSourceError(t){D(this._name,"[source:event] error"),this.trigger(new Ce(e.SubscriberEventTypes.CONNECT_FAILURE,void 0,t))}_onOrientationMetadata(t){const{orientation:i}=t,n=parseInt(i,10);i&&this._orientation!==n&&(D(this._name,"Metadata received: "+JSON.stringify(t,null,2)),this._orientation=n,this.trigger(new Ce(e.SubscriberEventTypes.ORIENTATION_CHANGE,{orientation:this._orientation,viewElement:this._view})),this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_METADATA,void 0,t)))}_onStreamingModeMetadata(t){const{streamingMode:i}=t,n=this._streamingMode;i&&n!==i&&(D(this._name,"Metadata received: "+JSON.stringify(t,null,2)),this._streamingMode=i,this.trigger(new Ce(e.SubscriberEventTypes.STREAMING_MODE_CHANGE,void 0,{streamingMode:this._streamingMode,previousStreamingMode:n,viewElement:this._view})),this.trigger(new Ce(e.SubscriberEventTypes.SUBSCRIBE_METADATA,void 0,t)))}_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=>k(ei,e);class ni extends Ht{constructor(){super()}_glomTrigger(e){e.on("*",e=>{const{type:t,data:i}=e;this.trigger(new Ce(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={...Nt,...e},this}async subscribe(){var t;try{const i=/^http(|s).*\.m3u8/g,{endpoint:n,mediaElementId:s}=this._options;return this._fileURL=n&&n.match(i)?n:(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&&s&&(this._playbackView=new It(s),this._sourceHandler=new Zt(this._playbackView.view,this.getType()),this._sourceHandler.addSource(this._fileURL),this._glomTrigger(this._sourceHandler)),this.trigger(new Ce(e.SubscriberEventTypes.CONNECT_SUCCESS,this,this._fileURL)),this._playIfAutoplaySet(this._options,null===(t=this._playbackView)||void 0===t?void 0:t.view),this}catch(t){throw t(t.message),this.trigger(new Ce(e.SubscriberEventTypes.CONNECT_FAILURE,this,t.message)),t}}async unsubscribe(){var t;return this._sourceHandler&&this._sourceHandler.disconnect(),null===(t=this._playbackView)||void 0===t||t.detachStream(),this._playbackView=void 0,this._sourceHandler=void 0,this.trigger(new Ce(e.SubscriberEventTypes.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={...Pt,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 hi extends be{constructor(e,t,i){super(e,i),this._slider=t}get slider(){return this._slider}}const{createElement:di,addGlobalEventListener:ci,removeGlobalEventListener:ui,globalUnassign:pi,getAssignedValue:_i,globalAssign:gi}=ie,vi="ControlSlider",mi="r5_liveseek_event_owner";class Ei extends U{constructor(e){super(),this._value=0,this._disabled=!1,this._eventStartPosition=0,this.debug=e=>D(vi,e),this.warn=e=>k(vi,e),this.name=[vi,e].join("::"),this.debug("[init]"),this._container=di("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(mi),ui("mousemove",this._mousemoveHandler),ui("mouseup",this._mouseupHandler),ui("touchmove",this._touchmoveHandler),ui("touchend",this._touchupHandler),this.trigger(new hi(li.CHANGE_COMPLETE,this))}_mousemove(e){if(_i(mi)!==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 hi(li.CHANGE,this,s))}_mousedown(e){this._eventStartPosition=e.clientX,this.trigger(new hi(li.CHANGE_START,this)),gi(mi,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=di("span");return e.classList.add("red5pro-media-slider-button"),e}createProgressBar(){const e=di("span");return e.classList.add("red5pro-media-slider-progress"),e}createTrack(){const e=di("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:bi,isTouchEnabled:Si,isPossiblySafari:Ci}=ie,Ti=e=>D("PlaybackControls",e);class yi extends ai{constructor(t,i){super(),this._state=e.PlaybackState.IDLE,this._mutedState=!1,this._resumeAfterSeek=!1,this._playbackDuration=0,this._volumeValue=1,this._player=t,this._container=i,this._onPlayPauseClickBound=this._onPlayPauseClick.bind(this),this._decorate(this._container)}_decorate(t){if(!t)return;Ti("[decorate]");const i=bi("div");let n;i.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(),i.appendChild(this._playPauseButton),i.appendChild(this._timeField),i.appendChild(this._seekTimeField.view),i.appendChild(this._muteButton),i.appendChild(this._volumeField.view),i.appendChild(this._fullScreenButton),t.appendChild(i),this._controlbar=i;const s=()=>{clearTimeout(n),n=setTimeout(()=>{i.classList.remove("red5pro-media-control-bar-show")},6e3)};Si()?(i.classList.add("red5pro-media-control-bar-show"),t.addEventListener("touchend",()=>{i.classList.toggle("red5pro-media-control-bar-show"),s()}),s()):(t.addEventListener("mouseover",()=>{i.classList.add("red5pro-media-control-bar-show")}),t.addEventListener("mouseout",()=>{i.classList.remove("red5pro-media-control-bar-show")})),this.setState(e.PlaybackState.IDLE).onFullScreenChange(!1).setSeekTime(0).enable(!1)}_onPlayPauseClick(){return this.getState()===e.PlaybackState.PLAYING?this._player.pause(!0):this.getState()===e.PlaybackState.PAUSED?this._player.resume(!0):this._player.play(!0),this}_createPlayPauseButton(){const e=bi("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=bi("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 t=new Ei("seek");return t.view.classList.add("red5pro-media-control-element"),t.view.classList.add("red5pro-media-seektime-slider"),t.view.classList.add("red5pro-media-slider"),t.on(li.CHANGE_START,()=>{this.getState()===e.PlaybackState.PLAYING&&(this._resumeAfterSeek=!0,this._player.pause(!0,!0)),this.trigger(new be(ri.SEEK_START))}),t.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)}),t.on(li.CHANGE_COMPLETE,()=>{this._resumeAfterSeek&&this.getState()===e.PlaybackState.PAUSED&&(this._resumeAfterSeek=!1,this._player.resume(!0)),this.trigger(new be(ri.SEEK_END))}),t}_createPlaybackTime(){const e=bi("span"),t=bi("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=bi("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(t){var i,n,s,o;return t===e.PlaybackState.PLAYING?(null===(i=this._playPauseButton)||void 0===i||i.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)&&Ci()?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 Ti(`[setState]: ${o[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 Ti(`[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 fi,Ai;!function(e){e[e.LIVE=0]="LIVE",e[e.VOD=1]="VOD"}(fi||(fi={})),function(e){e.LIVE="LiveSeek.LIVE",e.VOD="LiveSeek.VOD"}(Ai||(Ai={}));const wi={[fi.LIVE]:Ai.LIVE,[fi.VOD]:Ai.VOD};var Pi;!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"}(Pi||(Pi={}));const{createElement:Ni,findByQuerySelector:Ri,createHLSClient:Li,getHLSClientEventEnum:Ii}=ie,Oi="SourceHandlerSeekable",Di=e=>D(Oi,e),ki=e=>H(Oi,e),Hi=e=>k(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=Ni("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=Ri(`#${n}`);return s||(s=Ni("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(t){var i;const n=null!==(i=this._playbackNotificationCenter)&&void 0!==i?i:t.target,s=this.getControls();if(this.isSeekable){if(!this._isHLSPlaybackActive){const t=this._hlsElement.duration,i=n.currentTime-this._lastDurationUpdate,o=isNaN(t)||0===t?n.currentTime:t+this._averageSegmentDuration+i;s&&s.setSeekTime(o,o),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:o,duration:o,action:"rtc time update (1)"}))}}else super._onTimeUpdate(t)}_onEnded(){this.isHLSPlaybackActive||super._onEnded()}_onHLSDurationChange(t){const i=t.target,n=t.duration||i.duration;isNaN(this._wallOffset)&&(this._wallOffset=n-this._view.currentTime),this._lastDurationUpdate=this._view.currentTime;const s=n+this._averageSegmentDuration;Di(`[HLS:videoelement:duration] ${n}, ${this._averageSegmentDuration}`);const o=this.getControls();o&&o.setPlaybackDuration(s),this._isHLSPlaybackActive?this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:i.currentTime,duration:s,action:"hls time update"})):this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:s,duration:s,action:"hls time update"}))}_onHLSTimeUpdate(t){const i=t.target,n=this.getControls();n&&n.setSeekTime(i.currentTime,n.getPlaybackDuration()),i.currentTime>=i.duration?this._showHLSLivePlayback(!1,this._hlsElement,this._view,this._container):!isNaN(i.duration)&&this._isHLSPlaybackActive&&this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:i.currentTime,duration:i.duration+this._averageSegmentDuration,action:"hls time update"}))}_onHLSPlay(){Di("[HLS:videoelement:event] play");const t=this.getControls();t&&t.setState(e.PlaybackState.PLAYING),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PLAYING,state:o[e.PlaybackState.PLAYING]}))}_onHLSPause(){Di("[HLS:videoelement:event] pause");const t=this.getControls();t&&t.setState(e.PlaybackState.PAUSED),this.trigger(new Ce(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PAUSED,state:o[e.PlaybackState.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 Ce(Pi.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 Ce(Pi.LIVE_SEEK_ERROR,void 0,{hlsElement:e,hlsControl:t,error:n}))}else this.trigger(new Ce(Pi.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 Ce(Pi.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 Ce(Pi.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 Ce(Pi.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 Ce(Pi.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){Hi(`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){Hi(`Could not start playback: ${e.message}.`)}this._hlsElementGenerated&&(t.style.display="none")}const o=e?fi.VOD:fi.LIVE;this.trigger(new Ce(Pi.LIVE_SEEK_CHANGE,void 0,{code:o,state:wi[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 Hi(`Could not find lines in manifest: ${e}`);const a=o.reverse().find(e=>n.test(e));if(!a)return void Hi(`Could not find last segment in manifest: ${e}`);const r=o.find(e=>i.test(e));if(!r)return void Hi(`Could not find duration line in manifest: ${e}`);const l=r.match(i);if(!l)return void Hi(`Could not find duration in manifest: ${e}`);const h=l[1],d=parseFloat(h),c=a.match(n);if(!c)return void Hi(`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=d,this.isSeekable=!0,this.trigger(new Ce(Pi.LIVE_SEEK_ENABLED,void 0,{hlsElement:this._hlsElement,hlsControl:void 0})),this.onHLSDurationChange({target:t,duration:d*p}),this._manifestLoadTimeout=setTimeout(()=>{clearTimeout(this._manifestLoadTimeout),this._loadManifest(e,t)},1e3*d)}catch(e){ki(`Could not load manifest: ${e.message}.`),this.trigger(new Ce(Pi.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 yi(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=Ni("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):Li(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){Hi("[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){Hi("[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){Hi("[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=>Hi("[videoelement:action] play (CATCH::FAULT) "+(e.message?e.message:e)))}catch(e){Hi("[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){Hi("[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:ki("[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 Ce(Pi.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){Hi("[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=>H(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 k(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 Ce(Pi.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 h=ne(r,i,l);this._sourceHandler&&this._sourceHandler.switchLiveSeek(h)}super._onStreamSwitchComplete()}}const Gi="15.6.1";L(R.ERROR);const xi=(e,t=!1)=>{Object.prototype.hasOwnProperty.call(R,e.toUpperCase())&&(L(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:R,getLogger:I,getRecordedLogs:O,setLogLevel:xi,getVersion:Wi,PlaybackVideoEncoder:e.PlaybackVideoEncoder,PlaybackAudioEncoder:e.PlaybackAudioEncoder,PlaybackState:e.PlaybackState,PlaybackStateReadableMap:o,PublishVideoEncoder:e.PublishVideoEncoder,PublishAudioEncoder:e.PublishAudioEncoder,SubscriberEvent:Ce,PublisherEvent:Se,MessageTransportStateEvent:Te,PubNubEvent:ye,MessageChannelEvent:fe,PublisherEventTypes:e.PublisherEventTypes,SubscriberEventTypes:e.SubscriberEventTypes,RTCPublisherEventTypes:e.RTCPublisherEventTypes,RTCSubscriberEventTypes:e.RTCSubscriberEventTypes,MessageTransportStateEventTypes:e.MessageTransportStateEventTypes,MessageChannelEventTypes:e.MessageChannelEventTypes,WebRTCConnectionEventTypes:e.WebRTCConnectionEventTypes,PubNubEventTypes:e.PubNubEventTypes,WHIPClient:wt,WHEPClient:zt,HLSSubscriber:ni,LiveSeekClient:$i,PubNubClient:St,MessageChannel:Qt,Capability:Kt,defaultWhepSubscriberConfig:Pt,defaultWhipPublisherConfig:ve,defaultStatsConfig:ge,StatsEndpointType:e.StatsEndpointType};e.Capability=Kt,e.Event=be,e.EventEmitter=U,e.HLSSubscriber=ni,e.LOG_LEVELS=R,e.LiveSeekClient=$i,e.MessageChannel=Qt,e.MessageChannelEvent=fe,e.MessageTransportStateEvent=Te,e.PlaybackController=Ht,e.PlaybackControls=ai,e.PlaybackStateReadableMap=o,e.PubNubClient=St,e.PubNubEvent=ye,e.PublisherEvent=Se,e.SourceHandler=Mt,e.SourceHandlerImpl=Vt,e.SubscriberEvent=Ce,e.WHEPClient=zt,e.WHIPClient=wt,e.default=zi,e.defaultHLSSubscriberConfig=Nt,e.defaultLiveSeekConfig=oi,e.defaultStatsConfig=ge,e.defaultWhepSubscriberConfig=Pt,e.defaultWhipPublisherConfig=ve,e.getLogger=I,e.getRecordedLogs=O,e.getVersion=Wi,e.setLogLevel=xi,Object.defineProperty(e,"__esModule",{value:!0})});