trtc-sdk-v5 5.13.0-beta.22 → 5.13.0-beta.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/assets/debug-dialog.js +1 -1
  2. package/assets/denoiser-wasm-nosimd.js +1 -0
  3. package/assets/denoiser-wasm.js +1 -17
  4. package/assets/mediapipe/vision_wasm_internal.js.gz +0 -0
  5. package/assets/mediapipe/vision_wasm_nosimd_internal.js.gz +0 -0
  6. package/index.d.ts +128 -34
  7. package/package.json +1 -1
  8. package/plugins/cdn-streaming/cdn-streaming.esm.js +1 -1
  9. package/plugins/cdn-streaming/cdn-streaming.umd.js +1 -1
  10. package/plugins/cdn-streaming/package.json +1 -1
  11. package/plugins/chorus/chorus.esm.d.ts +13 -0
  12. package/plugins/chorus/chorus.esm.js +1 -0
  13. package/plugins/chorus/chorus.umd.js +1 -0
  14. package/plugins/chorus/package.json +29 -0
  15. package/plugins/cross-room/package.json +1 -1
  16. package/plugins/custom-encryption/custom-encryption.esm.js +1 -1
  17. package/plugins/custom-encryption/custom-encryption.umd.js +1 -1
  18. package/plugins/custom-encryption/package.json +1 -1
  19. package/plugins/device-detector/package.json +1 -1
  20. package/plugins/small-stream-auto-switcher/package.json +1 -1
  21. package/plugins/video-decoder/package.json +1 -1
  22. package/plugins/video-decoder/video-decoder.esm.js +1 -1
  23. package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +1 -1
  24. package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +1 -1
  25. package/plugins/video-effect/basic-beauty/package.json +1 -1
  26. package/plugins/video-effect/beauty/package.json +1 -1
  27. package/plugins/video-effect/video-mixer/package.json +1 -1
  28. package/plugins/video-effect/virtual-background/package.json +1 -1
  29. package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
  30. package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
  31. package/plugins/video-effect/watermark/package.json +1 -1
  32. package/plugins/voice-changer/package.json +1 -1
  33. package/trtc.esm.js +31 -31
  34. package/trtc.js +1 -1
package/index.d.ts CHANGED
@@ -6,16 +6,14 @@ import { Beauty, BeautyOptions, UpdateBeautyOptions } from './plugins/video-effe
6
6
  import { BasicBeauty, BasicBeautyOptions } from './plugins/video-effect/basic-beauty';
7
7
  import { CrossRoom, StartCrossRoomOption, UpdateCrossRoomOption, StopCrossRoomOption } from './plugins/cross-room';
8
8
  import { CustomEncryption, EncryptionOptions } from './plugins/custom-encryption';
9
- import { VideoMixerOptions, UpdateVideoMixerOptions, VideoMixer} from './plugins/video-effect/video-mixer'
9
+ import { VideoMixerOptions, UpdateVideoMixerOptions, VideoMixer } from './plugins/video-effect/video-mixer'
10
10
  import { SmallStreamAutoSwitcher, SmallStreamAutoSwitcherOptions } from './plugins/small-stream-auto-switcher';
11
- import { InitAudioProcessorOptions, UpdateAudioProcessorOptions } from 'trtc-js-sdk-core';
11
+ import { Chorus } from './plugins/chorus';
12
12
 
13
13
  export { CDNStreamingOptions, DeviceDetectorOptions, VirtualBackgroundOptions, UpdateVirtualBackgroundOptions, WatermarkOptions, BeautyOptions, UpdateBeautyOptions, BasicBeautyOptions, StartCrossRoomOption, UpdateCrossRoomOption, StopCrossRoomOption, SmallStreamAutoSwitcherOptions, VideoMixerOptions, UpdateVideoMixerOptions };
