trtc-sdk-v5 5.13.0-beta.34 → 5.13.0-beta.36

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 (38) hide show
  1. package/assets/debug-dialog.js +1 -1
  2. package/assets/denoiser-wasm.js +17 -1
  3. package/assets/mediapipe/vision.js +2 -2
  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 +38 -129
  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/cross-room/package.json +1 -1
  12. package/plugins/custom-encryption/custom-encryption.esm.js +1 -1
  13. package/plugins/custom-encryption/custom-encryption.umd.js +1 -1
  14. package/plugins/custom-encryption/package.json +1 -1
  15. package/plugins/device-detector/package.json +1 -1
  16. package/plugins/small-stream-auto-switcher/package.json +1 -1
  17. package/plugins/video-decoder/package.json +1 -1
  18. package/plugins/video-decoder/video-decoder.esm.js +1 -1
  19. package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +1 -1
  20. package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +1 -1
  21. package/plugins/video-effect/basic-beauty/package.json +1 -1
  22. package/plugins/video-effect/beauty/package.json +1 -1
  23. package/plugins/video-effect/video-mixer/package.json +1 -1
  24. package/plugins/video-effect/virtual-background/package.json +1 -1
  25. package/plugins/video-effect/virtual-background/virtual-background.esm.d.ts +4 -10
  26. package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
  27. package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
  28. package/plugins/video-effect/watermark/package.json +1 -1
  29. package/plugins/voice-changer/package.json +1 -1
  30. package/plugins/voice-changer/voice-changer.esm.js +1 -1
  31. package/plugins/voice-changer/voice-changer.umd.js +1 -1
  32. package/trtc.esm.js +31 -31
  33. package/trtc.js +1 -1
  34. package/assets/denoiser-wasm-nosimd.js +0 -1
  35. package/plugins/chorus/chorus.esm.d.ts +0 -13
  36. package/plugins/chorus/chorus.esm.js +0 -1
  37. package/plugins/chorus/chorus.umd.js +0 -1
  38. package/plugins/chorus/package.json +0 -29
package/index.d.ts CHANGED
@@ -6,15 +6,20 @@ 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 { Chorus } from './plugins/chorus';
11
+ import { InitAudioProcessorOptions, UpdateAudioProcessorOptions } from 'trtc-js-sdk-core';
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 | typeof Chorus;
14
+ type TRTCPlugin = typeof CrossRoom | typeof CDNStreaming | typeof DeviceDetector | typeof VirtualBackground | typeof Watermark | typeof Beauty | typeof BasicBeauty | typeof CustomEncryption | typeof SmallStreamAutoSwitcher | typeof VideoMixer;
15
15
  export declare type ExperimentalAPIFunctionMap = {
16
16
  'enableAudioFrameEvent': EnableAudioFrameEventOptions;
17
+ 'resumeRemotePlayer': RemotePlayerOptions;
18
+ 'pauseRemotePlayer': RemotePlayerOptions;
17
19
  }
