forked from red5pro/red5pro-webrtc-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathred5pro-sdk.esm.min.js
More file actions
34 lines (33 loc) · 127 KB
/
red5pro-sdk.esm.min.js
File metadata and controls
34 lines (33 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
*
* red5pro-html-sdk - Red5 Pro HTML SDK - 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.
*
*/
var e,t,i,n;!function(e){e.OPUS="OPUS",e.NONE="NONE"}(e||(e={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.NONE="NONE"}(t||(t={})),function(e){e[e.UNAVAILABLE=1e3]="UNAVAILABLE",e[e.AVAILABLE=0]="AVAILABLE",e[e.IDLE=1]="IDLE",e[e.PLAYING=2]="PLAYING",e[e.PAUSED=3]="PAUSED"}(i||(i={})),function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(n||(n={}));const s={[i.UNAVAILABLE]:n.UNAVAILABLE,[i.AVAILABLE]:n.AVAILABLE,[i.IDLE]:n.IDLE,[i.PLAYING]:n.PLAYING,[i.PAUSED]:n.PAUSED};var o,a,r,l;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(o||(o={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(a||(a={})),function(e){e.OPUS="OPUS"}(r||(r={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265"}(l||(l={}));var d={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},h={};function c(e){return"string"==typeof e?d[e.toLowerCase()]:e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function p(e,t,i){return p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,i){var n=[null];n.push.apply(n,t);var s=new(Function.bind.apply(e,n));return i&&u(s,i.prototype),s},p.apply(null,arguments)}function _(e){if(null==e)return e;if(Array.isArray(e))return e.slice();if("object"==typeof e){var t={};return Object.keys(e).forEach((function(i){t[i]=e[i]})),t}return e}function 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,a=String(e).replace(/%[sdj%]/g,(function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(s[n++]);case"%d":return Number(s[n++]);case"%j":try{return JSON.stringify(s[n++])}catch(e){return"[Circular]"}default:return e}})),r=s[n];n<o;r=s[++n])a+=null===r||"object"!=typeof r?" "+r:" "+m(r);return a}Object.keys(d).forEach((function(e){h[d[e]]=e}));var v={};function S(e,t){if(t){if(v[t])return;v[t]=!0}console.error(e+"\n")}var E=function(){function e(){}return e.prototype.write=function(e){e.level<30?console.log(e):e.level<40?console.info(e):e.level<50?console.warn(e):console.error(e),e.err&&e.err.stack&&console.error(e.err.stack),e.obj&&console.log(e.obj)},e}(),C=function(){function e(t,i,n){var s,o,a,r,l=this;if(!(this instanceof e))return new e(t,i);if(void 0!==i&&(s=t,t=i,!(s instanceof e)))throw new TypeError("invalid Logger creation: do not pass a second arg");if(!t)throw new TypeError("options (object) is required");if(s){if(t.name)throw new TypeError("invalid options.name: child cannot set logger name")}else if(!t.name)throw new TypeError("options.name (string) is required");if(t.stream&&t.streams)throw new TypeError('cannot mix "streams" and "stream" options');if(t.streams&&!Array.isArray(t.streams))throw new TypeError("invalid options.streams: must be an array");if(t.serializers&&("object"!=typeof t.serializers||Array.isArray(t.serializers)))throw new TypeError("invalid options.serializers: must be an object");if(s&&n){this._level=s._level,this.streams=s.streams,this.serializers=s.serializers,this.src=s.src,o=this.fields={};var d=Object.keys(s.fields);for(r=0;r<d.length;r++)o[a=d[r]]=s.fields[a];var h=Object.keys(t);for(r=0;r<h.length;r++)o[a=h[r]]=t[a]}else{if(s){for(this._level=s._level,this.streams=[],r=0;r<s.streams.length;r++){var c=_(s.streams[r]);this.streams.push(c)}this.serializers=_(s.serializers),this.src=s.src,this.fields=_(s.fields),t.level&&this.level(t.level)}else this._level=Number.POSITIVE_INFINITY,this.streams=[],this.serializers=null,this.src=!1,this.fields={};t.stream?this.addStream({type:"stream",stream:t.stream,level:t.level}):t.streams?t.streams.forEach((function(e){l.addStream(e,t.level)})):s&&t.level?this.level(t.level):s||this.addStream({type:"raw",stream:new E,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 a=c(t);i.level=a,a<this._level&&(this._level=a)},t._applySerializers=function(e,t){var i=this;Object.keys(this.serializers).forEach((function(n){if(!(void 0===e[n]||t&&t[n]))try{e[n]=i.serializers[n](e[n])}catch(t){S(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");S('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 a=this.streams[i];a.level<=o&&a.stream.write(e)}return n},e}();function f(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]):w.err(s[0])},o={err:!0},n=1===s.length?[i.err.message]:Array.prototype.slice.call(s,1)):"object"!=typeof s[0]&&null!==s[0]||Array.isArray(s[0])?(i=null,n=Array.prototype.slice.call(s)):(i=s[0],n=1===s.length&&i.err&&i.err instanceof Error?[i.err.message]:Array.prototype.slice.call(s,1));var a=_(t.fields);a.level=e;var r=i?_(i):null;if(r&&(t.serializers&&t._applySerializers(r,o),Object.keys(r).forEach((function(e){a[e]=r[e]}))),a.levelName=h[e],a.msg=n.length?g.apply(t,n):"",a.time||(a.time=new Date),t.src&&!a.src)try{throw new Error("call-stack-error")}catch(e){var l=e.stack?function(e,t){var i=e.split("\n");i[0]&&i[0].indexOf("call-stack-error")>=0&&i.shift();var n=i[t],s=null;if(n){var o=/^\s*(at|.*@)\s*(.+)?$/.exec(n);s=Array.isArray(o)&&o[2]?o[2]:n}return s}(e.stack,2):"";l||function(e){return v[e]}("src")||S("Unable to determine src line info","src"),a.src=l||""}return a.v=1,a}(n),this._emit(s))}}function b(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var i=e.cause();i&&(t+="\nCaused by: "+b(i))}return t}C.prototype.trace=f(10),C.prototype.debug=f(20),C.prototype.info=f(30),C.prototype.warn=f(40),C.prototype.error=f(50),C.prototype.fatal=f(60);var w={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:b(e),code:e.code,signal:e.signal}:e}};const A={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class y{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,A[e.level]||"UNKNOWN",e.msg)}}let T,L;const P=e=>(t,i)=>{var n;T&&"function"==typeof T[e]&&T[e]((n=t,e=>`(${n}) ${e}`)(i))},N={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},D=(e,t=!1,i)=>{const n=[{level:e,stream:new y,type:"raw"}];if(i){const t=i.map((t=>({...t,level:e})));n.push(...t)}t&&(L=[],n.push({level:e,stream:{write:t=>{const i=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==L||L.push(i)}},type:"raw"}));T=function(){return p(C,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:n})},R=()=>(T||D(N.INFO),T),H=()=>L||[];P(N.TRACE),P(N.INFO);const I=P(N.DEBUG),O=P(N.WARN),k=P(N.ERROR);P(N.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=>I(z,e),Y=e=>O(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:a}=t,r={appVersion:n,platform:s,userAgent:o,vendor:a};return e?{...i.browserDetails,...r}:r},supportsHLS:ee,onOrientationMetadata:(e,t)=>{const i=F.get(e);F.has(e)?Object.prototype.hasOwnProperty.call(i,"orientation")||(F.get(e).orientation=[]):(K(e),F.set(e,{orientation:[]})),F.get(e).orientation.push(t)},onStreamingModeMetadata:(e,t)=>{const i=F.get(e);F.has(e)?Object.prototype.hasOwnProperty.call(i,"streamingMode")||(F.get(e).streamingMode=[]):(K(e),F.set(e,{streamingMode:[]})),F.get(e).streamingMode.push(t)},isTouchEnabled:()=>"ontouchstart"in window,isPossiblySafari:()=>te?"safari"===window.adapter.browserDetails.browser.toLowerCase():ee(),findByQuerySelector:e=>document.querySelector(e),addGlobalEventListener:(e,t,i=document)=>{i.addEventListener(e,t)},removeGlobalEventListener:(e,t,i=document)=>{i.removeEventListener(e,t)},supportsNonNativeHLS:e=>{if(e)try{return e.isSupported()}catch(e){return Y("Could not access Hls.js."),!1}return!!window.Hls&&window.Hls.isSupported()},createHLSClient:(e={})=>new window.Hls(e),getHLSClientEventEnum:()=>window.Hls.Events,globalAssign:(e,t)=>{window[e]=t},globalUnassign:e=>{delete window[e]},getAssignedValue:e=>window[e]};const ne=(e,t,i)=>{const{liveSeek:{baseURL:n,fullURL:s}}=e,{host:o,protocol:a,port:r,app:l,streamName:d}=e;if(i||s)return i||s;const h=o,c="ws"===a?"http":"https",u=5080===r?5080:443,p=l,_=t||n;if(_){const e=_.length-1;return`${"/"===_.charAt(e)?_.substring(0,e):_}/${p}/${d}.m3u8`}return`${c}://${h}:${u}/${p}/${d}.m3u8`},se=e=>{const t=new URL(e),i=t.pathname.split("/").filter((e=>e.length>0)),n="https:"===t.protocol?"https":"http",s=t.hostname;return{protocol:n,port:t.port.length>0?t.port:443,app:i[0],host:s,streamName:i[i.length-1]}},oe=(e,t="whip")=>{var i;const{endpoint:n,proxy:s}=e;if(n)return n;{const{protocol:n,host:o,port:a,app:r,streamName:l}=e,d=n.match(/^http/)?n:"ws"===n?"http":"https";return(null==s?void 0:s.enabled)?`${d}://${o}:${a}/as/${null!==(i=s.version)&&void 0!==i?i:"v1"}/proxy/${t}/${r}/${l}`:`${d}://${o}:${a}/${r}/${t}/endpoint/${l}`}},ae=e=>{const t={audio:!1,video:!1},i={audio:!1,video:!1};return e.getTracks().forEach((e=>{"video"===e.kind?(i.video=e.getSettings(),t.video=e.getConstraints()):"audio"===e.kind&&(i.audio=e.getSettings(),t.audio=e.getConstraints())})),{requested:t,accepted:i}},re=e=>{const t=e.length;return function i(...n){return n.length>=t?e(...n):function(...e){return i(...n,...e)}}},le=re(((e,t)=>{let i=0;const n=t.length,s=[];for(;i<n;)e(t[i])&&(s[s.length]=t[i]),i+=1;return s}));var de,he,ce,ue;!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){O(this._name,"Could not parse message as JSON. Message= "+e.data+". Error= "+t.message)}return null}addResponseHandler(e){this._responseHandlers.push(e)}respond(e){O(this._name,`respond() should be overriden. Unhandled message: ${e}`)}post(e){return O(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 Se extends me{constructor(e,t,i){super(e,i),this._name=t}get name(){return this._name}}var Ee,Ce,fe,be,we;!function(e){e.CONNECT_SUCCESS="Connect.Success",e.CONNECT_FAILURE="Connect.Failure",e.PUBLISH_START="Publish.Start",e.PUBLISH_FAIL="Publish.Fail",e.PUBLISH_INVALID_NAME="Publish.InvalidName",e.UNPUBLISH_SUCCESS="Unpublish.Success",e.PUBLISH_METADATA="Publish.Metadata",e.PUBLISH_STATUS="Publish.Status",e.PUBLISH_AVAILABLE="Publish.Available",e.PUBLISH_INSUFFICIENT_BANDWIDTH="Publish.InsufficientBW",e.PUBLISH_SUFFICIENT_BANDWIDTH="Publish.SufficientBW",e.PUBLISH_RECOVERING_BANDWIDTH="Publish.RecoveringBW",e.PUBLISH_SEND_INVOKE="Publish.Send.Invoke",e.CONNECTION_CLOSED="Publisher.Connection.Closed",e.DIMENSION_CHANGE="Publisher.Video.DimensionChange",e.STATISTICS_ENDPOINT_CHANGE="Publisher.StatisticsEndpoint.Change"}(Ee||(Ee={})),function(e){e.CONSTRAINTS_ACCEPTED="WebRTC.MediaConstraints.Accepted",e.CONSTRAINTS_REJECTED="WebRTC.MediaConstraints.Rejected",e.MEDIA_STREAM_AVAILABLE="WebRTC.MediaStream.Available",e.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",e.OFFER_START="WebRTC.Offer.Start",e.OFFER_END="WebRTC.Offer.End",e.CANDIDATE_CREATE="WebRTC.Candidate.Create",e.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",e.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",e.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",e.SOCKET_MESSAGE="WebRTC.Socket.Message",e.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",e.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",e.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",e.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",e.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",e.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",e.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",e.UNSUPPORTED_FEATURE="WebRTC.Unsupported.Feature",e.TRANSFORM_ERROR="WebRTC.Transform.Error",e.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",e.STATS_REPORT="WebRTC.Stats.Report"}(Ce||(Ce={})),function(e){e.CONNECT_SUCCESS="Connect.Success",e.CONNECT_FAILURE="Connect.Failure",e.SUBSCRIBE_START="Subscribe.Start",e.SUBSCRIBE_STOP="Subscribe.Stop",e.SUBSCRIBE_FAIL="Subscribe.Fail",e.SUBSCRIBE_INVALID_NAME="Subscribe.InvalidName",e.SUBSCRIBE_METADATA="Subscribe.Metadata",e.SUBSCRIBE_STATUS="Subscribe.Status",e.SUBSCRIBE_SEND_INVOKE="Subscribe.Send.Invoke",e.SUBSCRIBE_PUBLISHER_CONGESTION="Subscribe.Publisher.NetworkCongestion",e.SUBSCRIBE_PUBLISHER_RECOVERY="Subscribe.Publisher.NetworkRecovery",e.PLAY_UNPUBLISH="Subscribe.Play.Unpublish",e.CONNECTION_CLOSED="Subscribe.Connection.Closed",e.ORIENTATION_CHANGE="Subscribe.Orientation.Change",e.STREAMING_MODE_CHANGE="Subscribe.StreamingMode.Change",e.VIDEO_DIMENSIONS_CHANGE="Subscribe.VideoDimensions.Change",e.LOADED_METADATA="Subscribe.LoadedMetadata",e.VOLUME_CHANGE="Subscribe.Volume.Change",e.SEEK_CHANGE="Subscribe.Seek.Change",e.PLAYBACK_TIME_UPDATE="Subscribe.Time.Update",e.PLAYBACK_STATE_CHANGE="Subscribe.Playback.Change",e.FULL_SCREEN_STATE_CHANGE="Subscribe.FullScreen.Change",e.AUTO_PLAYBACK_FAILURE="Subscribe.Autoplay.Failure",e.AUTO_PLAYBACK_MUTED="Subscribe.Autoplay.Muted",e.STATISTICS_ENDPOINT_CHANGE="Subscribe.StatisticsEndpoint.Change"}(fe||(fe={})),function(e){e.PEER_CONNECTION_AVAILABLE="WebRTC.PeerConnection.Available",e.OFFER_START="WebRTC.Offer.Start",e.OFFER_END="WebRTC.Offer.End",e.ANSWER_START="WebRTC.Answer.Start",e.ANSWER_END="WebRTC.Answer.End",e.CANDIDATE_CREATE="WebRTC.Candidate.Create",e.CANDIDATE_RECEIVE="WebRTC.Candidate.Receive",e.PEER_CANDIDATE_END="WebRTC.PeerConnection.CandidateEnd",e.ICE_TRICKLE_COMPLETE="WebRTC.IceTrickle.Complete",e.SOCKET_MESSAGE="WebRTC.Socket.Message",e.DATA_CHANNEL_MESSAGE="WebRTC.DataChannel.Message",e.DATA_CHANNEL_OPEN="WebRTC.DataChannel.Open",e.DATA_CHANNEL_AVAILABLE="WebRTC.DataChannel.Available",e.DATA_CHANNEL_CLOSE="WebRTC.DataChannel.Close",e.DATA_CHANNEL_ERROR="WebRTC.DataChannel.Error",e.PEER_CONNECTION_OPEN="WebRTC.PeerConnection.Open",e.ON_ADD_STREAM="WebRTC.Add.Stream",e.TRACK_ADDED="WebRTC.PeerConnection.OnTrack",e.SUBSCRIBE_STREAM_SWITCH="WebRTC.Subscribe.StreamSwitch",e.TRANSFORM_ERROR="WebRTC.Transform.Error",e.HOST_ENDPOINT_CHANGED="WebRTC.Endpoint.Changed",e.STATS_REPORT="WebRTC.Stats.Report"}(be||(be={})),function(e){e.OPEN="MessageTransport.Open",e.CLOSE="MessageTransport.Close",e.CHANGE="MessageTransport.Change",e.ERROR="MessageTransport.Error"}(we||(we={}));class Ae 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(e){e.onerror=t=>{this._responder.onDataChannelError(e,t.error.message)},e.onmessage=e=>{this._onDataChannelMessage(e)},e.onopen=()=>{this._responder.onDataChannelOpen(e)},e.onclose=t=>{this._responder.onDataChannelClose(e),this.trigger(new Se(we.CLOSE,this._name,{socket:this,event:t}))}}_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?(I(this._name,`[datachannel-response]: ${JSON.stringify(t,null,2)}`),this._handleMessageContent(t)):(O(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0)}_handleMessageContent(e){const{async:t,data:i,method:n,send:s,type:o,id:a}=e;if(this._isErrorMessage(i)){const e=(null==i?void 0:i.message)||(null==i?void 0:i.code);if(e)return this._responder.onDataChannelError(this._dataChannel,e),!0}if(n)return this._responder.onSendReceived(n,i),!0;if(s){const{senderName:t,dcLabel:i}=e,{data:n,method:o}=s,a={...n,senderName:t,dcLabel:i};return this._responder.onSendReceived(o,a),!0}return"metadata"===o&&i?(this._responder.onMetaData(i),!0):this._isStatusMessage(i)&&"NetConnection.Connect.Closed"===(null==i?void 0:i.code)?(this._responder.onConnectionClosed(),!0):!(!t||!a)&&this._handleAsyncResponse(a,e)}_handleAsyncResponse(e,t){const i=this._asyncTickets.find((t=>t.id===e));if(!i)return!1;const{promise:n}=i,{data:s}=t;if("error"===(null==s?void 0:s.type)){const e=s.message||s.code||"Unknown error";n.reject(new Error(e))}else n.resolve(s);return this._asyncTickets=this._asyncTickets.filter((t=>t.id!==e)),!0}async setUpWithPeerConfiguration(e,t){this.tearDown();try{I(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 O(this._name,`Could not establish a PeerConnection. ${e.message}`),new Error(e.message)}}tearDown(){if(this._dataChannel){I(this._name,"[teardown:datachannel]"),this._removeDataChannelHandlers(this._dataChannel);try{this._dataChannel.close()}catch(e){O(this._name,`[datachannel.close] error: ${e.message}`)}finally{this._dataChannel=void 0}}if(this._peerConnection){I(this._name,"[teardown:peerconnection]"),this._removeConnectionHandlers(this._peerConnection);try{this._peerConnection.close()}catch(e){O(this._name,`[peerconnection.close] error: ${e.message}`)}finally{this._peerConnection=void 0}}}async setLocalDescription(e){var t;return I(this._name,"[setlocaldescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setLocalDescription(e)}async setRemoteDescription(e){var t;return I(this._name,"[setremotedescription]"),null===(t=this._peerConnection)||void 0===t?void 0:t.setRemoteDescription(new RTCSessionDescription(e))}async addIceCandidate(e){var t;return I(this._name,"[addcandidate]"),null===(t=this._peerConnection)||void 0===t?void 0:t.addIceCandidate(e)}async waitToGatherIce(e=5e3){const t=this._peerConnection;return I(this._name,"[waittogatherice]"),new Promise((i=>{if("complete"===t.iceGatheringState)I(this._name,"[waittogatherice] ice gathering state complete."),t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{O(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}));else{I(this._name,"[waittogatherice] waiting...");const n=setTimeout((()=>{clearTimeout(n),t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{O(this._name,"Error adding null candidate: "+e.message||e),i(t.localDescription)}))}),e);t.onicegatheringstatechange=()=>{clearTimeout(n),I(this._name,"[waittogatherice] ice gathering state complete."),"complete"===t.iceGatheringState&&t.addIceCandidate(null).then((()=>{i(t.localDescription)})).catch((e=>{O(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);I(this._name,`[datachannel.send] message: ${t}`);try{return this._dataChannel.send(t),Promise.resolve(!0)}catch(e){k(this._name,e.message)}}return Promise.resolve(!1)}get connection(){return this._peerConnection}get dataChannel(){return this._dataChannel}}const ye=[{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}],Te=e=>"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||e,Le=re(((e,t)=>{var i,n;if("boolean"==typeof e.video)return!0;const s=(null===(i=e.video)||void 0===i?void 0:i.width)?Te(e.video.width):0,o=(null===(n=e.video)||void 0===n?void 0:n.height)?Te(e.video.height):0,a=s===t.width&&o===t.height;return a&&I("[gum:isExact]",`Found matching resolution for ${t.width}, ${t.height}.`),a})),Pe=re(((e,t)=>{const i=le(Le(t))(e);return I("[gum:hasMatchingFormat]","Filtered list: "+JSON.stringify(i,null,2)),i.length>0})),Ne=re(((e,t)=>{var i,n;if("boolean"==typeof e.video)return!0;const s=((null===(i=e.video)||void 0===i?void 0:i.width)?Te(e.video.width):0)*((null===(n=e.video)||void 0===n?void 0:n.height)?Te(e.video.height):0);return t.width*t.height<s})),De=re(((e,t)=>{const i=Ne(t);return le(i)(e)})),Re=async e=>{I("[gum:determineSupportedResolution]","Determine next neighbor based on constraints: "+JSON.stringify(e,null,2));const t=De(ye)(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=Pe(ye),n=async t=>{if(t){const e="string"==typeof t?t:[t.name,t.message].join(": ");I("[gum:getUserMedia]",`Failure in getUserMedia: ${e}. Attempting other resolution tests...`)}return await Re(e)};if((e=>e.video&&"object"==typeof e.video&&(e.video.width||e.video.height))(e)){if(!i(e))return await n(void 0);{I("[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:Te(e.video.width)}),(null===(i=e.video)||void 0===i?void 0:i.height)&&(n.video.height={exact:Te(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)}},Ie=(e,t,i)=>{const n="a=end-of-candidates",s=/^a=candidate:/,o=/^a=ice-ufrag:/,a=/^a=ice-pwd:/,r=/^m=(audio|video|application)\ /,l=e.split("\r\n");let d,h="",c="";const u=[];l.forEach((e=>{!d&&r.exec(e)?d=e:o.exec(e)?h=e:a.exec(e)?c=e:s.exec(e)&&(t&&-1!=e.indexOf(t)?u.push(e):t||u.push(e))})),i&&u[u.length-1]!==n&&u.push(n);return[h,c,d,"a=mid:0"].concat(u).join("\r\n")},Oe="RTCPeerConnectionPublisher";class ke extends Ae{constructor(e){super(e,Oe)}_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;I(Oe,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(I(this._name,"[peerconnection:open]"),this._responder.onPeerConnectionOpen()):"failed"!==t&&"disconnected"!==t||(O(this._name,"[peerconnection:error]"),"failed"===t&&this._responder.onPeerConnectionFail())},e.oniceconnectionstatechange=i=>{const{iceConnectionState:n}=e;I(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionClose(i)):"disconnected"===n?t=setTimeout((()=>{I(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached. Closing PeerConnection."),clearTimeout(t),this._responder.onPeerConnectionClose(i)}),3e3):t&&(I(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;I(this._name,`[peer.onicecandidate] - Peer Candidate: ${null==t?void 0:t.candidate}`),t&&this._responder.onIceCandidate(t)},e.ontrack=e=>{I(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 O(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0;I(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):(I(Oe,`[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):O(Oe,"PeerConnection not initialized. Cannot add track.")}async postUnpublish(e){const t=this.post({unpublish:e});return I(Oe,`[peerconnection:unpublish] complete: ${t}`),t}async createOfferWithoutSetLocal(e=null){var t;I(Oe,`[createoffer:withoutlocal]:: bandwidth request: ${JSON.stringify(e,null,2)}`);try{const i=await(null===(t=this._peerConnection)||void 0===t?void 0:t.createOffer());if(e){const t=((e,t)=>{const i=t.indexOf("m=audio");let n,s,o,a=t.indexOf("m=video"),r=t.indexOf("m=application");return i>-1&&e.audio&&(n=t.indexOf("\r\n",i),s=t.slice(0,n),o=t.slice(n+2,t.length),a=(t=[s,"b=AS:"+e.audio,o].join("\r\n")).indexOf("m=video"),r=t.indexOf("m=application")),a>-1&&e.video&&(n=t.indexOf("\r\n",a),s=t.slice(0,n),o=t.slice(n+2,t.length),r=(t=[s,"b=AS:"+e.video,o].join("\r\n")).indexOf("m=application")),r>-1&&e.dataChannel&&(n=t.indexOf("\r\n",r),s=t.slice(0,n),o=t.slice(n+2,t.length),t=[s,"b=AS:"+e.dataChannel,o].join("\r\n")),t})(e,i.sdp);i.sdp=t}return this._responder.onSDPSuccess(),i}catch(e){throw I(Oe,"[createoffer:error]"),this._responder.onSDPError(e),e}}async updateBandwidthRequest(e=null){var t;I(Oe,`[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{I(Oe,`[updatebandwidthrequest:${i}]:: bandwidth(${t.encodings[0].maxBitrate})`),e.setParameters(t).then(n).catch(s)}catch(e){s(e)}})),n=[];null==i||i.forEach((async i=>{var s,o;if("video"===(null===(s=i.track)||void 0===s?void 0:s.kind)&&e.video){const e=i.getParameters();e.encodings||(e.encodings=[{}]),e.encodings[0].maxBitrate=75e4,e.encodings[0].maxFramerate=60,e.encodings[0].priority="high",n.push(t(i,e,"video"))}else if("audio"===(null===(o=i.track)||void 0===o?void 0:o.kind)&&e.audio){const e=i.getParameters();e.encodings||(e.encodings=[{}]),e.encodings[0].maxBitrate=128e3,n.push(t(i,e,"audio"))}})),await Promise.all(n).catch((e=>{k(Oe,`[updatebandwidthrequest:error]:: ${e.message}`)}))}return!0}catch(e){k(Oe,`[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){I(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]}`})),I(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),a=e.get("username"),r=e.get("credential");s&&o&&a&&r?i.push({username:a,credential:r,urls:t}):t&&i.push({urls:t})}else if(n.indexOf(`rel="${$e.STATISTICS}"`)>-1){const e=We(n).get("url");e&&(s=e)}})),I(Ue,`[whipwhep-links]: ${JSON.stringify(i)}`),I(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 k(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}`),I(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:a}=s;if(a&&a.forEach(((e,t)=>{I(Ue,`[header] ${t}: ${e}`)})),o>=200&&o<300){const e=await s.text(),t=a.get("Location")||a.get("location");if(t){if(t.match(/^(http|https)/))this._resource=t;else{I(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 I(Ue,`[whipwhep-response] ${this._resource}: ${e}`),{sdp:e,location:this._resource}}return O(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(I(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(I(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 k(Ue,e.message),e}}async postSDPAnswer(e,t={}){I(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 I(Ue,Ve.get(n)),new Error(Ve.get(n));{const e=await t.text();throw Error(e)}}catch(e){throw k(Ue,e.message),e}}async trickle(e,t={}){I(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 I(Ue,`[whipwhep-response] ${this._resource}: ${e}`),{candidate:e}}if(405===n)throw I(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 k(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}`),I(Ue,"[whipwhep-teardown]");try{await fetch(i,{method:"DELETE",mode:"cors"})}catch(e){if(k(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 I(Ue,"[whipwhep:post] transport called."),Promise.resolve(!1)}async postAsync(){return I(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 k(je,`Could not instantiate a new instance of PublishView. Reason: ${e.message}`),e}}preview(e){const t=this.isAutoplay;I(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 O(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=>{k(this._name,`Failed to get stats report. ${e.message||e}`)}))}catch(e){k(this._name,`Failed to get stats report. ${e.message||e}`)}}_handleStatsReport(e){console.log(`[${this._name}]: ${JSON.stringify(e,null,2)}`)}_appendClientDetails(e){this._identifier.client={...this._identifier.client,...e}}async start(e){this._startTime=(new Date).getTime(),this._stopped=!1,this._connection=e,this.postAction("started"),this._getStats(),this._interval=setInterval((()=>{this._stopped||this._getStats()}),this._config.interval)}stop(){this._stopped=!0,clearInterval(this._interval),this.postAction("ended")}async post(e){const t={...this._identifier,type:"stats-report",timestamp:(new Date).getTime(),data:e},{endpoint:i,additionalHeaders:n}=this._config;if(this._client&&this._client.onStatsReport&&null===i)return void this._client.onStatsReport(this._connection,t);let s={"Content-Type":"application/json"};if(n&&(s={...s,...n}),i)try{const e=await fetch(i,{method:"POST",headers:s,body:JSON.stringify(t)});e.status>=200&&e.status<300?I(this._name,`Posted stats data to endpoint: ${i}.`):k(this._name,`Failed to post stats data to endpoint: ${i}. ${e.status}`)}catch(e){k(this._name,`Failed to post stats data to endpoint: ${i}. ${e.message||e}`)}else if(this._client&&this._client.getMessageTransport())try{let e=!1;const i=this._client.getMessageTransport();i&&(e=await i.post(t)),e||(this._queue.push(t),this._client.on(we.CHANGE,(()=>{this._client.off(we.CHANGE),this._emptyStatsReportQueue()})),O(this._name,"Failed to post stats data to message transport. Message transport is not available. Pushed to Queue."))}catch(e){k(this._name,`Failed to post stats data to message transport. ${e.message||e}`)}}async postAction(e,t=void 0){return this.post({action:{type:e,data:t,timestamp:(new Date).getTime()}})}async postEvent(e,t){return this.post({event:{type:e,data:t||void 0,timestamp:(new Date).getTime()}})}updateEndpoint(e,t=!0){const{endpoint:i}=this._config;t?this._config.endpoint=e:t||i||(this._config.endpoint=e)}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=[Ee.PUBLISH_START,Ee.PUBLISH_FAIL,Ee.PUBLISH_INSUFFICIENT_BANDWIDTH,Ee.PUBLISH_SUFFICIENT_BANDWIDTH,Ee.PUBLISH_RECOVERING_BANDWIDTH,Ee.STATISTICS_ENDPOINT_CHANGE];class Ze extends Ye{constructor(e,t){if(super("RTCPublisherStats",e,t),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=e=>{const{type:t,data:i}=e;if(Xe.indexOf(t)>-1){if(t===Ee.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=i;this.updateEndpoint(e,!1)}this.postEvent(t)}},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(Ce.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(Ce.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const e=({data:t})=>{this._client.off(Ce.PEER_CONNECTION_AVAILABLE,e),this.start(t)};this._client.on(Ce.PEER_CONNECTION_AVAILABLE,e)}}_handleStatsReport(e){const{type:t}=e,{include:i}=this._config,n=i&&i.length>0;if(n&&i.indexOf(t)>=-1)this.post(e);else if(!n)if(t===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:a,bytesSent:r,packetsSent:l,totalPacketsSendDelay:d}=e,h={type:t,kind:n,codecId:s,mediaType:o,active:a,bytesSent:r,packetsSent:l,totalPacketsSendDelay:d};if("audio"===n){if(this.lastAudioReport){const{bytesSent:e,timestamp:t}=this.lastAudioReport,n=8*(r-e)/(i-t);this.estimatedAudioBitrate=n}this.post({...h,estimatedBitrate:Math.floor(this.estimatedAudioBitrate)}),this.lastAudioReport=e}else if("video"===n){const{firCount:t,pliCount:n,frameWidth:s,frameHeight:o,framesEncoded:a,framesPerSecond:l,framesSent:d,keyFramesEncoded:c,qualityLimitationReason:u,qualityLimitationDurations:p}=e;let _={...h,firCount:t,pliCount:n,frameWidth:s,frameHeight:o,framesEncoded:a,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*(r-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(Ce.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(Ce.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),super.dispose()}}const et="WHIPClient",tt=pe,it=e=>I(et,e),nt=e=>k(et,e),st=e=>O(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(e){var t,i;const{onGetUserMedia:n}=e;if(n){it("Requesting gUM from user-defined configuration:onGetUserMedia.");const e=await n();return this.trigger(new ge(Ce.CONSTRAINTS_ACCEPTED,this,ae(e))),e}{const{mediaConstraints:n}=e;let s;it(`Requesting gUM using mediaConstraints: ${JSON.stringify(n,null,2)}`);let o=n;const a=await He(o);return a&&a.media||(s=await ie.gUM(o)),s=null!==(t=null==a?void 0:a.media)&&void 0!==t?t:s,o=null!==(i=null==a?void 0:a.constraints)&&void 0!==i?i:n,it(`Constraints accepted: ${JSON.stringify(o,null,2)}`),this.trigger(new ge(Ce.CONSTRAINTS_ACCEPTED,this,{constraints:o,...ae(s)})),s}}async getAndPreviewStreamIfAvailable(){var e;let t=this._mediaStream;if(!t){try{t=null!=t?t:await this.generateMediaStream(this._options)}catch(t){const i=null!==(e=t.message)&&void 0!==e?e:"Could not generate media stream.";throw this.trigger(new ge(Ce.CONSTRAINTS_REJECTED,this,{constraints:this._options.mediaConstraints})),new Error(i)}if(!t)throw new Error("Could not generate media stream.")}return this.trigger(new ge(Ce.MEDIA_STREAM_AVAILABLE,this,t)),this.preview(t),t}reorderCodecPreferences(e,t,i){e.getTransceivers().forEach((e=>{if(e.sender&&e.sender.track){const{kind:n}=e.sender.track;if(t&&"video"===n&&e.setCodecPreferences)try{const{codecs:i}=RTCRtpSender.getCapabilities("video"),n=i.findIndex((e=>e.mimeType===`video/${t}`));if(n>-1){const t=i.slice(0),s=i[n];t.splice(n,1),t.unshift(s),e.setCodecPreferences(t)}}catch(e){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(e){var t;try{const{sdp:i}=e;let{videoEncoding:n}=this._options;const{mungeOffer:s,streamMode:o,keyFramerate:a,iceTransport:r,connectionParams:d,mediaConstraints:h,forceVP8:c,audioEncoding:u,offerSDPResolution:p}=this._options;c&&!n&&(n=l.VP8);let _=i;s&&(it(`[MUNGE:before] offer: ${_}`),_=s(_),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 a=o.length;const r=/^m=video/;for(;--a>-1;)if(r.exec(o[a])){for(;++a<o.length;)if(o[a].indexOf("a=mid")>-1){o.splice(a+1,0,s);break}break}return o.join("\r\n")})(_,((e,t)=>{let i;if(e)try{const t=e.getVideoTracks()&&e.getVideoTracks()[0];if(t){const e=t.getSettings();i={width:e.width,height:e.height}}}catch(e){O("[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){O("[determineMediaResolution]",`Could not determine resolution from MediaConstraints. ${e.message||e}`)}return i&&I("[determineMediaResolution]",`constraints: ${JSON.stringify(i,null,2)}`),i})(this._mediaStream,h)),it(`[MUNGE:after] offer: ${_}`));const m={...d,mode:o,transport:r,keyFramerate:a};return n&&(m.videoEncoding=n),u&&(m.audioEncoding=u),await(null===(t=this._whipWhepService)||void 0===t?void 0:t.postSDPOffer(_,m))}catch(e){throw nt(e.message||e),e instanceof Me?this.trigger(new ge(Ee.PUBLISH_INVALID_NAME,this)):(this.trigger(new ge(Ee.CONNECT_FAILURE,this,e)),this.unpublish()),e}}async postCandidateFragments(e){var t;const{connectionParams:i}=this._options,n=Ie(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(e){var t,i,n,s;e&&(this._options.streamName=e);const{forceVP8:o,audioEncoding:a,rtcConfiguration:r,dataChannelConfiguration:d,includeDataChannel:h,signalingSocketOnly:c,enableChannelSignaling:u,connectionParams:p,bandwidth:_,mungeAnswer:m}=this._options;let{videoEncoding:g}=this._options;o&&(g=l.VP8,this._options.videoEncoding=g),this._mediaStream||(this._mediaStream=await this.getAndPreviewStreamIfAvailable());try{const e=null!=p?p:{};if(p){const{transcode:t}=p;t&&(e.transcode=t)}const s=await(null===(t=this._whipWhepService)||void 0===t?void 0:t.getOptions(e));(null==s?void 0:s.links)&&(this._options.rtcConfiguration={...r,iceServers:s.links}),(null==s?void 0:s.origin)&&this.trigger(new ge(Ce.HOST_ENDPOINT_CHANGED,this,{endpoint:s.origin})),(null==s?void 0:s.statisticsEndpoint)&&this._onStatisticsEndpointChange(s.statisticsEndpoint);const o=h||u||c?d:void 0;this._peerConnectionHelper=new ke({onDataChannelError:this._onDataChannelError.bind(this),onSendReceived:this._onSendReceived.bind(this),onMetaData:this._onMetaData.bind(this),onConnectionClosed:this._onConnectionClosed.bind(this),onDataChannelOpen:this._onDataChannelOpen.bind(this),onDataChannelClose:this._onDataChannelClose.bind(this),onDataChannelMessage:this._onDataChannelMessage.bind(this),onPeerConnectionOpen:this._onPeerConnectionOpen.bind(this),onPeerConnectionFail:this._onPeerConnectionFail.bind(this),onPeerConnectionClose:this._onPeerConnectionClose.bind(this),onIceCandidate:this._onIceCandidate.bind(this),onSDPSuccess:this._onSDPSuccess.bind(this),onSDPError:this._onSDPError.bind(this),onStatisticsEndpointChange:this._onStatisticsEndpointChange.bind(this),onPublisherStatus:this._onPublisherStatus.bind(this),onPeerConnectionTrackAdd:this._onPeerConnectionTrackAdd.bind(this),onInsufficientBandwidth:this._onInsufficientBandwidth.bind(this),onSufficientBandwidth:this._onSufficientBandwidth.bind(this),onRecoveringBandwidth:this._onRecoveringBandwidth.bind(this),onUnpublish:this._onUnpublish.bind(this)}),await this._peerConnectionHelper.setUpWithPeerConfiguration(this._options.rtcConfiguration,o),this.trigger(new ge(Ce.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 l=await(null===(i=this._peerConnectionHelper)||void 0===i?void 0:i.createOfferWithoutSetLocal(_));await this._peerConnectionHelper.setLocalDescription(l),this.trigger(new ge(Ce.OFFER_START,this,l));const{sdp:v}=await this.postOffer(l);let S=v;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(Ce.OFFER_END,this,S));const E=await this._peerConnectionHelper.waitToGatherIce(),{sdp:C}=E;return await this.postCandidateFragments(C),this.trigger(new ge(Ce.ICE_TRICKLE_COMPLETE,this)),ie.addOrientationChangeHandler(this._onOrientationChange),(null===(n=this._options)||void 0===n?void 0:n.includeDataChannel)||this.trigger(new ge(Ee.PUBLISH_START,this)),this}catch(e){throw nt(null!==(s=e.message)&&void 0!==s?s:"Could not publish."),this.trigger(new ge(Ee.CONNECT_FAILURE,this,e)),this.unpublish(!0),e}}async unpublish(e=!1){var t;it("[unpublish]"),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,e),(null===(t=this._options)||void 0===t?void 0:t.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(Ee.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,a=null!=e?e:ze;return this._statisticsConfiguration={...a,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(N).find((t=>t.toLowerCase()===e.toLowerCase()))?e:N.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(e,t){nt(`Data channel error: ${t}`),this.trigger(new ge(Ce.DATA_CHANNEL_ERROR,this,{dataChannel:e,error:t}))}_onSendReceived(e,t){it(`Send received: ${e} ${JSON.stringify(t)}`),"onMetaData"===e?this._onMetaData(t):this.trigger(new ge(Ee.PUBLISH_SEND_INVOKE,this,{methodName:e,data:t}))}_onMetaData(e){it(`Metadata received: ${JSON.stringify(e)}`),this.trigger(new ge(Ee.PUBLISH_METADATA,this,e))}_onConnectionClosed(){it("Connection closed"),this.unpublish(),this.trigger(new ge(Ee.CONNECTION_CLOSED,this))}_onDataChannelOpen(e){it(`Data channel opened: ${e.label}`),this.trigger(new ge(Ce.DATA_CHANNEL_OPEN,this,{dataChannel:e})),this.trigger(new ge(Ce.DATA_CHANNEL_AVAILABLE,this,{name:e.label,dataChannel:e})),this._messageTransport=this._peerConnectionHelper,this.trigger(new Se(we.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new ge(Ee.PUBLISH_START,this))}_onDataChannelClose(e){it(`Data channel closed: ${e.label}`),this.trigger(new ge(Ce.DATA_CHANNEL_CLOSE,this,{dataChannel:e}))}_onDataChannelMessage(e,t){it(`Data channel message: ${t.data}`),this.trigger(new ge(Ce.DATA_CHANNEL_MESSAGE,this,{dataChannel:e,message:t}))}_onPeerConnectionTrackAdd(e){it(`Peer connection track added: ${e.id}`),this.trigger(new ge(Ce.TRACK_ADDED,this,{track:e}))}_onPeerConnectionOpen(){it("Peer connection opened"),this.trigger(new ge(Ce.PEER_CONNECTION_OPEN,this,this.getPeerConnection()))}_onPeerConnectionFail(){nt("Peer connection failed"),this.trigger(new ge(Ee.PUBLISH_FAIL,this))}_onPeerConnectionClose(e){it(`Peer connection closed: ${e.type}`),this._peerConnectionHelper&&this._peerConnectionHelper.tearDown(),this.trigger(new ge(Ee.CONNECTION_CLOSED,this,e))}_onIceCandidate(e){it(`ICE candidate: ${JSON.stringify(e,null,2)}`),this.trigger(new ge(Ce.CANDIDATE_CREATE,this,{candidate:e}))}_onUnpublish(){it("Unpublish received")}_onPublisherStatus(e){it("[publisherstatus] - "+JSON.stringify(e,null,2)),e.code&&"NetStream.Publish.IsAvailable"===e.code?this.trigger(new ge(Ee.PUBLISH_AVAILABLE,this,e)):this.trigger(new ge(Ee.PUBLISH_STATUS,this,e))}_onInsufficientBandwidth(e){this.trigger(new ge(Ee.PUBLISH_INSUFFICIENT_BANDWIDTH,this,e))}_onSufficientBandwidth(e){this.trigger(new ge(Ee.PUBLISH_SUFFICIENT_BANDWIDTH,this,e))}_onRecoveringBandwidth(e){this.trigger(new ge(Ee.PUBLISH_RECOVERING_BANDWIDTH,this,e))}_onSDPSuccess(e=void 0){const t=e?": "+JSON.stringify(e,null,2):"";it(`[onsdpsuccess]:: ${t}`)}_onSDPError(e=void 0){this.trigger(new ge(Ee.PUBLISH_FAIL,this));const t=e?": "+JSON.stringify(e,null,2):"";nt(`[onsdperror]:: ${t}`)}_onOrientationChange(e){const t=this.getMessageTransport();t&&t.post({send:{method:"onMetaData",data:{deviceOrientation:e}}})}_onStatisticsEndpointChange(e){it(`Statistics endpoint changed: ${e}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(e),this.trigger(new ge(Ee.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:e}))}_onStatsReport(e,t){this.trigger(new ge(Ce.STATS_REPORT,this,{connection:e,report:t}))}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}trigger(e){super.trigger(e)}getType(){return"RTC"}}const at={...{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},rt={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 k(lt,`Could not instantiate a new instance of Red5ProSubscriber. Reason: ${e.message||e}`),e}}attachStream(e){const t=this.isAutoplay;I(lt,"[attachstream]"),ie.setVideoSource(this._targetElement,e,t)}detachStream(){I(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 Ae{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;I(ht,`[peer.onsignalingstatechange] - State: ${t}`)},e.onconnectionstatechange=()=>{const{connectionState:t}=e;"connected"===t?(I(this._name,"[peerconnection:open]"),this._responder.onPeerConnectionOpen()):"failed"!==t&&"disconnected"!==t||(O(this._name,"[peerconnection:error]"),"failed"===t&&this._responder.onPeerConnectionFail())},e.oniceconnectionstatechange=i=>{const{iceConnectionState:n}=e;I(this._name,`[peer.oniceconnectionstatechange] - State: ${n}`),"failed"===n?(t&&clearTimeout(t),this._responder.onPeerConnectionFail(),this._responder.onPeerConnectionClose(i)):"disconnected"===n?t=setTimeout((()=>{I(this._name,"[peer.oniceconnectionstatechange] - Reconnect timeout reached. Closing PeerConnection."),clearTimeout(t),this._responder.onPeerConnectionClose(i)}),3e3):t&&(I(this._name,"[peer.oniceconnectionstatechange] - Clearing timeout for reconnect."),clearTimeout(t))},e.onicecandidate=e=>{const{candidate:t}=e;I(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 O(this._name,"Determined websocket response not in correct format. Aborting message handle."),!0;I(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):(I(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=[fe.SUBSCRIBE_START,fe.SUBSCRIBE_STOP,fe.SUBSCRIBE_FAIL,fe.SUBSCRIBE_PUBLISHER_CONGESTION,fe.SUBSCRIBE_PUBLISHER_RECOVERY,fe.PLAY_UNPUBLISH,fe.STREAMING_MODE_CHANGE,fe.PLAYBACK_STATE_CHANGE,fe.STATISTICS_ENDPOINT_CHANGE];class gt extends Ye{constructor(e,t){if(super("RTCSubscriberStats",e,t),this.estimatedAudioBitrate=0,this.estimatedVideoBitrate=0,this.lastAudioReport=null,this.lastVideoReport=null,this._eventHandler=e=>{const{type:t,data:n}=e;if(mt.indexOf(t)>-1)if(t===fe.STREAMING_MODE_CHANGE){const{streamingMode:e,previousStreamingMode:i}=n;this.postEvent(t,{data:{streamingMode:e,previousStreamingMode:i}})}else if(t===fe.PLAYBACK_STATE_CHANGE){const{code:e}=n;let t;e===i.AVAILABLE&&(t={timeToFirstFrameMS:(new Date).getTime()-this._startTime}),this.postEvent(s[e],t)}else{if(t===fe.STATISTICS_ENDPOINT_CHANGE){const{statisticsEndpoint:e}=n;this.updateEndpoint(e,!1)}this.postEvent(t)}},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(be.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.on(be.HOST_ENDPOINT_CHANGED,this._hostEndpointChangedHandler),this._client.getPeerConnection())this.start(this._client.getPeerConnection());else{const e=({data:t})=>{this._client.off(be.PEER_CONNECTION_AVAILABLE,e),this.start(t)};this._client.on(be.PEER_CONNECTION_AVAILABLE,e)}}_handleStatsReport(e){const{type:t}=e,{include:i}=this._config,n=i&&i.length>0;if(n&&i.indexOf(t)>=-1)this.post(e);else if(!n)if(t===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:a,packetsReceived:r,bytesReceived:l}=e,d={type:t,kind:n,codecId:s,jitter:o,packetsLost:a,packetsReceived:r,bytesReceived:l};if("audio"===n){const{packetsDiscarded:t}=e;if(this.lastAudioReport){const{bytesReceived:e,timestamp:t}=this.lastAudioReport,n=8*(l-e)/(i-t);this.estimatedAudioBitrate=n}this.post({...d,packetsDiscarded:t,estimatedBitrate:Math.floor(this.estimatedAudioBitrate)}),this.lastAudioReport=e}else if("video"===n){const{firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:a,framesPerSecond:r,framesReceived:h,freezeCount:c,keyFramesDecoded:u,nackCount:p,pauseCount:_,pliCount:m,totalFreezesDuration:g,totalPausesDuration:v}=e,S={...d,firCount:t,frameWidth:n,frameHeight:s,framesDecoded:o,framesDropped:a,framesPerSecond:r,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({...S,estimatedBitrate:Math.floor(this.estimatedVideoBitrate)}),this.lastVideoReport=e}}}dispose(){this._client.off("*",this._eventHandler),this._client.off(be.CANDIDATE_CREATE,this._candidateCreateHandler),this._client.off(be.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(e){var t,i;e?null===(t=this._view)||void 0===t||t.classList.add("red5pro-media-container-full-screen"):null===(i=this._view)||void 0===i||i.classList.remove("red5pro-media-container-full-screen"),this.trigger(new ve(fe.FULL_SCREEN_STATE_CHANGE,void 0,e))}_cleanup(){this._playbackNotificationCenter&&this._removePlaybackNotificationCenterHandlers(this._playbackNotificationCenter),this._playbackNotificationCenter=void 0,this._view=void 0}_onCanPlay(e){var t;I(this._name,"[videoelement:event] canplay");const s=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,o=this.getControls();o&&o.enable(!0),this.trigger(new ve(fe.PLAYBACK_STATE_CHANGE,void 0,{code:i.AVAILABLE,state:n.AVAILABLE})),this.trigger(new ve(fe.VOLUME_CHANGE,void 0,{volume:s.volume}))}_onDurationChange(e){var t;I(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(){I(this._name,"[videoelement:event] ended");const e=this.getControls();e&&e.setState(i.IDLE),this.trigger(new ve(fe.PLAYBACK_STATE_CHANGE,void 0,{code:i.IDLE,state:n.IDLE}))}_onTimeUpdate(e){var t;const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();n&&n.setSeekTime(i.currentTime,this.isVOD()?i.duration:void 0),this.trigger(new ve(fe.PLAYBACK_TIME_UPDATE,void 0,{time:i.currentTime,duration:i.duration}))}_onPlay(){I(this._name,"[videoelement:event] play");const e=this.getControls();e&&e.setState(i.PLAYING),this.trigger(new ve(fe.PLAYBACK_STATE_CHANGE,void 0,{code:i.PLAYING,state:n.PLAYING}))}_onPause(){I(this._name,"[videoelement:event] pause");const e=this.getControls();e&&e.setState(i.PAUSED),this.trigger(new ve(fe.PLAYBACK_STATE_CHANGE,void 0,{code:i.PAUSED,state:n.PAUSED}))}_onVolumeChange(e){var t;I(this._name,"[videoelement:event] volumechange");const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();n&&n.getVolume()!==i.volume&&n.setVolume(i.volume),this.trigger(new ve(fe.VOLUME_CHANGE,void 0,{volume:i.volume}))}_onLoadedData(e){var t,i,n;I(this._name,"[videoelement:event] loadeddata");const s=null!==(t=this._view)&&void 0!==t?t:e.target;this.trigger(new ve(fe.VIDEO_DIMENSIONS_CHANGE,void 0,{width:null!==(i=s.videoWidth)&&void 0!==i?i:0,height:null!==(n=s.videoHeight)&&void 0!==n?n:0}))}_onLoadedMetadata(e){var t,i;I(this._name,"[videoelement:event] loadedmetadata");const n=null!==(t=this._view)&&void 0!==t?t:e.target;this.trigger(new ve(fe.LOADED_METADATA,void 0,{duration:null!==(i=n.duration)&&void 0!==i?i:0}))}_onResize(e){var t,i,n;I(this._name,"[videoelement:event] resize");const s=null!==(t=this._view)&&void 0!==t?t:e.target;this.trigger(new ve(fe.VIDEO_DIMENSIONS_CHANGE,void 0,{width:null!==(i=s.videoWidth)&&void 0!==i?i:0,height:null!==(n=s.videoHeight)&&void 0!==n?n:0}))}_onLoadStart(){I(this._name,"[videoelement:event] loadstart")}_onSuspend(){I(this._name,"[videoelement:event] suspend")}_onStalled(){I(this._name,"[videoelement:event] stalled")}_onWaiting(){I(this._name,"[videoelement:event] waiting")}_onEncrypted(){I(this._name,"[videoelement:event] encrypted")}_onError(e){I(this._name,"[videoelement:event] error"),this.trigger(new ve(fe.CONNECT_FAILURE,void 0,{error:e.message}))}async attemptAutoplay(e=!1){try{await this.play(),this.isMuted()&&this.trigger(new ve(fe.AUTO_PLAYBACK_MUTED,void 0,{element:this._view}))}catch(t){e?(this.mute(),this.attemptAutoplay(e)):this.trigger(new ve(fe.AUTO_PLAYBACK_FAILURE,void 0,{error:t.message?t.message:t,element:this._view}))}}async play(){var e,t;if(I(this._name,"[videoelement:action] play"),!(null===(e=this._view)||void 0===e?void 0:e.paused))return I(this._name,"[videoelement:action] play (ALREADY PLAYING)"),!0;try{return await(null===(t=this._view)||void 0===t?void 0:t.play()),!0}catch(e){throw k(this._name,"[videoelement:action] play (FAULT) - "+e.message),e}}async pause(){var e;I(this._name,"[videoelement:action] pause");try{return await(null===(e=this._view)||void 0===e?void 0:e.pause()),!0}catch(e){O(this._name,"[videoelement:action] pause (CATCH::FAULT) - "+e.message)}return!1}async resume(){var e;I(this._name,"[videoelement:action] resume");try{return await(null===(e=this._view)||void 0===e?void 0:e.play()),!0}catch(e){O(this._name,"[videoelement:action] resume (CATCH::FAULT) - "+e.message)}return!1}async stop(){var e;I(this._name,"[videoelement:action] stop");try{return await(null===(e=this._view)||void 0===e?void 0:e.pause()),!0}catch(e){O(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 St="WHEPClient",Et=at,Ct=e=>I(St,e),ft=e=>k(St,e),bt=e=>O(St,e);class wt extends pt{constructor(e,t,i){super(),this._videoMuted=!0,this._audioMuted=!0;const n=e?se(e):Et,s=i||Et,o={...s,...n,endpoint:e,mediaElementId:t?t.id:s.mediaElementId};this._videoUnmuteHandler=this._onVideoUnmute.bind(this),this._audioUnmuteHandler=this._onAudioUnmute.bind(this),e&&this.internalInit(o)}async internalInit(e){await this.init(e),await this.subscribe()}async _runMuteCheck(){var e,t,i;if(this.getPeerConnection())try{let n=this._videoMuted,s=this._audioMuted;const o=await(null===(e=this.getPeerConnection())||void 0===e?void 0:e.getStats());if(null==o||o.forEach((e=>{const{type:t,kind:i,bytesReceived:o}=e;"inbound-rtp"!==t&&"inboundrtp"!==t||("video"===i?n=o<=0:"audio"===i&&(s=o<=0))})),n===this._videoMuted&&s===this._audioMuted)return;this._videoMuted=n,this._audioMuted=s;const a={data:{streamingMode:(t=!this._videoMuted,i=!this._audioMuted,t&&i?ut.FULL:t?ut.VIDEO:i?ut.AUDIO:ut.EMPTY),method:"onMetaData"},type:"metadata",method:"onMetaData",eventTimestamp:(new Date).getTime()};this._onMetaData(a)}catch(e){ft(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(i){var n;Ct("[requestoffer]");const{iceTransport:s,maintainStreamVariant:o,videoEncoding:a,audioEncoding:r,connectionParams:l,mungeOffer:d}=this._options;i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const h={transport:s,doNotSwitch:o};a&&a!==t.NONE&&(h.videoEncoding=a),r&&r!==e.NONE&&(h.audioEncoding=r);const c=null!=l?l:{},u=await i.createOffer(),p=await(null===(n=this._whipWhepService)||void 0===n?void 0:n.postSDPOffer(u.sdp,{...c,...h},!1));if(!p)throw ft("Failed to get offer from WHEP"),new Error("Failed to get offer from WHEP");const{sdp:_}=p;let m=_;return d&&(Ct(`[MUNGE:before] offer: ${m}`),m=d(m),Ct(`[MUNGE:after] offer: ${m}`)),m}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=Ie(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={...Et,...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 e,t,i,n,s,o,a,r;const{connectionParams:l,rtcConfiguration:d,includeDataChannel:h,signalingSocketOnly:c,enableChannelSignaling:u,dataChannelConfiguration:p}=this._options;try{const r=l||{},m=await(null===(e=this._whipWhepService)||void 0===e?void 0:e.getOptions(r));this.trigger(new ve(fe.CONNECT_SUCCESS,this,null===(t=this._whipWhepService)||void 0===t?void 0:t.getUrl())),(null==m?void 0:m.links)&&(this._options.rtcConfiguration={...d,iceServers:m.links}),(null==m?void 0:m.origin)&&this.trigger(new ve(be.HOST_ENDPOINT_CHANGED,this,{endpoint:m.origin})),(null==m?void 0:m.statisticsEndpoint)&&this._onStatisticsEndpointChange(m.statisticsEndpoint);const g=h||u||c?p: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,g),null===(i=this.getPeerConnection())||void 0===i||i.addEventListener("track",(e=>{const{buffer:t}=this._options;Ct("[peerconnection.ontrack]");const{streams:i,track:n,receiver:s,transceiver:o}=e;s.playoutDelayHint=t,s.jitterBufferDelayHint=t,this.trigger(new ve(be.TRACK_ADDED,this,{streams:i,track:n,receiver:s,transceiver:o})),this._mediaStream=i&&i.length>0?i[0]:void 0,"video"===n.kind?(this._videoMuted=n.muted,n.muted&&n.addEventListener("unmute",this._videoUnmuteHandler)):"audio"===n.kind&&(this._audioMuted=n.muted,n.muted&&n.addEventListener("unmute",this._audioUnmuteHandler)),this._runMuteCheck()})),this.trigger(new ve(be.PEER_CONNECTION_AVAILABLE,this,this.getPeerConnection())),this.trigger(new ve(be.OFFER_START,this));const v=await this.requestOffer(this.getPeerConnection()),S=new RTCSessionDescription({type:"offer",sdp:v});await(null===(n=this.getPeerConnection())||void 0===n?void 0:n.setRemoteDescription(S)),this.trigger(new ve(be.OFFER_END,this)),this.trigger(new ve(be.ANSWER_START,this));const E=await this.requestAnswer(this.getPeerConnection()),C=(_=E).includes("stereo=1")?_:_.replace("useinbandfec=1","useinbandfec=1;stereo=1;sprop-stereo=1"),f=new RTCSessionDescription({type:"answer",sdp:C});await(null===(s=this.getPeerConnection())||void 0===s?void 0:s.setLocalDescription(f)),await this.sendAnswer(C),this.trigger(new ve(be.ANSWER_END,this));const b=await this._peerConnectionHelper.waitToGatherIce(),{sdp:w}=b;return await this.postCandidateFragments(w),this.trigger(new ve(be.ICE_TRICKLE_COMPLETE,this)),this._mediaStream&&(this.trigger(new ve(be.ON_ADD_STREAM,this,this._mediaStream)),this.addMediaStreamToPlayback(this._options.mediaElementId,this._mediaStream)),(null===(o=this._playbackView)||void 0===o?void 0:o.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(e){throw ft(null!==(r=e.message)&&void 0!==r?r:"Could not subscribe."),e instanceof Me?this._onStreamUnavailable(e):this.trigger(new ve(fe.CONNECT_FAILURE,this,e)),this._options.maintainConnectionOnSubscribeErrors||this.unsubscribe(!0),e}var _}async unsubscribe(e=!1){var t;Ct("[unsubscribe]"),this._peerConnectionHelper&&await this._peerConnectionHelper.tearDown(),this._whipWhepService&&await this._whipWhepService.tearDown(null,e),this._sourceHandler&&this._sourceHandler.disconnect(),this.unmonitorStats(),null===(t=this._playbackView)||void 0===t||t.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(fe.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(N).find((t=>t.toLowerCase()===e.toLowerCase()))?e:N.DEBUG,s="string"==typeof t?t:JSON.stringify(t);null===(i=this.getMessageTransport())||void 0===i||i.post({log:n.toUpperCase(),message:s})}catch(e){const t=e.message||e;ft("Could not send log to server. Message parameter expected to be String or JSON-serializable object."),ft(t)}}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():bt("Cannot play without a Source Handler.")}pause(){Ct("[pause]"),this._sourceHandler?this._sourceHandler.pause():bt("Cannot pause without a Source Handler.")}resume(){Ct("[resume]"),this._sourceHandler?this._sourceHandler.resume():bt("Cannot resume without a Source Handler.")}stop(){Ct("[stop]"),this._sourceHandler?this._sourceHandler.stop():bt("Cannot stop without a Source Handler.")}setVolume(e){Ct("[setVolume]"),this._sourceHandler?this._sourceHandler.setVolume(e):bt("Cannot set volume without a Source Handler.")}getVolume(){var e,t,i;return Ct("[getVolume]"),this._sourceHandler?this._sourceHandler.getVolume():(bt("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():bt("Cannot mute without a Source Handler.")}unmute(){Ct("[unmute]"),this._sourceHandler?this._sourceHandler.unmute():bt("Cannot unmute without a Source Handler.")}seekTo(e){Ct("[seekTo]"),this._sourceHandler?this._sourceHandler.seekTo(e):bt("Cannot seek without a Source Handler.")}toggleFullScreen(){Ct("[toggleFullScreen]"),this._sourceHandler?this._sourceHandler.toggleFullScreen():bt("Cannot toggle full screen without a Source Handler.")}monitorStats(e){Ct("[monitorStats]");const{host:t,endpoint:i,app:n,streamName:s,subscriptionId:o,connectionParams:a}=this._options,r=null!=e?e:ze;return this._statisticsConfiguration={...r,host:t,app:n,hostEndpoint:i,streamName:s,subscriptionId:o,connectionParams:a},this._statsMonitor?bt("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(fe.PLAY_UNPUBLISH,this)),this._sourceHandler&&this._sourceHandler.unpublish()}_onStreamUnavailable(e){Ct(`Stream ${this._options.streamName} does not exist.`),Ct("[onstreamunavailable]: "+JSON.stringify(e,null,2)),this.trigger(new ve(fe.SUBSCRIBE_INVALID_NAME,this))}_onDataChannelError(e,t){ft(`Data channel error: ${t}`),this.trigger(new ve(be.DATA_CHANNEL_ERROR,this,{dataChannel:e,error:t}))}_onSendReceived(e,t){Ct(`Send received: ${e} ${JSON.stringify(t)}`),"onMetaData"===e?this._onMetaData(t):this.trigger(new ve(fe.SUBSCRIBE_SEND_INVOKE,this,{methodName:e,data:t}))}_onStreamSwitchComplete(){Ct("[streamswitch::complete]");const e=this._requestedStreamSwitch;this.trigger(new ve(be.SUBSCRIBE_STREAM_SWITCH,this,{path:e})),this._requestedStreamSwitch=void 0}_onMetaData(e){const{orientation:t,streamingMode:i}=e,n=this._streamingMode;void 0!==t&&t!==this._orientation&&(this._orientation=t,this.trigger(new ve(fe.ORIENTATION_CHANGE,this,{orientation:parseInt(t,10),viewElement:this._playbackView?this._playbackView.view:void 0}))),i&&void 0!==i&&i!==n&&(this._streamingMode=i,this.trigger(new ve(fe.STREAMING_MODE_CHANGE,this,{streamingMode:i,previousStreamingMode:n,viewElement:this._playbackView?this._playbackView.view:void 0}))),this.trigger(new ve(fe.SUBSCRIBE_METADATA,this,e))}_onConnectionClosed(){Ct("Connection closed"),this.unsubscribe(!0),this.trigger(new ve(fe.CONNECTION_CLOSED,this))}_onDataChannelOpen(e){Ct(`Data channel opened: ${e.label}`),this.trigger(new ve(be.DATA_CHANNEL_OPEN,this,{dataChannel:e})),this.trigger(new ve(be.DATA_CHANNEL_AVAILABLE,this,{name:e.label,dataChannel:e})),this._messageTransport=this._peerConnectionHelper,this.trigger(new Se(we.CHANGE,this,{controller:this,transport:this._messageTransport})),this.trigger(new ve(fe.SUBSCRIBE_START,this))}_onDataChannelClose(e){Ct(`Data channel closed: ${e.label}`),this.trigger(new ve(be.DATA_CHANNEL_CLOSE,this,{dataChannel:e}))}_onDataChannelMessage(e,t){Ct(`Data channel message: ${t.data}`),this.trigger(new ve(be.DATA_CHANNEL_MESSAGE,this,{dataChannel:e,message:t}))}_onPeerConnectionOpen(){var e;Ct("Peer connection opened"),this.trigger(new ve(be.PEER_CONNECTION_OPEN,this,this.getPeerConnection())),(null===(e=this._options)||void 0===e?void 0:e.includeDataChannel)||this.trigger(new ve(fe.SUBSCRIBE_START,this))}_onPeerConnectionFail(){ft("Peer connection failed"),this.trigger(new ve(fe.SUBSCRIBE_FAIL,this))}_onPeerConnectionClose(e){Ct(`Peer connection closed: ${e.type}`)}_onIceCandidate(e){Ct(`ICE candidate: ${e.candidate}`),this.trigger(new ve(be.CANDIDATE_CREATE,this,{candidate:e}))}_onPeerConnectionTrackAdd(e){Ct(`Peer connection track added: ${e.id}`)}_onSubscriberStatus(e){Ct(`Subscriber status: ${JSON.stringify(e)}`)}_onSDPSuccess(){Ct("SDP success")}_onSDPError(e){ft(`SDP error: ${e}`)}_onStatisticsEndpointChange(e){Ct(`Statistics endpoint changed: ${e}`),this._statsMonitor&&this._statsMonitor.updateEndpoint(e),this.trigger(new ve(fe.STATISTICS_ENDPOINT_CHANGE,this,{statisticsEndpoint:e}))}_onStatsReport(e,t){this.trigger(new ve(be.STATS_REPORT,this,{connection:e,report:t}))}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}trigger(e){super.trigger(e)}getType(){return"RTC"}}class At 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(fe.SUBSCRIBE_START,this._view)),this._playingStarted=!0}_onSourceError(e){I(this._name,"[source:event] error"),this.trigger(new ve(fe.CONNECT_FAILURE,void 0,e))}_onOrientationMetadata(e){const{orientation:t}=e,i=parseInt(t,10);t&&this._orientation!==i&&(I(this._name,"Metadata received: "+JSON.stringify(e,null,2)),this._orientation=i,this.trigger(new ve(fe.ORIENTATION_CHANGE,{orientation:this._orientation,viewElement:this._view})),this.trigger(new ve(fe.SUBSCRIBE_METADATA,void 0,e)))}_onStreamingModeMetadata(e){const{streamingMode:t}=e,i=this._streamingMode;t&&i!==t&&(I(this._name,"Metadata received: "+JSON.stringify(e,null,2)),this._streamingMode=t,this.trigger(new ve(fe.STREAMING_MODE_CHANGE,void 0,{streamingMode:this._streamingMode,previousStreamingMode:i,viewElement:this._view})),this.trigger(new ve(fe.SUBSCRIBE_METADATA,void 0,e)))}_cleanup(){this._view&&this._view.removeEventListener("playing",this.onPlaying),this._source&&(this._source.removeEventListener("error",this.onSourceError),this._view.removeChild(this._source),this._source=void 0),super._cleanup()}}const yt="HLSSubscriber",Tt=e=>I(yt,e),Lt=e=>O(yt,e);class Pt 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={...rt,...e},this}async subscribe(){var e;try{const t=/^http(|s).*\.m3u8/g,{endpoint:i,mediaElementId:n}=this._options;return this._fileURL=i&&i.match(t)?i:(e=>{const{host:t,protocol:i,port:n,app:s,streamName:o,connectionParams:a}=e,r="ws"===i||"http"===i?"http":"https",l=`${r}://${t}:${n||("http"===r?5080:443)}/${s}/${o}.m3u8`;if(a)return`${l}?${Object.entries(a).map((([e,t])=>`${e}=${t}`)).join("&")}`;return l})(this._options),!this._playbackView&&n&&(this._playbackView=new dt(n),this._sourceHandler=new At(this._playbackView.view,this.getType()),this._sourceHandler.addSource(this._fileURL),this._glomTrigger(this._sourceHandler)),this.trigger(new ve(fe.CONNECT_SUCCESS,this,this._fileURL)),this._playIfAutoplaySet(this._options,null===(e=this._playbackView)||void 0===e?void 0:e.view),this}catch(e){throw e(e.message),this.trigger(new ve(fe.CONNECT_FAILURE,this,e.message)),e}}async unsubscribe(){var e;return this._sourceHandler&&this._sourceHandler.disconnect(),null===(e=this._playbackView)||void 0===e||e.detachStream(),this._playbackView=void 0,this._sourceHandler=void 0,this.trigger(new ve(fe.SUBSCRIBE_STOP,this)),this}play(){Tt("[play]"),this._sourceHandler?this._sourceHandler.play():Lt("Cannot play without a Source Handler.")}pause(){Tt("[pause]"),this._sourceHandler?this._sourceHandler.pause():Lt("Cannot pause without a Source Handler.")}resume(){Tt("[resume]"),this._sourceHandler?this._sourceHandler.resume():Lt("Cannot resume without a Source Handler.")}stop(){Tt("[stop]"),this._sourceHandler?this._sourceHandler.stop():Lt("Cannot stop without a Source Handler.")}setVolume(e){Tt("[setVolume]"),this._sourceHandler?this._sourceHandler.setVolume(e):Lt("Cannot set volume without a Source Handler.")}getVolume(){var e,t,i;return Tt("[getVolume]"),this._sourceHandler?this._sourceHandler.getVolume():(Lt("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(){Tt("[mute]"),this._sourceHandler?this._sourceHandler.mute():Lt("Cannot mute without a Source Handler.")}unmute(){Tt("[unmute]"),this._sourceHandler?this._sourceHandler.unmute():Lt("Cannot unmute without a Source Handler.")}seekTo(e){Tt("[seekTo]"),this._sourceHandler?this._sourceHandler.seekTo(e):Lt("Cannot seek without a Source Handler.")}toggleFullScreen(){Tt("[toggleFullScreen]"),this._sourceHandler?this._sourceHandler.toggleFullScreen():Lt("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 Nt={baseURL:void 0,fullURL:void 0,hlsjsRef:void 0,hlsElement:void 0,usePlaybackControlsUI:!0,options:{debug:!1,backBufferLength:0}},Dt={...at,liveSeek:Nt};class Rt extends U{trigger(e){super.trigger(e)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}var Ht,It;!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"}(It||(It={}));class Ot extends me{constructor(e,t,i){super(e,i),this._slider=t}get slider(){return this._slider}}const{createElement:kt,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=>I($t,e),this.warn=e=>O($t,e),this.name=[$t,e].join("::"),this.debug("[init]"),this._container=kt("div"),this._button=this.createButton(),this._track=this.createTrack(),this._progressBar=this.createProgressBar(),this._container.appendChild(this._track),this._container.appendChild(this._progressBar),this._container.appendChild(this._button),this._layout(),this._mouseupHandler=this._mouseup.bind(this),this._mousedownHandler=this._mousedown.bind(this),this._mousemoveHandler=this._mousemove.bind(this),this._touchupHandler=this._touchproxy.bind(this),this._touchdownHandler=this._touchproxy.bind(this),this._touchmoveHandler=this._touchproxy.bind(this),this._updateHandlers(this._disabled)}_touchproxy(e){var t,i,n,s;const o=e;this.debug(`${o.type} touches: ${(null===(t=o.changedTouches)||void 0===t?void 0:t.length)||0}`);try{o.preventDefault()}catch(e){this.warn("Failed to prevent default on touch event.")}if(!o.touches||o.touches.length>1||"touchend"===o.type&&o.touches.length>0)return;let a,r="";const l=o.target||document.body;switch(o.type){case"touchstart":r="mousedown",a=null===(i=o.changedTouches)||void 0===i?void 0:i[0];break;case"touchmove":r="mousemove",a=null===(n=o.changedTouches)||void 0===n?void 0:n[0];break;case"touchend":r="mouseup",a=null===(s=o.changedTouches)||void 0===s?void 0:s[0]}if(a&&r){const e=new MouseEvent(r,{bubbles:!0,cancelable:!0,view:l.ownerDocument.defaultView,screenX:a.screenX,screenY:a.screenY,clientX:a.clientX,clientY:a.clientY,ctrlKey:o.ctrlKey,altKey:o.altKey,shiftKey:o.shiftKey,metaKey:o.metaKey,button:0,relatedTarget:null});l.dispatchEvent(e)}}_mouseup(){this._eventStartPosition=0,Bt(Gt),Ut("mousemove",this._mousemoveHandler),Ut("mouseup",this._mouseupHandler),Ut("touchmove",this._touchmoveHandler),Ut("touchend",this._touchupHandler),this.trigger(new Ot(It.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 Ot(It.CHANGE,this,s))}_mousedown(e){this._eventStartPosition=e.clientX,this.trigger(new Ot(It.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=kt("span");return e.classList.add("red5pro-media-slider-button"),e}createProgressBar(){const e=kt("span");return e.classList.add("red5pro-media-slider-progress"),e}createTrack(){const e=kt("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=>I("PlaybackControls",e);class Jt extends Rt{constructor(e,t){super(),this._state=i.IDLE,this._mutedState=!1,this._resumeAfterSeek=!1,this._playbackDuration=0,this._volumeValue=1,this._player=e,this._container=t,this._onPlayPauseClickBound=this._onPlayPauseClick.bind(this),this._decorate(this._container)}_decorate(e){if(!e)return;zt("[decorate]");const t=xt("div");let n;t.classList.add("red5pro-media-control-bar"),this._playPauseButton=this._createPlayPauseButton(),this._muteButton=this._createMuteButton(),this._volumeField=this._createVolumeControl(),this._seekTimeField=this._createSeekControl(),this._timeField=this._createPlaybackTime(),this._fullScreenButton=this._createFullScreenToggle(),t.appendChild(this._playPauseButton),t.appendChild(this._timeField),t.appendChild(this._seekTimeField.view),t.appendChild(this._muteButton),t.appendChild(this._volumeField.view),t.appendChild(this._fullScreenButton),e.appendChild(t),this._controlbar=t;const s=()=>{clearTimeout(n),n=setTimeout((()=>{t.classList.remove("red5pro-media-control-bar-show")}),6e3)};jt()?(t.classList.add("red5pro-media-control-bar-show"),e.addEventListener("touchend",(()=>{t.classList.toggle("red5pro-media-control-bar-show"),s()})),s()):(e.addEventListener("mouseover",(()=>{t.classList.add("red5pro-media-control-bar-show")})),e.addEventListener("mouseout",(()=>{t.classList.remove("red5pro-media-control-bar-show")}))),this.setState(i.IDLE).onFullScreenChange(!1).setSeekTime(0).enable(!1)}_onPlayPauseClick(){return this.getState()===i.PLAYING?this._player.pause(!0):this.getState()===i.PAUSED?this._player.resume(!0):this._player.play(!0),this}_createPlayPauseButton(){const e=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(It.CHANGE,(e=>{const t=Number(e.data);this._player.setVolume(t)})),e}_createSeekControl(){const e=new Wt("seek");return e.view.classList.add("red5pro-media-control-element"),e.view.classList.add("red5pro-media-seektime-slider"),e.view.classList.add("red5pro-media-slider"),e.on(It.CHANGE_START,(()=>{this.getState()===i.PLAYING&&(this._resumeAfterSeek=!0,this._player.pause(!0,!0)),this.trigger(new me(Ht.SEEK_START))})),e.on(It.CHANGE,(e=>{const t=Number(e.data);this._player.seekTo(t,0===this._playbackDuration?void 0:this._playbackDuration),this.setSeekTime(t*this._playbackDuration,this._playbackDuration)})),e.on(It.CHANGE_COMPLETE,(()=>{this._resumeAfterSeek&&this.getState()===i.PAUSED&&(this._resumeAfterSeek=!1,this._player.resume(!0)),this.trigger(new me(Ht.SEEK_END))})),e}_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(e){var t,n,s,o;return e===i.PLAYING?(null===(t=this._playPauseButton)||void 0===t||t.classList.remove("red5pro-media-play-button"),null===(n=this._playPauseButton)||void 0===n||n.classList.add("red5pro-media-pause-button")):(null===(s=this._playPauseButton)||void 0===s||s.classList.add("red5pro-media-play-button"),null===(o=this._playPauseButton)||void 0===o||o.classList.remove("red5pro-media-pause-button")),this}onMutedStateChange(e){var t,i,n,s;return e?(null===(t=this._muteButton)||void 0===t||t.classList.add("red5pro-media-mute-button"),null===(i=this._muteButton)||void 0===i||i.classList.remove("red5pro-media-unmute-button"),this._volumeField&&(this._volumeField.value=0)):(null===(n=this._muteButton)||void 0===n||n.classList.remove("red5pro-media-mute-button"),null===(s=this._muteButton)||void 0===s||s.classList.add("red5pro-media-unmute-button"),this._volumeField&&(this._volumeField.value=this._volumeValue)),this}onFullScreenChange(e){var t,i,n,s;return e?(null===(t=this._fullScreenButton)||void 0===t||t.classList.add("red5pro-media-exit-fullscreen-button"),null===(i=this._fullScreenButton)||void 0===i||i.classList.remove("red5pro-media-fullscreen-button")):(null===(n=this._fullScreenButton)||void 0===n||n.classList.remove("red5pro-media-exit-fullscreen-button"),null===(s=this._fullScreenButton)||void 0===s||s.classList.add("red5pro-media-fullscreen-button")),this}enable(e){var t,i,n,s;return e?(null===(t=this._playPauseButton)||void 0===t||t.classList.remove("red5pro-media-element-button-disabled"),null===(i=this._playPauseButton)||void 0===i||i.addEventListener("click",this._onPlayPauseClickBound)):(null===(n=this._playPauseButton)||void 0===n||n.classList.add("red5pro-media-element-button-disabled"),null===(s=this._playPauseButton)||void 0===s||s.removeEventListener("click",this._onPlayPauseClickBound)),this}getVolume(){return this._volumeValue}setVolume(e){return this._volumeField&&(this._volumeField.value=e),this._volumeValue=e,0===e?this.setMutedState(!0):this.getMutedState()&&this.setMutedState(!1),this}setSeekTime(e,t=0){return this._seekTimeField&&(this._seekTimeField.value=0===t?0:e/t,0!==this._playbackDuration&&this._playbackDuration<=e&&(this._seekTimeField.value=1)),this._timeField&&(!isFinite(this._playbackDuration)&&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]: ${s[e]}`),this._state=e,this.onStateChange(this._state),this}setMutedState(e){return this._mutedState=e,this.onMutedStateChange(this._mutedState),this}getMutedState(){return"muted"in this._player?this._player.muted:this._mutedState}setAsVOD(e){return 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=>I(ni,e),oi=e=>k(ni,e),ai=e=>O(ni,e);class ri 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(e){var t;const i=null!==(t=this._playbackNotificationCenter)&&void 0!==t?t:e.target,n=this.getControls();if(this.isSeekable){if(!this._isHLSPlaybackActive){const e=this._hlsElement.duration,t=i.currentTime-this._lastDurationUpdate,s=isNaN(e)||0===e?i.currentTime:e+this._averageSegmentDuration+t;n&&n.setSeekTime(s,s),this.trigger(new ve(fe.PLAYBACK_TIME_UPDATE,void 0,{time:s,duration:s,action:"rtc time update (1)"}))}}else super._onTimeUpdate(e)}_onEnded(){this.isHLSPlaybackActive||super._onEnded()}_onHLSDurationChange(e){const t=e.target,i=e.duration||t.duration;isNaN(this._wallOffset)&&(this._wallOffset=i-this._view.currentTime),this._lastDurationUpdate=this._view.currentTime;const n=i+this._averageSegmentDuration;si(`[HLS:videoelement:duration] ${i}, ${this._averageSegmentDuration}`);const s=this.getControls();s&&s.setPlaybackDuration(n),this._isHLSPlaybackActive?this.trigger(new ve(fe.PLAYBACK_TIME_UPDATE,void 0,{time:t.currentTime,duration:n,action:"hls time update"})):this.trigger(new ve(fe.PLAYBACK_TIME_UPDATE,void 0,{time:n,duration:n,action:"hls time update"}))}_onHLSTimeUpdate(e){const t=e.target,i=this.getControls();i&&i.setSeekTime(t.currentTime,i.getPlaybackDuration()),t.currentTime>=t.duration?this._showHLSLivePlayback(!1,this._hlsElement,this._view,this._container):!isNaN(t.duration)&&this._isHLSPlaybackActive&&this.trigger(new ve(fe.PLAYBACK_TIME_UPDATE,void 0,{time:t.currentTime,duration:t.duration+this._averageSegmentDuration,action:"hls time update"}))}_onHLSPlay(){si("[HLS:videoelement:event] play");const e=this.getControls();e&&e.setState(i.PLAYING),this.trigger(new ve(fe.PLAYBACK_STATE_CHANGE,void 0,{code:i.PLAYING,state:s[i.PLAYING]}))}_onHLSPause(){si("[HLS:videoelement:event] pause");const e=this.getControls();e&&e.setState(i.PAUSED),this.trigger(new ve(fe.PLAYBACK_STATE_CHANGE,void 0,{code:i.PAUSED,state:s[i.PAUSED]}))}_addSeekableHandlers(e,t,i){if(t){const i=ii();t.on(i.ERROR,((i,n)=>{const{type:s,details:o,fatal:a,url:r}=n;if("networkerror"===s.toLowerCase()){if("levelemptyerror"===o.toLowerCase()){this.trigger(new ve(Xt.LIVE_SEEK_DISABLED,void 0,{hlsElement:e,hlsControl:t})),this.isSeekable=!1,t.destroy();const i=setTimeout((()=>{clearTimeout(i),this.enableLiveSeek(r,this._subscriptionId,this._hlsElement,!1)}),3e3);return}this.trigger(new 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()),a&&"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 a=6,r=0;if(o&&o.stats&&o.stats.segments){const e=o.stats.segments;for(let t=0;t<e.length;t++)r+=e[t].duration;a=r/e.length,this._averageSegmentDuration=a}si(`fragload, [HLS:videoelement:duration] ${s} + ${a}`),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 a=6,r=0;if(o&&o.stats&&o.stats.segments){const e=o.stats.segments;for(let t=0;t<e.length;t++)r+=e[t].duration;a=r/e.length,this._averageSegmentDuration=a}si(`fragparsed, [HLS:videoelement:duration] ${s} + ${a}`),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){ai(`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){ai(`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 ai(`Could not find lines in manifest: ${e}`);const a=o.reverse().find((e=>n.test(e)));if(!a)return void ai(`Could not find last segment in manifest: ${e}`);const r=o.find((e=>i.test(e)));if(!r)return void ai(`Could not find duration line in manifest: ${e}`);const l=r.match(i);if(!l)return void ai(`Could not find duration in manifest: ${e}`);const d=l[1],h=parseFloat(d),c=a.match(n);if(!c)return void ai(`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){ai("[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){ai("[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){ai("[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=>ai("[videoelement:action] play (CATCH::FAULT) "+(e.message?e.message:e))))}catch(e){ai("[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){ai("[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){ai("[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=>k(hi,e);class ui extends wt{constructor(e,t,i){super(e,t,i)}async init(e){const{liveSeek:t}=e;return t||(e.liveSeek=Nt),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 O(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 ri(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(),a=s.join("/"),r={...this._options,app:a,streamName:o};let l=n;if(n){const e=/.*\/(.*)\.m3u8/.exec(n);if(e&&e.length>1){const t=`${e[1]}.m3u8`;l=n.replace(t,`${o}.m3u8`)}}const d=ne(r,i,l);this._sourceHandler&&this._sourceHandler.switchLiveSeek(d)}super._onStreamSwitchComplete()}}const pi="15.0.0";D(N.ERROR);const _i=(e,t=!1)=>{Object.prototype.hasOwnProperty.call(N,e.toUpperCase())&&(D(e,t),console&&console.log(`Red5 Pro SDK Version ${mi()}`))},mi=()=>pi;I("RED5",`Red5 Pro HTML SDK Version: ${pi}`);var gi={version:pi,LOG_LEVELS:N,getLogger:R,getRecordedLogs:H,setLogLevel:_i,getVersion:mi,PlaybackVideoEncoder:t,PlaybackAudioEncoder:e,PlaybackState:i,PlaybackStateReadableMap:s,PublishVideoEncoder:l,PublishAudioEncoder:r,SubscriberEvent:ve,PublisherEvent:ge,MessageTransportStateEvent:Se,PublisherEventTypes:Ee,SubscriberEventTypes:fe,RTCPublisherEventTypes:Ce,RTCSubscriberEventTypes:be,MessageTransportStateEventTypes:we,WHIPClient:ot,WHEPClient:wt,HLSSubscriber:Pt,LiveSeekClient:ui,defaultWhepSubscriberConfig:at,defaultWhipPublisherConfig:pe};export{me as Event,U as EventEmitter,Pt as HLSSubscriber,N as LOG_LEVELS,ui as LiveSeekClient,Se as MessageTransportStateEvent,we as MessageTransportStateEventTypes,e as PlaybackAudioEncoder,pt as PlaybackController,Rt as PlaybackControls,i as PlaybackState,s as PlaybackStateReadableMap,t as PlaybackVideoEncoder,r as PublishAudioEncoder,l as PublishVideoEncoder,ge as PublisherEvent,Ee as PublisherEventTypes,Ce as RTCPublisherEventTypes,be as RTCSubscriberEventTypes,_t as SourceHandler,vt as SourceHandlerImpl,ve as SubscriberEvent,fe as SubscriberEventTypes,wt as WHEPClient,ot as WHIPClient,gi as default,rt as defaultHLSSubscriberConfig,Dt as defaultLiveSeekConfig,ze as defaultStatsConfig,at as defaultWhepSubscriberConfig,pe as defaultWhipPublisherConfig,R as getLogger,H as getRecordedLogs,mi as getVersion,_i as setLogLevel};