14
- type TRTCPlugin = typeof CrossRoom | typeof CDNStreaming | typeof DeviceDetector | typeof VirtualBackground | typeof Watermark | typeof Beauty | typeof BasicBeauty | typeof CustomEncryption | typeof SmallStreamAutoSwitcher | typeof VideoMixer;
14
+ type TRTCPlugin = typeof CrossRoom | typeof CDNStreaming | typeof DeviceDetector | typeof VirtualBackground | typeof Watermark | typeof Beauty | typeof BasicBeauty | typeof CustomEncryption | typeof SmallStreamAutoSwitcher | typeof VideoMixer | typeof Chorus;
15
15
  export declare type ExperimentalAPIFunctionMap = {
16
16
  'enableAudioFrameEvent': EnableAudioFrameEventOptions;
17
- 'resumeRemotePlayer': { userId: string, streamType: TRTCStreamType };
18
- 'pauseRemotePlayer': { userId: string, streamType: TRTCStreamType };
19
17
  }
20
18
  export declare type PluginStartOptionsMap = {
21
19
  'AudioMixer': AudioMixerOptions;
@@ -36,6 +34,7 @@ export declare type PluginStartOptionsMap = {
36
34
 
37
35
  export declare type PluginUpdateOptionsMap = {
38
36
  'AudioMixer': UpdateAudioMixerOptions;
37
+ 'AIDenoiser': UpdateDenoiserOptions;
39
38
  'CDNStreaming': CDNStreamingOptions;
40
39
  'VirtualBackground': UpdateVirtualBackgroundOptions;
41
40
  'Watermark': WatermarkOptions;
@@ -43,7 +42,8 @@ export declare type PluginUpdateOptionsMap = {
43
42
  'Beauty': UpdateBeautyOptions;
44
43
  'BasicBeauty': BasicBeautyOptions;
45
44
  'CrossRoom': UpdateCrossRoomOption;
46
- 'AudioProcessor': UpdateAudioProcessorOptions;
45
+ 'AudioProcessor': UpdateAudioProcessorOptions;
46
+ 'Debug': UpdateDebugOptions;
47
47
  };
48
48
 
49
49
  export declare type PluginStopOptionsMap = {
@@ -59,7 +59,7 @@ export declare type PluginStopOptionsMap = {
59
59
  'Debug': undefined;
60
60
  'CrossRoom': StopCrossRoomOption | undefined;
61
61
  'SmallStreamAutoSwitcher': undefined;
62
- 'AudioProcessor': undefined;
62
+ 'AudioProcessor': undefined;
63
63
  };
64
64
 
65
65
  export declare class RtcError extends Error implements RTCErrorInterface {
@@ -392,10 +392,10 @@ export interface PlayoutDelay {
392
392
  }
393
393
 
394
394
  export declare interface SwitchRoomConfig {
395
- roomId?: number,
396
- strRoomId?: string;
397
- privateMapKey?: string;
398
- userSig: string;
395
+ roomId?: number,
396
+ strRoomId?: string;
397
+ privateMapKey?: string;
398
+ userSig: string;
399
399
  }
400
400
 
401
401
  export declare interface ScreenShareConfig {
@@ -489,6 +489,15 @@ export declare const enum TRTCDeviceAction {
489
489
  Add = 'add',
490
490
  Active = 'active'
491
491
  }
492
+ export declare interface PermissionOption {
493
+ request?: boolean;
494
+ types?: ('camera' | 'microphone')[];
495
+ }
496
+
497
+ export declare interface PermissionResult {
498
+ camera: PermissionState | null;
499
+ microphone: PermissionState | null;
500
+ }
492
501
  export declare interface RTCErrorParams {
493
502
  code: number;
494
503
  extraCode?: number;
@@ -641,6 +650,14 @@ export declare interface UpdateAudioMixerOptions {
641
650
  seekFrom?: number;
642
651
  operation?: 'pause' | 'resume' | 'stop';
643
652
  }
653
+ export declare enum DenoiserMode {
654
+ NORMAL = 0,
655
+ FAR_FIELD_REDUCTION = 1
656
+ }
657
+
658
+ export declare interface UpdateDenoiserOptions {
659
+ mode: DenoiserMode;
660
+ }
644
661
  export declare interface StopAudioMixerOptions {
645
662
  id: string;
646
663
  }
@@ -649,8 +666,27 @@ export declare interface AIDenoiserOptions {
649
666
  sdkAppId: number;
650
667
  userId: string;
651
668
  userSig: string;
669
+ mode?: DenoiserMode;
670
+ }
671
+
672
+ export declare interface InitAudioProcessorOptions {
673
+ assetsPath?: string,
674
+ sdkAppId: number,
675
+ userId: string,
676
+ userSig: string,
677
+ audioReference?: AudioSource[];
652
678
  }
653
679
 
680
+ export declare interface UpdateAudioProcessorOptions {
681
+ audioReference?: AudioSource[];
682
+ }
683
+
684
+ export declare interface UpdateDebugOptions {
685
+ visible: boolean
686
+ }
687
+
688
+ export declare type AudioSource = HTMLAudioElement | MediaStreamAudioTrack | AudioNode;
689
+
654
690
  export declare interface TRTCStatistics {
655
691
  rtt: number;
656
692
  downLoss: number;
@@ -1178,6 +1214,32 @@ export declare const TRTCEvent: {
1178
1214
  * })
1179
1215
  */
1180
1216
  readonly FIRST_VIDEO_FRAME: 'first-video-frame';
1217
+
1218
+ /**
1219
+ * @since v5.13.0
1220
+ * @description Notification event for device permission changes.
1221
+ * @default 'permission-state-change'
1222
+ * @memberof module:EVENT
1223
+ * @example
1224
+ * trtc.on(TRTC.EVENT.PERMISSION_STATE_CHANGE, event => {
1225
+ * console.log(event.camera, event.microphone); // 'granted' | 'denied' | 'prompt' | null. null means the permission is not supported query.
1226
+ * });
1227
+ */
1228
+ readonly PERMISSION_STATE_CHANGE: 'permission-state-change';
1229
+ /**
1230
+ * @since v5.13.0
1231
+ * @description Video size changed event
1232
+ * @default 'video-size-changed'
1233
+ * @memberof module:EVENT
1234
+ * @example
1235
+ * trtc.on(TRTC.EVENT.VIDEO_SIZE_CHANGED, event => {
1236
+ * // event.newHeight: video height.
1237
+ * // event.newWidth: video width.
1238
+ * // event.streamType: video stream type.
1239
+ * // event.userId: The user ID of the local or a remote user. If it is empty, it indicates that video is the local video and the local user has not entered the room; if it is not empty, it indicates that video is remote video or local user enter room already.
1240
+ * })
1241
+ */
1242
+ readonly VIDEO_SIZE_CHANGED: 'video-size-changed'
1181
1243
  };
1182
1244
  export declare interface TRTCEventTypes {
1183
1245
  [TRTCEvent.ERROR]: [RtcError];
@@ -1264,6 +1326,22 @@ export declare interface TRTCEventTypes {
1264
1326
  sourceTrack: MediaStreamTrack;
1265
1327
  }];
1266
1328
  [TRTCEvent.CUSTOM_MESSAGE]: [CustomMessage];
1329
+ [TRTCEvent.PERMISSION_STATE_CHANGE]: [{
1330
+ camera: PermissionState;
1331
+ microphone: PermissionState;
1332
+ }];
1333
+ [TRTCEvent.VIDEO_SIZE_CHANGED]: [{
1334
+ newWidth: number;
1335
+ newHeight: number;
1336
+ streamType: TRTCStreamType;
1337
+ userId: string;
1338
+ }];
1339
+ [TRTCEvent.FIRST_VIDEO_FRAME]: [{
1340
+ userId: string;
1341
+ streamType: TRTCStreamType;
1342
+ width: number;
1343
+ height: number;
1344
+ }];
1267
1345
  }
1268
1346
 
1269
1347
  export declare interface CustomMessageData {
@@ -1423,10 +1501,10 @@ export declare class TRTC {
1423
1501
  * await trtc.switchRole(TRTC.TYPE.ROLE_ANCHOR, { privateMapKey: 'your new privateMapKey' });
1424
1502
  */
1425
1503
  switchRole(role: UserRole, option?: {
1426
- privateMapKey?: string;
1427
- latencyLevel?: number;
1428
- }): Promise<void>;
1429
- /**
1504
+ privateMapKey?: string;
1505
+ latencyLevel?: number;
1506
+ }): Promise<void>;
1507
+ /**
1430
1508
  * Switch a video call room.<br>
1431
1509
  * - Switch the video call room that the audience is watching in live scene. It is faster than exit old room and then entering the new room, and can optimize the opening time in live broadcast and other scenarios.
1432
1510
  * - [Contact us](https://trtc.io/contact) to enable this API.
@@ -1462,25 +1540,25 @@ export declare class TRTC {
1462
1540
  * roomId: 9999
1463
1541
  * });
1464
1542
  */
1465
- switchRoom(params: SwitchRoomConfig): Promise<void>;
1466
- /**
1467
- * Destroy the TRTC instance <br/>
1468
- *
1469
- * After exiting the room, if the business side no longer needs to use trtc, you need to call this interface to destroy the trtc instance in time and release related resources.
1470
- *
1471
- * Note:
1472
- * - The trtc instance after destruction cannot be used again.
1473
- * - If you have entered the room, you need to call the {@link TRTC#exitRoom TRTC.exitRoom} interface to exit the room successfully before calling this interface to destroy trtc.
1474
- *
1475
- * @example
1476
- * // When the call is over
1477
- * await trtc.exitRoom();
1478
- * // If the trtc is no longer needed, destroy the trtc and release the reference.
1479
- * trtc.destroy();
1480
- * trtc = null;
1481
- * @throws {@link module:ERROR_CODE.OPERATION_FAILED OPERATION_FAILED}
1482
- * @memberof TRTC
1483
- */
1543
+ switchRoom(params: SwitchRoomConfig): Promise<void>;
1544
+ /**
1545
+ * Destroy the TRTC instance <br/>
1546
+ *
1547
+ * After exiting the room, if the business side no longer needs to use trtc, you need to call this interface to destroy the trtc instance in time and release related resources.
1548
+ *
1549
+ * Note:
1550
+ * - The trtc instance after destruction cannot be used again.
1551
+ * - If you have entered the room, you need to call the {@link TRTC#exitRoom TRTC.exitRoom} interface to exit the room successfully before calling this interface to destroy trtc.
1552
+ *
1553
+ * @example
1554
+ * // When the call is over
1555
+ * await trtc.exitRoom();
1556
+ * // If the trtc is no longer needed, destroy the trtc and release the reference.
1557
+ * trtc.destroy();
1558
+ * trtc = null;
1559
+ * @throws {@link module:ERROR_CODE.OPERATION_FAILED OPERATION_FAILED}
1560
+ * @memberof TRTC
1561
+ */
1484
1562
  destroy(): void;
1485
1563
  /**
1486
1564
  * Start collecting audio from the local microphone and publish it to the current room.
@@ -2194,6 +2272,22 @@ export declare class TRTC {
2194
2272
  * | checkResult.detail.isVp8DecodeSupported | boolean | Whether the current browser supports VP8 decoding for downlink |
2195
2273
  */
2196
2274
  static isSupported(): Promise<any>;
2275
+
2276
+ /**
2277
+ * Get the permission state of the camera and microphone. Since v5.13.0+.
2278
+ * @param {PermissionOption} option
2279
+ * @param {boolean} [option.request=true] Whether to request permission to use the camera and microphone.
2280
+ * @param {string[]} [option.types=['camera', 'microphone']] The types of permission to request.
2281
+ * @returns {Promise<PermissionResult>} Promise returns the permission state of the camera and microphone
2282
+ * @example
2283
+ * const { camera, microphone } = await TRTC.getPermissions({
2284
+ * request: true, // if true, will request permission to use the camera and microphone.
2285
+ * types: ['camera', 'microphone']
2286
+ * });
2287
+ * console.log(camera, microphone); // 'granted' | 'denied' | 'prompt' | null. null means the permission is not supported query.
2288
+ */
2289
+ static getPermissions(option: PermissionOption): Promise<PermissionResult>;
2290
+
2197
2291
  /**
2198
2292
  * Returns the list of camera devices
2199
2293
  * <br>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trtc-sdk-v5",
3
- "version": "5.13.0-beta.22",
3
+ "version": "5.13.0-beta.24",
4
4
  "description": "Tencent Cloud RTC SDK for Web",
5
5
  "main": "trtc.js",
6
6
  "types": "index.d.ts",
@@ -1 +1 @@
1
- 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;
1
+ var __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,c=-1732584194,p=271733878;for(o=0;o<e.length;o+=16)d=m,u=_,l=c,h=p,m=i(m,_,c,p,e[o],7,-680876936),p=i(p,m,_,c,e[o+1],12,-389564586),c=i(c,p,m,_,e[o+2],17,606105819),_=i(_,c,p,m,e[o+3],22,-1044525330),m=i(m,_,c,p,e[o+4],7,-176418897),p=i(p,m,_,c,e[o+5],12,1200080426),c=i(c,p,m,_,e[o+6],17,-1473231341),_=i(_,c,p,m,e[o+7],22,-45705983),m=i(m,_,c,p,e[o+8],7,1770035416),p=i(p,m,_,c,e[o+9],12,-1958414417),c=i(c,p,m,_,e[o+10],17,-42063),_=i(_,c,p,m,e[o+11],22,-1990404162),m=i(m,_,c,p,e[o+12],7,1804603682),p=i(p,m,_,c,e[o+13],12,-40341101),c=i(c,p,m,_,e[o+14],17,-1502002290),m=s(m,_=i(_,c,p,m,e[o+15],22,1236535329),c,p,e[o+1],5,-165796510),p=s(p,m,_,c,e[o+6],9,-1069501632),c=s(c,p,m,_,e[o+11],14,643717713),_=s(_,c,p,m,e[o],20,-373897302),m=s(m,_,c,p,e[o+5],5,-701558691),p=s(p,m,_,c,e[o+10],9,38016083),c=s(c,p,m,_,e[o+15],14,-660478335),_=s(_,c,p,m,e[o+4],20,-405537848),m=s(m,_,c,p,e[o+9],5,568446438),p=s(p,m,_,c,e[o+14],9,-1019803690),c=s(c,p,m,_,e[o+3],14,-187363961),_=s(_,c,p,m,e[o+8],20,1163531501),m=s(m,_,c,p,e[o+13],5,-1444681467),p=s(p,m,_,c,e[o+2],9,-51403784),c=s(c,p,m,_,e[o+7],14,1735328473),m=a(m,_=s(_,c,p,m,e[o+12],20,-1926607734),c,p,e[o+5],4,-378558),p=a(p,m,_,c,e[o+8],11,-2022574463),c=a(c,p,m,_,e[o+11],16,1839030562),_=a(_,c,p,m,e[o+14],23,-35309556),m=a(m,_,c,p,e[o+1],4,-1530992060),p=a(p,m,_,c,e[o+4],11,1272893353),c=a(c,p,m,_,e[o+7],16,-155497632),_=a(_,c,p,m,e[o+10],23,-1094730640),m=a(m,_,c,p,e[o+13],4,681279174),p=a(p,m,_,c,e[o],11,-358537222),c=a(c,p,m,_,e[o+3],16,-722521979),_=a(_,c,p,m,e[o+6],23,76029189),m=a(m,_,c,p,e[o+9],4,-640364487),p=a(p,m,_,c,e[o+12],11,-421815835),c=a(c,p,m,_,e[o+15],16,530742520),m=n(m,_=a(_,c,p,m,e[o+2],23,-995338651),c,p,e[o],6,-198630844),p=n(p,m,_,c,e[o+7],10,1126891415),c=n(c,p,m,_,e[o+14],15,-1416354905),_=n(_,c,p,m,e[o+5],21,-57434055),m=n(m,_,c,p,e[o+12],6,1700485571),p=n(p,m,_,c,e[o+3],10,-1894986606),c=n(c,p,m,_,e[o+10],15,-1051523),_=n(_,c,p,m,e[o+1],21,-2054922799),m=n(m,_,c,p,e[o+8],6,1873313359),p=n(p,m,_,c,e[o+15],10,-30611744),c=n(c,p,m,_,e[o+6],15,-1560198380),_=n(_,c,p,m,e[o+13],21,1309151649),m=n(m,_,c,p,e[o+4],6,-145523070),p=n(p,m,_,c,e[o+11],10,-1120210379),c=n(c,p,m,_,e[o+2],15,718787259),_=n(_,c,p,m,e[o+9],21,-343485551),m=r(m,d),_=r(_,u),c=r(c,l),p=r(p,h);return[m,_,c,p]}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 c(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 p(e,t,r){return t?r?c(t,e):h(c(t,e)):r?_(e):h(_(e))}"function"==typeof define&&define.amd?define((function(){return p})):"object"==typeof t&&t.exports?t.exports=p:e.md5=p}(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 e{constructor(t,r){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_seq"),__publicField(this,"_taskId"),__publicField(this,"_startData",null),__publicField(this,"_updateData",null),__publicField(this,"_stopData",null),this._core=t,this._room=t.room,this._log=r,this._seq=0;const o=localStorage.getItem(e.TASK_ID_KEY);o&&(this._taskId=o)}async startPushStreamToRoom(t){var r,o;try{this._taskId&&await this.stopPushStreamToRoom()}catch(e){this._log.warn("stopPushStreamToRoom prev taskId failed",e)}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(t)),this._log.info(`startPushStreamToRoom: ${JSON.stringify(this._startData)}`);const i=await this._room.sendStartPushStreamToRoom(this._startData),{code:s,message:a}=i.data;0===s?(this._taskId=null==(o=null==(r=i.data)?void 0:r.data)?void 0:o.taskId,this._taskId?localStorage.setItem(e.TASK_ID_KEY,this._taskId):this.reportServerError("startPushStreamToRoom",s,`can't resolve task id: ${JSON.stringify(i.data)}`),this._log.info("[CDNStreaming] server success: taskId",this._taskId)):this.reportServerError("startPushStreamToRoom",s,a)}async updatePushStreamToRoom(e){var t;this._seq+=1,this._updateData=__spreadValues({taskid:this._taskId},this.getCommonParams(e)),this._core.utils.isBoolean(null==(t=e.mix)?void 0:t.enableNtpSync)&&(this._updateData.enableNtpSync=e.mix.enableNtpSync),this._log.info(`updatePushStreamToRoom: ${JSON.stringify(this._updateData)}`);const r=await this._room.sendUpdatePushStreamToRoom(this._updateData),{code:o,message:i}=r.data;0===o?this._log.info("server success: updatePushStreamToRoom"):this.reportServerError("updatePushStreamToRoom",o,i)}async stopPushStreamToRoom(){if(!this._taskId)return;this._seq+=1,this._stopData={sdkappid:this._room.sdkAppId,taskid:this._taskId},this._log.info(`stopPushStreamToRoom: ${JSON.stringify(this._stopData)}`);const t=await this._room.sendStopPushStreamToRoom(this._stopData),{code:r,message:o}=t.data;0===r?(delete this._taskId,localStorage.removeItem(e.TASK_ID_KEY),this._log.info("server success: start mix")):this.reportServerError("stopPushStreamToRoom",r,o)}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){var t;return{sdkappid:this._room.sdkAppId,transcode:!0,audioParam:this.getAudioParam(e),videoParam:this.getVideoParam(e),pushRtcRoomParams:this.getPushRtcRoomParams(e),sequenceNumber:this._seq,enableNtpSync:(null==(t=e.mix)?void 0:t.enableNtpSync)||!1}}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||""}}};__publicField(_PushStreamToRoom,"TASK_ID_KEY","trtc_mix_to_room_taskId");var errorModule,PushStreamToRoom=_PushStreamToRoom,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":await 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;