"use strict";var CDNStreaming=(()=>{var me=Object.create;var L=Object.defineProperty,le=Object.defineProperties,ce=Object.getOwnPropertyDescriptor,he=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertyNames,z=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var J=(l,e,i)=>e in l?L(l,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):l[e]=i,f=(l,e)=>{for(var i in e||(e={}))j.call(e,i)&&J(l,i,e[i]);if(z)for(var i of z(e))be.call(e,i)&&J(l,i,e[i]);return l},Y=(l,e)=>le(l,he(e));var Se=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),De=(l,e)=>{for(var i in e)L(l,i,{get:e[i],enumerable:!0})},Z=(l,e,i,u)=>{if(e&&typeof e=="object"||typeof e=="function")for(let d of pe(e))!j.call(l,d)&&d!==i&&L(l,d,{get:()=>e[d],enumerable:!(u=ce(e,d))||u.enumerable});return l};var Q=(l,e,i)=>(i=l!=null?me(ge(l)):{},Z(e||!l||!l.__esModule?L(i,"default",{value:l,enumerable:!0}):i,l)),Ce=l=>Z(L({},"__esModule",{value:!0}),l);var b=(l,e,i)=>(J(l,typeof e!="symbol"?e+"":e,i),i);var X=Se((ee,H)=>{(function(l){"use strict";function e(t,h){var r=(t&65535)+(h&65535),g=(t>>16)+(h>>16)+(r>>16);return g<<16|r&65535}function i(t,h){return t<>>32-h}function u(t,h,r,g,D,T){return e(i(e(e(h,t),e(g,T)),D),r)}function d(t,h,r,g,D,T,I){return u(h&r|~h&g,t,h,D,T,I)}function c(t,h,r,g,D,T,I){return u(h&g|r&~g,t,h,D,T,I)}function m(t,h,r,g,D,T,I){return u(h^r^g,t,h,D,T,I)}function p(t,h,r,g,D,T,I){return u(r^(h|~g),t,h,D,T,I)}function S(t,h){t[h>>5]|=128<>>9<<4)+14]=h;var r,g,D,T,I,a=1732584193,o=-271733879,s=-1732584194,n=271733878;for(r=0;r>5]>>>h%32&255);return r}function _(t){var h,r=[];for(r[(t.length>>2)-1]=void 0,h=0;h>5]|=(t.charCodeAt(h/8)&255)<16&&(g=S(g,t.length*8)),r=0;r<16;r+=1)D[r]=g[r]^909522486,T[r]=g[r]^1549556828;return I=S(D.concat(_(h)),512+h.length*8),C(S(T.concat(I),512+128))}function U(t){var h="0123456789abcdef",r="",g,D;for(D=0;D>>4&15)+h.charAt(g&15);return r}function R(t){return unescape(encodeURIComponent(t))}function M(t){return y(R(t))}function q(t){return U(M(t))}function B(t,h){return G(R(t),R(h))}function A(t,h){return U(B(t,h))}function V(t,h,r){return h?r?B(h,t):A(h,t):r?M(t):q(t)}typeof define=="function"&&define.amd?define(function(){return V}):typeof H=="object"&&H.exports?H.exports=V:l.md5=V})(ee)});var Pe={};De(Pe,{CDNStreaming:()=>W,PublishMode:()=>N,TRTCStreamType:()=>$,default:()=>Ae});var te=Q(X(),1);var N=(u=>(u.PublishMainStreamToCDN="publish-main-stream-to-cdn",u.PublishSubStreamToCDN="publish-sub-stream-to-cdn",u.PublishMixStreamToCDN="publish-mix-stream-to-cdn",u))(N||{}),$=(i=>(i.Main="main",i.Sub="sub",i))($||{});var F={IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5};var E=class{constructor(e,i){b(this,"_core");b(this,"_room");b(this,"_log");b(this,"_params");b(this,"_publishGivenCDNData",null);this._core=e,this._room=e.room,this._log=i}get isPublishingGivenCDN(){return!!this._params}async startPublishGivenCDN(e){if(this._log.info(`[CDNStreaming] startPublishGivenCDN() current: ${JSON.stringify(this._params)}, params: ${JSON.stringify(e)}`),this.isPublishingGivenCDN){let{appId:i,bizId:u,url:d}=this._params||{};if(i===e.appId&&u===e.bizId&&d===e.url)return;await this.stopPublishGivenCDN()}this._params=e,this._publishGivenCDNData={pushRequestTime:Date.now(),pushAppId:e.appId,pushBizId:e.bizId,pushCdnUrl:e.url,pushStreamType:this.convertStreamType(e==null?void 0:e.publishMode),pushStreamId:e.streamId};try{let i=await this._room.sendStartPublishCDN(this._publishGivenCDNData,!1),{code:u,message:d}=i.data;if(u===0)this._log.info("[CDNStreaming] server success: start given cdn.");else throw this.resetGivenCDN(),this._log.error(`[CDNStreaming] server failed: start given cdn errCode: ${u} errMsg: ${d} options: ${JSON.stringify(e)}`),new Error(`[CDNStreaming] server failed: start given cdn errCode: ${u} errMsg: ${d}`)}catch(i){throw this.resetGivenCDN(),i}}async stopPublishGivenCDN(){if(this._log.info("[CDNStreaming] stopPublishGivenCDN"),!this.isPublishingGivenCDN||!this._publishGivenCDNData){this.resetGivenCDN();return}let{pushAppId:e,pushBizId:i,pushCdnUrl:u,pushStreamType:d,pushStreamId:c}=this._publishGivenCDNData,m={pushRequestTime:Date.now(),pushAppId:e,pushBizId:i,pushCdnUrl:u,pushStreamType:d,pushStreamId:c},p=await this._room.sendStopPublishCDN(m,!1),{code:S,message:C}=p.data;if(S===0)this._log.info("[CDNStreaming] server success: stop given cdn."),this.resetGivenCDN();else throw this._log.error(`[CDNStreaming] server failed: stop given cdn errCode: ${S} errMsg: ${C} data: ${JSON.stringify(m)}`),new Error(`[CDNStreaming] server failed: stop given cdn errCode: ${S} errMsg: ${C}`)}resetGivenCDN(){this._publishGivenCDNData=null,this._params=void 0}convertStreamType(e){return e==="publish-sub-stream-to-cdn"?"aux":"main"}};var x=class{constructor(e,i){b(this,"_core");b(this,"_room");b(this,"_log");b(this,"_config",null);b(this,"_data",null);b(this,"_givenCDNManager");this._core=e,this._room=e.room,this._log=i,this.reset()}get isMixing(){return!!this._data}get isStarted(){return!!this._config}get hasCustomCDN(){var e,i,u;return((e=this._config)==null?void 0:e.target.appId)&&((i=this._config)==null?void 0:i.target.bizId)&&((u=this._config)==null?void 0:u.target.url)}async startMixTranscode(e){if(this._log.info(`startMixTranscode: ${JSON.stringify(e)}`),this._config=e,this.installEvents(),!!this._core.room.isJoined)try{let i=this.getInputParam(e),u=this.getOutputParam(e),d=this.getOutputSessionId({config:e,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&d!==this._data.outputSessionId&&(this._log.info("[CDNStreaming] streamId changed, auto stop mixing before start"),await this.doStopMixTranscode()),await this.doStartMixTranscode({outputSessionId:d,inputParam:i,outputParam:u});let{appId:c,bizId:m,url:p,streamId:S=""}=e.target;c&&m&&p&&(this._givenCDNManager||(this._givenCDNManager=new E(this._core,this._log)),await this._givenCDNManager.startPublishGivenCDN({publishMode:e.target.publishMode,appId:c,bizId:m,url:p,streamId:S}))}catch(i){throw this.reset(),i}}async doStartMixTranscode({outputSessionId:e,inputParam:i,outputParam:u}){let d={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:e,inputParam:i,outputParam:u};this._log.info(`[CDNStreaming] doStartMixTranscode: ${JSON.stringify(d)}`);let c=await this._room.sendStartMixTranscode(d),{code:m}=c.data,{message:p}=c.data;if(m===0)this._log.info("[CDNStreaming] server success: start mix"),this._data=d;else throw m===-102083&&(p=`Please enable relayed-push in ${this._core.constants.CLOUD_CONSOLE_URL} and try later, refer to ${this._core.constants.DOC_URL}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`[CDNStreaming] server failed: start mix errCode: ${m} errMsg: ${p}`),new Error(`[CDNStreaming] server failed: start mix errCode: ${m} errMsg: ${p}`)}async stopMixTranscode(){this._log.info("[CDNStreaming] stopMixTranscode");try{this.isStarted&&this.isMixing&&(await this.doStopMixTranscode(),this._config&&this.hasCustomCDN&&this._givenCDNManager&&await this._givenCDNManager.stopPublishGivenCDN())}catch(e){throw e}this.reset()}async doStopMixTranscode(){let e={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`[CDNStreaming] doStopMixTranscode: ${JSON.stringify(e)}`);let i=await this._room.sendStopMixTranscode(e),{code:u,message:d}=i.data;if(u===0)this._log.info("[CDNStreaming] server success: stop mix"),this.reset();else throw this._log.error(`[CDNStreaming] server failed: stop mix errCode: ${u} errMsg: ${d}`),new Error(`[CDNStreaming] server failed: stop mix errCode: ${u} errMsg: ${d}`)}reset(){this._config=null,this._data=null,this.uninstallEvents()}installEvents(){this._core.room.on("joined",this.handleRoomJoined,this),this._core.room.on("left",this.handleRoomLeft,this)}uninstallEvents(){this._core.room.off("joined",this.handleRoomJoined,this),this._core.room.off("left",this.handleRoomLeft,this)}async handleRoomJoined(){this._log.info(`[CDNStreaming] handleJoined: ${JSON.stringify(this._config)}`),this.isStarted&&this._config&&await this.startMixTranscode(this._config)}async handleRoomLeft(){this._log.info(`[CDNStreaming] handleRoomLeft: ${JSON.stringify(this._config)}`),this._data=null}getOutputSessionId({config:e,userId:i,roomId:u}){return this._core.utils.isString(e.target.streamId)&&e.target.streamId.length>0?e.target.streamId:(0,te.default)(`${u}_${i}_main`)}getStringRoomId(e,i){return e?String(e):i}getInputParam(e){let{mix:i={}}=e,{audioMixUserList:u=[],videoLayoutList:d=[]}=i,c=d.map(m=>({userId:m.fixedVideoUser.userId,roomId:this.getStringRoomId(m.fixedVideoUser.roomId,m.fixedVideoUser.strRoomId)||this._core.room.roomId,width:m.width||0,height:m.height||0,locationX:m.locationX||0,locationY:m.locationY||0,zOrder:m.zOrder||1,streamType:m.fixedVideoStreamType==="sub"?1:0,inputType:F.IT_PURE_VIDEO,renderMode:m.fillMode||0}));return u.forEach(m=>{let p=this._core.room.roomId;(m.roomId||m.strRoomId)&&(p=this.getStringRoomId(m.roomId,m.strRoomId));let S=c.findIndex(C=>C.userId===m.userId&&C.roomId===p);S!==-1?c[S].inputType=F.IT_AUDIO_VIDEO:c.push({userId:m.userId,roomId:m.roomId||m.strRoomId||this._core.room.roomId,inputType:F.IT_PURE_AUDIO})}),c}getOutputParam(e){let i=e.target.streamId||"",{encoding:u={},mix:d={}}=e;return{streamId:i,streamType:i.length>0?1:0,width:this._core.utils.isUndefined(u.videoWidth)?640:u.videoWidth,height:this._core.utils.isUndefined(u.videoHeight)?480:u.videoHeight,videoBps:u.videoBitrate||0,fps:u.videoFramerate||15,gop:u.videoGOP||2,audioSampleRate:u.audioSampleRate||48e3,audioBps:u.audioBitrate||64,audioChannels:u.audioChannels||1,backgroundColor:d.backgroundColor||0,backgroundImg:d.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}};var K=Q(X(),1);var v=class{constructor(e,i){b(this,"_room");b(this,"_core");b(this,"_log");b(this,"_paramsForTencentCDN");b(this,"_initParamsForTencentCDN",{isPublished:!1,isStarted:!1});this._core=e,this._room=e.room,this._log=i,this._paramsForTencentCDN=new Map([["publish-main-stream-to-cdn",this._initParamsForTencentCDN],["publish-sub-stream-to-cdn",this._initParamsForTencentCDN]])}installEvents(){this._core.innerEmitter.on("104",this.handlePublished,this),this._core.room.on("left",this.handleRoomLeft,this)}uninstallEvents(){this._core.innerEmitter.off("104",this.handlePublished,this),this._core.room.off("left",this.handleRoomLeft,this)}async handlePublished({track:e}){var d;if(e.room!==this._room||(this._log.info(`[CDNStreaming] handlePublished: mediaType ${e.mediaType}, roomID ${(d=e==null?void 0:e.room)==null?void 0:d.roomId}`),e.mediaType===1))return;let i=e.mediaType===4?"publish-main-stream-to-cdn":"publish-sub-stream-to-cdn",u=this._paramsForTencentCDN.get(i)||null;u!=null&&u.target&&u.isStarted&&await this.startPublishTencentCDN(u.target)}async handleRoomLeft(){this._log.info("[CDNStreaming] handleRoomLeft"),this.changeDataStatus("publish-main-stream-to-cdn",{isPublished:!1}),this.changeDataStatus("publish-sub-stream-to-cdn",{isPublished:!1})}isStreamPublished(e){return e==="publish-main-stream-to-cdn"&&!this._room.isMainStreamPublished?(this._log.info("[CDNStreaming] Main stream has not already published, will auto reStart after published."),!1):e==="publish-sub-stream-to-cdn"&&!this._room.isAuxStreamPublished?(this._log.info("[CDNStreaming] Sub has not already published, will auto reStart after published."),!1):!0}changeDataStatus(e,i){let u=this._paramsForTencentCDN.get(e),d=f(f({},u),i);this._paramsForTencentCDN.set(e,d)}async startPublishTencentCDN(e){if(this._log.info(`[CDNStreaming] startPublishTencentCDN ${JSON.stringify(e)}`),this.installEvents(),this.changeDataStatus(e.publishMode,{target:e,isStarted:!0}),!this.isStreamPublished(e.publishMode))return;let i=e.streamId||"",u=this.generatePublishCDNStreamId(i,e.publishMode),d=this.generatePublishCDNSessionId(e.publishMode),c=e.publishMode==="publish-sub-stream-to-cdn"?1:0,m={requestTime:Date.now(),sessionId:d,streamId:u,streamType:c};await this.doStartPublishTencentCDN(m,e.publishMode);let{appId:p,bizId:S,url:C}=e;if(p&&S&&C){let _=this._paramsForTencentCDN.get(e.publishMode)||this._initParamsForTencentCDN;_!=null&&_.givenCDNManager||(_.givenCDNManager=new E(this._core,this._log),this._paramsForTencentCDN.set(e.publishMode,_)),await _.givenCDNManager.startPublishGivenCDN({publishMode:e.publishMode,appId:p,bizId:S,url:C,streamId:u})}}async doStartPublishTencentCDN(e,i){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);let u=6,d=500,c=0;for(;;){let m=await this._room.sendStartPublishCDN(e,!0),{code:p}=m.data,{message:S}=m.data;if(p===0){this._log.info("[CDNStreaming] server success: start tencent cdn"),this.changeDataStatus(i,{isPublished:!0});break}else if(p===-10006&&csetTimeout(C,d));else throw this.changeDataStatus(i,{isPublished:!1}),p===-102083&&(S=`Please enable relayed-push in ${this._core.constants.CLOUD_CONSOLE_URL} and try later, refer to ${this._core.constants.DOC_URL}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`[CDNStreaming] server failed: start tencent cdn errCode: ${p} errMsg: ${S}`),new Error(`[CDNStreaming] server failed: start tencent cdn errCode: ${p} errMsg: ${S}`)}}async stopPublishTencentCDN(e){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);let i=this._paramsForTencentCDN.get(e)||this._initParamsForTencentCDN;if(i.isPublished){let{target:u}=i;u!=null&&u.bizId&&u.appId&&u.url&&(i!=null&&i.givenCDNManager)&&await(i==null?void 0:i.givenCDNManager.stopPublishGivenCDN()),await this.doStopPublishTencentCDN(e)}this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}async doStopPublishTencentCDN(e){let i={requestTime:Date.now(),sessionId:(0,K.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)};this._log.info(`[CDNStreaming] doStopPublishTencentCDN: ${JSON.stringify(i)}`);let u=await this._room.sendStopPublishCDN(i,!0),{code:d}=u.data,{message:c}=u.data;if(d===0)this._log.info("[CDNStreaming] server success: stop tencent cdn"),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),this.reset(e);else throw d===-102069&&(this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),c=`can not stop in auto relayed-push mode ${c}`),this._log.error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${d} errMsg: ${c}`),new Error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${d} errMsg: ${c}`)}reset(e){this.uninstallEvents(),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}generatePublishCDNStreamId(e,i){if(e===""){let u=`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(i)}`;return/^[A-Za-z\d_-]*$/.test(u)||(u=(0,K.default)(u)),`${this._room.sdkAppId}_${u}`}return e}convertPublishModeToStreamType(e){return e==="publish-main-stream-to-cdn"?"main":"aux"}generatePublishCDNSessionId(e){return(0,K.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)}};var re=l=>typeof l=="string";var P;function _e(l,e,i,u){if(!/^[A-Za-z\d_-]*$/.test(l)){let{RtcError:c,ErrorCode:m,ErrorCodeDictionary:p}=P;throw new c({code:m.INVALID_PARAMETER,extraCode:p.INVALID_STREAM_ID,messageParams:{key:"streamId"}})}}function Ie(l,e,i,u){let{RtcError:d,ErrorCode:c,ErrorCodeDictionary:m}=P;if(re(l))throw new d({code:c.INVALID_PARAMETER,extraCode:m.INVALID_ROOM_ID_INTEGER_STRING,fnName:i,messageParams:{key:"roomId"}});if(l===void 0)return;if(!(/^[1-9]\d*$/.test(String(l))&&l<4294967295))throw new d({code:c.INVALID_PARAMETER,extraCode:m.INVALID_ROOM_ID_INTEGER,fnName:i,messageParams:{key:"roomId"}})}function fe(l,e,i,u){let{RtcError:d,ErrorCode:c,ErrorCodeDictionary:m}=P;if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(l))throw new d({code:c.INVALID_PARAMETER,extraCode:m.INVALID_ROOM_ID_STRING,fnName:i,messageParams:{key:"strRoomId"}})}var O={type:"number",notLessThanZero:!0},ie={type:"object",required:!0,properties:{userId:{required:!0,type:"string"},roomId:{type:["string","number"],validate:Ie},strRoomId:{type:"string",validate:fe}}},ae={required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn"]},streamId:{required:!1,type:"string",validate:_e},appId:{type:"number",allowEmpty:!1},bizId:{type:"number",allowEmpty:!1},url:{type:"string",allowEmpty:!1}}},oe={required:!1,type:"object",properties:{videoWidth:O,videoHeight:O,videoBitrate:Y(f({},O),{allowEmpty:!1}),videoFramerate:{type:"number",validate(l,e,i,u){if(l<=0||l>30){let{RtcError:d,ErrorCode:c}=P;throw new d({code:c.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoFramerate, the value must be between (0, 30]."})}}},videoGOP:{type:"number",validate(l,e,i,u){if(l<1||l>8){let{RtcError:d,ErrorCode:c}=P;throw new d({code:c.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoGOP, the value must be between [1, 8]."})}}},audioSampleRate:O,audioBitrate:{type:"number",validate(l,e,i,u){if(l<32||l>192){let{RtcError:d,ErrorCode:c}=P;throw new d({code:c.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> audioBitrate, the value must be between [32, 192]."})}}},audioChannels:{type:"number",values:[1,2]}}},se={required:!1,type:"object",properties:{backgroundColor:{type:"number"},backgroundImage:{type:"string"},audioMixUserList:{type:"array",arrayItem:f({},ie)},videoLayoutList:{type:"array",required:!0,arrayItem:{type:"object",properties:{fixedVideoUser:f({},ie),fixedVideoStreamType:{type:"string",required:!0,values:["main","sub"]},fillMode:{type:"number",values:[0,1,2,4]},zOrder:{type:"number",required:!0,validate(l,e,i,u){if(l<1||l>15){let{RtcError:d,ErrorCode:c}=P;throw new d({code:c.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList -> zOrder, the value must be between [1, 15]."})}}},width:O,height:O,locationX:O,locationY:O}}}}};function ne(l){return P=l.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:f({},ae),encoding:f({},oe),mix:f({},se)},validate(e,i,u,d){var S,C;let{publishMode:c}=e.target,{encoding:m,mix:p}=e;if(c==="publish-mix-stream-to-cdn"){let{RtcError:_,ErrorCode:y,ErrorCodeDictionary:G}=l.errorModule;if(!m)throw new _({code:y.INVALID_PARAMETER,extraCode:G.INVALID_PARAMETER_REQUIRED,fnName:u,messageParams:{key:"encoding"}});if(!p)throw new _({code:y.INVALID_PARAMETER,extraCode:G.INVALID_PARAMETER_REQUIRED,fnName:u,messageParams:{key:"mix"}});if(p&&p.videoLayoutList){let U=0,R=0,M=[];if(p.videoLayoutList.forEach((A,V)=>{M.push(A.fixedVideoUser.userId),A.width+A.locationX>U&&(U=A.width+A.locationX),A.height+A.locationY>R&&(R=A.height+A.locationY)}),M.indexOf(l.room.userId)<0)throw new _({code:y.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList, the value must be include self."});let q=(S=m==null?void 0:m.videoWidth)!=null?S:640,B=(C=m==null?void 0:m.videoHeight)!=null?C:480;if(q