/**
 * 
 *   red5pro-html-sdk - Red5 Pro HTML SDK - TypeScript Edition
 *   Author: Infrared5 Inc.
 *   Version: 15.0.0
 *   Url: https://www.red5.net
 * 
 *   Copyright © 2015 Infrared5, Inc. All rights reserved.
 * 
 *   The accompanying code comprising examples for use solely in conjunction with Red5 Pro (the "Example Code")
 *   is  licensed  to  you  by  Infrared5  Inc.  in  consideration  of  your  agreement  to  the  following
 *   license terms  and  conditions.  Access,  use,  modification,  or  redistribution  of  the  accompanying
 *   code  constitutes your acceptance of the following license terms and conditions.
 * 
 *   Permission is hereby granted, free of charge, to you to use the Example Code and associated documentation
 *   files (collectively, the "Software") without restriction, including without limitation the rights to use,
 *   copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 *   persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 *   The Software shall be used solely in conjunction with Red5 Pro. Red5 Pro is licensed under a separate end
 *   user  license  agreement  (the  "EULA"),  which  must  be  executed  with  Infrared5,  Inc.
 *   An  example  of  the EULA can be found on our website at: https://account.red5.net/assets/LICENSE.txt.
 * 
 *   The above copyright notice and this license shall be included in all copies or portions of the Software.
 * 
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,  INCLUDING  BUT
 *   NOT  LIMITED  TO  THE  WARRANTIES  OF  MERCHANTABILITY, FITNESS  FOR  A  PARTICULAR  PURPOSE  AND
 *   NONINFRINGEMENT.   IN  NO  EVENT  SHALL INFRARED5, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *   WHETHER IN  AN  ACTION  OF  CONTRACT,  TORT  OR  OTHERWISE,  ARISING  FROM,  OUT  OF  OR  IN CONNECTION
 *   WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).red5prosdk={})}(this,(function(e){"use strict";var t,i,n,s;e.PlaybackAudioEncoder=void 0,(t=e.PlaybackAudioEncoder||(e.PlaybackAudioEncoder={})).OPUS="OPUS",t.NONE="NONE",e.PlaybackVideoEncoder=void 0,(i=e.PlaybackVideoEncoder||(e.PlaybackVideoEncoder={})).VP8="VP8",i.H264="H264",i.H265="H265",i.NONE="NONE",e.PlaybackState=void 0,(n=e.PlaybackState||(e.PlaybackState={}))[n.UNAVAILABLE=1e3]="UNAVAILABLE",n[n.AVAILABLE=0]="AVAILABLE",n[n.IDLE=1]="IDLE",n[n.PLAYING=2]="PLAYING",n[n.PAUSED=3]="PAUSED",function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(s||(s={}));const o={[e.PlaybackState.UNAVAILABLE]:s.UNAVAILABLE,[e.PlaybackState.AVAILABLE]:s.AVAILABLE,[e.PlaybackState.IDLE]:s.IDLE,[e.PlaybackState.PLAYING]:s.PLAYING,[e.PlaybackState.PAUSED]:s.PAUSED};var r,a,l;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(r||(r={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(a||(a={})),e.PublishAudioEncoder=void 0,(e.PublishAudioEncoder||(e.PublishAudioEncoder={})).OPUS="OPUS",e.PublishVideoEncoder=void 0,(l=e.PublishVideoEncoder||(e.PublishVideoEncoder={})).VP8="VP8",l.H264="H264",l.H265="H265";var d={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},h={};function c(e){return"string"==typeof e?d[e.toLowerCase()]:e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function p(e,t,i){return p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,i){var n=[null];n.push.apply(n,t);var s=new(Function.bind.apply(e,n));return i&&u(s,i.prototype),s},p.apply(null,arguments)}function _(e){if(null==e)return e;if(Array.isArray(e))return e.slice();if("object"==typeof e){var t={};return Object.keys(e).forEach((function(i){t[i]=e[i]})),t}return e}function m(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"[ "+e.map((function(e){return m(e)})).join(", ")+" ]":"object"==typeof e?JSON.stringify(e):"function"==typeof e?"[Function: "+e.name+"]":"boolean"==typeof e||"number"==typeof e?e:"'"+e.toString()+"'"}function g(e){if("string"!=typeof e){for(var t=new Array(arguments.length),i=0;i<arguments.length;i++)t[i]=m(arguments[i]);return t.join(" ")}for(var n=1,s=arguments,o=s.length,r=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}})),a=s[n];n<o;a=s[++n])r+=null===a||"object"!=typeof a?" "+a:" "+m(a);return r}Object.keys(d).forEach((function(e){h[d[e]]=e}));var v={};function E(e,t){if(t){if(v[t])return;v[t]=!0}console.error(e+"\n")}var S=function(){function e(){}return e.prototype.write=function(e){e.level<30?console.log(e):e.level<40?console.info(e):e.level<50?console.warn(e):console.error(e),e.err&&e.err.stack&&console.error(e.err.stack),e.obj&&console.log(e.obj)},e}(),C=function(){function e(t,i,n){var s,o,r,a,l=this;if(!(this instanceof e))return new e(t,i);if(void 0!==i&&(s=t,t=i,!(s instanceof e)))throw new TypeError("invalid Logger creation: do not pass a second arg");if(!t)throw new TypeError("options (object) is required");if(s){if(t.name)throw new TypeError("invalid options.name: child cannot set logger name")}else if(!t.name)throw new TypeError("options.name (string) is required");if(t.stream&&t.streams)throw new TypeError('cannot mix "streams" and "stream" options');if(t.streams&&!Array.isArray(t.streams))throw new TypeError("invalid options.streams: must be an array");if(t.serializers&&("object"!=typeof t.serializers||Array.isArray(t.serializers)))throw new TypeError("invalid options.serializers: must be an object");if(s&&n){this._level=s._level,this.streams=s.streams,this.serializers=s.serializers,this.src=s.src,o=this.fields={};var d=Object.keys(s.fields);for(a=0;a<d.length;a++)o[r=d[a]]=s.fields[r];var h=Object.keys(t);for(a=0;a<h.length;a++)o[r=h[a]]=t[r]}else{if(s){for(this._level=s._level,this.streams=[],a=0;a<s.streams.length;a++){var c=_(s.streams[a]);this.streams.push(c)}this.serializers=_(s.serializers),this.src=s.src,this.fields=_(s.fields),t.level&&this.level(t.level)}else this._level=Number.POSITIVE_INFINITY,this.streams=[],this.serializers=null,this.src=!1,this.fields={};t.stream?this.addStream({type:"stream",stream:t.stream,level:t.level}):t.streams?t.streams.forEach((function(e){l.addStream(e,t.level)})):s&&t.level?this.level(t.level):s||this.addStream({type:"raw",stream:new S,level:t.level}),t.serializers&&this.addSerializers(t.serializers),t.src&&(this.src=!0),delete(o=_(t)).stream,delete o.level,delete o.streams,delete o.serializers,delete o.src,this.serializers&&this._applySerializers(o),Object.keys(o).forEach((function(e){l.fields[e]=o[e]}))}}var t=e.prototype;return t.addStream=function(e,t){void 0===t&&(t=30),(e=_(e)).type="raw",e.level=c(e.level||t),e.level<this._level&&(this._level=e.level),this.streams.push(e),delete this.haveNonRawStreams},t.addSerializers=function(e){var t=this;this.serializers||(this.serializers={}),Object.keys(e).forEach((function(i){var n=e[i];if("function"!=typeof n)throw new TypeError(g('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(g('no stream with name "%s"',e))}if(void 0===t)return i.level;var r=c(t);i.level=r,r<this._level&&(this._level=r)},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(g('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]=g('(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)}(g("%s\n%s",e,t.stack)),s),n=g("(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 r=this.streams[i];r.level<=o&&r.stream.write(e)}return n},e}();function b(e){return function(){var t=this;var i=null,n=arguments,s=null;if(0===arguments.length)return this._level<=e;this._level>e||(s=function(s){var o;s[0]instanceof Error?(i={err:t.serializers&&t.serializers.err?t.serializers.err(s[0]):T.err(s[0])},o={err:!0},n=1===s.length?[i.err.message]:Array.prototype.slice.call(s,1)):"object"!=typeof s[0]&&null!==s[0]||Array.isArray(s[0])?(i=null,n=Array.prototype.slice.call(s)):(i=s[0],n=1===s.length&&i.err&&i.err instanceof Error?[i.err.message]:Array.prototype.slice.call(s,1));var r=_(t.fields);r.level=e;var a=i?_(i):null;if(a&&(t.serializers&&t._applySerializers(a,o),Object.keys(a).forEach((function(e){r[e]=a[e]}))),r.levelName=h[e],r.msg=n.length?g.apply(t,n):"",r.time||(r.time=new Date),t.src&&!r.src)try{throw new Error("call-stack-error")}catch(e){var l=e.stack?function(e,t){var i=e.split("\n");i[0]&&i[0].indexOf("call-stack-error")>=0&&i.shift();var n=i[t],s=null;if(n){var o=/^\s*(at|.*@)\s*(.+)?$/.exec(n);s=Array.isArray(o)&&o[2]?o[2]:n}return s}(e.stack,2):"";l||function(e){return v[e]}("src")||E("Unable to determine src line info","src"),r.src=l||""}return r.v=1,r}(n),this._emit(s))}}function f(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var i=e.cause();i&&(t+="\nCaused by: "+f(i))}return t}C.prototype.trace=b(10),C.prototype.debug=b(20),C.prototype.info=b(30),C.prototype.warn=b(40),C.prototype.error=b(50),C.prototype.fatal=b(60);var T={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:f(e),code:e.code,signal:e.signal}:e}};const y={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class w{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,y[e.level]||"UNKNOWN",e.msg)}}let A,P;const L=e=>(t,i)=>{var n;A&&"function"==typeof A[e]&&A[e]((n=t,e=>`(${n}) ${e}`)(i))},R={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},N=(e,t=!1,i)=>{const n=[{level:e,stream:new w,type:"raw"}];if(i){const t=i.map((t=>({...t,level:e})));n.push(...t)}t&&(P=[],n.push({level:e,stream:{write:t=>{const i=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==P||P.push(i)}},type:"raw"}));A=function(){return p(C,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:n})},D=()=>(A||N(R.INFO),A),H=()=>P||[];L(R.TRACE),L(R.INFO);const k=L(R.DEBUG),I=L(R.WARN),O=L(R.ERROR);L(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 W(e){const t=G(e,"orientation");if(t)return{orientation:parseInt(t)}}function x(e){const t=G(e,"streamingMode");if(t)return{streamingMode:t}}const j=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=W(i),s=x(i),o=j(e);n&&o&&o.orientation&&o.orientation.forEach((e=>{e(n)})),s&&o&&o.streamingMode&&o.streamingMode.forEach((e=>{e(s)}))}}}))})))},z="BrowserEnvironment",J=e=>k(z,e),Y=e=>I(z,e);let q=[];const Q=()=>{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 X=!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&&Q()),1===q.length&&(J("[window:orientation:addOrientationChangeHandler]: add"),window.addEventListener("orientationchange",Q))},removeOrientationChangeHandler:e=>{q=q.filter((t=>t!==e)),0===q.length&&window.removeEventListener("orientationchange",Q)},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,X||(X=!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:r}=t,a={appVersion:n,platform:s,userAgent:o,vendor:r};return e?{...i.browserDetails,...a}:a},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:r,port:a,app:l,streamName:d}=e;if(i||s)return i||s;const h=o,c="ws"===r?"http":"https",u=5080===a?5080:443,p=l,_=t||n;if(_){const e=_.length-1;return`${"/"===_.charAt(e)?_.substring(0,e):_}/${p}/${d}.m3u8`}return`${c}://${h}:${u}/${p}/${d}.m3u8`},se=e=>{const t=new URL(e),i=t.pathname.split("/").filter((e=>e.length>0)),n="https:"===t.protocol?"https":"http",s=t.hostname;return{protocol:n,port:t.port.length>0?t.port:443,app:i[0],host:s,streamName:i[i.length-1]}},oe=(e,t="whip")=>{var i;const{endpoint:n,proxy:s}=e;if(n)return n;{const{protocol:n,host:o,port:r,app:a,streamName:l}=e,d=n.match(/^http/)?n:"ws"===n?"http":"https";return(null==s?void 0:s.enabled)?`${d}://${o}:${r}/as/${null!==(i=s.version)&&void 0!==i?i:"v1"}/proxy/${t}/${a}/${l}`:`${d}://${o}:${r}/${a}/${t}/endpoint/${l}`}},re=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}},ae=e=>{const t=e.length;return function i(...n){return n.length>=t?e(...n):function(...e){return i(...n,...e)}}},le=ae(((e,t)=>{let i=0;const n=t.length,s=[];for(;i<n;)e(t[i])&&(s[s.length]=t[i]),i+=1;return s}));var de,he,ce,ue;!function(e){e.UDP="udp",e.TCP="tcp"}(de||(de={})),function(e){e.ENCODED_FRAME="EncodedFrame",e.PACKET="Packet"}(he||(he={})),function(e){e.VIDEO="encodeVideo",e.AUDIO="encodeAudio"}(ce||(ce={})),function(e){e.VIDEO="decodeVideo",e.AUDIO="decodeAudio"}(ue||(ue={}));const pe={...{protocol:"https",port:443,app:"live",streamMode:a.LIVE,keyFramerate:3e3,mediaElementId:"red5pro-publisher",rtcConfiguration:{iceServers:[{urls:"stun:stun2.l.google.com:19302"}],iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:de.UDP,bandwidth:{audio:56,video:750},clearMediaOnUnpublish:!1,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:void 0},signalingSocketOnly:!1,enableChannelSignaling:!1,includeDataChannel:!0,disableProxy:!0,trickleIce:!0,mungeOffer:void 0,mungeAnswer:void 0,offerSDPResolution:!1};class _e 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){I(this._name,"Could not parse message as JSON. Message= "+e.data+". Error= "+t.message)}return null}addResponseHandler(e){this._responseHandlers.push(e)}respond(e){I(this._name,`respond() should be overriden. Unhandled message: ${e}`)}post(e){return I(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 me=class{constructor(e,t){this._type=e,this._data=t}get type(){return this._type}get data(){return this._data}};class ge extends me{constructor(e,t,i){super(e,i),this._publisher=t}get publisher(){return this._publisher}}class ve extends me{constructor(e,t,i){super(e,i),this._subscriber=t}get subscriber(){return this._subscriber}}class Ee extends me{constructor(e,t,i){super(e,i),this._name=t}get name(){return this._name}}var Se,Ce,be,fe,Te;e.PublisherEventTypes=void 0,(Se=e.PublisherEventTypes||(e.PublisherEventTypes={})).CONNECT_SUCCESS="Connect.Success",Se.CONNECT_FAILURE="Connect.Failure",Se.PUBLISH_START="Publish.Start",Se.PUBLISH_FAIL="Publish.Fail",Se.PUBLISH_INVALID_NAME="Publish.InvalidName",Se.UNPUBLISH_SUCCESS="Unpublish.Success",Se.PUBLISH_METADATA="Publish.Metadata",Se.PUBLISH_STATUS="Publish.Status",Se.PUBLISH_AVAILABLE="Publish.Available",Se.PUBLISH_INSUFFICIENT_BANDWIDTH="Publish.InsufficientBW",Se.PUBLISH_SUFFICIENT_BANDWIDTH="Publish.SufficientBW",Se.PUBLISH_RECOVERING_BANDWIDTH="Publish.RecoveringBW",Se.PUBLISH_SEND_INVOKE="Publish.Send.Invoke",Se.CONNECTION_CLOSED="Publisher.Connection.Closed",Se.DIMENSION_CHANGE="Publisher.Video.DimensionChange",Se.STATISTICS_ENDPOINT_CHANGE="Publisher.StatisticsEndpoint.Change",e.RTCPublisherEventTypes=void 0,(Ce=e.RTCPublisherEventTypes||(e.RTCPublisherEventTypes={})).CONSTRAINTS_ACCEPTED="WebRTC.MediaConstraints.Accepted",Ce.CONSTRAINTS_REJECTED="WebRTC.MediaConstraints.Rejected",Ce.MEDIA_STREAM_AVAILABLE="WebRTC.MediaStream.Available",Ce.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",Ce.OFFER_START="WebRTC.Offer.Start",Ce.OFFER_END="WebRTC.Offer.End",Ce.CANDIDATE_CREATE="WebRTC.Candidate.Create",Ce.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",Ce.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",Ce.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",Ce.SOCKET_MESSAGE="WebRTC.Socket.Message",Ce.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",Ce.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",Ce.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",Ce.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",Ce.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",Ce.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",Ce.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",Ce.UNSUPPORTED_FEATURE="WebRTC.Unsupported.Feature",Ce.TRANSFORM_ERROR="WebRTC.Transform.Error",Ce.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",Ce.STATS_REPORT="WebRTC.Stats.Report",e.SubscriberEventTypes=void 0,(be=e.SubscriberEventTypes||(e.SubscriberEventTypes={})).CONNECT_SUCCESS="Connect.Success",be.CONNECT_FAILURE="Connect.Failure",be.SUBSCRIBE_START="Subscribe.Start",be.SUBSCRIBE_STOP="Subscribe.Stop",be.SUBSCRIBE_FAIL="Subscribe.Fail",be.SUBSCRIBE_INVALID_NAME="Subscribe.InvalidName",be.SUBSCRIBE_METADATA="Subscribe.Metadata",be.SUBSCRIBE_STATUS="Subscribe.Status",be.SUBSCRIBE_SEND_INVOKE="Subscribe.Send.Invoke",be.SUBSCRIBE_PUBLISHER_CONGESTION="Subscribe.Publisher.NetworkCongestion",be.SUBSCRIBE_PUBLISHER_RECOVERY="Subscribe.Publisher.NetworkRecovery",be.PLAY_UNPUBLISH="Subscribe.Play.Unpublish",be.CONNECTION_CLOSED="Subscribe.Connection.Closed",be.ORIENTATION_CHANGE="Subscribe.Orientation.Change",be.STREAMING_MODE_CHANGE="Subscribe.StreamingMode.Change",be.VIDEO_DIMENSIONS_CHANGE="Subscribe.VideoDimensions.Change",be.LOADED_METADATA="Subscribe.LoadedMetadata",be.VOLUME_CHANGE="Subscribe.Volume.Change",be.SEEK_CHANGE="Subscribe.Seek.Change",be.PLAYBACK_TIME_UPDATE="Subscribe.Time.Update",be.PLAYBACK_STATE_CHANGE="Subscribe.Playback.Change",be.FULL_SCREEN_STATE_CHANGE="Subscribe.FullScreen.Change",be.AUTO_PLAYBACK_FAILURE="Subscribe.Autoplay.Failure",be.AUTO_PLAYBACK_MUTED="Subscribe.Autoplay.Muted",be.STATISTICS_ENDPOINT_CHANGE="Subscribe.StatisticsEndpoint.Change",e.RTCSubscriberEventTypes=void 0,(fe=e.RTCSubscriberEventTypes||(e.RTCSubscriberEventTypes={})).PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",fe.OFFER_START="WebRTC.Offer.Start",fe.OFFER_END="WebRTC.Offer.End",fe.ANSWER_START="WebRTC.Answer.Start",fe.ANSWER_END="WebRTC.Answer.End",fe.CANDIDATE_CREATE="WebRTC.Candidate.Create",fe.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",fe.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",fe.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",fe.SOCKET_MESSAGE="WebRTC.Socket.Message",fe.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",fe.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",fe.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",fe.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",fe.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",fe.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",fe.ON_ADD_STREAM="WebRTC.Add.Stream",fe.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",fe.SUBSCRIBE_STREAM_SWITCH="WebRTC.Subscribe.StreamSwitch",fe.TRANSFORM_ERROR="WebRTC.Transform.Error",fe.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",fe.STATS_REPORT="WebRTC.Stats.Report",e.MessageTransportStateEventTypes=void 0,(Te=e.MessageTransportStateEventTypes||(e.MessageTransportStateEventTypes={})).OPEN="MessageTransport.Open",Te.CLOSE="MessageTransport.Close",Te.CHANGE="MessageTransport.Change",Te.ERROR="MessageTransport.Error";class ye extends _e{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 Ee(e.MessageTransportStateEventTypes.CLOSE,this._name,{socket:this,event:i}))}}_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?(k(this._name,`[datachannel-response]: ${JSON.stringify(t,null,2)}`),this._handleMessageContent(t)):(I(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:r}=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,r={...n,senderName:t,dcLabel:i};return this._responder.onSendReceived(o,r),!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||!r)&&this._handleAsyncResponse(r,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();try{k(this._name,`[peerconnection:setUpWithPeerConfiguration]: ${JSON.stringify(e,null,2)}`);const i=new RTCPeerConnection(e);return t&&(this._dataChannel=i.createDataChannel(t.name,{ordered:!0}),this._addDataChannelHandlers(this._dataChannel)),this._addConnectionHandlers(i),this._peerConnection=i,i}catch(e){throw I(this._name,`Could not establish a PeerConnection. ${e.message}`),new Error(e.message)}}tearDown(){if(this._dataChannel){k(this._name,"[teardown:datachannel]"),this._removeDataChannelHandlers(this._dataChannel);try{this._dataChannel.close()}catch(e){I(this._name,`[datachannel.close] error: ${e.message}`)}finally{this._dataChannel=void 0}}if(this._peerConnection){k(this._name,"[teardown:peerconnection]"),this._removeConnectionHandlers(this._peerConnection);try{this._peerConnection.close()}catch(e){I(this._name,`[peerconnection.close] error: ${e.message}`)}finally{this._peerConnection=void 0}}}async setLocalDescription(e){var t;return k(this._name,"[setlocaldescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setLocalDescription(e)}async setRemoteDescription(e){var t;return k(this._name,"[setremotedescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setRemoteDescription(new RTCSessionDescription(e))}async addIceCandidate(e){var t;return k(this._name,"[addcandidate]"),null===(t=this._peerConnection)||void 0===t?void 0:t.addIceCandidate(e)}async waitToGatherIce(e=5e3){const t=this._peerConnection;return k(this._name,"[waittogatherice]"),new Promise((i=>{if("complete"===t.iceGatheringState)k(this._name,"[waittogatherice] ice gathering state complete."),t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{I(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}));else{k(this._name,"[waittogatherice] waiting...");const n=setTimeout((()=>{clearTimeout(n),t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{I(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}))}),e);t.onicegatheringstatechange=()=>{clearTimeout(n),k(this._name,"[waittogatherice] ice gathering state complete."),"complete"===t.iceGatheringState&&t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{I(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);k(this._name,`[datachannel.send] message: ${t}`);try{return this._dataChannel.send(t),Promise.resolve(!0)}catch(e){O(this._name,e.message)}}return Promise.resolve(!1)}get connection(){return this._peerConnection}get dataChannel(){return this._dataChannel}}const we=[{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}],Ae=e=>"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||e,Pe=ae(((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)?Ae(e.video.width):0,o=(null===(n=e.video)||void 0===n?void 0:n.height)?Ae(e.video.height):0,r=s===t.width&&o===t.height;return r&&k("[gum:isExact]",`Found matching resolution for ${t.width}, ${t.height}.`),r})),Le=ae(((e,t)=>{const i=le(Pe(t))(e);return k("[gum:hasMatchingFormat]","Filtered list: "+JSON.stringify(i,null,2)),i.length>0})),Re=ae(((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)?Ae(e.video.width):0)*((null===(n=e.video)||void 0===n?void 0:n.height)?Ae(e.video.height):0);return t.width*t.height<s})),Ne=ae(((e,t)=>{const i=Re(t);return le(i)(e)})),De=async e=>{k("[gum:determineSupportedResolution]","Determine next neighbor based on constraints: "+JSON.stringify(e,null,2));const t=Ne(we)(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)},He=async e=>{let t;const i=Le(we),n=async t=>{if(t){const e="string"==typeof t?t:[t.name,t.message].join(": ");k("[gum:getUserMedia]",`Failure in getUserMedia: ${e}. Attempting other resolution tests...`)}return await De(e)};if((e=>e.video&&"object"==typeof e.video&&(e.video.width||e.video.height))(e)){if(!i(e))return await n(void 0);{k("[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:Ae(e.video.width)}),(null===(i=e.video)||void 0===i?void 0:i.height)&&(n.video.height={exact:Ae(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)}},ke=(e,t,i)=>{const n="a=end-of-candidates",s=/^a=candidate:/,o=/^a=ice-ufrag:/,r=/^a=ice-pwd:/,a=/^m=(audio|video|application)\ /,l=e.split("\r\n");let d,h="",c="";const u=[];l.forEach((e=>{!d&&a.exec(e)?d=e:o.exec(e)?h=e:r.exec(e)?c=e:s.exec(e)&&(t&&-1!=e.indexOf(t)?u.push(e):t||u.push(e))})),i&&u[u.length-1]!==n&&u.push(n);return[h,c,d,"a=mid:0"].concat(u).join("\r\n")},Ie="RTCPeerConnectionPublisher";class Oe extends ye{constructor(e){super(e,Ie)}_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;k(Ie,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(k(this._name,"[peerconnection:open]"),this._responder.onPeerConnectionOpen()):"failed"!==t&&"disconnected"!==t||(I(this._name,"[peerconnection:error]"),"failed"===t&&this._responder.onPeerConnectionFail())},e.oniceconnectionstatechange=i=>{const{iceConnectionState:n}=e;k(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionClose(i)):"disconnected"===n?t=setTimeout((()=>{k(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached. Closing PeerConnection."),clearTimeout(t),this._responder.onPeerConnectionClose(i)}),3e3):t&&(k(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;k(this._name,`[peer.onicecandidate] - Peer Candidate: ${null==t?void 0:t.candidate}`),t&&this._responder.onIceCandidate(t)},e.ontrack=e=>{k(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 I(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0;k(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):(k(Ie,`[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):I(Ie,"PeerConnection not initialized. Cannot add track.")}async postUnpublish(e){const t=this.post({unpublish:e});return k(Ie,`[peerconnection:unpublish] complete: ${t}`),t}async createOfferWithoutSetLocal(e=null){var t;k(Ie,`[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,r=t.indexOf("m=video"),a=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),r=(t=[s,"b=AS:"+e.audio,o].join("\r\n")).indexOf("m=video"),a=t.indexOf("m=application")),r>-1&&e.video&&(n=t.indexOf("\r\n",r),s=t.slice(0,n),o=t.slice(n+2,t.length),a=(t=[s,"b=AS:"+e.video,o].join("\r\n")).indexOf("m=application")),a>-1&&e.dataChannel&&(n=t.indexOf("\r\n",a),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 k(Ie,"[createoffer:error]"),this._responder.onSDPError(e),e}}async updateBandwidthRequest(e=null){var t;k(Ie,`[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{k(Ie,`[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=>{O(Ie,`[updatebandwidthrequest:error]:: ${e.message}`)}))}return!0}catch(e){O(Ie,`[updatebandwidthrequest:error]:: ${e.message}`)}return!1}}class Me extends Error{constructor(e){super(e),this.name="InvalidNameError"}}const Ue="WhipWhepSignalingHelper",Be=new Map;Be.set(400,"Invalid offer SDP."),Be.set(401,"Not authorized."),Be.set(404,"Scope resolver failed for the publish name and / or scope."),Be.set(405,"Remember to update the URL passed into the WHIP or WHEP client."),Be.set(406,"Scope connection rejected."),Be.set(409,"Session already initialized."),Be.set(412,"Invalid request body."),Be.set(417,"Session lookup or creation failure.");const Ve=new Map;Ve.set(400,"Offer already sent, double POST assumed."),Ve.set(401,"Not authorized."),Ve.set(404,"Scope resolver failed for the playback name and / or scope."),Ve.set(406,"Playback failed due to an exception during creation."),Ve.set(409,"Stream is not available to playback.");const Fe=["transcode"];var $e;!function(e){e.ICE_SERVER="ice-server",e.STATISTICS="statistics"}($e||($e={}));const Ge=e=>e&&(e=>{const t=/[?&](.*)=([^&#]*)/.exec(e);return t&&t.length>0})(e)?"&":"?",We=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 xe{constructor(e,t=!1,i=!0){k(Ue,`[whipwhep] ${e}`),this._url=e,this._origin=void 0,this._forceHost=i,this._resource=void 0,this._enableSignalingChannel=t}async getOptions(e={}){let t=`${this._url}${Ge(this._url)}signal=${this._enableSignalingChannel}`;e&&Object.keys(e).forEach((i=>{t+=`&${i}=${e[i]}`})),k(Ue,`[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="${$e.ICE_SERVER}"`)>-1){const e=We(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),r=e.get("username"),a=e.get("credential");s&&o&&r&&a?i.push({username:r,credential:a,urls:t}):t&&i.push({urls:t})}else if(n.indexOf(`rel="${$e.STATISTICS}"`)>-1){const e=We(n).get("url");e&&(s=e)}})),k(Ue,`[whipwhep-links]: ${JSON.stringify(i)}`),k(Ue,`[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 O(Ue,e.message),e}}async postSDPOffer(e,t={},i=!0){let n=`${this._url}${Ge(this._url)}signal=${this._enableSignalingChannel}`;t&&Object.keys(t).forEach((e=>{-1===Fe.indexOf(e)&&(n+=`&${e}=${t[e]}`)})),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n+=`&host=${this._origin}`),k(Ue,`[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:r}=s;if(r&&r.forEach(((e,t)=>{k(Ue,`[header] ${t}: ${e}`)})),o>=200&&o<300){const e=await s.text(),t=r.get("Location")||r.get("location");if(t){if(t.match(/^(http|https)/))this._resource=t;else{k(Ue,`[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 k(Ue,`[whipwhep-response] ${this._resource}: ${e}`),{sdp:e,location:this._resource}}return I(Ue,"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&&Be.get(o)){if(k(Ue,Be.get(o)),404===o||409===o)throw new Me(Be.get(o));throw new Error(Be.get(o))}if(!i&&Ve.get(o)){if(k(Ue,Ve.get(o)),404===o||409===o)throw new Me(Ve.get(o));throw new Error(Ve.get(o))}{const e=await s.text();throw Error(e)}}catch(e){throw O(Ue,e.message),e}}async postSDPAnswer(e,t={}){k(Ue,`[whipwhep:post-answer] ${this._resource}: `+JSON.stringify(e,null,2));let i=this._resource,n=Ge(i);t&&Object.keys(t).forEach((e=>{-1===Fe.indexOf(e)&&(n=Ge(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(Ve.get(n))throw k(Ue,Ve.get(n)),new Error(Ve.get(n));{const e=await t.text();throw Error(e)}}catch(e){throw O(Ue,e.message),e}}async trickle(e,t={}){k(Ue,`[whipwhep-trickle] ${this._resource}: `+JSON.stringify(e,null,2));let i=this._resource,n=Ge(i);t&&Object.keys(t).forEach((e=>{-1===Fe.indexOf(e)&&(n=Ge(i),i+=`${n}${e}=${t[e]}`)})),this._forceHost&&this._origin&&!(null==t?void 0:t.host)&&(n=Ge(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 k(Ue,`[whipwhep-response] ${this._resource}: ${e}`),{candidate:e}}if(405===n)throw k(Ue,"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 O(Ue,e.message),e}}async tearDown(e={},t=!1){if(!this._resource)return;let i=this._resource,n=Ge(i);e&&Object.keys(e).forEach((t=>{-1===Fe.indexOf(t)&&(n=Ge(i),i+=`${n}${t}=${e[t]}`)})),this._forceHost&&this._origin&&!(null==e?void 0:e.host)&&(n=Ge(i),i+=`${n}host=${this._origin}`),k(Ue,"[whipwhep-teardown]");try{await fetch(i,{method:"DELETE",mode:"cors"})}catch(e){if(O(Ue,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 k(Ue,"[whipwhep:post] transport called."),Promise.resolve(!1)}async postAsync(){return k(Ue,"[whipwhep:postAsync] transport called."),Promise.resolve(null)}getUrl(){return this._url}}const je="R5ProPublishView";class Ke{constructor(e="red5pro-publisher"){try{this._targetElement=ie.resolveElement(e)}catch(e){throw O(je,`Could not instantiate a new instance of PublishView. Reason: ${e.message}`),e}}preview(e){const t=this.isAutoplay;k(je,`[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}}const ze={endpoint:null,interval:5e3,include:[]};var Je;!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"}(Je||(Je={}));class Ye{constructor(e,t,i){this._name="RTCStatsMonitor",this._queue=[],this._startTime=0,this._stopped=!1,this._interval=0,this._name=e,this._config={...ze,...t},this._client=i,this._identifier={name:this._name,created:(new Date).getTime(),fingerprint:ie.getOrGenerateFingerprint(),device:ie.getBrowserDetails(),client:t}}_emptyStatsReportQueue(){for(;this._queue.length>0;){const e=this._client.getMessageTransport();if(e){const t=this._queue.shift();e.post(t)}else I(this._name,"Failed to post stats data to message transport. Message transport is not available.")}}_getStats(){const{_connection:e}=this;if(e&&"connected"===e.connectionState)try{e.getStats(null).then((e=>{e.forEach((e=>{this._handleStatsReport(e)}))})).catch((e=>{O(this._name,`Failed to get stats report. ${e.message||e}`)}))}catch(e){O(this._name,`Failed to get stats report. ${e.message||e}`)}}_handleStatsReport(e){console.log(`[${this._name}]: ${JSON.stringify(e,null,2)}`)}_appendClientDetails(e){this._identifier.client={...this._identifier.client,...e}}async start(e){this._startTime=(new Date).getTime(),this._stopped=!1,this._connection=e,this.postAction("started"),this._getStats(),this._interval=setInterval((()=>{this._stopped||this._getStats()}),this._config.interval)}stop(){this._stopped=!0,clearInterval(this._interval),this.postAction("ended")}async post(t){const i={...this._identifier,type:"stats-report",timestamp:(new Date).getTime(),data:t},{endpoint:n,additionalHeaders:s}=this._config;if(this._client&&this._client.onStatsReport&&null===n)return void this._client.onStatsReport(this._connection,i);let o={"Content-Type":"application/json"};if(s&&(o={...o,...s}),n)try{const e=await fetch(n,{method:"POST",headers:o,body:JSON.stringify(i)});e.status>=200&&e.status<300?k(this._name,`Posted stats data to endpoint: ${n}.`):O(this._name,`Failed to post stats data to endpoint: ${n}. ${e.status}`)}catch(e){O(this._name,`Failed to post stats data to endpoint: ${n}. ${e.message||e}`)}else if(this._client&&this._client.getMessageTransport())try{let t=!1;const n=this._client.getMessageTransport();n&&(t=await n.post(i)),t||(this._queue.push(i),this._client.on(e.MessageTransportStateEventTypes.CHANGE,(()=>{this._client.off(e.MessageTransportStateEventTypes.CHANGE),this._emptyStatsReportQueue()})),I(this._name,"Failed to post stats data to message transport. Message transport is not available. Pushed to Queue."))}catch(e){O(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)}dispose(){this.stop(),this._connection=void 0,this._client=void 0}}const qe=/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b) \d+ typ srflx/,Qe=e=>{const t=e.match(qe);return t&&t.length>1?t[1]:null},Xe=[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 Ze extends Ye{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(Xe.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=Qe(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===Je.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===Je.CANDIDATE_PAIR){const{availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o}=e;this.post({type:t,availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o})}else if(t===Je.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([Je.OUTBOUND,"outboundrtp"].indexOf(t)>-1){const{timestamp:i,kind:n,codecId:s,mediaType:o,active:r,bytesSent:a,packetsSent:l,totalPacketsSendDelay:d}=e,h={type:t,kind:n,codecId:s,mediaType:o,active:r,bytesSent:a,packetsSent:l,totalPacketsSendDelay:d};if("audio"===n){if(this.lastAudioReport){const{bytesSent:e,timestamp:t}=this.lastAudioReport,n=8*(a-e)/(i-t);this.estimatedAudioBitrate=n}this.post({...h,estimatedBitrate:Math.floor(this.estimatedAudioBitrate)}),this.lastAudioReport=e}else if("video"===n){const{firCount:t,pliCount:n,frameWidth:s,frameHeight:o,framesEncoded:r,framesPerSecond:l,framesSent:d,keyFramesEncoded:c,qualityLimitationReason:u,qualityLimitationDurations:p}=e;let _={...h,firCount:t,pliCount:n,frameWidth:s,frameHeight:o,framesEncoded:r,framesPerSecond:l,framesSent:d,keyFramesEncoded:c,qualityLimitationReason:"none"!==u?u:void 0,qualityLimitationDurations:"none"!==u?p:void 0};if(this.lastVideoReport){const{bytesSent:e,timestamp:t}=this.lastVideoReport,n=8*(a-e)/(i-t);this.estimatedVideoBitrate=n}this.post({..._,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 et="WHIPClient",tt=pe,it=e=>k(et,e),nt=e=>O(et,e),st=e=>I(et,e);class ot extends U{constructor(e,t,i){super();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){it("Requesting gUM from user-defined configuration:onGetUserMedia.");const t=await s();return this.trigger(new ge(e.RTCPublisherEventTypes.CONSTRAINTS_ACCEPTED,this,re(t))),t}{const{mediaConstraints:s}=t;let o;it(`Requesting gUM using mediaConstraints: ${JSON.stringify(s,null,2)}`);let r=s;const a=await He(r);return a&&a.media||(o=await ie.gUM(r)),o=null!==(i=null==a?void 0:a.media)&&void 0!==i?i:o,r=null!==(n=null==a?void 0:a.constraints)&&void 0!==n?n:s,it(`Constraints accepted: ${JSON.stringify(r,null,2)}`),this.trigger(new ge(e.RTCPublisherEventTypes.CONSTRAINTS_ACCEPTED,this,{constraints:r,...re(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 ge(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 ge(e.RTCPublisherEventTypes.MEDIA_STREAM_AVAILABLE,this,i)),this.preview(i),i}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){st(`[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){st(`[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:r,keyFramerate:a,iceTransport:l,connectionParams:d,mediaConstraints:h,forceVP8:c,audioEncoding:u,offerSDPResolution:p}=this._options;c&&!s&&(s=e.PublishVideoEncoder.VP8);let _=n;o&&(it(`[MUNGE:before] offer: ${_}`),_=o(_),it(`[MUNGE:after] offer: ${_}`)),p&&(it(`[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 r=o.length;const a=/^m=video/;for(;--r>-1;)if(a.exec(o[r])){for(;++r<o.length;)if(o[r].indexOf("a=mid")>-1){o.splice(r+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){I("[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){I("[determineMediaResolution]",`Could not determine resolution from MediaConstraints. ${e.message||e}`)}return i&&k("[determineMediaResolution]",`constraints: ${JSON.stringify(i,null,2)}`),i})(this._mediaStream,h)),it(`[MUNGE:after] offer: ${_}`));const m={...d,mode:r,transport:l,keyFramerate:a};return s&&(m.videoEncoding=s),u&&(m.audioEncoding=u),await(null===(i=this._whipWhepService)||void 0===i?void 0:i.postSDPOffer(_,m))}catch(t){throw nt(t.message||t),t instanceof Me?this.trigger(new ge(e.PublisherEventTypes.PUBLISH_INVALID_NAME,this)):(this.trigger(new ge(e.PublisherEventTypes.CONNECT_FAILURE,this,t)),this.unpublish()),t}}async postCandidateFragments(e){var t;const{connectionParams:i}=this._options,n=ke(e,void 0,!0);return await(null===(t=this._whipWhepService)||void 0===t?void 0:t.trickle(n,i))}async init(e){var t;this._options={...tt,...e};const i=oe(this._options),{includeDataChannel:n,disableProxy:s}=this._options;return this._whipWhepService=new xe(i,n,s),this._messageTransport=this._whipWhepService,(null===(t=this._options)||void 0===t?void 0:t.stats)&&this.monitorStats(this._options.stats),this._mediaStream=await this.getAndPreviewStreamIfAvailable(),this}async initWithStream(e,t){return this._mediaStream=t,this.init(e)}async publish(t){var i,n,s,o;t&&(this._options.streamName=t);const{forceVP8:r,audioEncoding:a,rtcConfiguration:l,dataChannelConfiguration:d,includeDataChannel:h,signalingSocketOnly:c,enableChannelSignaling:u,connectionParams:p,bandwidth:_,mungeAnswer:m}=this._options;let{videoEncoding:g}=this._options;r&&(g=e.PublishVideoEncoder.VP8,this._options.videoEncoding=g),this._mediaStream||(this._mediaStream=await this.getAndPreviewStreamIfAvailable());try{const t=null!=p?p:{};if(p){const{transcode:e}=p;e&&(t.transcode=e)}const o=await(null===(i=this._whipWhepService)||void 0===i?void 0:i.getOptions(t));(null==o?void 0:o.links)&&(this._options.rtcConfiguration={...l,iceServers:o.links}),(null==o?void 0:o.origin)&&this.trigger(new ge(e.RTCPublisherEventTypes.HOST_ENDPOINT_CHANGED,this,{endpoint:o.origin})),(null==o?void 0:o.statisticsEndpoint)&&this._onStatisticsEndpointChange(o.statisticsEndpoint);const r=h||u||c?d:void 0;this._peerConnectionHelper=new Oe({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,r),this.trigger(new ge(e.RTCPublisherEventTypes.PEER_CONNECTION_AVAILABLE,this,this.getPeerConnection())),this._mediaStream.getTracks().forEach((e=>{var t;null===(t=this.getPeerConnection())||void 0===t||t.addTransceiver(e,{direction:"sendonly"})})),this.reorderCodecPreferences(this.getPeerConnection(),g,a);const v=await(null===(n=this._peerConnectionHelper)||void 0===n?void 0:n.createOfferWithoutSetLocal(_));await this._peerConnectionHelper.setLocalDescription(v),this.trigger(new ge(e.RTCPublisherEventTypes.OFFER_START,this,v));const{sdp:E}=await this.postOffer(v);let S=E;m&&(it(`[MUNGE:before] answer: ${S}`),S=m(S),it(`[MUNGE:after] answer: ${S}`)),await this._peerConnectionHelper.setRemoteDescription({type:"answer",sdp:S}),this.trigger(new ge(e.RTCPublisherEventTypes.OFFER_END,this,S));const C=await this._peerConnectionHelper.waitToGatherIce(),{sdp:b}=C;return await this.postCandidateFragments(b),this.trigger(new ge(e.RTCPublisherEventTypes.ICE_TRICKLE_COMPLETE,this)),ie.addOrientationChangeHandler(this._onOrientationChange),(null===(s=this._options)||void 0===s?void 0:s.includeDataChannel)||this.trigger(new ge(e.PublisherEventTypes.PUBLISH_START,this)),this}catch(t){throw nt(null!==(o=t.message)&&void 0!==o?o:"Could not publish."),this.trigger(new ge(e.PublisherEventTypes.CONNECT_FAILURE,this,t)),this.unpublish(!0),t}}async unpublish(t=!1){var i;it("[unpublish]"),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,t),(null===(i=this._options)||void 0===i?void 0:i.clearMediaOnUnpublish)&&this.unpreview(),this._mediaStream=void 0,this._peerConnectionHelper=void 0,this._whipWhepService=void 0,this._messageTransport=void 0,this._publishView=void 0,this.trigger(new ge(e.PublisherEventTypes.UNPUBLISH_SUCCESS,this)),ie.removeOrientationChangeHandler(this._onOrientationChange)}preview(e){it("[preview]");const{mediaElementId:t}=this._options;t&&(this._publishView=new Ke(t),this._publishView.preview(e))}unpreview(){it("[unpreview]"),this._mediaStream&&this._mediaStream.getTracks().forEach((e=>{e.stop()})),this._publishView&&this._publishView.unpreview(),this._publishView=void 0}monitorStats(e){it("[monitorStats]");const{host:t,endpoint:i,app:n,streamName:s,connectionParams:o}=this._options,r=null!=e?e:ze;return this._statisticsConfiguration={...r,host:t,hostEndpoint:i,app:n,streamName:s,connectionParams:o},this._statsMonitor?st("Cannot monitor stats without a Peer Connection. Please call `init` before calling `monitorStats`."):this._statsMonitor=new Ze(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)}),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}})}send(e,t){var i;return null===(i=this.getMessageTransport())||void 0===i?void 0:i.post({send:{method:e,data:"string"==typeof t?JSON.parse(t):t}})}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){nt(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;nt("Could not send log to server. Message parameter expected to be String or JSON-serializable object."),nt(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}_onDataChannelError(t,i){nt(`Data channel error: ${i}`),this.trigger(new ge(e.RTCPublisherEventTypes.DATA_CHANNEL_ERROR,this,{dataChannel:t,error:i}))}_onSendReceived(t,i){it(`Send received: ${t} ${JSON.stringify(i)}`),"onMetaData"===t?this._onMetaData(i):this.trigger(new ge(e.PublisherEventTypes.PUBLISH_SEND_INVOKE,this,{methodName:t,data:i}))}_onMetaData(t){it(`Metadata received: ${JSON.stringify(t)}`),this.trigger(new ge(e.PublisherEventTypes.PUBLISH_METADATA,this,t))}_onConnectionClosed(){it("Connection closed"),this.unpublish(),this.trigger(new ge(e.PublisherEventTypes.CONNECTION_CLOSED,this))}_onDataChannelOpen(t){it(`Data channel opened: ${t.label}`),this.trigger(new ge(e.RTCPublisherEventTypes.DATA_CHANNEL_OPEN,this,{dataChannel:t})),this.trigger(new ge(e.RTCPublisherEventTypes.DATA_CHANNEL_AVAILABLE,this,{name:t.label,dataChannel:t})),this._messageTransport=this._peerConnectionHelper,this.trigger(new Ee(e.MessageTransportStateEventTypes.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new ge(e.PublisherEventTypes.PUBLISH_START,this))}_onDataChannelClose(t){it(`Data channel closed: ${t.label}`),this.trigger(new ge(e.RTCPublisherEventTypes.DATA_CHANNEL_CLOSE,this,{dataChannel:t}))}_onDataChannelMessage(t,i){it(`Data channel message: ${i.data}`),this.trigger(new ge(e.RTCPublisherEventTypes.DATA_CHANNEL_MESSAGE,this,{dataChannel:t,message:i}))}_onPeerConnectionTrackAdd(t){it(`Peer connection track added: ${t.id}`),this.trigger(new ge(e.RTCPublisherEventTypes.TRACK_ADDED,this,{track:t}))}_onPeerConnectionOpen(){it("Peer connection opened"),this.trigger(new ge(e.RTCPublisherEventTypes.PEER_CONNECTION_OPEN,this,this.getPeerConnection()))}_onPeerConnectionFail(){nt("Peer connection failed"),this.trigger(new ge(e.PublisherEventTypes.PUBLISH_FAIL,this))}_onPeerConnectionClose(t){it(`Peer connection closed: ${t.type}`),this._peerConnectionHelper&&this._peerConnectionHelper.tearDown(),this.trigger(new ge(e.PublisherEventTypes.CONNECTION_CLOSED,this,t))}_onIceCandidate(t){it(`ICE candidate: ${JSON.stringify(t,null,2)}`),this.trigger(new ge(e.RTCPublisherEventTypes.CANDIDATE_CREATE,this,{candidate:t}))}_onUnpublish(){it("Unpublish received")}_onPublisherStatus(t){it("[publisherstatus] - "+JSON.stringify(t,null,2)),t.code&&"NetStream.Publish.IsAvailable"===t.code?this.trigger(new ge(e.PublisherEventTypes.PUBLISH_AVAILABLE,this,t)):this.trigger(new ge(e.PublisherEventTypes.PUBLISH_STATUS,this,t))}_onInsufficientBandwidth(t){this.trigger(new ge(e.PublisherEventTypes.PUBLISH_INSUFFICIENT_BANDWIDTH,this,t))}_onSufficientBandwidth(t){this.trigger(new ge(e.PublisherEventTypes.PUBLISH_SUFFICIENT_BANDWIDTH,this,t))}_onRecoveringBandwidth(t){this.trigger(new ge(e.PublisherEventTypes.PUBLISH_RECOVERING_BANDWIDTH,this,t))}_onSDPSuccess(e=void 0){const t=e?": "+JSON.stringify(e,null,2):"";it(`[onsdpsuccess]:: ${t}`)}_onSDPError(t=void 0){this.trigger(new ge(e.PublisherEventTypes.PUBLISH_FAIL,this));const i=t?": "+JSON.stringify(t,null,2):"";nt(`[onsdperror]:: ${i}`)}_onOrientationChange(e){const t=this.getMessageTransport();t&&t.post({send:{method:"onMetaData",data:{deviceOrientation:e}}})}_onStatisticsEndpointChange(t){it(`Statistics endpoint changed: ${t}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(t),this.trigger(new ge(e.PublisherEventTypes.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:t}))}_onStatsReport(t,i){this.trigger(new ge(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)}getType(){return"RTC"}}const rt={...{protocol:"https",port:443,app:"live",autoLayoutOrientation:!0,mediaElementId:"red5pro-subscriber",rtcConfiguration:{iceServers:[{urls:"stun:stun2.l.google.com:19302"}],iceCandidatePoolSize:2,bundlePolicy:"max-bundle"},iceTransport:de.UDP,muteOnAutoplayRestriction:!0,maintainConnectionOnSubscribeErrors:!1,dataChannelConfiguration:{name:"red5pro"},signalingSocketOnly:!1,includeDataChannel:!0,maintainStreamVariant:!1,buffer:0,stats:void 0},signalingSocketOnly:!1,enableChannelSignaling:!1,includeDataChannel:!0,disableProxy:!0,trickleIce:!0,postEmptyOffer:!1,mungeOffer:void 0,mungeAnswer:void 0},at={protocol:"https",port:443,app:"live",mediaElementId:"red5pro-subscriber",muteOnAutoplayRestriction:!0},lt="R5ProPlaybackView";class dt{constructor(e="red5pro-subscriber"){try{this._targetElement=ie.resolveElement(e)}catch(e){throw O(lt,`Could not instantiate a new instance of Red5ProSubscriber. Reason: ${e.message||e}`),e}}attachStream(e){const t=this.isAutoplay;k(lt,"[attachstream]"),ie.setVideoSource(this._targetElement,e,t)}detachStream(){k(lt,"[detachstream]"),ie.setVideoSource(this._targetElement,null,this.isAutoplay)}get isAutoplay(){return ie.hasAttributeDefined(this._targetElement,"autoplay")}get view(){return this._targetElement}}const ht="RTCPeerConnectionSubscriber";class ct extends ye{constructor(e){super(e,ht)}_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;k(ht,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(k(this._name,"[peerconnection:open]"),this._responder.onPeerConnectionOpen()):"failed"!==t&&"disconnected"!==t||(I(this._name,"[peerconnection:error]"),"failed"===t&&this._responder.onPeerConnectionFail())},e.oniceconnectionstatechange=i=>{const{iceConnectionState:n}=e;k(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionFail(),this._responder.onPeerConnectionClose(i)):"disconnected"===n?t=setTimeout((()=>{k(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached. Closing PeerConnection."),clearTimeout(t),this._responder.onPeerConnectionClose(i)}),3e3):t&&(k(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;k(this._name,`[peer.onicecandidate] - Peer Candidate: ${null==t?void 0:t.candidate}`),t&&this._responder.onIceCandidate(t)}}_onDataChannelMessage(e){const t=e;if(super._onDataChannelMessage(e))return!0;const i=this.getJsonFromSocketMessage(t);if(null===i)return I(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0;k(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):(k(ht,`[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 ut;!function(e){e.EMPTY="Empty",e.VIDEO="Video",e.AUDIO="Audio",e.FULL="Video/Audio"}(ut||(ut={}));class pt extends U{trigger(e){super.trigger(e)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}class _t extends pt{}const mt=[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 gt extends Ye{constructor(t,i){if(super("RTCSubscriberStats",t,i),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=t=>{const{type:i,data:n}=t;if(mt.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=Qe(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===Je.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===Je.CANDIDATE_PAIR){const{availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o}=e;this.post({type:t,availableOutgoingBitrate:i,currentRoundTripTime:n,totalRoundTripTime:s,state:o})}else if([Je.INBOUND,"inboundrtp"].indexOf(t)>-1){const{timestamp:i,kind:n,codecId:s,jitter:o,packetsLost:r,packetsReceived:a,bytesReceived:l}=e,d={type:t,kind:n,codecId:s,jitter:o,packetsLost:r,packetsReceived:a,bytesReceived:l};if("audio"===n){const{packetsDiscarded:t}=e;if(this.lastAudioReport){const{bytesReceived:e,timestamp:t}=this.lastAudioReport,n=8*(l-e)/(i-t);this.estimatedAudioBitrate=n}this.post({...d,packetsDiscarded:t,estimatedBitrate:Math.floor(this.estimatedAudioBitrate)}),this.lastAudioReport=e}else if("video"===n){const{firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:r,framesPerSecond:a,framesReceived:h,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:m,totalFreezesDuration:g,totalPausesDuration:v}=e,E={...d,firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:r,framesPerSecond:a,framesReceived:h,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:m,totalFreezesDuration:g,totalPausesDuration:v};if(this.lastVideoReport){const{bytesReceived:e,timestamp:t}=this.lastVideoReport,n=8*(l-e)/(i-t);this.estimatedVideoBitrate=n}this.post({...E,estimatedBitrate:Math.floor(this.estimatedVideoBitrate)}),this.lastVideoReport=e}}}dispose(){this._client.off("*",this._eventHandler),this._client.off(e.RTCSubscriberEventTypes.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(e.RTCSubscriberEventTypes.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),super.dispose()}}class vt extends _t{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 ve(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;k(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 ve(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.AVAILABLE,state:s.AVAILABLE})),this.trigger(new ve(e.SubscriberEventTypes.VOLUME_CHANGE,void 0,{volume:n.volume}))}_onDurationChange(e){var t;k(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(){k(this._name,"[videoelement:event] ended");const t=this.getControls();t&&t.setState(e.PlaybackState.IDLE),this.trigger(new ve(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 ve(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:n.currentTime,duration:n.duration}))}_onPlay(){k(this._name,"[videoelement:event] play");const t=this.getControls();t&&t.setState(e.PlaybackState.PLAYING),this.trigger(new ve(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PLAYING,state:s.PLAYING}))}_onPause(){k(this._name,"[videoelement:event] pause");const t=this.getControls();t&&t.setState(e.PlaybackState.PAUSED),this.trigger(new ve(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PAUSED,state:s.PAUSED}))}_onVolumeChange(t){var i;k(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 ve(e.SubscriberEventTypes.VOLUME_CHANGE,void 0,{volume:n.volume}))}_onLoadedData(t){var i,n,s;k(this._name,"[videoelement:event] loadeddata");const o=null!==(i=this._view)&&void 0!==i?i:t.target;this.trigger(new ve(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;k(this._name,"[videoelement:event] loadedmetadata");const s=null!==(i=this._view)&&void 0!==i?i:t.target;this.trigger(new ve(e.SubscriberEventTypes.LOADED_METADATA,void 0,{duration:null!==(n=s.duration)&&void 0!==n?n:0}))}_onResize(t){var i,n,s;k(this._name,"[videoelement:event] resize");const o=null!==(i=this._view)&&void 0!==i?i:t.target;this.trigger(new ve(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(){k(this._name,"[videoelement:event] loadstart")}_onSuspend(){k(this._name,"[videoelement:event] suspend")}_onStalled(){k(this._name,"[videoelement:event] stalled")}_onWaiting(){k(this._name,"[videoelement:event] waiting")}_onEncrypted(){k(this._name,"[videoelement:event] encrypted")}_onError(t){k(this._name,"[videoelement:event] error"),this.trigger(new ve(e.SubscriberEventTypes.CONNECT_FAILURE,void 0,{error:t.message}))}async attemptAutoplay(t=!1){try{await this.play(),this.isMuted()&&this.trigger(new ve(e.SubscriberEventTypes.AUTO_PLAYBACK_MUTED,void 0,{element:this._view}))}catch(i){t?(this.mute(),this.attemptAutoplay(t)):this.trigger(new ve(e.SubscriberEventTypes.AUTO_PLAYBACK_FAILURE,void 0,{error:i.message?i.message:i,element:this._view}))}}async play(){var e,t;if(k(this._name,"[videoelement:action] play"),!(null===(e=this._view)||void 0===e?void 0:e.paused))return k(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 O(this._name,"[videoelement:action] play (FAULT) - "+e.message),e}}async pause(){var e;k(this._name,"[videoelement:action] pause");try{return await(null===(e=this._view)||void 0===e?void 0:e.pause()),!0}catch(e){I(this._name,"[videoelement:action] pause (CATCH::FAULT) - "+e.message)}return!1}async resume(){var e;k(this._name,"[videoelement:action] resume");try{return await(null===(e=this._view)||void 0===e?void 0:e.play()),!0}catch(e){I(this._name,"[videoelement:action] resume (CATCH::FAULT) - "+e.message)}return!1}async stop(){var e;k(this._name,"[videoelement:action] stop");try{return await(null===(e=this._view)||void 0===e?void 0:e.pause()),!0}catch(e){I(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 Et="WHEPClient",St=rt,Ct=e=>k(Et,e),bt=e=>O(Et,e),ft=e=>I(Et,e);class Tt extends pt{constructor(e,t,i){super(),this._videoMuted=!0,this._audioMuted=!0;const n=e?se(e):St,s=i||St,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 r={data:{streamingMode:(t=!this._videoMuted,i=!this._audioMuted,t&&i?ut.FULL:t?ut.VIDEO:i?ut.AUDIO:ut.EMPTY),method:"onMetaData"},type:"metadata",method:"onMetaData",eventTimestamp:(new Date).getTime()};this._onMetaData(r)}catch(e){bt(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 ve(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 dt(e)),null===(i=this._playbackView)||void 0===i||i.attachStream(t)}async requestOffer(t){var i;Ct("[requestoffer]");const{iceTransport:n,maintainStreamVariant:s,videoEncoding:o,audioEncoding:r,connectionParams:a,mungeOffer:l}=this._options;t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});const d={transport:n,doNotSwitch:s};o&&o!==e.PlaybackVideoEncoder.NONE&&(d.videoEncoding=o),r&&r!==e.PlaybackAudioEncoder.NONE&&(d.audioEncoding=r);const h=null!=a?a:{},c=await t.createOffer(),u=await(null===(i=this._whipWhepService)||void 0===i?void 0:i.postSDPOffer(c.sdp,{...h,...d},!1));if(!u)throw bt("Failed to get offer from WHEP"),new Error("Failed to get offer from WHEP");const{sdp:p}=u;let _=p;return l&&(Ct(`[MUNGE:before] offer: ${_}`),_=l(_),Ct(`[MUNGE:after] offer: ${_}`)),_}async requestAnswer(e){const{mungeAnswer:t}=this._options;let i=(await e.createAnswer()).sdp;return t&&(Ct(`[MUNGE:before] answer: ${i}`),i=t(i),Ct(`[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=ke(e,void 0,!0);return await(null===(t=this._whipWhepService)||void 0===t?void 0:t.trickle(n,i))}async init(e){var t;this._options={...St,...e},this._options.subscriptionId=this._options.subscriptionId||`subscriber-${Math.floor(65536*Math.random()).toString(16)}`;const i=oe(this._options,"whep"),{includeDataChannel:n,disableProxy:s}=this._options;return this._whipWhepService=new xe(`${i}?requestId=${this._options.subscriptionId}`,n,s),this._messageTransport=this._whipWhepService,(null===(t=this._options)||void 0===t?void 0:t.stats)&&this.monitorStats(this._options.stats),this}async subscribe(){var t,i,n,s,o,r,a,l;const{connectionParams:d,rtcConfiguration:h,includeDataChannel:c,signalingSocketOnly:u,enableChannelSignaling:p,dataChannelConfiguration:_}=this._options;try{const l=d||{},g=await(null===(t=this._whipWhepService)||void 0===t?void 0:t.getOptions(l));this.trigger(new ve(e.SubscriberEventTypes.CONNECT_SUCCESS,this,null===(i=this._whipWhepService)||void 0===i?void 0:i.getUrl())),(null==g?void 0:g.links)&&(this._options.rtcConfiguration={...h,iceServers:g.links}),(null==g?void 0:g.origin)&&this.trigger(new ve(e.RTCSubscriberEventTypes.HOST_ENDPOINT_CHANGED,this,{endpoint:g.origin})),(null==g?void 0:g.statisticsEndpoint)&&this._onStatisticsEndpointChange(g.statisticsEndpoint);const v=c||p||u?_:void 0;this._peerConnectionHelper=new ct({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,v),null===(n=this.getPeerConnection())||void 0===n||n.addEventListener("track",(t=>{const{buffer:i}=this._options;Ct("[peerconnection.ontrack]");const{streams:n,track:s,receiver:o,transceiver:r}=t;o.playoutDelayHint=i,o.jitterBufferDelayHint=i,this.trigger(new ve(e.RTCSubscriberEventTypes.TRACK_ADDED,this,{streams:n,track:s,receiver:o,transceiver:r})),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 ve(e.RTCSubscriberEventTypes.PEER_CONNECTION_AVAILABLE,this,this.getPeerConnection())),this.trigger(new ve(e.RTCSubscriberEventTypes.OFFER_START,this));const E=await this.requestOffer(this.getPeerConnection()),S=new RTCSessionDescription({type:"offer",sdp:E});await(null===(s=this.getPeerConnection())||void 0===s?void 0:s.setRemoteDescription(S)),this.trigger(new ve(e.RTCSubscriberEventTypes.OFFER_END,this)),this.trigger(new ve(e.RTCSubscriberEventTypes.ANSWER_START,this));const C=await this.requestAnswer(this.getPeerConnection()),b=(m=C).includes("stereo=1")?m:m.replace("useinbandfec=1","useinbandfec=1;stereo=1;sprop-stereo=1"),f=new RTCSessionDescription({type:"answer",sdp:b});await(null===(o=this.getPeerConnection())||void 0===o?void 0:o.setLocalDescription(f)),await this.sendAnswer(b),this.trigger(new ve(e.RTCSubscriberEventTypes.ANSWER_END,this));const T=await this._peerConnectionHelper.waitToGatherIce(),{sdp:y}=T;return await this.postCandidateFragments(y),this.trigger(new ve(e.RTCSubscriberEventTypes.ICE_TRICKLE_COMPLETE,this)),this._mediaStream&&(this.trigger(new ve(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===(a=this._playbackView)||void 0===a?void 0:a.view),this}catch(t){throw bt(null!==(l=t.message)&&void 0!==l?l:"Could not subscribe."),t instanceof Me?this._onStreamUnavailable(t):this.trigger(new ve(e.SubscriberEventTypes.CONNECT_FAILURE,this,t)),this._options.maintainConnectionOnSubscribeErrors||this.unsubscribe(!0),t}var m}async unsubscribe(t=!1){var i;Ct("[unsubscribe]"),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,t),this._sourceHandler&&this._sourceHandler.disconnect(),this.unmonitorStats(),null===(i=this._playbackView)||void 0===i||i.detachStream(),this._playbackView=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 ve(e.SubscriberEventTypes.SUBSCRIBE_STOP,this))}send(e,t){var i;return null===(i=this.getMessageTransport())||void 0===i?void 0:i.post({send:{method:e,data:"string"==typeof t?JSON.parse(t):t}})}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,Ct(`[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;bt("Could not send log to server. Message parameter expected to be String or JSON-serializable object."),bt(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}getPlayer(){var e;return null===(e=this._playbackView)||void 0===e?void 0:e.view}play(){Ct("[play]"),this._sourceHandler?this._sourceHandler.play():ft("Cannot play without a Source Handler.")}pause(){Ct("[pause]"),this._sourceHandler?this._sourceHandler.pause():ft("Cannot pause without a Source Handler.")}resume(){Ct("[resume]"),this._sourceHandler?this._sourceHandler.resume():ft("Cannot resume without a Source Handler.")}stop(){Ct("[stop]"),this._sourceHandler?this._sourceHandler.stop():ft("Cannot stop without a Source Handler.")}setVolume(e){Ct("[setVolume]"),this._sourceHandler?this._sourceHandler.setVolume(e):ft("Cannot set volume without a Source Handler.")}getVolume(){var e,t,i;return Ct("[getVolume]"),this._sourceHandler?this._sourceHandler.getVolume():(ft("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(){Ct("[mute]"),this._sourceHandler?this._sourceHandler.mute():ft("Cannot mute without a Source Handler.")}unmute(){Ct("[unmute]"),this._sourceHandler?this._sourceHandler.unmute():ft("Cannot unmute without a Source Handler.")}seekTo(e){Ct("[seekTo]"),this._sourceHandler?this._sourceHandler.seekTo(e):ft("Cannot seek without a Source Handler.")}toggleFullScreen(){Ct("[toggleFullScreen]"),this._sourceHandler?this._sourceHandler.toggleFullScreen():ft("Cannot toggle full screen without a Source Handler.")}monitorStats(e){Ct("[monitorStats]");const{host:t,endpoint:i,app:n,streamName:s,subscriptionId:o,connectionParams:r}=this._options,a=null!=e?e:ze;return this._statisticsConfiguration={...a,host:t,app:n,hostEndpoint:i,streamName:s,subscriptionId:o,connectionParams:r},this._statsMonitor?ft("Cannot monitor stats without a Peer Connection. Please call `init` before calling `monitorStats`."):this._statsMonitor=new gt(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)}),this}unmonitorStats(){return this._statsMonitor&&this._statsMonitor.dispose(),this._statsMonitor=void 0,this._statisticsConfiguration=void 0,this}_onUnpublish(){Ct("[unpublish]"),this.trigger(new ve(e.SubscriberEventTypes.PLAY_UNPUBLISH,this)),this._sourceHandler&&this._sourceHandler.unpublish()}_onStreamUnavailable(t){Ct(`Stream ${this._options.streamName} does not exist.`),Ct("[onstreamunavailable]: "+JSON.stringify(t,null,2)),this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_INVALID_NAME,this))}_onDataChannelError(t,i){bt(`Data channel error: ${i}`),this.trigger(new ve(e.RTCSubscriberEventTypes.DATA_CHANNEL_ERROR,this,{dataChannel:t,error:i}))}_onSendReceived(t,i){Ct(`Send received: ${t} ${JSON.stringify(i)}`),"onMetaData"===t?this._onMetaData(i):this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_SEND_INVOKE,this,{methodName:t,data:i}))}_onStreamSwitchComplete(){Ct("[streamswitch::complete]");const t=this._requestedStreamSwitch;this.trigger(new ve(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 ve(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 ve(e.SubscriberEventTypes.STREAMING_MODE_CHANGE,this,{streamingMode:n,previousStreamingMode:s,viewElement:this._playbackView?this._playbackView.view:void 0}))),this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_METADATA,this,t))}_onConnectionClosed(){Ct("Connection closed"),this.unsubscribe(!0),this.trigger(new ve(e.SubscriberEventTypes.CONNECTION_CLOSED,this))}_onDataChannelOpen(t){Ct(`Data channel opened: ${t.label}`),this.trigger(new ve(e.RTCSubscriberEventTypes.DATA_CHANNEL_OPEN,this,{dataChannel:t})),this.trigger(new ve(e.RTCSubscriberEventTypes.DATA_CHANNEL_AVAILABLE,this,{name:t.label,dataChannel:t})),this._messageTransport=this._peerConnectionHelper,this.trigger(new Ee(e.MessageTransportStateEventTypes.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_START,this))}_onDataChannelClose(t){Ct(`Data channel closed: ${t.label}`),this.trigger(new ve(e.RTCSubscriberEventTypes.DATA_CHANNEL_CLOSE,this,{dataChannel:t}))}_onDataChannelMessage(t,i){Ct(`Data channel message: ${i.data}`),this.trigger(new ve(e.RTCSubscriberEventTypes.DATA_CHANNEL_MESSAGE,this,{dataChannel:t,message:i}))}_onPeerConnectionOpen(){var t;Ct("Peer connection opened"),this.trigger(new ve(e.RTCSubscriberEventTypes.PEER_CONNECTION_OPEN,this,this.getPeerConnection())),(null===(t=this._options)||void 0===t?void 0:t.includeDataChannel)||this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_START,this))}_onPeerConnectionFail(){bt("Peer connection failed"),this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_FAIL,this))}_onPeerConnectionClose(e){Ct(`Peer connection closed: ${e.type}`)}_onIceCandidate(t){Ct(`ICE candidate: ${t.candidate}`),this.trigger(new ve(e.RTCSubscriberEventTypes.CANDIDATE_CREATE,this,{candidate:t}))}_onPeerConnectionTrackAdd(e){Ct(`Peer connection track added: ${e.id}`)}_onSubscriberStatus(e){Ct(`Subscriber status: ${JSON.stringify(e)}`)}_onSDPSuccess(){Ct("SDP success")}_onSDPError(e){bt(`SDP error: ${e}`)}_onStatisticsEndpointChange(t){Ct(`Statistics endpoint changed: ${t}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(t),this.trigger(new ve(e.SubscriberEventTypes.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:t}))}_onStatsReport(t,i){this.trigger(new ve(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)}getType(){return"RTC"}}class yt 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 ve(e.SubscriberEventTypes.SUBSCRIBE_START,this._view)),this._playingStarted=!0}_onSourceError(t){k(this._name,"[source:event] error"),this.trigger(new ve(e.SubscriberEventTypes.CONNECT_FAILURE,void 0,t))}_onOrientationMetadata(t){const{orientation:i}=t,n=parseInt(i,10);i&&this._orientation!==n&&(k(this._name,"Metadata received: "+JSON.stringify(t,null,2)),this._orientation=n,this.trigger(new ve(e.SubscriberEventTypes.ORIENTATION_CHANGE,{orientation:this._orientation,viewElement:this._view})),this.trigger(new ve(e.SubscriberEventTypes.SUBSCRIBE_METADATA,void 0,t)))}_onStreamingModeMetadata(t){const{streamingMode:i}=t,n=this._streamingMode;i&&n!==i&&(k(this._name,"Metadata received: "+JSON.stringify(t,null,2)),this._streamingMode=i,this.trigger(new ve(e.SubscriberEventTypes.STREAMING_MODE_CHANGE,void 0,{streamingMode:this._streamingMode,previousStreamingMode:n,viewElement:this._view})),this.trigger(new ve(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 wt="HLSSubscriber",At=e=>k(wt,e),Pt=e=>I(wt,e);class Lt extends pt{constructor(){super()}_glomTrigger(e){e.on("*",(e=>{const{type:t,data:i}=e;this.trigger(new ve(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={...at,...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:r}=e,a="ws"===i||"http"===i?"http":"https",l=`${a}://${t}:${n||("http"===a?5080:443)}/${s}/${o}.m3u8`;if(r)return`${l}?${Object.entries(r).map((([e,t])=>`${e}=${t}`)).join("&")}`;return l})(this._options),!this._playbackView&&s&&(this._playbackView=new dt(s),this._sourceHandler=new yt(this._playbackView.view,this.getType()),this._sourceHandler.addSource(this._fileURL),this._glomTrigger(this._sourceHandler)),this.trigger(new ve(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 ve(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 ve(e.SubscriberEventTypes.SUBSCRIBE_STOP,this)),this}play(){At("[play]"),this._sourceHandler?this._sourceHandler.play():Pt("Cannot play without a Source Handler.")}pause(){At("[pause]"),this._sourceHandler?this._sourceHandler.pause():Pt("Cannot pause without a Source Handler.")}resume(){At("[resume]"),this._sourceHandler?this._sourceHandler.resume():Pt("Cannot resume without a Source Handler.")}stop(){At("[stop]"),this._sourceHandler?this._sourceHandler.stop():Pt("Cannot stop without a Source Handler.")}setVolume(e){At("[setVolume]"),this._sourceHandler?this._sourceHandler.setVolume(e):Pt("Cannot set volume without a Source Handler.")}getVolume(){var e,t,i;return At("[getVolume]"),this._sourceHandler?this._sourceHandler.getVolume():(Pt("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(){At("[mute]"),this._sourceHandler?this._sourceHandler.mute():Pt("Cannot mute without a Source Handler.")}unmute(){At("[unmute]"),this._sourceHandler?this._sourceHandler.unmute():Pt("Cannot unmute without a Source Handler.")}seekTo(e){At("[seekTo]"),this._sourceHandler?this._sourceHandler.seekTo(e):Pt("Cannot seek without a Source Handler.")}toggleFullScreen(){At("[toggleFullScreen]"),this._sourceHandler?this._sourceHandler.toggleFullScreen():Pt("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 Rt={baseURL:void 0,fullURL:void 0,hlsjsRef:void 0,hlsElement:void 0,usePlaybackControlsUI:!0,options:{debug:!1,backBufferLength:0}},Nt={...rt,liveSeek:Rt};class Dt extends U{trigger(e){super.trigger(e)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}var Ht,kt;!function(e){e.SEEK_START="Seek.Start",e.SEEK_END="Seek.End"}(Ht||(Ht={})),function(e){e.CHANGE="Slider.Change",e.CHANGE_START="Slider.Change.Start",e.CHANGE_COMPLETE="Slider.Change.Complete"}(kt||(kt={}));class It extends me{constructor(e,t,i){super(e,i),this._slider=t}get slider(){return this._slider}}const{createElement:Ot,addGlobalEventListener:Mt,removeGlobalEventListener:Ut,globalUnassign:Bt,getAssignedValue:Vt,globalAssign:Ft}=ie,$t="ControlSlider",Gt="r5_liveseek_event_owner";class Wt extends U{constructor(e){super(),this._value=0,this._disabled=!1,this._eventStartPosition=0,this.debug=e=>k($t,e),this.warn=e=>I($t,e),this.name=[$t,e].join("::"),this.debug("[init]"),this._container=Ot("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 r,a="";const l=o.target||document.body;switch(o.type){case"touchstart":a="mousedown",r=null===(i=o.changedTouches)||void 0===i?void 0:i[0];break;case"touchmove":a="mousemove",r=null===(n=o.changedTouches)||void 0===n?void 0:n[0];break;case"touchend":a="mouseup",r=null===(s=o.changedTouches)||void 0===s?void 0:s[0]}if(r&&a){const e=new MouseEvent(a,{bubbles:!0,cancelable:!0,view:l.ownerDocument.defaultView,screenX:r.screenX,screenY:r.screenY,clientX:r.clientX,clientY:r.clientY,ctrlKey:o.ctrlKey,altKey:o.altKey,shiftKey:o.shiftKey,metaKey:o.metaKey,button:0,relatedTarget:null});l.dispatchEvent(e)}}_mouseup(){this._eventStartPosition=0,Bt(Gt),Ut("mousemove",this._mousemoveHandler),Ut("mouseup",this._mouseupHandler),Ut("touchmove",this._touchmoveHandler),Ut("touchend",this._touchupHandler),this.trigger(new It(kt.CHANGE_COMPLETE,this))}_mousemove(e){if(Vt(Gt)!==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 It(kt.CHANGE,this,s))}_mousedown(e){this._eventStartPosition=e.clientX,this.trigger(new It(kt.CHANGE_START,this)),Ft(Gt,this.name),Mt("mousemove",this._mousemoveHandler),Mt("mouseup",this._mouseupHandler),Mt("touchmove",this._touchmoveHandler),Mt("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),Ut("mousemove",this._mousemoveHandler),Ut("mouseup",this._mouseupHandler),Ut("touchmove",this._touchmoveHandler),Ut("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=Ot("span");return e.classList.add("red5pro-media-slider-button"),e}createProgressBar(){const e=Ot("span");return e.classList.add("red5pro-media-slider-progress"),e}createTrack(){const e=Ot("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:xt,isTouchEnabled:jt,isPossiblySafari:Kt}=ie,zt=e=>k("PlaybackControls",e);class Jt extends Dt{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;zt("[decorate]");const i=xt("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)};jt()?(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=xt("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=xt("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 Wt("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(kt.CHANGE,(e=>{const t=Number(e.data);this._player.setVolume(t)})),e}_createSeekControl(){const t=new Wt("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(kt.CHANGE_START,(()=>{this.getState()===e.PlaybackState.PLAYING&&(this._resumeAfterSeek=!0,this._player.pause(!0,!0)),this.trigger(new me(Ht.SEEK_START))})),t.on(kt.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(kt.CHANGE_COMPLETE,(()=>{this._resumeAfterSeek&&this.getState()===e.PlaybackState.PAUSED&&(this._resumeAfterSeek=!1,this._player.resume(!0)),this.trigger(new me(Ht.SEEK_END))})),t}_createPlaybackTime(){const e=xt("span"),t=xt("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=xt("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)&&Kt()?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 zt(`[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 zt(`[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 Yt,qt;!function(e){e[e.LIVE=0]="LIVE",e[e.VOD=1]="VOD"}(Yt||(Yt={})),function(e){e.LIVE="LiveSeek.LIVE",e.VOD="LiveSeek.VOD"}(qt||(qt={}));const Qt={[Yt.LIVE]:qt.LIVE,[Yt.VOD]:qt.VOD};var Xt;!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"}(Xt||(Xt={}));const{createElement:Zt,findByQuerySelector:ei,createHLSClient:ti,getHLSClientEventEnum:ii}=ie,ni="SourceHandlerSeekable",si=e=>k(ni,e),oi=e=>O(ni,e),ri=e=>I(ni,e);class ai 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=Zt("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=ei(`#${n}`);return s||(s=Zt("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;si("[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 ve(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;si(`[HLS:videoelement:duration] ${n}, ${this._averageSegmentDuration}`);const o=this.getControls();o&&o.setPlaybackDuration(s),this._isHLSPlaybackActive?this.trigger(new ve(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:i.currentTime,duration:s,action:"hls time update"})):this.trigger(new ve(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 ve(e.SubscriberEventTypes.PLAYBACK_TIME_UPDATE,void 0,{time:i.currentTime,duration:i.duration+this._averageSegmentDuration,action:"hls time update"}))}_onHLSPlay(){si("[HLS:videoelement:event] play");const t=this.getControls();t&&t.setState(e.PlaybackState.PLAYING),this.trigger(new ve(e.SubscriberEventTypes.PLAYBACK_STATE_CHANGE,void 0,{code:e.PlaybackState.PLAYING,state:o[e.PlaybackState.PLAYING]}))}_onHLSPause(){si("[HLS:videoelement:event] pause");const t=this.getControls();t&&t.setState(e.PlaybackState.PAUSED),this.trigger(new ve(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:r,url:a}=n;if("networkerror"===s.toLowerCase()){if("levelemptyerror"===o.toLowerCase()){this.trigger(new ve(Xt.LIVE_SEEK_DISABLED,void 0,{hlsElement:e,hlsControl:t})),this.isSeekable=!1,t.destroy();const i=setTimeout((()=>{clearTimeout(i),this.enableLiveSeek(a,this._subscriptionId,this._hlsElement,!1)}),3e3);return}this.trigger(new ve(Xt.LIVE_SEEK_ERROR,void 0,{hlsElement:e,hlsControl:t,error:n}))}else this.trigger(new ve(Xt.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()),r&&"networkerror"===s.toLowerCase()&&t.startLoad()})),t.on(i.MANIFEST_PARSED,(()=>{try{e.pause()}catch(e){si(`Could not pause seekable live stream: ${e.message}`)}this.isSeekable=!0,this.trigger(new ve(Xt.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 ve(Xt.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 r=6,a=0;if(o&&o.stats&&o.stats.segments){const e=o.stats.segments;for(let t=0;t<e.length;t++)a+=e[t].duration;r=a/e.length,this._averageSegmentDuration=r}si(`fragload, [HLS:videoelement:duration] ${s} + ${r}`),this.trigger(new ve(Xt.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 r=6,a=0;if(o&&o.stats&&o.stats.segments){const e=o.stats.segments;for(let t=0;t<e.length;t++)a+=e[t].duration;r=a/e.length,this._averageSegmentDuration=r}si(`fragparsed, [HLS:videoelement:duration] ${s} + ${r}`),this.trigger(new ve(Xt.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){ri(`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){ri(`Could not start playback: ${e.message}.`)}this._hlsElementGenerated&&(t.style.display="none")}const o=e?Yt.VOD:Yt.LIVE;this.trigger(new ve(Xt.LIVE_SEEK_CHANGE,void 0,{code:o,state:Qt[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 ri(`Could not find lines in manifest: ${e}`);const r=o.reverse().find((e=>n.test(e)));if(!r)return void ri(`Could not find last segment in manifest: ${e}`);const a=o.find((e=>i.test(e)));if(!a)return void ri(`Could not find duration line in manifest: ${e}`);const l=a.match(i);if(!l)return void ri(`Could not find duration in manifest: ${e}`);const d=l[1],h=parseFloat(d),c=r.match(n);if(!c)return void ri(`Could not find segment length in manifest: ${e}`);const u=c[1];let p=parseInt(u,10);isNaN(p)&&(p=1),p=p>1?p-1:p,this._averageSegmentDuration=h,this.isSeekable=!0,this.trigger(new ve(Xt.LIVE_SEEK_ENABLED,void 0,{hlsElement:this._hlsElement,hlsControl:void 0})),this.onHLSDurationChange({target:t,duration:h*p}),this._manifestLoadTimeout=setTimeout((()=>{clearTimeout(this._manifestLoadTimeout),this._loadManifest(e,t)}),1e3*h)}catch(e){oi(`Could not load manifest: ${e.message}.`),this.trigger(new ve(Xt.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(){si("[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 Jt(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=Zt("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):ti(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){ri("[videoelement:action] play (FAULT) - "+e.message)}this._url=e}async play(e=!1){si("[videoelement:action] play");try{return e&&this._hlsElement&&this._hlsElement.paused?(await this._hlsElement.play(),!0):super.play()}catch(e){ri("[videoelement:action] play (CATCH::FAULT) - "+e.message)}return!1}async pause(e=!1,t=!1){si("[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){ri("[videoelement:action] pause (CATCH::FAULT) - "+e.message)}return!1}async resume(e=!1){var t,i;si("[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((()=>si("[videoelement:action] play (START)"))).catch((e=>ri("[videoelement:action] play (CATCH::FAULT) "+(e.message?e.message:e))))}catch(e){ri("[videoelement:action] resume (CATCH::FAULT) - "+e.message)}return!1}async stop(){si("[videoelement:action] stop");try{return this._hlsElement&&this._hlsElement.pause(),super.stop()}catch(e){ri("[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:oi("[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 ve(Xt.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||(si("[hlsvod:action] play (START) - (seekTo)"),this.play(!0))}catch(e){ri("[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:li,supportsNonNativeHLS:di}=ie,hi="WHEPLiveSeekClient",ci=e=>O(hi,e);class ui extends Tt{constructor(e,t,i){super(e,t,i)}async init(e){const{liveSeek:t}=e;return t||(e.liveSeek=Rt),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 I(hi,"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(li()||di(i))return this._sourceHandler=new ai(e,this.getType(),this._options,s,n),this._sourceHandler.addSource(),!0;ci("Could not utilize the 'LiveSeek' request. This feature requires either native HLS playback or hls.js as a depenency."),this.trigger(new ve(Xt.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(!li()&&!di(n))throw new Error;{const t=ne(e);this._sourceHandler.enableLiveSeek(t,i,s,!di(n))}}catch(e){ci("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(),r=s.join("/"),a={...this._options,app:r,streamName:o};let l=n;if(n){const e=/.*\/(.*)\.m3u8/.exec(n);if(e&&e.length>1){const t=`${e[1]}.m3u8`;l=n.replace(t,`${o}.m3u8`)}}const d=ne(a,i,l);this._sourceHandler&&this._sourceHandler.switchLiveSeek(d)}super._onStreamSwitchComplete()}}const pi="15.0.0";N(R.ERROR);const _i=(e,t=!1)=>{Object.prototype.hasOwnProperty.call(R,e.toUpperCase())&&(N(e,t),console&&console.log(`Red5 Pro SDK Version ${mi()}`))},mi=()=>pi;k("RED5",`Red5 Pro HTML SDK Version: ${pi}`);var gi={version:pi,LOG_LEVELS:R,getLogger:D,getRecordedLogs:H,setLogLevel:_i,getVersion:mi,PlaybackVideoEncoder:e.PlaybackVideoEncoder,PlaybackAudioEncoder:e.PlaybackAudioEncoder,PlaybackState:e.PlaybackState,PlaybackStateReadableMap:o,PublishVideoEncoder:e.PublishVideoEncoder,PublishAudioEncoder:e.PublishAudioEncoder,SubscriberEvent:ve,PublisherEvent:ge,MessageTransportStateEvent:Ee,PublisherEventTypes:e.PublisherEventTypes,SubscriberEventTypes:e.SubscriberEventTypes,RTCPublisherEventTypes:e.RTCPublisherEventTypes,RTCSubscriberEventTypes:e.RTCSubscriberEventTypes,MessageTransportStateEventTypes:e.MessageTransportStateEventTypes,WHIPClient:ot,WHEPClient:Tt,HLSSubscriber:Lt,LiveSeekClient:ui,defaultWhepSubscriberConfig:rt,defaultWhipPublisherConfig:pe};e.Event=me,e.EventEmitter=U,e.HLSSubscriber=Lt,e.LOG_LEVELS=R,e.LiveSeekClient=ui,e.MessageTransportStateEvent=Ee,e.PlaybackController=pt,e.PlaybackControls=Dt,e.PlaybackStateReadableMap=o,e.PublisherEvent=ge,e.SourceHandler=_t,e.SourceHandlerImpl=vt,e.SubscriberEvent=ve,e.WHEPClient=Tt,e.WHIPClient=ot,e.default=gi,e.defaultHLSSubscriberConfig=at,e.defaultLiveSeekConfig=Nt,e.defaultStatsConfig=ze,e.defaultWhepSubscriberConfig=rt,e.defaultWhipPublisherConfig=pe,e.getLogger=D,e.getRecordedLogs=H,e.getVersion=mi,e.setLogLevel=_i,Object.defineProperty(e,"__esModule",{value:!0})}));
