UNPKG

trtc-sdk-v5

Version:
1 lines 30.2 kB
var errorModule,__create=Object.create,__defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,r)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__spreadValues=(e,t)=>{for(var r in t||(t={}))__hasOwnProp.call(t,r)&&__defNormalProp(e,r,t[r]);if(__getOwnPropSymbols)for(var r of __getOwnPropSymbols(t))__propIsEnum.call(t,r)&&__defNormalProp(e,r,t[r]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__commonJS=(e,t)=>function(){return t||(0,e[__getOwnPropNames(e)[0]])((t={exports:{}}).exports,t),t.exports},__copyProps=(e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===r||__defProp(e,i,{get:()=>t[i],enumerable:!(o=__getOwnPropDesc(t,i))||o.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?r:__defProp(r,"default",{value:e,enumerable:!0}),e)),__publicField=(e,t,r)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,r),require_md5=__commonJS({"../node_modules/.pnpm/blueimp-md5@2.19.0/node_modules/blueimp-md5/js/md5.js"(e,t){"use strict";!function(e){function r(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function o(e,t,o,i,s,a){return r((n=r(r(t,e),r(i,a)))<<(d=s)|n>>>32-d,o);var n,d}function i(e,t,r,i,s,a,n){return o(t&r|~t&i,e,t,s,a,n)}function s(e,t,r,i,s,a,n){return o(t&i|r&~i,e,t,s,a,n)}function a(e,t,r,i,s,a,n){return o(t^r^i,e,t,s,a,n)}function n(e,t,r,i,s,a,n){return o(r^(t|~i),e,t,s,a,n)}function d(e,t){var o,d,u,l,h;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var m=1732584193,_=-271733879,p=-1732584194,c=271733878;for(o=0;o<e.length;o+=16)d=m,u=_,l=p,h=c,m=i(m,_,p,c,e[o],7,-680876936),c=i(c,m,_,p,e[o+1],12,-389564586),p=i(p,c,m,_,e[o+2],17,606105819),_=i(_,p,c,m,e[o+3],22,-1044525330),m=i(m,_,p,c,e[o+4],7,-176418897),c=i(c,m,_,p,e[o+5],12,1200080426),p=i(p,c,m,_,e[o+6],17,-1473231341),_=i(_,p,c,m,e[o+7],22,-45705983),m=i(m,_,p,c,e[o+8],7,1770035416),c=i(c,m,_,p,e[o+9],12,-1958414417),p=i(p,c,m,_,e[o+10],17,-42063),_=i(_,p,c,m,e[o+11],22,-1990404162),m=i(m,_,p,c,e[o+12],7,1804603682),c=i(c,m,_,p,e[o+13],12,-40341101),p=i(p,c,m,_,e[o+14],17,-1502002290),m=s(m,_=i(_,p,c,m,e[o+15],22,1236535329),p,c,e[o+1],5,-165796510),c=s(c,m,_,p,e[o+6],9,-1069501632),p=s(p,c,m,_,e[o+11],14,643717713),_=s(_,p,c,m,e[o],20,-373897302),m=s(m,_,p,c,e[o+5],5,-701558691),c=s(c,m,_,p,e[o+10],9,38016083),p=s(p,c,m,_,e[o+15],14,-660478335),_=s(_,p,c,m,e[o+4],20,-405537848),m=s(m,_,p,c,e[o+9],5,568446438),c=s(c,m,_,p,e[o+14],9,-1019803690),p=s(p,c,m,_,e[o+3],14,-187363961),_=s(_,p,c,m,e[o+8],20,1163531501),m=s(m,_,p,c,e[o+13],5,-1444681467),c=s(c,m,_,p,e[o+2],9,-51403784),p=s(p,c,m,_,e[o+7],14,1735328473),m=a(m,_=s(_,p,c,m,e[o+12],20,-1926607734),p,c,e[o+5],4,-378558),c=a(c,m,_,p,e[o+8],11,-2022574463),p=a(p,c,m,_,e[o+11],16,1839030562),_=a(_,p,c,m,e[o+14],23,-35309556),m=a(m,_,p,c,e[o+1],4,-1530992060),c=a(c,m,_,p,e[o+4],11,1272893353),p=a(p,c,m,_,e[o+7],16,-155497632),_=a(_,p,c,m,e[o+10],23,-1094730640),m=a(m,_,p,c,e[o+13],4,681279174),c=a(c,m,_,p,e[o],11,-358537222),p=a(p,c,m,_,e[o+3],16,-722521979),_=a(_,p,c,m,e[o+6],23,76029189),m=a(m,_,p,c,e[o+9],4,-640364487),c=a(c,m,_,p,e[o+12],11,-421815835),p=a(p,c,m,_,e[o+15],16,530742520),m=n(m,_=a(_,p,c,m,e[o+2],23,-995338651),p,c,e[o],6,-198630844),c=n(c,m,_,p,e[o+7],10,1126891415),p=n(p,c,m,_,e[o+14],15,-1416354905),_=n(_,p,c,m,e[o+5],21,-57434055),m=n(m,_,p,c,e[o+12],6,1700485571),c=n(c,m,_,p,e[o+3],10,-1894986606),p=n(p,c,m,_,e[o+10],15,-1051523),_=n(_,p,c,m,e[o+1],21,-2054922799),m=n(m,_,p,c,e[o+8],6,1873313359),c=n(c,m,_,p,e[o+15],10,-30611744),p=n(p,c,m,_,e[o+6],15,-1560198380),_=n(_,p,c,m,e[o+13],21,1309151649),m=n(m,_,p,c,e[o+4],6,-145523070),c=n(c,m,_,p,e[o+11],10,-1120210379),p=n(p,c,m,_,e[o+2],15,718787259),_=n(_,p,c,m,e[o+9],21,-343485551),m=r(m,d),_=r(_,u),p=r(p,l),c=r(c,h);return[m,_,p,c]}function u(e){var t,r="",o=32*e.length;for(t=0;t<o;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function l(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var o=8*e.length;for(t=0;t<o;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function h(e){var t,r,o="0123456789abcdef",i="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),i+=o.charAt(t>>>4&15)+o.charAt(15&t);return i}function m(e){return unescape(encodeURIComponent(e))}function _(e){return function(e){return u(d(l(e),8*e.length))}(m(e))}function p(e,t){return function(e,t){var r,o,i=l(e),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=d(i,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^i[r],a[r]=1549556828^i[r];return o=d(s.concat(l(t)),512+8*t.length),u(d(a.concat(o),640))}(m(e),m(t))}function c(e,t,r){return t?r?p(t,e):h(p(t,e)):r?_(e):h(_(e))}"function"==typeof define&&define.amd?define((function(){return c})):"object"==typeof t&&t.exports?t.exports=c:e.md5=c}(e)}}),import_blueimp_md5=__toESM(require_md5(),1),MIX_INPUT_TYPE={IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5},GivenCDNManager=class{constructor(e,t){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_params"),__publicField(this,"_publishGivenCDNData",null),this._core=e,this._room=e.room,this._log=t}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){const{appId:t,bizId:r,url:o}=this._params||{};if(t===e.appId&&r===e.bizId&&o===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(null==e?void 0:e.publishMode),pushStreamId:e.streamId};try{const t=await this._room.sendStartPublishCDN(this._publishGivenCDNData,!1),{code:r,message:o}=t.data;if(0!==r)throw this.resetGivenCDN(),this._log.error(`[CDNStreaming] server failed: start given cdn errCode: ${r} errMsg: ${o} options: ${JSON.stringify(e)}`),new Error(`[CDNStreaming] server failed: start given cdn errCode: ${r} errMsg: ${o}`);this._log.info("[CDNStreaming] server success: start given cdn.")}catch(e){throw this.resetGivenCDN(),e}}async stopPublishGivenCDN(){if(this._log.info("[CDNStreaming] stopPublishGivenCDN"),!this.isPublishingGivenCDN||!this._publishGivenCDNData)return void this.resetGivenCDN();const{pushAppId:e,pushBizId:t,pushCdnUrl:r,pushStreamType:o,pushStreamId:i}=this._publishGivenCDNData,s={pushRequestTime:Date.now(),pushAppId:e,pushBizId:t,pushCdnUrl:r,pushStreamType:o,pushStreamId:i},a=await this._room.sendStopPublishCDN(s,!1),{code:n,message:d}=a.data;if(0!==n)throw this._log.error(`[CDNStreaming] server failed: stop given cdn errCode: ${n} errMsg: ${d} data: ${JSON.stringify(s)}`),new Error(`[CDNStreaming] server failed: stop given cdn errCode: ${n} errMsg: ${d}`);this._log.info("[CDNStreaming] server success: stop given cdn."),this.resetGivenCDN()}resetGivenCDN(){this._publishGivenCDNData=null,this._params=void 0}convertStreamType(e){return"publish-sub-stream-to-cdn"===e?"aux":"main"}},MixTranscodeManager=class{constructor(e,t){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_config",null),__publicField(this,"_data",null),__publicField(this,"_givenCDNManager"),this._core=e,this._room=e.room,this._log=t,this.reset()}get isMixing(){return!!this._data}get isStarted(){return!!this._config}get hasCustomCDN(){var e,t,r;return(null==(e=this._config)?void 0:e.target.appId)&&(null==(t=this._config)?void 0:t.target.bizId)&&(null==(r=this._config)?void 0:r.target.url)}async startMixTranscode(e){if(this._log.info(`startMixTranscode: ${JSON.stringify(e)}`),this._config=e,this.installEvents(),this._core.room.isJoined)try{const t=this.getInputParam(e),r=this.getOutputParam(e),o=this.getOutputSessionId({config:e,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&o!==this._data.outputSessionId&&(this._log.info("[CDNStreaming] streamId changed, auto stop mixing before start"),await this.doStopMixTranscode()),await this.doStartMixTranscode({outputSessionId:o,inputParam:t,outputParam:r});const{appId:i,bizId:s,url:a,streamId:n=""}=e.target;i&&s&&a&&(this._givenCDNManager||(this._givenCDNManager=new GivenCDNManager(this._core,this._log)),await this._givenCDNManager.startPublishGivenCDN({publishMode:e.target.publishMode,appId:i,bizId:s,url:a,streamId:n}))}catch(e){throw this.reset(),e}}async doStartMixTranscode({outputSessionId:e,inputParam:t,outputParam:r}){const o={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:e,inputParam:t,outputParam:r};this._log.info(`[CDNStreaming] doStartMixTranscode: ${JSON.stringify(o)}`);const i=await this._room.sendStartMixTranscode(o),{code:s}=i.data;let{message:a}=i.data;if(0!==s)throw-102083===s&&(a=`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: ${s} errMsg: ${a}`),new Error(`[CDNStreaming] server failed: start mix errCode: ${s} errMsg: ${a}`);this._log.info("[CDNStreaming] server success: start mix"),this._data=o}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(){const e={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`[CDNStreaming] doStopMixTranscode: ${JSON.stringify(e)}`);const t=await this._room.sendStopMixTranscode(e),{code:r,message:o}=t.data;if(0!==r)throw this._log.error(`[CDNStreaming] server failed: stop mix errCode: ${r} errMsg: ${o}`),new Error(`[CDNStreaming] server failed: stop mix errCode: ${r} errMsg: ${o}`);this._log.info("[CDNStreaming] server success: stop mix"),this.reset()}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:t,roomId:r}){return this._core.utils.isString(e.target.streamId)&&e.target.streamId.length>0?e.target.streamId:(0,import_blueimp_md5.default)(`${r}_${t}_main`)}getStringRoomId(e,t){return e?String(e):t}getInputParam(e){const{mix:t={}}=e,{audioMixUserList:r=[],videoLayoutList:o=[]}=t,i=o.map((e=>({userId:e.fixedVideoUser.userId,roomId:this.getStringRoomId(e.fixedVideoUser.roomId,e.fixedVideoUser.strRoomId)||this._core.room.roomId,width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder||1,streamType:"sub"===e.fixedVideoStreamType?1:0,inputType:MIX_INPUT_TYPE.IT_PURE_VIDEO,renderMode:e.fillMode||0})));return r.forEach((e=>{let t=this._core.room.roomId;(e.roomId||e.strRoomId)&&(t=this.getStringRoomId(e.roomId,e.strRoomId));const r=i.findIndex((r=>r.userId===e.userId&&r.roomId===t));-1!==r?i[r].inputType=MIX_INPUT_TYPE.IT_AUDIO_VIDEO:i.push({userId:e.userId,roomId:e.roomId||e.strRoomId||this._core.room.roomId,inputType:MIX_INPUT_TYPE.IT_PURE_AUDIO})})),i}getOutputParam(e){const t=e.target.streamId||"",{encoding:r={},mix:o={}}=e;return{streamId:t,streamType:t.length>0?1:0,width:this._core.utils.isUndefined(r.videoWidth)?640:r.videoWidth,height:this._core.utils.isUndefined(r.videoHeight)?480:r.videoHeight,videoBps:r.videoBitrate||0,fps:r.videoFramerate||15,gop:r.videoGOP||2,audioSampleRate:r.audioSampleRate||48e3,audioBps:r.audioBitrate||64,audioChannels:r.audioChannels||1,backgroundColor:o.backgroundColor||0,backgroundImg:o.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}},import_blueimp_md52=__toESM(require_md5(),1),PublishCDNManager=class{constructor(e,t){__publicField(this,"_room"),__publicField(this,"_core"),__publicField(this,"_log"),__publicField(this,"_paramsForTencentCDN"),__publicField(this,"_initParamsForTencentCDN",{isPublished:!1,isStarted:!1}),this._core=e,this._room=e.room,this._log=t,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 t;if(e.room!==this._room)return;if(this._log.info(`[CDNStreaming] handlePublished: mediaType ${e.mediaType}, roomID ${null==(t=null==e?void 0:e.room)?void 0:t.roomId}`),1===e.mediaType)return;const r=4===e.mediaType?"publish-main-stream-to-cdn":"publish-sub-stream-to-cdn",o=this._paramsForTencentCDN.get(r)||null;(null==o?void 0:o.target)&&o.isStarted&&await this.startPublishTencentCDN(o.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"publish-main-stream-to-cdn"!==e||this._room.isMainStreamPublished?!("publish-sub-stream-to-cdn"===e&&!this._room.isAuxStreamPublished)||(this._log.info("[CDNStreaming] Sub has not already published, will auto reStart after published."),!1):(this._log.info("[CDNStreaming] Main stream has not already published, will auto reStart after published."),!1)}changeDataStatus(e,t){const r=this._paramsForTencentCDN.get(e),o=__spreadValues(__spreadValues({},r),t);this._paramsForTencentCDN.set(e,o)}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;const t=e.streamId||"",r=this.generatePublishCDNStreamId(t,e.publishMode),o=this.generatePublishCDNSessionId(e.publishMode),i="publish-sub-stream-to-cdn"===e.publishMode?1:0,s={requestTime:Date.now(),sessionId:o,streamId:r,streamType:i};await this.doStartPublishTencentCDN(s,e.publishMode);const{appId:a,bizId:n,url:d}=e;if(a&&n&&d){const t=this._paramsForTencentCDN.get(e.publishMode)||this._initParamsForTencentCDN;(null==t?void 0:t.givenCDNManager)||(t.givenCDNManager=new GivenCDNManager(this._core,this._log),this._paramsForTencentCDN.set(e.publishMode,t)),await t.givenCDNManager.startPublishGivenCDN({publishMode:e.publishMode,appId:a,bizId:n,url:d,streamId:r})}}async doStartPublishTencentCDN(e,t){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);let r=0;for(;;){const o=await this._room.sendStartPublishCDN(e,!0),{code:i}=o.data;let{message:s}=o.data;if(0===i){this._log.info("[CDNStreaming] server success: start tencent cdn"),this.changeDataStatus(t,{isPublished:!0});break}if(!(-10006===i&&r<6))throw this.changeDataStatus(t,{isPublished:!1}),-102083===i&&(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: ${i} errMsg: ${s}`),new Error(`[CDNStreaming] server failed: start tencent cdn errCode: ${i} errMsg: ${s}`);this._log.warn(`[CDNStreaming] doStartPublishTencentCDN: retry...${r+1}/6, reason: ${s}`),r+=1,await new Promise((e=>setTimeout(e,500)))}}async stopPublishTencentCDN(e){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);const t=this._paramsForTencentCDN.get(e)||this._initParamsForTencentCDN;if(t.isPublished){const{target:r}=t;(null==r?void 0:r.bizId)&&r.appId&&r.url&&(null==t?void 0:t.givenCDNManager)&&await(null==t?void 0:t.givenCDNManager.stopPublishGivenCDN()),await this.doStopPublishTencentCDN(e)}this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}async doStopPublishTencentCDN(e){const t={requestTime:Date.now(),sessionId:(0,import_blueimp_md52.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)};this._log.info(`[CDNStreaming] doStopPublishTencentCDN: ${JSON.stringify(t)}`);const r=await this._room.sendStopPublishCDN(t,!0),{code:o}=r.data;let{message:i}=r.data;if(0!==o)throw-102069===o&&(this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),i=`can not stop in auto relayed-push mode ${i}`),this._log.error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${o} errMsg: ${i}`),new Error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${o} errMsg: ${i}`);this._log.info("[CDNStreaming] server success: stop tencent cdn"),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),this.reset(e)}reset(e){this.uninstallEvents(),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}generatePublishCDNStreamId(e,t){if(""===e){let e=`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(t)}`;return/^[A-Za-z\d_-]*$/.test(e)||(e=(0,import_blueimp_md52.default)(e)),`${this._room.sdkAppId}_${e}`}return e}convertPublishModeToStreamType(e){return"publish-main-stream-to-cdn"===e?"main":"aux"}generatePublishCDNSessionId(e){return(0,import_blueimp_md52.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)}},import_blueimp_md53=__toESM(require_md5(),1),PushStreamToRoom=class{constructor(e,t){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_seq"),__publicField(this,"_taskId",null),__publicField(this,"_startData",null),__publicField(this,"_updateData",null),__publicField(this,"_stopData",null),this._core=e,this._room=e.room,this._log=t,this._seq=0}async startPushStreamToRoom(e){var t,r;this._seq+=1,this._startData=__spreadValues({roomid:String(this._room.roomId),roomType:this._room.useStringRoomId?1:0,sessionId:(0,import_blueimp_md53.default)(`${this._room.roomId}_${this._room.userId}_start`),agentParam:{cdnRobotUserid:`mcu_robot_${this._room.roomId}_${this._room.userId}`}},this.getCommonParams(e)),this._log.info(`startPushStreamToRoom: ${JSON.stringify(this._startData)}`);const o=await this._room.sendStartPushStreamToRoom(this._startData),{code:i,message:s}=o.data;0===i?(this._taskId=null==(r=null==(t=o.data)?void 0:t.data)?void 0:r.taskId,this._taskId||this.reportServerError("startPushStreamToRoom",i,`can't resolve task id: ${JSON.stringify(o.data)}`),this._log.info("[CDNStreaming] server success: taskId",this._taskId)):this.reportServerError("startPushStreamToRoom",i,s)}async updatePushStreamToRoom(e){this._seq+=1,this._updateData=__spreadProps(__spreadValues({taskid:this._taskId},this.getCommonParams(e)),{enableNtpSync:!0}),this._log.info(`updatePushStreamToRoom: ${JSON.stringify(this._updateData)}`);const t=await this._room.sendUpdatePushStreamToRoom(this._updateData),{code:r,message:o}=t.data;0===r?this._log.info("server success: updatePushStreamToRoom"):this.reportServerError("updatePushStreamToRoom",r,o)}async stopPushStreamToRoom(){this._seq+=1,this._stopData={sdkappid:this._room.sdkAppId,taskid:this._taskId},this._log.info(`stopPushStreamToRoom: ${JSON.stringify(this._stopData)}`);const e=await this._room.sendStopPushStreamToRoom(this._stopData),{code:t,message:r}=e.data;0===t?this._log.info("server success: start mix"):this.reportServerError("stopPushStreamToRoom",t,r)}reportServerError(e,t,r){const o=`server failed: ${e} errCode: ${t} errMsg: ${r}`;throw this._log.error(o),new Error(o)}getPushRtcRoomParams(e){const{robotUser:t}=e.target;return t?[{roomid:String((null==t?void 0:t.roomId)||(null==t?void 0:t.strRoomId))||this._room.roomId,roomType:(null==t?void 0:t.roomId)?0:1,pushRobotUserid:null==t?void 0:t.userId}]:[]}getCommonParams(e){return{sdkappid:this._room.sdkAppId,transcode:!0,audioParam:this.getAudioParam(e),videoParam:this.getVideoParam(e),pushRtcRoomParams:this.getPushRtcRoomParams(e),sequenceNumber:this._seq}}getAudioParam(e){const{mix:t={},encoding:r={}}=e,o={audioSamplerate:r.audioSampleRate||48e3,audioBitrateKbps:r.audioBitrate||64,audioChannels:r.audioChannels||1},{audioMixUserList:i}=t;return{audioEncodeParam:o,mixAudioUsers:(null==i?void 0:i.map((e=>({roomid:String(e.roomId||e.strRoomId)||this._room.roomId,userid:e.userId,roomType:e.roomId?0:1}))))||[]}}getVideoParam(e){const{mix:t={},encoding:r={}}=e,o={videoCodec:2,videoWidth:r.videoWidth||640,videoHeight:r.videoHeight||480,videoFramerate:r.videoFramerate||15,videoGop:r.videoGOP||2,videoBitrateKbps:r.videoBitrate||800},{videoLayoutList:i}=t;return{videoEncodeParam:o,layoutParams:(null==i?void 0:i.map((e=>({userMediaStream:{userInfo:{roomid:String(e.fixedVideoUser.roomId||e.fixedVideoUser.strRoomId)||this._room.roomId,userid:e.fixedVideoUser.userId,roomType:e.fixedVideoUser.roomId?0:1},streamType:"sub"===e.fixedVideoStreamType?1:0},imageWidth:e.width||0,imageHeight:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,imageZorder:e.zOrder||1,renderMode:e.fillMode||0}))))||[],backgroundColor:t.backgroundColor||0,backgroundImageUrl:t.backgroundImage||""}}},isString=e=>"string"==typeof e;function streamIdValidate(e,t,r,o){if(!/^[A-Za-z\d_-]*$/.test(e)){const{RtcError:e,ErrorCode:t,ErrorCodeDictionary:r}=errorModule;throw new e({code:t.INVALID_PARAMETER,extraCode:r.INVALID_STREAM_ID,messageParams:{key:"streamId"}})}}function roomIdValidate(e,t,r,o){const{RtcError:i,ErrorCode:s,ErrorCodeDictionary:a}=errorModule;if(isString(e))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_INTEGER_STRING,fnName:r,messageParams:{key:"roomId"}});if(void 0!==e){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_INTEGER,fnName:r,messageParams:{key:"roomId"}})}}function strRoomIdValidate(e,t,r,o){const{RtcError:i,ErrorCode:s,ErrorCodeDictionary:a}=errorModule;if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_STRING,fnName:r,messageParams:{key:"strRoomId"}})}var notLessThanZero={type:"number",notLessThanZero:!0},UserRule={type:"object",properties:{userId:{required:!0,type:"string"},roomId:{type:["string","number"],validate:roomIdValidate},strRoomId:{type:"string",validate:strRoomIdValidate}}},TargetRule={required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn","publish-mix-stream-to-room"]},streamId:{required:!1,type:"string",validate:streamIdValidate},appId:{type:"number",allowEmpty:!1},bizId:{type:"number",allowEmpty:!1},url:{type:"string",allowEmpty:!1},robotUser:__spreadValues({},UserRule)},validate(e,t,r,o){const{publishMode:i,robotUser:s}=e;if("publish-mix-stream-to-room"===i&&!s){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter target, the value of publishMode is PublishMixStreamToRoom, robotUser is required."})}}},EncodingRule={required:!1,type:"object",properties:{videoWidth:notLessThanZero,videoHeight:notLessThanZero,videoBitrate:__spreadProps(__spreadValues({},notLessThanZero),{allowEmpty:!1}),videoFramerate:{type:"number",validate(e,t,r,o){if(e<=0||e>30){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoFramerate, the value must be between (0, 30]."})}}},videoGOP:{type:"number",validate(e,t,r,o){if(e<1||e>8){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoGOP, the value must be between [1, 8]."})}}},audioSampleRate:notLessThanZero,audioBitrate:{type:"number",validate(e,t,r,o){if(e<32||e>192){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> audioBitrate, the value must be between [32, 192]."})}}},audioChannels:{type:"number",values:[1,2]}}},MixRule={required:!1,type:"object",properties:{backgroundColor:{type:"number"},backgroundImage:{type:"string"},audioMixUserList:{type:"array",arrayItem:__spreadValues({},UserRule)},videoLayoutList:{type:"array",required:!0,arrayItem:{type:"object",properties:{fixedVideoUser:__spreadValues({},UserRule),fixedVideoStreamType:{type:"string",required:!0,values:["main","sub"]},fillMode:{type:"number",values:[0,1,2,4]},zOrder:{type:"number",required:!0,validate(e,t,r,o){if(e<1||e>15){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList -> zOrder, the value must be between [1, 15]."})}}},width:notLessThanZero,height:notLessThanZero,locationX:notLessThanZero,locationY:notLessThanZero}}}}};function startValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:__spreadValues({},TargetRule),encoding:__spreadValues({},EncodingRule),mix:__spreadValues({},MixRule)},validate(t,r,o,i){var s,a;const{publishMode:n}=t.target,{encoding:d,mix:u}=t;if("publish-mix-stream-to-cdn"===n){const{RtcError:t,ErrorCode:r,ErrorCodeDictionary:i}=e.errorModule;if(!d)throw new t({code:r.INVALID_PARAMETER,extraCode:i.INVALID_PARAMETER_REQUIRED,fnName:o,messageParams:{key:"encoding"}});if(!u)throw new t({code:r.INVALID_PARAMETER,extraCode:i.INVALID_PARAMETER_REQUIRED,fnName:o,messageParams:{key:"mix"}});if(u&&u.videoLayoutList){let o=0,i=0;const n=[];if(u.videoLayoutList.forEach(((e,t)=>{n.push(e.fixedVideoUser.userId),e.width+e.locationX>o&&(o=e.width+e.locationX),e.height+e.locationY>i&&(i=e.height+e.locationY)})),n.indexOf(e.room.userId)<0)throw new t({code:r.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList, the value must be include self."});const l=null!=(s=null==d?void 0:d.videoWidth)?s:640,h=null!=(a=null==d?void 0:d.videoHeight)?a:480;if(l<o||h<i)throw new t({code:r.INVALID_PARAMETER,message:"Invalid parameter encoding, the width and height of the mixed video must encompass all the mixed-in video streams."})}}}}}function updateValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:__spreadValues({},TargetRule),encoding:__spreadValues({},EncodingRule),mix:__spreadValues({},MixRule)}}}function stopValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:{required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn","publish-mix-stream-to-room"]}}}}}}var cdnSeq=0,_CDNStreaming=class e{constructor(e){this.core=e,__publicField(this,"_mixTranscodeManager"),__publicField(this,"_publishCDNManager"),__publicField(this,"_pushStreamToRoomManager"),__publicField(this,"_core"),__publicField(this,"_modeOptions"),__publicField(this,"seq"),__publicField(this,"_log"),cdnSeq+=1,this.seq=cdnSeq,this._log=e.log.createChild({id:`${this.getAlias()}${cdnSeq}`}),this._log.info(`[CDNStreaming] created id=${this.getAlias()}${cdnSeq}`),this._core=e,this._modeOptions=new Map,this._mixTranscodeManager=new MixTranscodeManager(e,this._log),this._publishCDNManager=new PublishCDNManager(e,this._log),this._pushStreamToRoomManager=new PushStreamToRoom(e,this._log)}getName(){return e.Name}getAlias(){return"cdn"}getValidateRule(e){switch(e){case"start":return startValidateRule(this._core);case"update":return updateValidateRule(this._core);case"stop":return stopValidateRule(this._core)}}getGroup(e){return e.target.publishMode}async start(e){return this._modeOptions.set(e.target.publishMode,e),"publish-mix-stream-to-room"===e.target.publishMode?this._pushStreamToRoomManager.startPushStreamToRoom(e):await this.doStart(e)}async update(e){const t=this._modeOptions.get(e.target.publishMode);return this._core.utils.deepMerge(t,e),"publish-mix-stream-to-room"===e.target.publishMode?this._pushStreamToRoomManager.updatePushStreamToRoom(t):await this.doStart(t)}async stop(e){switch(e.target.publishMode){case"publish-mix-stream-to-cdn":await this._mixTranscodeManager.stopMixTranscode();break;case"publish-main-stream-to-cdn":case"publish-sub-stream-to-cdn":await this._publishCDNManager.stopPublishTencentCDN(e.target.publishMode);break;case"publish-mix-stream-to-room":this._pushStreamToRoomManager.stopPushStreamToRoom()}this._modeOptions.delete(e.target.publishMode)}async doStart(e){switch(this._log.info(`[CDNStreaming] doStart: ${JSON.stringify(e)}`),e.target.publishMode){case"publish-mix-stream-to-cdn":await this._mixTranscodeManager.startMixTranscode(e);break;case"publish-main-stream-to-cdn":case"publish-sub-stream-to-cdn":await this._publishCDNManager.startPublishTencentCDN(e.target)}}};__publicField(_CDNStreaming,"TYPE",{PublishMode:{PublishMainStreamToCDN:"publish-main-stream-to-cdn",PublishSubStreamToCDN:"publish-sub-stream-to-cdn",PublishMixStreamToCDN:"publish-mix-stream-to-cdn",PublishMixStreamToRoom:"publish-mix-stream-to-room"}}),__publicField(_CDNStreaming,"Name","CDNStreaming");var CDNStreaming=_CDNStreaming,index_default=CDNStreaming;export{index_default as default};export{CDNStreaming};export const PublishMode=CDNStreaming.TYPE.PublishMode;