20
+
21
+ export interface RemotePlayerOptions { userId: string, streamType?: TRTCStreamType }
22
+
18
23
  export declare type PluginStartOptionsMap = {
19
24
  'AudioMixer': AudioMixerOptions;
20
25
  'AIDenoiser': AIDenoiserOptions;
@@ -34,7 +39,6 @@ export declare type PluginStartOptionsMap = {
34
39
 
35
40
  export declare type PluginUpdateOptionsMap = {
36
41
  'AudioMixer': UpdateAudioMixerOptions;
37
- 'AIDenoiser': UpdateDenoiserOptions;
38
42
  'CDNStreaming': CDNStreamingOptions;
39
43
  'VirtualBackground': UpdateVirtualBackgroundOptions;
40
44
  'Watermark': WatermarkOptions;
@@ -42,8 +46,7 @@ export declare type PluginUpdateOptionsMap = {
42
46
  'Beauty': UpdateBeautyOptions;
43
47
  'BasicBeauty': BasicBeautyOptions;
44
48
  'CrossRoom': UpdateCrossRoomOption;
45
- 'AudioProcessor': UpdateAudioProcessorOptions;
46
- 'Debug': UpdateDebugOptions;
49
+ 'AudioProcessor': UpdateAudioProcessorOptions;
47
50
  };
48
51
 
49
52
  export declare type PluginStopOptionsMap = {
@@ -59,7 +62,7 @@ export declare type PluginStopOptionsMap = {
59
62
  'Debug': undefined;
60
63
  'CrossRoom': StopCrossRoomOption | undefined;
61
64
  'SmallStreamAutoSwitcher': undefined;
62
- 'AudioProcessor': undefined;
65
+ 'AudioProcessor': undefined;
63
66
  };
64
67
 
65
68
  export declare class RtcError extends Error implements RTCErrorInterface {
@@ -393,10 +396,10 @@ export interface PlayoutDelay {
393
396
  }
394
397
 
395
398
  export declare interface SwitchRoomConfig {
396
- roomId?: number,
397
- strRoomId?: string;
398
- privateMapKey?: string;
399
- userSig: string;
399
+ roomId?: number,
400
+ strRoomId?: string;
401
+ privateMapKey?: string;
402
+ userSig: string;
400
403
  }
401
404
 
402
405
  export declare interface ScreenShareConfig {
@@ -450,7 +453,7 @@ export declare interface LocalAudioConfig {
450
453
  audioTrack?: MediaStreamTrack;
451
454
  captureVolume?: number;
452
455
  earMonitorVolume?: number;
453
- echoCancellation?: boolean | 'remote-only' | 'all';
456
+ echoCancellation?: boolean;
454
457
  autoGainControl?: boolean;
455
458
  noiseSuppression?: boolean;
456
459
  };
@@ -490,15 +493,6 @@ export declare const enum TRTCDeviceAction {
490
493
  Add = 'add',
491
494
  Active = 'active'
492
495
  }
493
- export declare interface PermissionOption {
494
- request?: boolean;
495
- types?: ('camera' | 'microphone')[];
496
- }
497
-
498
- export declare interface PermissionResult {
499
- camera: PermissionState | null;
500
- microphone: PermissionState | null;
501
- }
502
496
  export declare interface RTCErrorParams {
503
497
  code: number;
504
498
  extraCode?: number;
@@ -651,14 +645,6 @@ export declare interface UpdateAudioMixerOptions {
651
645
  seekFrom?: number;
652
646
  operation?: 'pause' | 'resume' | 'stop';
653
647
  }
654
- export declare enum DenoiserMode {
655
- NORMAL = 0,
656
- FAR_FIELD_REDUCTION = 1
657
- }
658
-
659
- export declare interface UpdateDenoiserOptions {
660
- mode: DenoiserMode;
661
- }
662
648
  export declare interface StopAudioMixerOptions {
663
649
  id: string;
664
650
  }
@@ -667,27 +653,8 @@ export declare interface AIDenoiserOptions {
667
653
  sdkAppId: number;
668
654
  userId: string;
669
655
  userSig: string;
670
- mode?: DenoiserMode;
671
- }
672
-
673
- export declare interface InitAudioProcessorOptions {
674
- assetsPath?: string,
675
- sdkAppId: number,
676
- userId: string,
677
- userSig: string,
678
- audioReference?: AudioSource[];
679
656
  }
680
657
 
681
- export declare interface UpdateAudioProcessorOptions {
682
- audioReference?: AudioSource[];
683
- }
684
-
685
- export declare interface UpdateDebugOptions {
686
- visible: boolean
687
- }
688
-
689
- export declare type AudioSource = HTMLAudioElement | MediaStreamAudioTrack | AudioNode;
690
-
691
658
  export declare interface TRTCStatistics {
692
659
  rtt: number;
693
660
  downLoss: number;
@@ -1215,32 +1182,6 @@ export declare const TRTCEvent: {
1215
1182
  * })
1216
1183
  */
1217
1184
  readonly FIRST_VIDEO_FRAME: 'first-video-frame';
1218
-
1219
- /**
1220
- * @since v5.13.0
1221
- * @description Notification event for device permission changes.
1222
- * @default 'permission-state-change'
1223
- * @memberof module:EVENT
1224
- * @example
1225
- * trtc.on(TRTC.EVENT.PERMISSION_STATE_CHANGE, event => {
1226
- * console.log(event.camera, event.microphone); // 'granted' | 'denied' | 'prompt' | null. null means the permission is not supported query.
1227
- * });
1228
- */
1229
- readonly PERMISSION_STATE_CHANGE: 'permission-state-change';
1230
- /**
1231
- * @since v5.13.0
1232
- * @description Video size changed event
1233
- * @default 'video-size-changed'
1234
- * @memberof module:EVENT
1235
- * @example
1236
- * trtc.on(TRTC.EVENT.VIDEO_SIZE_CHANGED, event => {
1237
- * // event.newHeight: video height.
1238
- * // event.newWidth: video width.
1239
- * // event.streamType: video stream type.
1240
- * // 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.
1241
- * })
1242
- */
1243
- readonly VIDEO_SIZE_CHANGED: 'video-size-changed'
1244
1185
  };
1245
1186
  export declare interface TRTCEventTypes {
1246
1187
  [TRTCEvent.ERROR]: [RtcError];
@@ -1327,22 +1268,6 @@ export declare interface TRTCEventTypes {
1327
1268
  sourceTrack: MediaStreamTrack;
1328
1269
  }];
1329
1270
  [TRTCEvent.CUSTOM_MESSAGE]: [CustomMessage];
1330
- [TRTCEvent.PERMISSION_STATE_CHANGE]: [{
1331
- camera: PermissionState;
1332
- microphone: PermissionState;
1333
- }];
1334
- [TRTCEvent.VIDEO_SIZE_CHANGED]: [{
1335
- newWidth: number;
1336
- newHeight: number;
1337
- streamType: TRTCStreamType;
1338
- userId: string;
1339
- }];
1340
- [TRTCEvent.FIRST_VIDEO_FRAME]: [{
1341
- userId: string;
1342
- streamType: TRTCStreamType;
1343
- width: number;
1344
- height: number;
1345
- }];
1346
1271
  }
1347
1272
 
1348
1273
  export declare interface CustomMessageData {
@@ -1502,10 +1427,10 @@ export declare class TRTC {
1502
1427
  * await trtc.switchRole(TRTC.TYPE.ROLE_ANCHOR, { privateMapKey: 'your new privateMapKey' });
1503
1428
  */
1504
1429
  switchRole(role: UserRole, option?: {
1505
- privateMapKey?: string;
1506
- latencyLevel?: number;
1507
- }): Promise<void>;
1508
- /**
1430
+ privateMapKey?: string;
1431
+ latencyLevel?: number;
1432
+ }): Promise<void>;
1433
+ /**
1509
1434
  * Switch a video call room.<br>
1510
1435
  * - 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.
1511
1436
  * - [Contact us](https://trtc.io/contact) to enable this API.
@@ -1541,25 +1466,25 @@ export declare class TRTC {
1541
1466
  * roomId: 9999
1542
1467
  * });
1543
1468
  */
1544
- switchRoom(params: SwitchRoomConfig): Promise<void>;
1545
- /**
1546
- * Destroy the TRTC instance <br/>
1547
- *
1548
- * 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.
1549
- *
1550
- * Note:
1551
- * - The trtc instance after destruction cannot be used again.
1552
- * - 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.
1553
- *
1554
- * @example
1555
- * // When the call is over
1556
- * await trtc.exitRoom();
1557
- * // If the trtc is no longer needed, destroy the trtc and release the reference.
1558
- * trtc.destroy();
1559
- * trtc = null;
1560
- * @throws {@link module:ERROR_CODE.OPERATION_FAILED OPERATION_FAILED}
1561
- * @memberof TRTC
1562
- */
1469
+ switchRoom(params: SwitchRoomConfig): Promise<void>;
1470
+ /**
1471
+ * Destroy the TRTC instance <br/>
1472
+ *
1473
+ * 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.
1474
+ *
1475
+ * Note:
1476
+ * - The trtc instance after destruction cannot be used again.
1477
+ * - 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.
1478
+ *
1479
+ * @example
1480
+ * // When the call is over
1481
+ * await trtc.exitRoom();
1482
+ * // If the trtc is no longer needed, destroy the trtc and release the reference.
1483
+ * trtc.destroy();
1484
+ * trtc = null;
1485
+ * @throws {@link module:ERROR_CODE.OPERATION_FAILED OPERATION_FAILED}
1486
+ * @memberof TRTC
1487
+ */
1563
1488
  destroy(): void;
1564
1489
  /**
1565
1490
  * Start collecting audio from the local microphone and publish it to the current room.
@@ -2273,22 +2198,6 @@ export declare class TRTC {
2273
2198
  * | checkResult.detail.isVp8DecodeSupported | boolean | Whether the current browser supports VP8 decoding for downlink |
2274
2199
  */
2275
2200
  static isSupported(): Promise<any>;
2276
-
2277
- /**
2278
- * Get the permission state of the camera and microphone. Since v5.13.0+.
2279
- * @param {PermissionOption} option
2280
- * @param {boolean} [option.request=true] Whether to request permission to use the camera and microphone.
2281
- * @param {string[]} [option.types=['camera', 'microphone']] The types of permission to request.
2282
- * @returns {Promise<PermissionResult>} Promise returns the permission state of the camera and microphone
2283
- * @example
2284
- * const { camera, microphone } = await TRTC.getPermissions({
2285
- * request: true, // if true, will request permission to use the camera and microphone.
2286
- * types: ['camera', 'microphone']
2287
- * });
2288
- * console.log(camera, microphone); // 'granted' | 'denied' | 'prompt' | null. null means the permission is not supported query.
2289
- */
2290
- static getPermissions(option: PermissionOption): Promise<PermissionResult>;
2291
-
2292
2201
  /**
2293
2202
  * Returns the list of camera devices
2294
2203
  * <br>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trtc-sdk-v5",
3
- "version": "5.13.0-beta.34",
3
+ "version": "5.13.0-beta.36",
4
4
  "description": "Tencent Cloud RTC SDK for Web",
5
5
  "main": "trtc.js",
6
6
  "types": "index.d.ts",
@@ -1 +1 @@
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;this._log.info(`[CDNStreaming] handlePublished: mediaType ${e.mediaType}, roomID ${null==(t=null==e?void 0:e.room)?void 0:t.roomId}`);const r="main"===e.streamType?"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;
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;