@hysc/meeting 10.0.67 → 10.1.0
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.
- package/dist/index.d.mts +2387 -0
- package/dist/index.d.ts +2387 -0
- package/dist/index.js +5 -0
- package/dist/index.mjs +5 -0
- package/package.json +16 -15
- package/esm/BMChat/BMChatVM.d.ts +0 -24
- package/esm/BMChat/BMMessageInfo.d.ts +0 -31
- package/esm/BMRoom/BMLiveVM.d.ts +0 -35
- package/esm/BMRoom/BMRoom.d.ts +0 -638
- package/esm/BMRoom/BMRoomInfo.d.ts +0 -189
- package/esm/BMRoom/BMRoomVM.d.ts +0 -284
- package/esm/BMRoom/RoomEvent.d.ts +0 -1
- package/esm/BMRoom/attachEvents.d.ts +0 -27
- package/esm/BMStream/BMSpeaker.d.ts +0 -44
- package/esm/BMStream/BMStreamModel.d.ts +0 -262
- package/esm/BMStream/BMStreamModelVM.d.ts +0 -235
- package/esm/BMStream/getHTMLMediaStreamOptions.d.ts +0 -35
- package/esm/BMUser/BMUser.d.ts +0 -153
- package/esm/BMUser/BMUserVM.d.ts +0 -131
- package/esm/bjy-common/function/debounce.d.ts +0 -9
- package/esm/bjy-common/function/execute.d.ts +0 -9
- package/esm/bjy-common/function/getErrorMessage.d.ts +0 -1
- package/esm/bjy-common/function/isDef.d.ts +0 -1
- package/esm/bjy-common/function/isNative.d.ts +0 -1
- package/esm/bjy-common/function/isUndef.d.ts +0 -1
- package/esm/bjy-common/function/nextTick.d.ts +0 -2
- package/esm/bjy-common/function/throttling.d.ts +0 -9
- package/esm/bjy-common/function/toNumber.d.ts +0 -1
- package/esm/bjy-common/function/toString.d.ts +0 -1
- package/esm/bjy-common/type/api.d.ts +0 -66
- package/esm/bjy-common/type/options.d.ts +0 -7
- package/esm/bjy-common/type/type.d.ts +0 -90
- package/esm/bjy-common/util/CustomEvent.d.ts +0 -30
- package/esm/bjy-common/util/Emitter.d.ts +0 -57
- package/esm/bjy-common/util/NextTask.d.ts +0 -28
- package/esm/bjy-common/util/Sleep.d.ts +0 -14
- package/esm/bjy-common/util/Timer.d.ts +0 -13
- package/esm/bjy-common/util/array.d.ts +0 -96
- package/esm/bjy-common/util/browser.d.ts +0 -6
- package/esm/bjy-common/util/constant.d.ts +0 -50
- package/esm/bjy-common/util/holder.d.ts +0 -6
- package/esm/bjy-common/util/is.d.ts +0 -49
- package/esm/bjy-common/util/keypath.d.ts +0 -41
- package/esm/bjy-common/util/logger.d.ts +0 -42
- package/esm/bjy-common/util/network.d.ts +0 -4
- package/esm/bjy-common/util/object.d.ts +0 -83
- package/esm/bjy-common/util/os.d.ts +0 -14
- package/esm/bjy-common/util/string.d.ts +0 -102
- package/esm/boom-core/src/BoomCore/BCClient/clientEventType.d.ts +0 -426
- package/esm/boom-meeting/src/BMChat/BMChatVM.d.ts +0 -26
- package/esm/boom-meeting/src/BMChat/BMMessageInfo.d.ts +0 -31
- package/esm/boom-meeting/src/BMRoom/BMLiveVM.d.ts +0 -35
- package/esm/boom-meeting/src/BMRoom/BMRoom.d.ts +0 -694
- package/esm/boom-meeting/src/BMRoom/BMRoomInfo.d.ts +0 -215
- package/esm/boom-meeting/src/BMRoom/BMRoomVM.d.ts +0 -317
- package/esm/boom-meeting/src/BMRoom/RoomEvent.d.ts +0 -1
- package/esm/boom-meeting/src/BMRoom/attachEvents.d.ts +0 -34
- package/esm/boom-meeting/src/BMStream/BMSpeaker.d.ts +0 -35
- package/esm/boom-meeting/src/BMStream/BMStreamModel.d.ts +0 -288
- package/esm/boom-meeting/src/BMStream/BMStreamModelVM.d.ts +0 -250
- package/esm/boom-meeting/src/BMStream/getHTMLMediaStreamOptions.d.ts +0 -35
- package/esm/boom-meeting/src/BMStream/sortStream.d.ts +0 -30
- package/esm/boom-meeting/src/BMUser/BMUser.d.ts +0 -156
- package/esm/boom-meeting/src/BMUser/BMUserVM.d.ts +0 -177
- package/esm/boom-meeting/src/EventHandler.d.ts +0 -20
- package/esm/boom-meeting/src/SingletonQueue/SingletonQueue.d.ts +0 -25
- package/esm/boom-meeting/src/audioPlay/AudioPlay.d.ts +0 -24
- package/esm/boom-meeting/src/bjy-common/function/debounce.d.ts +0 -9
- package/esm/boom-meeting/src/bjy-common/function/execute.d.ts +0 -9
- package/esm/boom-meeting/src/bjy-common/function/getErrorMessage.d.ts +0 -1
- package/esm/boom-meeting/src/bjy-common/function/isDef.d.ts +0 -1
- package/esm/boom-meeting/src/bjy-common/function/isNative.d.ts +0 -1
- package/esm/boom-meeting/src/bjy-common/function/isUndef.d.ts +0 -1
- package/esm/boom-meeting/src/bjy-common/function/nextTick.d.ts +0 -2
- package/esm/boom-meeting/src/bjy-common/function/throttling.d.ts +0 -9
- package/esm/boom-meeting/src/bjy-common/function/toNumber.d.ts +0 -1
- package/esm/boom-meeting/src/bjy-common/function/toString.d.ts +0 -1
- package/esm/boom-meeting/src/bjy-common/type/api.d.ts +0 -66
- package/esm/boom-meeting/src/bjy-common/type/options.d.ts +0 -7
- package/esm/boom-meeting/src/bjy-common/type/type.d.ts +0 -90
- package/esm/boom-meeting/src/bjy-common/util/CustomEvent.d.ts +0 -30
- package/esm/boom-meeting/src/bjy-common/util/Emitter.d.ts +0 -57
- package/esm/boom-meeting/src/bjy-common/util/NextTask.d.ts +0 -28
- package/esm/boom-meeting/src/bjy-common/util/Sleep.d.ts +0 -14
- package/esm/boom-meeting/src/bjy-common/util/Timer.d.ts +0 -13
- package/esm/boom-meeting/src/bjy-common/util/array.d.ts +0 -96
- package/esm/boom-meeting/src/bjy-common/util/browser.d.ts +0 -6
- package/esm/boom-meeting/src/bjy-common/util/constant.d.ts +0 -50
- package/esm/boom-meeting/src/bjy-common/util/holder.d.ts +0 -6
- package/esm/boom-meeting/src/bjy-common/util/is.d.ts +0 -49
- package/esm/boom-meeting/src/bjy-common/util/keypath.d.ts +0 -41
- package/esm/boom-meeting/src/bjy-common/util/logger.d.ts +0 -42
- package/esm/boom-meeting/src/bjy-common/util/network.d.ts +0 -4
- package/esm/boom-meeting/src/bjy-common/util/object.d.ts +0 -83
- package/esm/boom-meeting/src/bjy-common/util/os.d.ts +0 -14
- package/esm/boom-meeting/src/bjy-common/util/string.d.ts +0 -102
- package/esm/boom-meeting/src/constants.d.ts +0 -116
- package/esm/boom-meeting/src/error/RTCError.d.ts +0 -20
- package/esm/boom-meeting/src/error/errorMap.d.ts +0 -70
- package/esm/boom-meeting/src/error/errorType.d.ts +0 -96
- package/esm/boom-meeting/src/handleEvent/attachEvents.d.ts +0 -46
- package/esm/boom-meeting/src/handleEvent/brtcNetEvent.d.ts +0 -9
- package/esm/boom-meeting/src/handleEvent/customMessageEvent.d.ts +0 -2
- package/esm/boom-meeting/src/handleEvent/handleParticipantEvent.d.ts +0 -24
- package/esm/boom-meeting/src/handleEvent/handleRoomEvent.d.ts +0 -20
- package/esm/boom-meeting/src/handleEvent/messageEvent.d.ts +0 -5
- package/esm/boom-meeting/src/handleEvent/pullUser.d.ts +0 -7
- package/esm/boom-meeting/src/handleEvent/roomErrEvent.d.ts +0 -9
- package/esm/boom-meeting/src/handleEvent/streamEvent.d.ts +0 -21
- package/esm/boom-meeting/src/logger/logger.d.ts +0 -86
- package/esm/boom-meeting/src/type/customStats.d.ts +0 -123
- package/esm/boom-meeting/src/type/index.d.ts +0 -9
- package/esm/boom-meeting/src/type/stream.d.ts +0 -15
- package/esm/boom-meeting/src/type/user.d.ts +0 -9
- package/esm/boom-meeting/src/util/PackLoss.d.ts +0 -7
- package/esm/boom-meeting/src/util/Pqueue.d.ts +0 -62
- package/esm/boom-meeting/src/util/Privileges.d.ts +0 -20
- package/esm/boom-meeting/src/util/ReportCollector.d.ts +0 -22
- package/esm/boom-meeting/src/util/Stutter.d.ts +0 -19
- package/esm/boom-meeting/src/util/Thread.d.ts +0 -12
- package/esm/boom-meeting/src/util/base64.d.ts +0 -4
- package/esm/boom-meeting/src/util/checkPermissions.d.ts +0 -1
- package/esm/boom-meeting/src/util/checkSystemRequirements.d.ts +0 -1
- package/esm/boom-meeting/src/util/constant.d.ts +0 -67
- package/esm/boom-meeting/src/util/devices.d.ts +0 -2
- package/esm/boom-meeting/src/util/emitter.d.ts +0 -42
- package/esm/boom-meeting/src/util/formatUserId.d.ts +0 -2
- package/esm/boom-meeting/src/util/is.d.ts +0 -70
- package/esm/boom-meeting/src/util/peerToPeerProbe.d.ts +0 -9
- package/esm/boom-meeting/src/util/request.d.ts +0 -45
- package/esm/boom-meeting/src/util/roomUtils.d.ts +0 -9
- package/esm/boom-meeting/src/util/sortUtils.d.ts +0 -10
- package/esm/boom-meeting/src/util/util.d.ts +0 -77
- package/esm/constants.d.ts +0 -107
- package/esm/error/RTCError.d.ts +0 -20
- package/esm/error/errorMap.d.ts +0 -70
- package/esm/error/errorType.d.ts +0 -96
- package/esm/index.d.ts +0 -2
- package/esm/index.js +0 -29
- package/esm/index.js.map +0 -7
- package/esm/logger/logger.d.ts +0 -86
- package/esm/src/BMChat/BMChatVM.d.ts +0 -26
- package/esm/src/BMChat/BMMessageInfo.d.ts +0 -31
- package/esm/src/BMRoom/BMLiveVM.d.ts +0 -35
- package/esm/src/BMRoom/BMRoom.d.ts +0 -694
- package/esm/src/BMRoom/BMRoomInfo.d.ts +0 -215
- package/esm/src/BMRoom/BMRoomVM.d.ts +0 -317
- package/esm/src/BMRoom/RoomEvent.d.ts +0 -1
- package/esm/src/BMRoom/attachEvents.d.ts +0 -34
- package/esm/src/BMStream/BMSpeaker.d.ts +0 -35
- package/esm/src/BMStream/BMStreamModel.d.ts +0 -288
- package/esm/src/BMStream/BMStreamModelVM.d.ts +0 -250
- package/esm/src/BMStream/getHTMLMediaStreamOptions.d.ts +0 -35
- package/esm/src/BMStream/sortStream.d.ts +0 -30
- package/esm/src/BMUser/BMUser.d.ts +0 -156
- package/esm/src/BMUser/BMUserVM.d.ts +0 -177
- package/esm/src/EventHandler.d.ts +0 -20
- package/esm/src/SingletonQueue/SingletonQueue.d.ts +0 -25
- package/esm/src/audioPlay/AudioPlay.d.ts +0 -24
- package/esm/src/bjy-common/function/debounce.d.ts +0 -9
- package/esm/src/bjy-common/function/execute.d.ts +0 -9
- package/esm/src/bjy-common/function/getErrorMessage.d.ts +0 -1
- package/esm/src/bjy-common/function/isDef.d.ts +0 -1
- package/esm/src/bjy-common/function/isNative.d.ts +0 -1
- package/esm/src/bjy-common/function/isUndef.d.ts +0 -1
- package/esm/src/bjy-common/function/nextTick.d.ts +0 -2
- package/esm/src/bjy-common/function/throttling.d.ts +0 -9
- package/esm/src/bjy-common/function/toNumber.d.ts +0 -1
- package/esm/src/bjy-common/function/toString.d.ts +0 -1
- package/esm/src/bjy-common/type/api.d.ts +0 -66
- package/esm/src/bjy-common/type/options.d.ts +0 -7
- package/esm/src/bjy-common/type/type.d.ts +0 -90
- package/esm/src/bjy-common/util/CustomEvent.d.ts +0 -30
- package/esm/src/bjy-common/util/Emitter.d.ts +0 -57
- package/esm/src/bjy-common/util/NextTask.d.ts +0 -28
- package/esm/src/bjy-common/util/Sleep.d.ts +0 -14
- package/esm/src/bjy-common/util/Timer.d.ts +0 -13
- package/esm/src/bjy-common/util/array.d.ts +0 -96
- package/esm/src/bjy-common/util/browser.d.ts +0 -6
- package/esm/src/bjy-common/util/constant.d.ts +0 -50
- package/esm/src/bjy-common/util/holder.d.ts +0 -6
- package/esm/src/bjy-common/util/is.d.ts +0 -49
- package/esm/src/bjy-common/util/keypath.d.ts +0 -41
- package/esm/src/bjy-common/util/logger.d.ts +0 -42
- package/esm/src/bjy-common/util/network.d.ts +0 -4
- package/esm/src/bjy-common/util/object.d.ts +0 -83
- package/esm/src/bjy-common/util/os.d.ts +0 -14
- package/esm/src/bjy-common/util/string.d.ts +0 -102
- package/esm/src/constants.d.ts +0 -116
- package/esm/src/error/RTCError.d.ts +0 -20
- package/esm/src/error/errorMap.d.ts +0 -70
- package/esm/src/error/errorType.d.ts +0 -96
- package/esm/src/handleEvent/attachEvents.d.ts +0 -46
- package/esm/src/handleEvent/brtcNetEvent.d.ts +0 -9
- package/esm/src/handleEvent/customMessageEvent.d.ts +0 -2
- package/esm/src/handleEvent/handleParticipantEvent.d.ts +0 -24
- package/esm/src/handleEvent/handleRoomEvent.d.ts +0 -20
- package/esm/src/handleEvent/messageEvent.d.ts +0 -5
- package/esm/src/handleEvent/pullUser.d.ts +0 -7
- package/esm/src/handleEvent/roomErrEvent.d.ts +0 -9
- package/esm/src/handleEvent/streamEvent.d.ts +0 -21
- package/esm/src/index.d.ts +0 -2
- package/esm/src/logger/logger.d.ts +0 -86
- package/esm/src/type/customStats.d.ts +0 -123
- package/esm/src/type/index.d.ts +0 -9
- package/esm/src/type/stream.d.ts +0 -15
- package/esm/src/type/user.d.ts +0 -9
- package/esm/src/util/PackLoss.d.ts +0 -7
- package/esm/src/util/Pqueue.d.ts +0 -62
- package/esm/src/util/Privileges.d.ts +0 -20
- package/esm/src/util/ReportCollector.d.ts +0 -22
- package/esm/src/util/Stutter.d.ts +0 -19
- package/esm/src/util/Thread.d.ts +0 -12
- package/esm/src/util/base64.d.ts +0 -4
- package/esm/src/util/checkPermissions.d.ts +0 -1
- package/esm/src/util/checkSystemRequirements.d.ts +0 -1
- package/esm/src/util/constant.d.ts +0 -67
- package/esm/src/util/devices.d.ts +0 -2
- package/esm/src/util/emitter.d.ts +0 -42
- package/esm/src/util/formatUserId.d.ts +0 -2
- package/esm/src/util/is.d.ts +0 -70
- package/esm/src/util/peerToPeerProbe.d.ts +0 -9
- package/esm/src/util/request.d.ts +0 -45
- package/esm/src/util/roomUtils.d.ts +0 -9
- package/esm/src/util/sortUtils.d.ts +0 -10
- package/esm/src/util/util.d.ts +0 -77
- package/esm/type/customStats.d.ts +0 -117
- package/esm/type/index.d.ts +0 -9
- package/esm/type/stream.d.ts +0 -17
- package/esm/type/user.d.ts +0 -9
- package/esm/util/PackLoss.d.ts +0 -7
- package/esm/util/Pqueue.d.ts +0 -61
- package/esm/util/Privileges.d.ts +0 -20
- package/esm/util/ReportCollector.d.ts +0 -22
- package/esm/util/Stutter.d.ts +0 -19
- package/esm/util/base64.d.ts +0 -4
- package/esm/util/checkPermissions.d.ts +0 -1
- package/esm/util/checkSystemRequirements.d.ts +0 -1
- package/esm/util/constant.d.ts +0 -67
- package/esm/util/devices.d.ts +0 -2
- package/esm/util/emitter.d.ts +0 -18
- package/esm/util/formatUserId.d.ts +0 -2
- package/esm/util/is.d.ts +0 -70
- package/esm/util/peerToPeerProbe.d.ts +0 -9
- package/esm/util/request.d.ts +0 -45
- package/esm/util/roomUtils.d.ts +0 -9
- package/esm/util/sortUtils.d.ts +0 -10
- package/esm/util/util.d.ts +0 -76
- package/esm/utils/BoomError.d.ts +0 -19
- package/esm/utils/ErrorTypes.d.ts +0 -139
- package/esm/utils/index.d.ts +0 -9
- package/umd/BMChat/BMChatVM.d.ts +0 -24
- package/umd/BMChat/BMMessageInfo.d.ts +0 -31
- package/umd/BMRoom/BMLiveVM.d.ts +0 -35
- package/umd/BMRoom/BMRoom.d.ts +0 -638
- package/umd/BMRoom/BMRoomInfo.d.ts +0 -189
- package/umd/BMRoom/BMRoomVM.d.ts +0 -284
- package/umd/BMRoom/RoomEvent.d.ts +0 -1
- package/umd/BMRoom/attachEvents.d.ts +0 -27
- package/umd/BMStream/BMSpeaker.d.ts +0 -44
- package/umd/BMStream/BMStreamModel.d.ts +0 -262
- package/umd/BMStream/BMStreamModelVM.d.ts +0 -235
- package/umd/BMStream/getHTMLMediaStreamOptions.d.ts +0 -35
- package/umd/BMUser/BMUser.d.ts +0 -153
- package/umd/BMUser/BMUserVM.d.ts +0 -131
- package/umd/bjy-common/function/debounce.d.ts +0 -9
- package/umd/bjy-common/function/execute.d.ts +0 -9
- package/umd/bjy-common/function/getErrorMessage.d.ts +0 -1
- package/umd/bjy-common/function/isDef.d.ts +0 -1
- package/umd/bjy-common/function/isNative.d.ts +0 -1
- package/umd/bjy-common/function/isUndef.d.ts +0 -1
- package/umd/bjy-common/function/nextTick.d.ts +0 -2
- package/umd/bjy-common/function/throttling.d.ts +0 -9
- package/umd/bjy-common/function/toNumber.d.ts +0 -1
- package/umd/bjy-common/function/toString.d.ts +0 -1
- package/umd/bjy-common/type/api.d.ts +0 -66
- package/umd/bjy-common/type/options.d.ts +0 -7
- package/umd/bjy-common/type/type.d.ts +0 -90
- package/umd/bjy-common/util/CustomEvent.d.ts +0 -30
- package/umd/bjy-common/util/Emitter.d.ts +0 -57
- package/umd/bjy-common/util/NextTask.d.ts +0 -28
- package/umd/bjy-common/util/Sleep.d.ts +0 -14
- package/umd/bjy-common/util/Timer.d.ts +0 -13
- package/umd/bjy-common/util/array.d.ts +0 -96
- package/umd/bjy-common/util/browser.d.ts +0 -6
- package/umd/bjy-common/util/constant.d.ts +0 -50
- package/umd/bjy-common/util/holder.d.ts +0 -6
- package/umd/bjy-common/util/is.d.ts +0 -49
- package/umd/bjy-common/util/keypath.d.ts +0 -41
- package/umd/bjy-common/util/logger.d.ts +0 -42
- package/umd/bjy-common/util/network.d.ts +0 -4
- package/umd/bjy-common/util/object.d.ts +0 -83
- package/umd/bjy-common/util/os.d.ts +0 -14
- package/umd/bjy-common/util/string.d.ts +0 -102
- package/umd/boom-core/src/BoomCore/BCClient/clientEventType.d.ts +0 -426
- package/umd/boom-meeting/src/BMChat/BMChatVM.d.ts +0 -26
- package/umd/boom-meeting/src/BMChat/BMMessageInfo.d.ts +0 -31
- package/umd/boom-meeting/src/BMRoom/BMLiveVM.d.ts +0 -35
- package/umd/boom-meeting/src/BMRoom/BMRoom.d.ts +0 -694
- package/umd/boom-meeting/src/BMRoom/BMRoomInfo.d.ts +0 -215
- package/umd/boom-meeting/src/BMRoom/BMRoomVM.d.ts +0 -317
- package/umd/boom-meeting/src/BMRoom/RoomEvent.d.ts +0 -1
- package/umd/boom-meeting/src/BMRoom/attachEvents.d.ts +0 -34
- package/umd/boom-meeting/src/BMStream/BMSpeaker.d.ts +0 -35
- package/umd/boom-meeting/src/BMStream/BMStreamModel.d.ts +0 -288
- package/umd/boom-meeting/src/BMStream/BMStreamModelVM.d.ts +0 -250
- package/umd/boom-meeting/src/BMStream/getHTMLMediaStreamOptions.d.ts +0 -35
- package/umd/boom-meeting/src/BMStream/sortStream.d.ts +0 -30
- package/umd/boom-meeting/src/BMUser/BMUser.d.ts +0 -156
- package/umd/boom-meeting/src/BMUser/BMUserVM.d.ts +0 -177
- package/umd/boom-meeting/src/EventHandler.d.ts +0 -20
- package/umd/boom-meeting/src/SingletonQueue/SingletonQueue.d.ts +0 -25
- package/umd/boom-meeting/src/audioPlay/AudioPlay.d.ts +0 -24
- package/umd/boom-meeting/src/bjy-common/function/debounce.d.ts +0 -9
- package/umd/boom-meeting/src/bjy-common/function/execute.d.ts +0 -9
- package/umd/boom-meeting/src/bjy-common/function/getErrorMessage.d.ts +0 -1
- package/umd/boom-meeting/src/bjy-common/function/isDef.d.ts +0 -1
- package/umd/boom-meeting/src/bjy-common/function/isNative.d.ts +0 -1
- package/umd/boom-meeting/src/bjy-common/function/isUndef.d.ts +0 -1
- package/umd/boom-meeting/src/bjy-common/function/nextTick.d.ts +0 -2
- package/umd/boom-meeting/src/bjy-common/function/throttling.d.ts +0 -9
- package/umd/boom-meeting/src/bjy-common/function/toNumber.d.ts +0 -1
- package/umd/boom-meeting/src/bjy-common/function/toString.d.ts +0 -1
- package/umd/boom-meeting/src/bjy-common/type/api.d.ts +0 -66
- package/umd/boom-meeting/src/bjy-common/type/options.d.ts +0 -7
- package/umd/boom-meeting/src/bjy-common/type/type.d.ts +0 -90
- package/umd/boom-meeting/src/bjy-common/util/CustomEvent.d.ts +0 -30
- package/umd/boom-meeting/src/bjy-common/util/Emitter.d.ts +0 -57
- package/umd/boom-meeting/src/bjy-common/util/NextTask.d.ts +0 -28
- package/umd/boom-meeting/src/bjy-common/util/Sleep.d.ts +0 -14
- package/umd/boom-meeting/src/bjy-common/util/Timer.d.ts +0 -13
- package/umd/boom-meeting/src/bjy-common/util/array.d.ts +0 -96
- package/umd/boom-meeting/src/bjy-common/util/browser.d.ts +0 -6
- package/umd/boom-meeting/src/bjy-common/util/constant.d.ts +0 -50
- package/umd/boom-meeting/src/bjy-common/util/holder.d.ts +0 -6
- package/umd/boom-meeting/src/bjy-common/util/is.d.ts +0 -49
- package/umd/boom-meeting/src/bjy-common/util/keypath.d.ts +0 -41
- package/umd/boom-meeting/src/bjy-common/util/logger.d.ts +0 -42
- package/umd/boom-meeting/src/bjy-common/util/network.d.ts +0 -4
- package/umd/boom-meeting/src/bjy-common/util/object.d.ts +0 -83
- package/umd/boom-meeting/src/bjy-common/util/os.d.ts +0 -14
- package/umd/boom-meeting/src/bjy-common/util/string.d.ts +0 -102
- package/umd/boom-meeting/src/constants.d.ts +0 -116
- package/umd/boom-meeting/src/error/RTCError.d.ts +0 -20
- package/umd/boom-meeting/src/error/errorMap.d.ts +0 -70
- package/umd/boom-meeting/src/error/errorType.d.ts +0 -96
- package/umd/boom-meeting/src/handleEvent/attachEvents.d.ts +0 -46
- package/umd/boom-meeting/src/handleEvent/brtcNetEvent.d.ts +0 -9
- package/umd/boom-meeting/src/handleEvent/customMessageEvent.d.ts +0 -2
- package/umd/boom-meeting/src/handleEvent/handleParticipantEvent.d.ts +0 -24
- package/umd/boom-meeting/src/handleEvent/handleRoomEvent.d.ts +0 -20
- package/umd/boom-meeting/src/handleEvent/messageEvent.d.ts +0 -5
- package/umd/boom-meeting/src/handleEvent/pullUser.d.ts +0 -7
- package/umd/boom-meeting/src/handleEvent/roomErrEvent.d.ts +0 -9
- package/umd/boom-meeting/src/handleEvent/streamEvent.d.ts +0 -21
- package/umd/boom-meeting/src/logger/logger.d.ts +0 -86
- package/umd/boom-meeting/src/type/customStats.d.ts +0 -123
- package/umd/boom-meeting/src/type/index.d.ts +0 -9
- package/umd/boom-meeting/src/type/stream.d.ts +0 -15
- package/umd/boom-meeting/src/type/user.d.ts +0 -9
- package/umd/boom-meeting/src/util/PackLoss.d.ts +0 -7
- package/umd/boom-meeting/src/util/Pqueue.d.ts +0 -62
- package/umd/boom-meeting/src/util/Privileges.d.ts +0 -20
- package/umd/boom-meeting/src/util/ReportCollector.d.ts +0 -22
- package/umd/boom-meeting/src/util/Stutter.d.ts +0 -19
- package/umd/boom-meeting/src/util/Thread.d.ts +0 -12
- package/umd/boom-meeting/src/util/base64.d.ts +0 -4
- package/umd/boom-meeting/src/util/checkPermissions.d.ts +0 -1
- package/umd/boom-meeting/src/util/checkSystemRequirements.d.ts +0 -1
- package/umd/boom-meeting/src/util/constant.d.ts +0 -67
- package/umd/boom-meeting/src/util/devices.d.ts +0 -2
- package/umd/boom-meeting/src/util/emitter.d.ts +0 -42
- package/umd/boom-meeting/src/util/formatUserId.d.ts +0 -2
- package/umd/boom-meeting/src/util/is.d.ts +0 -70
- package/umd/boom-meeting/src/util/peerToPeerProbe.d.ts +0 -9
- package/umd/boom-meeting/src/util/request.d.ts +0 -45
- package/umd/boom-meeting/src/util/roomUtils.d.ts +0 -9
- package/umd/boom-meeting/src/util/sortUtils.d.ts +0 -10
- package/umd/boom-meeting/src/util/util.d.ts +0 -77
- package/umd/constants.d.ts +0 -107
- package/umd/error/RTCError.d.ts +0 -20
- package/umd/error/errorMap.d.ts +0 -70
- package/umd/error/errorType.d.ts +0 -96
- package/umd/index.d.ts +0 -2
- package/umd/index.js +0 -29
- package/umd/index.js.map +0 -1
- package/umd/logger/logger.d.ts +0 -86
- package/umd/src/BMChat/BMChatVM.d.ts +0 -25
- package/umd/src/BMChat/BMMessageInfo.d.ts +0 -31
- package/umd/src/BMRoom/BMLiveVM.d.ts +0 -35
- package/umd/src/BMRoom/BMRoom.d.ts +0 -694
- package/umd/src/BMRoom/BMRoomInfo.d.ts +0 -213
- package/umd/src/BMRoom/BMRoomVM.d.ts +0 -302
- package/umd/src/BMRoom/RoomEvent.d.ts +0 -1
- package/umd/src/BMRoom/attachEvents.d.ts +0 -34
- package/umd/src/BMStream/BMSpeaker.d.ts +0 -44
- package/umd/src/BMStream/BMStreamModel.d.ts +0 -260
- package/umd/src/BMStream/BMStreamModelVM.d.ts +0 -252
- package/umd/src/BMStream/getHTMLMediaStreamOptions.d.ts +0 -35
- package/umd/src/BMUser/BMUser.d.ts +0 -156
- package/umd/src/BMUser/BMUserVM.d.ts +0 -140
- package/umd/src/EventHandler.d.ts +0 -20
- package/umd/src/bjy-common/function/debounce.d.ts +0 -9
- package/umd/src/bjy-common/function/execute.d.ts +0 -9
- package/umd/src/bjy-common/function/getErrorMessage.d.ts +0 -1
- package/umd/src/bjy-common/function/isDef.d.ts +0 -1
- package/umd/src/bjy-common/function/isNative.d.ts +0 -1
- package/umd/src/bjy-common/function/isUndef.d.ts +0 -1
- package/umd/src/bjy-common/function/nextTick.d.ts +0 -2
- package/umd/src/bjy-common/function/throttling.d.ts +0 -9
- package/umd/src/bjy-common/function/toNumber.d.ts +0 -1
- package/umd/src/bjy-common/function/toString.d.ts +0 -1
- package/umd/src/bjy-common/type/api.d.ts +0 -66
- package/umd/src/bjy-common/type/options.d.ts +0 -7
- package/umd/src/bjy-common/type/type.d.ts +0 -90
- package/umd/src/bjy-common/util/CustomEvent.d.ts +0 -30
- package/umd/src/bjy-common/util/Emitter.d.ts +0 -57
- package/umd/src/bjy-common/util/NextTask.d.ts +0 -28
- package/umd/src/bjy-common/util/Sleep.d.ts +0 -14
- package/umd/src/bjy-common/util/Timer.d.ts +0 -13
- package/umd/src/bjy-common/util/array.d.ts +0 -96
- package/umd/src/bjy-common/util/browser.d.ts +0 -6
- package/umd/src/bjy-common/util/constant.d.ts +0 -50
- package/umd/src/bjy-common/util/holder.d.ts +0 -6
- package/umd/src/bjy-common/util/is.d.ts +0 -49
- package/umd/src/bjy-common/util/keypath.d.ts +0 -41
- package/umd/src/bjy-common/util/logger.d.ts +0 -42
- package/umd/src/bjy-common/util/network.d.ts +0 -4
- package/umd/src/bjy-common/util/object.d.ts +0 -83
- package/umd/src/bjy-common/util/os.d.ts +0 -14
- package/umd/src/bjy-common/util/string.d.ts +0 -102
- package/umd/src/constants.d.ts +0 -112
- package/umd/src/error/RTCError.d.ts +0 -20
- package/umd/src/error/errorMap.d.ts +0 -70
- package/umd/src/error/errorType.d.ts +0 -96
- package/umd/src/index.d.ts +0 -2
- package/umd/src/logger/logger.d.ts +0 -86
- package/umd/src/type/customStats.d.ts +0 -118
- package/umd/src/type/index.d.ts +0 -9
- package/umd/src/type/stream.d.ts +0 -17
- package/umd/src/type/user.d.ts +0 -9
- package/umd/src/util/PackLoss.d.ts +0 -7
- package/umd/src/util/Pqueue.d.ts +0 -61
- package/umd/src/util/Privileges.d.ts +0 -20
- package/umd/src/util/ReportCollector.d.ts +0 -22
- package/umd/src/util/Stutter.d.ts +0 -19
- package/umd/src/util/base64.d.ts +0 -4
- package/umd/src/util/checkPermissions.d.ts +0 -1
- package/umd/src/util/checkSystemRequirements.d.ts +0 -1
- package/umd/src/util/constant.d.ts +0 -67
- package/umd/src/util/devices.d.ts +0 -2
- package/umd/src/util/emitter.d.ts +0 -19
- package/umd/src/util/formatUserId.d.ts +0 -2
- package/umd/src/util/is.d.ts +0 -70
- package/umd/src/util/peerToPeerProbe.d.ts +0 -9
- package/umd/src/util/request.d.ts +0 -45
- package/umd/src/util/roomUtils.d.ts +0 -9
- package/umd/src/util/sortUtils.d.ts +0 -10
- package/umd/src/util/util.d.ts +0 -77
- package/umd/type/customStats.d.ts +0 -117
- package/umd/type/index.d.ts +0 -9
- package/umd/type/stream.d.ts +0 -17
- package/umd/type/user.d.ts +0 -9
- package/umd/util/PackLoss.d.ts +0 -7
- package/umd/util/Pqueue.d.ts +0 -61
- package/umd/util/Privileges.d.ts +0 -20
- package/umd/util/ReportCollector.d.ts +0 -22
- package/umd/util/Stutter.d.ts +0 -19
- package/umd/util/base64.d.ts +0 -4
- package/umd/util/checkPermissions.d.ts +0 -1
- package/umd/util/checkSystemRequirements.d.ts +0 -1
- package/umd/util/constant.d.ts +0 -67
- package/umd/util/devices.d.ts +0 -2
- package/umd/util/emitter.d.ts +0 -18
- package/umd/util/formatUserId.d.ts +0 -2
- package/umd/util/is.d.ts +0 -70
- package/umd/util/peerToPeerProbe.d.ts +0 -9
- package/umd/util/request.d.ts +0 -45
- package/umd/util/roomUtils.d.ts +0 -9
- package/umd/util/sortUtils.d.ts +0 -10
- package/umd/util/util.d.ts +0 -76
- package/umd/utils/BoomError.d.ts +0 -19
- package/umd/utils/ErrorTypes.d.ts +0 -139
- package/umd/utils/index.d.ts +0 -9
package/esm/index.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function __awaiter$2(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}function __values(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],r=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,n,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function __spreadArray(e,t,i){if(i||2===arguments.length)for(var r,n=0,s=t.length;n<s;n++)!r&&n in t||(r||(r=Array.prototype.slice.call(t,0,n)),r[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))}var global$3="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout$2(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout$2(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout$2=defaultSetTimout$2,cachedClearTimeout$2=defaultClearTimeout$2;function runTimeout$2(e){if(cachedSetTimeout$2===setTimeout)return setTimeout(e,0);if((cachedSetTimeout$2===defaultSetTimout$2||!cachedSetTimeout$2)&&setTimeout)return cachedSetTimeout$2=setTimeout,setTimeout(e,0);try{return cachedSetTimeout$2(e,0)}catch(t){try{return cachedSetTimeout$2.call(null,e,0)}catch(t){return cachedSetTimeout$2.call(this,e,0)}}}function runClearTimeout$2(e){if(cachedClearTimeout$2===clearTimeout)return clearTimeout(e);if((cachedClearTimeout$2===defaultClearTimeout$2||!cachedClearTimeout$2)&&clearTimeout)return cachedClearTimeout$2=clearTimeout,clearTimeout(e);try{return cachedClearTimeout$2(e)}catch(t){try{return cachedClearTimeout$2.call(null,e)}catch(t){return cachedClearTimeout$2.call(this,e)}}}"function"==typeof global$3.setTimeout&&(cachedSetTimeout$2=setTimeout),"function"==typeof global$3.clearTimeout&&(cachedClearTimeout$2=clearTimeout);var queue$2=[],draining$2=!1,currentQueue$2,queueIndex$2=-1;function cleanUpNextTick$2(){draining$2&¤tQueue$2&&(draining$2=!1,currentQueue$2.length?queue$2=currentQueue$2.concat(queue$2):queueIndex$2=-1,queue$2.length&&drainQueue$2())}function drainQueue$2(){if(!draining$2){var e=runTimeout$2(cleanUpNextTick$2);draining$2=!0;for(var t=queue$2.length;t;){for(currentQueue$2=queue$2,queue$2=[];++queueIndex$2<t;)currentQueue$2&¤tQueue$2[queueIndex$2].run();queueIndex$2=-1,t=queue$2.length}currentQueue$2=null,draining$2=!1,runClearTimeout$2(e)}}function nextTick$4(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];queue$2.push(new Item$2(e,t)),1!==queue$2.length||draining$2||runTimeout$2(drainQueue$2)}function Item$2(e,t){this.fun=e,this.array=t}Item$2.prototype.run=function(){this.fun.apply(null,this.array)};var title$2="browser",platform$2="browser",browser$2=!0,env$2={},argv$2=[],version$3="",versions$2={},release$2={},config$3={};function noop$3(){}var on$2=noop$3,addListener$2=noop$3,once$3=noop$3,off$2=noop$3,removeListener$2=noop$3,removeAllListeners$2=noop$3,emit$2=noop$3;function binding$2(e){throw new Error("process.binding is not supported")}function cwd$2(){return"/"}function chdir$2(e){throw new Error("process.chdir is not supported")}function umask$2(){return 0}var performance$3=global$3.performance||{},performanceNow$2=performance$3.now||performance$3.mozNow||performance$3.msNow||performance$3.oNow||performance$3.webkitNow||function(){return(new Date).getTime()};function hrtime$2(e){var t=.001*performanceNow$2.call(performance$3),i=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(i-=e[0],(r-=e[1])<0&&(i--,r+=1e9)),[i,r]}var startTime$2=new Date;function uptime$2(){return(new Date-startTime$2)/1e3}var process$3={nextTick:nextTick$4,title:title$2,browser:browser$2,env:env$2,argv:argv$2,version:version$3,versions:versions$2,on:on$2,addListener:addListener$2,once:once$3,off:off$2,removeListener:removeListener$2,removeAllListeners:removeAllListeners$2,emit:emit$2,binding:binding$2,cwd:cwd$2,chdir:chdir$2,umask:umask$2,hrtime:hrtime$2,platform:platform$2,release:release$2,config:config$3,uptime:uptime$2};function _mergeNamespaces(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}function __awaiter$1(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}let Global={token:""};function request({url:e,method:t="get",data:i={},contentType:r="application/json",_header:n={},succCB:s,errCB:o,dataType:a,responseType:c}){let u=Global.token;t=t.toUpperCase(),n.Authorization="Bearer "+u,-1==e.indexOf("/proxies")&&(n.checkdelay="570ed35e48494f1d6aa7d1bd20d0a2be",n.ch="web",n.os="web",n.p="3",n.delay=(new Date).getTime(),n.version="2.2.7",n.ver="2.2.7",n.lan="zh",n.osv="",n.wh="",n.apn="");let d={headers:n,method:t};if(c&&(d.responseType=c),"GET"===t){if(i){e+="?";for(let t in i)e+=`${t}=${i[t]}&`;e=e.substring(0,e.length-1)}d.cache="no-store"}else if("RESTFUL"===t){e+="/";for(let t of i)e+=t+"/";e=e.substring(0,e.length-1),t="GET",d.method=t,d.cache="no-store"}else d.body="multipart/form-data"===r?i:JSON.stringify(i);return console.log("\n############# getData host==\n"+e+"\n Header=",n,"\n optins=",d),fetch(e,d).then((t=>"blob"===a?t:handleServerData(t,e,i,c))).then((t=>(console.log(`此接口【${e}】返回的data:`,t),"blob"!==a?(t.msg=t.message||t.msg,t):"200"===t.code||200===t.status?("function"==typeof s&&s(t),t):("function"==typeof o&&o(t),void Promise.reject(t))))).catch((t=>(console.log("\n############## err"+t.message,e),t.msg=t.message||t.msg,Promise.reject(t))))}function handleServerData(e,t,i,r){return e.ok?"blob"===r?e.blob():e.json():500===e.status?Promise.reject({code:500,message:"连接服务器失败, 请检查网络重试!",url:t,param:i}):404===e.status?Promise.reject({code:404,message:"404",url:t,param:i}):502===e.status?Promise.reject({code:502,message:"连接服务器失败, 请检查网络重试!",url:t,param:i}):Promise.reject({code:e.status,message:e.status+"",url:t,param:i})}var BCEvent$2;!function(e){e.ROOM_CONNECTED="room-connected",e.ROOM_RECONNECTING="room-reconnecting",e.ROOM_RECONNECTED="room-reconnected",e.ROOM_SYNC="room-synced",e.JOINUSER="participant-joined",e.LEAVEUSER="participant-left",e.ROOMERROR="room-error",e.UNPUBLISH="participant-unpublished",e.PUBLISHED="participant-published",e.SENDMESSAGE="new-message",e.CUSTOMMESSAGE="custom-message",e.STREAMERROR="error-media",e.STREAMDISCONNECTED="stream-disconnected",e.EVICTED="participant-evicted",e.UPDATESTATS="update-stats",e.CUSTOMSTATS="update-custom-stats",e.UPDATEUSER="participant-update",e.CHANGEMASTER="change-master",e.USERREJOINED="user-rejoined",e.TOKENWILLEXPIRE="token-will-expire",e.TOKENEXPIRE="token-expire",e.ICECANDIDATE="onIceCandidate",e.STREAMUPDATE="stream-update",e.UPDATE="update",e.ANALYSISDATA="analysis-data",e.ANALYSISERROR="analysis-error",e.STARTANALYSIS="start-analyze",e.STOPANALYSIS="stop-analyze",e.REPORTINFO="info-reported",e.STREAM_ADDED="stream-added",e.STREAM_REMOVED="stream-removed",e.STREAM_UPDATED="stream-updated",e.BLOUD_STREAM_UPDATED="bloud-stream-update",e.MOVE_USER_ROOM="move-user-room",e.STREAM_PUBLISHED="stream-published",e.STREAM_SUBSCRIBED="stream-subscribed",e.MUTE_VIDEO="mute-video",e.UNMUTE_VIDEO="unmute-video",e.MUTE_AUDIO="mute-audio",e.UNMUTE_AUDIO="unmute-audio",e.ERROR="error",e.PEER_JOINED="peer-joined",e.PEER_LEAVED="peer-leaved",e.CLIENT_BANNED="client-banned",e.USER_KICKED="user-kicked",e.TOKEN_WILL_EXPIRE="token-will-expire",e.TOKEN_EXPIRE="token-expire",e.ROOM_CLOSED="room-closed",e.NETWORK_ERROR="network-error",e.BRTC_SYNC_ROOM_COMPLETED="sync-room-completed",e.BRTC_ROOM_ROCONNECTING="brtc-room-reconnecting",e.BRTC_ROOM_RECONNECTED="brtc-room-reconnected",e.JOIN_READY="join-ready",e.BRTC_SHARE_SYNC_ROOM_COMPLETED="brtc-share-sync-room-completed",e.LEAVE_USERS="leaveUsers"}(BCEvent$2||(BCEvent$2={}));class BCUser{constructor(e){this.userinfo=e.userinfo,this.permission=e.permission,this.stream=e.stream,this.userId=e.userId,this.customInfo=e.customInfo,this.nickname=e.nickname}static toUser(e,t){var i,r;let n;return e&&(n=new BCUser({userinfo:Object.assign({},e.getUserInfo()),userId:e.getID(),stream:e.getStreams(),permission:e.getPermission(),customInfo:Object.assign({},null===(r=null===(i=e.params)||void 0===i?void 0:i.info)||void 0===r?void 0:r.customInfo),nickname:e.getNickName()})),n}}const BrtcEvents=[BCEvent$2.ERROR,BCEvent$2.STREAM_PUBLISHED,BCEvent$2.CLIENT_BANNED,BCEvent$2.USER_KICKED,BCEvent$2.ROOM_CLOSED,BCEvent$2.BRTC_SYNC_ROOM_COMPLETED],bloudEvents=[BCEvent$2.ROOM_CONNECTED,BCEvent$2.ROOM_RECONNECTED,BCEvent$2.JOINUSER,BCEvent$2.LEAVEUSER,BCEvent$2.ROOMERROR,BCEvent$2.UNPUBLISH,BCEvent$2.PUBLISHED,BCEvent$2.EVICTED,BCEvent$2.ROOM_CLOSED,BCEvent$2.ROOM_SYNC,BCEvent$2.SENDMESSAGE,BCEvent$2.CUSTOMMESSAGE,BCEvent$2.STREAMERROR,BCEvent$2.STREAMDISCONNECTED,BCEvent$2.UPDATESTATS,BCEvent$2.UPDATEUSER,BCEvent$2.CHANGEMASTER,BCEvent$2.ICECANDIDATE,BCEvent$2.USERREJOINED,BCEvent$2.TOKENWILLEXPIRE,BCEvent$2.TOKENEXPIRE,BCEvent$2.ICECANDIDATE,BCEvent$2.STREAMUPDATE,BCEvent$2.ANALYSISDATA,BCEvent$2.ANALYSISERROR,BCEvent$2.STARTANALYSIS,BCEvent$2.REPORTINFO,BCEvent$2.UPDATE,BCEvent$2.CUSTOMSTATS,BCEvent$2.NETWORK_ERROR,BCEvent$2.BLOUD_STREAM_UPDATED,BCEvent$2.MOVE_USER_ROOM,BCEvent$2.LEAVE_USERS],defaultBloudEventFunction=e=>e;function transBloudUser(e){return e.participant&&(e.user=BCUser.toUser(e.participant,this.type)),e}const customUserEvent=[BCEvent$2.JOINUSER,BCEvent$2.UPDATEUSER],BloudParameterHandlerMap={};function addEvent2Bloud(){Object.values(BCEvent$2).forEach((e=>{BloudParameterHandlerMap[e]||(customUserEvent.includes(e)?BloudParameterHandlerMap[e]=transBloudUser:BloudParameterHandlerMap[e]=defaultBloudEventFunction)}))}const RAW_FUNCTION$3="function";Object.freeze({}),Object.freeze([]);const LOGGER_TAG_CLIENT$1="c",LOGGER_TAG_PLAYER="p",SING_MODE=1,MIX_MODE=2,EMPTY_FUNCTION$3=function(){},nativeConsole$3=void 0!==typeof console?console:null;function formatLog$1(e,t,i,r){let n=[];return i&&n.push(i),r&&n.push(r),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function debug$1(e,t,i,r=[]){r.unshift(formatLog$1("DEBUG",e,t,i)),nativeConsole$3.log.apply(nativeConsole$3.log,r)}function info$1(e,t,i,r=[]){r.unshift(formatLog$1("INFO",e,t,i)),nativeConsole$3.log.apply(nativeConsole$3.log,r)}function error$2(e,t,i,r=[]){r.unshift(formatLog$1("ERROR",e,t,i)),nativeConsole$3.error.apply(nativeConsole$3.error,r)}/BRTC/.test(EMPTY_FUNCTION$3.toString());var global$2=void 0!==global$3?global$3:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout$1(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout$1(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout$1=defaultSetTimout$1,cachedClearTimeout$1=defaultClearTimeout$1;function runTimeout$1(e){if(cachedSetTimeout$1===setTimeout)return setTimeout(e,0);if((cachedSetTimeout$1===defaultSetTimout$1||!cachedSetTimeout$1)&&setTimeout)return cachedSetTimeout$1=setTimeout,setTimeout(e,0);try{return cachedSetTimeout$1(e,0)}catch(t){try{return cachedSetTimeout$1.call(null,e,0)}catch(t){return cachedSetTimeout$1.call(this,e,0)}}}function runClearTimeout$1(e){if(cachedClearTimeout$1===clearTimeout)return clearTimeout(e);if((cachedClearTimeout$1===defaultClearTimeout$1||!cachedClearTimeout$1)&&clearTimeout)return cachedClearTimeout$1=clearTimeout,clearTimeout(e);try{return cachedClearTimeout$1(e)}catch(t){try{return cachedClearTimeout$1.call(null,e)}catch(t){return cachedClearTimeout$1.call(this,e)}}}"function"==typeof global$2.setTimeout&&(cachedSetTimeout$1=setTimeout),"function"==typeof global$2.clearTimeout&&(cachedClearTimeout$1=clearTimeout);var queue$1=[],draining$1=!1,currentQueue$1,queueIndex$1=-1;function cleanUpNextTick$1(){draining$1&¤tQueue$1&&(draining$1=!1,currentQueue$1.length?queue$1=currentQueue$1.concat(queue$1):queueIndex$1=-1,queue$1.length&&drainQueue$1())}function drainQueue$1(){if(!draining$1){var e=runTimeout$1(cleanUpNextTick$1);draining$1=!0;for(var t=queue$1.length;t;){for(currentQueue$1=queue$1,queue$1=[];++queueIndex$1<t;)currentQueue$1&¤tQueue$1[queueIndex$1].run();queueIndex$1=-1,t=queue$1.length}currentQueue$1=null,draining$1=!1,runClearTimeout$1(e)}}function nextTick$3(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];queue$1.push(new Item$1(e,t)),1!==queue$1.length||draining$1||runTimeout$1(drainQueue$1)}function Item$1(e,t){this.fun=e,this.array=t}Item$1.prototype.run=function(){this.fun.apply(null,this.array)};var title$1="browser",platform$1="browser",browser$1=!0,env$1={},argv$1=[],version$1="",versions$1={},release$1={},config$1={};function noop$1(){}var on$1=noop$1,addListener$1=noop$1,once$2=noop$1,off$1=noop$1,removeListener$1=noop$1,removeAllListeners$1=noop$1,emit$1=noop$1;function binding$1(e){throw new Error("process.binding is not supported")}function cwd$1(){return"/"}function chdir$1(e){throw new Error("process.chdir is not supported")}function umask$1(){return 0}var performance$2=global$2.performance||{},performanceNow$1=performance$2.now||performance$2.mozNow||performance$2.msNow||performance$2.oNow||performance$2.webkitNow||function(){return(new Date).getTime()};function hrtime$1(e){var t=.001*performanceNow$1.call(performance$2),i=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(i-=e[0],(r-=e[1])<0&&(i--,r+=1e9)),[i,r]}var startTime$1=new Date;function uptime$1(){return(new Date-startTime$1)/1e3}var process$2={nextTick:nextTick$3,title:title$1,browser:browser$1,env:env$1,argv:argv$1,version:version$1,versions:versions$1,on:on$1,addListener:addListener$1,once:once$2,off:off$1,removeListener:removeListener$1,removeAllListeners:removeAllListeners$1,emit:emit$1,binding:binding$1,cwd:cwd$1,chdir:chdir$1,umask:umask$1,hrtime:hrtime$1,platform:platform$1,release:release$1,config:config$1,uptime:uptime$1};function __awaiter(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}class Timer{constructor(e,t,i){this.task=e,this.timeout=t,this.interval=i}start(){const e=this;e.stop();let t=e.timeout;const i=e.interval,r=function(){!1!==e.task()&&e.timer?e.timer=setTimeout(r,e.interval):e.stop()};null==t&&(t=i),e.timer=setTimeout(r,t)}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}updateInterval(e){this.interval=e}isStarted(){return!!this.timer}destroy(){this.stop(),this.task=this.timeout=this.interval=null}}const TRUE$2=!0,FALSE$2=!1,NULL$2=null,UNDEFINED$2=void 0,MINUS_ONE$2=-1,RAW_UNDEFINED$2="undefined",RAW_FUNCTION$2="function",RAW_DOT$2=".",WINDOW$2=typeof window!==RAW_UNDEFINED$2?window:UNDEFINED$2,GLOBAL$2=typeof global$2!==RAW_UNDEFINED$2?global$2:WINDOW$2,EMPTY_FUNCTION$2=function(){};Object.freeze({}),Object.freeze([]);const EMPTY_STRING$2="";function isDef(e){return e!==UNDEFINED$2}function func$3(e){return typeof e===RAW_FUNCTION$2}function array$2(e){return Array.isArray(e)}function object$2(e){return e!==NULL$2&&"object"==typeof e}function string$2(e){return"string"==typeof e}function number$2(e){return"number"==typeof e&&!isNaN(e)}function numeric(e){return number$2(e)||string$2(e)&&!isNaN(parseFloat(e))&&isFinite(+e)}function arrayBuffer(e){return e instanceof ArrayBuffer}function execute$2(e,t,i){if(func$3(e))return array$2(i)?e.apply(t,i):t!==UNDEFINED$2?e.call(t,i):i!==UNDEFINED$2?e(i):e()}function each$1$1(e,t,i){if(!e)return;const{length:r}=e;if(r)if(i)for(let i=r-1;i>=0&&t(e[i],i)!==FALSE$2;i--);else for(let i=0;i<r&&t(e[i],i)!==FALSE$2;i++);}function nativePush$2(e,t){e[e.length]=t}function addItem$2(e,t,i){array$2(t)?each$1$1(t,(function(t){i(e,t)})):i(e,t)}function push$2(e,t){addItem$2(e,t,nativePush$2)}function indexOf$2$1(e,t,i){let r=MINUS_ONE$2;return each$1$1(e,(function(e,n){if(i===FALSE$2?e==t:e===t)return r=n,FALSE$2})),r}function has$1$1(e,t,i){return indexOf$2$1(e,t,i)>=0}function toString$2(e,t){return e!=NULL$2&&e.toString?e.toString():t!==UNDEFINED$2?t:EMPTY_STRING$2}function slice$2(e,t,i){return number$2(i)?t===i?EMPTY_STRING$2:e.slice(t,i):e.slice(t)}function indexOf$1$1(e,t,i){return e.indexOf(t,i!==UNDEFINED$2?i:0)}function has$2(e,t){return indexOf$1$1(e,t)>=0}function keys(e){return isDef(e)?Object.keys(e):[]}function each$4(e,t){for(let i in e)if(t(e[i],i)===FALSE$2)break}function _extend(e,t){return object$2(e)?object$2(t)?(each$4(t,(function(t,i){e[i]=t})),e):e:t}function extend(e,t,i){return _extend(_extend(e,t),i)}function copy$2(e,t){let i=e;return array$2(e)?t?(i=[],each$1$1(e,(function(e,r){i[r]=copy$2(e,t)}))):i=e.slice():object$2(e)&&(i={},each$4(e,(function(e,r){i[r]=t?copy$2(e,t):e}))),i}class CustomEvent$2{constructor(e,t){this.type=e,this.phase=CustomEvent$2.PHASE_CURRENT,t&&(this.originalEvent=t)}preventDefault(){const e=this;if(!e.isPrevented){const{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=TRUE$2}return e}stopPropagation(){const e=this;if(!e.isStoped){const{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=TRUE$2}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}}CustomEvent$2.PHASE_CURRENT=0,CustomEvent$2.PHASE_UPWARD=1,CustomEvent$2.PHASE_DOWNWARD=MINUS_ONE$2;const TRACE$1=0,DEBUG$1$1=1,INFO$2=2,WARN$2=3,ERROR$2=4,FATAL$2=5;let defaultTag$1="boom-bloud ";const nativeConsole$2=typeof console!==RAW_UNDEFINED$2?console:NULL$2,defaultLogLevel$2=/bjy/.test(toString$2(EMPTY_FUNCTION$2))?INFO$2:WARN$2,stylePrefix$2=WINDOW$2&&/edge|msie|trident/i.test(WINDOW$2.navigator.userAgent)?EMPTY_STRING$2:"%c",printLog$2=nativeConsole$2?stylePrefix$2?function(e,t,i,r){r?nativeConsole$2.log(stylePrefix$2+e,i,t,r):nativeConsole$2.log(stylePrefix$2+e,i,t)}:function(e,t,i){i?nativeConsole$2.log(e,t,i):nativeConsole$2.log(e,t)}:EMPTY_FUNCTION$2;function getLogLevel$2(){if(GLOBAL$2){const e=GLOBAL$2.BJY_LOG_LEVEL;if(e>=TRACE$1&&e<=FATAL$2)return e}return defaultLogLevel$2}function getStyle$2(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function trace(e,t){getLogLevel$2()<=TRACE$1&&printLog$2(`${t||defaultTag$1} trace`,e,getStyle$2("#999"))}function debug(e,t){getLogLevel$2()<=DEBUG$1$1&&printLog$2(`${t||defaultTag$1} debug`,e,getStyle$2("#999"))}function info$2(e,t){getLogLevel$2()<=INFO$2&&printLog$2(`${t||defaultTag$1} info`,e,getStyle$2("#2db7f5"))}function call(e,t,i){getLogLevel$2()<=INFO$2&&printLog$2(`${t||defaultTag$1} info`,e,getStyle$2("#66cdaa"),i)}function warn$2(e,t){getLogLevel$2()<=WARN$2&&printLog$2(`${t||defaultTag$1} warn`,e,getStyle$2("#f90"))}function error$1$1(e,t){getLogLevel$2()<=ERROR$2&&printLog$2(`${t||defaultTag$1} error`,e,getStyle$2("#ed4014"))}function fatal$2(e,t){if(getLogLevel$2()<=FATAL$2)throw new Error(`[${t||defaultTag$1} fatal]: ${e}`)}let enableUpload=!0,uploadLevel=WARN$2;function canUploadLog(){return enableUpload}function getUploadLevel(){return uploadLevel}class Emitter$2{constructor(e){this.ns=e||FALSE$2,this.listeners={}}fire(e,t,i){let r=this,n=string$2(e)?r.parse(e):e,s=r.listeners[n.type],o=TRUE$2;if(s){s=copy$2(s);const e=t&&t[0]instanceof CustomEvent$2?t[0]:UNDEFINED$2;each$1$1(s,(function(a){if(!matchNamespace$2(n.ns,a,TRUE$2)||!has$1$1(s,a)||i&&!i(n,t,a))return;e&&(e.listener=a.fn);let c=execute$2(a.fn,a.ctx,t);return e&&(e.listener=UNDEFINED$2),a.num=a.num?a.num+1:1,a.num===a.max&&r.off(n,a.fn),e&&(c===FALSE$2?e.prevent().stop():e.isStoped&&(c=FALSE$2)),c===FALSE$2?o=FALSE$2:void 0}))}return o}on(e,t){const i=this,r=i.listeners,n=func$3(t)?{fn:t}:t;if(object$2(n)&&func$3(n.fn)){const t=string$2(e)?i.parse(e):e;n.ns=t.ns,push$2(r[t.type]||(r[t.type]=[]),n)}else"development"===process$2.env.NODE_ENV&&fatal$2('emitter.on(type, listener) invoke failed:\n\n"listener" is expected to be a Function or an EmitterOptions.\n');return this}one(e,t){return func$3(t)?t={fn:t,max:1}:t.max=1,this.on(e,t)}off(e,t){const i=this,r=i.listeners;if(e){const n=string$2(e)?i.parse(e):e,s=n.type,o=n.ns,a=createMatchListener$2(t),c=function(e,t){each$1$1(e,(function(t,i){a(t)&&e.splice(i,1)}),TRUE$2),e.length||delete r[t]},u=function(e,t){each$1$1(e,(function(t,i){matchNamespace$2(o,t)&&e.splice(i,1)}),TRUE$2),e.length||delete r[t]};s?r[s]&&c(r[s],s):o&&each$4(r,u),"development"===process$2.env.NODE_ENV&&arguments.length>1&&t==NULL$2&&warn$2(`emitter.off(type, listener) is invoked, but "listener" is ${t}.`)}else i.listeners={},"development"===process$2.env.NODE_ENV&&arguments.length>0&&warn$2(`emitter.off(type) is invoked, but "type" is ${e}.`)}has(e,t){let i=this.listeners,r=string$2(e)?this.parse(e):e,n=r.type,s=r.ns,o=TRUE$2,a=createMatchListener$2(t);return n?i[n]&&each$1$1(i[n],(function(e){if(a(e))return o=FALSE$2})):s&&each$4(i,(function(e){return each$1$1(e,(function(e){if(matchNamespace$2(s,e))return o=FALSE$2})),o})),!o}parse(e){const t={type:e,ns:EMPTY_STRING$2};if(this.ns){const i=indexOf$1$1(e,RAW_DOT$2);i>=0&&(t.type=slice$2(e,0,i),t.ns=slice$2(e,i+1))}return t}}function matchTrue$2(){return TRUE$2}function createMatchListener$2(e){return func$3(e)?function(t){return e===t.fn}:matchTrue$2}function matchNamespace$2(e,t,i){const{ns:r}=t;return r&&e?r===e:i?TRUE$2:FALSE$2}const ON_SEND="onsend",ON_RECEIVE="onreceive",RECONNECTED$1="reconnected",CONNECTED="connected",CLOSE="close",ERROR$1="error",TIMEOUT$1="timeout",RECONNECTING$1="reconnecting",BINARY="binary",NOTIFY="notify",REQUEST="request";class Logger$1{constructor(e={}){this.TRACE=TRACE$1,this.DEBUG=DEBUG$1$1,this.INFO=INFO$2,this.WARN=WARN$2,this.ERROR=ERROR$2,this.FATAL=FATAL$2,this.options=extend({uploadLevel:getUploadLevel()},e),this.canUpload=!0}static Log(){return this.instance||(this.instance=new Logger$1),this.instance}enableUploadLog(){this.canUpload=!0}disableUploadLog(){this.canUpload=!1}setUploadLevel(e){this.options.uploadLevel=e}fatal(e,t,i=!1){(FATAL$2>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,FATAL$2,t),fatal$2(e,t)}error(e,t,i=!1){error$1$1(e,t),(ERROR$2>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,ERROR$2,t)}warn(e,t,i=!1){warn$2(e,t),(WARN$2>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,WARN$2,t)}info(e,t,i=!1){info$2(e,t),(INFO$2>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,INFO$2,t)}call(e,t,i=!1){call(e,t),(INFO$2>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,INFO$2,t)}debug(e,t,i=!1,r=!1){debug(e,t),r||(DEBUG$1$1>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,DEBUG$1$1,t)}trace(e,t,i=!1){trace(e,t),TRACE$1>=this.options.uploadLevel&&i&&this.canUpload&&this.options.onUpload&&canUploadLog()&&this.options.onUpload(e,TRACE$1,t)}log(e,t,i,r=!1){switch(t){case TRACE$1:this.trace(e,i,r);break;case DEBUG$1$1:this.debug(e,i,r);break;case INFO$2:this.info(e,i,r);break;case WARN$2:this.warn(e,i,r);break;case ERROR$2:this.error(e,i,r);break;case FATAL$2:this.fatal(e,i,r);break;default:this.debug(e,i,r)}}}function getTimestamp(){return Date.now()}function getErrorMessage(e){if(string$2(e))return e;if(object$2(e)){if(string$2(e.message))return e.message;if(string$2(e.msg))return e.msg;if(func$3(e.toString))return e.toString()}return"unknow"}const tag="RpcBuilder",defaultOptions$3={maxRetry:0,requestTimeout:5e3,responseTimeout:5e3,duplicatesTimeout:5e3};function formatKey(...e){let t="";for(let i=0;i<e.length;i++)e[i]&&(t+=e[i]);return t}class RpcBuilder extends Emitter$2{constructor(e,t,i={},r){super(!1),this.packer=e,this.options=extend({},defaultOptions$3,i),this.requestID=0,this.notifyId=0,this.reqMap=new Map,this.resMap=new Map,this.reqKeyMap=new Map,this.logger=r||new Logger$1,this.onmessageHandler=e=>{this.onmessage(e)},t&&this.handlTransport(t)}handlTransport(e){this.transport&&(func$3(this.transport.removeListener)?this.transport.removeListener(this.onmessageHandler):func$3(this.transport.removeEventListener)?this.transport.removeEventListener(this.onmessageHandler):func$3(this.transport.onmessage)&&(this.transport.onmessage=null)),e&&(func$3(e.addListener)?e.addListener("onmessage",this.onmessageHandler):func$3(e.addEventListener)?e.addEventListener("onmessage",this.onmessageHandler):e.onmessage=this.onmessageHandler,this.transport=e)}send(e){func$3(this.transport.send)?this.transport.send(e):func$3(this.transport.write)?this.transport.write(e):func$3(this.transport.postMessage)&&this.transport.postMessage(e)}request(e,t={},i={}){return __awaiter(this,void 0,void 0,(function*(){if(!this.transport)throw new Error(`request ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);return new Promise(((r,n)=>{var s,o;if(i.key&&this.reqKeyMap.has(i.key)){const r=this.reqKeyMap.get(i.key);clearTimeout(r.timer),this.logger.warn(`request ${e}, params: ${JSON.stringify(t)} canceled because there is call new request whoes key is same as before`),r.reject(new Error("request canceled because there is call new request which key is same as before")),this.reqMap.delete(formatKey(r.id)),this.reqKeyMap.delete(i.key)}const a=this.requestID++;i.dest&&(t.dest=i.dest),this.options.peerId&&(t.from=this.options.peerId);const c={resolve:r,reject:n,id:a,dest:i.dest,timer:null,retryCount:0,maxRetry:null!==(s=i.maxRetry)&&void 0!==s?s:this.options.maxRetry,errorRetry:null!==(o=i.errorRetry)&&void 0!==o&&o,method:e,params:t,message:this.packer.pack({method:e,params:t},a),timestamp:getTimestamp(),key:i.key,timeout:i.timeout,timeoutFn:()=>{c.retryCount>=c.maxRetry?(this.reqMap.delete(formatKey(c.id)),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key),this.logger.error(`request ${e}, params: ${JSON.stringify(t)} timeout`),n(new Error("request timeout"))):(c.retryCount++,c.timer=setTimeout(c.timeoutFn,i.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${e}, params: ${JSON.stringify(t)}, count: ${c.retryCount}`),this.send(c.message))},needRetry:i.needRetry};c.timer=setTimeout(c.timeoutFn,i.timeout||this.options.requestTimeout*(c.retryCount+1)),this.reqMap.set(formatKey(c.id),c),c.key&&this.reqKeyMap.set(c.key,c),this.send(c.message)}))}))}reply(e,t,i){var r;this.options.peerId&&(t&&(t.from=this.options.peerId),i&&(i.from=this.options.peerId));const n=this.packer.pack({result:t,error:i},e.id),s={id:e.id,message:n,timer:null},o=formatKey(e.id,null===(r=e.params)||void 0===r?void 0:r.from);this.options.responseTimeout&&(s.timer=setTimeout((()=>{this.resMap.delete(o)}),this.options.responseTimeout),this.resMap.set(o,s)),this.send(s.message)}notify(e,t={},i){if(!this.transport)throw new Error(`notify ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);const r=this.notifyId++;i&&(t.dest=i),this.options.peerId&&(t.from=this.options.peerId),this.send(this.packer.pack({method:e,params:t,seq:r}))}onmessage(e){var t;if(this.transport)if(isDef(e))if(string$2(e)){let i;try{i=this.packer.unpack(e)}catch(t){return void this.logger.error(`unpack message error, message: ${e}, error: ${getErrorMessage(t)}`,tag)}const r=i.id,n=i.method,s=null!==(t=i.params)&&void 0!==t?t:{},o=s.dest;if(s.dest,isDef(this.options.peerId)&&this.options.peerId===o)return void this.logger.warn(`ignored the message which send from me, message: ${e}`);if(isDef(r))if(n){const t=this.resMap.get(formatKey(r,o));t?(this.logger.warn(`request: ${e} has replyed in ${this.options.responseTimeout}ms, send same again`),this.send(t.message)):this.fire(REQUEST,[i])}else{const t=i.error,o=i.result;if((null==t?void 0:t.dest)!==this.options.peerId||(null==o?void 0:o.dest)!==this.options.peerId)return void this.logger.warn(`ignored the message which not sent for me, message: ${e}`);const a=formatKey(r),c=this.reqMap.get(a);if(c){if(clearTimeout(c.timer),t){if(this.logger.error(`[request error] request: ${c.message}, response: ${e}, consume: ${getTimestamp()-c.timestamp}`),c.errorRetry&&c.retryCount<c.maxRetry&&(!c.needRetry||c.needRetry(t)))return c.retryCount++,c.timer=setTimeout(c.timeoutFn,c.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${c.method}, params: ${JSON.stringify(c.params)}, count: ${c.retryCount}`),c.id=this.requestID++,c.message=this.packer.pack({method:n,params:s},c.id),void this.send(c.message);c.reject(t)}else this.logger.debug(`[request success] method: ${c.method}, id: ${c.id}, consume: ${getTimestamp()-c.timestamp}`),c.resolve(o);this.reqMap.delete(a),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key)}else this.logger.warn(`no request for the response: ${e}`)}else this.fire(NOTIFY,[n,s,i.seq])}else this.fire(BINARY,[e]);else this.logger.warn("message is not defined",tag)}destroy(){this.off(),this.handlTransport(),this.reqMap&&(this.reqMap.forEach((e=>{clearTimeout(e.timer),e.reject("transport closed")})),this.reqMap.clear(),this.reqMap=null),this.reqKeyMap&&(this.reqKeyMap.clear(),this.reqKeyMap=null),this.resMap&&(this.resMap.forEach((e=>{clearTimeout(e.timer)})),this.resMap.clear(),this.resMap=null),this.packer=null,this.transport=null}getPacker(){return this.packer}getTransport(){return this.transport}setTransport(e){this.handlTransport(e)}resetRequest(){this.reqMap&&this.reqMap.forEach((e=>{clearTimeout(e.timer),e.timer=setTimeout(e.timeoutFn,e.timeout||this.options.requestTimeout*(e.retryCount+1)),this.send(e.message)}))}}var TransportStatus,e;e=TransportStatus||(TransportStatus={}),e[e.NONE=0]="NONE",e[e.OPEN=1]="OPEN",e[e.ERROR=2]="ERROR",e[e.CLOSE=3]="CLOSE",e[e.CLOSING=4]="CLOSING",e[e.TIMEOUT=5]="TIMEOUT",e[e.CONNECTING=6]="CONNECTING";const TransportEvent={OPEN:"open",CLOSE:"close",ERROR:"error",SEND:"send",MESSAGE:"message",TIMEOUT:"timeout",RECONNECTING:"reconnecting"};class Transport extends Emitter$2{constructor(e){var t;super(!0),extend(this,e),this.status=TransportStatus.NONE,this.queue=[],this.isReconnect=!1,e.retryCount&&e.retryCount>0&&(this.retryIndex=0),this.logger=Logger$1.Log(),this.logLevel=null!==(t=this.logLevel)&&void 0!==t?t:this.logger.TRACE,this.connectCount=0}isOpen(){return this.status===TransportStatus.OPEN}isConnecting(){return this.status===TransportStatus.CONNECTING}getStatus(){return this.status}connect(e,t){const i=this;if(this.server=e,this.proxys=t,this.connectCount=0,i.status===TransportStatus.OPEN||i.status===TransportStatus.CONNECTING||i.status===TransportStatus.CLOSING)return;let r=[e];t&&t.length&&(r=r.concat(t));let n=-1;const s=function(){i.nextStartTimer=null,i.status===TransportStatus.CONNECTING?function(e,t){i.connectCount++;let r=i.nativeOptions;i.native===WebSocket&&(r=i.nativeOptions.protocols),i.logger.debug(`${i.tag||"Transport"} connecting url: ${e.url}`);const n=getTimestamp(),s=new i.native(e.url,r);let o,a=function(i){o&&clearTimeout(o),s.onopen=s.onerror=null,t(s,e,i)};s.onopen=function(e){var t;i.consume=null!==(t=null==e?void 0:e.consume)&&void 0!==t?t:getTimestamp()-n,a(TransportStatus.OPEN)},s.onerror=function(){a(TransportStatus.ERROR)},i.timeout>0&&(o=setTimeout((function(){o=null,s.onerror=null,s.onopen=null,func$3(s.close)&&s.close(),a(TransportStatus.TIMEOUT)}),i.timeout))}(r[++n],(function(e,s,a){if(i.status===TransportStatus.CONNECTING)if(a===TransportStatus.OPEN){if(i.url=s.url,i.socket=e,i.status=TransportStatus.OPEN,e.onmessage=function(e){i.status===TransportStatus.OPEN&&(i.logger.log(`${i.tag||"Transport"} Received: ${string$2(e.data)?e.data:"binary"}`,i.logLevel),i.onReceive&&string$2(e.data)&&i.onReceive(JSON.parse(e.data)),i.onmessage&&i.onmessage(e.data),i.fire(TransportEvent.MESSAGE,[e.data]))},e.onclose=function(r){if(i.status===TransportStatus.OPEN)if(i.connectOnClose&&i.retryCount>0){if(i.status=TransportStatus.NONE,i.onReconnecting&&(i.onReconnecting(),i.status===TransportStatus.CLOSING||i.status===TransportStatus.CLOSE))return;i.fire(TransportEvent.RECONNECTING),i.isReconnect=!0,i.logger.warn(`${i.tag||"Transport"} reconnecting`),e.clear&&e.clear(),i.connect(s,t)}else i.onClose&&i.onClose(r),i.fire(TransportEvent.CLOSE,[r])},i.retryCount>0&&(i.retryIndex=0),i.onOpen&&(i.logger.debug(`${i.tag||"Transport"} ${i.isReconnect?"reconnect":"connect"} success`),i.onOpen({server:s,reconnect:i.isReconnect})),i.fire(TransportEvent.OPEN,[{server:s,reconnect:i.isReconnect}]),i.queue.length)for(;i.queue.length;){const t=i.queue.shift(),r=string$2(t)||arrayBuffer(t)?t:JSON.stringify(t);e.send(r),i.logger.log(`${i.tag||"Transport"} Sent: ${arrayBuffer(t)?"binary":r}`,i.logLevel),i.onSend&&i.onSend(r),i.fire(TransportEvent.SEND,[r])}}else if(n===r.length-1){if(i.retryCount>0&&i.retryIndex++<i.retryCount-1)return n=-1,void o();switch(i.status=a){case TransportStatus.ERROR:i.logger.error(`${i.tag||"Transport"} ${i.isReconnect?"reconnect":"connect"} error`),i.onError&&i.onError({server:s}),i.fire(TransportEvent.ERROR,[{server:s}]);break;case TransportStatus.TIMEOUT:i.logger.error(`${i.tag||"Transport"} ${i.isReconnect?"reconnect":"connect"} timeout`),i.onTimeout&&i.onTimeout({server:s}),i.fire(TransportEvent.TIMEOUT,[{server:s}])}}else o();else if(i.status===TransportStatus.CLOSING){let t=!1;if(a===TransportStatus.OPEN&&i.refreshQueueOnClose&&i.queue.length){for(;i.queue.length;){const t=i.queue.shift(),r=string$2(t)||arrayBuffer(t)?t:JSON.stringify(t);e.send(r),i.logger.log(`${i.tag||"Transport"} Sent: ${arrayBuffer(t)?"binary":r}`,i.logLevel),i.onSend&&i.onSend(r),i.fire(TransportEvent.SEND,[r])}t=!0}t?setTimeout((()=>{e.close(),i.status=TransportStatus.CLOSE}),1e3):(e.close(),i.status=TransportStatus.CLOSE)}})):i.status===TransportStatus.CLOSING&&(i.status=TransportStatus.CLOSE)},o=function(){i.interval>0?i.nextStartTimer=setTimeout(s,i.interval):s()};i.status=TransportStatus.CONNECTING,s()}send(e){if(this.status!==TransportStatus.OPEN&&this.status!==TransportStatus.CLOSING)return this.queueMax>0&&this.queue.length===this.queueMax&&this.queue.shift(),void this.queue.push(e);const t=this.socket;if(t){const i=string$2(e)||arrayBuffer(e)?e:JSON.stringify(e);t.send(i),this.logger.log(`${this.tag||"Transport"} Sent: ${arrayBuffer(e)?"binary":i}`,this.logLevel),this.onSend&&this.onSend(i),this.fire(TransportEvent.SEND,[i])}}close(){const e=this.socket;if(this.socket=null,this.status=TransportStatus.CLOSING,e){let t=!1;if(this.refreshQueueOnClose&&this.queue.length){for(;this.queue.length;)this.send(this.queue.shift());t=!0}e.onmessage=e.onclose=null,t?setTimeout((()=>{e.close(),this.status=TransportStatus.CLOSE}),1e3):(e.close(),this.status=TransportStatus.CLOSE)}this.nextStartTimer&&(clearTimeout(this.nextStartTimer),this.nextStartTimer=null)}reconnect(){this.status!==TransportStatus.CONNECTING&&(this.close(),this.status===TransportStatus.CLOSING?setTimeout((()=>{this.status=TransportStatus.CLOSE,this.connect(this.server,this.proxys)}),1e3):this.connect(this.server,this.proxys))}getSocket(){return this.socket}getConsume(){return Math.max(this.consume||0,0)}getConnectCount(){return this.connectCount}}class Packer{constructor(){}}class JsonPacker extends Packer{constructor(){super()}pack(e,t){const i={jsonrpc:"2.0"};if(e.method)i.method=e.method,e.params&&(i.params=e.params),isDef(t)&&(i.id=t),e.seq&&(i.seq=e.seq);else if(isDef(t)){if(e.error){if(e.result)throw new TypeError("Both result and error are defined");i.error=e.error}else{if(!e.result)throw new TypeError("No result or error is defined");i.result=e.result}i.id=t}return JSON.stringify(i)}unpack(e){const t=JSON.parse(e);if("2.0"!==t.jsonrpc)throw new TypeError(`Invalid JsonRPC version ${t.jsonrpc}: ${e}`);if(!isDef(t.method)){if(!isDef(t.id))throw new TypeError(`Invalid message: ${e}`);const i=isDef(t.error),r=isDef(t.result);if(r&&i)throw new TypeError(`Both result and error are defined: ${e}`);if(!r&&!i)throw new TypeError(`No result or error is defined: ${e}`)}return t}}function isNative$1(e){return func$3(e)&&has$2(toString$2(e),"[native code]")}let nextTick$1;typeof setImmediate===RAW_FUNCTION$2&&isNative$1(setImmediate)&&(nextTick$1=setImmediate),nextTick$1=typeof MessageChannel===RAW_FUNCTION$2&&isNative$1(MessageChannel)?function(e){const t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(1)}:setTimeout;var nextTick$2=nextTick$1;const defaultOptions$2={heartbeat:15e3,requestTimeout:15e3,maxRetry:3,packer:JsonPacker,retryInterval:500,connectTimeout:1e4,connectOnClose:!0,requestMaxRetry:0};class JsonRpcClient extends Emitter$2{constructor(e,t,i,r){var n,s;super(!0),this.server=e,this.proxys=i,this.options=extend({},defaultOptions$2,t),this.logger=Logger$1.Log(),this.heartbeatTimer=new Timer((()=>{this.heartbeat()}),this.options.heartbeat,this.options.heartbeat),this.packer=new this.options.packer,this.transport=new Transport({native:null!==(n=this.options.transport)&&void 0!==n?n:WebSocket,onSend:e=>{this.fire(ON_SEND,[e])},onReceive:e=>{this.fire(ON_RECEIVE,[e])},onOpen:e=>{this.fire(e.reconnect?RECONNECTED$1:CONNECTED),this.heartbeatTimer&&this.heartbeatTimer.start()},onClose:()=>{this.fire(CLOSE),this.heartbeatTimer&&this.heartbeatTimer.stop()},onError:()=>{this.fire(ERROR$1),this.heartbeatTimer&&this.heartbeatTimer.stop()},onTimeout:()=>{this.fire(TIMEOUT$1),this.heartbeatTimer&&this.heartbeatTimer.stop()},onReconnecting:()=>{this.fire(RECONNECTING$1),this.heartbeatTimer&&this.heartbeatTimer.stop()},connectOnClose:this.options.connectOnClose,retryCount:this.options.maxRetry,nativeOptions:null!==(s=this.options.transportOptions)&&void 0!==s?s:{},tag:this.options.tag,interval:this.options.retryInterval,timeout:this.options.connectTimeout,logLevel:this.options.logLevel}),this.rpc=new RpcBuilder(this.packer,this.transport,{requestTimeout:this.options.requestTimeout,responseTimeout:this.options.requestTimeout,peerId:this.options.peerId,maxRetry:this.options.requestMaxRetry},this.logger),this.rpc.on(BINARY,(e=>{this.fire(BINARY,[e])})),this.rpc.on(NOTIFY,((e,t,i)=>{this.fire(NOTIFY,[e,t,i])})),this.rpc.on(REQUEST,(e=>{this.fire(REQUEST,[e])})),nextTick$2((()=>{this.transport&&this.transport.connect(this.server,this.proxys)}))}request(e,t={},i){return __awaiter(this,void 0,void 0,(function*(){return this.rpc.request(e,t,i)}))}reply(e,t,i){return this.rpc.reply(e,t,i)}notify(e,t={}){return this.rpc.notify(e,t)}sendBinary(e){const t=this.transport.getSocket();t&&t.send(e)}getConsume(){return this.transport?this.transport.getConsume():0}getTransportConnectCount(){return this.transport?this.transport.getConnectCount():0}getTransportStatus(){return this.transport?this.transport.getStatus():TransportStatus.NONE}destroy(){this.off(),this.rpc&&this.rpc.destroy(),this.transport&&this.transport.close(),this.transport=null,this.rpc=null,this.packer=null,this.heartbeatTimer&&this.heartbeatTimer.destroy(),this.heartbeatTimer=null}resetRequest(){this.rpc&&this.rpc.resetRequest()}}const PARTICIPANT_JOINED="participant-joined",PARTICIPANT_LEFT="participant-left",ROOM_CLOSED="room-closed",ERROR="room-error",TIMEOUT="network-error",RECONNECTED="room-reconnected",RECONNECTING="room-reconnecting",UPDATE_STATS="update-stats",UPDATE_USER="participant-update",CHANGE_MASTER="change-master",STREAM_PUBLISHED="participant-published",STREAM_REMOVED="participant-unpublished",SEND_MESSAGE="new-message",CUSTOM_MESSAGE="custom-message",UPDATE_CUSTOM_STATS="update-custom-stats",MOVE_USER_ROOM="move-user-room",STREAM_UPDATE="stream-update",EVICTED="participant-evicted",USER_REJOINED="user-rejoined",SESSION_CLOED="session-close",STATE_NOTIFY="state-notify",LEAVE_USERS="leaveUsers";class Channel extends JsonRpcClient{constructor(e,t,i,r){super({url:e},t,void 0,r),this.notified=-1,this.seq=0,this.sessionId=null,this.syncRoomLock=!1,this.retryQueue=[],this.proxy=i}resetTimeout(){this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout((()=>{this.resetTimer=void 0,this.fire(TIMEOUT$1),this.destroy()}),4*this.options.heartbeat)}syncNotify(){return __awaiter(this,void 0,void 0,(function*(){this.fire(SESSION_CLOED)}))}request(e,t,i){const r=Object.create(null,{request:{get:()=>super.request}});return __awaiter(this,void 0,void 0,(function*(){const n=this.seq++;return this.syncRoomLock&&"syncRoom"!==e?(this.logger.warn(`session closed, waiting for sync room, method: ${e}, params: ${JSON.stringify(t)}`),new Promise(((i,r)=>{this.retryQueue.push({method:e,params:t,resolve:i,reject:r,id:n})}))):(this.syncRoomLock||"syncRoom"!==e||(this.syncRoomLock=!0),t&&"syncRoom"!==e&&!t.sessinId&&(t.sessionId=this.sessionId),t&&"syncRoom"===e&&(t.sid=this.sessionId),r.request.call(this,e,t,i).then((t=>(this.resetTimeout(),(!this.sessionId&&t.sessionId||this.sessionId!==t.sessionId)&&(this.sessionId=t.sessionId),"syncRoom"===e&&(this.syncRoomLock=!1,this.retryQueue.length&&(this.retryQueue=this.retryQueue.filter((e=>"recover"!==e.method)),this.retryQueue.sort(((e,t)=>e.id-t.id)),each$1$1(this.retryQueue,(e=>{e.params.sessionId=this.sessionId,this.logger.info(`retry the retryQueue request, ${e.method}, params: ${JSON.stringify(e.params)}`),this.request(e.method,e.params).then((t=>{e.resolve(t)})).catch((t=>{e.reject(t)}))})),this.retryQueue=[])),t))).catch((i=>{if("request timeout"!==getErrorMessage(i)&&this.resetTimeout(),99===(null==i?void 0:i.code))return this.sessionId&&this.sessionId!==t.sessionId?(this.logger.warn(`the request session has closed but the seesion is update after sync room, retry request again, ${e}, params: ${JSON.stringify(t)}`),t.sessionId=this.sessionId,this.request(e,t)):(this.syncRoomLock||(this.sessionId=null,this.syncRoomLock=!0,this.fire(SESSION_CLOED)),this.logger.warn(`the session has closed, push the request into retry queue, ${e}, params: ${JSON.stringify(t)}`),new Promise(((i,r)=>{this.retryQueue.push({method:e,params:t,resolve:i,reject:r,id:n})})));throw i})))}))}heartbeat(){this.request("ping",{sessionId:this.sessionId}).then((e=>{this.resetTimeout()})).catch((e=>{this.logger.error(`channel heartbeat error: ${JSON.stringify(e)}`)}))}destroy(){this.seq=null,this.notified=null,this.sessionId=null,this.retryQueue=null,this.syncRoomLock=null,this.resetTimer&&(clearTimeout(this.resetTimer),this.resetTimer=null),super.destroy()}getProxy(){return this.proxy}}function toNumber$1(e,t){return numeric(e)?+e:t!==UNDEFINED$2?t:0}const EventMap={joinUser:PARTICIPANT_JOINED,leaveUser:PARTICIPANT_LEFT,roomClosed:ROOM_CLOSED,roomError:ERROR,updateStats:UPDATE_STATS,updateUser:UPDATE_USER,changeMaster:CHANGE_MASTER,publishStream:STREAM_PUBLISHED,unpublishStream:STREAM_REMOVED,sendMessage:SEND_MESSAGE,customMessage:CUSTOM_MESSAGE,updateCustomStats:UPDATE_CUSTOM_STATS,moveUserRoom:MOVE_USER_ROOM,streamUpdate:STREAM_UPDATE,evicted:EVICTED,userRejoined:USER_REJOINED,leaveUsers:LEAVE_USERS},defaultOptions$1={enableRace:!0,forceWS:!1,forceDC:!1,forceWT:!1};class Client extends Emitter$2{constructor(e,t,i={},r){super(!1),this.options=extend({},defaultOptions$1,t),this.closed=!1,this.icefull=!1,this.isConnecting=!1,this.connectCount=0,this.isLeaving=!1,this.rpc=i,this.proxies=e,this.logger=r||new Logger$1}getUrl(e){return e.activeUrl=e.url||e.dcurl||e.wturl,this.options.token&&(e.activeUrl+=`?token=${this.options.token}`),e.activeUrl}raceConnect(){return __awaiter(this,void 0,void 0,(function*(){let e=this.proxies;if(this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}this.connectingTimers={};const t=`.connecting${Math.random()}`;return new Promise(((i,r)=>{let n=!1;this.connectCount=0;const s=(e,s)=>{n?e.destroy():this.closed?(each$4(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.warn("signal open after call close function, reject"),r("signal has already closed")):(n=!0,each$4(this.connectingTimers,((e,t)=>{clearTimeout(e.timer),e.channel&&t!=s&&e.channel.destroy()})),this.connectingTimers={},e.off(t),this.connectCount=e.getTransportConnectCount(),i(e))};let o=0;const a=()=>{++o===e.length&&(each$4(this.connectingTimers,(e=>{e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.error("connect all proxies failed"),r("connect all proxies failed"))},c=(e,i)=>{const r=new Channel(e,{maxRetry:5,transport:void 0,transportOptions:{},tag:"Client",logLevel:DEBUG$1$1},i,this.logger);r.one(CONNECTED+t,(()=>{i.consume=r.getConsume(),this.connectCount=r.getTransportConnectCount(),s(r,e)})).one(RECONNECTED$1+t,(()=>{i.consume=r.getConsume(),this.connectCount=r.getTransportConnectCount(),s(r,e)})).one(ERROR$1+t,(()=>{this.connectCount=r.getTransportConnectCount(),a()})).one(TIMEOUT$1+t,(()=>{this.connectCount=r.getTransportConnectCount(),a()})),this.connectingTimers[e].channel=r};each$1$1(e,(e=>{const t=e.delay?toNumber$1(e.delay):0,i=this.getUrl(e);i&&(this.connectingTimers[i]={timer:setTimeout((()=>{c(i,e)}),t)})}))}))}))}queueConnect(){return __awaiter(this,void 0,void 0,(function*(){let e=this.proxies;if(this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}const t=`.connecting${Math.random()}`;return new Promise(((i,r)=>{let n=0;this.connectCount=0;const s=()=>{this.closed&&r("signal has closed");const o=e[n],a=this.getUrl(o);a||r("url can not be empty!");const c=this.connectingChannel=new Channel(a,{maxRetry:3,transport:void 0,transportOptions:{},tag:"Client",logLevel:DEBUG$1$1},o,this.logger);c.one(CONNECTED+t,(()=>{c.off(t),this.connectingChannel=void 0,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),i(c)})).one(RECONNECTED$1+t,(()=>{c.off(t),this.connectingChannel=void 0,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),i(c)})).one(ERROR$1+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=void 0,this.logger.error(`queue connect proxy: ${n} ${a} error`),this.fire(STATE_NOTIFY,[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} error`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,r("connect all proxies failed")):setTimeout((()=>{s()}),1e3)})).one(TIMEOUT$1+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=void 0,this.logger.error(`queue connect proxy: ${n} ${a} timeout`),this.fire(STATE_NOTIFY,[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} timeout`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,r("connect all proxies failed")):setTimeout((()=>{s()}),1e3)}))};s()}))}))}connect(){return __awaiter(this,void 0,void 0,(function*(){if(!this.proxies.length)return new Error("not has any proxy to connect");this.isConnecting=!0,this.options.enableRace?this.channel=yield this.raceConnect():this.channel=yield this.queueConnect(),this.channel.on(ERROR$1,(()=>{this.logger.error(`proxy connect error, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(ERROR$1)})).on(CLOSE,(()=>{this.logger.error(`proxy connect close, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(CLOSE)})).on(TIMEOUT$1,(()=>{this.logger.error(`proxy connect timeout, proxy: ${JSON.stringify(this.getProxy())}`),this.fire(TIMEOUT$1)})).on(CONNECTED,(()=>{this.fire(CONNECTED)})).on(RECONNECTING$1,(()=>{this.fire(RECONNECTING$1)})).on(RECONNECTED$1,(()=>{if(this.isLeaving)return;this.fire(RECONNECTED$1),this.channel.syncNotify();const e=this.channel.getProxy();e&&(e.consume=this.channel.getConsume())})).on(NOTIFY,((e,t,i)=>{this.channel.notified=i,this.channel.resetTimeout(),EventMap[e]?this.fire(EventMap[e],[t]):this.fire(NOTIFY,[{method:e,params:t}])})).on(REQUEST,(e=>__awaiter(this,void 0,void 0,(function*(){if(e.method&&this.rpc[e.method]){this.channel.resetTimeout();const{error:t,result:i}=yield this.rpc[e.method](e);this.channel.reply(e,i,t)}})))).on(SESSION_CLOED,(()=>{this.fire(SESSION_CLOED)})),this.isConnecting=!1,this.logger.info(`connect proxy success, proxy: ${JSON.stringify(this.channel.getProxy())}`)}))}request(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request(e,t)}))}join(e){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("joinRoom",e).then((e=>(this.channel.resetTimeout(),this.isLeaving=!1,e)))}))}leave(e){return __awaiter(this,void 0,void 0,(function*(){return this.isLeaving=!0,this.channel.request("leaveRoom",e,{timeout:3e3}).then((e=>(this.isLeaving=!1,e)))}))}syncRoom(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("syncRoom",{roomId:e,userId:t,info:i})}))}updateCustomStats(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("updateCustomStats",{roomId:e,userId:t,options:i.customStats,replace:r})}))}releaseRoom(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("releaseRoom",{roomId:e,userId:t})}))}updateRoom(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("updateRoom",{roomId:e,userId:t,options:i})}))}updateUser(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("updateUser",{roomId:e,userId:t,info:i})}))}evictUser(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("evictUser",{roomId:e,userId:t,evictId:i,withoutBlack:r})}))}changeMaster(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("changeMaster",{roomId:e,userId:t,master:i,isKeep:r})}))}leaveRoom(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("leaveRoom",{roomId:e,userId:t,desc:i})}))}getUsers(e,t,i,r,n,s){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("getUsers",{roomId:e,userId:t,pagesize:i,index:r,permission:n,waitRoom:s})}))}getUsersList(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("getUserList",{pagesize:t,index:e,permission:i,waitRoom:r})}))}queryUsers(e){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("queryUsers",{userIds:e})}))}publishStream(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("publishStream",{roomId:e,userId:t,streamId:i,options:r})}))}controlStream(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("controlStream",{roomId:e,userId:t,streamId:i,options:r})}))}resetStream(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("resetStream",{roomId:e,userId:t,streamId:i,options:r})}))}unpublishStream(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("unpublishStream",{roomId:e,userId:t,streamId:i})}))}getMessages(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("getMessages",{roomId:e,userId:t})}))}sendMessage(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("sendMessage",{roomId:e,userId:t,to:i,msg:r})}))}customMessage(e,t,i,r){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("customMessage",{roomId:e,userId:t,to:i,msg:r})}))}startRecord(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("startRecord",{roomId:e,streamId:t,options:i})}))}stopRecord(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("stopRecord",{roomId:e,streamId:t})}))}searchUsers(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("searchUsers",{nickname:e,pageSize:t,waitRoom:i})}))}syncUser(e){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("syncUser",{pageSize:e})}))}moveUserRoom(e,t,i){return __awaiter(this,void 0,void 0,(function*(){return this.channel.request("moveUserRoom",{target:e,toWait:t,autoJoin:i})}))}close(){this.connectingChannel&&this.connectingChannel.destroy(),keys(this.connectingTimers).length&&(each$4(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={}),this.channel&&this.channel.destroy(),this.closed=!0,this.off()}getSessionId(){var e;return null===(e=this.channel)||void 0===e?void 0:e.sessionId}getProxy(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getProxy()}getConnectCount(){return this.connectCount}getConnectedProxyConsume(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getConsume()}}const getBrowser$1=()=>{const e=getUserAgent$1();let t="none";return null!==e.match("fake")?t="fake":null!==e.match("ios")?t="ios":null!==e.match("android")?t="android":null!==e.match("Firefox")?t="mozilla":null!==e.match("Chrome")?(t="chrome-stable",null!==e.match("Electron")&&(t="electron")):(null!==e.match("Safari")||null!==e.match("AppleWebKit"))&&(t="safari"),t},getUserAgent$1=()=>window.navigator.userAgent;class Permission{constructor(e){this.permission=e||Permission.default}getRead(){return this.permission.indexOf("R")>=0}getWrite(){return this.permission.indexOf("W")>=0}getPublish(){return this.permission.indexOf("P")>=0}getSubscribe(){return this.permission.indexOf("S")>=0}getManage(){return this.permission.indexOf("M")>=0}getAudio(){return this.permission.indexOf("A")>=0}getVideo(){return this.permission.indexOf("V")>=0}getOwn(){return this.permission.indexOf("O")>=0}setManage(e){this._update("M",e)}setSubscribe(e){this._update("S",e)}setPublish(e){this._update("P",e)}setWrite(e){this._update("W",e)}setRead(e){this._update("R",e)}setAudio(e){this._update("A",e)}setVideo(e){this._update("V",e)}setOwn(e){this._update("O",e)}set(e){this.permission=e}get(){return this.permission}_update(e,t){t?this.permission.indexOf(e)<0&&(this.permission+=e):this.permission=this.permission.replace(e,"")}}Permission.default="RWPSAV";var global$1=void 0!==global$2?global$2:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal$2="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeGlobal$1$1=freeGlobal$2,freeSelf$1="object"==typeof self&&self&&self.Object===Object&&self,root$2=freeGlobal$1$1||freeSelf$1||Function("return this")(),root$1$1=root$2,Symbol$1$1=root$1$1.Symbol,Symbol$1$1$1=Symbol$1$1,objectProto$7=Object.prototype,hasOwnProperty$5=objectProto$7.hasOwnProperty,nativeObjectToString$1$1=objectProto$7.toString,symToStringTag$1$1=Symbol$1$1$1?Symbol$1$1$1.toStringTag:void 0;function getRawTag$1(e){var t=hasOwnProperty$5.call(e,symToStringTag$1$1),i=e[symToStringTag$1$1];try{e[symToStringTag$1$1]=void 0;var r=!0}catch(e){}var n=nativeObjectToString$1$1.call(e);return r&&(t?e[symToStringTag$1$1]=i:delete e[symToStringTag$1$1]),n}var objectProto$6=Object.prototype,nativeObjectToString$2=objectProto$6.toString;function objectToString$1(e){return nativeObjectToString$2.call(e)}var nullTag$1="[object Null]",undefinedTag$1="[object Undefined]",symToStringTag$2=Symbol$1$1$1?Symbol$1$1$1.toStringTag:void 0;function baseGetTag$1(e){return null==e?void 0===e?undefinedTag$1:nullTag$1:symToStringTag$2&&symToStringTag$2 in Object(e)?getRawTag$1(e):objectToString$1(e)}function isObjectLike$1(e){return null!=e&&"object"==typeof e}var isArray=Array.isArray,isArray$1=isArray;function isObject$1(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function identity$1(e){return e}var asyncTag="[object AsyncFunction]",funcTag$1="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction$1(e){if(!isObject$1(e))return!1;var t=baseGetTag$1(e);return t==funcTag$1||t==genTag||t==asyncTag||t==proxyTag}var coreJsData=root$1$1["__core-js_shared__"],coreJsData$1=coreJsData,maskSrcKey=(uid=/[^.]+$/.exec(coreJsData$1&&coreJsData$1.keys&&coreJsData$1.keys.IE_PROTO||""),uid?"Symbol(src)_1."+uid:""),uid;function isMasked(e){return!!maskSrcKey&&maskSrcKey in e}var funcProto$1=Function.prototype,funcToString$1=funcProto$1.toString;function toSource(e){if(null!=e){try{return funcToString$1.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,funcProto=Function.prototype,objectProto$5=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$4=objectProto$5.hasOwnProperty,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty$4).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(e){return!(!isObject$1(e)||isMasked(e))&&(isFunction$1(e)?reIsNative:reIsHostCtor).test(toSource(e))}function getValue(e,t){return null==e?void 0:e[t]}function getNative(e,t){var i=getValue(e,t);return baseIsNative(i)?i:void 0}function apply(e,t,i){switch(i.length){case 0:return e.call(t);case 1:return e.call(t,i[0]);case 2:return e.call(t,i[0],i[1]);case 3:return e.call(t,i[0],i[1],i[2])}return e.apply(t,i)}var HOT_COUNT=800,HOT_SPAN=16,nativeNow=Date.now;function shortOut(e){var t=0,i=0;return function(){var r=nativeNow(),n=HOT_SPAN-(r-i);if(i=r,n>0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function constant(e){return function(){return e}}var defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),defineProperty$1=defineProperty,baseSetToString=defineProperty$1?function(e,t){return defineProperty$1(e,"toString",{configurable:!0,enumerable:!1,value:constant(t),writable:!0})}:identity$1,baseSetToString$1=baseSetToString,setToString=shortOut(baseSetToString$1),setToString$1=setToString,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(e,t){var i=typeof e;return!!(t=null==t?MAX_SAFE_INTEGER$1:t)&&("number"==i||"symbol"!=i&&reIsUint.test(e))&&e>-1&&e%1==0&&e<t}function eq(e,t){return e===t||e!=e&&t!=t}var nativeMax$1=Math.max;function overRest(e,t,i){return t=nativeMax$1(void 0===t?e.length-1:t,0),function(){for(var r=arguments,n=-1,s=nativeMax$1(r.length-t,0),o=Array(s);++n<s;)o[n]=r[t+n];n=-1;for(var a=Array(t+1);++n<t;)a[n]=r[n];return a[t]=i(o),apply(e,this,a)}}function baseRest(e,t){return setToString$1(overRest(e,t,identity$1),e+"")}var MAX_SAFE_INTEGER=9007199254740991;function isLength(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction$1(e)}function isIterateeCall(e,t,i){if(!isObject$1(i))return!1;var r=typeof t;return!!("number"==r?isArrayLike(i)&&isIndex(t,i.length):"string"==r&&t in i)&&eq(i[t],e)}var objectProto$4=Object.prototype;function isPrototype(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||objectProto$4)}function baseTimes(e,t){for(var i=-1,r=Array(e);++i<e;)r[i]=t(i);return r}var argsTag$1="[object Arguments]";function baseIsArguments(e){return isObjectLike$1(e)&&baseGetTag$1(e)==argsTag$1}var objectProto$3=Object.prototype,hasOwnProperty$3=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(e){return isObjectLike$1(e)&&hasOwnProperty$3.call(e,"callee")&&!propertyIsEnumerable.call(e,"callee")},isArguments$1=isArguments;function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer=moduleExports$1?root$1$1.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,isBuffer$1=isBuffer,argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag$1="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike$1(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag$1(e)]}function baseUnary(e){return function(t){return e(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag$1]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal$1$1.process,nodeUtil=function(){try{return freeModule&&freeModule.require&&freeModule.require("util").types||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeUtil$1=nodeUtil,nodeIsTypedArray=nodeUtil$1&&nodeUtil$1.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,isTypedArray$1=isTypedArray,objectProto$2=Object.prototype,hasOwnProperty$2=objectProto$2.hasOwnProperty;function arrayLikeKeys(e,t){var i=isArray$1(e),r=!i&&isArguments$1(e),n=!i&&!r&&isBuffer$1(e),s=!i&&!r&&!n&&isTypedArray$1(e),o=i||r||n||s,a=o?baseTimes(e.length,String):[],c=a.length;for(var u in e)!t&&!hasOwnProperty$2.call(e,u)||o&&("length"==u||n&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||isIndex(u,c))||a.push(u);return a}function nativeKeysIn(e){var t=[];if(null!=e)for(var i in Object(e))t.push(i);return t}var objectProto$1$1=Object.prototype,hasOwnProperty$1=objectProto$1$1.hasOwnProperty;function baseKeysIn(e){if(!isObject$1(e))return nativeKeysIn(e);var t=isPrototype(e),i=[];for(var r in e)("constructor"!=r||!t&&hasOwnProperty$1.call(e,r))&&i.push(r);return i}function keysIn(e){return isArrayLike(e)?arrayLikeKeys(e,!0):baseKeysIn(e)}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty,defaults=baseRest((function(e,t){e=Object(e);var i=-1,r=t.length,n=r>2?t[2]:void 0;for(n&&isIterateeCall(t[0],t[1],n)&&(r=1);++i<r;)for(var s=t[i],o=keysIn(s),a=-1,c=o.length;++a<c;){var u=o[a],d=e[u];(void 0===d||eq(d,objectProto$8[u])&&!hasOwnProperty$6.call(e,u))&&(e[u]=s[u])}return e})),defaults$1=defaults;class Participant{constructor(e,t,i){this.streams=new Map,this.local=e,this.userId=t,this.params=i;let r=i.permission;!r&&i.info&&(r=i.info.permission),r||(r=Permission.default),this.permission=new Permission(r)}setID(e){this.userId=e}getID(){return this.userId}getPermission(){return this.permission}getUserInfo(){var e,t;return null!==(t=null!==(e=this.params.userinfo)&&void 0!==e?e:this.params.info.userinfo)&&void 0!==t?t:{}}update(e){e.permission&&this.permission.set(e.permission),this.params=defaults$1(e,this.params)}getNickName(){var e,t;return null!==(t=null!==(e=this.params.nickname)&&void 0!==e?e:this.params.info.nickname)&&void 0!==t?t:""}getStreams(){return this.streams}getStream(e){return this.streams.get(e)}addStream(e){this.streams.set(e.getID(),e)}removeStream(e){this.streams.delete(e)}}const BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Utils{static getFirstMatch(e,t){const i=t.match(e);return i&&i.length>0&&i[1]||""}static getSecondMatch(e,t){const i=t.match(e);return i&&i.length>1&&i[2]||""}static matchAndReturnConst(e,t,i){if(e.test(t))return i}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,i=!1){const r=Utils.getVersionPrecision(e),n=Utils.getVersionPrecision(t);let s=Math.max(r,n),o=0;const a=Utils.map([e,t],(e=>{const t=s-Utils.getVersionPrecision(e),i=e+new Array(t+1).join(".0");return Utils.map(i.split("."),(e=>new Array(20-e.length).join("0")+e)).reverse()}));for(i&&(o=s-Math.min(r,n)),s-=1;s>=o;){if(a[0][s]>a[1][s])return 1;if(a[0][s]===a[1][s]){if(s===o)return 0;s-=1}else if(a[0][s]<a[1][s])return-1}}static map(e,t){const i=[];let r;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)i.push(t(e[r]));return i}static find(e,t){let i,r;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(i=0,r=e.length;i<r;i+=1){const r=e[i];if(t(r,i))return r}}static assign(e,...t){const i=e;let r,n;if(Object.assign)return Object.assign(e,...t);for(r=0,n=t.length;r<n;r+=1){const e=t[r];"object"==typeof e&&null!==e&&Object.keys(e).forEach((t=>{i[t]=e[t]}))}return e}static getBrowserAlias(e){return BROWSER_ALIASES_MAP[e]}static getBrowserTypeByAlias(e){return BROWSER_MAP[e]||""}}const commonVersionIdentifier=/version\/(\d+(\.?_?\d+)+)/i,browsersList=[{test:[/googlebot/i],describe(e){const t={name:"Googlebot"},i=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/opera/i],describe(e){const t={name:"Opera"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/opr\/|opios/i],describe(e){const t={name:"Opera"},i=Utils.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:"Samsung Internet for Android"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/Whale/i],describe(e){const t={name:"NAVER Whale Browser"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/MZBrowser/i],describe(e){const t={name:"MZ Browser"},i=Utils.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/focus/i],describe(e){const t={name:"Focus"},i=Utils.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/swing/i],describe(e){const t={name:"Swing"},i=Utils.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/coast/i],describe(e){const t={name:"Opera Coast"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(e){const t={name:"Opera Touch"},i=Utils.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/yabrowser/i],describe(e){const t={name:"Yandex Browser"},i=Utils.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/ucbrowser/i],describe(e){const t={name:"UC Browser"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:"Maxthon"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/epiphany/i],describe(e){const t={name:"Epiphany"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/puffin/i],describe(e){const t={name:"Puffin"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/sleipnir/i],describe(e){const t={name:"Sleipnir"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/k-meleon/i],describe(e){const t={name:"K-Meleon"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/micromessenger/i],describe(e){const t={name:"WeChat"},i=Utils.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},i=Utils.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/msie|trident/i],describe(e){const t={name:"Internet Explorer"},i=Utils.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/\sedg\//i],describe(e){const t={name:"Microsoft Edge"},i=Utils.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:"Microsoft Edge"},i=Utils.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/vivaldi/i],describe(e){const t={name:"Vivaldi"},i=Utils.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/seamonkey/i],describe(e){const t={name:"SeaMonkey"},i=Utils.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/sailfish/i],describe(e){const t={name:"Sailfish"},i=Utils.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return i&&(t.version=i),t}},{test:[/silk/i],describe(e){const t={name:"Amazon Silk"},i=Utils.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/phantom/i],describe(e){const t={name:"PhantomJS"},i=Utils.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/slimerjs/i],describe(e){const t={name:"SlimerJS"},i=Utils.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t={name:"BlackBerry"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:"WebOS Browser"},i=Utils.getFirstMatch(commonVersionIdentifier,e)||Utils.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/bada/i],describe(e){const t={name:"Bada"},i=Utils.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/tizen/i],describe(e){const t={name:"Tizen"},i=Utils.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/qupzilla/i],describe(e){const t={name:"QupZilla"},i=Utils.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:"Firefox"},i=Utils.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/electron/i],describe(e){const t={name:"Electron"},i=Utils.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:"Miui"},i=Utils.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/chromium/i],describe(e){const t={name:"Chromium"},i=Utils.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:"Chrome"},i=Utils.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/GSA/i],describe(e){const t={name:"Google Search"},i=Utils.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test(e){const t=!e.test(/like android/i),i=e.test(/android/i);return t&&i},describe(e){const t={name:"Android Browser"},i=Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/playstation 4/i],describe(e){const t={name:"PlayStation 4"},i=Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:"Safari"},i=Utils.getFirstMatch(commonVersionIdentifier,e);return i&&(t.version=i),t}},{test:[/.*/i],describe(e){const t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Utils.getFirstMatch(t,e),version:Utils.getSecondMatch(t,e)}}}];var osParsersList=[{test:[/Roku\/DVP/],describe(e){const t=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=Utils.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),i=Utils.getWindowsVersionName(t);return{name:OS_MAP.Windows,version:t,versionName:i}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(e){const t={name:OS_MAP.iOS},i=Utils.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return i&&(t.version=i),t}},{test:[/macintosh/i],describe(e){const t=Utils.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),i=Utils.getMacOSVersionName(t),r={name:OS_MAP.MacOS,version:t};return i&&(r.versionName=i),r}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=Utils.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:OS_MAP.iOS,version:t}}},{test(e){const t=!e.test(/like android/i),i=e.test(/android/i);return t&&i},describe(e){const t=Utils.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),i=Utils.getAndroidVersionName(t),r={name:OS_MAP.Android,version:t};return i&&(r.versionName=i),r}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),i={name:OS_MAP.WebOS};return t&&t.length&&(i.version=t),i}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t=Utils.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||Utils.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||Utils.getFirstMatch(/\bbb(\d+)/i,e);return{name:OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:()=>({name:OS_MAP.Linux})},{test:[/CrOS/],describe:()=>({name:OS_MAP.ChromeOS})},{test:[/PlayStation 4/],describe(e){const t=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:OS_MAP.PlayStation4,version:t}}}],platformParsersList=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(e){const t=Utils.getFirstMatch(/(can-l01)/i,e)&&"Nova",i={type:PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(i.model=t),i}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:PLATFORMS_MAP.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:PLATFORMS_MAP.tablet})},{test(e){const t=e.test(/ipod|iphone/i),i=e.test(/like (ipod|iphone)/i);return t&&!i},describe(e){const t=Utils.getFirstMatch(/(ipod|iphone)/i,e);return{type:PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"blackberry"===e.getBrowserName(!0),describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"BlackBerry"})},{test:e=>"bada"===e.getBrowserName(!0),describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"windows phone"===e.getBrowserName(),describe:()=>({type:PLATFORMS_MAP.mobile,vendor:"Microsoft"})},{test(e){const t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:()=>({type:PLATFORMS_MAP.tablet})},{test:e=>"android"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.mobile})},{test:e=>"macos"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop,vendor:"Apple"})},{test:e=>"windows"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop})},{test:e=>"linux"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.desktop})},{test:e=>"playstation 4"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.tv})},{test:e=>"roku"===e.getOSName(!0),describe:()=>({type:PLATFORMS_MAP.tv})}],enginesParsersList=[{test:e=>"microsoft edge"===e.getBrowserName(!0),describe(e){if(/\sedg\//i.test(e))return{name:ENGINE_MAP.Blink};const t=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe(e){const t={name:ENGINE_MAP.Trident},i=Utils.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:e=>e.test(/presto/i),describe(e){const t={name:ENGINE_MAP.Presto},i=Utils.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test(e){const t=e.test(/gecko/i),i=e.test(/like gecko/i);return t&&!i},describe(e){const t={name:ENGINE_MAP.Gecko},i=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:ENGINE_MAP.Blink})},{test:[/(apple)?webkit/i],describe(e){const t={name:ENGINE_MAP.WebKit},i=Utils.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}}];class Parser{constructor(e,t=!1){if(null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=Utils.find(browsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=Utils.find(osParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=Utils.find(platformParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=Utils.find(enginesParsersList,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Utils.assign({},this.parsedResult)}satisfies(e){const t={};let i=0;const r={};let n=0;if(Object.keys(e).forEach((s=>{const o=e[s];"string"==typeof o?(r[s]=o,n+=1):"object"==typeof o&&(t[s]=o,i+=1)})),i>0){const e=Object.keys(t),i=Utils.find(e,(e=>this.isOS(e)));if(i){const e=this.satisfies(t[i]);if(void 0!==e)return e}const r=Utils.find(e,(e=>this.isPlatform(e)));if(r){const e=this.satisfies(t[r]);if(void 0!==e)return e}}if(n>0){const e=Object.keys(r),t=Utils.find(e,(e=>this.isBrowser(e,!0)));if(void 0!==t)return this.compareVersion(r[t])}}isBrowser(e,t=!1){const i=this.getBrowserName().toLowerCase();let r=e.toLowerCase();const n=Utils.getBrowserTypeByAlias(r);return t&&n&&(r=n.toLowerCase()),r===i}compareVersion(e){let t=[0],i=e,r=!1;const n=this.getBrowserVersion();if("string"==typeof n)return">"===e[0]||"<"===e[0]?(i=e.substr(1),"="===e[1]?(r=!0,i=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?i=e.substr(1):"~"===e[0]&&(r=!0,i=e.substr(1)),t.indexOf(Utils.compareVersions(n,i,r))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some((e=>this.is(e)))}}
|
|
2
|
-
/*!
|
|
3
|
-
* Bowser - a browser detector
|
|
4
|
-
* https://github.com/lancedikson/bowser
|
|
5
|
-
* MIT License | (c) Dustin Diaz 2012-2015
|
|
6
|
-
* MIT License | (c) Denis Demchenko 2015-2019
|
|
7
|
-
*/class Bowser{static getParser(e,t=!1){if("string"!=typeof e)throw new Error("UserAgent should be a string");return new Parser(e,t)}static parse(e){return new Parser(e).getResult()}static get BROWSER_MAP(){return BROWSER_MAP}static get ENGINE_MAP(){return ENGINE_MAP}static get OS_MAP(){return OS_MAP}static get PLATFORMS_MAP(){return PLATFORMS_MAP}}const userAgent=()=>{let e;try{e=require("react-native").Platform}catch(e){}let t="none";return"undefined"!=typeof module&&module.exports?e?"ios"===e.OS?t="ios":"android"===e.OS&&(t="android"):t="fake":t=window.navigator.userAgent,t},isMobile=()=>{let e;try{e=require("react-native").Platform}catch(e){}let t=!1;return"undefined"!=typeof module&&module.exports&&e&&("ios"===e.OS||"android"===e.OS)&&(t=!0),t},isElectron=()=>!1,VLBrowser={userAgent:userAgent,isMobile:isMobile,isElectron:isElectron},CHROME="chrome",OPERA="opera",FIREFOX="firefox",INTERNET_EXPLORER="iexplorer",SAFARI="safari",NWJS="nwjs",ELECTRON="electron",REACT_NATIVE="react-native",UNKNOWN="unknown",WECHAT="wechat";var browsers=Object.freeze({__proto__:null,CHROME:CHROME,OPERA:OPERA,FIREFOX:FIREFOX,INTERNET_EXPLORER:INTERNET_EXPLORER,SAFARI:SAFARI,NWJS:NWJS,ELECTRON:ELECTRON,REACT_NATIVE:REACT_NATIVE,UNKNOWN:UNKNOWN,WECHAT:WECHAT});const bowserNameToJitsiName={Chrome:CHROME,Chromium:CHROME,Opera:OPERA,Firefox:FIREFOX,"Internet Explorer":INTERNET_EXPLORER,Safari:SAFARI,WeChat:WECHAT};var UserAgentLocal=navigator.userAgent;function _detectChromiumBased(){const e=UserAgentLocal,t={name:UNKNOWN,version:void 0};if(e.match(/Chrome/)&&!e.match(/Edge/))if(e.match(/Edg/)){const i=e.match(/Edg\/([\d.]+)/)[1];Number.parseInt(i,10)>72&&(t.name=CHROME,t.version=i)}else t.name=CHROME,t.version=e.match(/Chrome\/([\d.]+)/)[1];return t}function _detectElectron(){const e=UserAgentLocal;if(e.match(/Electron/)){const t=e.match(/Electron\/([\d.]+)/)[1];return{name:ELECTRON,version:t}}}function _detectNWJS(){const e=UserAgentLocal;if(e.match(/JitsiMeetNW/)){const t=e.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:NWJS,version:t}}}function _detectWeChat(){const e=UserAgentLocal;if(e.match(/MicroMessenger/)){const t=e.match(/MicroMessenger\/([\d.]+)/)[1];return{name:WECHAT,version:t}}}function _detectReactNative(){const e=UserAgentLocal.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(e||"ReactNative"===navigator.product)return e&&e.length>2&&(t=e[2]),t||(t="unknown"),{name:REACT_NATIVE,version:t}}function _detect(e){let t;const i=[_detectReactNative,_detectElectron,_detectNWJS,_detectWeChat];for(let e=0;e<i.length;e++)if(t=i[e](),t)return t;const r=e.getBrowserName();return r in bowserNameToJitsiName?{name:bowserNameToJitsiName[r],version:e.getBrowserVersion()}:(t=_detectChromiumBased(),t||{name:UNKNOWN,version:void 0})}navigator.userAgent||(UserAgentLocal=navigator.product);class BrowserDetection{constructor(e){let t,i;if(this.browsers=browsers,this._bowser=Bowser.getParser(UserAgentLocal),void 0===e){const e=_detect(this._bowser);t=e.name,i=e.version}else e.name in bowserNameToJitsiName?(t=bowserNameToJitsiName[e.name],i=e.version):(t=UNKNOWN,i=void 0);this._name=t,this._version=i}getName(){return this._name}isChrome(){return this._name===CHROME}isOpera(){return this._name===OPERA}isFirefox(){return this._name===FIREFOX}isIExplorer(){return this._name===INTERNET_EXPLORER}isSafari(){return this._name===SAFARI}isNWJS(){return this._name===NWJS}isElectron(){return this._name===ELECTRON}isReactNative(){return this._name===REACT_NATIVE}getVersion(){return this._version}_checkCondition(e){if(this._version)return this._bowser.satisfies(e)}isVersionGreaterThan(e){return this._checkCondition({[this._name]:`>${e}`})}isVersionLessThan(e){return this._checkCondition({[this._name]:`<${e}`})}isVersionEqualTo(e){return this._checkCondition({[this._name]:`~${e}`})}}const mediaDevices=()=>{let e;try{e=require("react-native-webrtc").mediaDevices}catch(t){e=navigator.mediaDevices}return e},PRTCPeerConnection=()=>{let e;try{e=require("react-native-webrtc").RTCPeerConnection}catch(t){e=RTCPeerConnection}return e},VLWebRtc={mediaDevices:mediaDevices,PRTCPeerConnection:PRTCPeerConnection},Logger=Logger$1.Log(),getBrowser=()=>{let e="none";return null!==VLBrowser.userAgent().match("fake")?e="fake":null!==VLBrowser.userAgent().match("ios")?e="ios":null!==VLBrowser.userAgent().match("android")?e="android":null!==VLBrowser.userAgent().match("Firefox")?e="mozilla":null!==VLBrowser.userAgent().match("Chrome")?(e="chrome-stable",null!==VLBrowser.userAgent().match("Electron")&&(e="electron")):(null!==VLBrowser.userAgent().match("Safari")||null!==VLBrowser.userAgent().match("AppleWebKit"))&&(e="safari"),e},getUserAgent=()=>window.navigator.userAgent,GetUserMediaCb=(e,t=(()=>{}),i=(()=>{}))=>{let r,n=VLWebRtc.mediaDevices();const s=(e,t,i)=>{n.getUserMedia(e).then(t).catch(i)};e.screen?(()=>{switch(Logger.debug("Screen access requested"),getBrowser()){case"electron":Logger.debug("Screen sharing in Electron"),r={},r.video=e.video||{},r.video.mandatory=e.video.mandatory||{},r.video.mandatory.chromeMediaSource="desktop",r.video.mandatory.chromeMediaSourceId=e.desktopStreamId,s(r,t,i);break;case"mozilla":case"mozilla":Logger.debug("Screen sharing in Firefox"),r={},void 0!==e.video?(r.video=e.video,r.video.mediaSource||(r.video.mediaSource="window")):r={audio:e.audio,video:{mediaSource:"window"}},s(r,t,i);break;case"chrome-stable":Logger.debug("Screen sharing in Chrome"),r={},e.desktopStreamId&&(r.video=e.video||{mandatory:{}},r.video.mandatory=r.video.mandatory||{},r.video.mandatory.chromeMediaSource="desktop",r.video.mandatory.chromeMediaSourceId=e.desktopStreamId,s(r,t,i));break;case"chrome-stable":if(Logger.debug("Screen sharing in Chrome"),r={},e.desktopStreamId)r.video=e.video||{mandatory:{}},r.video.mandatory=r.video.mandatory||{},r.video.mandatory.chromeMediaSource="desktop",r.video.mandatory.chromeMediaSourceId=e.desktopStreamId,s(r,t,i);else{let n="jbglfdfehfdcpnbhfnciaiokkfocjcjk";e.extensionId&&(Logger.debug(`extensionId supplied, using ${e.extensionId}`),n=e.extensionId),Logger.debug("Screen access on chrome stable, looking for extension");try{chrome.runtime.sendMessage(n,{getStream:!0},(n=>{if(void 0===n)return Logger.error("Access to screen denied"),void i({code:"Access to screen denied"});const o=n.streamId;void 0!==e.video.mandatory?(r.video=e.video||{mandatory:{}},r.video.mandatory.chromeMediaSource="desktop",r.video.mandatory.chromeMediaSourceId=o):r={video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:o}}},s(r,t,i)}))}catch(e){Logger.debug("Screensharing plugin is not accessible "),i({code:"no_plugin_present"})}}break;default:Logger.error("This browser does not support ScreenSharing")}})():(Logger.debug("Calling getUserMedia with config",e),s(e,t,i))};function formatVideoTrack$1(e,t){if(!t)return e;let i=e.getVideoTracks()[0];if(!i)return e;if("function"!=typeof i.getCapabilities)return e;let r=i.getConstraints(),n=e.clone();return i=n.getVideoTracks()[0],i?(e.getTracks().forEach((e=>e.stop())),r.width,r.height,r.frameRate=t||r.frameRate,i.applyConstraints(r),n):(n.getTracks().forEach((e=>e.stop())),e)}let GetUserMedia=e=>new Promise(((t,i)=>{GetUserMediaCb(e,(i=>{(new BrowserDetection).isReactNative()&&t(i),e.fps&&i.clone?t(formatVideoTrack$1(i,e.fps)):t(i)}),(e=>{i(e)}))}));const ConnectionHelpers={GetUserMedia:GetUserMedia,getBrowser:getBrowser,getUserAgent:getUserAgent},errors={ERR_NOT_INSTALLED:1,ERR_NOT_FOUND:10,ERR_TIMEOUT:11,ERR_STATS:12,ERR_NO_SERVICE:13,ERR_AUTH:14,ERR_INVALID_REQUEST:15,ERR_METHOD:16,ERR_NOT_STARTUP:17,ERR_CUSTOM_AUTH_FAILED:18,ERR_USER_LIMIT:19,ERR_QDTLS:20,ERR_OVEVLOAD:21,ERR_EVICTED:22,ERR_PERMISSION:23,ERR_SENSITIVE_WORD:24,ERR_NOT_AT_ROOM:25,ERR_MEDIA_PIPELINE:26,ERR_NO_STREAM:27,ERR_LOCKED:28,ERR_UNKNOWN:33};function formatVideoTrack(e,t,i,r=15){if(!t||!i)return e;let n=e.getVideoTracks()[0];if(!n)return e;if("function"!=typeof n.getCapabilities)return e;let s=n.getConstraints(),o=n.getCapabilities(),a=o.width.max,c=o.height.max;if((a<=t||c<=i)&&!r)return e;let u=e.clone();if(n=u.getVideoTracks()[0],!n)return u.getTracks().forEach((e=>e.stop())),e;e.getTracks().forEach((e=>e.stop()));let d=t,l=i,h=1*a/c,m=1*t/i;return h>m?l=Math.floor(1*c/a*t):d=Math.floor(h*i),l>1600&&(l=1600,d=1600*m),d%2&&(d-=1),l%2&&(l-=1),n.applyConstraints({width:{min:0,ideal:d},height:{min:0,ideal:l},frameRate:r||s.frameRate}).catch((e=>{console.log("track.applyConstraints error")})),u}class ChromeScreenShare{constructor(){this._stream=null,this.avaliable=!0}check(){return new Promise(((e,t)=>{chrome.runtime.sendMessage({check:!0},(i=>{""!=i.id&&null!=i.id?e(i.id):t("not plugin")}))}))}detect(e){return new Promise(((t,i)=>{var r=document.createElement("img");r.src="chrome-extension://"+e+"/icon.png",r.onload=function(){t()},r.onerror=function(){i({code:errors.ERR_NOT_INSTALLED,error:"not-installed"})}}))}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this;let i=e.extensionId||"jbglfdfehfdcpnbhfnciaiokkfocjcjk";return this.detect(i).then((()=>new Promise(((r,n)=>{chrome.runtime.sendMessage(i,{getStream:!0},(i=>{if(void 0===i)return Logger$1.Log().error("Access to screen denied"),void error({code:"Access to screen denied"});const s=t._toConstraints(e,i.streamId);ConnectionHelpers.GetUserMedia(s).then((e=>{t._stream=e,r(t._stream)})).catch((e=>{n(e)}))}))})))).catch((e=>{Logger$1.Log().warn("onerror plugin"),reject(e)}))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return this.avaliable}needExtension(){return!this.avaliable}_toConstraints(e,t){const i={video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t},optional:[{googTemporalLayeredScreencast:!0}]},audio:!1};return isFinite(e.width)&&(i.video.mandatory.maxWidth=e.width,i.video.mandatory.minWidth=e.width),isFinite(e.height)&&(i.video.mandatory.maxHeight=e.height,i.video.mandatory.minHeight=e.height),isFinite(e.frameRate)&&(i.video.mandatory.maxFrameRate=e.frameRate,i.video.mandatory.minFrameRate=e.frameRate),i}}class Chrome72ScreenShare{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this._toConstraints(e);return navigator.mediaDevices.getDisplayMedia(t).then((e=>(this._stream=e,Promise.resolve(this._stream))))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){return{video:{frameRate:e.fps},audio:e.audio||!1}}}class FirefoxScreenShare{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this._toConstraints(e);let i;try{i=require("react-native-webrtc").mediaDevices}catch(e){i=navigator.mediaDevices}return i.getUserMedia(t).then((t=>(this._stream=formatVideoTrack(t,e.width,e.height,e.fps),Promise.resolve(this._stream))))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){const t={video:{mediaSource:"window"},audio:!1};return"mediaSource"in e&&(t.video.mediaSource=e.mediaSource),isFinite(e.width)&&(t.video.width={min:e.width,max:e.width}),isFinite(e.height)&&(t.video.height={min:e.height,max:e.height}),isFinite(e.frameRate)&&(t.video.frameRate={min:e.frameRate,max:e.frameRate}),t}}class EdgeScreenShare{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this._toConstraints(e);return navigator.getDisplayMedia(t).then((t=>(this._stream=formatVideoTrack(t,e.width,e.height,e.fps),Promise.resolve(this._stream))))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(){return{video:!0}}}class ElectronScreenShare{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this._toConstraints(e),i="boolean"==typeof e.audio&&e.audio,r="boolean"==typeof e.isRecord&&e.isRecord;let n,s;"boolean"==typeof e.isLocalProjection&&e.isLocalProjection;try{n=window.require("electron")}catch(e){n=window.parent.require("electron")}const o={types:["window","screen"]};if(n)s=n.desktopCapturer?n.desktopCapturer.getSources(o):n.ipcRenderer.invoke("desktopCapturer:getSources",o);else{let e;e=window.electronAPI?window.electronAPI.desktopCapturerGetSources(o):window.parent.electronAPI.desktopCapturerGetSources(o),s=e}const a=e=>{e.id.startsWith("window");const r=!!i&&{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id,echoCancellation:!0}};return navigator.mediaDevices.getUserMedia({audio:r,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id,minWidth:t.video.mandatory.minWidth,maxWidth:t.video.mandatory.maxWidth,minHeight:t.video.mandatory.minHeight,maxHeight:t.video.mandatory.maxHeight,minFrameRate:t.video.mandatory.minFrameRate,maxFrameRate:t.video.mandatory.maxFrameRate}}}).then((t=>(console.log("ElectronScreenShare:",e.id),this._stream=t,t)))};return s.then((async t=>{console.log("---share name selected:"+e.source_name);const i=t.find((t=>t.name===e.source_name));if(i)return a(i);for(const i of t)if(r||e.source_name===i.name){try{return a(i)}catch(e){console.log("ElectronScreenShare.start.error:",e)}break}return null})).catch((e=>(console.error("ElectronScreenShare:error",e),Promise.reject(e))))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){const t={video:{frameRate:e.fps,mandatory:{maxWidth:e.width,minWidth:e.width,maxHeight:e.height,minHeight:e.height}},audio:!1};return Logger$1.Log().log("====fps:",e.fps),isFinite(e.width)&&(t.video.mandatory.maxWidth=e.width,t.video.mandatory.minWidth=e.width),isFinite(e.height)&&(t.video.mandatory.minHeight=e.height,t.video.mandatory.maxHeight=e.height),isFinite(e.fps)&&(t.video.mandatory.minFrameRate=e.fps,t.video.mandatory.maxFrameRate=e.fps),void 0===e.width&&(t.video.mandatory.maxWidth=1920,t.video.mandatory.minWidth=1920),void 0===e.height&&(t.video.mandatory.maxHeight=1080,t.video.mandatory.minHeight=1080),void 0===e.fps&&(t.video.mandatory.minFrameRate=15,t.video.mandatory.maxFrameRate=15),t}}class ReactNativeScreenShare{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this._toConstraints(e);let i;try{i=require("react-native-webrtc").mediaDevices}catch(e){i=navigator.mediaDevices}return i.getDisplayMedia(t).then((e=>(this._stream=e,Promise.resolve(e))))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){return!1===e.audio||"object"!=typeof e.audio?{videoscreen:{frameRate:e.fps,width:e.width,height:e.height}}:{videoscreen:{frameRate:e.fps,width:e.width,height:e.height},audio:e.audio}}}class Safari13ScreenShare{constructor(){this._stream=null}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this._toConstraints(e);return navigator.mediaDevices.getDisplayMedia(t).then((t=>(this._stream=formatVideoTrack(t,e.width,e.height,e.fps||15),Promise.resolve(this._stream))))}stop(){this._stream instanceof MediaStream!=0&&(this._stream.getTracks().forEach((e=>e.stop())),this._stream=null)}isScreenShareAvailable(){return!0}needExtension(){return!1}_toConstraints(e){return{video:{frameRate:e.fps||15}}}}class DefaultScreenShare{isScreenShareAvailable(){return!1}needExtension(){return!1}}let sharing$2;class ScreenShare{static create(){if(sharing$2)return sharing$2;let e;e=VLBrowser.isMobile()?VLBrowser.userAgent():navigator.userAgent;const t=e,i=Bowser.getParser(t),r=i.getEngine();let n;try{n=r.name.toLowerCase()}catch(e){}const s=new BrowserDetection;if(s.isElectron())return console.log("===========Client============="),sharing$2=new ElectronScreenShare,sharing$2;if(s.isReactNative())return console.log("===========APP============="),sharing$2=new ReactNativeScreenShare,sharing$2;if(console.log("===========Browser============="),i.satisfies({chrome:">=72",chromium:">=72"}))sharing$2=new Chrome72ScreenShare;else if(i.satisfies({chrome:">=55",chromium:">=55"}))sharing$2=new ChromeScreenShare;else if(i.satisfies({firefox:">=60"}))sharing$2=new FirefoxScreenShare;else if(i.satisfies({"microsoft edge":"~11"}))sharing$2=new EdgeScreenShare;else if("blink"===n){Logger$1.Log().debug("best effort Chromium based browser detection");const e=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(e){const t=Number(e[1]);sharing$2=t>=72?new Chrome72ScreenShare:new ChromeScreenShare}else sharing$2=new ChromeScreenShare}else sharing$2=i.satisfies({safari:">=13"})&&"undefined"!=typeof RTCRtpTransceiver?new Safari13ScreenShare:(i.satisfies({safari:">=11"}),new DefaultScreenShare);return sharing$2}}let sharing$1=ScreenShare.create();Logger$1.Log();class BloudStream{constructor(e,t,i,r,n){this.published=!1,this.audio=n.audio,this.video=n.video,this.audio_enable=n.audio_enable,this.video_enable=n.video_enable,this.screen=n.screen,this.client=e,this.room=t,this.participant=i,this.local=r,this.options=n,this.id=n.id,this.roomId=t.getID(),this.userId=i.getID()}audioEnabled(){return this.audio_enable}videoEnabled(){return this.video_enable}setAudioEnabled(e){return this.client.controlStream(this.roomId,this.userId,this.id,{audio_enable:e}).then((()=>{this.audio_enable=e}))}setVideoEnabled(e){return this.client.controlStream(this.roomId,this.userId,this.id,{video_enable:e}).then((()=>{this.video_enable=e}))}isLocal(){return this.local}getID(){return this.id}getParticipant(){return this.participant}publish(e){var t,i;return __awaiter(this,void 0,void 0,(function*(){this.audio_enable=null!==(t=e.audio_enable)&&void 0!==t?t:this.audio_enable,this.video_enable=null!==(i=e.video_enable)&&void 0!==i?i:this.video_enable,yield this.client.publishStream(this.roomId,this.userId,this.id,{audio_enable:this.audio_enable,video_enable:this.video_enable,video:this.video,audio:this.audio}),this.participant.addStream(this),this.published=!0}))}unpublish(){return __awaiter(this,void 0,void 0,(function*(){yield this.client.unpublishStream(this.roomId,this.userId,this.id),this.participant.removeStream(this.getID()),this.published=!1}))}static sharing(){return sharing$1}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$2?global$2:"undefined"!=typeof self?self:{},specialChar="~",safeSpecialChar="\\x"+("0"+specialChar.charCodeAt(0).toString(16)).slice(-2),escapedSafeSpecialChar="\\"+safeSpecialChar,specialCharRG=new RegExp(safeSpecialChar,"g"),safeSpecialCharRG=new RegExp(escapedSafeSpecialChar,"g"),safeStartWithSpecialCharRG=new RegExp("(?:^|([^\\\\]))"+escapedSafeSpecialChar),indexOf$4=[].indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},$String=String;
|
|
8
|
-
/*!
|
|
9
|
-
Copyright (C) 2013-2017 by Andrea Giammarchi - @WebReflection
|
|
10
|
-
|
|
11
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
-
in the Software without restriction, including without limitation the rights
|
|
14
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
-
furnished to do so, subject to the following conditions:
|
|
17
|
-
|
|
18
|
-
The above copyright notice and this permission notice shall be included in
|
|
19
|
-
all copies or substantial portions of the Software.
|
|
20
|
-
|
|
21
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
27
|
-
THE SOFTWARE.
|
|
28
|
-
|
|
29
|
-
*/function generateReplacer(e,t,i){var r,n,s=!1,o=!!t,a=[],c=[e],u=[e],d=[i?specialChar:"[Circular]"],l=e,h=1;return o&&(n="object"==typeof t?function(e,i){return""!==e&&t.indexOf(e)<0?void 0:i}:t),function(e,t){return o&&(t=n.call(this,e,t)),s?(l!==this&&(r=h-indexOf$4.call(c,this)-1,h-=r,c.splice(h,c.length),a.splice(h-1,a.length),l=this),"object"==typeof t&&t?(indexOf$4.call(c,t)<0&&c.push(l=t),h=c.length,(r=indexOf$4.call(u,t))<0?(r=u.push(t)-1,i?(a.push((""+e).replace(specialCharRG,safeSpecialChar)),d[r]=specialChar+a.join(specialChar)):d[r]=d[0]):t=d[r]):"string"==typeof t&&i&&(t=t.replace(safeSpecialChar,escapedSafeSpecialChar).replace(specialChar,safeSpecialChar))):s=!0,t}}function retrieveFromPath(e,t){for(var i=0,r=t.length;i<r;e=e[t[i++].replace(safeSpecialCharRG,specialChar)]);return e}function generateReviver(e){return function(t,i){var r="string"==typeof i;return r&&i.charAt(0)===specialChar?new $String(i.slice(1)):(""===t&&(i=regenerate(i,i,{})),r&&(i=i.replace(safeStartWithSpecialCharRG,"$1"+specialChar).replace(escapedSafeSpecialChar,safeSpecialChar)),e?e.call(this,t,i):i)}}function regenerateArray(e,t,i){for(var r=0,n=t.length;r<n;r++)t[r]=regenerate(e,t[r],i);return t}function regenerateObject(e,t,i){for(var r in t)t.hasOwnProperty(r)&&(t[r]=regenerate(e,t[r],i));return t}function regenerate(e,t,i){return t instanceof Array?regenerateArray(e,t,i):t instanceof $String?t.length?i.hasOwnProperty(t)?i[t]:i[t]=retrieveFromPath(e,t.split(specialChar)):e:t instanceof Object?regenerateObject(e,t,i):t}var CircularJSON={stringify:function(e,t,i,r){return CircularJSON.parser.stringify(e,generateReplacer(e,t,!r),i)},parse:function(e,t){return CircularJSON.parser.parse(e,generateReviver(t))},parser:JSON},circularJson_node=CircularJSON;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];queue.push(new Item(e,t)),1!==queue.length||draining||runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser=!0,env={},argv=[],version$2="",versions={},release={},config$2={};function noop$2(){}var on=noop$2,addListener=noop$2,once$1=noop$2,off=noop$2,removeListener=noop$2,removeAllListeners=noop$2,emit=noop$2;function binding(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance$1=global$1.performance||{},performanceNow=performance$1.now||performance$1.mozNow||performance$1.msNow||performance$1.oNow||performance$1.webkitNow||function(){return(new Date).getTime()};function hrtime(e){var t=.001*performanceNow.call(performance$1),i=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(i-=e[0],(r-=e[1])<0&&(i--,r+=1e9)),[i,r]}var startTime=new Date;function uptime(){return(new Date-startTime)/1e3}var process$1={nextTick:nextTick,title:title,browser:browser,env:env,argv:argv,version:version$2,versions:versions,on:on,addListener:addListener,once:once$1,off:off,removeListener:removeListener,removeAllListeners:removeAllListeners,emit:emit,binding:binding,cwd:cwd,chdir:chdir,umask:umask,hrtime:hrtime,platform:platform,release:release,config:config$2,uptime:uptime},md5$1={exports:{}};(function(module){(function(){var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof process$1&&process$1.versions&&process$1.versions.node;NODE_JS?root=commonjsGlobal:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&module.exports,ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t){return new Md5(!0).update(t)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t<OUTPUT_TYPES.length;++t){var i=OUTPUT_TYPES[t];e[i]=createOutputMethod(i)}return e},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(e){if("string"==typeof e)return crypto.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw ERROR;return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),Array.isArray(e)||ArrayBuffer.isView(e)||e.constructor===Buffer?crypto.createHash("md5").update(new Buffer(e)).digest("hex"):method(e)};return nodeMethod};function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Md5.prototype.update=function(e){if(!this.finalized){var t,i=typeof e;if("string"!==i){if("object"!==i)throw ERROR;if(null===e)throw ERROR;if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw ERROR;t=!0}for(var r,n,s=0,o=e.length,a=this.blocks,c=this.buffer8;s<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)if(ARRAY_BUFFER)for(n=this.start;s<o&&n<64;++s)c[n++]=e[s];else for(n=this.start;s<o&&n<64;++s)a[n>>2]|=e[s]<<SHIFT[3&n++];else if(ARRAY_BUFFER)for(n=this.start;s<o&&n<64;++s)(r=e.charCodeAt(s))<128?c[n++]=r:r<2048?(c[n++]=192|r>>6,c[n++]=128|63&r):r<55296||r>=57344?(c[n++]=224|r>>12,c[n++]=128|r>>6&63,c[n++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),c[n++]=240|r>>18,c[n++]=128|r>>12&63,c[n++]=128|r>>6&63,c[n++]=128|63&r);else for(n=this.start;s<o&&n<64;++s)(r=e.charCodeAt(s))<128?a[n>>2]|=r<<SHIFT[3&n++]:r<2048?(a[n>>2]|=(192|r>>6)<<SHIFT[3&n++],a[n>>2]|=(128|63&r)<<SHIFT[3&n++]):r<55296||r>=57344?(a[n>>2]|=(224|r>>12)<<SHIFT[3&n++],a[n>>2]|=(128|r>>6&63)<<SHIFT[3&n++],a[n>>2]|=(128|63&r)<<SHIFT[3&n++]):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),a[n>>2]|=(240|r>>18)<<SHIFT[3&n++],a[n>>2]|=(128|r>>12&63)<<SHIFT[3&n++],a[n>>2]|=(128|r>>6&63)<<SHIFT[3&n++],a[n>>2]|=(128|63&r)<<SHIFT[3&n++]);this.lastByteIndex=n,this.bytes+=n-this.start,n>=64?(this.start=n-64,this.hash(),this.hashed=!0):this.start=n}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,i,r,n,s,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879<<0)^(i=((i=(-271733879^(r=((r=(-1732584194^2004318071&e)+o[1]-117830708)<<12|r>>>20)+e<<0)&(-271733879^e))+o[2]-1126478375)<<17|i>>>15)+r<<0)&(r^e))+o[3]-1316259209)<<22|t>>>10)+i<<0:(e=this.h0,t=this.h1,i=this.h2,t=((t+=((e=((e+=((r=this.h3)^t&(i^r))+o[0]-680876936)<<7|e>>>25)+t<<0)^(i=((i+=(t^(r=((r+=(i^e&(t^i))+o[1]-389564586)<<12|r>>>20)+e<<0)&(e^t))+o[2]+606105819)<<17|i>>>15)+r<<0)&(r^e))+o[3]-1044525330)<<22|t>>>10)+i<<0),t=((t+=((e=((e+=(r^t&(i^r))+o[4]-176418897)<<7|e>>>25)+t<<0)^(i=((i+=(t^(r=((r+=(i^e&(t^i))+o[5]+1200080426)<<12|r>>>20)+e<<0)&(e^t))+o[6]-1473231341)<<17|i>>>15)+r<<0)&(r^e))+o[7]-45705983)<<22|t>>>10)+i<<0,t=((t+=((e=((e+=(r^t&(i^r))+o[8]+1770035416)<<7|e>>>25)+t<<0)^(i=((i+=(t^(r=((r+=(i^e&(t^i))+o[9]-1958414417)<<12|r>>>20)+e<<0)&(e^t))+o[10]-42063)<<17|i>>>15)+r<<0)&(r^e))+o[11]-1990404162)<<22|t>>>10)+i<<0,t=((t+=((e=((e+=(r^t&(i^r))+o[12]+1804603682)<<7|e>>>25)+t<<0)^(i=((i+=(t^(r=((r+=(i^e&(t^i))+o[13]-40341101)<<12|r>>>20)+e<<0)&(e^t))+o[14]-1502002290)<<17|i>>>15)+r<<0)&(r^e))+o[15]+1236535329)<<22|t>>>10)+i<<0,t=((t+=((r=((r+=(t^i&((e=((e+=(i^r&(t^i))+o[1]-165796510)<<5|e>>>27)+t<<0)^t))+o[6]-1069501632)<<9|r>>>23)+e<<0)^e&((i=((i+=(e^t&(r^e))+o[11]+643717713)<<14|i>>>18)+r<<0)^r))+o[0]-373897302)<<20|t>>>12)+i<<0,t=((t+=((r=((r+=(t^i&((e=((e+=(i^r&(t^i))+o[5]-701558691)<<5|e>>>27)+t<<0)^t))+o[10]+38016083)<<9|r>>>23)+e<<0)^e&((i=((i+=(e^t&(r^e))+o[15]-660478335)<<14|i>>>18)+r<<0)^r))+o[4]-405537848)<<20|t>>>12)+i<<0,t=((t+=((r=((r+=(t^i&((e=((e+=(i^r&(t^i))+o[9]+568446438)<<5|e>>>27)+t<<0)^t))+o[14]-1019803690)<<9|r>>>23)+e<<0)^e&((i=((i+=(e^t&(r^e))+o[3]-187363961)<<14|i>>>18)+r<<0)^r))+o[8]+1163531501)<<20|t>>>12)+i<<0,t=((t+=((r=((r+=(t^i&((e=((e+=(i^r&(t^i))+o[13]-1444681467)<<5|e>>>27)+t<<0)^t))+o[2]-51403784)<<9|r>>>23)+e<<0)^e&((i=((i+=(e^t&(r^e))+o[7]+1735328473)<<14|i>>>18)+r<<0)^r))+o[12]-1926607734)<<20|t>>>12)+i<<0,t=((t+=((s=(r=((r+=((n=t^i)^(e=((e+=(n^r)+o[5]-378558)<<4|e>>>28)+t<<0))+o[8]-2022574463)<<11|r>>>21)+e<<0)^e)^(i=((i+=(s^t)+o[11]+1839030562)<<16|i>>>16)+r<<0))+o[14]-35309556)<<23|t>>>9)+i<<0,t=((t+=((s=(r=((r+=((n=t^i)^(e=((e+=(n^r)+o[1]-1530992060)<<4|e>>>28)+t<<0))+o[4]+1272893353)<<11|r>>>21)+e<<0)^e)^(i=((i+=(s^t)+o[7]-155497632)<<16|i>>>16)+r<<0))+o[10]-1094730640)<<23|t>>>9)+i<<0,t=((t+=((s=(r=((r+=((n=t^i)^(e=((e+=(n^r)+o[13]+681279174)<<4|e>>>28)+t<<0))+o[0]-358537222)<<11|r>>>21)+e<<0)^e)^(i=((i+=(s^t)+o[3]-722521979)<<16|i>>>16)+r<<0))+o[6]+76029189)<<23|t>>>9)+i<<0,t=((t+=((s=(r=((r+=((n=t^i)^(e=((e+=(n^r)+o[9]-640364487)<<4|e>>>28)+t<<0))+o[12]-421815835)<<11|r>>>21)+e<<0)^e)^(i=((i+=(s^t)+o[15]+530742520)<<16|i>>>16)+r<<0))+o[2]-995338651)<<23|t>>>9)+i<<0,t=((t+=((r=((r+=(t^((e=((e+=(i^(t|~r))+o[0]-198630844)<<6|e>>>26)+t<<0)|~i))+o[7]+1126891415)<<10|r>>>22)+e<<0)^((i=((i+=(e^(r|~t))+o[14]-1416354905)<<15|i>>>17)+r<<0)|~e))+o[5]-57434055)<<21|t>>>11)+i<<0,t=((t+=((r=((r+=(t^((e=((e+=(i^(t|~r))+o[12]+1700485571)<<6|e>>>26)+t<<0)|~i))+o[3]-1894986606)<<10|r>>>22)+e<<0)^((i=((i+=(e^(r|~t))+o[10]-1051523)<<15|i>>>17)+r<<0)|~e))+o[1]-2054922799)<<21|t>>>11)+i<<0,t=((t+=((r=((r+=(t^((e=((e+=(i^(t|~r))+o[8]+1873313359)<<6|e>>>26)+t<<0)|~i))+o[15]-30611744)<<10|r>>>22)+e<<0)^((i=((i+=(e^(r|~t))+o[6]-1560198380)<<15|i>>>17)+r<<0)|~e))+o[13]+1309151649)<<21|t>>>11)+i<<0,t=((t+=((r=((r+=(t^((e=((e+=(i^(t|~r))+o[4]-145523070)<<6|e>>>26)+t<<0)|~i))+o[11]-1120210379)<<10|r>>>22)+e<<0)^((i=((i+=(e^(r|~t))+o[2]+718787259)<<15|i>>>17)+r<<0)|~e))+o[9]-343485551)<<21|t>>>11)+i<<0,this.first?(this.h0=e+1732584193<<0,this.h1=t-271733879<<0,this.h2=i-1732584194<<0,this.h3=r+271733878<<0,this.first=!1):(this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+i<<0,this.h3=this.h3+r<<0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,i=this.h2,r=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[i>>4&15]+HEX_CHARS[15&i]+HEX_CHARS[i>>12&15]+HEX_CHARS[i>>8&15]+HEX_CHARS[i>>20&15]+HEX_CHARS[i>>16&15]+HEX_CHARS[i>>28&15]+HEX_CHARS[i>>24&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,i=this.h2,r=this.h3;return[255&e,e>>8&255,e>>16&255,e>>24&255,255&t,t>>8&255,t>>16&255,t>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,i,r="",n=this.array(),s=0;s<15;)e=n[s++],t=n[s++],i=n[s++],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|i>>>6)]+BASE64_ENCODE_CHAR[63&i];return e=n[s],r+(BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"==")};var exports=createMethod();COMMON_JS?module.exports=exports:root.md5=exports})()})(md5$1);var md5=md5$1.exports,events={exports:{}},R="object"==typeof Reflect?Reflect:null,ReflectApply=R&&"function"==typeof R.apply?R.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)},ReflectOwnKeys;function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}ReflectOwnKeys=R&&"function"==typeof R.ownKeys?R.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var NumberIsNaN=Number.isNaN||function(e){return e!=e};function EventEmitter$1(){EventEmitter$1.init.call(this)}events.exports=EventEmitter$1,events.exports.once=once,EventEmitter$1.EventEmitter=EventEmitter$1,EventEmitter$1.prototype._events=void 0,EventEmitter$1.prototype._eventsCount=0,EventEmitter$1.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function _getMaxListeners(e){return void 0===e._maxListeners?EventEmitter$1.defaultMaxListeners:e._maxListeners}function _addListener(e,t,i,r){var n,s,o;if(checkListener(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),o=s[t]),void 0===o)o=s[t]=i,++e._eventsCount;else if("function"==typeof o?o=s[t]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),(n=_getMaxListeners(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,ProcessEmitWarning(a)}return e}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,i){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=onceWrapper.bind(r);return n.listener=i,r.wrapFn=n,n}function _listeners(e,t,i){var r=e._events;if(void 0===r)return[];var n=r[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?unwrapListeners(n):arrayClone(n,n.length)}function listenerCount(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function arrayClone(e,t){for(var i=new Array(t),r=0;r<t;++r)i[r]=e[r];return i}function spliceOne(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function unwrapListeners(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}function once(e,t){return new Promise((function(i,r){function n(i){e.removeListener(t,s),r(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),i([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,s,{once:!0}),"error"!==t&&addErrorHandlerIfEventEmitter(e,n,{once:!0})}))}function addErrorHandlerIfEventEmitter(e,t,i){"function"==typeof e.on&&eventTargetAgnosticAddListener(e,"error",t,i)}function eventTargetAgnosticAddListener(e,t,i,r){if("function"==typeof e.on)r.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(s){r.once&&e.removeEventListener(t,n),i(s)}))}}Object.defineProperty(EventEmitter$1,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(e){if("number"!=typeof e||e<0||NumberIsNaN(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");defaultMaxListeners=e}}),EventEmitter$1.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter$1.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||NumberIsNaN(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},EventEmitter$1.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter$1.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,n=this._events;if(void 0!==n)r=r&&void 0===n.error;else if(!r)return!1;if(r){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)ReflectApply(a,this,t);else{var c=a.length,u=arrayClone(a,c);for(i=0;i<c;++i)ReflectApply(u[i],this,t)}return!0},EventEmitter$1.prototype.addListener=function(e,t){return _addListener(this,e,t,!1)},EventEmitter$1.prototype.on=EventEmitter$1.prototype.addListener,EventEmitter$1.prototype.prependListener=function(e,t){return _addListener(this,e,t,!0)},EventEmitter$1.prototype.once=function(e,t){return checkListener(t),this.on(e,_onceWrap(this,e,t)),this},EventEmitter$1.prototype.prependOnceListener=function(e,t){return checkListener(t),this.prependListener(e,_onceWrap(this,e,t)),this},EventEmitter$1.prototype.removeListener=function(e,t){var i,r,n,s,o;if(checkListener(t),void 0===(r=this._events))return this;if(void 0===(i=r[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){o=i[s].listener,n=s;break}if(n<0)return this;0===n?i.shift():spliceOne(i,n),1===i.length&&(r[e]=i[0]),void 0!==r.removeListener&&this.emit("removeListener",e,o||t)}return this},EventEmitter$1.prototype.off=EventEmitter$1.prototype.removeListener,EventEmitter$1.prototype.removeAllListeners=function(e){var t,i,r;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var n,s=Object.keys(i);for(r=0;r<s.length;++r)"removeListener"!==(n=s[r])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},EventEmitter$1.prototype.listeners=function(e){return _listeners(this,e,!0)},EventEmitter$1.prototype.rawListeners=function(e){return _listeners(this,e,!1)},EventEmitter$1.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter$1.prototype.listenerCount=listenerCount,EventEmitter$1.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};const C1=2,C2=1,C3=0,DECISION_INTERVAL=400,DECISION_MAKER_IDLE_TIMEOUT=15e3,LEVEL_IDLE_TIMEOUT=400,LONG_COUNT=1,LONG_THRESHOLD=2,MAX_LEVEL=127,MIN_LEVEL=0,MIN_LEVEL_WINDOW_LENGTH=75,MIN_SPEECH_ACTIVITY_SCORE=1e-10,ACTIVE_SPEECH_LEVEL=10,MEDIUM_THRESHOLD=3,N1=15,N1_SUBUNIT_LENGTH=(MAX_LEVEL-MIN_LEVEL+N1-1)/N1,N2=5,N3=5,SPEAKER_IDLE_TIMEOUT=36e5,ACTIVE_TIME_OUT=2e3;function binomialCoefficient(e,t){let i=e-t;t<i&&(t=i);let r=1;for(let i=e,n=1;i>t;i--,n++)r=Math.floor(r*i/n);return r}function computeBigs(e,t,i){let r=t.length,n=Math.floor(e.length/r),s=!1;for(let o=0,a=0;o<r;o++){let r=0;for(let t=a+n;a<t;a++)e[a]>i&&r++;t[o]!=r&&(t[o]=r,s=!0)}return s}function computeSpeechActivityScore(e,t,i,r){let n=Math.log(binomialCoefficient(t,e))+e*Math.log(i)+(t-e)*Math.log(1-i)-Math.log(r)+r*e;return n<MIN_SPEECH_ACTIVITY_SCORE&&(n=MIN_SPEECH_ACTIVITY_SCORE),n}class Speaker{constructor(e){this.stream=e,this.immediates=new Array(LONG_COUNT*N3*N2),this.immediateSpeechActivityScore=MIN_SPEECH_ACTIVITY_SCORE,this.lastLevelChangedTime=(new Date).getTime(),this.levels=new Array(this.immediates.length),this.longs=new Array(LONG_COUNT),this.longSpeechActivityScore=MIN_SPEECH_ACTIVITY_SCORE,this.mediums=new Array(LONG_COUNT*N3),this.mediumSpeechActivityScore=MIN_SPEECH_ACTIVITY_SCORE,this.minLevel=MIN_LEVEL,this.nextMinLevel=MIN_LEVEL,this.nextMinLevelWindowLength=void 0,this.lastActiveTime=this.lastLevelChangedTime-ACTIVE_TIME_OUT-1}getStream(){return this.stream}getID(){return this.stream.getID()}computeImmediates(){let e=this.immediates,t=this.levels,i=Math.floor(this.minLevel+N1_SUBUNIT_LENGTH),r=!1;for(let n=0;n<e.length;++n){let s=t[n];s<i&&(s=MIN_LEVEL);let o=Math.floor(s/N1_SUBUNIT_LENGTH);e[n]!=o&&(e[n]=o,r=!0)}return r}computeLongs(){return computeBigs(this.mediums,this.longs,LONG_THRESHOLD)}computeMediums(){return computeBigs(this.immediates,this.mediums,MEDIUM_THRESHOLD)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=computeSpeechActivityScore(this.immediates[0],N1,.5,.78)}evaluateLongSpeechActivityScore(){this.longSpeechActivityScore=computeSpeechActivityScore(this.longs[0],N3,.5,47)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=computeSpeechActivityScore(this.mediums[0],N2,.5,24)}evaluateSpeechActivityScores(){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore()))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){let e=this.levels,t=new Array(e.length);for(let i=e.length-1,r=0;r<t.length;--i,++r)t[r]=e[i];return t}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;default:return this.longSpeechActivityScore}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){let i;this.lastLevelChangedTime=t,i=e<MIN_LEVEL?MIN_LEVEL:e>MAX_LEVEL?MAX_LEVEL:e;for(let e=this.levels.length-1;e>0;--e)this.levels[e]=this.levels[e-1];this.levels[0]=i,this.updateMinLevel(i)}e>ACTIVE_SPEECH_LEVEL&&(this.lastActiveTime=(new Date).getTime())}levelTimeout(){this.levelChanged(MIN_LEVEL,this.lastLevelChangedTime)}updateMinLevel(e){if(e!=MIN_LEVEL){if(this.minLevel==MIN_LEVEL||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=MIN_LEVEL,void(this.nextMinLevelWindowLength=0);if(this.nextMinLevel==MIN_LEVEL)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=MIN_LEVEL_WINDOW_LENGTH){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<MIN_LEVEL?e=MIN_LEVEL:e>MAX_LEVEL&&(e=MAX_LEVEL),this.minLevel=e,this.nextMinLevel=MIN_LEVEL,this.nextMinLevelWindowLength=0}}}getSilent(){return(new Date).getTime()-this.lastActiveTime>ACTIVE_TIME_OUT}}class DecisionMaker{constructor(e){this.algorithm=e}run(){let e=this.algorithm.runInDecisionMaker(this);e<0?this.algorithm.decisionMakerExited(this):setTimeout((()=>{this.run()}),e)}}class SpeakerDetector extends events.exports.EventEmitter{constructor(){super(),this.decisionMaker=void 0,this.dominant=void 0,this.lastDecisionTime=0,this.lastLevelChangedTime=0,this.lastLevelIdleTime=0,this.relativeSpeechActivities=[0,0,0],this.speakers=new Map}addStream(e){e.on("audio-level",this.levelChanged.bind(this,e)),e.collectAudioLevel()}removeStream(e){this.speakers.delete(e.getID())}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new DecisionMaker(this),this.decisionMaker.run())}decisionMakerExited(e){e==this.decisionMaker&&(this.decisionMaker=void 0)}getDominantSpeaker(){let e=this.speakers.get(this.dominant);if(e)return e.getStream()}getOrCreateSpeaker(e){let t=e.getID(),i=this.speakers.get(t);return i||(i=new Speaker(e),this.speakers.set(t,i),this.maybeStartDecisionMaker()),i}levelChanged(e,t){t=Math.min(t*MAX_LEVEL*2,MAX_LEVEL);let i=this.getOrCreateSpeaker(e),r=(new Date).getTime();this.lastLevelChangedTime<r&&(this.lastLevelChangedTime=r,this.maybeStartDecisionMaker()),i.levelChanged(t,r)}decisionChoice(){let e=this.speakers.get(this.dominant),t="";e||(e=this.speakers.entries().next().value[1],t=e.getID()),e.evaluateSpeechActivityScores();let i=this.relativeSpeechActivities,r=C2;for(let[n,s]of this.speakers){if(s==e)continue;s.evaluateSpeechActivityScores();for(let t=0;t<i.length;++t)i[t]=Math.log(s.getSpeechActivityScore(t)/e.getSpeechActivityScore(t));let o=i[0],a=i[1],c=i[2];o>C1&&a>C2&&c>C3&&a>r&&(r=a,t=n)}return t}makeDecision(){let e;if(0!=this.speakers.size&&(e=this.decisionChoice()),e&&e!=this.dominant){this.dominant=e;let t=this.speakers.get(this.dominant);t&&!t.getSilent()?this.emit("speaker",t.getStream()):(this.emit("speaker"),this.dominant=void 0)}else if(this.dominant){let e=this.speakers.get(this.dominant);(e&&e.getSilent()||!e)&&(this.dominant=void 0,this.emit("speaker"))}}runInDecisionMaker(e){if(e&&e!=this.decisionMaker)return-1;if(0<this.lastDecisionTime&&this.lastDecisionTime-this.lastLevelChangedTime>=DECISION_MAKER_IDLE_TIMEOUT)return-1;let t=(new Date).getTime(),i=LEVEL_IDLE_TIMEOUT-(t-this.lastLevelIdleTime),r=0;i<=0?(0!=this.lastLevelIdleTime&&this.timeoutIdleLevels(t),this.lastLevelIdleTime=t):r=i;let n=DECISION_INTERVAL-(t-this.lastDecisionTime);return n<=0&&(this.lastDecisionTime=t,this.makeDecision(),n=DECISION_INTERVAL-((new Date).getTime()-t)),n>0&&r>n&&(r=n),r}timeoutIdleLevels(e){for(let[t,i]of this.speakers){let r=e-i.getLastLevelChangedTime();SPEAKER_IDLE_TIMEOUT<r&&(!this.dominant||i.getID()!=this.dominant)?this.speakers.delete(t):LEVEL_IDLE_TIMEOUT<r&&i.levelTimeout()}}}class RecordingAdapter extends events.exports.EventEmitter{constructor(){super(),this._recording=!1}start(e,t){}stop(){}exportRecordedData(){}setMuted(e){}setMicDevice(e){}_getAudioStream(){return navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}isRecording(){return this._recording}}let sharing=ScreenShare.create();class VideoRecordingAdapter extends RecordingAdapter{constructor(){super(),this._trackSources=new Map,this._stream=null,this._recordedData=[]}start(e,t){return this._createDesktopStream(t.capture).then((i=>__awaiter(this,void 0,void 0,(function*(){try{return this._getMixedAudioTrack(e).then((e=>{e&&(i.addTrack(e),this._stream=i,this._mediaRecorder=this._newMediaRecorder(i,t.record),this._mediaRecorder.ondataavailable=e=>this._saveMediaData(e.data),this._mediaRecorder.start(1e3),this._recording=!0,this.emit("started"))}))}catch(e){throw Logger$1.Log().error(circularJson_node.stringify(e)),this._localAudioTrack&&this._localAudioTrack.stop(),i.getTracks().forEach((e=>e.stop())),e}}))))}stop(){return new Promise(((e,t)=>{this._mediaRecorder?(this._mediaRecorder.onstop=e,this._mediaRecorder.stop(),this._mediaRecorder=null,this._localAudioTrack&&(this._localAudioTrack.stop(),this._localAudioStream=null),this._stream&&this._stream.getTracks().forEach((e=>e.stop())),this._trackSources&&(this._trackSources.forEach((e=>e.disconnect(this._audioContextDest))),this._trackSources.clear()),this._recording=!1,this.emit("stopped")):t()}))}exportRecordedData(){return this._recordedData?Promise.resolve({data:this._recordedData,format:"mp4"}):Promise.reject("No video data recorded.")}setMuted(e){this._localAudioTrack&&(this._localAudioTrack.enabled=!e)}setMicDevice(e){return __awaiter(this,void 0,void 0,(function*(){if(this._localAudioTrack)try{return this.disconnectTrack(this._localAudioTrack),this._localAudioTrack.stop(),this._getLocalAudioTrack(e).then((e=>{this.connectTrack(e)}))}catch(e){return Promise.reject()}return Promise.reject()}))}_saveMediaData(e){console.log("save media data..., size:",e.size),this._recordedData.push(e)}_createDesktopStream(e){return sharing.start(e).then((e=>{let t=e.getVideoTracks()[0];return t&&(t.onended=()=>{this.emit("track-ended")}),e}))}_newMediaRecorder(e,t){const i={bitsPerSecond:(t=t||{}).bitrate?t.bitrate:3e6};if(MediaRecorder.isTypeSupported(t.format))i.mimeType=t.format;else{const e=["video/mp4;codecs=h264","video/mp4;codecs=vp9","video/mp4;codecs=vp8"];for(const t of e)if(MediaRecorder.isTypeSupported(t)){i.mimeType=t;break}}return new MediaRecorder(e,i)}_getLocalAudioTrack(e){return this._getAudioStream().then((e=>{this._localAudioStream=e;const t=this._localAudioStream.getAudioTracks()[0];return this._localAudioTrack=t,t}))}_getMixedAudioTrack(e){return this._getLocalAudioTrack(e).then((()=>{if(this._localAudioStream){const e=new AudioContext,t=e.createMediaStreamSource(this._localAudioStream),i=e.createMediaStreamDestination();return t.connect(i),this._audioContext=e,this._audioContextDest=i,this._trackSources.set(this._localAudioTrack,t),i.stream.getAudioTracks()[0]}}))}connectTrack(e){const t=this._audioContext.createMediaStreamSource(new MediaStream([e]));null==t||t.connect(this._audioContextDest),this._trackSources.set(e,t)}disconnectTrack(e){const t=this._trackSources.get(e);t&&(t.disconnect(this._audioContextDest),this._trackSources.delete(e))}}class Recorder extends events.exports.EventEmitter{constructor(e){super(),this._opts=e,this._filename=e.filename,this._adapter=new VideoRecordingAdapter,this._adapter.on("started",this.emit.bind(this,"started")),this._adapter.on("stopped",this.emit.bind(this,"stopped")),this._adapter.on("track-ended",this.emit.bind(this,"track-ended"))}downloadBlob(e,t="recording.webm"){let i=new Blob(e);const r=window.URL.createObjectURL(i),n=document.createElement("a");n.style.display="none",n.href=r,n.download=t,document.body.appendChild(n),console.log("a tag to save recorded data..."),n.click(),setTimeout((function(){document.body.removeChild(n),window.URL.revokeObjectURL(r)}),1e3)}start(){return this._adapter.start("0",this._opts)}stop(){return this._adapter.stop().then((()=>(console.log("export recorded data..."),this._adapter.exportRecordedData()))).then((e=>{const{data:t,format:i}=e;console.log("download recorded data..."),this.downloadBlob(t,this._filename)}))}muteAudio(e){this._adapter.isRecording()&&this._adapter.setMuted(e)}addStream(e){let t=e&&e.getAudioTrack();t&&this._adapter.isRecording()&&this._adapter.connectTrack(t)}removeStream(e){let t=e.getAudioTrack();t&&this._adapter.isRecording()&&this._adapter.disconnectTrack(t)}addEventListener(e,t){this.addListener(e,t)}on(e,t){return this.addListener(e,t),this}}const defaultOptions={enableRace:!1};class Room extends Emitter$2{constructor(e){var t;super(!0),this.switch=!1,this.audiooff=!1,this.selfopenaudio=!0,this.videooff=!1,this.msgoff=!1,this.creator="",this.master="",this.lock=!1,this.getUsersList=(e,t,i,r)=>this.client.getUsersList(e,t,i,r).then((e=>{const t=e.value;return{participants:this.parseGetUser(t),total:e.total,pageIndex:e.index}})),this.searchUsers=(e,t,i)=>this.client.searchUsers(e,t,i).then((e=>{const t=e.value;return{participants:this.parseGetUser(t)}})),this.queryUsers=e=>this.client.queryUsers(e).then((e=>{const t=e.value;return{participants:this.parseGetUser(t)}})),this.options=extend({},defaultOptions,e),this.joined=!1,this.logger=Logger$1.Log(),this.roomId=e.room,this.userId=e.user,this.hasSecret=!!this.options.secret,this.connectopts={nickname:this.options.nickname,custom_token:this.options.custom_token,userinfo:this.options.userinfo},this.create=null===(t=e.create)||void 0===t||t,this.nickname=e.nickname,this.localParticipant=new Participant(!0,this.userId,e)}connect(){return __awaiter(this,void 0,void 0,(function*(){this.client=new Client(this.options.proxies,{forceWS:this.options.forceWS,enableRace:this.options.enableRace,token:this.options.token},this.getRpc(),this.logger),this.handleEvents(),yield this.client.connect();try{const e=yield this.client.join({roomId:this.roomId,userId:this.userId,info:this.getJoinUserInfo(this.options.userinfo)});this.joined=!0,this.logger.info(`joined: sessionId: ${e.sessionId}, callId: ${e.raw.callId}`);const t=this.parseJoinResponse(e);this.fire("room-connected",[t])}catch(e){throw this.logger.error(`join room failed: ${getErrorMessage(e)}, proxy: ${JSON.stringify(this.getActiveProxy())}`),this.client.close(),e}}))}leave(){var e;return __awaiter(this,void 0,void 0,(function*(){this.client&&(this.logger.info(`leaved: sessionId: ${(null===(e=this.client)||void 0===e?void 0:e.getSessionId())||""}`),yield this.client.leave({roomId:this.roomId,userId:this.userId,sessionId:this.client.getSessionId()||""}),this.client.close(),this.client=void 0,this.joined=!1)}))}request(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){return null===(i=this.client)||void 0===i?void 0:i.request(e,t)}))}handleEvents(){this.client.on(ERROR$1,(()=>{this.logger.error("client error"),this.fire(ERROR)})).on(CLOSE,(()=>{this.logger.error("client close"),this.fire(ERROR)})).on(TIMEOUT$1,(()=>{this.logger.error("client timeout"),this.fire(TIMEOUT,[{msg:"timeout"}])})).on(RECONNECTED$1,(()=>{this.logger.info("client reconnected"),this.fire(RECONNECTED)})).on(RECONNECTING$1,(()=>{this.fire(RECONNECTING)})).on(EventMap.joinUser,(e=>{this.logger.debug("participant joined");const t=new Participant(!1,e.userId,e);this.fire(EventMap.joinUser,[{participant:t,mode:e.mode,data:e}])})).on(EventMap.leaveUser,(e=>{e.userId!==this.userId&&this.fire(EventMap.leaveUser,[{userId:e.userId,mode:e.mode,data:e}])})).on(EventMap.leaveUsers,(e=>{this.fire(EventMap.leaveUsers,[e])})).on(EventMap.roomClosed,(e=>{this.logger.error("room closed"),this.fire(EventMap.roomClosed,[e]),this.destroy()})).on(EventMap.roomError,(()=>{this.logger.error("room error"),this.fire(EventMap.roomError),this.destroy()})).on(EventMap.publishStream,(e=>{if(e.userId===this.userId)return;const t=e.userId,i=e.streamId,r=i.endsWith("_screen");this.fire(EventMap.publishStream,[{userId:t,streamId:i,video:e.params.video_enable,audio:e.params.audio_enable,isScreen:r}])})).on(EventMap.streamUpdate,(e=>{if(e.userId===this.userId)return;const t=e.userId,i=e.streamId,r=i.endsWith("_screen");this.fire("bloud-stream-update",[{userId:t,streamId:i,video:e.params.video_enable,audio:e.params.audio_enable,isScreen:r}])})).on(EventMap.unpublishStream,(e=>{if(e.userId===this.userId)return;const t=e.userId,i=e.streams[0],r=i.endsWith("_screen");this.fire(EventMap.unpublishStream,[{userId:t,streamId:i,isScreen:r}])})).on(EventMap.sendMessage,(e=>{const t={room:e.roomId,user:e.userId,message:e.msg,to:e.to,seq:e.seq};this.fire(EventMap.sendMessage,[t])})).on(EventMap.customMessage,(e=>{const t={room:e.roomId,user:e.userId,message:e.msg,to:e.to};this.fire(EventMap.customMessage,[t])})).on(EventMap.moveUserRoom,(e=>{var t,i;(null===(t=e.info)||void 0===t?void 0:t.master)&&(this.master=e.info.master),(null===(i=e.info)||void 0===i?void 0:i.customStats)&&(this.customStats=e.info.customStats),this.fire(EventMap.moveUserRoom,[e])})).on(EventMap.evicted,(e=>{this.fire(EventMap.evicted,[{userId:e.userId}])})).on(EventMap.updateStats,(e=>{this.switch=e.stats.switch,this.hasSecret=e.stats.secret,this.audiooff=e.stats.audiooff,this.selfopenaudio=e.stats.selfopenaudio,this.videooff=e.stats.videooff,this.msgoff=e.stats.msgoff,this.lock=e.stats.lock,this.creator=e.stats.creator,this.master=e.stats.master;const t=e.stats.updates;let i=Object.keys(t);this.fire(EventMap.updateStats,[{room:this,options:i,stats:e.stats}])})).on(EventMap.updateCustomStats,(e=>{this.customStats=e.customStats||{},this.fire(EventMap.updateCustomStats,[{room:this,customStats:this.customStats,updateKeys:e.updateKeys}])})).on(EventMap.changeMaster,(e=>{this.master=e.master,this.fire(EventMap.changeMaster,[{master:this.master,oldMaster:e.oldmaster,isKeep:e.isKeep,type:e.type,data:e}])})).on(EventMap.updateUser,(e=>{if(e.user===this.getLocalParticipant().getID())this.getLocalParticipant().update(e.info),this.fire(EventMap.updateUser,[{participant:this.getLocalParticipant()}]);else{const t=new Participant(!1,e.user,e.info);this.fire(EventMap.updateUser,[{participant:t}])}})).on(EventMap.userRejoined,(e=>{this.fire(EventMap.userRejoined,[{userId:e.userId,info:e.info}])}))}getRpc(){return{sessionClosed:()=>(nextTick$2((()=>{this.syncRoom()})),{result:0})}}getActiveProxy(){return this.client.getProxy()}destroy(){this.client&&(this.client.close(),this.client=void 0),this.joined=!1,this.off()}getJoinUserInfo(e,t=!1){let i={};return i.ua=e.ua?e.ua:getUserAgent$1(),i.device=e.device?e.device:getBrowser$1(),i.platform=e.platform?e.platform:"Web",i.network=e.network?e.network:"unknown",i.role=e.role?e.role:"anchor",i.create=this.options.create,i.secret=this.options.secret?md5(`${this.roomId}.${this.options.secret}`):void 0,i.nickname=this.options.nickname,i.userinfo=this.options.userinfo,i.hasWaitRoom=!0,i.permission=t?this.permission:this.options.permission,i.custom_token=this.options.custom_token,i.prefer=this.options.prefer,i.name=this.options.name,i.userinfo.jointime||(i.userinfo.jointime=Math.floor(Date.now()/1e3)),i}getLocalParticipant(){return this.localParticipant}getID(){return this.roomId}getAudioOff(){return this.audiooff}getSelfOpenAudio(){return this.selfopenaudio}getVideoOff(){return this.videooff}getMsgOff(){return this.msgoff}getLock(){return this.lock}setAudioOff(e,t){return this.update({audiooff:e,selfopenaudio:t})}setVideoOff(e){return this.update({videooff:e})}setMsgOff(e){return this.update({msgoff:e})}setSwitch(e){return this.update({switch:e})}setLock(e){return this.update({lock:e})}getSwitch(){return this.switch}setSecret(e){return this.update({secret:e})}getLimits(){return this.limit}getMaster(){return this.master}getCreator(){return this.creator}getName(){return this.name}getMsgSeq(){return this.msgSeq}changeMaster(e,t){if(e!=this.getMaster())return this.client.changeMaster(this.roomId,this.userId,e,t).then((()=>{this.master=e})).catch((e=>{Logger$1.Log().error(circularJson_node.stringify(e))}))}syncUser(e){return this.client.syncUser(e).then((e=>(Logger$1.Log().info("syncUser success"),e))).catch((e=>{Logger$1.Log().error("syncUser error",e)}))}evictUser(e){return this.client.evictUser(this.roomId,this.userId,e)}evictUser2(e,t,i){return e!=this.getMaster()?Promise.reject("not master."):this.client.evictUser(this.roomId,this.userId,t,i)}updateUser(e,t){return this.localParticipant.getID()==this.getMaster()||this.localParticipant.getPermission().getManage()||!t.permission&&e==this.localParticipant.getID()?this.client.updateUser(this.roomId,this.localParticipant.getID(),{info:t,target:e}).then((()=>{e==this.localParticipant.getID()&&this.localParticipant.update(t)})).catch((e=>{Logger$1.Log().error(e)})):Promise.reject({code:errors.ERR_PERMISSION,error:"permission denied."})}parseStreams(e,t){let i=[];if(t.streams)for(let r=0;r<t.streams.length;r++){let n=t.streams[r].params;const s=t.streams[r].streamId;let o={id:s,audio:n.audio,video:n.video,audio_enable:n.audio_enable,video_enable:n.video_enable,screen:s.endsWith("_screen")},a=new BloudStream(this.client,this,e,!1,o);i.push(a)}return i}parseJoinResponse(e){return this.logger.log(`room-connect耗时: ${e.duration}`),this.total=e.total,this.pagesize=e.pagesize,this.index=e.index,this.startup=e.startup,this.duration=e.duration,this.limit=e.limit,this.switch=e.switch,this.audiooff=e.audiooff,this.selfopenaudio=e.selfopenaudio,this.videooff=e.videooff,this.msgoff=e.msgoff,this.lock=e.lock,this.master=e.master,this.creator=e.creator,this.name=e.name,this.limit=e.limit,this.msgSeq=e.msgSeq,this.sessionId=e.sessionId,this.permission=e.permission,this.customStats=e.customStats,this.getLocalParticipant().getPermission().set(this.permission),{total:this.total,sessionId:this.sessionId,customStats:this.customStats,joinwait:e.joinwait,waitroom:e.waitroom,permission:e.permission,audiooff:e.audiooff}}syncRoom(){let e=this.getJoinUserInfo(this.options.userinfo,!0);return this.client.syncRoom(this.options.room,this.options.user,e).then((e=>{Logger$1.Log().log("bloud syncRoom response : "+circularJson_node.stringify(e));let t=this.parseJoinResponse(e);this.fire("room-synced",[t])})).catch((e=>{throw Logger$1.Log().error(e),this.fire("error-room",[{error:e}]),e}))}update(e={}){return"string"==typeof e.secret&&(e.secret=md5(`${this.roomId}.${e.secret}`)),this.client.updateRoom(this.roomId,this.userId,e).then((()=>{"boolean"==typeof e.audiooff&&(this.audiooff=e.audiooff),"boolean"==typeof e.videooff&&(this.videooff=e.videooff),"boolean"==typeof e.msgoff&&(this.msgoff=e.msgoff),"boolean"==typeof e.switch&&(this.switch=e.switch),"string"==typeof e.secret&&(this.secret=e.secret),"boolean"==typeof e.lock&&(this.lock=e.lock),"boolean"==typeof e.selfopenaudio&&(this.selfopenaudio=e.selfopenaudio),Logger$1.Log().info(e)})).catch((e=>{throw Logger$1.Log().error(e),e}))}updateCustomStats(e,t){return e=e||{},this.client.updateCustomStats(this.roomId,this.userId,e,t).then((()=>{Logger$1.Log().info("updateCustomStats:"+circularJson_node.stringify(e))})).catch((e=>{throw Logger$1.Log().error(e),e}))}getMessages(e,t){return this.client.getMessages(this.roomId,this.userId,{startSeq:e,endSeq:t})}parseGetUser(e){const t=[];for(let i=0;i<e.length;i++){if(e[i].userId===this.getLocalParticipant().getID()){t.push(this.getLocalParticipant());continue}const r=new Participant(!1,e[i].userId,e[i]);this.parseStreams(r,e[i]).forEach((e=>r.addStream(e))),t.push(r)}return t}getUsers(e,t,i,r=!1){return this.index=e,this.pagesize=i||this.pagesize,this.client.getUsers(this.roomId,this.userId,this.pagesize,this.index+1,t,r).then((e=>{const t=e.value;this.total=e.total,this.pagesize=e.pagesize,this.index=e.index;const i=this.parseGetUser(t);return this.fire("users-list",[{usersEvent:{participants:i}}]),{participants:i,total:this.total}}))}getTotalUsers(){return this.total}getInfo(e){return e.ua=e.ua?e.ua:getUserAgent$1(),e.device=e.device?e.device:getBrowser$1(),e.platform=e.platform?e.platform:"Web",e.network=e.network?e.network:"unknown",e.role=e.role?e.role:"anchor",e.create=this.create,e.secret=this.secret,e.nickname=this.nickname,e.userinfo=this.userinfo,e.permission=this.permission,e.custom_token=this.custom_token,e.name=this.name,this.create&&(e.limit=this.limit,e.limittime=this.limittime,e.stoptime=this.stoptime),e.pagesize=this.pagesize,e}getCustomStats(){return this.customStats}sendMessage(e,t){return this.client.sendMessage(this.roomId,this.userId,t,e).then((e=>(Logger$1.Log().log(circularJson_node.stringify(e)),e))).catch((e=>{throw Logger$1.Log().error(e),e}))}customMessage(e,t){return this.client.customMessage(this.roomId,this.userId,t,e).then((e=>(Logger$1.Log().log(circularJson_node.stringify(e)),e))).catch((e=>{throw Logger$1.Log().error(e),e}))}moveUserRoom(e,t,i){return this.client.moveUserRoom(e,t,i)}release(){return this.client.releaseRoom(this.roomId,this.userId).then((e=>(Logger$1.Log().log(circularJson_node.stringify(e)),e))).catch((e=>{throw Logger$1.Log().error(e),e}))}close(){this.client&&(this.client.close(),this.client=void 0)}SpeakerDetector(){return new SpeakerDetector}Recorder(e){var t;let i=new Recorder(e);return Logger$1.Log().info("create local recorder"),i.addEventListener("started",(()=>{Logger$1.Log().info("local recorder started.")})),i.addEventListener("stopped",(()=>{var e,t;Logger$1.Log().info("local recorder stopped");let r=null===(e=this.recorders)||void 0===e?void 0:e.indexOf(i);r&&r>=0&&(this.recorders=null===(t=this.recorders)||void 0===t?void 0:t.splice(r,1))})),i.addEventListener("track-ended",(()=>{Logger$1.Log().info("local recorder track ended")})),null===(t=this.recorders)||void 0===t||t.push(i),i}removeAllListeners(){this.off()}Stream(e){if(this.client)return new BloudStream(this.client,this,this.getLocalParticipant(),!0,e)}}const Bloud={Room:Room,Stream:BloudStream,getUserMedia:function(e){return e.screen?BloudStream.sharing().start(e):(e.audio&&e.audio.deviceId&&(e.audio.deviceId={exact:e.audio.deviceId}),e.video&&e.video.deviceId&&(e.video.deviceId={exact:e.video.deviceId}),navigator.mediaDevices.getUserMedia(e))}};class SingleMode{static singleModeJoin(e,t){return __awaiter$1(this,void 0,void 0,(function*(){try{let i,r;try{i=yield e._getBloudProxiesUrl(e.token)}catch(e){return error$2("_getBloudProxiesUrl error","","",[JSON.stringify(e)]),Promise.reject(e)}switch(e.identity){case"5":r="RWPSAVM";break;case"3":case"4":r="RWPS";break;case"6":r="RWPAV"}const n={room:e.roomId,user:e.userId.toString(),enableCollection:!1,enableRace:!0,proxies:i.proxies,nickname:e.userinfo.nickname,custom_token:e.customToken,userinfo:e.userinfo,token:e.token,secret:e.secret,forceWS:!0,name:e.name,create:e.tarCreate,disableMediaEngine:e.disableMediaEngine,permission:r};try{e.client&&e.client.destroy()}catch(e){}e.client=new Bloud.Room(n),t(),yield e.client.connect(),info$1("singleModeJoin==>单一模式加入会议成功",e.userId,1)}catch(t){return error$2("singleModeJoin==>单一模式加入会议失败",e.userId,1,[JSON.stringify(t)]),e.bloud=null,e.client=null,Promise.reject(t)}}))}static singleModeLeave(e){return __awaiter$1(this,void 0,void 0,(function*(){if(!e.client)throw new Error("没有 joined");try{yield e.client.leave(),console.log("client leave success",e.userId),e.clearObject()}catch(t){throw console.log("client leave fail",e.userId,[t]),e.clearObject(),new Error(t)}}))}}const TRUE$1=!0,FALSE$1=!1,NULL$1=null,UNDEFINED$1=void 0,MINUS_ONE$1=-1,RAW_UNDEFINED$1="undefined",RAW_FUNCTION$1="function",RAW_DOT$1=".",WINDOW$1=typeof window!==RAW_UNDEFINED$1?window:UNDEFINED$1,GLOBAL$1=typeof global$3!==RAW_UNDEFINED$1?global$3:WINDOW$1,EMPTY_FUNCTION$1$1=function(){};Object.freeze({});const EMPTY_ARRAY=Object.freeze([]),EMPTY_STRING$1="";function func$2(e){return typeof e===RAW_FUNCTION$1}function array$1(e){return Array.isArray(e)}function object$1(e){return e!==NULL$1&&"object"==typeof e}function string$1(e){return"string"==typeof e}function number$1(e){return"number"==typeof e&&!isNaN(e)}function execute$1(e,t,i){if(func$2(e))return array$1(i)?e.apply(t,i):t!==UNDEFINED$1?e.call(t,i):i!==UNDEFINED$1?e(i):e()}class CustomEvent$1{constructor(e,t){this.type=e,this.phase=CustomEvent$1.PHASE_CURRENT,t&&(this.originalEvent=t)}preventDefault(){const e=this;if(!e.isPrevented){const{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=TRUE$1}return e}stopPropagation(){const e=this;if(!e.isStoped){const{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=TRUE$1}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}}function each$3(e,t,i){const{length:r}=e;if(r)if(i)for(let i=r-1;i>=0&&t(e[i],i)!==FALSE$1;i--);else for(let i=0;i<r&&t(e[i],i)!==FALSE$1;i++);}function nativePush$1(e,t){e[e.length]=t}function addItem$1(e,t,i){array$1(t)?each$3(t,(function(t){i(e,t)})):i(e,t)}function push$1(e,t){addItem$1(e,t,nativePush$1)}function indexOf$3(e,t,i){let r=MINUS_ONE$1;return each$3(e,(function(e,n){if(i===FALSE$1?e==t:e===t)return r=n,FALSE$1})),r}function has$1$2(e,t,i){return indexOf$3(e,t,i)>=0}function toArray(e){return array$1(e)?e:execute$1(EMPTY_ARRAY.slice,e)}function slice$1(e,t,i){return number$1(i)?t===i?EMPTY_STRING$1:e.slice(t,i):e.slice(t)}function indexOf$2(e,t,i){return e.indexOf(t,i!==UNDEFINED$1?i:0)}function each$2(e,t){for(let i in e)if(t(e[i],i)===FALSE$1)break}function copy$1(e,t){let i=e;return array$1(e)?t?(i=[],each$3(e,(function(e,r){i[r]=copy$1(e,t)}))):i=e.slice():object$1(e)&&(i={},each$2(e,(function(e,r){i[r]=t?copy$1(e,t):e}))),i}function toString$1(e,t){return e!=NULL$1&&e.toString?e.toString():t!==UNDEFINED$1?t:EMPTY_STRING$1}CustomEvent$1.PHASE_CURRENT=0,CustomEvent$1.PHASE_UPWARD=1,CustomEvent$1.PHASE_DOWNWARD=MINUS_ONE$1;const DEBUG$2=1,INFO$1=2,WARN$1$1=3,FATAL$1=5,nativeConsole$1=typeof console!==RAW_UNDEFINED$1?console:NULL$1,defaultLogLevel$1=/yox/.test(toString$1(EMPTY_FUNCTION$1$1))?INFO$1:WARN$1$1,stylePrefix$1=WINDOW$1&&/edge|msie|trident/i.test(WINDOW$1.navigator.userAgent)?EMPTY_STRING$1:"%c",printLog$1=nativeConsole$1?stylePrefix$1?function(e,t,i,r){r?nativeConsole$1.log(stylePrefix$1+e,i,t,r):nativeConsole$1.log(stylePrefix$1+e,i,t)}:function(e,t,i){i?nativeConsole$1.log(e,t,i):nativeConsole$1.log(e,t)}:EMPTY_FUNCTION$1$1;function getLogLevel$1(){if(GLOBAL$1){const e=GLOBAL$1.YOX_LOG_LEVEL;if(e>=DEBUG$2&&e<=FATAL$1)return e}return defaultLogLevel$1}function getStyle$1(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function warn$1$1(e,t){getLogLevel$1()<=WARN$1$1&&printLog$1(t||"bjy warn",e,getStyle$1("#f90"))}function fatal$1(e,t){if(getLogLevel$1()<=FATAL$1)throw new Error(`[${t||"bjy fatal"}]: ${e}`)}class Emitter$1{constructor(e){this.ns=e||FALSE$1,this.listeners={}}fire(e,t,i){let r=this,n=string$1(e)?r.parse(e):e,s=r.listeners[n.type],o=TRUE$1;if(s){s=copy$1(s);const e=t&&t[0]instanceof CustomEvent$1?t[0]:UNDEFINED$1;each$3(s,(function(a){if(!matchNamespace$1(n.ns,a,TRUE$1)||!has$1$2(s,a)||i&&!i(n,t,a))return;e&&(e.listener=a.fn);let c=execute$1(a.fn,a.ctx,t);return e&&(e.listener=UNDEFINED$1),a.num=a.num?a.num+1:1,a.num===a.max&&r.off(n,a.fn),e&&(c===FALSE$1?e.prevent().stop():e.isStoped&&(c=FALSE$1)),c===FALSE$1?o=FALSE$1:void 0}))}return o}on(e,t){const i=this,r=i.listeners,n=func$2(t)?{fn:t}:t;if(object$1(n)&&func$2(n.fn)){const t=string$1(e)?i.parse(e):e;n.ns=t.ns,push$1(r[t.type]||(r[t.type]=[]),n)}else"development"===process$3.env.NODE_ENV&&fatal$1('emitter.on(type, listener) invoke failed:\n\n"listener" is expected to be a Function or an EmitterOptions.\n')}off(e,t){const i=this,r=i.listeners;if(e){const n=string$1(e)?i.parse(e):e,s=n.type,o=n.ns,a=createMatchListener$1(t),c=function(e,t){each$3(e,(function(t,i){a(t)&&e.splice(i,1)}),TRUE$1),e.length||delete r[t]},u=function(e,t){each$3(e,(function(t,i){matchNamespace$1(o,t)&&e.splice(i,1)}),TRUE$1),e.length||delete r[t]};s?r[s]&&c(r[s],s):o&&each$2(r,u),"development"===process$3.env.NODE_ENV&&arguments.length>1&&t==NULL$1&&warn$1$1(`emitter.off(type, listener) is invoked, but "listener" is ${t}.`)}else i.listeners={},"development"===process$3.env.NODE_ENV&&arguments.length>0&&warn$1$1(`emitter.off(type) is invoked, but "type" is ${e}.`)}has(e,t){let i=this.listeners,r=string$1(e)?this.parse(e):e,n=r.type,s=r.ns,o=TRUE$1,a=createMatchListener$1(t),c=function(e){return each$3(e,(function(e){if(a(e))return o=FALSE$1})),o};return n?i[n]&&c(i[n]):s&&each$2(i,c),!o}parse(e){const t={type:e,ns:EMPTY_STRING$1};if(this.ns){const i=indexOf$2(e,RAW_DOT$1);i>=0&&(t.type=slice$1(e,0,i),t.ns=slice$1(e,i+1))}return t}}function matchTrue$1(){return TRUE$1}function createMatchListener$1(e){return func$2(e)?function(t){return e===t.fn}:matchTrue$1}function matchNamespace$1(e,t,i){const{ns:r}=t;return r&&e?r===e:i?TRUE$1:FALSE$1}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var BRTC$2={exports:{}};BRTC$2.exports=function(e){var t={};function i(r){if(t[r])return t[r].exports;var n=t[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=e,i.c=t,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(r,n,function(t){return e[t]}.bind(null,n));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=30)}([function(e,t,i){i.d(t,"d",(function(){return n})),i.d(t,"a",(function(){return s})),i.d(t,"h",(function(){return o})),i.d(t,"i",(function(){return a})),i.d(t,"f",(function(){return c})),i.d(t,"c",(function(){return u})),i.d(t,"g",(function(){return d})),i.d(t,"e",(function(){return h})),i.d(t,"b",(function(){return m}));var r=i(2);function n(e){return typeof e===r.i}function s(e){return Array.isArray(e)}function o(e){return e!==r.g&&"object"==typeof e}function a(e){return"string"==typeof e}function c(e){return"number"==typeof e&&!isNaN(e)}function u(e){return"boolean"==typeof e}function d(e){return c(e)||a(e)&&!isNaN(parseFloat(e))&&isFinite(+e)}const l={}.hasOwnProperty;function h(e){if(!o(e)||e.nodeType||e===e.window)return!1;if(e.constructor&&!l.call(e,"constructor")&&!l.call(e.constructor.prototype||{},"isPrototypeOf"))return!1;let t;for(t in e);return void 0===t||l.call(e,t)}function m(e){return e instanceof ArrayBuffer}},function(e,t,i){i.r(t),function(e){i.d(t,"TRACE",(function(){return s})),i.d(t,"DEBUG",(function(){return o})),i.d(t,"INFO",(function(){return a})),i.d(t,"WARN",(function(){return c})),i.d(t,"ERROR",(function(){return u})),i.d(t,"FATAL",(function(){return d})),i.d(t,"setLevel",(function(){return g})),i.d(t,"trace",(function(){return y})),i.d(t,"debug",(function(){return S})),i.d(t,"info",(function(){return E})),i.d(t,"call",(function(){return b})),i.d(t,"warn",(function(){return T})),i.d(t,"error",(function(){return I})),i.d(t,"fatal",(function(){return C})),i.d(t,"log",(function(){return w})),i.d(t,"setDefaultTag",(function(){return R})),i.d(t,"enableUploadLog",(function(){return M})),i.d(t,"disableUploadLog",(function(){return O})),i.d(t,"canUploadLog",(function(){return L})),i.d(t,"setUploadLevel",(function(){return P})),i.d(t,"getUploadLevel",(function(){return N}));var r=i(2),n=i(3);const s=0,o=1,a=2,c=3,u=4,d=5;let l="bjy";const h=typeof console!==r.j?console:r.g,m=/bjy/.test(Object(n.a)(r.b))?a:c,p=r.n&&/edge|msie|trident/i.test(r.n.navigator.userAgent)?r.c:"%c",f=h?p?function(e,t,i,r){r?h.log(p+e,i,t,r):h.log(p+e,i,t)}:function(e,t,i){i?h.log(e,t,i):h.log(e,t)}:r.b;function v(){if(r.e){const e=r.e.BJY_LOG_LEVEL;if(e>=s&&e<=d)return e}return m}function g(t){e.BJY_LOG_LEVEL=t}function _(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function y(e,t){v()<=s&&f((t||l)+" trace",e,_("#999"))}function S(e,t){v()<=o&&f((t||l)+" debug",e,_("#999"))}function E(e,t){v()<=a&&f((t||l)+" info",e,_("#2db7f5"))}function b(e,t,i){v()<=a&&f((t||l)+" info",e,_("#66cdaa"),i)}function T(e,t){v()<=c&&f((t||l)+" warn",e,_("#f90"))}function I(e,t){v()<=u&&f((t||l)+" error",e,_("#ed4014"))}function C(e,t){if(v()<=d)throw new Error(`[${t||l} fatal]: ${e}`)}function w(e,t,i){e===s?y(t,i):e===o?S(t,i):e===a?E(t,i):e===c?T(t,i):e===u?I(t,i):e===d&&C(t,i)}function R(e){l=e}let k=!0,A=c;function M(){k=!0}function O(){k=!1}function L(){return k}function P(e){A=e}function N(){return A}}.call(this,i(7))},function(e,t,i){(function(e){i.d(t,"l",(function(){return r})),i.d(t,"d",(function(){return n})),i.d(t,"g",(function(){return s})),i.d(t,"m",(function(){return o})),i.d(t,"f",(function(){return a})),i.d(t,"j",(function(){return c})),i.d(t,"i",(function(){return u})),i.d(t,"k",(function(){return d})),i.d(t,"h",(function(){return l})),i.d(t,"n",(function(){return h})),i.d(t,"e",(function(){return m})),i.d(t,"b",(function(){return p})),i.d(t,"a",(function(){return f})),i.d(t,"c",(function(){return v}));const r=!0,n=!1,s=null,o=void 0,a=-1,c="undefined",u="function",d="*",l=".",h=typeof window!==c?window:o,m=typeof e!==c?e:h,p=function(){},f=(Object.freeze({}),Object.freeze([])),v=""}).call(this,i(7))},function(e,t,i){i.d(t,"a",(function(){return n}));var r=i(2);function n(e,t){return e!=r.g&&e.toString?e.toString():t!==r.m?t:r.c}},function(e,t,i){i.d(t,"c",(function(){return s})),i.d(t,"b",(function(){return o})),i.d(t,"d",(function(){return a})),i.d(t,"a",(function(){return c}));var r=i(0),n=i(2);function s(e,t,i){return r.f(i)?t===i?n.c:e.slice(t,i):e.slice(t)}function o(e,t,i){return e.indexOf(t,i!==n.m?i:0)}function a(e,t){return 0===o(e,t)}function c(e,t){return o(e,t)>=0}i(3)},function(e,t,i){(function(e){var r=i(8),n=i(2);let s;typeof e===n.i&&Object(r.a)(e)&&(s=e),s=typeof MessageChannel===n.i&&Object(r.a)(MessageChannel)?function(e){const t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(1)}:setTimeout,t.a=s}).call(this,i(14).setImmediate)},function(e,t,i){(function(t){e.exports=function(){function e(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function i(t){for(var i=1;i<arguments.length;i++){var r=null!=arguments[i]?arguments[i]:{};i%2?e(Object(r),!0).forEach((function(e){d(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):e(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function r(){r=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},s=n.iterator||"@@iterator",o=n.asyncIterator||"@@asyncIterator",a=n.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function u(e,t,i,r){var n=t&&t.prototype instanceof h?t:h,s=Object.create(n.prototype),o=new I(r||[]);return s._invoke=function(e,t,i){var r="suspendedStart";return function(n,s){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===n)throw s;return{value:void 0,done:!0}}for(i.method=n,i.arg=s;;){var o=i.delegate;if(o){var a=E(o,i);if(a){if(a===l)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===r)throw r="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);r="executing";var c=d(e,t,i);if("normal"===c.type){if(r=i.done?"completed":"suspendedYield",c.arg===l)continue;return{value:c.arg,done:i.done}}"throw"===c.type&&(r="completed",i.method="throw",i.arg=c.arg)}}}(e,i,o),s}function d(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var l={};function h(){}function m(){}function p(){}var f={};c(f,s,(function(){return this}));var v=Object.getPrototypeOf,g=v&&v(v(C([])));g&&g!==t&&i.call(g,s)&&(f=g);var _=p.prototype=h.prototype=Object.create(f);function y(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function S(e,t){function r(n,s,o,a){var c=d(e[n],e,s);if("throw"!==c.type){var u=c.arg,l=u.value;return l&&"object"==typeof l&&i.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,o,a)}),(function(e){r("throw",e,o,a)})):t.resolve(l).then((function(e){u.value=e,o(u)}),(function(e){return r("throw",e,o,a)}))}a(c.arg)}var n;this._invoke=function(e,i){function s(){return new t((function(t,n){r(e,i,t,n)}))}return n=n?n.then(s,s):s()}}function E(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,E(e,t),"throw"===t.method))return l;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return l}var r=d(i,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,l;var n=r.arg;return n?n.done?(t[e.resultName]=n.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,l):n:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,l)}function b(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(b,this),this.reset(!0)}function C(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,n=function t(){for(;++r<e.length;)if(i.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return n.next=n}}return{next:w}}function w(){return{value:void 0,done:!0}}return m.prototype=p,c(_,"constructor",p),c(p,"constructor",m),m.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(_),e},e.awrap=function(e){return{__await:e}},y(S.prototype),c(S.prototype,o,(function(){return this})),e.AsyncIterator=S,e.async=function(t,i,r,n,s){void 0===s&&(s=Promise);var o=new S(u(t,i,r,n),s);return e.isGeneratorFunction(i)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},y(_),c(_,a,"Generator"),c(_,s,(function(){return this})),c(_,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var i in e)t.push(i);return t.reverse(),function i(){for(;t.length;){var r=t.pop();if(r in e)return i.value=r,i.done=!1,i}return i.done=!0,i}},e.values=C,I.prototype={constructor:I,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(i,r){return o.type="throw",o.arg=e,t.next=i,r&&(t.method="next",t.arg=void 0),!!r}for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n],o=s.completion;if("root"===s.tryLoc)return r("end");if(s.tryLoc<=this.prev){var a=i.call(s,"catchLoc"),c=i.call(s,"finallyLoc");if(a&&c){if(this.prev<s.catchLoc)return r(s.catchLoc,!0);if(this.prev<s.finallyLoc)return r(s.finallyLoc)}else if(a){if(this.prev<s.catchLoc)return r(s.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return r(s.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var s=n;break}}s&&("break"===e||"continue"===e)&&s.tryLoc<=t&&t<=s.finallyLoc&&(s=null);var o=s?s.completion:{};return o.type=e,o.arg=t,s?(this.method="next",this.next=s.finallyLoc,l):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),l},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),T(i),l}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var r=i.completion;if("throw"===r.type){var n=r.arg;T(i)}return n}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),l}},e}function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t,i,r,n,s,o){try{var a=e[s](o),c=a.value}catch(e){return void i(e)}a.done?t(c):Promise.resolve(c).then(r,n)}function o(e){return function(){var t=this,i=arguments;return new Promise((function(r,n){var o=e.apply(t,i);function a(e){s(o,r,n,a,c,"next",e)}function c(e){s(o,r,n,a,c,"throw",e)}a(void 0)}))}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function u(e,t,i){return t&&c(e.prototype,t),i&&c(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function d(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&m(e,t)}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,t){return(m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function f(e,t,i){return(f=p()?Reflect.construct.bind():function(e,t,i){var r=[null];r.push.apply(r,t);var n=new(Function.bind.apply(e,r));return i&&m(n,i.prototype),n}).apply(null,arguments)}function v(e){var t="function"==typeof Map?new Map:void 0;return(v=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf("[native code]")))return e;var i;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return f(e,arguments,h(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),m(r,e)})(e)}function g(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function _(e){var t=p();return function(){var i,r=h(e);if(t){var n=h(this).constructor;i=Reflect.construct(r,arguments,n)}else i=r.apply(this,arguments);return g(this,i)}}function y(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=h(e)););return e}function S(){return(S="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var r=y(e,t);if(r){var n=Object.getOwnPropertyDescriptor(r,t);return n.get?n.get.call(arguments.length<3?e:i):n.value}}).apply(this,arguments)}function E(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,n,s=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(r=i.next()).done)&&(s.push(r.value),!t||s.length!==t);o=!0);}catch(e){a=!0,n=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw n}}return s}}(e,t)||T(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function b(e){return function(e){if(Array.isArray(e))return I(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||T(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function T(e,t){if(e){if("string"==typeof e)return I(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?I(e,t):void 0}}function I(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=new Array(t);i<t;i++)r[i]=e[i];return r}function C(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=T(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var r=0,n=function(){};return{s:n,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,s=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw s}}}}function w(e,t,i,r,n){var s={};return Object.keys(r).forEach((function(e){s[e]=r[e]})),s.enumerable=!!s.enumerable,s.configurable=!!s.configurable,("value"in s||s.initializer)&&(s.writable=!0),s=i.slice().reverse().reduce((function(i,r){return r(e,t,i)||i}),s),n&&void 0!==s.initializer&&(s.value=s.initializer?s.initializer.call(n):void 0,s.initializer=void 0),void 0===s.initializer&&(Object.defineProperty(e,t,s),s=null),s}var R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{},k=function(e){return e&&e.Math==Math&&e},A=k("object"==typeof globalThis&&globalThis)||k("object"==typeof window&&window)||k("object"==typeof self&&self)||k("object"==typeof R&&R)||function(){return this}()||Function("return this")(),M={},O=function(e){try{return!!e()}catch(e){return!0}},L=!O((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),P=!O((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),N=P,D=Function.prototype.call,x=N?D.bind(D):function(){return D.apply(D,arguments)},U={},$={}.propertyIsEnumerable,B=Object.getOwnPropertyDescriptor,V=B&&!$.call({1:2},1);U.f=V?function(e){var t=B(this,e);return!!t&&t.enumerable}:$;var F,j,H=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},W=P,G=Function.prototype,q=G.call,J=W&&G.bind.bind(q,q),z=function(e){return W?J(e):function(){return q.apply(e,arguments)}},Y=z,Q=Y({}.toString),K=Y("".slice),X=function(e){return K(Q(e),8,-1)},Z=X,ee=z,te=function(e){if("Function"===Z(e))return ee(e)},ie=O,re=X,ne=Object,se=te("".split),oe=ie((function(){return!ne("z").propertyIsEnumerable(0)}))?function(e){return"String"==re(e)?se(e,""):ne(e)}:ne,ae=function(e){return null==e},ce=ae,ue=TypeError,de=function(e){if(ce(e))throw ue("Can't call method on "+e);return e},le=oe,he=de,me=function(e){return le(he(e))},pe="object"==typeof document&&document.all,fe={all:pe,IS_HTMLDDA:void 0===pe&&void 0!==pe},ve=fe.all,ge=fe.IS_HTMLDDA?function(e){return"function"==typeof e||e===ve}:function(e){return"function"==typeof e},_e=ge,ye=fe.all,Se=fe.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:_e(e)||e===ye}:function(e){return"object"==typeof e?null!==e:_e(e)},Ee=A,be=ge,Te=function(e){return be(e)?e:void 0},Ie=function(e,t){return arguments.length<2?Te(Ee[e]):Ee[e]&&Ee[e][t]},Ce=te({}.isPrototypeOf),we=Ie("navigator","userAgent")||"",Re=A,ke=we,Ae=Re.process,Me=Re.Deno,Oe=Ae&&Ae.versions||Me&&Me.version,Le=Oe&&Oe.v8;Le&&(j=(F=Le.split("."))[0]>0&&F[0]<4?1:+(F[0]+F[1])),!j&&ke&&(!(F=ke.match(/Edge\/(\d+)/))||F[1]>=74)&&(F=ke.match(/Chrome\/(\d+)/))&&(j=+F[1]);var Pe=j,Ne=Pe,De=O,xe=!!Object.getOwnPropertySymbols&&!De((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ne&&Ne<41})),Ue=xe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,$e=Ie,Be=ge,Ve=Ce,Fe=Object,je=Ue?function(e){return"symbol"==typeof e}:function(e){var t=$e("Symbol");return Be(t)&&Ve(t.prototype,Fe(e))},He=String,We=function(e){try{return He(e)}catch(e){return"Object"}},Ge=ge,qe=We,Je=TypeError,ze=function(e){if(Ge(e))return e;throw Je(qe(e)+" is not a function")},Ye=ze,Qe=ae,Ke=function(e,t){var i=e[t];return Qe(i)?void 0:Ye(i)},Xe=x,Ze=ge,et=Se,tt=TypeError,it={exports:{}},rt=A,nt=Object.defineProperty,st=function(e,t){try{nt(rt,e,{value:t,configurable:!0,writable:!0})}catch(i){rt[e]=t}return t},ot=st,at="__core-js_shared__",ct=A[at]||ot(at,{}),ut=ct;(it.exports=function(e,t){return ut[e]||(ut[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.25.5",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.25.5/LICENSE",source:"https://github.com/zloirock/core-js"});var dt=de,lt=Object,ht=function(e){return lt(dt(e))},mt=ht,pt=te({}.hasOwnProperty),ft=Object.hasOwn||function(e,t){return pt(mt(e),t)},vt=te,gt=0,_t=Math.random(),yt=vt(1..toString),St=function(e){return"Symbol("+(void 0===e?"":e)+")_"+yt(++gt+_t,36)},Et=A,bt=it.exports,Tt=ft,It=St,Ct=xe,wt=Ue,Rt=bt("wks"),kt=Et.Symbol,At=kt&&kt.for,Mt=wt?kt:kt&&kt.withoutSetter||It,Ot=function(e){if(!Tt(Rt,e)||!Ct&&"string"!=typeof Rt[e]){var t="Symbol."+e;Ct&&Tt(kt,e)?Rt[e]=kt[e]:Rt[e]=wt&&At?At(t):Mt(t)}return Rt[e]},Lt=x,Pt=Se,Nt=je,Dt=Ke,xt=TypeError,Ut=Ot("toPrimitive"),$t=function(e,t){if(!Pt(e)||Nt(e))return e;var i,r=Dt(e,Ut);if(r){if(void 0===t&&(t="default"),i=Lt(r,e,t),!Pt(i)||Nt(i))return i;throw xt("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var i,r;if("string"===t&&Ze(i=e.toString)&&!et(r=Xe(i,e)))return r;if(Ze(i=e.valueOf)&&!et(r=Xe(i,e)))return r;if("string"!==t&&Ze(i=e.toString)&&!et(r=Xe(i,e)))return r;throw tt("Can't convert object to primitive value")}(e,t)},Bt=$t,Vt=je,Ft=function(e){var t=Bt(e,"string");return Vt(t)?t:t+""},jt=Se,Ht=A.document,Wt=jt(Ht)&&jt(Ht.createElement),Gt=function(e){return Wt?Ht.createElement(e):{}},qt=Gt,Jt=!L&&!O((function(){return 7!=Object.defineProperty(qt("div"),"a",{get:function(){return 7}}).a})),zt=L,Yt=x,Qt=U,Kt=H,Xt=me,Zt=Ft,ei=ft,ti=Jt,ii=Object.getOwnPropertyDescriptor;M.f=zt?ii:function(e,t){if(e=Xt(e),t=Zt(t),ti)try{return ii(e,t)}catch(e){}if(ei(e,t))return Kt(!Yt(Qt.f,e,t),e[t])};var ri={},ni=L&&O((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),si=Se,oi=String,ai=TypeError,ci=function(e){if(si(e))return e;throw ai(oi(e)+" is not an object")},ui=L,di=Jt,li=ni,hi=ci,mi=Ft,pi=TypeError,fi=Object.defineProperty,vi=Object.getOwnPropertyDescriptor;ri.f=ui?li?function(e,t,i){if(hi(e),t=mi(t),hi(i),"function"==typeof e&&"prototype"===t&&"value"in i&&"writable"in i&&!i.writable){var r=vi(e,t);r&&r.writable&&(e[t]=i.value,i={configurable:"configurable"in i?i.configurable:r.configurable,enumerable:"enumerable"in i?i.enumerable:r.enumerable,writable:!1})}return fi(e,t,i)}:fi:function(e,t,i){if(hi(e),t=mi(t),hi(i),di)try{return fi(e,t,i)}catch(e){}if("get"in i||"set"in i)throw pi("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var gi=ri,_i=H,yi=L?function(e,t,i){return gi.f(e,t,_i(1,i))}:function(e,t,i){return e[t]=i,e},Si={exports:{}},Ei=L,bi=ft,Ti=Function.prototype,Ii=Ei&&Object.getOwnPropertyDescriptor,Ci=bi(Ti,"name"),wi={EXISTS:Ci,PROPER:Ci&&"something"===function(){}.name,CONFIGURABLE:Ci&&(!Ei||Ei&&Ii(Ti,"name").configurable)},Ri=ge,ki=ct,Ai=te(Function.toString);Ri(ki.inspectSource)||(ki.inspectSource=function(e){return Ai(e)});var Mi,Oi,Li,Pi=ki.inspectSource,Ni=ge,Di=A.WeakMap,xi=Ni(Di)&&/native code/.test(String(Di)),Ui=it.exports,$i=St,Bi=Ui("keys"),Vi=function(e){return Bi[e]||(Bi[e]=$i(e))},Fi={},ji=xi,Hi=A,Wi=Se,Gi=yi,qi=ft,Ji=ct,zi=Vi,Yi=Fi,Qi="Object already initialized",Ki=Hi.TypeError,Xi=Hi.WeakMap;if(ji||Ji.state){var Zi=Ji.state||(Ji.state=new Xi);Zi.get=Zi.get,Zi.has=Zi.has,Zi.set=Zi.set,Mi=function(e,t){if(Zi.has(e))throw Ki(Qi);return t.facade=e,Zi.set(e,t),t},Oi=function(e){return Zi.get(e)||{}},Li=function(e){return Zi.has(e)}}else{var er=zi("state");Yi[er]=!0,Mi=function(e,t){if(qi(e,er))throw Ki(Qi);return t.facade=e,Gi(e,er,t),t},Oi=function(e){return qi(e,er)?e[er]:{}},Li=function(e){return qi(e,er)}}var tr={set:Mi,get:Oi,has:Li,enforce:function(e){return Li(e)?Oi(e):Mi(e,{})},getterFor:function(e){return function(t){var i;if(!Wi(t)||(i=Oi(t)).type!==e)throw Ki("Incompatible receiver, "+e+" required");return i}}},ir=O,rr=ge,nr=ft,sr=L,or=wi.CONFIGURABLE,ar=Pi,cr=tr.enforce,ur=tr.get,dr=Object.defineProperty,lr=sr&&!ir((function(){return 8!==dr((function(){}),"length",{value:8}).length})),hr=String(String).split("String"),mr=Si.exports=function(e,t,i){"Symbol("===String(t).slice(0,7)&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!nr(e,"name")||or&&e.name!==t)&&(sr?dr(e,"name",{value:t,configurable:!0}):e.name=t),lr&&i&&nr(i,"arity")&&e.length!==i.arity&&dr(e,"length",{value:i.arity});try{i&&nr(i,"constructor")&&i.constructor?sr&&dr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(e){}var r=cr(e);return nr(r,"source")||(r.source=hr.join("string"==typeof t?t:"")),e};Function.prototype.toString=mr((function(){return rr(this)&&ur(this).source||ar(this)}),"toString");var pr=ge,fr=ri,vr=Si.exports,gr=st,_r=function(e,t,i,r){r||(r={});var n=r.enumerable,s=void 0!==r.name?r.name:t;if(pr(i)&&vr(i,s,r),r.global)n?e[t]=i:gr(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(e){}n?e[t]=i:fr.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},yr={},Sr=Math.ceil,Er=Math.floor,br=Math.trunc||function(e){var t=+e;return(t>0?Er:Sr)(t)},Tr=function(e){var t=+e;return t!=t||0===t?0:br(t)},Ir=Tr,Cr=Math.max,wr=Math.min,Rr=function(e,t){var i=Ir(e);return i<0?Cr(i+t,0):wr(i,t)},kr=Tr,Ar=Math.min,Mr=function(e){return e>0?Ar(kr(e),9007199254740991):0},Or=Mr,Lr=function(e){return Or(e.length)},Pr=me,Nr=Rr,Dr=Lr,xr=function(e){return function(t,i,r){var n,s=Pr(t),o=Dr(s),a=Nr(r,o);if(e&&i!=i){for(;o>a;)if((n=s[a++])!=n)return!0}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},Ur={includes:xr(!0),indexOf:xr(!1)},$r=ft,Br=me,Vr=Ur.indexOf,Fr=Fi,jr=te([].push),Hr=function(e,t){var i,r=Br(e),n=0,s=[];for(i in r)!$r(Fr,i)&&$r(r,i)&&jr(s,i);for(;t.length>n;)$r(r,i=t[n++])&&(~Vr(s,i)||jr(s,i));return s},Wr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Gr=Hr,qr=Wr.concat("length","prototype");yr.f=Object.getOwnPropertyNames||function(e){return Gr(e,qr)};var Jr={};Jr.f=Object.getOwnPropertySymbols;var zr=Ie,Yr=yr,Qr=Jr,Kr=ci,Xr=te([].concat),Zr=zr("Reflect","ownKeys")||function(e){var t=Yr.f(Kr(e)),i=Qr.f;return i?Xr(t,i(e)):t},en=ft,tn=Zr,rn=M,nn=ri,sn=O,on=ge,an=/#|\.prototype\./,cn=function(e,t){var i=dn[un(e)];return i==hn||i!=ln&&(on(t)?sn(t):!!t)},un=cn.normalize=function(e){return String(e).replace(an,".").toLowerCase()},dn=cn.data={},ln=cn.NATIVE="N",hn=cn.POLYFILL="P",mn=cn,pn=A,fn=M.f,vn=yi,gn=_r,_n=st,yn=function(e,t,i){for(var r=tn(t),n=nn.f,s=rn.f,o=0;o<r.length;o++){var a=r[o];en(e,a)||i&&en(i,a)||n(e,a,s(t,a))}},Sn=mn,En=function(e,t){var i,r,n,s,o,a=e.target,c=e.global,u=e.stat;if(i=c?pn:u?pn[a]||_n(a,{}):(pn[a]||{}).prototype)for(r in t){if(s=t[r],n=e.dontCallGetSet?(o=fn(i,r))&&o.value:i[r],!Sn(c?r:a+(u?".":"#")+r,e.forced)&&void 0!==n){if(typeof s==typeof n)continue;yn(s,n)}(e.sham||n&&n.sham)&&vn(s,"sham",!0),gn(i,r,s,e)}},bn=ze,Tn=P,In=te(te.bind),Cn=function(e,t){return bn(e),void 0===t?e:Tn?In(e,t):function(){return e.apply(t,arguments)}},wn=X,Rn=Array.isArray||function(e){return"Array"==wn(e)},kn={};kn[Ot("toStringTag")]="z";var An="[object z]"===String(kn),Mn=An,On=ge,Ln=X,Pn=Ot("toStringTag"),Nn=Object,Dn="Arguments"==Ln(function(){return arguments}()),xn=Mn?Ln:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=Nn(e),Pn))?i:Dn?Ln(t):"Object"==(r=Ln(t))&&On(t.callee)?"Arguments":r},Un=te,$n=O,Bn=ge,Vn=xn,Fn=Pi,jn=function(){},Hn=[],Wn=Ie("Reflect","construct"),Gn=/^\s*(?:class|function)\b/,qn=Un(Gn.exec),Jn=!Gn.exec(jn),zn=function(e){if(!Bn(e))return!1;try{return Wn(jn,Hn,e),!0}catch(e){return!1}},Yn=function(e){if(!Bn(e))return!1;switch(Vn(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jn||!!qn(Gn,Fn(e))}catch(e){return!0}};Yn.sham=!0;var Qn=!Wn||$n((function(){var e;return zn(zn.call)||!zn(Object)||!zn((function(){e=!0}))||e}))?Yn:zn,Kn=Rn,Xn=Qn,Zn=Se,es=Ot("species"),ts=Array,is=function(e,t){return new(function(e){var t;return Kn(e)&&(t=e.constructor,(Xn(t)&&(t===ts||Kn(t.prototype))||Zn(t)&&null===(t=t[es]))&&(t=void 0)),void 0===t?ts:t}(e))(0===t?0:t)},rs=Cn,ns=oe,ss=ht,os=Lr,as=is,cs=te([].push),us=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,s=6==e,o=7==e,a=5==e||s;return function(c,u,d,l){for(var h,m,p=ss(c),f=ns(p),v=rs(u,d),g=os(f),_=0,y=l||as,S=t?y(c,g):i||o?y(c,0):void 0;g>_;_++)if((a||_ in f)&&(m=v(h=f[_],_,p),e))if(t)S[_]=m;else if(m)switch(e){case 3:return!0;case 5:return h;case 6:return _;case 2:cs(S,h)}else switch(e){case 4:return!1;case 7:cs(S,h)}return s?-1:r||n?n:S}},ds={forEach:us(0),map:us(1),filter:us(2),some:us(3),every:us(4),find:us(5),findIndex:us(6),filterReject:us(7)},ls=O,hs=Pe,ms=Ot("species"),ps=function(e){return hs>=51||!ls((function(){var t=[];return(t.constructor={})[ms]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},fs=ds.map;En({target:"Array",proto:!0,forced:!ps("map")},{map:function(e){return fs(this,e,arguments.length>1?arguments[1]:void 0)}});var vs=ds.filter;En({target:"Array",proto:!0,forced:!ps("filter")},{filter:function(e){return vs(this,e,arguments.length>1?arguments[1]:void 0)}});var gs=xn,_s=An?{}.toString:function(){return"[object "+gs(this)+"]"};An||_r(Object.prototype,"toString",_s,{unsafe:!0});var ys=En,Ss=O,Es=me,bs=M.f,Ts=L,Is=Ss((function(){bs(1)}));ys({target:"Object",stat:!0,forced:!Ts||Is,sham:!Ts},{getOwnPropertyDescriptor:function(e,t){return bs(Es(e),t)}});let Cs=!0,ws=!0;function Rs(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function ks(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,s),n.apply(this,[e,s])};const s=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function As(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Cs=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Ms(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ws=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Os(){if("object"==typeof window){if(Cs)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ls(e,t){ws&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ps(e){return"[object Object]"===Object.prototype.toString.call(e)}function Ns(e){return Ps(e)?Object.keys(e).reduce((function(t,i){const r=Ps(e[i]),n=r?Ns(e[i]):e[i],s=r&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[i]:n})}),{}):e}function Ds(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&function e(t,i,r){i&&!r.has(i.id)&&(r.set(i.id,i),Object.keys(i).forEach((n=>{n.endsWith("Id")?e(t,t.get(i[n]),r):n.endsWith("Ids")&&i[n].forEach((i=>{e(t,t.get(i),r)}))})))}(e,i,n)}))})),n}const xs=Os;function Us(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),xs("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return xs("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function $s(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Bs(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ks(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Vs(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Fs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(s(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(n(t)))},i])})).then(i,r)}}function js(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ds(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ks(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ds(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Hs(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function Ws(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Hs(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=o(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Gs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function qs(e,t){ks(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Js=Object.freeze({__proto__:null,shimMediaStream:$s,shimOnTrack:Bs,shimGetSendersWithDtmf:Vs,shimGetStats:Fs,shimSenderReceiverGetStats:js,shimAddTrackRemoveTrackWithNative:Hs,shimAddTrackRemoveTrack:Ws,shimPeerConnection:Gs,fixNegotiationNeeded:qs,shimGetUserMedia:Us,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}}),zs={exports:{}};!function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){var i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((function(e){return 0===e.indexOf(i)}))},t.parseCandidate=function(e){for(var t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:i[t[r]]=t[r+1]}return i},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,i={},r=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<r.length;n++)i[(t=r[n].trim().split("="))[0].trim()]=t[1];return i},t.writeFmtp=function(e){var t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var r=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substr(t+1,r-t-1),i.value=e.substr(r+1)):i.attribute=e.substr(t+1),i},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){var r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" "),n=3;n<r.length;n++){var s=r[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){var a=t.parseRtpMap(o),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){i.headerExtensions.push(t.parseExtmap(e))})),i},t.writeRtpDescription=function(e,i){var r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" UDP/TLS/RTP/SAVPF ",r+=i.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((function(e){r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));var n=0;return i.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),r+="a=rtcp-mux\r\n",i.headerExtensions&&i.headerExtensions.forEach((function(e){r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){var i,r=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,u=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));u.length>0&&u[0].length>1&&u[0][0]===c&&(i=u[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&i&&(t.rtx={ssrc:i}),r.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&c&&r.push({ssrc:c});var d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,r.forEach((function(e){e.maxBitrate=d}))),r},t.parseRtcpParameters=function(e){var i={},r=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);var n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;var s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.parseMsid=function(e){var i,r=t.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(i=r[0].substr(7).split(" "))[0],track:i[1]};var n=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(i=n[0].value.split(" "))[0],track:i[1]}:void 0},t.parseSctpDescription=function(e){var i,r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");n.length>0&&(i=parseInt(n[0].substr(19),10)),isNaN(i)&&(i=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:r.fmt,maxMessageSize:i};if(t.matchPrefix(e,"a=sctpmap:").length>0){var o=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){var i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,i,r){var n=void 0!==i?i:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,i,r,n){var s=t.writeRtpDescription(e.kind,i);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+o,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+o,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+o,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,i){for(var r=t.splitLines(e),n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substr(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var i=t.splitLines(e)[0].substr(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){var i=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var i=t.splitLines(e),r=0;r<i.length;r++)if(i[r].length<2||"="!==i[r].charAt(1))return!1;return!0},e.exports=t}(zs);var Ys=zs.exports,Qs=zs.exports;function Ks(e,t,i,r,n){var s=Qs.writeRtpDescription(e.kind,t);if(s+=Qs.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=Qs.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":n||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=o;var a="msid:"+(r?r.id:"-")+" "+o+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+Qs.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+Qs.localCName+"\r\n"),s}function Xs(e,t){var i={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(e,t){e=parseInt(e,10);for(var i=0;i<t.length;i++)if(t[i].payloadType===e||t[i].preferredPayloadType===e)return t[i]},n=function(e,t,i,n){var s=r(e.parameters.apt,i),o=r(t.parameters.apt,n);return s&&o&&s.name.toLowerCase()===o.name.toLowerCase()};return e.codecs.forEach((function(r){for(var s=0;s<t.codecs.length;s++){var o=t.codecs[s];if(r.name.toLowerCase()===o.name.toLowerCase()&&r.clockRate===o.clockRate){if("rtx"===r.name.toLowerCase()&&r.parameters&&o.parameters.apt&&!n(r,o,e.codecs,t.codecs))continue;(o=JSON.parse(JSON.stringify(o))).numChannels=Math.min(r.numChannels,o.numChannels),i.codecs.push(o),o.rtcpFeedback=o.rtcpFeedback.filter((function(e){for(var t=0;t<r.rtcpFeedback.length;t++)if(r.rtcpFeedback[t].type===e.type&&r.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var r=0;r<t.headerExtensions.length;r++){var n=t.headerExtensions[r];if(e.uri===n.uri){i.headerExtensions.push(n);break}}})),i}function Zs(e,t,i){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(i)}function eo(e,t){var i=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return i||e.addRemoteCandidate(t),!i}function to(e,t){var i=new Error(t);return i.name=e,i.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],i}function io(e){const t=e&&e.navigator,i=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return i(e).catch((e=>Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString(){return this.name}}}(e))))}}function ro(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function no(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const i=new Event("enabled");i.enabled=e,this.dispatchEvent(i)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const i=function(e,t){function i(t,i){i.addTrack(t),i.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function r(t,i,r,n){var s=new Event("track");s.track=i,s.receiver=r,s.transceiver={receiver:r},s.streams=n,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var n=function(i){var r=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){r[e]=n[e].bind(n)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",i=JSON.parse(JSON.stringify(i||{})),this.usingBundle="max-bundle"===i.bundlePolicy,"negotiate"===i.rtcpMuxPolicy)throw to("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(i.rtcpMuxPolicy||(i.rtcpMuxPolicy="require"),i.iceTransportPolicy){case"all":case"relay":break;default:i.iceTransportPolicy="all"}switch(i.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:i.bundlePolicy="balanced"}if(i.iceServers=function(e,t){var i=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var r=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof r;return n&&(r=[r]),r=r.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||i?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(i=!0,!0)})),delete e.url,e.urls=n?r[0]:r,!!r.length}}))}(i.iceServers||[],t),this._iceGatherers=[],i.iceCandidatePoolSize)for(var s=i.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:i.iceServers,gatherPolicy:i.iceTransportPolicy}));else i.iceCandidatePoolSize=0;this._config=i,this.transceivers=[],this._sdpSessionId=Qs.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(n.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(n.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),n.prototype.onicecandidate=null,n.prototype.onaddstream=null,n.prototype.ontrack=null,n.prototype.onremovestream=null,n.prototype.onsignalingstatechange=null,n.prototype.oniceconnectionstatechange=null,n.prototype.onconnectionstatechange=null,n.prototype.onicegatheringstatechange=null,n.prototype.onnegotiationneeded=null,n.prototype.ondatachannel=null,n.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},n.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},n.prototype.getConfiguration=function(){return this._config},n.prototype.getLocalStreams=function(){return this.localStreams},n.prototype.getRemoteStreams=function(){return this.remoteStreams},n.prototype._createTransceiver=function(e,t){var i=this.transceivers.length>0,r={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&i)r.iceTransport=this.transceivers[0].iceTransport,r.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();r.iceTransport=n.iceTransport,r.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(r),r},n.prototype.addTrack=function(t,i){if(this._isClosed)throw to("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var r;if(this.transceivers.find((function(e){return e.track===t})))throw to("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(r=this.transceivers[n]);return r||(r=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(i)&&this.localStreams.push(i),r.track=t,r.stream=i,r.rtpSender=new e.RTCRtpSender(t,r.dtlsTransport),r.rtpSender},n.prototype.addStream=function(e){var i=this;if(t>=15025)e.getTracks().forEach((function(t){i.addTrack(t,e)}));else{var r=e.clone();e.getTracks().forEach((function(e,t){var i=r.getTracks()[t];e.addEventListener("enabled",(function(e){i.enabled=e.enabled}))})),r.getTracks().forEach((function(e){i.addTrack(e,r)}))}},n.prototype.removeTrack=function(t){if(this._isClosed)throw to("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var i=this.transceivers.find((function(e){return e.rtpSender===t}));if(!i)throw to("InvalidAccessError","Sender was not created by this connection.");var r=i.stream;i.rtpSender.stop(),i.rtpSender=null,i.track=null,i.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(r)&&this.localStreams.indexOf(r)>-1&&this.localStreams.splice(this.localStreams.indexOf(r),1),this._maybeFireNegotiationNeeded()},n.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var i=t.getSenders().find((function(t){return t.track===e}));i&&t.removeTrack(i)}))},n.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},n.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},n.prototype._createIceGatherer=function(t,i){var r=this;if(i&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var i=!e.candidate||0===Object.keys(e.candidate).length;n.state=i?"completed":"gathering",null!==r.transceivers[t].bufferedCandidateEvents&&r.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},n.prototype._gather=function(t,i){var r=this,n=this.transceivers[i].iceGatherer;if(!n.onlocalcandidate){var s=this.transceivers[i].bufferedCandidateEvents;this.transceivers[i].bufferedCandidateEvents=null,n.removeEventListener("localcandidate",this.transceivers[i].bufferCandidates),n.onlocalcandidate=function(e){if(!(r.usingBundle&&i>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:i};var o=e.candidate,a=!o||0===Object.keys(o).length;if(a)"new"!==n.state&&"gathering"!==n.state||(n.state="completed");else{"new"===n.state&&(n.state="gathering"),o.component=1,o.ufrag=n.getLocalParameters().usernameFragment;var c=Qs.writeCandidate(o);s.candidate=Object.assign(s.candidate,Qs.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var u=Qs.getMediaSections(r._localDescription.sdp);u[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",r._localDescription.sdp=Qs.getDescription(r._localDescription.sdp)+u.join("");var d=r.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==r.iceGatheringState&&(r.iceGatheringState="gathering",r._emitGatheringStateChange()),a||r._dispatchEvent("icecandidate",s),d&&(r._dispatchEvent("icecandidate",new Event("icecandidate")),r.iceGatheringState="complete",r._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){n.onlocalcandidate(e)}))}),0)}},n.prototype._createIceAndDtlsTransports=function(){var t=this,i=new e.RTCIceTransport(null);i.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var r=new e.RTCDtlsTransport(i);return r.ondtlsstatechange=function(){t._updateConnectionState()},r.onerror=function(){Object.defineProperty(r,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:i,dtlsTransport:r}},n.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var i=this.transceivers[e].iceTransport;i&&(delete i.onicestatechange,delete this.transceivers[e].iceTransport);var r=this.transceivers[e].dtlsTransport;r&&(delete r.ondtlsstatechange,delete r.onerror,delete this.transceivers[e].dtlsTransport)},n.prototype._transceive=function(e,i,r){var n=Xs(e.localCapabilities,e.remoteCapabilities);i&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:Qs.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(n.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(n)),r&&e.rtpReceiver&&n.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?n.encodings=e.recvEncodingParameters:n.encodings=[{}],n.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(n.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(n.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(n))},n.prototype.setLocalDescription=function(e){var t,i,r=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(to("TypeError",'Unsupported type "'+e.type+'"'));if(!Zs("setLocalDescription",e.type,r.signalingState)||r._isClosed)return Promise.reject(to("InvalidStateError","Can not set local "+e.type+" in state "+r.signalingState));if("offer"===e.type)t=Qs.splitSections(e.sdp),i=t.shift(),t.forEach((function(e,t){var i=Qs.parseRtpParameters(e);r.transceivers[t].localCapabilities=i})),r.transceivers.forEach((function(e,t){r._gather(e.mid,t)}));else if("answer"===e.type){t=Qs.splitSections(r._remoteDescription.sdp),i=t.shift();var n=Qs.matchPrefix(i,"a=ice-lite").length>0;t.forEach((function(e,t){var s=r.transceivers[t],o=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,u=s.localCapabilities,d=s.remoteCapabilities;if(!(Qs.isRejected(e)&&0===Qs.matchPrefix(e,"a=bundle-only").length||s.rejected)){var l=Qs.getIceParameters(e,i),h=Qs.getDtlsParameters(e,i);n&&(h.role="server"),r.usingBundle&&0!==t||(r._gather(s.mid,t),"new"===a.state&&a.start(o,l,n?"controlling":"controlled"),"new"===c.state&&c.start(h));var m=Xs(u,d);r._transceive(s,m.codecs.length>0,!1)}}))}return r._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?r._updateSignalingState("have-local-offer"):r._updateSignalingState("stable"),Promise.resolve()},n.prototype.setRemoteDescription=function(n){var s=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(to("TypeError",'Unsupported type "'+n.type+'"'));if(!Zs("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(to("InvalidStateError","Can not set remote "+n.type+" in state "+s.signalingState));var o={};s.remoteStreams.forEach((function(e){o[e.id]=e}));var a=[],c=Qs.splitSections(n.sdp),u=c.shift(),d=Qs.matchPrefix(u,"a=ice-lite").length>0,l=Qs.matchPrefix(u,"a=group:BUNDLE ").length>0;s.usingBundle=l;var h=Qs.matchPrefix(u,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!h&&h.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(r,c){var h=Qs.splitLines(r),m=Qs.getKind(r),p=Qs.isRejected(r)&&0===Qs.matchPrefix(r,"a=bundle-only").length,f=h[0].substr(2).split(" ")[2],v=Qs.getDirection(r,u),g=Qs.parseMsid(r),_=Qs.getMid(r)||Qs.generateIdentifier();if(p||"application"===m&&("DTLS/SCTP"===f||"UDP/DTLS/SCTP"===f))s.transceivers[c]={mid:_,kind:m,protocol:f,rejected:!0};else{var y,S,E,b,T,I,C,w,R;!p&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(m,!0));var k,A,M=Qs.parseRtpParameters(r);p||(k=Qs.getIceParameters(r,u),(A=Qs.getDtlsParameters(r,u)).role="client"),C=Qs.parseRtpEncodingParameters(r);var O=Qs.parseRtcpParameters(r),L=Qs.matchPrefix(r,"a=end-of-candidates",u).length>0,P=Qs.matchPrefix(r,"a=candidate:").map((function(e){return Qs.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!p&&l&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==n.type||p)"answer"!==n.type||p||(S=(y=s.transceivers[c]).iceGatherer,E=y.iceTransport,b=y.dtlsTransport,T=y.rtpReceiver,I=y.sendEncodingParameters,w=y.localCapabilities,s.transceivers[c].recvEncodingParameters=C,s.transceivers[c].remoteCapabilities=M,s.transceivers[c].rtcpParameters=O,P.length&&"new"===E.state&&(!d&&!L||l&&0!==c?P.forEach((function(e){eo(y.iceTransport,e)})):E.setRemoteCandidates(P)),l&&0!==c||("new"===E.state&&E.start(S,k,"controlling"),"new"===b.state&&b.start(A)),!Xs(y.localCapabilities,y.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&y.sendEncodingParameters[0].rtx&&delete y.sendEncodingParameters[0].rtx,s._transceive(y,"sendrecv"===v||"recvonly"===v,"sendrecv"===v||"sendonly"===v),!T||"sendrecv"!==v&&"sendonly"!==v?delete y.rtpReceiver:(R=T.track,g?(o[g.stream]||(o[g.stream]=new e.MediaStream),i(R,o[g.stream]),a.push([R,T,o[g.stream]])):(o.default||(o.default=new e.MediaStream),i(R,o.default),a.push([R,T,o.default]))));else{(y=s.transceivers[c]||s._createTransceiver(m)).mid=_,y.iceGatherer||(y.iceGatherer=s._createIceGatherer(c,l)),P.length&&"new"===y.iceTransport.state&&(!L||l&&0!==c?P.forEach((function(e){eo(y.iceTransport,e)})):y.iceTransport.setRemoteCandidates(P)),w=e.RTCRtpReceiver.getCapabilities(m),t<15019&&(w.codecs=w.codecs.filter((function(e){return"rtx"!==e.name}))),I=y.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var N,D=!1;"sendrecv"===v||"sendonly"===v?(D=!y.rtpReceiver,T=y.rtpReceiver||new e.RTCRtpReceiver(y.dtlsTransport,m),D&&(R=T.track,g&&"-"===g.stream||(g?(o[g.stream]||(o[g.stream]=new e.MediaStream,Object.defineProperty(o[g.stream],"id",{get:function(){return g.stream}})),Object.defineProperty(R,"id",{get:function(){return g.track}}),N=o[g.stream]):(o.default||(o.default=new e.MediaStream),N=o.default)),N&&(i(R,N),y.associatedRemoteMediaStreams.push(N)),a.push([R,T,N]))):y.rtpReceiver&&y.rtpReceiver.track&&(y.associatedRemoteMediaStreams.forEach((function(t){var i=t.getTracks().find((function(e){return e.id===y.rtpReceiver.track.id}));i&&function(t,i){i.removeTrack(t),i.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(i,t)})),y.associatedRemoteMediaStreams=[]),y.localCapabilities=w,y.remoteCapabilities=M,y.rtpReceiver=T,y.rtcpParameters=O,y.sendEncodingParameters=I,y.recvEncodingParameters=C,s._transceive(s.transceivers[c],!1,D)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===n.type?"active":"passive"),s._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(o).forEach((function(t){var i=o[t];if(i.getTracks().length){if(-1===s.remoteStreams.indexOf(i)){s.remoteStreams.push(i);var n=new Event("addstream");n.stream=i,e.setTimeout((function(){s._dispatchEvent("addstream",n)}))}a.forEach((function(e){var t=e[0],n=e[1];i.id===e[2].id&&r(s,t,n,[i])}))}})),a.forEach((function(e){e[2]||r(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},n.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},n.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},n.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},n.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var i=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",i)}},n.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var i=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",i)}},n.prototype.createOffer=function(){var i=this;if(i._isClosed)return Promise.reject(to("InvalidStateError","Can not call createOffer after close"));var r=i.transceivers.filter((function(e){return"audio"===e.kind})).length,n=i.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(r=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(n=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(i.transceivers.forEach((function(e){"audio"===e.kind?--r<0&&(e.wantReceive=!1):"video"===e.kind&&--n<0&&(e.wantReceive=!1)}));r>0||n>0;)r>0&&(i._createTransceiver("audio"),r--),n>0&&(i._createTransceiver("video"),n--);var o=Qs.writeSessionBoilerplate(i._sdpSessionId,i._sdpSessionVersion++);i.transceivers.forEach((function(r,n){var s=r.track,o=r.kind,a=r.mid||Qs.generateIdentifier();r.mid=a,r.iceGatherer||(r.iceGatherer=i._createIceGatherer(n,i.usingBundle));var c=e.RTCRtpSender.getCapabilities(o);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),r.remoteCapabilities&&r.remoteCapabilities.codecs&&r.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(r.remoteCapabilities&&r.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var u=r.sendEncodingParameters||[{ssrc:1001*(2*n+1)}];s&&t>=15019&&"video"===o&&!u[0].rtx&&(u[0].rtx={ssrc:u[0].ssrc+1}),r.wantReceive&&(r.rtpReceiver=new e.RTCRtpReceiver(r.dtlsTransport,o)),r.localCapabilities=c,r.sendEncodingParameters=u})),"max-compat"!==i._config.bundlePolicy&&(o+="a=group:BUNDLE "+i.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n",i.transceivers.forEach((function(e,t){o+=Ks(e,e.localCapabilities,"offer",e.stream,i._dtlsRole),o+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===i.iceGatheringState||0!==t&&i.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,o+="a="+Qs.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(o+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:o});return Promise.resolve(a)},n.prototype.createAnswer=function(){var i=this;if(i._isClosed)return Promise.reject(to("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==i.signalingState&&"have-local-pranswer"!==i.signalingState)return Promise.reject(to("InvalidStateError","Can not call createAnswer in signalingState "+i.signalingState));var r=Qs.writeSessionBoilerplate(i._sdpSessionId,i._sdpSessionVersion++);i.usingBundle&&(r+="a=group:BUNDLE "+i.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),r+="a=ice-options:trickle\r\n";var n=Qs.getMediaSections(i._remoteDescription.sdp).length;i.transceivers.forEach((function(e,s){if(!(s+1>n)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?r+="m=application 0 DTLS/SCTP 5000\r\n":r+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?r+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(r+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(r+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var o;e.stream&&("audio"===e.kind?o=e.stream.getAudioTracks()[0]:"video"===e.kind&&(o=e.stream.getVideoTracks()[0]),o&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1}));var a=Xs(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,r+=Ks(e,a,"answer",e.stream,i._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(r+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:r});return Promise.resolve(s)},n.prototype.addIceCandidate=function(e){var t,i=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(r,n){if(!i._remoteDescription)return n(to("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var o=0;o<i.transceivers.length;o++)if(i.transceivers[o].mid===e.sdpMid){s=o;break}var a=i.transceivers[s];if(!a)return n(to("OperationError","Can not add ICE candidate"));if(a.rejected)return r();var c=Object.keys(e.candidate).length>0?Qs.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return r();if(c.component&&1!==c.component)return r();if((0===s||s>0&&a.iceTransport!==i.transceivers[0].iceTransport)&&!eo(a.iceTransport,c))return n(to("OperationError","Can not add ICE candidate"));var u=e.candidate.trim();0===u.indexOf("a=")&&(u=u.substr(2)),(t=Qs.getMediaSections(i._remoteDescription.sdp))[s]+="a="+(c.type?u:"end-of-candidates")+"\r\n",i._remoteDescription.sdp=Qs.getDescription(i._remoteDescription.sdp)+t.join("")}else for(var d=0;d<i.transceivers.length&&(i.transceivers[d].rejected||(i.transceivers[d].iceTransport.addRemoteCandidate({}),(t=Qs.getMediaSections(i._remoteDescription.sdp))[d]+="a=end-of-candidates\r\n",i._remoteDescription.sdp=Qs.getDescription(i._remoteDescription.sdp)+t.join(""),!i.usingBundle));d++);r()}))},n.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var i=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?i=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(i=e.rtpReceiver)})),!i)throw to("InvalidAccessError","Invalid selector.");return i.getStats()}var r=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&r.push(e[t].getStats())}))})),Promise.all(r).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var i=e[t];if(i&&i.prototype&&i.prototype.getStats){var r=i.prototype.getStats;i.prototype.getStats=function(){return r.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(i){var r;e[i].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(r=e[i]).type]||r.type,t.set(i,e[i])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),n}(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let i=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&Ls("RTCIceServer.url","RTCIceServer.urls");const r="string"==typeof t;return r&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!i?(i=!0,!0):t&&!i})),delete e.url,e.urls=r?t[0]:t,!!t.length}}))}(e.iceServers,t.version),Os("ICE servers after filtering:",e.iceServers)),new i(e)},e.RTCPeerConnection.prototype=i.prototype}function so(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var oo=Object.freeze({__proto__:null,shimPeerConnection:no,shimReplaceTrack:so,shimGetUserMedia:io,shimGetDisplayMedia:ro});function ao(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){Ls("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function co(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function uo(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,s)}}function lo(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ho(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ks(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function mo(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ls("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function po(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function fo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],i=e&&"sendEncodings"in e;i&&e.sendEncodings.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function vo(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function go(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function _o(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var yo=Object.freeze({__proto__:null,shimOnTrack:co,shimPeerConnection:uo,shimSenderGetStats:lo,shimReceiverGetStats:ho,shimRemoveStream:mo,shimRTCDataChannel:po,shimAddTransceiver:fo,shimGetParameters:vo,shimCreateOffer:go,shimCreateAnswer:_o,shimGetUserMedia:ao,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function So(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Eo(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function bo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function To(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Io(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function Io(e){return e&&void 0!==e.video?Object.assign({},e,{video:Ns(e.video)}):e}function Co(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];!r.hasOwnProperty("urls")&&r.hasOwnProperty("url")?(Ls("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function wo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ro(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video")}return t.apply(this,arguments)}}function ko(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ao=Object.freeze({__proto__:null,shimLocalStreamsAPI:So,shimRemoteStreamsAPI:Eo,shimCallbacksAPI:bo,shimGetUserMedia:To,shimConstraints:Io,shimRTCIceServerUrls:Co,shimTrackEventTransceiver:wo,shimCreateOfferLegacy:Ro,shimAudioContext:ko});function Mo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),r=Ys.parseCandidate(e.candidate),n=Object.assign(i,r);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ks(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Oo(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Ys.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Ys.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},r=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},n=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=Ys.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=r(arguments[0]),t=n(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function Lo(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},ks(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Po(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function No(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Do(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var xo=Object.freeze({__proto__:null,shimRTCIceCandidate:Mo,shimMaxMessageSize:Oo,shimSendThrowTypeError:Lo,shimConnectionState:Po,removeExtmapAllowMixed:No,shimAddIceCandidateNullOrEmpty:Do});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const i=Os,r=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=Rs(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=Rs(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.mediaDevices&&i.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=Rs(i.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Rs(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:xo,extractVersion:Rs,disableLog:As,disableWarnings:Ms};switch(r.browser){case"chrome":if(!Js||!Gs||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=Js,Do(e,r),Us(e,r),$s(e),Gs(e,r),Bs(e),Ws(e,r),Vs(e),Fs(e),js(e),qs(e,r),Mo(e),Po(e),Oo(e,r),Lo(e),No(e,r);break;case"firefox":if(!yo||!uo||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=yo,Do(e,r),ao(e,r),uo(e,r),co(e),mo(e),lo(e),ho(e),po(e),fo(e),vo(e),go(e),_o(e),Mo(e),Po(e),Oo(e,r),Lo(e);break;case"edge":if(!oo||!no||!t.shimEdge)return i("MS edge shim is not included in this adapter release."),n;i("adapter.js shimming edge."),n.browserShim=oo,io(e),ro(e),no(e,r),so(e),Oo(e,r),Lo(e);break;case"safari":if(!Ao||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=Ao,Do(e,r),Co(e),Ro(e),bo(e),So(e),Eo(e),wo(e),To(e),ko(e),Mo(e),Oo(e,r),Lo(e),No(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var Uo="4.14.7",$o={},Bo=Hr,Vo=Wr,Fo=Object.keys||function(e){return Bo(e,Vo)},jo=L,Ho=ni,Wo=ri,Go=ci,qo=me,Jo=Fo;$o.f=jo&&!Ho?Object.defineProperties:function(e,t){Go(e);for(var i,r=qo(t),n=Jo(t),s=n.length,o=0;s>o;)Wo.f(e,i=n[o++],r[i]);return e};var zo,Yo=Ie("document","documentElement"),Qo=ci,Ko=$o,Xo=Wr,Zo=Fi,ea=Yo,ta=Gt,ia=Vi("IE_PROTO"),ra=function(){},na=function(e){return"<script>"+e+"<\/script>"},sa=function(e){e.write(na("")),e.close();var t=e.parentWindow.Object;return e=null,t},oa=function(){try{zo=new ActiveXObject("htmlfile")}catch(e){}var e,t;oa="undefined"!=typeof document?document.domain&&zo?sa(zo):((t=ta("iframe")).style.display="none",ea.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(na("document.F=Object")),e.close(),e.F):sa(zo);for(var i=Xo.length;i--;)delete oa.prototype[Xo[i]];return oa()};Zo[ia]=!0;var aa=Object.create||function(e,t){var i;return null!==e?(ra.prototype=Qo(e),i=new ra,ra.prototype=null,i[ia]=e):i=oa(),void 0===t?i:Ko.f(i,t)},ca=Ot,ua=aa,da=ri.f,la=ca("unscopables"),ha=Array.prototype;null==ha[la]&&da(ha,la,{configurable:!0,value:ua(null)});var ma,pa,fa,va=function(e){ha[la][e]=!0},ga={},_a=!O((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),ya=ft,Sa=ge,Ea=ht,ba=_a,Ta=Vi("IE_PROTO"),Ia=Object,Ca=Ia.prototype,wa=ba?Ia.getPrototypeOf:function(e){var t=Ea(e);if(ya(t,Ta))return t[Ta];var i=t.constructor;return Sa(i)&&t instanceof i?i.prototype:t instanceof Ia?Ca:null},Ra=O,ka=ge,Aa=Se,Ma=wa,Oa=_r,La=Ot("iterator"),Pa=!1;[].keys&&("next"in(fa=[].keys())?(pa=Ma(Ma(fa)))!==Object.prototype&&(ma=pa):Pa=!0),(!Aa(ma)||Ra((function(){var e={};return ma[La].call(e)!==e})))&&(ma={}),ka(ma[La])||Oa(ma,La,(function(){return this}));var Na={IteratorPrototype:ma,BUGGY_SAFARI_ITERATORS:Pa},Da=ri.f,xa=ft,Ua=Ot("toStringTag"),$a=function(e,t,i){e&&!i&&(e=e.prototype),e&&!xa(e,Ua)&&Da(e,Ua,{configurable:!0,value:t})},Ba=Na.IteratorPrototype,Va=aa,Fa=H,ja=$a,Ha=ga,Wa=function(){return this},Ga=function(e,t,i,r){var n=t+" Iterator";return e.prototype=Va(Ba,{next:Fa(+!r,i)}),ja(e,n,!1),Ha[n]=Wa,e},qa=ge,Ja=String,za=TypeError,Ya=te,Qa=ci,Ka=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Ya(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(i,[]),t=i instanceof Array}catch(e){}return function(i,r){return Qa(i),function(e){if("object"==typeof e||qa(e))return e;throw za("Can't set "+Ja(e)+" as a prototype")}(r),t?e(i,r):i.__proto__=r,i}}():void 0),Xa=En,Za=x,ec=ge,tc=Ga,ic=wa,rc=Ka,nc=$a,sc=yi,oc=_r,ac=ga,cc=wi.PROPER,uc=wi.CONFIGURABLE,dc=Na.IteratorPrototype,lc=Na.BUGGY_SAFARI_ITERATORS,hc=Ot("iterator"),mc="values",pc="entries",fc=function(){return this},vc=function(e,t,i,r,n,s,o){tc(i,t,r);var a,c,u,d=function(e){if(e===n&&f)return f;if(!lc&&e in m)return m[e];switch(e){case"keys":case mc:case pc:return function(){return new i(this,e)}}return function(){return new i(this)}},l=t+" Iterator",h=!1,m=e.prototype,p=m[hc]||m["@@iterator"]||n&&m[n],f=!lc&&p||d(n),v="Array"==t&&m.entries||p;if(v&&(a=ic(v.call(new e)))!==Object.prototype&&a.next&&(ic(a)!==dc&&(rc?rc(a,dc):ec(a[hc])||oc(a,hc,fc)),nc(a,l,!0)),cc&&n==mc&&p&&p.name!==mc&&(uc?sc(m,"name",mc):(h=!0,f=function(){return Za(p,this)})),n)if(c={values:d(mc),keys:s?f:d("keys"),entries:d(pc)},o)for(u in c)(lc||h||!(u in m))&&oc(m,u,c[u]);else Xa({target:t,proto:!0,forced:lc||h},c);return m[hc]!==f&&oc(m,hc,f,{name:n}),ac[t]=f,c},gc=function(e,t){return{value:e,done:t}},_c=me,yc=va,Sc=ga,Ec=tr,bc=ri.f,Tc=vc,Ic=gc,Cc=L,wc="Array Iterator",Rc=Ec.set,kc=Ec.getterFor(wc),Ac=Tc(Array,"Array",(function(e,t){Rc(this,{type:wc,target:_c(e),index:0,kind:t})}),(function(){var e=kc(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Ic(void 0,!0)):Ic("keys"==i?r:"values"==i?t[r]:[r,t[r]],!1)}),"values"),Mc=Sc.Arguments=Sc.Array;if(yc("keys"),yc("values"),yc("entries"),Cc&&"values"!==Mc.name)try{bc(Mc,"name",{value:"values"})}catch(e){}var Oc={exports:{}},Lc={},Pc=Ft,Nc=ri,Dc=H,xc=function(e,t,i){var r=Pc(t);r in e?Nc.f(e,r,Dc(0,i)):e[r]=i},Uc=Rr,$c=Lr,Bc=xc,Vc=Array,Fc=Math.max,jc=function(e,t,i){for(var r=$c(e),n=Uc(t,r),s=Uc(void 0===i?r:i,r),o=Vc(Fc(s-n,0)),a=0;n<s;n++,a++)Bc(o,a,e[n]);return o.length=a,o},Hc=X,Wc=me,Gc=yr.f,qc=jc,Jc="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Lc.f=function(e){return Jc&&"Window"==Hc(e)?function(e){try{return Gc(e)}catch(e){return qc(Jc)}}(e):Gc(Wc(e))};var zc=O((function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}})),Yc=O,Qc=Se,Kc=X,Xc=zc,Zc=Object.isExtensible,eu=Yc((function(){Zc(1)}))||Xc?function(e){return!!Qc(e)&&(!Xc||"ArrayBuffer"!=Kc(e))&&(!Zc||Zc(e))}:Zc,tu=!O((function(){return Object.isExtensible(Object.preventExtensions({}))})),iu=En,ru=te,nu=Fi,su=Se,ou=ft,au=ri.f,cu=yr,uu=Lc,du=eu,lu=tu,hu=!1,mu=St("meta"),pu=0,fu=function(e){au(e,mu,{value:{objectID:"O"+pu++,weakData:{}}})},vu=Oc.exports={enable:function(){vu.enable=function(){},hu=!0;var e=cu.f,t=ru([].splice),i={};i[mu]=1,e(i).length&&(cu.f=function(i){for(var r=e(i),n=0,s=r.length;n<s;n++)if(r[n]===mu){t(r,n,1);break}return r},iu({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:uu.f}))},fastKey:function(e,t){if(!su(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!ou(e,mu)){if(!du(e))return"F";if(!t)return"E";fu(e)}return e[mu].objectID},getWeakData:function(e,t){if(!ou(e,mu)){if(!du(e))return!0;if(!t)return!1;fu(e)}return e[mu].weakData},onFreeze:function(e){return lu&&hu&&du(e)&&!ou(e,mu)&&fu(e),e}};nu[mu]=!0;var gu=ga,_u=Ot("iterator"),yu=Array.prototype,Su=function(e){return void 0!==e&&(gu.Array===e||yu[_u]===e)},Eu=xn,bu=Ke,Tu=ae,Iu=ga,Cu=Ot("iterator"),wu=function(e){if(!Tu(e))return bu(e,Cu)||bu(e,"@@iterator")||Iu[Eu(e)]},Ru=x,ku=ze,Au=ci,Mu=We,Ou=wu,Lu=TypeError,Pu=function(e,t){var i=arguments.length<2?Ou(e):t;if(ku(i))return Au(Ru(i,e));throw Lu(Mu(e)+" is not iterable")},Nu=x,Du=ci,xu=Ke,Uu=function(e,t,i){var r,n;Du(e);try{if(!(r=xu(e,"return"))){if("throw"===t)throw i;return i}r=Nu(r,e)}catch(e){n=!0,r=e}if("throw"===t)throw i;if(n)throw r;return Du(r),i},$u=Cn,Bu=x,Vu=ci,Fu=We,ju=Su,Hu=Lr,Wu=Ce,Gu=Pu,qu=wu,Ju=Uu,zu=TypeError,Yu=function(e,t){this.stopped=e,this.result=t},Qu=Yu.prototype,Ku=function(e,t,i){var r,n,s,o,a,c,u,d=i&&i.that,l=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),m=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),f=$u(t,d),v=function(e){return r&&Ju(r,"normal",e),new Yu(!0,e)},g=function(e){return l?(Vu(e),p?f(e[0],e[1],v):f(e[0],e[1])):p?f(e,v):f(e)};if(h)r=e.iterator;else if(m)r=e;else{if(!(n=qu(e)))throw zu(Fu(e)+" is not iterable");if(ju(n)){for(s=0,o=Hu(e);o>s;s++)if((a=g(e[s]))&&Wu(Qu,a))return a;return new Yu(!1)}r=Gu(e,n)}for(c=h?e.next:r.next;!(u=Bu(c,r)).done;){try{a=g(u.value)}catch(e){Ju(r,"throw",e)}if("object"==typeof a&&a&&Wu(Qu,a))return a}return new Yu(!1)},Xu=Ce,Zu=TypeError,ed=function(e,t){if(Xu(t,e))return e;throw Zu("Incorrect invocation")},td=Ot("iterator"),id=!1;try{var rd=0,nd={next:function(){return{done:!!rd++}},return:function(){id=!0}};nd[td]=function(){return this},Array.from(nd,(function(){throw 2}))}catch(e){}var sd=function(e,t){if(!t&&!id)return!1;var i=!1;try{var r={};r[td]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(e){}return i},od=ge,ad=Se,cd=Ka,ud=function(e,t,i){var r,n;return cd&&od(r=t.constructor)&&r!==i&&ad(n=r.prototype)&&n!==i.prototype&&cd(e,n),e},dd=En,ld=A,hd=te,md=mn,pd=_r,fd=Oc.exports,vd=Ku,gd=ed,_d=ge,yd=ae,Sd=Se,Ed=O,bd=sd,Td=$a,Id=ud,Cd=function(e,t,i){var r=-1!==e.indexOf("Map"),n=-1!==e.indexOf("Weak"),s=r?"set":"add",o=ld[e],a=o&&o.prototype,c=o,u={},d=function(e){var t=hd(a[e]);pd(a,e,"add"==e?function(e){return t(this,0===e?0:e),this}:"delete"==e?function(e){return!(n&&!Sd(e))&&t(this,0===e?0:e)}:"get"==e?function(e){return n&&!Sd(e)?void 0:t(this,0===e?0:e)}:"has"==e?function(e){return!(n&&!Sd(e))&&t(this,0===e?0:e)}:function(e,i){return t(this,0===e?0:e,i),this})};if(md(e,!_d(o)||!(n||a.forEach&&!Ed((function(){(new o).entries().next()})))))c=i.getConstructor(t,e,r,s),fd.enable();else if(md(e,!0)){var l=new c,h=l[s](n?{}:-0,1)!=l,m=Ed((function(){l.has(1)})),p=bd((function(e){new o(e)})),f=!n&&Ed((function(){for(var e=new o,t=5;t--;)e[s](t,t);return!e.has(-0)}));p||((c=t((function(e,t){gd(e,a);var i=Id(new o,e,c);return yd(t)||vd(t,i[s],{that:i,AS_ENTRIES:r}),i}))).prototype=a,a.constructor=c),(m||f)&&(d("delete"),d("has"),r&&d("get")),(f||h)&&d(s),n&&a.clear&&delete a.clear}return u[e]=c,dd({global:!0,constructor:!0,forced:c!=o},u),Td(c,e),n||i.setStrong(c,e,r),c},wd=_r,Rd=function(e,t,i){for(var r in t)wd(e,r,t[r],i);return e},kd=Ie,Ad=ri,Md=L,Od=Ot("species"),Ld=function(e){var t=kd(e),i=Ad.f;Md&&t&&!t[Od]&&i(t,Od,{configurable:!0,get:function(){return this}})},Pd=ri.f,Nd=aa,Dd=Rd,xd=Cn,Ud=ed,$d=ae,Bd=Ku,Vd=vc,Fd=gc,jd=Ld,Hd=L,Wd=Oc.exports.fastKey,Gd=tr.set,qd=tr.getterFor,Jd={getConstructor:function(e,t,i,r){var n=e((function(e,n){Ud(e,s),Gd(e,{type:t,index:Nd(null),first:void 0,last:void 0,size:0}),Hd||(e.size=0),$d(n)||Bd(n,e[r],{that:e,AS_ENTRIES:i})})),s=n.prototype,o=qd(t),a=function(e,t,i){var r,n,s=o(e),a=c(e,t);return a?a.value=i:(s.last=a={index:n=Wd(t,!0),key:t,value:i,previous:r=s.last,next:void 0,removed:!1},s.first||(s.first=a),r&&(r.next=a),Hd?s.size++:e.size++,"F"!==n&&(s.index[n]=a)),e},c=function(e,t){var i,r=o(e),n=Wd(t);if("F"!==n)return r.index[n];for(i=r.first;i;i=i.next)if(i.key==t)return i};return Dd(s,{clear:function(){for(var e=o(this),t=e.index,i=e.first;i;)i.removed=!0,i.previous&&(i.previous=i.previous.next=void 0),delete t[i.index],i=i.next;e.first=e.last=void 0,Hd?e.size=0:this.size=0},delete:function(e){var t=this,i=o(t),r=c(t,e);if(r){var n=r.next,s=r.previous;delete i.index[r.index],r.removed=!0,s&&(s.next=n),n&&(n.previous=s),i.first==r&&(i.first=n),i.last==r&&(i.last=s),Hd?i.size--:t.size--}return!!r},forEach:function(e){for(var t,i=o(this),r=xd(e,arguments.length>1?arguments[1]:void 0);t=t?t.next:i.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!c(this,e)}}),Dd(s,i?{get:function(e){var t=c(this,e);return t&&t.value},set:function(e,t){return a(this,0===e?0:e,t)}}:{add:function(e){return a(this,e=0===e?0:e,e)}}),Hd&&Pd(s,"size",{get:function(){return o(this).size}}),n},setStrong:function(e,t,i){var r=t+" Iterator",n=qd(t),s=qd(r);Vd(e,t,(function(e,t){Gd(this,{type:r,target:e,state:n(e),kind:t,last:void 0})}),(function(){for(var e=s(this),t=e.kind,i=e.last;i&&i.removed;)i=i.previous;return e.target&&(e.last=i=i?i.next:e.state.first)?Fd("keys"==t?i.key:"values"==t?i.value:[i.key,i.value],!1):(e.target=void 0,Fd(void 0,!0))}),i?"entries":"values",!i,!0),jd(t)}};Cd("Set",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),Jd);var zd=xn,Yd=String,Qd=function(e){if("Symbol"===zd(e))throw TypeError("Cannot convert a Symbol value to a string");return Yd(e)},Kd=te,Xd=Tr,Zd=Qd,el=de,tl=Kd("".charAt),il=Kd("".charCodeAt),rl=Kd("".slice),nl=function(e){return function(t,i){var r,n,s=Zd(el(t)),o=Xd(i),a=s.length;return o<0||o>=a?e?"":void 0:(r=il(s,o))<55296||r>56319||o+1===a||(n=il(s,o+1))<56320||n>57343?e?tl(s,o):r:e?rl(s,o,o+2):n-56320+(r-55296<<10)+65536}},sl={codeAt:nl(!1),charAt:nl(!0)},ol=sl.charAt,al=Qd,cl=tr,ul=vc,dl=gc,ll="String Iterator",hl=cl.set,ml=cl.getterFor(ll);ul(String,"String",(function(e){hl(this,{type:ll,string:al(e),index:0})}),(function(){var e,t=ml(this),i=t.string,r=t.index;return r>=i.length?dl(void 0,!0):(e=ol(i,r),t.index+=e.length,dl(e,!1))}));var pl={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},fl=Gt("span").classList,vl=fl&&fl.constructor&&fl.constructor.prototype,gl=vl===Object.prototype?void 0:vl,_l=A,yl=pl,Sl=gl,El=Ac,bl=yi,Tl=Ot,Il=Tl("iterator"),Cl=Tl("toStringTag"),wl=El.values,Rl=function(e,t){if(e){if(e[Il]!==wl)try{bl(e,Il,wl)}catch(t){e[Il]=wl}if(e[Cl]||bl(e,Cl,t),yl[t])for(var i in El)if(e[i]!==El[i])try{bl(e,i,El[i])}catch(t){e[i]=El[i]}}};for(var kl in yl)Rl(_l[kl]&&_l[kl].prototype,kl);Rl(Sl,"DOMTokenList");var Al=P,Ml=Function.prototype,Ol=Ml.apply,Ll=Ml.call,Pl="object"==typeof Reflect&&Reflect.apply||(Al?Ll.bind(Ol):function(){return Ll.apply(Ol,arguments)}),Nl=te([].slice),Dl=TypeError,xl=function(e,t){if(e<t)throw Dl("Not enough arguments");return e},Ul=A,$l=Pl,Bl=ge,Vl=Nl,Fl=xl,jl=/MSIE .\./.test(we),Hl=Ul.Function,Wl=function(e){return jl?function(t,i){var r=Fl(arguments.length,1)>2,n=Bl(t)?t:Hl(t),s=r?Vl(arguments,2):void 0;return e(r?function(){$l(n,this,s)}:n,i)}:e},Gl={setTimeout:Wl(Ul.setTimeout),setInterval:Wl(Ul.setInterval)},ql=Gl.setInterval;En({global:!0,bind:!0,forced:A.setInterval!==ql},{setInterval:ql});var Jl=Gl.setTimeout;En({global:!0,bind:!0,forced:A.setTimeout!==Jl},{setTimeout:Jl}),Cd("Map",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),Jd);var zl=L,Yl=Rn,Ql=TypeError,Kl=Object.getOwnPropertyDescriptor,Xl=zl&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}(),Zl=TypeError,eh=function(e){if(e>9007199254740991)throw Zl("Maximum allowed index exceeded");return e},th=We,ih=TypeError,rh=function(e,t){if(!delete e[t])throw ih("Cannot delete property "+th(t)+" of "+th(e))},nh=En,sh=ht,oh=Rr,ah=Tr,ch=Lr,uh=Xl?function(e,t){if(Yl(e)&&!Kl(e,"length").writable)throw Ql("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},dh=eh,lh=is,hh=xc,mh=rh,ph=ps("splice"),fh=Math.max,vh=Math.min;nh({target:"Array",proto:!0,forced:!ph},{splice:function(e,t){var i,r,n,s,o,a,c=sh(this),u=ch(c),d=oh(e,u),l=arguments.length;for(0===l?i=r=0:1===l?(i=0,r=u-d):(i=l-2,r=vh(fh(ah(t),0),u-d)),dh(u+i-r),n=lh(c,r),s=0;s<r;s++)(o=d+s)in c&&hh(n,s,c[o]);if(n.length=r,i<r){for(s=d;s<u-r;s++)a=s+i,(o=s+r)in c?c[a]=c[o]:mh(c,a);for(s=u;s>u-r+i;s--)mh(c,s-1)}else if(i>r)for(s=u-r;s>d;s--)a=s+i-1,(o=s+r-1)in c?c[a]=c[o]:mh(c,a);for(s=0;s<i;s++)c[s+d]=arguments[s+2];return uh(c,u-r+i),n}});var gh=O,_h=function(e,t){var i=[][e];return!!i&&gh((function(){i.call(null,t||function(){return 1},1)}))},yh=ds.forEach,Sh=_h("forEach")?[].forEach:function(e){return yh(this,e,arguments.length>1?arguments[1]:void 0)};En({target:"Array",proto:!0,forced:[].forEach!=Sh},{forEach:Sh});var Eh=A,bh=pl,Th=gl,Ih=Sh,Ch=yi,wh=function(e){if(e&&e.forEach!==Ih)try{Ch(e,"forEach",Ih)}catch(t){e.forEach=Ih}};for(var Rh in bh)bh[Rh]&&wh(Eh[Rh]&&Eh[Rh].prototype);wh(Th);var kh=En,Ah=oe,Mh=me,Oh=_h,Lh=te([].join),Ph=Ah!=Object,Nh=Oh("join",",");kh({target:"Array",proto:!0,forced:Ph||!Nh},{join:function(e){return Lh(Mh(this),void 0===e?",":e)}});var Dh=En,xh=O,Uh=Rn,$h=Se,Bh=ht,Vh=Lr,Fh=eh,jh=xc,Hh=is,Wh=ps,Gh=Pe,qh=Ot("isConcatSpreadable"),Jh=Gh>=51||!xh((function(){var e=[];return e[qh]=!1,e.concat()[0]!==e})),zh=Wh("concat"),Yh=function(e){if(!$h(e))return!1;var t=e[qh];return void 0!==t?!!t:Uh(e)};Dh({target:"Array",proto:!0,arity:1,forced:!Jh||!zh},{concat:function(e){var t,i,r,n,s,o=Bh(this),a=Hh(o,0),c=0;for(t=-1,r=arguments.length;t<r;t++)if(Yh(s=-1===t?o:arguments[t]))for(n=Vh(s),Fh(c+n),i=0;i<n;i++,c++)i in s&&jh(a,c,s[i]);else Fh(c+1),jh(a,c++,s);return a.length=c,a}});var Qh=te,Kh=_r,Xh=Date.prototype,Zh="Invalid Date",em=Qh(Xh.toString),tm=Qh(Xh.getTime);String(new Date(NaN))!=Zh&&Kh(Xh,"toString",(function(){var e=tm(this);return e==e?em(this):Zh}));var im=Tr,rm=Qd,nm=de,sm=RangeError,om=function(e){var t=rm(nm(this)),i="",r=im(e);if(r<0||1/0==r)throw sm("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},am=te,cm=Mr,um=Qd,dm=de,lm=am(om),hm=am("".slice),mm=Math.ceil,pm=function(e){return function(t,i,r){var n,s,o=um(dm(t)),a=cm(i),c=o.length,u=void 0===r?" ":um(r);return a<=c||""==u?o:((s=lm(u,mm((n=a-c)/u.length))).length>n&&(s=hm(s,0,n)),e?o+s:s+o)}},fm={start:pm(!1),end:pm(!0)},vm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(we),gm=fm.start;En({target:"String",proto:!0,forced:vm},{padStart:function(e){return gm(this,e,arguments.length>1?arguments[1]:void 0)}});var _m=ci,ym=function(){var e=_m(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Sm=O,Em=A.RegExp,bm=Sm((function(){var e=Em("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Tm=bm||Sm((function(){return!Em("a","y").sticky})),Im={BROKEN_CARET:bm||Sm((function(){var e=Em("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),MISSED_STICKY:Tm,UNSUPPORTED_Y:bm},Cm=O,wm=A.RegExp,Rm=Cm((function(){var e=wm(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),km=O,Am=A.RegExp,Mm=km((function(){var e=Am("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Om=x,Lm=te,Pm=Qd,Nm=ym,Dm=Im,xm=it.exports,Um=aa,$m=tr.get,Bm=Rm,Vm=Mm,Fm=xm("native-string-replace",String.prototype.replace),jm=RegExp.prototype.exec,Hm=jm,Wm=Lm("".charAt),Gm=Lm("".indexOf),qm=Lm("".replace),Jm=Lm("".slice),zm=function(){var e=/a/,t=/b*/g;return Om(jm,e,"a"),Om(jm,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Ym=Dm.BROKEN_CARET,Qm=void 0!==/()??/.exec("")[1];(zm||Qm||Ym||Bm||Vm)&&(Hm=function(e){var t,i,r,n,s,o,a,c=this,u=$m(c),d=Pm(e),l=u.raw;if(l)return l.lastIndex=c.lastIndex,t=Om(Hm,l,d),c.lastIndex=l.lastIndex,t;var h=u.groups,m=Ym&&c.sticky,p=Om(Nm,c),f=c.source,v=0,g=d;if(m&&(p=qm(p,"y",""),-1===Gm(p,"g")&&(p+="g"),g=Jm(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Wm(d,c.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,v++),i=new RegExp("^(?:"+f+")",p)),Qm&&(i=new RegExp("^"+f+"$(?!\\s)",p)),zm&&(r=c.lastIndex),n=Om(jm,m?i:c,g),m?n?(n.input=Jm(n.input,v),n[0]=Jm(n[0],v),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:zm&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Qm&&n&&n.length>1&&Om(Fm,n[0],i,(function(){for(s=1;s<arguments.length-2;s++)void 0===arguments[s]&&(n[s]=void 0)})),n&&h)for(n.groups=o=Um(null),s=0;s<h.length;s++)o[(a=h[s])[0]]=n[a[1]];return n});var Km=Hm;En({target:"RegExp",proto:!0,forced:/./.exec!==Km},{exec:Km});var Xm=te,Zm=_r,ep=Km,tp=O,ip=Ot,rp=yi,np=ip("species"),sp=RegExp.prototype,op=function(e,t,i,r){var n=ip(e),s=!tp((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),o=s&&!tp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[np]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!s||!o||i){var a=Xm(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var o=Xm(e),c=t.exec;return c===ep||c===sp.exec?s&&!n?{done:!0,value:a(t,i,r)}:{done:!0,value:o(i,t,r)}:{done:!1}}));Zm(String.prototype,e,c[0]),Zm(sp,n,c[1])}r&&rp(sp[n],"sham",!0)},ap=sl.charAt,cp=function(e,t,i){return t+(i?ap(e,t).length:1)},up=te,dp=ht,lp=Math.floor,hp=up("".charAt),mp=up("".replace),pp=up("".slice),fp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,vp=/\$([$&'`]|\d{1,2})/g,gp=x,_p=ci,yp=ge,Sp=X,Ep=Km,bp=TypeError,Tp=function(e,t){var i=e.exec;if(yp(i)){var r=gp(i,e,t);return null!==r&&_p(r),r}if("RegExp"===Sp(e))return gp(Ep,e,t);throw bp("RegExp#exec called on incompatible receiver")},Ip=Pl,Cp=x,wp=te,Rp=op,kp=O,Ap=ci,Mp=ge,Op=ae,Lp=Tr,Pp=Mr,Np=Qd,Dp=de,xp=cp,Up=Ke,$p=function(e,t,i,r,n,s){var o=i+e.length,a=r.length,c=vp;return void 0!==n&&(n=dp(n),c=fp),mp(s,c,(function(s,c){var u;switch(hp(c,0)){case"$":return"$";case"&":return e;case"`":return pp(t,0,i);case"'":return pp(t,o);case"<":u=n[pp(c,1,-1)];break;default:var d=+c;if(0===d)return s;if(d>a){var l=lp(d/10);return 0===l?s:l<=a?void 0===r[l-1]?hp(c,1):r[l-1]+hp(c,1):s}u=r[d-1]}return void 0===u?"":u}))},Bp=Tp,Vp=Ot("replace"),Fp=Math.max,jp=Math.min,Hp=wp([].concat),Wp=wp([].push),Gp=wp("".indexOf),qp=wp("".slice),Jp="$0"==="a".replace(/./,"$0"),zp=!!/./[Vp]&&""===/./[Vp]("a","$0"),Yp=!kp((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Rp("replace",(function(e,t,i){var r=zp?"$":"$0";return[function(e,i){var r=Dp(this),n=Op(e)?void 0:Up(e,Vp);return n?Cp(n,e,r,i):Cp(t,Np(r),e,i)},function(e,n){var s=Ap(this),o=Np(e);if("string"==typeof n&&-1===Gp(n,r)&&-1===Gp(n,"$<")){var a=i(t,s,o,n);if(a.done)return a.value}var c=Mp(n);c||(n=Np(n));var u=s.global;if(u){var d=s.unicode;s.lastIndex=0}for(var l=[];;){var h=Bp(s,o);if(null===h)break;if(Wp(l,h),!u)break;""===Np(h[0])&&(s.lastIndex=xp(o,Pp(s.lastIndex),d))}for(var m,p="",f=0,v=0;v<l.length;v++){for(var g=Np((h=l[v])[0]),_=Fp(jp(Lp(h.index),o.length),0),y=[],S=1;S<h.length;S++)Wp(y,void 0===(m=h[S])?m:String(m));var E=h.groups;if(c){var b=Hp([g],y,_,o);void 0!==E&&Wp(b,E);var T=Np(Ip(n,void 0,b))}else T=$p(g,o,_,y,E,n);_>=f&&(p+=qp(o,f,_)+T,f=_+g.length)}return p+qp(o,f)}]}),!Yp||!Jp||zp);var Qp=x,Kp=ft,Xp=Ce,Zp=ym,ef=RegExp.prototype,tf=function(e){var t=e.flags;return void 0!==t||"flags"in ef||Kp(e,"flags")||!Xp(ef,e)?t:Qp(Zp,e)},rf=wi.PROPER,nf=_r,sf=ci,of=Qd,af=O,cf=tf,uf="toString",df=RegExp.prototype.toString,lf=af((function(){return"/a/b"!=df.call({source:"a",flags:"b"})})),hf=rf&&df.name!=uf;(lf||hf)&&nf(RegExp.prototype,uf,(function(){var e=sf(this);return"/"+of(e.source)+"/"+of(cf(e))}),{unsafe:!0});var mf=O,pf=Ot("iterator"),ff=!mf((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[pf]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),vf=jc,gf=Math.floor,_f=function(e,t){var i=e.length,r=gf(i/2);return i<8?yf(e,t):Sf(e,_f(vf(e,0,r),t),_f(vf(e,r),t),t)},yf=function(e,t){for(var i,r,n=e.length,s=1;s<n;){for(r=s,i=e[s];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==s++&&(e[r]=i)}return e},Sf=function(e,t,i,r){for(var n=t.length,s=i.length,o=0,a=0;o<n||a<s;)e[o+a]=o<n&&a<s?r(t[o],i[a])<=0?t[o++]:i[a++]:o<n?t[o++]:i[a++];return e},Ef=_f,bf=En,Tf=A,If=x,Cf=te,wf=L,Rf=ff,kf=_r,Af=Rd,Mf=$a,Of=Ga,Lf=tr,Pf=ed,Nf=ge,Df=ft,xf=Cn,Uf=xn,$f=ci,Bf=Se,Vf=Qd,Ff=aa,jf=H,Hf=Pu,Wf=wu,Gf=xl,qf=Ef,Jf=Ot("iterator"),zf="URLSearchParams",Yf="URLSearchParamsIterator",Qf=Lf.set,Kf=Lf.getterFor(zf),Xf=Lf.getterFor(Yf),Zf=Object.getOwnPropertyDescriptor,ev=function(e){if(!wf)return Tf[e];var t=Zf(Tf,e);return t&&t.value},tv=ev("fetch"),iv=ev("Request"),rv=ev("Headers"),nv=iv&&iv.prototype,sv=rv&&rv.prototype,ov=Tf.RegExp,av=Tf.TypeError,cv=Tf.decodeURIComponent,uv=Tf.encodeURIComponent,dv=Cf("".charAt),lv=Cf([].join),hv=Cf([].push),mv=Cf("".replace),pv=Cf([].shift),fv=Cf([].splice),vv=Cf("".split),gv=Cf("".slice),_v=/\+/g,yv=Array(4),Sv=function(e){return yv[e-1]||(yv[e-1]=ov("((?:%[\\da-f]{2}){"+e+"})","gi"))},Ev=function(e){try{return cv(e)}catch(t){return e}},bv=function(e){var t=mv(e,_v," "),i=4;try{return cv(t)}catch(e){for(;i;)t=mv(t,Sv(i--),Ev);return t}},Tv=/[!'()~]|%20/g,Iv={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Cv=function(e){return Iv[e]},wv=function(e){return mv(uv(e),Tv,Cv)},Rv=Of((function(e,t){Qf(this,{type:Yf,iterator:Hf(Kf(e).entries),kind:t})}),"Iterator",(function(){var e=Xf(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),i}),!0),kv=function(e){this.entries=[],this.url=null,void 0!==e&&(Bf(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===dv(e,0)?gv(e,1):e:Vf(e)))};kv.prototype={type:zf,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,s,o,a,c=Wf(e);if(c)for(i=(t=Hf(e,c)).next;!(r=If(i,t)).done;){if(s=(n=Hf($f(r.value))).next,(o=If(s,n)).done||(a=If(s,n)).done||!If(s,n).done)throw av("Expected sequence with length 2");hv(this.entries,{key:Vf(o.value),value:Vf(a.value)})}else for(var u in e)Df(e,u)&&hv(this.entries,{key:u,value:Vf(e[u])})},parseQuery:function(e){if(e)for(var t,i,r=vv(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=vv(t,"="),hv(this.entries,{key:bv(pv(i)),value:bv(lv(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],hv(i,wv(e.key)+"="+wv(e.value));return lv(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Av=function(){Pf(this,Mv),Qf(this,new kv(arguments.length>0?arguments[0]:void 0))},Mv=Av.prototype;if(Af(Mv,{append:function(e,t){Gf(arguments.length,2);var i=Kf(this);hv(i.entries,{key:Vf(e),value:Vf(t)}),i.updateURL()},delete:function(e){Gf(arguments.length,1);for(var t=Kf(this),i=t.entries,r=Vf(e),n=0;n<i.length;)i[n].key===r?fv(i,n,1):n++;t.updateURL()},get:function(e){Gf(arguments.length,1);for(var t=Kf(this).entries,i=Vf(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){Gf(arguments.length,1);for(var t=Kf(this).entries,i=Vf(e),r=[],n=0;n<t.length;n++)t[n].key===i&&hv(r,t[n].value);return r},has:function(e){Gf(arguments.length,1);for(var t=Kf(this).entries,i=Vf(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){Gf(arguments.length,1);for(var i,r=Kf(this),n=r.entries,s=!1,o=Vf(e),a=Vf(t),c=0;c<n.length;c++)(i=n[c]).key===o&&(s?fv(n,c--,1):(s=!0,i.value=a));s||hv(n,{key:o,value:a}),r.updateURL()},sort:function(){var e=Kf(this);qf(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Kf(this).entries,r=xf(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new Rv(this,"keys")},values:function(){return new Rv(this,"values")},entries:function(){return new Rv(this,"entries")}},{enumerable:!0}),kf(Mv,Jf,Mv.entries,{name:"entries"}),kf(Mv,"toString",(function(){return Kf(this).serialize()}),{enumerable:!0}),Mf(Av,zf),bf({global:!0,constructor:!0,forced:!Rf},{URLSearchParams:Av}),!Rf&&Nf(rv)){var Ov=Cf(sv.has),Lv=Cf(sv.set),Pv=function(e){if(Bf(e)){var t,i=e.body;if(Uf(i)===zf)return t=e.headers?new rv(e.headers):new rv,Ov(t,"content-type")||Lv(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),Ff(e,{body:jf(0,Vf(i)),headers:jf(0,t)})}return e};if(Nf(tv)&&bf({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return tv(e,arguments.length>1?Pv(arguments[1]):{})}}),Nf(iv)){var Nv=function(e){return Pf(this,nv),new iv(e,arguments.length>1?Pv(arguments[1]):{})};nv.constructor=Nv,Nv.prototype=nv,bf({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Nv})}}var Dv={URLSearchParams:Av,getState:Kf},xv=Object.is||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t},Uv=x,$v=ci,Bv=ae,Vv=de,Fv=xv,jv=Qd,Hv=Ke,Wv=Tp;op("search",(function(e,t,i){return[function(t){var i=Vv(this),r=Bv(t)?void 0:Hv(t,e);return r?Uv(r,t,i):new RegExp(t)[e](jv(i))},function(e){var r=$v(this),n=jv(e),s=i(t,r,n);if(s.done)return s.value;var o=r.lastIndex;Fv(o,0)||(r.lastIndex=0);var a=Wv(r,n);return Fv(r.lastIndex,o)||(r.lastIndex=o),null===a?-1:a.index}]})),(new Date).getTime();var Gv=0,qv=function(){return(new Date).getTime()+Gv},Jv=function(){var e=new Date;return e.setTime(qv()),e.toLocaleString()},zv=x,Yv=ci,Qv=ae,Kv=Mr,Xv=Qd,Zv=de,eg=Ke,tg=cp,ig=Tp;op("match",(function(e,t,i){return[function(t){var i=Zv(this),r=Qv(t)?void 0:eg(t,e);return r?zv(r,t,i):new RegExp(t)[e](Xv(i))},function(e){var r=Yv(this),n=Xv(e),s=i(t,r,n);if(s.done)return s.value;if(!r.global)return ig(r,n);var o=r.unicode;r.lastIndex=0;for(var a,c=[],u=0;null!==(a=ig(r,n));){var d=Xv(a[0]);c[u]=d,""===d&&(r.lastIndex=tg(n,Kv(r.lastIndex),o)),u++}return 0===u?null:c}]}));var rg=Se,ng=X,sg=Ot("match"),og=function(e){var t;return rg(e)&&(void 0!==(t=e[sg])?!!t:"RegExp"==ng(e))},ag=ri.f,cg=L,ug=A,dg=te,lg=mn,hg=ud,mg=yi,pg=yr.f,fg=Ce,vg=og,gg=Qd,_g=tf,yg=Im,Sg=function(e,t,i){i in e||ag(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Eg=_r,bg=O,Tg=ft,Ig=tr.enforce,Cg=Ld,wg=Rm,Rg=Mm,kg=Ot("match"),Ag=ug.RegExp,Mg=Ag.prototype,Og=ug.SyntaxError,Lg=dg(Mg.exec),Pg=dg("".charAt),Ng=dg("".replace),Dg=dg("".indexOf),xg=dg("".slice),Ug=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,$g=/a/g,Bg=/a/g,Vg=new Ag($g)!==$g,Fg=yg.MISSED_STICKY,jg=yg.UNSUPPORTED_Y;if(lg("RegExp",cg&&(!Vg||Fg||wg||Rg||bg((function(){return Bg[kg]=!1,Ag($g)!=$g||Ag(Bg)==Bg||"/a/i"!=Ag($g,"i")}))))){for(var Hg=function(e,t){var i,r,n,s,o,a,c=fg(Mg,this),u=vg(e),d=void 0===t,l=[],h=e;if(!c&&u&&d&&e.constructor===Hg)return e;if((u||fg(Mg,e))&&(e=e.source,d&&(t=_g(h))),e=void 0===e?"":gg(e),t=void 0===t?"":gg(t),h=e,wg&&"dotAll"in $g&&(r=!!t&&Dg(t,"s")>-1)&&(t=Ng(t,/s/g,"")),i=t,Fg&&"sticky"in $g&&(n=!!t&&Dg(t,"y")>-1)&&jg&&(t=Ng(t,/y/g,"")),Rg&&(e=(s=function(e){for(var t,i=e.length,r=0,n="",s=[],o={},a=!1,c=!1,u=0,d="";r<=i;r++){if("\\"===(t=Pg(e,r)))t+=Pg(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:Lg(Ug,xg(e,r+1))&&(r+=2,c=!0),n+=t,u++;continue;case">"===t&&c:if(""===d||Tg(o,d))throw new Og("Invalid capture group name");o[d]=!0,s[s.length]=[d,u],c=!1,d="";continue}c?d+=t:n+=t}return[n,s]}(e))[0],l=s[1]),o=hg(Ag(e,t),c?this:Mg,Hg),(r||n||l.length)&&(a=Ig(o),r&&(a.dotAll=!0,a.raw=Hg(function(e){for(var t,i=e.length,r=0,n="",s=!1;r<=i;r++)"\\"!==(t=Pg(e,r))?s||"."!==t?("["===t?s=!0:"]"===t&&(s=!1),n+=t):n+="[\\s\\S]":n+=t+Pg(e,++r);return n}(e),i)),n&&(a.sticky=!0),l.length&&(a.groups=l)),e!==h)try{mg(o,"source",""===h?"(?:)":h)}catch(e){}return o},Wg=pg(Ag),Gg=0;Wg.length>Gg;)Sg(Hg,Ag,Wg[Gg++]);Mg.constructor=Hg,Hg.prototype=Mg,Eg(ug,"RegExp",Hg,{constructor:!0})}Cg("RegExp");var qg=te(1..valueOf),Jg="\t\n\v\f\r \u2028\u2029\ufeff",zg=de,Yg=Qd,Qg=te("".replace),Kg="[\t\n\v\f\r \u2028\u2029\ufeff]",Xg=RegExp("^"+Kg+Kg+"*"),Zg=RegExp(Kg+Kg+"*$"),e_=function(e){return function(t){var i=Yg(zg(t));return 1&e&&(i=Qg(i,Xg,"")),2&e&&(i=Qg(i,Zg,"")),i}},t_={start:e_(1),end:e_(2),trim:e_(3)},i_=L,r_=A,n_=te,s_=mn,o_=_r,a_=ft,c_=ud,u_=Ce,d_=je,l_=$t,h_=O,m_=yr.f,p_=M.f,f_=ri.f,v_=qg,g_=t_.trim,__=r_.Number,y_=__.prototype,S_=r_.TypeError,E_=n_("".slice),b_=n_("".charCodeAt),T_=function(e){var t=l_(e,"number");return"bigint"==typeof t?t:I_(t)},I_=function(e){var t,i,r,n,s,o,a,c,u=l_(e,"number");if(d_(u))throw S_("Cannot convert a Symbol value to a number");if("string"==typeof u&&u.length>2)if(u=g_(u),43===(t=b_(u,0))||45===t){if(88===(i=b_(u,2))||120===i)return NaN}else if(48===t){switch(b_(u,1)){case 66:case 98:r=2,n=49;break;case 79:case 111:r=8,n=55;break;default:return+u}for(o=(s=E_(u,2)).length,a=0;a<o;a++)if((c=b_(s,a))<48||c>n)return NaN;return parseInt(s,r)}return+u};if(s_("Number",!__(" 0o1")||!__("0b1")||__("+0x1"))){for(var C_,w_=function(e){var t=arguments.length<1?0:__(T_(e)),i=this;return u_(y_,i)&&h_((function(){v_(i)}))?c_(Object(t),i,w_):t},R_=i_?m_(__):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),k_=0;R_.length>k_;k_++)a_(__,C_=R_[k_])&&!a_(w_,C_)&&f_(w_,C_,p_(__,C_));w_.prototype=y_,y_.constructor=w_,o_(r_,"Number",w_,{constructor:!0})}var A_=En,M_=Ur.indexOf,O_=_h,L_=te([].indexOf),P_=!!L_&&1/L_([1],1,-0)<0,N_=O_("indexOf");A_({target:"Array",proto:!0,forced:P_||!N_},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return P_?L_(this,e,t)||0:M_(this,e,t)}});var D_=ht,x_=wa,U_=_a;En({target:"Object",stat:!0,forced:O((function(){x_(1)})),sham:!U_},{getPrototypeOf:function(e){return x_(D_(e))}});var $_=Pl,B_=ze,V_=ci;En({target:"Reflect",stat:!0,forced:!O((function(){Reflect.apply((function(){}))}))},{apply:function(e,t,i){return $_(B_(e),t,V_(i))}});var F_=L,j_=wi.EXISTS,H_=te,W_=ri.f,G_=Function.prototype,q_=H_(G_.toString),J_=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,z_=H_(J_.exec);F_&&!j_&&W_(G_,"name",{configurable:!0,get:function(){try{return z_(J_,q_(this))[1]}catch(e){return""}}});var Y_=En,Q_=Date,K_=te(Q_.prototype.getTime);Y_({target:"Date",stat:!0},{now:function(){return K_(new Q_)}});var X_,Z_,ey,ty,iy="process"==X(A.process),ry=Qn,ny=We,sy=TypeError,oy=function(e){if(ry(e))return e;throw sy(ny(e)+" is not a constructor")},ay=ci,cy=oy,uy=ae,dy=Ot("species"),ly=function(e,t){var i,r=ay(e).constructor;return void 0===r||uy(i=ay(r)[dy])?t:cy(i)},hy=/(?:ipad|iphone|ipod).*applewebkit/i.test(we),my=A,py=Pl,fy=Cn,vy=ge,gy=ft,_y=O,yy=Yo,Sy=Nl,Ey=Gt,by=xl,Ty=hy,Iy=iy,Cy=my.setImmediate,wy=my.clearImmediate,Ry=my.process,ky=my.Dispatch,Ay=my.Function,My=my.MessageChannel,Oy=my.String,Ly=0,Py={};try{X_=my.location}catch(e){}var Ny=function(e){if(gy(Py,e)){var t=Py[e];delete Py[e],t()}},Dy=function(e){return function(){Ny(e)}},xy=function(e){Ny(e.data)},Uy=function(e){my.postMessage(Oy(e),X_.protocol+"//"+X_.host)};Cy&&wy||(Cy=function(e){by(arguments.length,1);var t=vy(e)?e:Ay(e),i=Sy(arguments,1);return Py[++Ly]=function(){py(t,void 0,i)},Z_(Ly),Ly},wy=function(e){delete Py[e]},Iy?Z_=function(e){Ry.nextTick(Dy(e))}:ky&&ky.now?Z_=function(e){ky.now(Dy(e))}:My&&!Ty?(ty=(ey=new My).port2,ey.port1.onmessage=xy,Z_=fy(ty.postMessage,ty)):my.addEventListener&&vy(my.postMessage)&&!my.importScripts&&X_&&"file:"!==X_.protocol&&!_y(Uy)?(Z_=Uy,my.addEventListener("message",xy,!1)):Z_="onreadystatechange"in Ey("script")?function(e){yy.appendChild(Ey("script")).onreadystatechange=function(){yy.removeChild(this),Ny(e)}}:function(e){setTimeout(Dy(e),0)});var $y,By,Vy,Fy,jy,Hy,Wy,Gy,qy={set:Cy,clear:wy},Jy=A,zy=/ipad|iphone|ipod/i.test(we)&&void 0!==Jy.Pebble,Yy=/web0s(?!.*chrome)/i.test(we),Qy=A,Ky=Cn,Xy=M.f,Zy=qy.set,eS=hy,tS=zy,iS=Yy,rS=iy,nS=Qy.MutationObserver||Qy.WebKitMutationObserver,sS=Qy.document,oS=Qy.process,aS=Qy.Promise,cS=Xy(Qy,"queueMicrotask"),uS=cS&&cS.value;uS||($y=function(){var e,t;for(rS&&(e=oS.domain)&&e.exit();By;){t=By.fn,By=By.next;try{t()}catch(e){throw By?Fy():Vy=void 0,e}}Vy=void 0,e&&e.enter()},eS||rS||iS||!nS||!sS?!tS&&aS&&aS.resolve?((Wy=aS.resolve(void 0)).constructor=aS,Gy=Ky(Wy.then,Wy),Fy=function(){Gy($y)}):rS?Fy=function(){oS.nextTick($y)}:(Zy=Ky(Zy,Qy),Fy=function(){Zy($y)}):(jy=!0,Hy=sS.createTextNode(""),new nS($y).observe(Hy,{characterData:!0}),Fy=function(){Hy.data=jy=!jy}));var dS=uS||function(e){var t={fn:e,next:void 0};Vy&&(Vy.next=t),By||(By=t,Fy()),Vy=t},lS=A,hS=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},mS=function(){this.head=null,this.tail=null};mS.prototype={add:function(e){var t={item:e,next:null};this.head?this.tail.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return this.head=e.next,this.tail===e&&(this.tail=null),e.item}};var pS=mS,fS=A.Promise,vS="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,gS=!vS&&!iy&&"object"==typeof window&&"object"==typeof document,_S=A,yS=fS,SS=ge,ES=mn,bS=Pi,TS=Ot,IS=gS,CS=vS,wS=Pe;yS&&yS.prototype;var RS=TS("species"),kS=!1,AS=SS(_S.PromiseRejectionEvent),MS={CONSTRUCTOR:ES("Promise",(function(){var e=bS(yS),t=e!==String(yS);if(!t&&66===wS)return!0;if(!wS||wS<51||!/native code/.test(e)){var i=new yS((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[RS]=r,!(kS=i.then((function(){}))instanceof r))return!0}return!t&&(IS||CS)&&!AS})),REJECTION_EVENT:AS,SUBCLASSING:kS},OS={},LS=ze,PS=TypeError,NS=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw PS("Bad Promise constructor");t=e,i=r})),this.resolve=LS(t),this.reject=LS(i)};OS.f=function(e){return new NS(e)};var DS,xS,US,$S=En,BS=iy,VS=A,FS=x,jS=_r,HS=Ka,WS=$a,GS=Ld,qS=ze,JS=ge,zS=Se,YS=ed,QS=ly,KS=qy.set,XS=dS,ZS=hS,eE=pS,tE=tr,iE=fS,rE=OS,nE="Promise",sE=MS.CONSTRUCTOR,oE=MS.REJECTION_EVENT,aE=MS.SUBCLASSING,cE=tE.getterFor(nE),uE=tE.set,dE=iE&&iE.prototype,lE=iE,hE=dE,mE=VS.TypeError,pE=VS.document,fE=VS.process,vE=rE.f,gE=vE,_E=!!(pE&&pE.createEvent&&VS.dispatchEvent),yE="unhandledrejection",SE=function(e){var t;return!(!zS(e)||!JS(t=e.then))&&t},EE=function(e,t){var i,r,n,s=t.value,o=1==t.state,a=o?e.ok:e.fail,c=e.resolve,u=e.reject,d=e.domain;try{a?(o||(2===t.rejection&&wE(t),t.rejection=1),!0===a?i=s:(d&&d.enter(),i=a(s),d&&(d.exit(),n=!0)),i===e.promise?u(mE("Promise-chain cycle")):(r=SE(i))?FS(r,i,c,u):c(i)):u(s)}catch(e){d&&!n&&d.exit(),u(e)}},bE=function(e,t){e.notified||(e.notified=!0,XS((function(){for(var i,r=e.reactions;i=r.get();)EE(i,e);e.notified=!1,t&&!e.rejection&&IE(e)})))},TE=function(e,t,i){var r,n;_E?((r=pE.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),VS.dispatchEvent(r)):r={promise:t,reason:i},!oE&&(n=VS["on"+e])?n(r):e===yE&&function(e,t){var i=lS.console;i&&i.error&&(1==arguments.length?i.error(e):i.error(e,t))}("Unhandled promise rejection",i)},IE=function(e){FS(KS,VS,(function(){var t,i=e.facade,r=e.value;if(CE(e)&&(t=ZS((function(){BS?fE.emit("unhandledRejection",r,i):TE(yE,i,r)})),e.rejection=BS||CE(e)?2:1,t.error))throw t.value}))},CE=function(e){return 1!==e.rejection&&!e.parent},wE=function(e){FS(KS,VS,(function(){var t=e.facade;BS?fE.emit("rejectionHandled",t):TE("rejectionhandled",t,e.value)}))},RE=function(e,t,i){return function(r){e(t,r,i)}},kE=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,bE(e,!0))},AE=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw mE("Promise can't be resolved itself");var r=SE(t);r?XS((function(){var i={done:!1};try{FS(r,t,RE(AE,i,e),RE(kE,i,e))}catch(t){kE(i,t,e)}})):(e.value=t,e.state=1,bE(e,!1))}catch(t){kE({done:!1},t,e)}}};if(sE&&(hE=(lE=function(e){YS(this,hE),qS(e),FS(DS,this);var t=cE(this);try{e(RE(AE,t),RE(kE,t))}catch(e){kE(t,e)}}).prototype,(DS=function(e){uE(this,{type:nE,done:!1,notified:!1,parent:!1,reactions:new eE,rejection:!1,state:0,value:void 0})}).prototype=jS(hE,"then",(function(e,t){var i=cE(this),r=vE(QS(this,lE));return i.parent=!0,r.ok=!JS(e)||e,r.fail=JS(t)&&t,r.domain=BS?fE.domain:void 0,0==i.state?i.reactions.add(r):XS((function(){EE(r,i)})),r.promise})),xS=function(){var e=new DS,t=cE(e);this.promise=e,this.resolve=RE(AE,t),this.reject=RE(kE,t)},rE.f=vE=function(e){return e===lE||void 0===e?new xS(e):gE(e)},JS(iE)&&dE!==Object.prototype)){US=dE.then,aE||jS(dE,"then",(function(e,t){var i=this;return new lE((function(e,t){FS(US,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete dE.constructor}catch(e){}HS&&HS(dE,hE)}$S({global:!0,constructor:!0,wrap:!0,forced:sE},{Promise:lE}),WS(lE,nE,!1),GS(nE);var ME=fS,OE=MS.CONSTRUCTOR||!sd((function(e){ME.all(e).then(void 0,(function(){}))})),LE=x,PE=ze,NE=OS,DE=hS,xE=Ku;En({target:"Promise",stat:!0,forced:OE},{all:function(e){var t=this,i=NE.f(t),r=i.resolve,n=i.reject,s=DE((function(){var i=PE(t.resolve),s=[],o=0,a=1;xE(e,(function(e){var c=o++,u=!1;a++,LE(i,t,e).then((function(e){u||(u=!0,s[c]=e,--a||r(s))}),n)})),--a||r(s)}));return s.error&&n(s.value),i.promise}});var UE=En,$E=MS.CONSTRUCTOR,BE=fS,VE=Ie,FE=ge,jE=_r,HE=BE&&BE.prototype;if(UE({target:"Promise",proto:!0,forced:$E,real:!0},{catch:function(e){return this.then(void 0,e)}}),FE(BE)){var WE=VE("Promise").prototype.catch;HE.catch!==WE&&jE(HE,"catch",WE,{unsafe:!0})}var GE=x,qE=ze,JE=OS,zE=hS,YE=Ku;En({target:"Promise",stat:!0,forced:OE},{race:function(e){var t=this,i=JE.f(t),r=i.reject,n=zE((function(){var n=qE(t.resolve);YE(e,(function(e){GE(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var QE=x,KE=OS;En({target:"Promise",stat:!0,forced:MS.CONSTRUCTOR},{reject:function(e){var t=KE.f(this);return QE(t.reject,void 0,e),t.promise}});var XE=ci,ZE=Se,eb=OS,tb=En,ib=MS.CONSTRUCTOR;Ie("Promise"),tb({target:"Promise",stat:!0,forced:ib},{resolve:function(e){return function(e,t){if(XE(e),ZE(t)&&t.constructor===e)return t;var i=eb.f(e);return(0,i.resolve)(t),i.promise}(this,e)}});var rb=A,nb=O,sb=Qd,ob=t_.trim,ab=te("".charAt),cb=rb.parseFloat,ub=rb.Symbol,db=ub&&ub.iterator,lb=1/cb("\t\n\v\f\r \u2028\u2029\ufeff-0")!=-1/0||db&&!nb((function(){cb(Object(db))}))?function(e){var t=ob(sb(e)),i=cb(t);return 0===i&&"-"==ab(t,0)?-0:i}:cb;En({global:!0,forced:parseFloat!=lb},{parseFloat:lb});var hb=window.navigator&&window.navigator.userAgent||"",mb=/AppleWebKit\/([\d.]+)/i.exec(hb);mb&&parseFloat(mb.pop());var pb=/iPad/i.test(hb),fb=navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/Macintosh/.test(hb),vb=/iPhone/i.test(hb)&&!pb,gb=/iPod/i.test(hb),_b=vb||pb||gb||fb,yb=/Android/i.test(hb);yb&&function(){var e=hb.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;var t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);t&&i&&parseFloat(e[1]+"."+e[2])}(),yb&&/webkit/i.test(hb);var Sb=/Firefox/i.test(hb),Eb=Sb&&function(){var e=hb.match(/Firefox\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),bb=/Edge\//i.test(hb),Tb=bb&&function(){var e=hb.match(/Edge\/(\d+)/i);if(e&&e[1])return e[1]}(),Ib=/Edg\//i.test(hb),Cb=Ib&&function(){var e=hb.match(/Edg\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),wb=/SogouMobileBrowser\//i.test(hb),Rb=wb&&function(){var e=hb.match(/SogouMobileBrowser\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),kb=/MetaSr\s/i.test(hb),Ab=kb&&function(){var e=hb.match(/MetaSr(\s\d+(\.\d+)+)/);return e&&e[1]?parseFloat(e[1]):null}(),Mb=/TBS\/\d+/i.test(hb),Ob=Mb&&function(){var e=hb.match(/TBS\/(\d+)/i);if(e&&e[1])return e[1]}(),Lb=/XWEB\/\d+/i.test(hb),Pb=Lb&&function(){var e=hb.match(/XWEB\/(\d+)/i);if(e&&e[1])return e[1]}();/MSIE\s8\.0/.test(hb),/MSIE\/\d+/i.test(hb)&&function(){var e=/MSIE\s(\d+)\.\d/.exec(hb),t=e&&parseFloat(e[1]);!t&&/Trident\/7.0/i.test(hb)&&/rv:11.0/.test(hb)&&(t=11)}();var Nb=/(micromessenger|webbrowser)/i.test(hb),Db=Nb&&function(){var e=hb.match(/MicroMessenger\/(\d+)/i);if(e&&e[1])return e[1]}(),xb=!Mb&&/MQQBrowser\/\d+/i.test(hb)&&/COVC\/\d+/i.test(hb),Ub=!Mb&&/MQQBrowser\/\d+/i.test(hb)&&!/COVC\/\d+/i.test(hb),$b=(Ub||xb)&&function(){var e=hb.match(/ MQQBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Bb=!Mb&&/ QQBrowser\/\d+/i.test(hb),Vb=Bb&&function(){var e=hb.match(/ QQBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Fb=!Mb&&/QQBrowserLite\/\d+/i.test(hb),jb=Fb&&function(){var e=hb.match(/QQBrowserLite\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Hb=!Mb&&/MQBHD\/\d+/i.test(hb),Wb=Hb&&function(){var e=hb.match(/MQBHD\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Gb=/Windows/i.test(hb),qb=!_b&&/MAC OS X/i.test(hb),Jb=!yb&&/Linux/i.test(hb);/MicroMessenger/i.test(hb);var zb=/UCBrowser/i.test(hb);/Electron/i.test(hb);var Yb,Qb,Kb=/MiuiBrowser/i.test(hb),Xb=Kb&&function(){var e=hb.match(/MiuiBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Zb=/HuaweiBrowser/i.test(hb),eT=/Huawei/i.test(hb),tT=Zb&&function(){var e=hb.match(/HuaweiBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),iT=/SamsungBrowser/i.test(hb),rT=iT&&function(){var e=hb.match(/SamsungBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),nT=/HeyTapBrowser/i.test(hb),sT=nT&&function(){var e=hb.match(/HeyTapBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),oT=/VivoBrowser/i.test(hb),aT=oT&&function(){var e=hb.match(/VivoBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),cT=function(){var e=hb.match(/Chrome\/(\d+)/);return e&&e[1]?Number(e[1]):null},uT=/Chrome/i.test(hb),dT=!bb&&!kb&&!wb&&!Mb&&!Lb&&!Ib&&!Bb&&!Kb&&!Zb&&!iT&&!nT&&!oT&&/Chrome/i.test(hb),lT=dT&&cT(),hT=dT&&function(){var e=hb.match(/Chrome\/([\d.]+)/);return e&&e[1]?e[1]:null}(),mT=!uT&&!Ub&&!xb&&!Fb&&!Hb&&/Safari/i.test(hb),pT=function(){if(mT){var e=hb.match(/Version\/([\d.]+)/);if(e&&e[1])return e[1]}return""}(),fT=/Android.*(wv|.0.0.0)/.test(hb),vT=function(){if(fb)return pT;if(_b){var e=hb.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){var t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""}(),gT="15.1"===pT,_T="15.1"===vT,yT=14===(Yb=Number(vT.split(".")[0]))||13===Yb,ST="file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname,ET=function(){if(ew(Qb))try{Qb=window.localStorage}catch(e){Mw.warn(e),Qb=!1}return Qb},bT=new Map([[Sb,["Firefox",Eb]],[Ib,["Edg",Cb]],[dT,["Chrome",hT]],[mT,["Safari",pT]],[Mb,["TBS",Ob]],[Lb,["XWEB",Pb]],[Nb&&vb,["WeChat",Db]],[Bb,["QQ(Win)",Vb]],[Ub,["QQ(Mobile)",$b]],[xb,["QQ(Mobile X5)",$b]],[Fb,["QQ(Mac)",jb]],[Hb,["QQ(iPad)",Wb]],[Kb,["MI",Xb]],[Zb,["HW",tT]],[iT,["Samsung",rT]],[nT,["OPPO",sT]],[oT,["VIVO",aT]],[bb,["EDGE",Tb]],[wb,["SogouMobile",Rb]],[kb,["Sogou",Ab]]]);function TT(){var e="unknown",t="unknown";return bT.get(!0)&&(e=bT.get(!0)[0],t=bT.get(!0)[1]),{name:e,version:t}}var IT=ht,CT=Fo;En({target:"Object",stat:!0,forced:O((function(){CT(1)}))},{keys:function(e){return CT(IT(e))}});var wT="audio",RT="video",kT="auxiliary",AT="smallVideo",MT="environment",OT="mute",LT="unmute",PT="ended",NT="playing",DT="pause",xT="error",UT="loadeddata",$T="audioinput",BT="videoinput",VT="main",FT="backup",jT="sei-message",HT="PLAYING",WT="PAUSED",GT="STOPPED",qT="qcloud",JT="",zT="jssdk_log",YT="live",QT="anchor",KT="audience",XT="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ZT="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",eI=VT,tI=kT,iI="unknown",rI="DISCONNECTED",nI="CONNECTING",sI="RECONNECTING",oI="CONNECTED",aI="connecting",cI="closed",uI="connected",dI="publish",lI="unpublish",hI="subscribe",mI="unsubscribe",pI="uplink-connection",fI="uplink-reconnection",vI="downlink-connection",gI="downlink-reconnection",_I="setLocalDescription",yI="setRemoteDescription",SI="iceConnectionState",EI="stream-initialize",bI="websocketConnectionState",TI="websocketReconnectionState",II="update-stream",CI="recover-subscription",wI="start-mix-transcode",RI="stop-mix-transcode",kI="player-error",AI="schedule",MI="load-worklet",OI="unsubscribe",LI="subscribe_change",PI="unified-plan",NI="preset-layout",DI="$PLACE_HOLDER_REMOTE$",xI="string",UI="number",$I="boolean",BI="object",VI="add",FI="remove",jI={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5},HI=6048e5,WI="schedule.rtc.qq.com",GI="schedule.rtc.qcloud.com",qI="schedule.rtc.tencentcloud.com",JI="schedule-ecdn.rtc.tencentcloud.com",zI="LocalStream",YI="RemoteStream",QI="web.sdk.qcloud.com",KI="web.sdk.tencent.cn",XI="web.sdk.cloud.tencent.cn",ZI="https://console.cloud.tencent.com/trtc",eC="https://".concat(QI,"/trtc/webrtc/doc"),tC="".concat(eC,"/zh-cn/"),iC="trtc_error_assistance",rC="default",nC="communications",sC={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,NONE:5},oC=Object.keys(sC),aC=["normal leave","timeout leave","kick","role change"],cC="ric",uC="raf",dC="interval",lC="timeout",hC=de,mC=Qd,pC=/"/g,fC=te("".replace),vC=function(e,t,i,r){var n=mC(hC(e)),s="<"+t;return""!==i&&(s+=" "+i+'="'+fC(mC(r),pC,""")+'"'),s+">"+n+"</"+t+">"},gC=O,_C=function(e){return gC((function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}))},yC=vC;En({target:"String",proto:!0,forced:_C("link")},{link:function(e){return yC(this,"a","href",e)}}),En({target:"Array",stat:!0},{isArray:Rn});var SC="AVOID_REPEATED_CALL",EC="INVALID_PARAMETER_TYPE",bC="INVALID_PARAMETER_INSTANCE",TC="SIGNAL_CHANNEL_RECONNECTION_FAILED",IC="JOIN_ROOM_FAILED",CC="INVALID_REMOTE_STREAM",wC="INVALID_OPERATION_START_PUBLISH_CDN",RC="START_PUBLISH_CDN_FAILED",kC="STOP_PUBLISH_CDN_FAILED",AC="INVALID_AUDIO_VOLUME",MC="INVALID_REPLACE_TRACK",OC="INVALID_STREAM_INITIALIZED",LC="CLIENT_DESTROYED",PC="PLAY_FAILED",NC="NOT_SUPPORTED_HTTP",DC="NOT_SUPPORTED_WEBRTC",xC="NOT_SUPPORTED_H264ENCODE",UC="NOT_SUPPORTED_H264DECODE",$C="SIGNAL_RESPONSE_FAILED",BC="CATCH_HANDLER_ERROR",VC="SEI_NOT_SUPPORT",FC="CALL_FREQUENCY_LIMIT",jC="CONNECTION_ABORED",HC={AVOID_REPEATED_CALL:function(e){return"previous ".concat(e.name,"() is ongoing, please avoid repeated calls.")},INVALID_PARAMETER_REQUIRED:function(e){var t=e.key,i=e.rule,r=e.fnName,n=e.value;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE:function(e){var t,i=e.key,r=e.rule,n=e.fnName,s=e.value,o="".concat(i||r.name);return t=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(o,"' must be type of ").concat(t," when calling ").concat(n,"(), received type: ").concat(aw(s),".")},INVALID_PARAMETER_EMPTY:function(e){var t=e.key,i=e.rule,r=e.fnName,n=e.value;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE:function(e){var t=e.key,i=e.rule,r=e.fnName,n=e.value,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(aw(n),".")},INVALID_PARAMETER_RANGE:function(e){var t=e.key,i=e.rule,r=e.fnName,n=e.value;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},API_CALL_TIMEOUT:function(e){return"".concat(e.commandDesc||e.command," timeout observed.")},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:function(e){return"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," }).")},ERROR_MESSAGE:function(e){var t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:function(e){return"exchange sdp failed ".concat(e.errMsg,".")},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:function(e){return"'".concat(e,"' must be validate string when useStringRoomId is true.")},INVALID_ROOMID_INTEGER:function(e){return"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false.")},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:function(e){var t=e.error,i=e.code;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:function(e){return"reJoin room: ".concat(e.roomId," failed, please check your network.")},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat(KT,', please call switchRole("').concat(QT,'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:"duplicate publishing, please unpublish and then re-publish.",INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:function(e){var t=e.message,i=e.stream;return"failed to subscribe ".concat(i.getUserId()," ").concat(i.getType()," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat(QT," or ").concat(KT,"."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:function(e){return"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,".")},CLIENT_BANNED:function(e){return"client was banned because of "+e.message+"."},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:function(e){return"startPublishCDNStream failed, errMsg: ".concat(e.message,".")},STOP_PUBLISH_CDN_FAILED:function(e){return"stopPublishCDNStream failed, errMsg: ".concat(e.message,".")},INVALID_STREAM_ID:function(e){return"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"the track to be removed is not being publishing.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REMOVE_TRACK_NOT_PUBLISHED:function(e){return"try to replace ".concat(e.kind," track but there's no previous ").concat(e.kind," being published.")},START_MIX_TRANSCODE_FAILED:function(e){return"startMixTranscode failed, errMsg: ".concat(e.message,".")},STOP_MIX_TRANSCODE_FAILED:function(e){return"stopMixTranscode failed, errMsg: ".concat(e.message,".")},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:function(e){var t=e.key,i=e.rule,r=e.fnName;return e.value,"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:function(e){return"'".concat(e,"' is required and must be between 1 and 15.")},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:function(e){var t=e.key,i=e.fnName;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:function(e){var t=e.key,i=e.fnName,r=e.type;return"the element corresponding to '".concat(t,"' must be instanceof HTMLDivElement when calling ").concat(i,"(), received: ").concat(r,".")},PLAY_FAILED:function(e){return"".concat(e.media," play failed,browser exception: ").concat(e.error.toString())},INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_REPLACE_TRACK:"replaceTrack is not supported in this browser, please use switchDevice or addTrack instead.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone and the configuration on TRTC.createStream.",CAMERA_NOT_FOUND:"no camera detected, please check your camera and the configuration on TRTC.createStream.",SIGNAL_RESPONSE_FAILED:function(e){return"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,".")},CATCH_HANDLER_ERROR:function(e){var t=e.name,i=e.event;return"an error was caught on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST:function(e){var t=e.name;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:function(e){return"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join.")},STREAM_UNSUBSCRIBED:"stream has been unsubscribed, please call client.unsubscribe after last client.subscribe finished.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:function(e){var t=e.funName;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:function(e){return"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":"")},SEI_DISABLED:"SEI is disabled, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:function(e){return"buffer size(".concat(e,") is over 1000 Bytes")},SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:function(e){var t=e.isSize,i=e.name,r=e.timesInSecond,n=e.maxSizeInSecond;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?n+" bytes":r," in a second.")},CONNECTION_ABORED:function(e){return"connection aborted due to: "+e}},WC=function(e,t){return t?eC+"/"+e+"/"+t:eC+"/"+e+"/index.html"};function GC(e){var t=e.key,i=e.data,r=e.link,n=e.addDocLink,s=void 0===n||n,o="",a="",c="";ZC(HC[t])?o=HC[t](i):tw(HC[t])&&(o=HC[t]);var u=function(){if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};var e=localStorage.getItem(iC);if(e){e=JSON.parse(e);var t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);var i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}}(),d=u.TRTC_ERROR_INFO,l=u.TRTC_ERROR_LINK;r?c="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(c=l[t]);var h=o;return mw()&&(d&&d[t]&&(ZC(d[t])?a=d[t](i):tw(d[t])&&(a=d[t])),a&&(h=s?a+"\n请查看文档: "+WC("zh-cn",c)+"\n\n":a+"\n\n",h+=o)),s&&(h+=" \nRefer to: "+WC("en",c)+"\n"),h}var qC=function(){return function(e){var t=window.location.search.match(new RegExp("(\\?|&)trtc_env=([^&]*)(&|$)"));return t?decodeURIComponent(t[2]):""}()},JC=function(e){return(e=Number(e))>0&&e<14e8},zC=function(e,t){var i;i=JT||(JC(e)?"https://apisgp.my-imcloud.com":"https://yun.tim.qq.com");var r=Math.floor(Math.random()*Math.pow(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function YC(){var e=navigator.userAgent,t=navigator.connection,i=e.match(/NetType\/\w+/)?e.match(/NetType\/\w+/)[0]:"";"3gnet"===(i=i.toLowerCase().replace("nettype/",""))&&(i="3g");var r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();"slow-2"===n&&(n="2g");var s=i||"unknown";if(r)switch(r){case"cellular":case"wimax":s=n||"unknown";break;case"wifi":s="wifi";break;case"ethernet":s="wired";break;case"none":case"other":case"unknown":s="unknown"}return s}var QC=function(e){if(!e||"object"!==n(e)||"[object Object]"!=Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function KC(e){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:KC(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function XC(e){var t=Math.round(e/2)+1;return t>6?13e3:1e3*KC(t)}var ZC=function(e){return"function"==typeof e},ew=function(e){return void 0===e},tw=function(e){return"string"==typeof e},iw=function(e){return"number"==typeof e},rw=function(e){return"boolean"==typeof e},nw=function(e){return"object"===aw(e)},sw=function(e){return"array"===aw(e)},ow=function(e){return aw(e)==="MediaStreamTrack".toLowerCase()};function aw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}function cw(e){var t={};return t.urls="turn:".concat(e.url),ew(e.username)||ew(e.credential)||(t.username=e.username,t.credential=e.credential,t.credentialType="password",ew(e.credentialType)||(t.credentialType=e.credentialType)),t}function uw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}function dw(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"big";if(!tw(e))return 0;var i=e.split(".");return"big"===t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var lw,hw,mw=function(){return"zh"===(navigator.language||navigator.userLanguage).substr(0,2)},pw=(lw=!1,hw=document.visibilityState,function(){document.visibilityState!==hw&&Mw.info("visibility change: ".concat(document.visibilityState)),lw||(document.addEventListener("visibilitychange",(function(){Mw.info("visibility change: "+document.visibilityState),hw=document.visibilityState})),lw=!0)});window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext;var fw=function(){var e;return function(){return e||((e=new window.AudioContext).onstatechange=function(){Mw.info("gain context state: ".concat(e.state)),"suspended"===e.state?(e.resume(),document.addEventListener("click",e.resume)):"interrupted"===e.state?e.resume():document.removeEventListener("click",e.resume)},e)}}(),vw=!!window.AudioWorkletNode,gw=function(e,t){var i=e.emit;return e.emit=function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];try{i.apply(e,n)}catch(e){var o=GC({key:BC,data:{name:t,event:n[0]},addDocLink:!1});Mw.warn(o+"\n\n"+e.stack)}},e},_w=function(e){return+e<10?"0".concat(e):e},yw=function(e){var t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;var i=t.split("."),r=_w(i[1])+_w(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),i.join(".")+"."+r};function Sw(e){var t=e.url,i=e.body,r=e.method,n=e.timeout,s=new XMLHttpRequest;return new Promise((function(e,o){s.onload=function(t){if(s.status>=200&&s.status<300&&s.responseText.length>0)try{var i=JSON.parse(s.response);e({data:i})}catch(t){e({data:s.response})}else s.status>0&&o({code:s.status,message:"request failed, readyState:".concat(s.readyState," status:").concat(s.status," loaded size:").concat(t.loaded)})};var a=function(e){o({code:s.readyState,message:"request ".concat(e.type,", readyState:").concat(s.readyState," status:").concat(s.status," loaded size:").concat(e.loaded)})};s.onerror=a,s.onabort=a,s.ontimeout=a,s.timeout=n||5e3,s.open(r||"POST",t,!0),s.send(i)}))}var Ew={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,r,s,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new n(r,s||e,o),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,r,n=[];if(0===this._eventsCount)return n;for(r in e=this._events)t.call(e,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,o=new Array(s);n<s;n++)o[n]=r[n].fn;return o},a.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,n,s,o){var a=i?i+e:e;if(!this._events[a])return!1;var c,u,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,n),!0;case 5:return d.fn.call(d.context,t,r,n,s),!0;case 6:return d.fn.call(d.context,t,r,n,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var h,m=d.length;for(u=0;u<m;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,r);break;case 4:d[u].fn.call(d[u].context,t,r,n);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,r,n){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||n&&!a.once||r&&a.context!==r||o(this,s);else{for(var c=0,u=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(Ew);var bw=Ew.exports,Tw=new bw,Iw=110,Cw=113,ww=114;function Rw(e){var t=e.retryFunction,i=e.settings,n=e.onError,s=e.onRetrying,a=e.onRetryFailed,c=e.context;return function(){for(var e=this,u=arguments.length,d=new Array(u),l=0;l<u;l++)d[l]=arguments[l];var h=i.retries||5,m=0,p=-1,f=0,v=function(){var u=o(r().mark((function o(u,l){var g,_,y,S;return r().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return g=c||e,r.prev=1,r.next=4,t.apply(g,d);case 4:_=r.sent,m=0,u(_),r.next=14;break;case 9:r.prev=9,r.t0=r.catch(1),y=function(){clearTimeout(p),m=0,f=2,l(r.t0)},S=function(){2!==f&&m<h?(m++,f=1,ZC(s)&&s.call(g,m,y),p=setTimeout((function(){p=-1,v(u,l)}),ew(i.timeout)?1e3:i.timeout)):(y(),ZC(a)&&a.call(g,r.t0))},ZC(n)?n.call(g,r.t0,S,l):S();case 14:case"end":return r.stop()}}),o,null,[[1,9]])})));return function(e,t){return u.apply(this,arguments)}}();return new Promise(v)}}var kw=u((function e(t){a(this,e),this.log=t.log,this.level=t.level,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.forAllJoinedClients=t.forAllJoinedClients,this.uploaded=!1})),Aw=function(){function e(t){a(this,e),this.id_=t.id,this.userId_=t.userId,this.sdkAppId_=t.sdkAppId,this.type_=t.type,this.isLocal_=!rw(t.isLocal)||t.isLocal}return u(e,[{key:"setUserId",value:function(e){this.userId_=e}},{key:"setSdkAppId",value:function(e){this.sdkAppId_=e}},{key:"log",value:function(e,t){Mw.log({log:"[".concat(this.isLocal_?"↑":"↓").concat(this.id_,"] ").concat(this.type_?this.type_+" ":"").concat(t),level:e,forAllJoinedClients:ew(this.userId_),userId:this.userId_,sdkAppId:this.sdkAppId_})}},{key:"info",value:function(e){this.log(sC.INFO,e)}},{key:"debug",value:function(e){this.log(sC.DEBUG,e)}},{key:"warn",value:function(e){this.log(sC.WARN,e)}},{key:"error",value:function(e){this.log(sC.ERROR,e)}}]),e}(),Mw=new(function(){function e(){var t=this;a(this,e),this.clients_=new Set,this.queue_=[],this.timeoutId_=-1,this.logLevel_=sC.DEBUG,this.logLevelToUpload_=sC.INFO,this.enableUploadLog_=!0,this.isAbleToUpload_=!1,this.startUpload(),this.checkURLParam(),Tw.on(30,(function(e){var i=e.client;return t.clients_.add(i)})),Tw.on(33,(function(e){var i=e.client;return t.clients_.delete(i)})),Tw.on(31,(function(e){e&&QC(e.config)&&oC[e.config.logLevelToUpload]&&(t.logLevelToUpload_=e.config.logLevelToUpload)})),Tw.on(4,this.setIsAbleToUpload,this),Tw.on(5,this.setIsAbleToUpload,this)}var t,i;return u(e,[{key:"getIsAbleToUpload",value:function(){return this.isAbleToUpload_}},{key:"setIsAbleToUpload",value:function(){this.isAbleToUpload_=!0,Tw.off(4,this.setIsAbleToUpload,this),Tw.off(5,this.setIsAbleToUpload,this)}},{key:"startUpload",value:(i=o(r().mark((function e(){var t=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.upload();case 3:e.next=7;break;case 5:e.prev=5,e.t0=e.catch(0);case 7:this.timeoutId_=setTimeout((function(){return t.startUpload()}),2e3);case 8:case"end":return e.stop()}}),e,this,[[0,5]])}))),function(){return i.apply(this,arguments)})},{key:"stopUpload",value:function(){-1!==this.timeoutId_&&(clearTimeout(this.timeoutId_),this.timeoutId_=-1)}},{key:"getLogsToUpload",value:function(){var e=this,t={map:new Map,splicedQueue:[]};if(this.queue_[0].forAllJoinedClients&&0===this.clients_.size)return t;for(var i=0,r=function(){if(50===i)return"break";var r=e.queue_[i];r.forAllJoinedClients?e.clients_.forEach((function(e){if(e.getIsJoined()){var i=e.getUserId(),n=e.getSDKAppId();t.map.has(i)?t.map.get(i).logs.push(r):t.map.set(i,{userId:i,sdkAppId:n,logs:[r]})}})):t.map.has(r.userId)?t.map.get(r.userId).logs.push(r):t.map.set(r.userId,{userId:r.userId,sdkAppId:r.sdkAppId,logs:[r]})};i<this.queue_.length&&"break"!==r();i++);return t.map.size>0&&(t.splicedQueue=this.queue_.splice(0,i)),t}},{key:"upload",value:(t=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this.queue_.length&&this.isAbleToUpload_){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getLogsToUpload(),i=t.map,n=t.splicedQueue,0!==i.size){e.next=5;break}return e.abrupt("return");case 5:e.prev=5,s=b(i.values()),o=0;case 8:if(!(o<s.length)){e.next=16;break}return a=s[o],c=a.userId,u=a.sdkAppId,d=a.logs,e.next=12,this.uploadLogWithRetry(JSON.stringify({timestamp:Jv(),sdkAppId:String(u),userId:c,version:Uo,log:d.map((function(e){return e.log})).join("\n")}),u);case 12:d.forEach((function(e){return e.uploaded=!0}));case 13:o++,e.next=8;break;case 16:e.next=20;break;case 18:e.prev=18,e.t0=e.catch(5);case 20:(l=n.filter((function(e){return!e.uploaded}))).length>0&&(this.queue_=l.concat(this.queue_));case 22:case"end":return e.stop()}}),e,this,[[5,18]])}))),function(){return t.apply(this,arguments)})},{key:"uploadLogWithRetry",value:function(e,t){return Rw({retryFunction:function(){return Sw({url:zC(t,zT),body:e,timeout:5e3})},settings:{retries:3,timeout:1e3},onError:function(e,t){t()}})()}},{key:"getPrefix",value:function(e){var t=new Date;return t.setTime(qv()),String.prototype.padStart?"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t.getMilliseconds().toString().padStart(3,"0"),"] <").concat(oC[e],">"):"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t.getMilliseconds(),"] <").concat(oC[e],">")}},{key:"getLogLevel",value:function(){return this.logLevel_}},{key:"setLogLevel",value:function(e){ew(oC[e])||(this.logLevel_!==e&&this.info("setLogLevel ".concat(e)),this.logLevel_=e)}},{key:"enableUploadLog",value:function(){this.enableUploadLog_=!0}},{key:"disableUploadLog",value:function(){this.enableUploadLog_=!1}},{key:"log",value:function(e){var t=e.log,i=e.level,r=e.forAllJoinedClients,n=void 0===r||r,s=e.userId,o=e.sdkAppId;if(t="".concat(this.getPrefix(i)," ").concat(t),this.enableUploadLog_&&i>=this.logLevelToUpload_&&this.queue_.push(new kw({log:t,level:i,userId:s,sdkAppId:o,forAllJoinedClients:n})),!(i<this.logLevel_)){var a=oC[i]?oC[i].toLowerCase():"info";console[a](t)}}},{key:"debug",value:function(e){this.log({log:e,level:sC.DEBUG})}},{key:"info",value:function(e){this.log({log:e,level:sC.INFO})}},{key:"warn",value:function(e){this.log({log:e,level:sC.WARN})}},{key:"error",value:function(e){this.log({log:e,level:sC.ERROR})}},{key:"createLogger",value:function(e){return new Aw(e)}},{key:"checkURLParam",value:function(){var e=new URLSearchParams(location.search).get("logLevelToUpload");oC[e]&&(this.logLevelToUpload_=e)}}]),e}()),Ow=!0,Lw=Se,Pw=Math.floor,Nw=Number.isInteger||function(e){return!Lw(e)&&isFinite(e)&&Pw(e)===e};En({target:"Number",stat:!0},{isInteger:Nw});var Dw,xw=og,Uw=TypeError,$w=function(e){if(xw(e))throw Uw("The method doesn't accept regular expressions");return e},Bw=Ot("match"),Vw=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[Bw]=!1,"/./"[e](t)}catch(e){}}return!1},Fw=En,jw=te,Hw=M.f,Ww=Mr,Gw=Qd,qw=$w,Jw=de,zw=Vw,Yw=jw("".startsWith),Qw=jw("".slice),Kw=Math.min,Xw=zw("startsWith");Fw({target:"String",proto:!0,forced:!(!Xw&&(Dw=Hw(String.prototype,"startsWith"),Dw&&!Dw.writable)||Xw)},{startsWith:function(e){var t=Gw(Jw(this));qw(e);var i=Ww(Kw(arguments.length>1?arguments[1]:void 0,t.length)),r=Gw(e);return Yw?Yw(t,r,i):Qw(t,i,i+r.length)===r}});var Zw=L,eR=te,tR=x,iR=O,rR=Fo,nR=Jr,sR=U,oR=ht,aR=oe,cR=Object.assign,uR=Object.defineProperty,dR=eR([].concat),lR=!cR||iR((function(){if(Zw&&1!==cR({b:1},cR(uR({},"a",{enumerable:!0,get:function(){uR(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!=cR({},e)[i]||rR(cR({},t)).join("")!=r}))?function(e,t){for(var i=oR(e),r=arguments.length,n=1,s=nR.f,o=sR.f;r>n;)for(var a,c=aR(arguments[n++]),u=s?dR(rR(c),s(c)):rR(c),d=u.length,l=0;d>l;)a=u[l++],Zw&&!tR(o,c,a)||(i[a]=c[a]);return i}:cR,hR=lR;En({target:"Object",stat:!0,arity:2,forced:Object.assign!==hR},{assign:hR});var mR=te,pR=ze,fR=Se,vR=ft,gR=Nl,_R=P,yR=Function,SR=mR([].concat),ER=mR([].join),bR={},TR=function(e,t,i){if(!vR(bR,t)){for(var r=[],n=0;n<t;n++)r[n]="a["+n+"]";bR[t]=yR("C,a","return new C("+ER(r,",")+")")}return bR[t](e,i)},IR=_R?yR.bind:function(e){var t=pR(this),i=t.prototype,r=gR(arguments,1),n=function(){var i=SR(r,gR(arguments));return this instanceof n?TR(t,i.length,i):t.apply(e,i)};return fR(i)&&(n.prototype=i),n};En({target:"Function",proto:!0,forced:Function.bind!==IR},{bind:IR});var CR=En,wR=ds.findIndex,RR=va,kR="findIndex",AR=!0;kR in[]&&Array(1).findIndex((function(){AR=!1})),CR({target:"Array",proto:!0,forced:AR},{findIndex:function(e){return wR(this,e,arguments.length>1?arguments[1]:void 0)}}),RR(kR);var MR=L,OR=te,LR=Fo,PR=me,NR=OR(U.f),DR=OR([].push),xR=function(e){return function(t){for(var i,r=PR(t),n=LR(r),s=n.length,o=0,a=[];s>o;)i=n[o++],MR&&!NR(r,i)||DR(a,e?[i,r[i]]:r[i]);return a}}(!1);En({target:"Object",stat:!0},{values:function(e){return xR(e)}});var UR=Ur.includes,$R=va;En({target:"Array",proto:!0,forced:O((function(){return!Array(1).includes()}))},{includes:function(e){return UR(this,e,arguments.length>1?arguments[1]:void 0)}}),$R("includes");var BR=En,VR=$w,FR=de,jR=Qd,HR=Vw,WR=te("".indexOf);BR({target:"String",proto:!0,forced:!HR("includes")},{includes:function(e){return!!~WR(jR(FR(this)),jR(VR(e)),arguments.length>1?arguments[1]:void 0)}});var GR="DISCONNECTED",qR="CONNECTING",JR="RECONNECTING",zR="CONNECTED",YR={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772},QR=[YR.UPDATE_REMOTE_MUTE_STAT,YR.UPLINK_NETWORK_STATS,YR.USER_LIST_RES,YR.MUTE_RESULT],KR={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res"},XR="unpublish",ZR={INVALID_PARAMETER:4096,INVALID_OPERATION:4097,NOT_SUPPORTED:4098,DEVICE_NOT_FOUND:4099,INITIALIZE_FAILED:4100,SIGNAL_CHANNEL_SETUP_FAILED:16385,SIGNAL_CHANNEL_ERROR:16386,ICE_TRANSPORT_ERROR:16387,JOIN_ROOM_FAILED:16388,CREATE_OFFER_FAILED:16389,SIGNAL_CHANNEL_RECONNECTION_FAILED:16390,UPLINK_RECONNECTION_FAILED:16391,DOWNLINK_RECONNECTION_FAILED:16392,REMOTE_STREAM_NOT_EXIST:16400,CLIENT_BANNED:16448,SERVER_TIMEOUT:16449,SUBSCRIPTION_TIMEOUT:16450,PLAY_NOT_ALLOWED:16451,DEVICE_AUTO_RECOVER_FAILED:16452,START_PUBLISH_CDN_FAILED:16453,STOP_PUBLISH_CDN_FAILED:16454,START_MIX_TRANSCODE_FAILED:16455,STOP_MIX_TRANSCODE_FAILED:16456,NOT_SUPPORTED_H264:16457,SWITCH_ROLE_FAILED:16458,API_CALL_TIMEOUT:16459,SCHEDULE_FAILED:16460,API_CALL_ABORTED:16461,UNKNOWN:65535},ek=function(e){l(i,e);var t=_(i);function i(e){var r,n=e.name,s=void 0===n?"RtcError":n,o=e.message,c=e.code,u=void 0===c?ZR.UNKNOWN:c,d=e.extraCode,l=void 0===d?0:d,h=e.constraint;a(this,i);var m="<".concat(function(e){for(var t in ZR)if(ZR[t]===e)return t;return"UNKNOWN"}(u)," 0x").concat(u.toString(16),">");return(r=t.call(this,o+"".concat(h?" constraint: ".concat(h):"")+"".concat(null!=o&&o.includes(m)?"":" "+m))).code_=u,r.extraCode_=l,r.name=s,r.message_=o,h&&(r.constraint=h),r}return u(i,[{key:"getCode",value:function(){return this.code_}},{key:"getExtraCode",value:function(){return this.extraCode_}}]),i}(v(Error)),tk=new Map,ik=function(e,t){var i=tk.get(e);i||(tk.set(e,[]),i=tk.get(e)),i.push(t)},rk=function(e){var t=tk.get(e),i=[];return t?(tk.delete(e),i=t.map((function(e){return{uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}}))):i=[],i},nk=Object.prototype.hasOwnProperty;function sk(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(QC(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(var t in e)if(nk.call(e,t))return!1;return!0}return!1}var ok=new(function(){function e(){a(this,e);var t=TT(),i=t.name,r=t.version;this.roomIdMap_=new Map,this.configs_={sdkAppId:"",userId:"",version:Uo,env:qT,browserVersion:i+r,ua:navigator.userAgent}}return u(e,[{key:"setConfig",value:function(e){var t=e.sdkAppId,i=e.env,r=e.userId,n=e.roomId;t!==this.configs_.sdkAppId&&(this.configs_.sdkAppId=String(t)),this.configs_.env=i,this.configs_.userId=r,this.roomIdMap_.set(r,String(n))}},{key:"logEvent",value:function(e){if(!ST){var t=i(i(i({},e),this.configs_),{},{userId:e.userId||this.configs_.userId});ew(t.code)&&(t.code="failed"===t.result?ZR.UNKNOWN:0),this.sendRequest(zC(this.configs_.sdkAppId,"jssdk_event"),t)}}},{key:"logSuccessEvent",value:function(e){ST||(this.logEvent(i(i({},e),{},{result:"success",roomId:this.roomIdMap_.get(e.userId)})),this.configs_.env===qT&&this.uploadEventToKibana(i(i({},e),{},{result:"success"})))}},{key:"logFailedEvent",value:function(e){if(!ST){var t=e.eventType,r=e.code,n=e.error,s=e.userId,o={roomId:this.roomIdMap_.get(s),userId:s,eventType:t,result:"failed",code:r||(n instanceof ek?n.getExtraCode()||n.getCode():ZR.UNKNOWN)};this.logEvent(o),this.configs_.env===qT&&this.uploadEventToKibana(i(i({},o),{},{error:n}))}}},{key:"uploadEventToKibana",value:function(e){var t="stat-".concat(e.eventType,"-").concat(e.result);"delta-join"!==e.eventType&&"delta-leave"!==e.eventType&&"delta-publish"!==e.eventType||(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}},{key:"uploadEvent",value:function(e){var t=e.log,i=e.userId,r=e.error,n={timestamp:Jv(),sdkAppId:this.configs_.sdkAppId,userId:i||this.configs_.userId,version:this.configs_.version,log:t};r&&(n.errorInfo=r.message),this.sendRequest(zC(this.configs_.sdkAppId,zT),n)}},{key:"sendRequest",value:function(e,t){var i=this;Mw.getIsAbleToUpload()?Sw({url:e,body:JSON.stringify(t)}).catch((function(){})):setTimeout((function(){i.sendRequest(e,t)}),1e3)}}]),e}()),ak=function(){function e(t){a(this,e),this.client_=t.client,this.sdkAppId_=t.sdkAppId,this.userId_=t.userId,this.userSig_=t.userSig,this.url_=t.url,this.backupUrl_=t.backupUrl;var i="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId_),"&userId=").concat(encodeURIComponent(this.userId_),"&userSig=").concat(encodeURIComponent(this.userSig_));this.urlWithParam_="".concat(this.url_).concat(i),this.backupUrlWithParam_="".concat(this.backupUrl_).concat(i),this.isConnected_=!1,this.isConnecting_=!1,this.socketInUse_=null,this.socket_=null,this.backupSocket_=null,this.backupTimer_=-1,this.signalInfo_={},this.currentState_=GR,this.reconnectionCount_=0,this.reconnectionTimer_=-1,this.seq_=0,this.log_=Mw.createLogger({id:"ws|"+this.userId_,userId:this.userId_,sdkAppId:this.sdkAppId_}),this.emitter_=new bw}return u(e,[{key:"connect",value:function(){var e=this;return new Promise((function(t,i){e.log_.info("connect to url: ".concat(e.urlWithParam_)),e.emitConnectionStateChanged(qR),e.socket_=new WebSocket(e.urlWithParam_),e.bindSocket(e.socket_),e.backupTimer_=setTimeout((function(){e.isConnected_||(e.log_.info("trying to connect to backupUrl"),e.tryConnectBackup())}),5e3),e.once(3,t),e.once(4,i)}))}},{key:"tryConnectBackup",value:function(){this.backupSocket_||(this.unbindAndCloseSocket(VT),this.log_.debug("try to connect to url: ".concat(this.backupUrlWithParam_)),this.backupSocket_=new WebSocket(this.backupUrlWithParam_),this.bindSocket(this.backupSocket_))}},{key:"bindSocket",value:function(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}},{key:"unbindSocket",value:function(e){e.onopen=function(){},e.onclose=function(){},e.onerror=function(){},e.onmessage=function(){}}},{key:"unbindAndCloseSocket",value:function(e){if(e===VT){if(this.socket_){this.unbindSocket(this.socket_);try{this.socket_.close(1e3)}catch(e){}this.socket_=null}}else if(this.backupSocket_){this.unbindSocket(this.backupSocket_);try{this.backupSocket_.close(1e3)}catch(e){}this.backupSocket_=null}}},{key:"clearBackupTimer",value:function(){-1!==this.backupTimer_&&(clearTimeout(this.backupTimer_),this.backupTimer_=-1)}},{key:"clearReconnectionTimer",value:function(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}},{key:"onopen",value:function(e){if(!this.isConnected_){this.isConnected_=!0,this.isConnecting_=!1,this.clearBackupTimer(),e.target===this.socket_?(this.unbindAndCloseSocket(FT),this.socketInUse_=this.socket_):(this.unbindAndCloseSocket(VT),this.socketInUse_=this.backupSocket_);var t=e.target.url;this.log_.info("websocket[".concat(t,"] is connected")),this.currentState_===qR?this.addSignalEvent(32791,"signal channel is connected"):this.currentState_===JR&&this.addSignalEvent(32795,"signal channel reconnect success"),this.emitConnectionStateChanged(zR),this.emitter_.emit(3)}}},{key:"onclose",value:function(e){var t=e.target.url,i=e.target===this.socketInUse_;this.log_.info("websocket[".concat(t," InUse: ").concat(i,"] is closed with code: ").concat(e.code)),e.target===this.socketInUse_&&(this.isConnected_=!1,this.emitConnectionStateChanged(GR),this.addSignalEvent(32790,"signal channel is disconnected"),e.wasClean&&1e3===e.code||(this.log_.warn("onclose code:".concat(e.code," reason:").concat(e.reason)),this.log_.warn("close current websocket and schedule a reconnect timeout"),this.socketInUse_.onclose=function(){},this.socketInUse_.close(4011),this.socket_=this.backupSocket_=this.socketInUse_=null,this.reconnect(VT)))}},{key:"onerror",value:function(e){var t=e.target.url;this.log_.error("websocket[".concat(t,"] error observed")),this.isConnected_?e.target===this.socketInUse_&&(this.isConnected_=!1,this.unbindAndCloseSocket(VT),this.unbindAndCloseSocket(FT),this.socketInUse_=null,this.reconnect(VT)):(this.isReconnecting_||ok.logFailedEvent({userId:this.client_.getUserId(),eventType:bI,code:ZR.UNKNOWN}),e.target==this.socket_?(this.unbindAndCloseSocket(VT),this.reconnect(FT)):(this.unbindAndCloseSocket(FT),this.reconnect(VT))),this.isConnecting_=!1,this.isConnected_=!1}},{key:"onmessage",value:function(e){if(this.isConnected_){var t=JSON.parse(e.data),i=t.cmd,r=t.data,n=Object.values(YR),s=Object.keys(YR)[n.indexOf(i)],o=KR[s];switch(QR.includes(i)||(this.log_.debug("received msg: ".concat(e.data)),this.log_.info("Received event: [ ".concat(o||"unknown cmd: "+i," ]"))),i){case YR.CHANNEL_SETUP_RESULT:if(0===t.code)this.signalInfo_.clientIp=r.clientIp,this.signalInfo_.signalIp=r.signalInnerIp,this.signalInfo_.tinyId=t.tinyId,r.svrTime&&function(e){Gv=e-(new Date).getTime();var t=new Date;t.setTime(e),Mw.info("baseTime from server: "+t+" offset: "+Gv)}(r.svrTime),this.log_.info("ChannelSetup Success"),ok.logSuccessEvent({userId:this.userId_,eventType:bI}),this.emitter_.emit(1,{signalInfo:this.signalInfo_});else{var a=new ek({code:ZR.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:GC({key:"SIGNAL_CHANNEL_SETUP_FAILED",data:{errorCode:t.code,errorMsg:t.message}})});this.log_.error("".concat(t.code,", ").concat(t.message)),this.close(),ok.logFailedEvent({userId:this.userId_,eventType:bI,error:a}),this.emitter_.emit(5,a)}break;case YR.JOIN_ROOM_RESULT:0===t.code&&(this.signalInfo_.relayIp=r.relayOuterIp,this.signalInfo_.relayInnerIp=r.relayInnerIp,this.signalInfo_.relayPort=r.relayPort,this.log_.info("signalIp:".concat(this.signalInfo_.signalIp," clientIp:").concat(this.signalInfo_.clientIp," relayIp: ").concat(this.signalInfo_.relayIp))),this.emitter_.emit(o,{data:t});break;case YR.CHANNEL_RECONNECT_RESULT:0===t.code?(this.log_.warn("reconnect success"),this.stopReconnection(),ok.logSuccessEvent({userId:this.userId_,eventType:TI}),this.client_.syncUserList(),this.client_.checkConnectionsToReconnect()):(this.log_.warn("reconnect failed, ".concat(t.code," ").concat(t.message)),this.client_.reJoin());break;default:this.emitter_.emit(o,{data:t})}}}},{key:"addSignalEvent",value:function(e,t){ik(this.userId_,{eventId:e,eventDesc:t,timestamp:qv(),userId:this.userId_,tinyId:this.signalInfo_.tinyId})}},{key:"reconnect",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:VT;if(this.isConnecting_||-1!==this.reconnectionTimer_)this.log_.info("signal channel is reconnecting, ignoring current reconnection");else{if(this.reconnectionCount_>=30){this.log_.warn("SDK has tried reconnect signal channel for ".concat(30," times, but all failed. please check your network"));var i=new ek({code:ZR.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:GC({key:TC})});return ok.logFailedEvent({userId:this.client_.getUserId(),eventType:TI,error:i}),this.addSignalEvent(32796,"signal channel reconnect fail"),void this.emitter_.emit(4,i)}this.isConnecting_=!0,this.reconnectionCount_++,this.currentState_!==JR&&(this.emitConnectionStateChanged(JR),this.addSignalEvent(32794,"signal channel is reconnecting")),this.log_.warn("reconnecting to ".concat(t," signal channel [").concat(this.reconnectionCount_,"/").concat(30,"]"));var r=this.getReconnectionUrl(t);t===VT?(this.socket_=new WebSocket(r),this.bindSocket(this.socket_)):(this.backupSocket_=new WebSocket(r),this.bindSocket(this.backupSocket_));var n=XC(this.reconnectionCount_);this.reconnectionTimer_=setTimeout((function(){e.log_.warn("reconnect ".concat(t," signal channel timeout(").concat(n/1e3,"s), close and try again")),e.isConnecting_=!1,e.clearReconnectionTimer(),e.unbindAndCloseSocket(t),e.reconnect(t===VT?FT:VT)}),n)}}},{key:"isConnected",value:function(){return this.isConnected_}},{key:"isReconnecting_",get:function(){return-1!==this.reconnectionTimer_}},{key:"getReconnectionUrl",value:function(e){var t=e===VT?this.urlWithParam_:this.backupUrlWithParam_;if(!sk(this.signalInfo_)&&-1===t.indexOf("&rc=1")){var i=this.client_.getRoomId(),r=this.client_.getUseStringRoomId();t+="&rc=1&relayInnerIp=".concat(this.signalInfo_.relayInnerIp,"&relayOuterIp=").concat(this.signalInfo_.relayIp,"&relayPort=").concat(this.signalInfo_.relayPort,"&roomId=").concat(i,"&useStringRoomId=").concat(r)}return t}},{key:"send",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected_){var i={cmd:e,data:t,userId:this.userId_,tinyId:this.signalInfo_.tinyId,seq:++this.seq_};return this.socketInUse_.send(JSON.stringify(i)),i.seq}}},{key:"sendWaitForResponse",value:function(e){var t=this,i=e.command,r=e.data,n=e.timeout,s=void 0===n?5e3:n,o=e.responseCommand,a=e.commandDesc,c=e.enableLog,u=void 0===c||c;return new Promise((function(e,n){var c=setTimeout((function(){t.off(o,d);var e=new ek({code:ZR.API_CALL_TIMEOUT,message:GC({key:"API_CALL_TIMEOUT",data:{commandDesc:a,command:i}})});u&&t.log_.warn(e),n(e)}),s),d=function i(r){r.data.seq===l&&(clearTimeout(c),t.off(o,i),e(r))};t.on(o,d);var l=t.send(i,r)}))}},{key:"sendWaitForResponseWithRetry",value:function(){var e=this,t=arguments.length<=0?void 0:arguments[0],i=t.commandDesc,r=t.command,n=t.retries,s=void 0===n?0:n,o=t.retryTimeout,a=void 0===o?0:o;return Rw({retryFunction:this.sendWaitForResponse,onRetrying:function(t){e.log_.warn("".concat(i||r," timeout observed, retrying [").concat(t,"/").concat(s,"]"))},settings:{retries:s,timeout:a},context:this}).apply(void 0,arguments)}},{key:"getCurrentState",value:function(){return this.currentState_}},{key:"getSignalInfo",value:function(){return this.signalInfo_}},{key:"stopReconnection",value:function(){this.isReconnecting_&&(this.reconnectionCount_=0,this.clearReconnectionTimer())}},{key:"close",value:function(){this.log_.info("close SignalChannel"),this.clearBackupTimer(),this.stopReconnection(),this.isConnecting_=!1,this.isConnected_=!1,this.socketInUse_=null,this.unbindAndCloseSocket(VT),this.unbindAndCloseSocket(FT),this.emitConnectionStateChanged(GR)}},{key:"on",value:function(e,t,i){this.emitter_.on(e,t,i)}},{key:"removeListener",value:function(e,t,i){this.emitter_.removeListener(e,t,i)}},{key:"once",value:function(e,t,i){this.emitter_.once(e,t,i)}},{key:"off",value:function(e,t,i){this.emitter_.off(e,t,i)}},{key:"emitConnectionStateChanged",value:function(e){e!==this.currentState_&&(this.emitter_.emit(2,{prevState:this.currentState_,state:e}),this.currentState_=e)}}]),e}(),ck=En,uk=ds.find,dk=va,lk=!0;"find"in[]&&Array(1).find((function(){lk=!1})),ck({target:"Array",proto:!0,forced:lk},{find:function(e){return uk(this,e,arguments.length>1?arguments[1]:void 0)}}),dk("find");var hk={},mk={},pk={exports:{}},fk=pk.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(fk).forEach((function(e){fk[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:n?i[e.name]:i;!function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))}(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=pk.exports,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,o,n)}})),t.media=s,t};var s=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}}(mk);var vk=pk.exports,gk=/%[sdv%]/g,_k=function(e){var t=1,i=arguments,r=i.length;return e.replace(gk,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},yk=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?r.push(i[t.name][s]):r.push(i[t.names[n]])}else r.push(i[t.name]);return _k.apply(null,r)},Sk=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ek=["i","c","b","a"],bk=mk;hk.write=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||Sk,r=t.innerOrder||Ek,n=[];return i.forEach((function(t){vk[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(yk(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(yk(t,i,e))}))}))})),e.media.forEach((function(e){n.push(yk("m",vk.m[0],e)),r.forEach((function(t){vk[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(yk(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(yk(t,i,e))}))}))}))})),n.join("\r\n")+"\r\n"},hk.parse=bk.parse,hk.parseParams=bk.parseParams,hk.parseFmtpConfig=bk.parseFmtpConfig,hk.parsePayloads=bk.parsePayloads,hk.parseRemoteCandidates=bk.parseRemoteCandidates,hk.parseImageAttributes=bk.parseImageAttributes,hk.parseSimulcastStreamList=bk.parseSimulcastStreamList;var Tk=function(e){return hk.parse(e)},Ik=function(e){return hk.write(e)},Ck=function(e){var t=Tk(e);return t.media.forEach((function(e){e.type===wT&&e.fmtp.forEach((function(e){e.config+=";sprop-stereo=1;stereo=1"}))})),Ik(t)};function wk(e){var t=Tk(e);return t.media.forEach((function(e){if(e.type===RT){var t=new Set;e.rtp.forEach((function(e){var i=e.payload;return"H264"===e.codec&&t.add(i)})),e.fmtp.forEach((function(e){var i=e.payload,r=e.config.match(/apt=(\d+)/);r&&r[1]&&t.has(Number(r[1]))&&t.add(i)}));var i=function(e){var i=e.payload;return!t.has(i)};e.rtp=e.rtp.filter(i),e.rtcpFb=e.rtcpFb.filter(i),e.fmtp=e.fmtp.filter(i),e.payloads=e.payloads.split(" ").filter((function(e){return!t.has(Number(e))})).join(" ")}})),Ik(t)}var Rk,kk,Ak,Mk,Ok=En,Lk=te,Pk=Tr,Nk=qg,Dk=om,xk=O,Uk=RangeError,$k=String,Bk=Math.floor,Vk=Lk(Dk),Fk=Lk("".slice),jk=Lk(1..toFixed),Hk=function(e,t,i){return 0===t?i:t%2==1?Hk(e,t-1,i*e):Hk(e*e,t/2,i)},Wk=function(e,t,i){for(var r=-1,n=i;++r<6;)n+=t*e[r],e[r]=n%1e7,n=Bk(n/1e7)},Gk=function(e,t){for(var i=6,r=0;--i>=0;)r+=e[i],e[i]=Bk(r/t),r=r%t*1e7},qk=function(e){for(var t=6,i="";--t>=0;)if(""!==i||0===t||0!==e[t]){var r=$k(e[t]);i=""===i?r:i+Vk("0",7-r.length)+r}return i};Ok({target:"Number",proto:!0,forced:xk((function(){return"0.000"!==jk(8e-5,3)||"1"!==jk(.9,0)||"1.25"!==jk(1.255,2)||"1000000000000000128"!==jk(0xde0b6b3a7640080,0)}))||!xk((function(){jk({})}))},{toFixed:function(e){var t,i,r,n,s=Nk(this),o=Pk(e),a=[0,0,0,0,0,0],c="",u="0";if(o<0||o>20)throw Uk("Incorrect fraction digits");if(s!=s)return"NaN";if(s<=-1e21||s>=1e21)return $k(s);if(s<0&&(c="-",s=-s),s>1e-21)if(i=(t=function(e){for(var t=0,i=e;i>=4096;)t+=12,i/=4096;for(;i>=2;)t+=1,i/=2;return t}(s*Hk(2,69,1))-69)<0?s*Hk(2,-t,1):s/Hk(2,t,1),i*=4503599627370496,(t=52-t)>0){for(Wk(a,0,i),r=o;r>=7;)Wk(a,1e7,0),r-=7;for(Wk(a,Hk(10,r,1),0),r=t-1;r>=23;)Gk(a,1<<23),r-=23;Gk(a,1<<r),Wk(a,1,1),Gk(a,2),u=qk(a)}else Wk(a,0,i),Wk(a,1<<-t,0),u=qk(a)+Vk("0",o);return o>0?c+((n=u.length)<=o?"0."+Vk("0",o-n)+u:Fk(u,0,n-o)+"."+Fk(u,n-o)):c+u}});var Jk=(null===(Rk=window)||void 0===Rk?void 0:Rk.requestIdleCallback)||function(e){var t=Date.now();return setTimeout((function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})}),1e3)},zk=(null===(kk=window)||void 0===kk?void 0:kk.cancelIdleCallback)||function(e){clearTimeout(e)},Yk=(null===(Ak=window)||void 0===Ak?void 0:Ak.cancelAnimationFrame)||(null===(Mk=window)||void 0===Mk?void 0:Mk.mozCancelAnimationFrame),Qk=function(){function e(){a(this,e)}return u(e,null,[{key:"generateTaskID",value:function(){return this.currentTaskID++}},{key:"run",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:lC,t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0;r=i(i({},e===dC?{delay:2e3,count:0,backgroundTask:!0}:e===cC?{delay:1e4,count:0}:e===uC?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),r),nw(t)&&(r=i(i({},r),t)),ZC(e)&&(t=e,e=lC);var n=i({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},r);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}},{key:"interval",value:function(e){var t=this;return e.intervalID=setInterval((function(){e.callback(),e.loopCount+=1,t.isBreakLoop(e)}),e.delay)}},{key:"timeout",value:function(e){var t=this;return e.timeoutID=setTimeout((function i(){if(e.callback(),e.loopCount+=1,!t.isBreakLoop(e))return e.timeoutID=setTimeout(i,e.delay)}),e.delay)}},{key:"ric",value:function(e){var t,i=this,r=uw();return e.ricID=Jk((function n(){if((t=uw()-r)>=e.delay&&(r=uw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!i.isBreakLoop(e))return e.ricID=Jk(n,{timeout:e.delay})}),{timeout:e.delay})}},{key:"raf",value:function(e){var t=this;e.delay=(1e3/e.fps).toFixed(2);var i,r=uw(),n=function n(){if(document.hidden&&e.backgroundTask){if(i=uw()-r,r=uw(),e.callback(),e.loopCount+=1,t.isBreakLoop(e))return;return e.timeoutID=setTimeout(n,e.delay-Math.floor(i%e.delay))}if((i=uw()-r)>=e.delay&&(r=uw()-Math.floor(i%e.delay),e.callback(),e.loopCount+=1),!t.isBreakLoop(e))return e.rafID=requestAnimationFrame(n)};if(e.rafID=requestAnimationFrame(n),e.backgroundTask){var s=function(){if(document.hidden){var t=uw()-r;t>=e.delay?n():e.timeoutID=setTimeout(n,e.delay-t)}};document.addEventListener("visibilitychange",s),e.onVisibilitychange=s,document.hidden&&s()}return e.taskID}},{key:"hasTask",value:function(e){return this.taskMap.has(e)}},{key:"clearTask",value:function(e){if(!this.taskMap.has(e))return!0;var t=this.taskMap.get(e),i=t.intervalID,r=t.timeoutID,n=t.rafID,s=t.ricID,o=t.onVisibilitychange;return i&&clearInterval(i),r&&clearTimeout(r),n&&Yk(n),s&&zk(s),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}},{key:"isBreakLoop",value:function(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}}]),e}();d(Qk,"taskMap",new Map),d(Qk,"currentTaskID",1);var Kk=new(function(){function e(){a(this,e),this.prefix_="TRTC",this.queue_=new Map,this.checkStorage()}return u(e,[{key:"getRealKey",value:function(e){return"".concat(this.prefix_,"_").concat(e)}},{key:"checkStorage",value:function(){var e=this;ET()&&Object.keys(localStorage).filter((function(t){if(t.startsWith(e.prefix_)){var i=JSON.parse(localStorage.getItem(t));if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((function(e){return localStorage.removeItem(e)}))}},{key:"doFlush",value:function(){if(ET())try{var e,t=C(this.queue_);try{for(t.s();!(e=t.n()).done;){var i=E(e.value,2),r=i[0],n=i[1];localStorage.setItem(r,JSON.stringify(n))}}catch(e){t.e(e)}finally{t.f()}}catch(e){Mw.warn(e)}}},{key:"getItem",value:function(e){if(!ET())return null;try{var t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){Mw.warn(e)}}},{key:"setItem",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(ET())try{var r={expiresIn:Date.now()+HI,value:t};i?localStorage.setItem(this.getRealKey(e),JSON.stringify(r)):(this.queue_.set(this.getRealKey(e),r),Qk.hasTask(this.intervalId_)||(this.intervalId_=Qk.run(cC,this.doFlush.bind(this),{count:1})))}catch(e){Mw.warn(e)}}},{key:"deleteItem",value:function(e){if(!ET())return!1;try{return e=this.getRealKey(e),this.queue_.delete(e),localStorage.removeItem(e),!0}catch(e){return Mw.warn(e),!1}}},{key:"clear",value:function(){if(ET())try{localStorage.clear()}catch(e){Mw.warn(e)}}}]),e}()),Xk={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isMediaDevicesSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Zk="checkResult",eA=function(){return!(zb||bb||Ib&&Cb<80||Sb&&Eb<56)},tA=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((function(e){return e in window})).length>0},iA=function(){if(!navigator.mediaDevices)return!1;var e=["getUserMedia","enumerateDevices"];return e.filter((function(e){return e in navigator.mediaDevices})).length===e.length},rA=function(){var e=o(r().mark((function e(){var t,i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Xk.detail.isH264EncodeSupported||!Xk.detail.isVp8EncodeSupported){e.next=2;break}return e.abrupt("return",{isH264EncodeSupported:Xk.detail.isH264EncodeSupported,isVp8EncodeSupported:Xk.detail.isVp8EncodeSupported});case 2:return t="",i=!1,n=!1,e.prev=5,s=new RTCPeerConnection,(o=document.createElement("canvas")).getContext("2d"),a=o.captureStream(0),s.addTrack(a.getVideoTracks()[0],a),e.next=13,s.createOffer();case 13:return-1!==(t=e.sent).sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(n=!0),s.close(),Xk.detail.isH264EncodeSupported=i,Xk.detail.isVp8EncodeSupported=n,e.abrupt("return",{isH264EncodeSupported:Xk.detail.isH264EncodeSupported,isVp8EncodeSupported:Xk.detail.isVp8EncodeSupported});case 22:return e.prev=22,e.t0=e.catch(5),e.abrupt("return",{isH264EncodeSupported:!1,isVp8EncodeSupported:!1});case 25:case"end":return e.stop()}}),e,null,[[5,22]])})));return function(){return e.apply(this,arguments)}}();function nA(){return sA.apply(this,arguments)}function sA(){return(sA=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",new Promise(function(){var e=o(r().mark((function e(t){var i,n,s,a,c,u,d,l,h,m,p,f,v,g;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i={encode:!1,decode:!1},n=null,e.prev=2,s=document.createElement("canvas"),a=s.getContext("2d"),s.width=640,s.height=480,c=setInterval((function(){a.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),33),u=-1,d=-1,n=function(){clearInterval(u),clearInterval(c),clearTimeout(d),h.close(),m.close(),l.getTracks().forEach((function(e){return e.stop()}))},d=setTimeout((function(){n(),t(i)}),3e3),l=s.captureStream(),h=new RTCPeerConnection({}),m=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),h.addEventListener("icecandidate",(function(e){return m.addIceCandidate(e.candidate)})),m.addEventListener("icecandidate",(function(e){return h.addIceCandidate(e.candidate)})),h.addTrack(l.getVideoTracks()[0],l),e.next=20,h.createOffer();case 20:return p=e.sent,e.next=23,h.setLocalDescription(p);case 23:return e.next=25,m.setRemoteDescription(p);case 25:return e.next=27,m.createAnswer();case 27:return f=e.sent,v=Tk(f.sdp),g=v.media[0].rtp.findIndex((function(e){return"H264"===e.codec})),v.media[0].rtp=[v.media[0].rtp[g]],v.media[0].fmtp=v.media[0].fmtp.filter((function(e){return e.payload===v.media[0].rtp[0].payload})),v.media[0].rtcpFb=v.media[0].rtcpFb.filter((function(e){return e.payload===v.media[0].rtp[0].payload})),f.sdp=Ik(v),e.next=36,m.setLocalDescription(f);case 36:return e.next=38,h.setRemoteDescription(f);case 38:u=setInterval(o(r().mark((function e(){var s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i.encode&&i.decode&&(n(),t(i)),e.next=3,h.getStats();case 3:return s=e.sent,e.next=6,m.getStats();case 6:o=e.sent,i.encode||s.forEach((function(e){"outbound-rtp"===e.type&&e.mediaType===RT&&e.framesEncoded>0&&(i.encode=!0)})),i.decode||o.forEach((function(e){"inbound-rtp"===e.type&&e.mediaType===RT&&e.framesDecoded>0&&(i.decode=!0)}));case 9:case"end":return e.stop()}}),e)}))),500),e.next=46;break;case 41:e.prev=41,e.t0=e.catch(2),n(),Mw.warn(e.t0),t(i);case 46:case"end":return e.stop()}}),e,null,[[2,41]])})));return function(t){return e.apply(this,arguments)}}()));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var oA=function(){var e=o(r().mark((function e(){var t,i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Xk.detail.isH264DecodeSupported||!Xk.detail.isVp8DecodeSupported){e.next=2;break}return e.abrupt("return",{isH264DecodeSupported:Xk.detail.isH264DecodeSupported,isVp8DecodeSupported:Xk.detail.isVp8DecodeSupported});case 2:return t="",i=!1,n=!1,e.prev=5,s=new RTCPeerConnection,e.next=9,s.createOffer({offerToReceiveAudio:1,offerToReceiveVideo:1});case 9:return-1!==(t=e.sent).sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(n=!0),s.close(),e.abrupt("return",{isH264DecodeSupported:i,isVp8DecodeSupported:n});case 16:return e.prev=16,e.t0=e.catch(5),e.abrupt("return",{isH264DecodeSupported:!1,isVp8DecodeSupported:!1});case 19:case"end":return e.stop()}}),e,null,[[5,16]])})));return function(){return e.apply(this,arguments)}}(),aA=function(e,t){var i=null;return function(){if(i)return i;for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(i=e.apply(this,r)).then((function(e){return i=null,e})).catch((function(e){throw i=null,e})),i}}(function(){var e=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l,h,m,p;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(cA()){e.next=2;break}return e.abrupt("return",Xk);case 2:return t=eA(),i=tA(),n=iA(),e.next=7,rA();case 7:return s=e.sent,o=s.isH264EncodeSupported,a=s.isVp8EncodeSupported,e.next=12,oA();case 12:if(c=e.sent,u=c.isH264DecodeSupported,d=c.isVp8DecodeSupported,o&&a){e.next=21;break}return e.next=18,rA();case 18:l=e.sent,o=l.isH264EncodeSupported,a=l.isVp8EncodeSupported;case 21:if(!(o&&u&&(nT||oT||fT)&&!Mb&&cT()<79)){e.next=29;break}return e.next=24,nA();case 24:h=e.sent,m=h.encode,p=h.decode,o=m,u=p;case 29:return Xk.result=t&&i&&n&&(o||a)&&(u||d),Xk.detail.isBrowserSupported=t,Xk.detail.isWebRTCSupported=i,Xk.detail.isMediaDevicesSupported=n,Xk.detail.isH264EncodeSupported=o,Xk.detail.isVp8EncodeSupported=a,Xk.detail.isH264DecodeSupported=u,Xk.detail.isVp8DecodeSupported=d,cA()&&(Mw.warn(GC({key:DC})),Mw.info("".concat(navigator.userAgent," ").concat(JSON.stringify(Xk.detail)))),Kk.setItem(Zk,{ua:navigator.userAgent,checkResult:Xk},!0),e.abrupt("return",Xk);case 40:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}());function cA(){return Object.keys(Xk.detail).findIndex((function(e){return!Xk.detail[e]}))>=0}function uA(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)}function dA(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function lA(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function hA(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function mA(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function pA(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&lA()}function fA(){return!!ew(navigator.mediaDevices)&&(Mw.error(HC.NOT_SUPPORTED_MEDIA),!0)}function vA(){return"http:"===location.protocol&&!ST&&(Mw.warn(GC({key:NC})),!0)}var gA="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&cT()>=86;function _A(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state||rw(e.selected)&&!e.selected)}var yA=new Map([[yb,"Android"],[_b,"iOS"],[Gb,"Windows"],[qb,"MacOS"],[Jb,"Linux"]]);function SA(){var e="unknown";return yA.get(!0)&&(e=yA.get(!0)),e}function EA(){var e="";return screen.width&&(e+=(screen.width?screen.width*window.devicePixelRatio:"")+" * "+(screen.height?screen.height*window.devicePixelRatio:"")),e}function bA(){var e=!1;return(navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)&&(e=!0),e}function TA(){for(var e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"],i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function IA(){return!Nb&&!_b&&!(!eA()||!("captureStream"in HTMLCanvasElement.prototype))}var CA=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,wA=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,RA=function(){var e,t,i;return(null===(e=window)||void 0===e?void 0:e.OffscreenCanvas)&&(null===(t=window)||void 0===t?void 0:t.MediaStreamTrackProcessor)&&(null===(i=window)||void 0===i?void 0:i.MediaStreamTrackGenerator)};!function(){vA();var e=Kk.getItem(Zk);e&&e.ua===navigator.userAgent&&(Xk=e.checkResult),aA()}();var kA,AA="stream-added",MA="stream-removed",OA="stream-updated",LA="stream-subscribed",PA="error",NA="connection-state-changed",DA=jT,xA="stream-added",UA="peer-join",$A="mute-audio",BA="mute-video",VA="unmute-audio",FA="unmute-video",jA="network-quality",HA="audio-volume",WA="error",GA="player-state-changed",qA="error",JA="player-state-changed",zA=function(){function e(t){a(this,e);var i=t.getUserId();this.log_=Mw.createLogger({id:i,userId:i,sdkAppId:t.getSDKAppId()}),this.prevReportTime_=0,this.prevReport_={},this.prevEncoderImplementation_="",this.prevQualityLimitationReason_="",this.prevDecoderImplementationMap_=new Map}var t,i,n,s;return u(e,[{key:"statInterval",get:function(){return 0===this.prevReportTime_?2:(Date.now()-this.prevReportTime_)/1e3}},{key:"getSenderStats",value:(s=o(r().mark((function e(t){var i,n,s,o=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0,smallFramesEncoded:0,smallFPSCapture:0,smallFramesSent:0},rtt:0},n=t.getPeerConnection(),s=t.getSSRC(),!n){e.next=14;break}return e.prev=4,e.next=7,n.getStats();case 7:e.sent.forEach((function(e){if("outbound-rtp"===e.type)if(e.mediaType===RT){if(!Sb&&ew(e.trackId))return;e.ssrc!==s.video||ew(e.encoderImplementation)||o.prevEncoderImplementation_===e.encoderImplementation||(o.log_.info("encoderImplementation change to ".concat(e.encoderImplementation)),o.prevEncoderImplementation_=e.encoderImplementation),e.ssrc!==s.video||ew(e.qualityLimitationReason)||o.prevQualityLimitationReason_===e.qualityLimitationReason||(o.log_.info("qualityLimitationReason change to ".concat(e.qualityLimitationReason)),o.prevQualityLimitationReason_=e.qualityLimitationReason);var r=t.getSSRC();e.ssrc===r.video?(i.video.bytesSent=e.bytesSent,i.video.packetsSent=e.packetsSent,i.video.framesEncoded=e.framesEncoded):(i.video.smallBytesSent=e.bytesSent,i.video.smallFramesEncoded=e.framesEncoded)}else e.mediaType===wT&&(i.audio.bytesSent=e.bytesSent,i.audio.packetsSent=e.packetsSent);else if("candidate-pair"===e.type)_A(e)&&iw(e.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*e.currentRoundTripTime));else if("track"===e.type){var n;ew(e.frameWidth)||(e.trackIdentifier===t.getLocalStreamVideoTrackId()?(i.video.frameWidth=e.frameWidth,i.video.frameHeight=e.frameHeight,i.video.framesSent=e.framesSent):(i.video.smallFrameWidth=e.frameWidth,i.video.smallFrameHeight=e.frameHeight,i.video.smallFramesSent=e.framesSent)),ew(e.audioLevel)?mT&&(i.audio.audioLevel=(null===(n=t.getLocalStream())||void 0===n?void 0:n.getInternalAudioLevel())||0):i.audio.audioLevel=e.audioLevel||0}else"media-source"===e.type&&(e.kind===wT?(i.audio.audioLevel=e.audioLevel||0,i.audio.totalAudioEnergy=e.totalAudioEnergy||0):e.kind===RT&&(e.trackIdentifier===t.getLocalStreamVideoTrackId()?i.video.fpsCapture=e.framesPerSecond:i.video.smallFPSCapture=e.framesPerSecond))})),e.next=14;break;case 11:e.prev=11,e.t0=e.catch(4),this.log_.warn("failed to getStats on sender connection "+e.t0);case 14:return e.abrupt("return",i);case 15:case"end":return e.stop()}}),e,this,[[4,11]])}))),function(e){return s.apply(this,arguments)})},{key:"getReceiverStats",value:(n=o(r().mark((function e(t){var i,n,s=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i={tinyId:t.getTinyId(),userId:t.getUserId(),rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0}},!(n=t.getPeerConnection())){e.next=13;break}return e.prev=3,e.next=6,n.getStats();case 6:e.sent.forEach((function(e){if("inbound-rtp"===e.type){if(e.mediaType===wT)i.audio.packetsReceived=e.packetsReceived,i.audio.bytesReceived=e.bytesReceived,i.audio.packetsLost=e.packetsLost,i.audio.jitter=e.jitter,i.hasAudio=!0;else if(e.mediaType===RT){if(Sb&&0===e.bytesReceived)return;var r=t.getSSRC();e.ssrc===r.video&&(i.video.packetsReceived=e.packetsReceived,i.video.bytesReceived=e.bytesReceived,i.video.packetsLost=e.packetsLost,i.video.framesReceived=e.framesReceived,i.video.framesDecoded=e.framesDecoded,i.video.fpsDecoded=e.framesPerSecond,i.hasVideo=!0,!e.decoderImplementation||s.prevDecoderImplementationMap_.has(i.userId)&&s.prevDecoderImplementationMap_.get(i.userId)===e.decoderImplementation||(s.log_.info("".concat(i.userId," decoderImplementation change to ").concat(e.decoderImplementation)),s.prevDecoderImplementationMap_.set(i.userId,e.decoderImplementation))),e.ssrc===r.auxiliary&&(i.auxiliary.packetsReceived=e.packetsReceived,i.auxiliary.bytesReceived=e.bytesReceived,i.auxiliary.packetsLost=e.packetsLost,i.auxiliary.framesReceived=e.framesReceived,i.auxiliary.framesDecoded=e.framesDecoded,i.auxiliary.fpsDecoded=e.framesPerSecond,i.hasAuxiliary=!0)}}else"track"===e.type?(ew(e.frameWidth)||(e.trackIdentifier===t.getMainStreamVideoTrackId()&&(i.video.frameWidth=e.frameWidth,i.video.frameHeight=e.frameHeight),e.trackIdentifier===t.getAuxStreamVideoTrackId()&&(i.auxiliary.frameWidth=e.frameWidth,i.auxiliary.frameHeight=e.frameHeight)),ew(e.audioLevel)||(i.audio.audioLevel=e.audioLevel||0,i.audio.totalAudioEnergy=e.totalAudioEnergy||0)):"candidate-pair"===e.type&&_A(e)&&iw(e.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*e.currentRoundTripTime))})),e.next=13;break;case 10:e.prev=10,e.t0=e.catch(3),this.log_.warn("failed to getStats on receiver connection "+e.t0);case 13:return e.abrupt("return",i);case 14:case"end":return e.stop()}}),e,this,[[3,10]])}))),function(e){return n.apply(this,arguments)})},{key:"getStats",value:(i=o(r().mark((function e(t,i){var n,s,o,a,c,u,d;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n={},!t){e.next=5;break}return e.next=4,this.getSenderStats(t);case 4:n=e.sent;case 5:s=[],o=C(i),e.prev=7,o.s();case 9:if((a=o.n()).done){e.next=17;break}return(c=E(a.value,2))[0],u=c[1],e.next=13,this.getReceiverStats(u);case 13:d=e.sent,s.push(d);case 15:e.next=9;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(7),o.e(e.t0);case 22:return e.prev=22,o.f(),e.finish(22);case 25:return e.abrupt("return",{senderStats:n,receiverStats:s});case 26:case"end":return e.stop()}}),e,this,[[7,19,22,25]])}))),function(e,t){return i.apply(this,arguments)})},{key:"getDifferenceValue",value:function(e,t){if(sk(e))return t;var i=t-e;return i<0?0:i}},{key:"prepareReport",value:function(e){var t=this,i=e.stats,r=e.report,n=e.freezeMap;if(!sk(i.senderStats)){var s={uint32_audio_level:1e8*i.senderStats.audio.audioLevel,uint32_audio_energy:1e6*i.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent,audioLevel:i.senderStats.audio.audioLevel},o=[],a={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded};if(o.push(a),i.senderStats.video.smallBytesSent){var c={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.video.smallFramesSent||0,uint32_video_capture_fps:i.senderStats.video.smallFPSCapture||0,uint32_video_width:i.senderStats.video.smallFrameWidth||0,uint32_video_height:i.senderStats.video.smallFrameHeight||0,uint32_video_codec_bitrate:i.senderStats.video.smallBytesSent,uint32_video_enc_fps:i.senderStats.video.smallFramesEncoded||0};o.push(c)}var u={uint32_bitrate:"",uint32_rtt:i.senderStats.rtt};r.msg_up_stream_info={msg_audio_status:s,msg_video_status:o,msg_network_status:u}}var d=this.statInterval;r.msg_down_stream_info=[],i.receiverStats.forEach((function(e){var t={};if(t.msg_user_info={str_identifier:e.userId,uint64_tinyid:e.tinyId},t.msg_network_status={uint32_rtt:e.rtt},t.msg_video_status={},e.hasAudio){var i={uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost,audioLevel:e.audio.audioLevel};t.msg_audio_status=i}if(t.msg_video_status=[],e.hasVideo){var s=n.get(e.userId+"_"+eI),o=s?s.duration:0,a={uint32_video_stream_type:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:o,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(a)}if(e.hasAuxiliary){var c=n.get(e.userId+"_"+tI),u=c?c.duration:0,d={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:u,uint32_video_dec_fps:e.auxiliary.framesDecoded};t.msg_video_status.push(d)}r.msg_down_stream_info.push(t)}));var l=this.prevReport_;this.prevReport_=JSON.parse(JSON.stringify(r));var h=l.msg_up_stream_info.msg_audio_status,m=r.msg_up_stream_info.msg_audio_status,p=this.getDifferenceValue(h.uint32_audio_codec_bitrate,m.uint32_audio_codec_bitrate);m.uint32_audio_codec_bitrate=Math.round(8*p/d);var f=l.msg_up_stream_info.msg_video_status;r.msg_up_stream_info.msg_video_status.forEach((function(e,i){var r=f[i],n=0,s=0,o=0;r&&(n=r.uint32_video_codec_bitrate,s=r.uint32_video_enc_fps,o=r.uint32_video_codec_fps);var a=t.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/d),e.uint32_video_enc_fps=Math.round(t.getDifferenceValue(s,e.uint32_video_enc_fps)/d),e.uint32_video_codec_fps=Math.round(t.getDifferenceValue(o,e.uint32_video_codec_fps)/d)}));var v=r.msg_down_stream_info,g=l.msg_down_stream_info;return v.forEach((function(e){var i=g.find((function(t){return t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid}));if(i){if(e.msg_audio_status&&i.msg_audio_status){var r=e.msg_audio_status,n=i.msg_audio_status;r.uint32_audio_origin_lost=t.getDifferenceValue(n.uint32_audio_origin_lost,r.uint32_audio_origin_lost),r.uint32_audio_receive=t.getDifferenceValue(n.uint32_audio_receive,r.uint32_audio_receive),r.uint32_audio_receive+=r.uint32_audio_origin_lost;var s=t.getDifferenceValue(n.uint32_audio_codec_bitrate,r.uint32_audio_codec_bitrate);r.uint32_audio_codec_bitrate=Math.round(8*s/d),r.uint32_audio_total_bitrate=Math.round(8*s/d)}if(e.msg_video_status&&i.msg_video_status){var o=e.msg_video_status,a=i.msg_video_status;o.forEach((function(e,i){var r=a[i],n=0,s=0,o=0,c=0,u=0;r&&(n=r.uint32_video_receive,s=r.uint32_video_origin_lost,o=r.uint32_video_codec_bitrate,c=r.uint32_video_receive_fps,u=r.uint32_video_dec_fps),e.uint32_video_origin_lost=t.getDifferenceValue(s,e.uint32_video_origin_lost),e.uint32_video_receive=t.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;var l=t.getDifferenceValue(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/d);var h=t.getDifferenceValue(c,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(h/d),e.uint32_video_dec_fps=Math.round(t.getDifferenceValue(u,e.uint32_video_dec_fps)/d)}))}}})),r.msg_up_stream_info.msg_network_status.uint32_bitrate=r.msg_up_stream_info.msg_audio_status.uint32_audio_codec_bitrate+r.msg_up_stream_info.msg_video_status[0].uint32_video_codec_bitrate,r}},{key:"getStatsReport",value:(t=o(r().mark((function e(t){var i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=t.uplinkConnection,n=t.downlinkConnections,s=t.freezeMap,o={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,audioLevel:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_codec_fps:0,uint32_video_capture_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_final_lost:0,uint32_video_enc_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0},msg_qos:[{uint32_video_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_bitrate:0,uint32_audio_bitrate:0,uint32_video_stream_type:0}]},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:""},msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0,audioLevel:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0,uint32_jitter:0},msg_qos:[{uint32_video_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_bitrate:0,uint32_audio_bitrate:0,uint32_video_stream_type:0}]}]},e.next=4,this.getStats(i,n);case 4:return a=e.sent,"{}"===JSON.stringify(this.prevReport_)&&(this.prevReport_=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:a,report:o,freezeMap:s}),this.prevReportTime_=Date.now(),e.abrupt("return",o);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"reset",value:function(){this.prevReportTime_=0,this.prevReport_={},this.prevEncoderImplementation_="",this.prevQualityLimitationReason_="",this.prevDecoderImplementationMap_=new Map}}]),e}(),YA=function(){function e(t){var i=t.signalChannel,r=t.connections,n=t.client;a(this,e),this.client_=n,this.signalChannel_=i,this.connections_=r,this.client_=n,this.log_=Mw.createLogger({id:"q|"+this.client_.getUserId(),userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId()}),this.uplinkConnection_=null,this.uplinkNetworkQuality_=0,this.uplinkRTT_=0,this.uplinkLoss_=0,this.downlinkNetworkQuality_=0,this.downlinkRTT_=0,this.downlinkLoss_=0,this.downlinkPrevStatMap_=new Map,this.downlinkLossAndRTTMap_=new Map,this.interval_=-1,this.emitter_=new bw,this.initialize()}var t,i;return u(e,[{key:"uplinkNetworkQuality",get:function(){return this.uplinkNetworkQuality_},set:function(e){e!==this.uplinkNetworkQuality_&&this.log_.info("uplink network quality change ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT_,", loss: ").concat(this.uplinkLoss_)),this.uplinkNetworkQuality_=e}},{key:"downlinkNetworkQuality",get:function(){return this.downlinkNetworkQuality_},set:function(e){if(e!==this.downlinkNetworkQuality_){var t=this.getAverageLossAndRTT(b(this.downlinkLossAndRTTMap_.values())),i=t.rtt,r=t.loss;this.log_.info("downlink network quality change ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(i,", loss: ").concat(r))}this.downlinkNetworkQuality_=e}},{key:"initialize",value:function(){var e=this;this.signalChannel_.on(KR.UPLINK_NETWORK_STATS,(function(t){e.handleUplinkNetworkQuality(t)})),this.signalChannel_.on(2,this.handleSignalConnectionStateChange.bind(this)),this.start()}},{key:"handleUplinkNetworkQuality",value:function(e){if(!this.uplinkConnection_)return this.uplinkNetworkQuality=0,this.uplinkLoss_=0,void(this.uplinkRTT_=0);var t=this.uplinkConnection_.getPeerConnection();if(t&&this.isPeerConnectionDisconnected(t))return this.uplinkNetworkQuality=6,this.uplinkLoss_=0,void(this.uplinkRTT_=0);if(0===e.data.code){var i=e.data.data,r=i.expectAudPkg+i.expectVidPkg,n=i.recvAudPkg+i.recvVidPkg,s=r-n,o=i.delay;if(o&&this.updateDelay(o),0===r&&0===n)return;this.uplinkLoss_=s<=0?0:Math.round(s/r*100),this.uplinkRTT_=i.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss_,this.uplinkRTT_)}}},{key:"handleDownlinkNetworkQuality",value:(i=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l,h,m,p,f,v,g=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.connections_&&0!==this.connections_.size){e.next=3;break}return this.downlinkNetworkQuality=0,e.abrupt("return");case 3:if(t=b(this.connections_.values()),i=t.filter((function(e){return e.getPeerConnection()&&e.getPeerConnection().connectionState===uI})),t.filter((function(e){return e.getPeerConnection()&&g.isPeerConnectionDisconnected(e.getPeerConnection())})).length!==t.length){e.next=9;break}return this.downlinkNetworkQuality=6,e.abrupt("return");case 9:n=0;case 10:if(!(n<i.length)){e.next=31;break}return s=i[n].getPeerConnection(),e.next=14,this.getStat(s);case 14:if(o=e.sent,a=o.rtt,c=o.totalPacketsLost,u=o.totalPacketsReceived,this.downlinkPrevStatMap_.has(s)){e.next=21;break}return this.downlinkPrevStatMap_.set(s,{totalPacketsLost:c,totalPacketsReceived:u}),e.abrupt("continue",28);case 21:l=this.downlinkPrevStatMap_.get(s),h=c-l.totalPacketsLost,m=u-l.totalPacketsReceived,d=h<=0||m<0?0:Math.round(h/(h+m)*100),this.downlinkPrevStatMap_.set(s,{totalPacketsLost:c,totalPacketsReceived:u}),this.downlinkLossAndRTTMap_.set(s,{rtt:a,loss:d,userId:i[n].getUserId()});case 28:n++,e.next=10;break;case 31:if(b(this.downlinkPrevStatMap_.keys()).forEach((function(e){g.isPeerConnectionDisconnected(e)&&(g.downlinkPrevStatMap_.delete(e),g.downlinkLossAndRTTMap_.delete(e))})),0!==this.downlinkLossAndRTTMap_.size){e.next=34;break}return e.abrupt("return");case 34:p=this.getAverageLossAndRTT(b(this.downlinkLossAndRTTMap_.values())),f=p.rtt,v=p.loss,this.downlinkRTT_=f,this.downlinkLoss_=v,this.downlinkNetworkQuality=this.getNetworkQuality(v,f);case 38:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"getStat",value:(t=o(r().mark((function e(t){var i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i={rtt:0,totalPacketsLost:0,totalPacketsReceived:0},t&&dA()){e.next=3;break}return e.abrupt("return",i);case 3:n=t.getReceivers(),e.prev=4,s=0;case 6:if(!(s<n.length)){e.next=15;break}return o=n[s],e.next=10,o.getStats();case 10:e.sent.forEach((function(e){"candidate-pair"===e.type&&iw(e.currentRoundTripTime)&&(i.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"!==e.type||e.mediaType!==wT&&e.mediaType!==RT||(i.totalPacketsLost+=e.packetsLost,i.totalPacketsReceived+=e.packetsReceived)}));case 12:s++,e.next=6;break;case 15:return e.abrupt("return",i);case 18:return e.prev=18,e.t0=e.catch(4),e.abrupt("return",i);case 21:case"end":return e.stop()}}),e,null,[[4,18]])}))),function(e){return t.apply(this,arguments)})},{key:"getAverageLossAndRTT",value:function(e){var t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((function(e){t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((function(i){t[i]=Math.round(t[i]/e.length)}))),t}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}},{key:"handleSignalConnectionStateChange",value:function(e){e.state===GR?(this.uplinkRTT_=0,this.uplinkLoss_=0,this.uplinkNetworkQuality=6):e.state===zR&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}},{key:"handleUplinkConnectionStateChange",value:function(e){var t=e.state;t===rI?(this.uplinkLoss_=0,this.uplinkRTT_=0,this.uplinkNetworkQuality=6):t===oI&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}},{key:"isPeerConnectionDisconnected",value:function(e){return!(!e||"disconnected"!==e.connectionState&&"failed"!==e.connectionState&&e.connectionState!==cI)}},{key:"setUplinkConnection",value:function(e){this.uplinkConnection_=e,this.uplinkConnection_?this.uplinkConnection_.on(NA,this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT_=0,this.uplinkLoss_=0)}},{key:"start",value:function(){var e=this;-1===this.interval_?(this.log_.info("start network quality calculating"),this.interval_=Qk.run(cC,(function(){e.handleDownlinkNetworkQuality(),Tw.emit(300,{client:e.client_,uplinkNetworkQuality:e.uplinkNetworkQuality,downlinkNetworkQuality:e.downlinkNetworkQuality,uplinkRTT:e.uplinkRTT_,uplinkLoss:e.uplinkLoss_,downlinkRTT:e.downlinkRTT_,downlinkLoss:e.downlinkLoss_,downlinkLossAndRTTMap:e.downlinkLossAndRTTMap_}),e.emitter_.emit(jA,{uplinkNetworkQuality:e.uplinkNetworkQuality,downlinkNetworkQuality:e.downlinkNetworkQuality,uplinkRTT:e.uplinkRTT_,uplinkLoss:e.uplinkLoss_,downlinkRTT:e.downlinkRTT_,downlinkLoss:e.downlinkLoss_})}),{delay:2e3})):this.log_.info("network quality calculating is already started")}},{key:"stop",value:function(){this.log_.info("stop network quality calculating"),-1!==this.interval_&&(Qk.clearTask(this.interval_),this.interval_=-1),this.downlinkLossAndRTTMap_.clear(),this.downlinkPrevStatMap_.clear()}},{key:"on",value:function(e,t){this.emitter_.on(e,t)}},{key:"updateDelay",value:function(e){var t=this;e.forEach((function(e){var i=e.srcTinyId,r=e.videoDelay,n=e.audioDelay,s=t.connections_.get(i);s&&s.setDelay({videoDelay:r,audioDelay:n})}))}}]),e}(),QA=function(){function e(t){a(this,e),this.log_=Mw.createLogger({id:t.client.getUserId(),userId:t.client.getUserId(),sdkAppId:t.client.getSDKAppId()}),this.localStream_=null,this.prevDevices_=[],this.initialize()}var t,i;return u(e,[{key:"initialize",value:function(){navigator.mediaDevices&&(this.onDeviceChange=this.onDeviceChange.bind(this),navigator.mediaDevices.addEventListener("devicechange",this.onDeviceChange))}},{key:"destroy",value:function(){navigator.mediaDevices&&navigator.mediaDevices.removeEventListener("devicechange",this.onDeviceChange)}},{key:"onDeviceChange",value:(i=o(r().mark((function e(){var t,i,n,s=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localStream_&&this.localStream_.getMediaStream()&&!this.localStream_.getScreen()){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,VF.getDevices();case 4:t=e.sent,i=t.filter((function(e){return s.prevDevices_.findIndex((function(t){var i=t.deviceId;return e.deviceId===i}))<0})),n=this.prevDevices_.filter((function(e){return t.findIndex((function(t){var i=t.deviceId;return e.deviceId===i}))<0})),i.length>0&&this.handleDeviceAdded(this.prevDevices_,i),n.length>0&&this.handleDeviceRemoved(t,n),this.prevDevices_=t;case 10:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"setLocalStream",value:(t=o(r().mark((function e(t){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t){e.next=4;break}return e.next=3,VF.getDevices();case 3:this.prevDevices_=e.sent;case 4:this.localStream_=t;case 5:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"handleDeviceAdded",value:function(e,t){var i,r;this.log_.warn("devicesAdded: ".concat(JSON.stringify(t))),this.localStream_.updateDeviceIdInUse();var n=t.filter((function(e){return e.kind===BT})),s=t.filter((function(e){return e.kind===$T})),o=e.filter((function(e){return e.kind===BT})),a=e.filter((function(e){return e.kind===$T})),c=n.length>0&&0===o.length&&"live"!==(null===(i=this.localStream_.getVideoTrack())||void 0===i?void 0:i.readyState),u=s.length>0&&0===a.length&&"live"!==(null===(r=this.localStream_.getAudioTrack())||void 0===r?void 0:r.readyState);if(u&&c)return this.log_.info("new microphone and camera detected, but there was no device before."),void this.localStream_.recoverCapture({audio:!0,video:!0,cameraId:n[0].deviceId,microphoneId:s[0].deviceId});c&&(this.log_.info("new camera detected, but there was no camera before."),this.localStream_.recoverCapture({audio:!1,video:!0,cameraId:n[0].deviceId})),u&&(this.log_.info("new microphone detected, but there was no microphone before."),this.localStream_.recoverCapture({audio:!0,video:!1,microphoneId:s[0].deviceId}))}},{key:"handleDeviceRemoved",value:function(e,t){this.log_.warn("devicesRemoved: ".concat(JSON.stringify(t))),this.localStream_.updateDeviceIdInUse();var i=!1,r=!1,n=this.localStream_.getCameraId(),s=this.localStream_.getMicrophoneId();if(s===rC){var o=this.localStream_.getMicrophoneGroupId(),a=e.filter((function(e){return e.deviceId===rC&&e.kind===$T}))[0];a&&a.groupId!==o&&(r=!0)}if(t.forEach((function(e){var t=e.deviceId;n.length>0&&t===n?i=!0:s.length>0&&t===s&&(r=!0)})),i&&r)return this.log_.warn("current camera and microphone in use is lost, cameraId: ".concat(n,", microphoneId: ").concat(s)),void((this.localStream_.getAudio()||this.localStream_.getVideo())&&this.localStream_.recoverCapture({video:!0,audio:!0}));i&&(this.log_.warn("current camera in use is lost, deviceId: ".concat(n)),this.localStream_.getVideo()&&this.localStream_.recoverCapture({video:!0,audio:!1})),r&&(this.log_.warn("current microphone in use is lost, deviceId: ".concat(s)),this.localStream_.getAudio()&&this.localStream_.recoverCapture({video:!1,audio:!0}))}}]),e}(),KA=Si.exports,XA=ri,ZA=ci,eM=Uu,tM=Cn,iM=x,rM=ht,nM=function(e,t,i,r){try{return r?t(ZA(i)[0],i[1]):t(i)}catch(t){eM(e,"throw",t)}},sM=Su,oM=Qn,aM=Lr,cM=xc,uM=Pu,dM=wu,lM=Array,hM=te,mM=2147483647,pM=/[^\0-\u007E]/,fM=/[.\u3002\uFF0E\uFF61]/g,vM="Overflow: input needs wider integers to process",gM=RangeError,_M=hM(fM.exec),yM=Math.floor,SM=String.fromCharCode,EM=hM("".charCodeAt),bM=hM([].join),TM=hM([].push),IM=hM("".replace),CM=hM("".split),wM=hM("".toLowerCase),RM=function(e){return e+22+75*(e<26)},kM=function(e,t,i){var r=0;for(e=i?yM(e/700):e>>1,e+=yM(e/t);e>455;)e=yM(e/35),r+=36;return yM(r+36*e/(e+38))},AM=function(e){var t,i,r=[],n=(e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=EM(e,i++);if(n>=55296&&n<=56319&&i<r){var s=EM(e,i++);56320==(64512&s)?TM(t,((1023&n)<<10)+(1023&s)+65536):(TM(t,n),i--)}else TM(t,n)}return t}(e)).length,s=128,o=0,a=72;for(t=0;t<e.length;t++)(i=e[t])<128&&TM(r,SM(i));var c=r.length,u=c;for(c&&TM(r,"-");u<n;){var d=mM;for(t=0;t<e.length;t++)(i=e[t])>=s&&i<d&&(d=i);var l=u+1;if(d-s>yM((mM-o)/l))throw gM(vM);for(o+=(d-s)*l,s=d,t=0;t<e.length;t++){if((i=e[t])<s&&++o>mM)throw gM(vM);if(i==s){for(var h=o,m=36;;){var p=m<=a?1:m>=a+26?26:m-a;if(h<p)break;var f=h-p,v=36-p;TM(r,SM(RM(p+f%v))),h=yM(f/v),m+=36}TM(r,SM(RM(h))),a=kM(o,l,u==c),o=0,u++}}o++,s++}return bM(r,"")},MM=En,OM=L,LM=ff,PM=A,NM=Cn,DM=te,xM=_r,UM=function(e,t,i){return i.get&&KA(i.get,t,{getter:!0}),i.set&&KA(i.set,t,{setter:!0}),XA.f(e,t,i)},$M=ed,BM=ft,VM=lR,FM=function(e){var t=rM(e),i=oM(this),r=arguments.length,n=r>1?arguments[1]:void 0,s=void 0!==n;s&&(n=tM(n,r>2?arguments[2]:void 0));var o,a,c,u,d,l,h=dM(t),m=0;if(!h||this===lM&&sM(h))for(o=aM(t),a=i?new this(o):lM(o);o>m;m++)l=s?n(t[m],m):t[m],cM(a,m,l);else for(d=(u=uM(t,h)).next,a=i?new this:[];!(c=iM(d,u)).done;m++)l=s?nM(u,n,[c.value,m],!0):c.value,cM(a,m,l);return a.length=m,a},jM=jc,HM=sl.codeAt,WM=Qd,GM=$a,qM=xl,JM=Dv,zM=tr,YM=zM.set,QM=zM.getterFor("URL"),KM=JM.URLSearchParams,XM=JM.getState,ZM=PM.URL,eO=PM.TypeError,tO=PM.parseInt,iO=Math.floor,rO=Math.pow,nO=DM("".charAt),sO=DM(/./.exec),oO=DM([].join),aO=DM(1..toString),cO=DM([].pop),uO=DM([].push),dO=DM("".replace),lO=DM([].shift),hO=DM("".split),mO=DM("".slice),pO=DM("".toLowerCase),fO=DM([].unshift),vO="Invalid scheme",gO="Invalid host",_O="Invalid port",yO=/[a-z]/i,SO=/[\d+-.a-z]/i,EO=/\d/,bO=/^0x/i,TO=/^[0-7]+$/,IO=/^\d+$/,CO=/^[\da-f]+$/i,wO=/[\0\t\n\r #%/:<>?@[\\\]^|]/,RO=/[\0\t\n\r #/:<>?@[\\\]^|]/,kO=/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,AO=/[\t\n\r]/g,MO=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)fO(t,e%256),e=iO(e/256);return oO(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,s=0;s<8;s++)0!==e[s]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=s),++n);return n>i&&(t=r,i=n),t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=aO(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},OO={},LO=VM({},OO,{" ":1,'"':1,"<":1,">":1,"`":1}),PO=VM({},LO,{"#":1,"?":1,"{":1,"}":1}),NO=VM({},PO,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),DO=function(e,t){var i=HM(e,0);return i>32&&i<127&&!BM(t,e)?e:encodeURIComponent(e)},xO={ftp:21,file:null,http:80,https:443,ws:80,wss:443},UO=function(e,t){var i;return 2==e.length&&sO(yO,nO(e,0))&&(":"==(i=nO(e,1))||!t&&"|"==i)},$O=function(e){var t;return e.length>1&&UO(mO(e,0,2))&&(2==e.length||"/"===(t=nO(e,2))||"\\"===t||"?"===t||"#"===t)},BO=function(e){return"."===e||"%2e"===pO(e)},VO={},FO={},jO={},HO={},WO={},GO={},qO={},JO={},zO={},YO={},QO={},KO={},XO={},ZO={},eL={},tL={},iL={},rL={},nL={},sL={},oL={},aL=function(e,t,i){var r,n,s,o=WM(e);if(t){if(n=this.parse(o))throw eO(n);this.searchParams=null}else{if(void 0!==i&&(r=new aL(i,!0)),n=this.parse(o,null,r))throw eO(n);(s=XM(new KM)).bindURL(this),this.searchParams=s}};aL.prototype={type:"URL",parse:function(e,t,i){var r,n,s,o,a,c=this,u=t||VO,d=0,l="",h=!1,m=!1,p=!1;for(e=WM(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=dO(e,kO,"")),e=dO(e,AO,""),r=FM(e);d<=r.length;){switch(n=r[d],u){case VO:if(!n||!sO(yO,n)){if(t)return vO;u=jO;continue}l+=pO(n),u=FO;break;case FO:if(n&&(sO(SO,n)||"+"==n||"-"==n||"."==n))l+=pO(n);else{if(":"!=n){if(t)return vO;l="",u=jO,d=0;continue}if(t&&(c.isSpecial()!=BM(xO,l)||"file"==l&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=l,t)return void(c.isSpecial()&&xO[c.scheme]==c.port&&(c.port=null));l="","file"==c.scheme?u=ZO:c.isSpecial()&&i&&i.scheme==c.scheme?u=HO:c.isSpecial()?u=JO:"/"==r[d+1]?(u=WO,d++):(c.cannotBeABaseURL=!0,uO(c.path,""),u=nL)}break;case jO:if(!i||i.cannotBeABaseURL&&"#"!=n)return vO;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=jM(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,u=oL;break}u="file"==i.scheme?ZO:GO;continue;case HO:if("/"!=n||"/"!=r[d+1]){u=GO;continue}u=zO,d++;break;case WO:if("/"==n){u=YO;break}u=rL;continue;case GO:if(c.scheme=i.scheme,n==kA)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=jM(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())u=qO;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=jM(i.path),c.query="",u=sL;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=jM(i.path),c.path.length--,u=rL;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=jM(i.path),c.query=i.query,c.fragment="",u=oL}break;case qO:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,u=rL;continue}u=YO}else u=zO;break;case JO:if(u=zO,"/"!=n||"/"!=nO(l,d+1))continue;d++;break;case zO:if("/"!=n&&"\\"!=n){u=YO;continue}break;case YO:if("@"==n){h&&(l="%40"+l),h=!0,s=FM(l);for(var f=0;f<s.length;f++){var v=s[f];if(":"!=v||p){var g=DO(v,NO);p?c.password+=g:c.username+=g}else p=!0}l=""}else if(n==kA||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==l)return"Invalid authority";d-=FM(l).length+1,l="",u=QO}else l+=n;break;case QO:case KO:if(t&&"file"==c.scheme){u=tL;continue}if(":"!=n||m){if(n==kA||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==l)return gO;if(t&&""==l&&(c.includesCredentials()||null!==c.port))return;if(o=c.parseHost(l))return o;if(l="",u=iL,t)return;continue}"["==n?m=!0:"]"==n&&(m=!1),l+=n}else{if(""==l)return gO;if(o=c.parseHost(l))return o;if(l="",u=XO,t==KO)return}break;case XO:if(!sO(EO,n)){if(n==kA||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=l){var _=tO(l,10);if(_>65535)return _O;c.port=c.isSpecial()&&_===xO[c.scheme]?null:_,l=""}if(t)return;u=iL;continue}return _O}l+=n;break;case ZO:if(c.scheme="file","/"==n||"\\"==n)u=eL;else{if(!i||"file"!=i.scheme){u=rL;continue}if(n==kA)c.host=i.host,c.path=jM(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=jM(i.path),c.query="",u=sL;else{if("#"!=n){$O(oO(jM(r,d),""))||(c.host=i.host,c.path=jM(i.path),c.shortenPath()),u=rL;continue}c.host=i.host,c.path=jM(i.path),c.query=i.query,c.fragment="",u=oL}}break;case eL:if("/"==n||"\\"==n){u=tL;break}i&&"file"==i.scheme&&!$O(oO(jM(r,d),""))&&(UO(i.path[0],!0)?uO(c.path,i.path[0]):c.host=i.host),u=rL;continue;case tL:if(n==kA||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&UO(l))u=rL;else if(""==l){if(c.host="",t)return;u=iL}else{if(o=c.parseHost(l))return o;if("localhost"==c.host&&(c.host=""),t)return;l="",u=iL}continue}l+=n;break;case iL:if(c.isSpecial()){if(u=rL,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=kA&&(u=rL,"/"!=n))continue}else c.fragment="",u=oL;else c.query="",u=sL;break;case rL:if(n==kA||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=pO(a=l))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||uO(c.path,"")):BO(l)?"/"==n||"\\"==n&&c.isSpecial()||uO(c.path,""):("file"==c.scheme&&!c.path.length&&UO(l)&&(c.host&&(c.host=""),l=nO(l,0)+":"),uO(c.path,l)),l="","file"==c.scheme&&(n==kA||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)lO(c.path);"?"==n?(c.query="",u=sL):"#"==n&&(c.fragment="",u=oL)}else l+=DO(n,PO);break;case nL:"?"==n?(c.query="",u=sL):"#"==n?(c.fragment="",u=oL):n!=kA&&(c.path[0]+=DO(n,OO));break;case sL:t||"#"!=n?n!=kA&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":DO(n,OO)):(c.fragment="",u=oL);break;case oL:n!=kA&&(c.fragment+=DO(n,LO))}d++}},parseHost:function(e){var t,i,r;if("["==nO(e,0)){if("]"!=nO(e,e.length-1))return gO;if(!(t=function(e){var t,i,r,n,s,o,a,c=[0,0,0,0,0,0,0,0],u=0,d=null,l=0,h=function(){return nO(e,l)};if(":"==h()){if(":"!=nO(e,1))return;l+=2,d=++u}for(;h();){if(8==u)return;if(":"!=h()){for(t=i=0;i<4&&sO(CO,h());)t=16*t+tO(h(),16),l++,i++;if("."==h()){if(0==i)return;if(l-=i,u>6)return;for(r=0;h();){if(n=null,r>0){if(!("."==h()&&r<4))return;l++}if(!sO(EO,h()))return;for(;sO(EO,h());){if(s=tO(h(),10),null===n)n=s;else{if(0==n)return;n=10*n+s}if(n>255)return;l++}c[u]=256*c[u]+n,2!=++r&&4!=r||u++}if(4!=r)return;break}if(":"==h()){if(l++,!h())return}else if(h())return;c[u++]=t}else{if(null!==d)return;l++,d=++u}}if(null!==d)for(o=u-d,u=7;0!=u&&o>0;)a=c[u],c[u--]=c[d+o-1],c[d+--o]=a;else if(8!=u)return;return c}(mO(e,1,-1))))return gO;this.host=t}else if(this.isSpecial()){if(e=function(e){var t,i,r=[],n=CM(IM(wM(e),fM,"."),".");for(t=0;t<n.length;t++)i=n[t],TM(r,_M(pM,i)?"xn--"+AM(i):i);return bM(r,".")}(e),sO(wO,e))return gO;if(null===(t=function(e){var t,i,r,n,s,o,a,c=hO(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""==(n=c[r]))return e;if(s=10,n.length>1&&"0"==nO(n,0)&&(s=sO(bO,n)?16:8,n=mO(n,8==s?1:2)),""===n)o=0;else{if(!sO(10==s?IO:8==s?TO:CO,n))return e;o=tO(n,s)}uO(i,o)}for(r=0;r<t;r++)if(o=i[r],r==t-1){if(o>=rO(256,5-t))return null}else if(o>255)return null;for(a=cO(i),r=0;r<i.length;r++)a+=i[r]*rO(256,3-r);return a}(e)))return gO;this.host=t}else{if(sO(RO,e))return gO;for(t="",i=FM(e),r=0;r<i.length;r++)t+=DO(i[r],OO);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return BM(xO,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&UO(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,s=e.port,o=e.path,a=e.query,c=e.fragment,u=t+":";return null!==n?(u+="//",e.includesCredentials()&&(u+=i+(r?":"+r:"")+"@"),u+=MO(n),null!==s&&(u+=":"+s)):"file"==t&&(u+="//"),u+=e.cannotBeABaseURL?o[0]:o.length?"/"+oO(o,"/"):"",null!==a&&(u+="?"+a),null!==c&&(u+="#"+c),u},setHref:function(e){var t=this.parse(e);if(t)throw eO(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new cL(e.path[0]).origin}catch(e){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+MO(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(WM(e)+":",VO)},getUsername:function(){return this.username},setUsername:function(e){var t=FM(WM(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=DO(t[i],NO)}},getPassword:function(){return this.password},setPassword:function(e){var t=FM(WM(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=DO(t[i],NO)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?MO(e):MO(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,QO)},getHostname:function(){var e=this.host;return null===e?"":MO(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,KO)},getPort:function(){var e=this.port;return null===e?"":WM(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=WM(e))?this.port=null:this.parse(e,XO))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+oO(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,iL))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=WM(e))?this.query=null:("?"==nO(e,0)&&(e=mO(e,1)),this.query="",this.parse(e,sL)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=WM(e))?("#"==nO(e,0)&&(e=mO(e,1)),this.fragment="",this.parse(e,oL)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var cL=function(e){var t=$M(this,uL),i=qM(arguments.length,1)>1?arguments[1]:void 0,r=YM(t,new aL(e,!1,i));OM||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},uL=cL.prototype,dL=function(e,t){return{get:function(){return QM(this)[e]()},set:t&&function(e){return QM(this)[t](e)},configurable:!0,enumerable:!0}};if(OM&&(UM(uL,"href",dL("serialize","setHref")),UM(uL,"origin",dL("getOrigin")),UM(uL,"protocol",dL("getProtocol","setProtocol")),UM(uL,"username",dL("getUsername","setUsername")),UM(uL,"password",dL("getPassword","setPassword")),UM(uL,"host",dL("getHost","setHost")),UM(uL,"hostname",dL("getHostname","setHostname")),UM(uL,"port",dL("getPort","setPort")),UM(uL,"pathname",dL("getPathname","setPathname")),UM(uL,"search",dL("getSearch","setSearch")),UM(uL,"searchParams",dL("getSearchParams")),UM(uL,"hash",dL("getHash","setHash"))),xM(uL,"toJSON",(function(){return QM(this).serialize()}),{enumerable:!0}),xM(uL,"toString",(function(){return QM(this).serialize()}),{enumerable:!0}),ZM){var lL=ZM.createObjectURL,hL=ZM.revokeObjectURL;lL&&xM(cL,"createObjectURL",NM(lL,ZM)),hL&&xM(cL,"revokeObjectURL",NM(hL,ZM))}GM(cL,"URL"),MM({global:!0,constructor:!0,forced:!LM,sham:!OM},{URL:cL});var mL,pL,fL=new Blob(["class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.port.onmessage=event=>{const{data}=event;switch(data.name){case'setIntervalTime':this.intervalTime=data.intervalTime;break;case'stop':this.isStop=true;break}}}process(inputs){const input=inputs[0];if(this.isStop){return false}if(input.length>0){const firstChannel=input[0];let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);"],{type:"application/javascript"}),vL=!1,gL=function(){function e(t){a(this,e),this.context_=t.context,this.addModuleToContext()}var t;return u(e,[{key:"addModuleToContext",value:(t=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.context_.audioWorklet.addModule(URL.createObjectURL(fL));case 3:Mw.info("worklet addModule success"),Tw.emit(302),vL=!0,e.next=12;break;case 8:e.prev=8,e.t0=e.catch(0),Mw.info("worklet addModule catch error. ".concat(e.t0.message)),Tw.emit(303);case 12:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return t.apply(this,arguments)})},{key:"initWorkletSuccess",get:function(){return vL}}]),e}(),_L=function(){function e(t){a(this,e);var i=t.track,r=t.log,n=t.stream;this.volume_=0,this.log_=r,this.track_=i,this.stream_=n,mL||(mL=new window.AudioContext),this.audioCtx_=mL,this.destination_=this.audioCtx_.destination;var s=new MediaStream;s.addTrack(this.track_),this.streamSource_=this.audioCtx_.createMediaStreamSource(s),this.audioWorkletNode_=null,this.scriptProcessorNode_=null,this.interval_=200,Tw.on(301,this.resume,this),Tw.on(32,this.handleAudioLevelInterval,this),vw?(Tw.on(302,this.initAudioWorklet,this),Tw.on(303,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor()}return u(e,[{key:"preload",value:function(){pL?pL.initWorkletSuccess&&this.initAudioWorklet():pL=new gL({context:mL})}},{key:"initAudioWorklet",value:function(){var e=this;if(!this.audioWorkletNode_)try{this.audioWorkletNode_=new AudioWorkletNode(this.audioCtx_,"volume-meter"),this.audioWorkletNode_.port.onmessage=function(t){e.volume_=t.data.volume||0},this.streamSource_.connect(this.audioWorkletNode_).connect(this.destination_),this.handleAudioLevelInterval({interval:this.interval_}),ok.logSuccessEvent({userId:this.stream_.getUserId(),eventType:MI})}catch(e){ok.logFailedEvent({userId:this.stream_.getUserId(),eventType:MI}),this.initScriptProcessor()}}},{key:"initScriptProcessor",value:function(){var e=this;if(!this.scriptProcessorNode_)try{this.scriptProcessorNode_=this.audioCtx_.createScriptProcessor(2048,1,1),this.scriptProcessorNode_.onaudioprocess=function(t){for(var i=t.inputBuffer.getChannelData(0),r=0,n=0;n<i.length;++n)r+=i[n]*i[n];e.volume_=Math.sqrt(r/i.length)||0},this.streamSource_.connect(this.scriptProcessorNode_),this.scriptProcessorNode_.connect(this.destination_)}catch(e){this.log_.error("volumeMeter init script processor error: "+e)}}},{key:"destroy",value:function(){this.streamSource_&&this.streamSource_.disconnect(),this.scriptProcessorNode_&&(this.scriptProcessorNode_.onaudioprocess=null,this.scriptProcessorNode_.disconnect()),this.audioWorkletNode_&&(this.audioWorkletNode_.port.postMessage({name:"stop"}),this.audioWorkletNode_.port.onmessage=null,this.audioWorkletNode_.disconnect()),this.audioWorkletNode_=null,this.scriptProcessorNode_=null,this.audioCtx_=null,Tw.off(301,this.resume,this),Tw.off(32,this.handleAudioLevelInterval,this),Tw.off(302,this.initAudioWorklet,this),Tw.off(303,this.initScriptProcessor,this)}},{key:"resume",value:function(){var e;null===(e=mL)||void 0===e||e.resume()}},{key:"getInternalAudioLevel",value:function(){return this.volume_}},{key:"getCalculatedVolume",value:function(){return this.volume_.toFixed(2)}},{key:"handleAudioLevelInterval",value:function(e){var t,i=e.interval;this.interval_=i,null===(t=this.audioWorkletNode_)||void 0===t||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}}]),e}(),yL=function(){function e(t){a(this,e),this.stream_=t.stream,this.userId_=t.stream.getUserId(),this.log_=this.stream_.getLogger(),this.track_=t.track,t.gainedTrack&&(this.gainedTrack_=t.gainedTrack),this.div_=t.div,this.muted_=t.muted,this.outputDeviceId_=t.outputDeviceId,this.volume_=t.volume,this.pausedRetryCount_=5,this.emitter_=new bw,this.initializeElement(),this.state_="NONE",this.volumeMeter_=new _L({stream:this.stream_,track:this.gainedTrack_||this.track_,log:this.log_})}var t,i,n,s;return u(e,[{key:"isPlaying",get:function(){return this.state_===HT}},{key:"initializeElement",value:function(){if(this.isAudioElementInit()){var e=new MediaStream;e.addTrack(this.gainedTrack_||this.track_);var t=document.createElement(wT);t.srcObject=e,t.muted=this.muted_,t.setAttribute("id","audio_".concat(this.stream_.getId())),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.div_.appendChild(t),this.element_=t}this.handleEvents()}},{key:"setMuted",value:function(e){this.element_&&(this.element_.muted=e,this.muted_=e)}},{key:"play",value:(s=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.outputDeviceId_||!this.element_){e.next=3;break}return e.next=3,this.element_.setSinkId(this.outputDeviceId_);case 3:if(this.setVolume(this.volume_),e.prev=4,!this.element_){e.next=8;break}return e.next=8,this.element_.play();case 8:e.next=16;break;case 10:if(e.prev=10,e.t0=e.catch(4),t=GC({key:PC,data:{media:"Audio",error:e.t0}}),this.log_.warn(t),!t.includes("NotAllowedError")){e.next=16;break}throw new ek({code:ZR.PLAY_NOT_ALLOWED,message:t});case 16:case"end":return e.stop()}}),e,this,[[4,10]])}))),function(){return s.apply(this,arguments)})},{key:"handleEvents",value:function(){this.handleElementEvent=this.handleElementEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.element_&&(this.element_.addEventListener(NT,this.handleElementEvent),this.element_.addEventListener(PT,this.handleElementEvent),this.element_.addEventListener(DT,this.handleElementEvent),this.element_.addEventListener(xT,this.handleElementEvent)),this.track_.addEventListener(PT,this.handleTrackEvent),this.track_.addEventListener(OT,this.handleTrackEvent),this.track_.addEventListener(LT,this.handleTrackEvent),this.track_.readyState===PT&&this.handleTrackEvent({type:PT}),this.track_.muted&&this.handleTrackEvent({type:OT})}},{key:"handleElementEvent",value:(n=o(r().mark((function e(t){var i,n,s,o,a,c,u,d=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=t.type,e.t0=i,e.next=e.t0===NT?4:e.t0===PT?9:e.t0===DT?12:e.t0===xT?21:32;break;case 4:return this.log_.info("audio player is playing"),this.state_=HT,Tw.emit(103,{stream:this.stream_}),this.emitter_.emit(JA,{state:this.state_,reason:NT}),e.abrupt("break",32);case 9:return this.log_.info("audio player is ended"),this.state_!==GT&&(this.state_=GT,this.emitter_.emit(JA,{state:this.state_,reason:PT})),e.abrupt("break",32);case 12:return this.log_.info("audio player is paused"),this.state_=WT,this.emitter_.emit(JA,{state:this.state_,reason:DT}),(n=this.div_&&document.getElementById(this.div_.id))||this.log_.warn("audio player has been remove, element ID: ".concat(this.div_.id)),s=cT(),this.pausedRetryCount_>0&&(iw(s)&&s<=70||!n)&&(this.resume(),this.pausedRetryCount_--),_b&&(this.interval_=Qk.run((function(){d.element_&&d.state_===WT&&d.resume()}),{delay:3e3})),e.abrupt("break",32);case 21:if(!this.element_||!this.element_.error){e.next=31;break}return o="".concat(SA(),"/").concat(TT().name,"/").concat(TT().version),e.next=25,VF.getSpeakers();case 25:a=e.sent,c=a[0].label,(u=a.find((function(e){return e.deviceId===d.outputDeviceId_})))&&(c=u.label),this.log_.error("audio player error observed. code: ".concat(this.element_.error.code," message: ").concat(this.element_.error.message," deviceInfo: ").concat(o," speaker: ").concat(c)),ok.uploadEvent("stat-".concat(this.stream_.getType(),"-audio-").concat(kI,"-").concat(this.element_.error.code,"-").concat(o,"-").concat(c),this.element_.error);case 31:return e.abrupt("break",32);case 32:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"handleTrackEvent",value:function(e){var t=e.type;switch(t){case PT:this.log_.info("audio player track is ended"),this.state_!==GT&&(this.state_=GT,this.emitter_.emit(JA,{state:this.state_,reason:PT})),Tw.emit(137,{stream:this.stream_,type:t});break;case OT:this.log_.info("audio track is unable to provide media output"),this.stream_.isRemote()||pw(),this.state_!==WT&&(this.state_=WT,this.emitter_.emit(JA,{state:this.state_,reason:OT})),Tw.emit(136,{stream:this.stream_,type:t});break;case LT:this.log_.info("audio track is able to provide media output"),this.state_===WT&&(this.state_=HT,this.emitter_.emit(JA,{state:this.state_,reason:LT}))}}},{key:"unbindEvents",value:function(){this.element_&&(this.element_.removeEventListener(NT,this.handleElementEvent),this.element_.removeEventListener(PT,this.handleElementEvent),this.element_.removeEventListener(DT,this.handleElementEvent),this.element_.removeEventListener(xT,this.handleElementEvent)),this.track_&&(this.track_.removeEventListener(PT,this.handleTrackEvent),this.track_.removeEventListener(OT,this.handleTrackEvent),this.track_.removeEventListener(LT,this.handleTrackEvent))}},{key:"setSinkId",value:(i=o(r().mark((function e(t){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.outputDeviceId_===t){e.next=5;break}if(!this.element_){e.next=4;break}return e.next=4,this.element_.setSinkId(t);case 4:this.outputDeviceId_=t;case 5:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"setVolume",value:function(e){this.element_&&(this.log_.info("audioElement setVolume to : ".concat(e)),this.element_.volume=e)}},{key:"getAudioLevel",value:function(){return this.volumeMeter_.getCalculatedVolume()}},{key:"getInternalAudioLevel",value:function(){return this.volumeMeter_.getInternalAudioLevel()}},{key:"stop",value:function(){this.unbindEvents(),this.element_&&(this.div_.removeChild(this.element_),this.element_.srcObject=null,this.element_=null),this.volumeMeter_&&(this.volumeMeter_.destroy(),this.volumeMeter_=null),this.interval_>0&&Qk.clearTask(this.interval_)}},{key:"resume",value:(t=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.volumeMeter_&&this.volumeMeter_.resume(),!this.element_){e.next=5;break}return e.next=5,this.element_.play();case 5:e.next=13;break;case 7:if(e.prev=7,e.t0=e.catch(0),t=GC({key:PC,data:{media:"Audio",error:e.t0}}),this.log_.warn(t),!t.includes("NotAllowedError")){e.next=13;break}throw new ek({code:ZR.PLAY_NOT_ALLOWED,message:t});case 13:case"end":return e.stop()}}),e,this,[[0,7]])}))),function(){return t.apply(this,arguments)})},{key:"on",value:function(e,t){this.emitter_.on(e,t)}},{key:"isAudioElementInit",value:function(){return!("15.2"===vT||"15.3"===vT||"15.4"===vT)||"local"!==this.stream_.getType()||!this.muted_||(this.log_.info("audioElement is muted."),!1)}}]),e}(),SL=wi.PROPER,EL=O,bL=Jg,TL=t_.trim;En({target:"String",proto:!0,forced:function(e){return EL((function(){return!!bL[e]()||"
"!=="
"[e]()||SL&&bL[e].name!==e}))}("trim")},{trim:function(){return TL(this)}});var IL="trtc_autoplay",CL="".concat(IL,"_mask"),wL="".concat(IL,"_wrapper"),RL="".concat(IL,"_header"),kL="".concat(IL,"_content"),AL="".concat(IL,"_action_wrapper"),ML="".concat(IL,"_question"),OL="".concat(IL,"_collapse"),LL="".concat(IL,"_action_confirm"),PL="".concat(IL,"_detail"),NL="#2473E8",DL="dialog",xL="".concat(DL,"-show"),UL="".concat(DL,"-1"),$L="".concat(DL,"-2"),BL=!1,VL=function(){return!!document.querySelector(".".concat(wL))},FL="".concat(eC,"/").concat(mw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),jL="<br><a href='".concat(FL,"' target='_blank'>").concat(mw()?"其他方案?":"Any other solution?","</a>"),HL="".concat(mw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(jL):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(jL)),WL=function(){function e(){if(a(this,e),this.dialogNode_=null,this.bodyPosition_="",this.content="音视频播放被浏览器拦截,请点击“恢复播放”。",mw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!BL){var t=document.createElement("style");t.innerHTML=".".concat(CL,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(CL," div:not(.").concat(AL,"){display:block !important;}.").concat(wL,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(wL," a{color:").concat(NL,";}.").concat(RL,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(kL,"{margin:8px 0;}.").concat(AL,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(OL,"{margin-right:auto;cursor:pointer}.").concat(ML,"{height:100%;line-height:16px;cursor:pointer;}.").concat(LL,"{margin-left:8px;color:#fff;background:").concat(NL,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(LL,":hover{opacity:0.9;}.").concat(OL,",.").concat(LL,",.").concat(kL,",.").concat(ML,"{font-size:14px;}@media screen and (max-width:750px){.").concat(wL,"{width:80vw;}}"),document.head.appendChild(t),BL=!0}this.showDetail_=!1,this.isCollapseClicked_=!1,this.isQuestionClicked_=!1,this.addDiaLog()}return u(e,[{key:"createDiaLog",value:function(){var e=document.createElement("template");e.innerHTML='<div class="'.concat(CL,"\"><div class='").concat(wL,"'><div class='").concat(RL,"'>").concat(location.host,"</div><div class='").concat(kL,"'>").concat(this.content,"</div><div class='").concat(PL,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(HL,"</div><div class='").concat(AL,"'></div></div></div>").trim();var t=document.createElement("button");t.className=LL,t.innerText=mw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);var i=document.createElement("div");i.className=ML,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);var r=document.createElement("div");r.className=OL,r.innerText="".concat(mw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);var n=e.content.firstChild,s=n.querySelector(".".concat(AL));return s.appendChild(r),s.appendChild(i),s.appendChild(t),n}},{key:"addDiaLog",value:function(){VL()||(this.dialogNode_=this.createDiaLog(),document.body.appendChild(this.dialogNode_),this.dialogNode_.onclick=this.onConfirm.bind(this),this.dialogNode_.querySelector(".".concat(wL)).onclick=function(e){return e.stopPropagation()},this.bodyPosition_=document.body.style.position,document.body.style.position="fixed",Mw.info("show autoplay dialog"),ok.uploadEvent({log:xL}))}},{key:"deleteDiaLog",value:function(){this.dialogNode_&&(document.body.removeChild(this.dialogNode_),document.body.style.position=this.bodyPosition_,this.dialogNode_=null)}},{key:"onConfirm",value:function(){Mw.warn("confirm clicked, try resume stream"),Tw.emit(301),this.deleteDiaLog()}},{key:"onCollapseClick",value:function(){var e=this.dialogNode_.querySelector(".".concat(PL));e.style.visibility="".concat(this.showDetail_?"hidden":"visible"),e.style.height="".concat(this.showDetail_?0:"fit-content"),this.showDetail_=!this.showDetail_,this.isCollapseClicked_||ok.uploadEvent({log:UL}),this.isCollapseClicked_=!0}},{key:"onQuestionClick",value:function(){window.open(FL,"_blank"),this.isQuestionClicked_||ok.uploadEvent({log:$L}),this.isQuestionClicked_=!0}}]),e}(),GL=function(){function e(t){a(this,e),this.stream_=t.stream,this.userId_=t.stream.getUserId(),this.log_=this.stream_.getLogger(),this.track_=t.track,this.div_=t.div,this.muted_=t.muted,this.objectFit_=t.objectFit,this.mirror_=t.mirror,this.emitter_=new bw,this.initializeElement(),this.state_="NONE",this.pausedRetryCount_=5}var t;return u(e,[{key:"isPlaying",get:function(){return this.state_===HT}},{key:"initializeElement",value:function(){var e=new MediaStream;e.addTrack(this.track_);var t=document.createElement(RT);t.srcObject=e,t.muted=!0;var i="width: 100%; height: 100%; object-fit: ".concat(this.objectFit_,";");this.mirror_&&(i+="transform: scaleX(-1);"),t.setAttribute("id","video_".concat(this.stream_.getId())),t.setAttribute("style",i),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.div_&&this.div_.appendChild(t),this.element_=t,this.handleEvents()}},{key:"setRect",value:function(e){var t=e.width,i=e.height;this.element_&&(this.element_.style.width=t+"px",this.element_.style.height=i+"px")}},{key:"setMirror",value:function(e){this.element_&&(this.element_.style.transform=e?"scaleX(-1)":"",this.mirror_=e)}},{key:"setObjectFit",value:function(e){this.element_&&(this.element_.style.objectFit="".concat(e),this.objectFit_=e)}},{key:"play",value:(t=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.element_.play();case 3:e.next=11;break;case 5:if(e.prev=5,e.t0=e.catch(0),t=GC({key:PC,data:{media:"Video",error:e.t0}}),this.log_.warn(t),!t.includes("NotAllowedError")){e.next=11;break}throw new ek({code:ZR.PLAY_NOT_ALLOWED,message:t});case 11:case"end":return e.stop()}}),e,this,[[0,5]])}))),function(){return t.apply(this,arguments)})},{key:"handleEvents",value:function(){this.handleElementEvent=this.handleElementEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.element_.addEventListener(NT,this.handleElementEvent),this.element_.addEventListener(PT,this.handleElementEvent),this.element_.addEventListener(DT,this.handleElementEvent),this.element_.addEventListener(xT,this.handleElementEvent),this.element_.addEventListener(UT,this.handleElementEvent),this.track_.addEventListener(PT,this.handleTrackEvent),this.track_.addEventListener(OT,this.handleTrackEvent),this.track_.addEventListener(LT,this.handleTrackEvent),this.track_.readyState===PT&&this.handleTrackEvent({type:PT}),this.track_.muted&&this.handleTrackEvent({type:OT})}},{key:"handleElementEvent",value:function(e){var t=this;switch(e.type){case NT:this.log_.info("video player is playing"),this.state_=HT,Tw.emit(102,{stream:this.stream_}),this.emitter_.emit(JA,{state:this.state_,reason:NT}),this.interval_&&(Qk.clearTask(this.interval_),this.interval_=null);break;case PT:this.log_.info("video player is ended"),this.state_!==GT&&(this.state_=GT,this.emitter_.emit(JA,{state:this.state_,reason:PT}));break;case DT:this.log_.info("video player is paused"),this.div_&&!document.getElementById(this.div_.id)&&this.log_.warn("video player has been remove, element ID: ".concat(this.div_.id)),this.state_=WT,this.emitter_.emit(JA,{state:this.state_,reason:DT}),this.pausedRetryCount_>0&&!VL()&&(this.log_.info("video player auto resume when video paused"),this.resume(),this.pausedRetryCount_--),_b&&(this.interval_=Qk.run((function(){t.element_&&t.state_===WT&&t.resume()}),{delay:3e3}));break;case xT:if(this.element_&&this.element_.error){var i="".concat(SA(),"/").concat(TT().name,"/").concat(TT().version);this.log_.error("video player error observed. code: ".concat(this.element_.error.code," message: ").concat(this.element_.error.message," deviceInfo: ").concat(i)),ok.uploadEvent("stat-".concat(this.stream_.getType(),"-video-").concat(kI,"-").concat(this.element_.error.code,"-").concat(i),this.element_.error)}break;case UT:Tw.emit(133,{stream:this.stream_})}}},{key:"handleTrackEvent",value:function(e){var t=e.type;switch(t){case PT:this.log_.info("video track is ended"),Tw.emit(135,{stream:this.stream_,type:t}),this.state_!==GT&&(this.state_=GT,this.emitter_.emit(JA,{state:this.state_,reason:PT}));break;case OT:this.log_.info("video track is unable to provide media output"),this.stream_.isRemote()||pw(),Tw.emit(130,{stream:this.stream_,type:t}),this.state_!==WT&&(this.state_=WT,this.emitter_.emit(JA,{state:this.state_,reason:OT}));break;case LT:this.log_.info("video track is able to provide media output"),Tw.emit(131,{stream:this.stream_}),this.state_===WT&&(this.state_=HT,this.emitter_.emit(JA,{state:this.state_,reason:LT}))}}},{key:"unbindEvents",value:function(){this.element_&&(this.element_.removeEventListener(NT,this.handleElementEvent),this.element_.removeEventListener(PT,this.handleElementEvent),this.element_.removeEventListener(DT,this.handleElementEvent),this.element_.removeEventListener(xT,this.handleElementEvent),this.element_.removeEventListener(UT,this.handleElementEvent)),this.track_&&(this.track_.removeEventListener(PT,this.handleTrackEvent),this.track_.removeEventListener(OT,this.handleTrackEvent),this.track_.removeEventListener(LT,this.handleTrackEvent))}},{key:"stop",value:function(){this.unbindEvents(),this.div_&&this.div_.removeChild(this.element_),this.element_.srcObject=null,this.element_=null,this.interval_&&Qk.clearTask(this.interval_)}},{key:"resume",value:function(){return this.play()}},{key:"getVideoFrame",value:function(){var e=document.createElement("canvas");return e.width=this.element_.videoWidth,e.height=this.element_.videoHeight,e.getContext("2d").drawImage(this.element_,0,0),e.toDataURL("image/png")}},{key:"on",value:function(e,t){this.emitter_.on(e,t)}},{key:"getElement",value:function(){return this.element_?this.element_:null}}]),e}(),qL="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,JL=Tr,zL=Mr,YL=RangeError,QL=function(e){if(void 0===e)return 0;var t=JL(e),i=zL(t);if(t!==i)throw YL("Wrong length or index");return i},KL=Array,XL=Math.abs,ZL=Math.pow,eP=Math.floor,tP=Math.log,iP=Math.LN2,rP=ht,nP=Rr,sP=Lr,oP=function(e){for(var t=rP(this),i=sP(t),r=arguments.length,n=nP(r>1?arguments[1]:void 0,i),s=r>2?arguments[2]:void 0,o=void 0===s?i:nP(s,i);o>n;)t[n++]=e;return t},aP=A,cP=te,uP=L,dP=qL,lP=wi,hP=yi,mP=Rd,pP=O,fP=ed,vP=Tr,gP=Mr,_P=QL,yP=function(e,t,i){var r,n,s,o=KL(i),a=8*i-t-1,c=(1<<a)-1,u=c>>1,d=23===t?ZL(2,-24)-ZL(2,-77):0,l=e<0||0===e&&1/e<0?1:0,h=0;for((e=XL(e))!=e||1/0===e?(n=e!=e?1:0,r=c):(r=eP(tP(e)/iP),e*(s=ZL(2,-r))<1&&(r--,s*=2),(e+=r+u>=1?d/s:d*ZL(2,1-u))*s>=2&&(r++,s/=2),r+u>=c?(n=0,r=c):r+u>=1?(n=(e*s-1)*ZL(2,t),r+=u):(n=e*ZL(2,u-1)*ZL(2,t),r=0));t>=8;)o[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)o[h++]=255&r,r/=256,a-=8;return o[--h]|=128*l,o},SP=function(e,t){var i,r=e.length,n=8*r-t-1,s=(1<<n)-1,o=s>>1,a=n-7,c=r-1,u=e[c--],d=127&u;for(u>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-o;else{if(d===s)return i?NaN:u?-1/0:1/0;i+=ZL(2,t),d-=o}return(u?-1:1)*i*ZL(2,d-t)},EP=wa,bP=Ka,TP=yr.f,IP=ri.f,CP=oP,wP=jc,RP=$a,kP=lP.PROPER,AP=lP.CONFIGURABLE,MP=tr.get,OP=tr.set,LP="ArrayBuffer",PP="Wrong index",NP=aP.ArrayBuffer,DP=NP,xP=DP&&DP.prototype,UP=aP.DataView,$P=UP&&UP.prototype,BP=Object.prototype,VP=aP.Array,FP=aP.RangeError,jP=cP(CP),HP=cP([].reverse),WP=yP,GP=SP,qP=function(e){return[255&e]},JP=function(e){return[255&e,e>>8&255]},zP=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},YP=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},QP=function(e){return WP(e,23,4)},KP=function(e){return WP(e,52,8)},XP=function(e,t){IP(e.prototype,t,{get:function(){return MP(this)[t]}})},ZP=function(e,t,i,r){var n=_P(i),s=MP(e);if(n+t>s.byteLength)throw FP(PP);var o=MP(s.buffer).bytes,a=n+s.byteOffset,c=wP(o,a,a+t);return r?c:HP(c)},eN=function(e,t,i,r,n,s){var o=_P(i),a=MP(e);if(o+t>a.byteLength)throw FP(PP);for(var c=MP(a.buffer).bytes,u=o+a.byteOffset,d=r(+n),l=0;l<t;l++)c[u+l]=d[s?l:t-l-1]};if(dP){var tN=kP&&NP.name!==LP;if(pP((function(){NP(1)}))&&pP((function(){new NP(-1)}))&&!pP((function(){return new NP,new NP(1.5),new NP(NaN),1!=NP.length||tN&&!AP})))tN&&AP&&hP(NP,"name",LP);else{(DP=function(e){return fP(this,xP),new NP(_P(e))}).prototype=xP;for(var iN,rN=TP(NP),nN=0;rN.length>nN;)(iN=rN[nN++])in DP||hP(DP,iN,NP[iN]);xP.constructor=DP}bP&&EP($P)!==BP&&bP($P,BP);var sN=new UP(new DP(2)),oN=cP($P.setInt8);sN.setInt8(0,2147483648),sN.setInt8(1,2147483649),!sN.getInt8(0)&&sN.getInt8(1)||mP($P,{setInt8:function(e,t){oN(this,e,t<<24>>24)},setUint8:function(e,t){oN(this,e,t<<24>>24)}},{unsafe:!0})}else xP=(DP=function(e){fP(this,xP);var t=_P(e);OP(this,{bytes:jP(VP(t),0),byteLength:t}),uP||(this.byteLength=t)}).prototype,$P=(UP=function(e,t,i){fP(this,$P),fP(e,xP);var r=MP(e).byteLength,n=vP(t);if(n<0||n>r)throw FP("Wrong offset");if(n+(i=void 0===i?r-n:gP(i))>r)throw FP("Wrong length");OP(this,{buffer:e,byteLength:i,byteOffset:n}),uP||(this.buffer=e,this.byteLength=i,this.byteOffset=n)}).prototype,uP&&(XP(DP,"byteLength"),XP(UP,"buffer"),XP(UP,"byteLength"),XP(UP,"byteOffset")),mP($P,{getInt8:function(e){return ZP(this,1,e)[0]<<24>>24},getUint8:function(e){return ZP(this,1,e)[0]},getInt16:function(e){var t=ZP(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ZP(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return YP(ZP(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return YP(ZP(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return GP(ZP(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return GP(ZP(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){eN(this,1,e,qP,t)},setUint8:function(e,t){eN(this,1,e,qP,t)},setInt16:function(e,t){eN(this,2,e,JP,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){eN(this,2,e,JP,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){eN(this,4,e,zP,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){eN(this,4,e,zP,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){eN(this,4,e,QP,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){eN(this,8,e,KP,t,arguments.length>2?arguments[2]:void 0)}});RP(DP,LP),RP(UP,"DataView");var aN={ArrayBuffer:DP,DataView:UP},cN=En,uN=te,dN=O,lN=ci,hN=Rr,mN=Mr,pN=ly,fN=aN.ArrayBuffer,vN=aN.DataView,gN=vN.prototype,_N=uN(fN.prototype.slice),yN=uN(gN.getUint8),SN=uN(gN.setUint8);cN({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:dN((function(){return!new fN(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(_N&&void 0===t)return _N(lN(this),e);for(var i=lN(this).byteLength,r=hN(e,i),n=hN(void 0===t?i:t,i),s=new(pN(this,fN))(mN(n-r)),o=new vN(this),a=new vN(s),c=0;r<n;)SN(a,c++,yN(o,r++));return s}}),En({global:!0,constructor:!0,forced:!qL},{DataView:aN.DataView});var EN=En,bN=Rn,TN=te([].reverse),IN=[1,2];EN({target:"Array",proto:!0,forced:String(IN)===String(IN.reverse())},{reverse:function(){return bN(this)&&(this.length=this.length),TN(this)}});var CN=ze,wN=ht,RN=oe,kN=Lr,AN=TypeError,MN=function(e){return function(t,i,r,n){CN(i);var s=wN(t),o=RN(s),a=kN(s),c=e?a-1:0,u=e?-1:1;if(r<2)for(;;){if(c in o){n=o[c],c+=u;break}if(c+=u,e?c<0:a<=c)throw AN("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=u)c in o&&(n=i(n,o[c],c,s));return n}},ON={left:MN(!1),right:MN(!0)},LN=ON.left,PN=Pe,NN=iy;En({target:"Array",proto:!0,forced:!_h("reduce")||!NN&&PN>79&&PN<83},{reduce:function(e){var t=arguments.length;return LN(this,e,t,t>1?arguments[1]:void 0)}});var DN=Ld,xN=aN.ArrayBuffer;En({global:!0,constructor:!0,forced:A.ArrayBuffer!==xN},{ArrayBuffer:xN}),DN("ArrayBuffer");var UN=En,$N=Rn,BN=Qn,VN=Se,FN=Rr,jN=Lr,HN=me,WN=xc,GN=Ot,qN=Nl,JN=ps("slice"),zN=GN("species"),YN=Array,QN=Math.max;UN({target:"Array",proto:!0,forced:!JN},{slice:function(e,t){var i,r,n,s=HN(this),o=jN(s),a=FN(e,o),c=FN(void 0===t?o:t,o);if($N(s)&&(i=s.constructor,(BN(i)&&(i===YN||$N(i.prototype))||VN(i)&&null===(i=i[zN]))&&(i=void 0),i===YN||void 0===i))return qN(s,a,c);for(r=new(void 0===i?YN:i)(QN(c-a,0)),n=0;a<c;a++,n++)a in s&&WN(r,n,s[a]);return r.length=n,r}});var KN=A,XN=O,ZN=te,eD=Qd,tD=t_.trim,iD=Jg,rD=KN.parseInt,nD=KN.Symbol,sD=nD&&nD.iterator,oD=/^[+-]?0x/i,aD=ZN(oD.exec),cD=8!==rD(iD+"08")||22!==rD(iD+"0x16")||sD&&!XN((function(){rD(Object(sD))}))?function(e,t){var i=tD(eD(e));return rD(i,t>>>0||(aD(oD,i)?16:10))}:rD;En({global:!0,forced:parseInt!=cD},{parseInt:cD});var uD,dD,lD,hD={exports:{}},mD=qL,pD=L,fD=A,vD=ge,gD=Se,_D=ft,yD=xn,SD=We,ED=yi,bD=_r,TD=ri.f,ID=Ce,CD=wa,wD=Ka,RD=Ot,kD=St,AD=tr.enforce,MD=tr.get,OD=fD.Int8Array,LD=OD&&OD.prototype,PD=fD.Uint8ClampedArray,ND=PD&&PD.prototype,DD=OD&&CD(OD),xD=LD&&CD(LD),UD=Object.prototype,$D=fD.TypeError,BD=RD("toStringTag"),VD=kD("TYPED_ARRAY_TAG"),FD=mD&&!!wD&&"Opera"!==yD(fD.opera),jD=!1,HD={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},WD={BigInt64Array:8,BigUint64Array:8},GD=function(e){var t=CD(e);if(gD(t)){var i=MD(t);return i&&_D(i,"TypedArrayConstructor")?i.TypedArrayConstructor:GD(t)}},qD=function(e){if(!gD(e))return!1;var t=yD(e);return _D(HD,t)||_D(WD,t)};for(uD in HD)(lD=(dD=fD[uD])&&dD.prototype)?AD(lD).TypedArrayConstructor=dD:FD=!1;for(uD in WD)(lD=(dD=fD[uD])&&dD.prototype)&&(AD(lD).TypedArrayConstructor=dD);if((!FD||!vD(DD)||DD===Function.prototype)&&(DD=function(){throw $D("Incorrect invocation")},FD))for(uD in HD)fD[uD]&&wD(fD[uD],DD);if((!FD||!xD||xD===UD)&&(xD=DD.prototype,FD))for(uD in HD)fD[uD]&&wD(fD[uD].prototype,xD);if(FD&&CD(ND)!==xD&&wD(ND,xD),pD&&!_D(xD,BD))for(uD in jD=!0,TD(xD,BD,{get:function(){return gD(this)?this[VD]:void 0}}),HD)fD[uD]&&ED(fD[uD],VD,uD);var JD={NATIVE_ARRAY_BUFFER_VIEWS:FD,TYPED_ARRAY_TAG:jD&&VD,aTypedArray:function(e){if(qD(e))return e;throw $D("Target is not a typed array")},aTypedArrayConstructor:function(e){if(vD(e)&&(!wD||ID(DD,e)))return e;throw $D(SD(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(pD){if(i)for(var n in HD){var s=fD[n];if(s&&_D(s.prototype,e))try{delete s.prototype[e]}catch(i){try{s.prototype[e]=t}catch(e){}}}xD[e]&&!i||bD(xD,e,i?t:FD&&LD[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(pD){if(wD){if(i)for(r in HD)if((n=fD[r])&&_D(n,e))try{delete n[e]}catch(e){}if(DD[e]&&!i)return;try{return bD(DD,e,i?t:FD&&DD[e]||t)}catch(e){}}for(r in HD)!(n=fD[r])||n[e]&&!i||bD(n,e,t)}},getTypedArrayConstructor:GD,isView:function(e){if(!gD(e))return!1;var t=yD(e);return"DataView"===t||_D(HD,t)||_D(WD,t)},isTypedArray:qD,TypedArray:DD,TypedArrayPrototype:xD},zD=A,YD=O,QD=sd,KD=JD.NATIVE_ARRAY_BUFFER_VIEWS,XD=zD.ArrayBuffer,ZD=zD.Int8Array,ex=!KD||!YD((function(){ZD(1)}))||!YD((function(){new ZD(-1)}))||!QD((function(e){new ZD,new ZD(null),new ZD(1.5),new ZD(e)}),!0)||YD((function(){return 1!==new ZD(new XD(2),1,void 0).length})),tx=Tr,ix=RangeError,rx=RangeError,nx=function(e,t){var i=function(e){var t=tx(e);if(t<0)throw ix("The argument can't be less than 0");return t}(e);if(i%t)throw rx("Wrong offset");return i},sx=xn,ox=te("".slice),ax=$t,cx=TypeError,ux=function(e){var t=ax(e,"number");if("number"==typeof t)throw cx("Can't convert number to bigint");return BigInt(t)},dx=Cn,lx=x,hx=oy,mx=ht,px=Lr,fx=Pu,vx=wu,gx=Su,_x=function(e){return"Big"===ox(sx(e),0,3)},yx=JD.aTypedArrayConstructor,Sx=ux,Ex=En,bx=A,Tx=x,Ix=L,Cx=ex,wx=JD,Rx=aN,kx=ed,Ax=H,Mx=yi,Ox=Nw,Lx=Mr,Px=QL,Nx=nx,Dx=Ft,xx=ft,Ux=xn,$x=Se,Bx=je,Vx=aa,Fx=Ce,jx=Ka,Hx=yr.f,Wx=function(e){var t,i,r,n,s,o,a,c,u=hx(this),d=mx(e),l=arguments.length,h=l>1?arguments[1]:void 0,m=void 0!==h,p=vx(d);if(p&&!gx(p))for(c=(a=fx(d,p)).next,d=[];!(o=lx(c,a)).done;)d.push(o.value);for(m&&l>2&&(h=dx(h,arguments[2])),i=px(d),r=new(yx(u))(i),n=_x(r),t=0;i>t;t++)s=m?h(d[t],t):d[t],r[t]=n?Sx(s):+s;return r},Gx=ds.forEach,qx=Ld,Jx=ri,zx=M,Yx=ud,Qx=tr.get,Kx=tr.set,Xx=tr.enforce,Zx=Jx.f,eU=zx.f,tU=Math.round,iU=bx.RangeError,rU=Rx.ArrayBuffer,nU=rU.prototype,sU=Rx.DataView,oU=wx.NATIVE_ARRAY_BUFFER_VIEWS,aU=wx.TYPED_ARRAY_TAG,cU=wx.TypedArray,uU=wx.TypedArrayPrototype,dU=wx.aTypedArrayConstructor,lU=wx.isTypedArray,hU="BYTES_PER_ELEMENT",mU="Wrong length",pU=function(e,t){dU(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},fU=function(e,t){Zx(e,t,{get:function(){return Qx(this)[t]}})},vU=function(e){var t;return Fx(nU,e)||"ArrayBuffer"==(t=Ux(e))||"SharedArrayBuffer"==t},gU=function(e,t){return lU(e)&&!Bx(t)&&t in e&&Ox(+t)&&t>=0},_U=function(e,t){return t=Dx(t),gU(e,t)?Ax(2,e[t]):eU(e,t)},yU=function(e,t,i){return t=Dx(t),!(gU(e,t)&&$x(i)&&xx(i,"value"))||xx(i,"get")||xx(i,"set")||i.configurable||xx(i,"writable")&&!i.writable||xx(i,"enumerable")&&!i.enumerable?Zx(e,t,i):(e[t]=i.value,e)};Ix?(oU||(zx.f=_U,Jx.f=yU,fU(uU,"buffer"),fU(uU,"byteOffset"),fU(uU,"byteLength"),fU(uU,"length")),Ex({target:"Object",stat:!0,forced:!oU},{getOwnPropertyDescriptor:_U,defineProperty:yU}),hD.exports=function(e,t,i){var r=e.match(/\d+$/)[0]/8,n=e+(i?"Clamped":"")+"Array",s="get"+e,o="set"+e,a=bx[n],c=a,u=c&&c.prototype,d={},l=function(e,t){Zx(e,t,{get:function(){return function(e,t){var i=Qx(e);return i.view[s](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var s=Qx(e);i&&(n=(n=tU(n))<0?0:n>255?255:255&n),s.view[o](t*r+s.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};oU?Cx&&(c=t((function(e,t,i,n){return kx(e,u),Yx($x(t)?vU(t)?void 0!==n?new a(t,Nx(i,r),n):void 0!==i?new a(t,Nx(i,r)):new a(t):lU(t)?pU(c,t):Tx(Wx,c,t):new a(Px(t)),e,c)})),jx&&jx(c,cU),Gx(Hx(a),(function(e){e in c||Mx(c,e,a[e])})),c.prototype=u):(c=t((function(e,t,i,n){kx(e,u);var s,o,a,d=0,h=0;if($x(t)){if(!vU(t))return lU(t)?pU(c,t):Tx(Wx,c,t);s=t,h=Nx(i,r);var m=t.byteLength;if(void 0===n){if(m%r)throw iU(mU);if((o=m-h)<0)throw iU(mU)}else if((o=Lx(n)*r)+h>m)throw iU(mU);a=o/r}else a=Px(t),s=new rU(o=a*r);for(Kx(e,{buffer:s,byteOffset:h,byteLength:o,length:a,view:new sU(s)});d<a;)l(e,d++)})),jx&&jx(c,cU),u=c.prototype=Vx(uU)),u.constructor!==c&&Mx(u,"constructor",c),Xx(u).TypedArrayConstructor=c,aU&&Mx(u,aU,n);var h=c!=a;d[n]=c,Ex({global:!0,constructor:!0,forced:h,sham:!oU},d),hU in c||Mx(c,hU,r),hU in u||Mx(u,hU,r),qx(n)}):hD.exports=function(){},(0,hD.exports)("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var SU=ht,EU=Rr,bU=Lr,TU=rh,IU=Math.min,CU=JD,wU=te([].copyWithin||function(e,t){var i=SU(this),r=bU(i),n=EU(e,r),s=EU(t,r),o=arguments.length>2?arguments[2]:void 0,a=IU((void 0===o?r:EU(o,r))-s,r-n),c=1;for(s<n&&n<s+a&&(c=-1,s+=a-1,n+=a-1);a-- >0;)s in i?i[n]=i[s]:TU(i,n),n+=c,s+=c;return i}),RU=CU.aTypedArray;(0,CU.exportTypedArrayMethod)("copyWithin",(function(e,t){return wU(RU(this),e,t,arguments.length>2?arguments[2]:void 0)}));var kU=ds.every,AU=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("every",(function(e){return kU(AU(this),e,arguments.length>1?arguments[1]:void 0)}));var MU=oP,OU=ux,LU=xn,PU=x,NU=O,DU=JD.aTypedArray,xU=JD.exportTypedArrayMethod,UU=te("".slice);xU("fill",(function(e){var t=arguments.length;DU(this);var i="Big"===UU(LU(this),0,3)?OU(e):+e;return PU(MU,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),NU((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var $U=Lr,BU=ly,VU=JD.aTypedArrayConstructor,FU=JD.getTypedArrayConstructor,jU=function(e){return VU(BU(e,FU(e)))},HU=jU,WU=ds.filter,GU=function(e,t){return function(e,t){for(var i=0,r=$U(t),n=new e(r);r>i;)n[i]=t[i++];return n}(HU(e),t)},qU=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("filter",(function(e){var t=WU(qU(this),e,arguments.length>1?arguments[1]:void 0);return GU(this,t)}));var JU=ds.find,zU=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("find",(function(e){return JU(zU(this),e,arguments.length>1?arguments[1]:void 0)}));var YU=ds.findIndex,QU=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("findIndex",(function(e){return YU(QU(this),e,arguments.length>1?arguments[1]:void 0)}));var KU=ds.forEach,XU=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("forEach",(function(e){KU(XU(this),e,arguments.length>1?arguments[1]:void 0)}));var ZU=Ur.includes,e$=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("includes",(function(e){return ZU(e$(this),e,arguments.length>1?arguments[1]:void 0)}));var t$=Ur.indexOf,i$=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("indexOf",(function(e){return t$(i$(this),e,arguments.length>1?arguments[1]:void 0)}));var r$=A,n$=O,s$=te,o$=JD,a$=Ac,c$=Ot("iterator"),u$=r$.Uint8Array,d$=s$(a$.values),l$=s$(a$.keys),h$=s$(a$.entries),m$=o$.aTypedArray,p$=o$.exportTypedArrayMethod,f$=u$&&u$.prototype,v$=!n$((function(){f$[c$].call([1])})),g$=!!f$&&f$.values&&f$[c$]===f$.values&&"values"===f$.values.name,_$=function(){return d$(m$(this))};p$("entries",(function(){return h$(m$(this))}),v$),p$("keys",(function(){return l$(m$(this))}),v$),p$("values",_$,v$||!g$,{name:"values"}),p$(c$,_$,v$||!g$,{name:"values"});var y$=JD.aTypedArray,S$=JD.exportTypedArrayMethod,E$=te([].join);S$("join",(function(e){return E$(y$(this),e)}));var b$=Pl,T$=me,I$=Tr,C$=Lr,w$=_h,R$=Math.min,k$=[].lastIndexOf,A$=!!k$&&1/[1].lastIndexOf(1,-0)<0,M$=w$("lastIndexOf"),O$=Pl,L$=A$||!M$?function(e){if(A$)return b$(k$,this,arguments)||0;var t=T$(this),i=C$(t),r=i-1;for(arguments.length>1&&(r=R$(r,I$(arguments[1]))),r<0&&(r=i+r);r>=0;r--)if(r in t&&t[r]===e)return r||0;return-1}:k$,P$=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("lastIndexOf",(function(e){var t=arguments.length;return O$(L$,P$(this),t>1?[e,arguments[1]]:[e])}));var N$=ds.map,D$=jU,x$=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("map",(function(e){return N$(x$(this),e,arguments.length>1?arguments[1]:void 0,(function(e,t){return new(D$(e))(t)}))}));var U$=ON.left,$$=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("reduce",(function(e){var t=arguments.length;return U$($$(this),e,t,t>1?arguments[1]:void 0)}));var B$=ON.right,V$=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("reduceRight",(function(e){var t=arguments.length;return B$(V$(this),e,t,t>1?arguments[1]:void 0)}));var F$=JD.aTypedArray,j$=JD.exportTypedArrayMethod,H$=Math.floor;j$("reverse",(function(){for(var e,t=this,i=F$(t).length,r=H$(i/2),n=0;n<r;)e=t[n],t[n++]=t[--i],t[i]=e;return t}));var W$=A,G$=x,q$=JD,J$=Lr,z$=nx,Y$=ht,Q$=O,K$=W$.RangeError,X$=W$.Int8Array,Z$=X$&&X$.prototype,eB=Z$&&Z$.set,tB=q$.aTypedArray,iB=q$.exportTypedArrayMethod,rB=!Q$((function(){var e=new Uint8ClampedArray(2);return G$(eB,e,{length:1,0:3},1),3!==e[1]})),nB=rB&&q$.NATIVE_ARRAY_BUFFER_VIEWS&&Q$((function(){var e=new X$(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));iB("set",(function(e){tB(this);var t=z$(arguments.length>1?arguments[1]:void 0,1),i=Y$(e);if(rB)return G$(eB,this,i,t);var r=this.length,n=J$(i),s=0;if(n+t>r)throw K$("Wrong length");for(;s<n;)this[t+s]=i[s++]}),!rB||nB);var sB=jU,oB=Nl,aB=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("slice",(function(e,t){for(var i=oB(aB(this),e,t),r=sB(this),n=0,s=i.length,o=new r(s);s>n;)o[n]=i[n++];return o}),O((function(){new Int8Array(1).slice()})));var cB=ds.some,uB=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("some",(function(e){return cB(uB(this),e,arguments.length>1?arguments[1]:void 0)}));var dB=we.match(/firefox\/(\d+)/i),lB=!!dB&&+dB[1],hB=/MSIE|Trident/.test(we),mB=we.match(/AppleWebKit\/(\d+)\./),pB=!!mB&&+mB[1],fB=te,vB=O,gB=ze,_B=Ef,yB=lB,SB=hB,EB=Pe,bB=pB,TB=JD.aTypedArray,IB=JD.exportTypedArrayMethod,CB=A.Uint16Array,wB=CB&&fB(CB.prototype.sort),RB=!(!wB||vB((function(){wB(new CB(2),null)}))&&vB((function(){wB(new CB(2),{})}))),kB=!!wB&&!vB((function(){if(EB)return EB<74;if(yB)return yB<67;if(SB)return!0;if(bB)return bB<602;var e,t,i=new CB(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(wB(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));IB("sort",(function(e){return void 0!==e&&gB(e),kB?wB(this,e):_B(TB(this),function(e){return function(t,i){return void 0!==e?+e(t,i)||0:i!=i?-1:t!=t?1:0===t&&0===i?1/t>0&&1/i<0?1:-1:t>i}}(e))}),!kB||RB);var AB=Mr,MB=Rr,OB=jU,LB=JD.aTypedArray;(0,JD.exportTypedArrayMethod)("subarray",(function(e,t){var i=LB(this),r=i.length,n=MB(e,r);return new(OB(i))(i.buffer,i.byteOffset+n*i.BYTES_PER_ELEMENT,AB((void 0===t?r:MB(t,r))-n))}));var PB=Pl,NB=JD,DB=O,xB=Nl,UB=A.Int8Array,$B=NB.aTypedArray,BB=NB.exportTypedArrayMethod,VB=[].toLocaleString,FB=!!UB&&DB((function(){VB.call(new UB(1))}));BB("toLocaleString",(function(){return PB(VB,FB?xB($B(this)):$B(this),xB(arguments))}),DB((function(){return[1,2].toLocaleString()!=new UB([1,2]).toLocaleString()}))||!DB((function(){UB.prototype.toLocaleString.call([1,2])})));var jB=JD.exportTypedArrayMethod,HB=O,WB=te,GB=A.Uint8Array,qB=GB&&GB.prototype||{},JB=[].toString,zB=WB([].join);HB((function(){JB.call({})}))&&(JB=function(){return zB(this)});var YB=qB.toString!=JB;jB("toString",JB,YB);var QB=function(){function e(t,i,r){a(this,e),this.isUplink_=r,this.connection_=t,this.log_=i,this.seiMessageList_=[],this.seiPayloadType_=243,this.senderOrReceiver_=null,this.abortController_=null,this.abortMap_=new Map,this.onSEIMessage=null}return u(e,[{key:"isRunning",get:function(){return!!this.abortController_}},{key:"start",value:function(e){this.senderOrReceiver_=e;var t=e.createEncodedStreams(),i=t.readable,r=t.writable,n=new TransformStream({transform:this.isUplink_?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this.abortController_=new AbortController,i.pipeThrough(n).pipeTo(r,{signal:this.abortController_.signal}).catch((function(){}))}},{key:"restart",value:function(e){this.stop(),this.start(e)}},{key:"stop",value:function(){var e;null===(e=this.abortController_)||void 0===e||e.abort(),this.abortController_=null}},{key:"destory",value:function(){this.stop(),this.abortMap_.forEach((function(e){return e.abort()})),this.abortMap_.clear(),this.log_=null,this.onSEIMessage=null,this.senderOrReceiver_=null,this.connection_=null}},{key:"handleEncodedStreams",value:function(){var e=this;try{var t=this.connection_.getPeerConnection();if(this.clearUnusedSenderOrReceiver(t),this.isUplink_){var i,r=null===(i=this.connection_.getLocalStream())||void 0===i?void 0:i.getVideoTrack();t.getSenders().forEach((function(t){e.abortMap_.has(t)||t===e.senderOrReceiver_||(t.track&&t.track===r?e.isRunning?e.restart(t):e.start(t):e.pipeSenderOrReceiver(t))}))}else t.getReceivers().forEach((function(t,i){var r;e.abortMap_.has(t)||t===e.senderOrReceiver_||(1===i&&(null===(r=t.track)||void 0===r?void 0:r.kind)===RT?e.isRunning?e.restart(t):e.start(t):e.pipeSenderOrReceiver(t))}))}catch(e){this.log_.warn(e)}}},{key:"pipeSenderOrReceiver",value:function(e){var t=e.createEncodedStreams(),i=t.readable,r=t.writable,n=new AbortController;this.abortMap_.set(e,n),i.pipeTo(r,{signal:n.signal}).catch((function(){}))}},{key:"clearUnusedSenderOrReceiver",value:function(e){var t=this;this.abortMap_.forEach((function(i,r){(t.isUplink_?e.getSenders():e.getReceivers()).find((function(e){return e===r}))||(i.abort(),t.abortMap_.delete(r))}))}},{key:"push",value:function(e,t){t&&t.seiPayloadType&&(this.seiPayloadType_=t.seiPayloadType),this.seiMessageList_.push(e)}},{key:"hasSEI",value:function(e){var t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}},{key:"isEmptyFrame",value:function(e){return"empty"===e.type||0===e.data.byteLength}},{key:"getNaluCount",value:function(e){for(var t=0,i=0,r=new DataView(e),n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:2!==t&&3!==t||i++,t=0;break;default:t=0}return i}},{key:"encodeVideoFrame",value:function(e,t){try{if(this.connection_.isH264&&this.seiMessageList_.length>0&&!this.isEmptyFrame(e)){var i=9-this.getNaluCount(e.data);if(i<=0)return;for(var r=this.seiMessageList_.splice(0,i).reverse().map(this.encodeSEINalu.bind(this)),n=r.reduce((function(e,t){return e+t.dataView.byteLength}),0),s=new ArrayBuffer(n+e.data.byteLength),o=new DataView(s),a=new DataView(e.data),c=0,u=0;u<r.length;u++)for(var d=0;d<r[u].dataView.byteLength;d++)o.setInt8(c++,r[u].dataView.getInt8(d));for(var l=0;l<e.data.byteLength;l++)o.setInt8(c++,a.getInt8(l));e.data=s,this.log_.debug("".concat(r.length," sei sent"))}}catch(e){this.log_.warn(e)}t.enqueue(e)}},{key:"decodeVideoFrame",value:function(e,t){var i=this;try{if(this.connection_.isH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){for(var r=[],n=new DataView(e.data),s=0,o=-1,a=-1,c=0;c<e.data.byteLength;c++){var u=n.getUint8(c);if(0===u)s++;else if(1===u){if(2===s||3===s){var d=c-s;if(-1===o?o=d:-1===a&&(a=d,r.push(new KB(new DataView(n.buffer.slice(o,a)))),o=d,a=-1),6!==n.getUint8(c+1)){e.data=new DataView(n.buffer.slice(d)).buffer;break}}s=0}else s=0}this.log_.debug("".concat(r.length," sei received")),ZC(this.onSEIMessage)&&r.reverse().forEach((function(e){i.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer})}))}}catch(e){this.log_.warn(e)}t.enqueue(e)}},{key:"encodeSEINalu",value:function(e){var t=e.byteLength,i=parseInt(t/255),r=t%255,n=[];n.push(0,0,0,1,6,this.seiPayloadType_);for(var s=0;s<i;s++)n.push(255);n.push(r);var o=new DataView(e);return n.push.apply(n,b(new Uint8Array(o.buffer))),n.push(128),new KB(new DataView(new Uint8Array(n).buffer),!0)}}]),e}(),KB=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];a(this,e),this.dataView=t,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}return u(e,[{key:"addPreventionByte",value:function(){for(var e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0,n=e;n<=t;n++){var s=this.dataView.getInt8(n);switch(s){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==s?r++:r=0,i.push(s);break;default:r=0,i.push(s)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));var o=new DataView(new Uint8Array([].concat(b(new Uint8Array(this.dataView.buffer).slice(0,e)),i)).buffer);this.dataView=o}},{key:"removePreventionByte",value:function(){for(var e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0,n=e;n<=t;n++)switch(this.dataView.getInt8(n)){case 0:r++,i.push(this.dataView.getInt8(n));break;case 3:2!==r&&i.push(this.dataView.getInt8(n)),r=0;break;default:i.push(this.dataView.getInt8(n)),r=0}var s=new DataView(new Uint8Array([].concat(b(new Uint8Array(this.dataView.buffer).slice(0,e)),i)).buffer);this.dataView=s}},{key:"isSEI",get:function(){return 6===this.dataView.getUint8(4)}},{key:"seiPayloadStartIndex",get:function(){for(var e=6,t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}},{key:"seiPayloadType",get:function(){return this.isSEI?this.dataView.getUint8(5):null}},{key:"seiPayload",get:function(){if(!this.isSEI)return null;for(var e=0,t=6,i=6;i<this.dataView.buffer.byteLength;i++){var r=this.dataView.getUint8(i);if(t++,255!==r){e+=r;break}e+=255}for(var n=new ArrayBuffer(e),s=new DataView(n),o=0;o<n.byteLength;o++,t++)s.setInt8(o,this.dataView.getInt8(t));return s}}]),e}(),XB=function(){function e(t){a(this,e),this.userId_=t.userId,this.tinyId_=t.tinyId,this.client_=t.client,this.sdpSemantics_=t.client.getSdpSemantics(),this.isUplink_=t.isUplink,this.log_=Mw.createLogger({id:"n|"+this.userId_,userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId(),isLocal:this.isUplink_}),this.signalChannel_=t.signalChannel,this.peerConnection_=null,this.isErrorObserved_=!1,this.emitter_=new bw,this.currentState_=rI,this.waitForPeerConnectionConnectedPromise_=null,this.isReconnecting_=!1,this.reconnectionCount_=0,this.reconnectionTimer_=-1,this.isFirstConnection_=!0,this.delay_={audioDelay:0,videoDelay:0},this.enableSEI_=t.enableSEI,this.enableSEI_&&gA&&(this.sei_=new QB(this,this.log_,this.isUplink_))}var t;return u(e,[{key:"initialize",value:function(){var e={encodedInsertableStreams:this.enableSEI_&&gA,iceServers:this.client_.getIceServers(),iceTransportPolicy:this.client_.getIceTransportPolicy(),sdpSemantics:this.sdpSemantics_,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this.peerConnection_=new RTCPeerConnection(e),this.peerConnection_.onconnectionstatechange=this.onConnectionStateChange.bind(this)}},{key:"close",value:function(){this.log_.info("closing connection"),this.closePeerConnection(),this.sei_&&(this.sei_.destory(),this.sei_=null)}},{key:"closePeerConnection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.peerConnection_&&(this.peerConnection_.onconnectionstatechange=function(){},this.peerConnection_.close(),this.peerConnection_=null,e&&this.emitConnectionStateChangedEvent(rI))}},{key:"getDTLSTransportState",value:function(){if(!this.peerConnection_)return iI;var e=null;if(this.isUplink_){if(!lA()||0===this.peerConnection_.getSenders().length)return iI;e=this.peerConnection_.getSenders()[0].transport}else{if(!dA()||0===this.peerConnection_.getReceivers().length)return iI;e=this.peerConnection_.getReceivers()[0].transport}return e?e.state:iI}},{key:"onConnectionStateChange",value:function(e){var t=this.peerConnection_.iceConnectionState,i=this.getDTLSTransportState();if(this.log_.info("onConnectionStateChange() connectionState: "+e.target.connectionState),this.log_.info("ICE Transport state: ".concat(t,", DTLS Transport state: ").concat(i)),e.target.connectionState===aI&&this.emitConnectionStateChangedEvent(nI),"failed"===e.target.connectionState||e.target.connectionState===cI){var r="".concat(this.isUplink_?"uplink":"downlink"," ICE/DTLS Transport connection ").concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new ek({message:r,code:ZR.ICE_TRANSPORT_ERROR});ok.logFailedEvent({userId:this.client_.getUserId(),eventType:SI,error:n}),this.emitConnectionStateChangedEvent(rI),this.isErrorObserved_||this.emitter_.emit(PA,n)}e.target.connectionState!==uI&&"completed"!==e.target.connectionState||(this.logSelectedCandidate(),ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:SI}),this.emitConnectionStateChangedEvent(oI))}},{key:"emitConnectionStateChangedEvent",value:function(e){e!==this.currentState_&&(this.currentState_===sI&&e===nI||(Tw.emit(200,{client:this.client_,connection:this,prevState:this.currentState_,state:e}),this.emitter_.emit(NA,{prevState:this.currentState_,state:e}),this.currentState_=e))}},{key:"hitTest",value:function(e){return(0===e||"0"===e)&&this.isUplink_||e===this.tinyId_}},{key:"addEventInternal",value:function(e,t){var i=this.client_.getUserId(),r={eventId:e,eventDesc:t,timestamp:qv(),userId:i,tinyId:this.client_.getTinyId()};this.isUplink_||(r.remoteUserId=this.userId_,r.remoteTinyId=this.tinyId_),ik(i,r)}},{key:"getPeerConnection",value:function(){return this.peerConnection_}},{key:"getClient",value:function(){return this.client_}},{key:"getUserId",value:function(){return this.userId_}},{key:"getTinyId",value:function(){return this.tinyId_}},{key:"logSelectedCandidate",value:(t=o(r().mark((function e(){var t,i,n,s,o,a,c;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.peerConnection_){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,this.peerConnection_.getStats();case 4:t=e.sent,i=C(t),e.prev=6,i.s();case 8:if((n=i.n()).done){e.next=18;break}if((s=E(n.value,2))[0],!_A(o=s[1])){e.next=16;break}return a=t.get(o.localCandidateId),c=t.get(o.remoteCandidateId),a&&this.log_.info("local candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port," ").concat(a.networkType||""," ").concat("relay"===a.candidateType?"relayProtocol:"+a.relayProtocol:"")),c&&this.log_.info("remote candidate: ".concat(c.candidateType," ").concat(c.protocol,":").concat(c.ip||c.address,":").concat(c.port)),e.abrupt("break",18);case 16:e.next=8;break;case 18:e.next=23;break;case 20:e.prev=20,e.t0=e.catch(6),i.e(e.t0);case 23:return e.prev=23,i.f(),e.finish(23);case 26:case"end":return e.stop()}}),e,this,[[6,20,23,26]])}))),function(){return t.apply(this,arguments)})},{key:"getCurrentState",value:function(){return this.currentState_}},{key:"waitForPeerConnectionConnected",value:function(){var e=this;return this.waitForPeerConnectionConnectedPromise_||(this.waitForPeerConnectionConnectedPromise_=new Promise((function(t,i){if(e.currentState_===oI)return t();var r=function(e){e.state===oI&&(clearTimeout(-1),o(),t())},n=function(t){t.client===e.client_&&(clearTimeout(-1),o(),i(new ek({code:ZR.API_CALL_ABORTED,message:GC({key:jC,data:"leave room"})})))},s=function(t){var r=t.client,n=t.stream;!e.isUplink_&&r===e.client_&&n.getConnection()===e&&!e.peerConnection_&&(clearTimeout(-1),o(),i(new ek({code:ZR.API_CALL_ABORTED,message:GC({key:jC,data:"unsubscribe stream"})})))},o=function(){Tw.off(22,n,e),Tw.off(ww,s,e),e.emitter_.off(NA,r,e)};e.connectionTimeoutId_=setTimeout((function(){e.emitter_.off(NA,r,e);var t=new ek({code:ZR.API_CALL_TIMEOUT,message:"connection timeout"});i(t)}),1e4),Tw.on(22,n,e),e.emitter_.on(NA,r,e),e.isUplink_||Tw.on(ww,s,e)})),this.waitForPeerConnectionConnectedPromise_=this.waitForPeerConnectionConnectedPromise_.then((function(t){return e.waitForPeerConnectionConnectedPromise_=null,t})).catch((function(t){throw e.waitForPeerConnectionConnectedPromise_=null,t}))),this.waitForPeerConnectionConnectedPromise_}},{key:"getReconnectionCount",value:function(){return this.reconnectionCount_}},{key:"startReconnection",value:function(){this.isReconnecting_=!0,this.emitConnectionStateChangedEvent(sI),this.reconnect(),this.addEventInternal(this.isUplink_?32797:32800,"".concat(this.isUplink_?"uplink":"downlink","-connection is reconnecting"))}},{key:"stopReconnection",value:function(){this.log_.info("stop reconnection"),this.isReconnecting_=!1,this.reconnectionCount_=0,this.clearReconnectionTimer(),this.signalChannel_.off(3,this.reconnect,this)}},{key:"on",value:function(e,t,i){this.emitter_.on(e,t,i)}},{key:"off",value:function(e,t,i){this.emitter_.off(e,t,i)}},{key:"setDelay",value:function(e){var t=e.audioDelay,i=e.videoDelay;this.delay_={audioDelay:t,videoDelay:i}}},{key:"getDelay",value:function(){return this.delay_}},{key:"isH264",get:function(){var e,t;return!(null===(e=this.peerConnection_)||void 0===e||null===(t=e.remoteDescription)||void 0===t||!t.sdp.includes("H264"))}}]),e}(),ZB=new(function(){function e(){a(this,e),this.set_=new Set,Tw.on(1,this.add,this),Tw.on(4,this.add,this),Tw.on(5,this.delete,this),Tw.on(22,this.delete,this)}return u(e,[{key:"add",value:function(e){var t=e.client,i=e.roomId;if("rtc"!==t.getMode()){var r=this.getKey(t.getUserId(),i||t.getRoomId(),t.getSDKAppId(),t.getUseStringRoomId());this.set_.add(r)}}},{key:"delete",value:function(e){var t=e.client;if("rtc"!==t.getMode()){var i=this.getKey(t.getUserId(),t.getRoomId(),t.getSDKAppId(),t.getUseStringRoomId());this.set_.delete(i)}}},{key:"getKey",value:function(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}},{key:"isJoined",value:function(e){var t=e.userId,i=e.roomId,r=e.sdkAppId,n=e.client;return"rtc"!==n.getMode()&&this.set_.has(this.getKey(t,i,r,n.getUseStringRoomId()))}}]),e}());function eV(e,t,i,r){if(this.useStringRoomId_){if(!tw(e)||!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_ROOMID_STRING",data:t,link:{className:r,fnName:i}})})}else if(!(iw(e)&&/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_ROOMID_INTEGER",data:t,link:{className:r,fnName:i}})})}function tV(e,t,i,r){if(!/^[A-Za-z\d_-]*$/.test(e))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_STREAM_ID",data:t,link:{className:r,fnName:i}})})}var iV,rV,nV={createClient:{name:"clientConfig",required:!0,type:BI,properties:{sdkAppId:{required:!0,type:UI,allowEmpty:!1},userId:{required:!0,type:xI,allowEmpty:!1},userSig:{required:!0,type:xI,allowEmpty:!1},mode:{required:!0,type:xI,values:["rtc",YT]},useStringRoomId:{type:$I},autoSubscribe:{type:$I},enableAutoPlayDialog:{type:$I},streamId:{type:xI},userDefineRecordId:{type:xI},pureAudioPushMode:{type:UI,values:[1,2]},enableSEI:{type:$I}}},createStream:{name:"streamConfig",required:!0,type:BI,properties:{userId:{type:xI},audio:{type:$I},video:{type:$I},screen:{type:$I},screenAudio:{type:$I},microphoneId:{type:xI},cameraId:{type:xI},facingMode:{type:[xI,BI]},audioSource:{instanceOf:window.MediaStreamTrack},videoSource:{instanceOf:window.MediaStreamTrack}},validate:function(e){if(!ew(e.screen)&&e.screen&&ew(e.audio)&&(e.audio=!1),!(ew(e.audio)&&ew(e.video)||ew(e.audioSource)&&ew(e.videoSource)))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_CREATE_STREAM_SOURCE"})});if(!ew(e.screen)&&!0===e.screen&&!0===e.video)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_CREATE_STREAM_SCREEN"})});if(e.audio&&e.screenAudio)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_CREATE_STREAM_AUDIO"})});if(!0!==e.screen&&!0===e.screenAudio)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_CREATE_STREAM_SCREEN_AUDIO"})});if(!ew(e.screen)&&!0===e.screen&&!this.isScreenShareSupported())throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"NOT_SUPPORTED_CAPTURE"})})}}},sV={join:{name:"options",required:!0,properties:{roomId:{required:!0,type:[UI,xI],allowEmpty:!1,validate:eV},role:{type:[xI],values:[QT,KT]},privateMapKey:{type:[xI]}},validate:function(e){if(this.isJoined_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_JOIN"})});if(this.checkDestroy(),ZB.isJoined({userId:this.userId_,roomId:e.roomId,sdkAppId:this.sdkAppId_,client:this}))throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"REPEAT_JOIN",data:this.userId_})})}},publish:{name:"stream",required:!0,instanceOf:zI,validate:function(e){if(!this.isJoined_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_PUBLISH"})});if(this.mode_===YT&&this.role_===KT)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_AUDIENCE"})});if(this.localStream_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_DUPLICATE_PUBLISHING"})});if(!e.getIsReadyToPublish())throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_INITIALIZE"})});if(this.notPublishWithoutH264Supported_)throw new ek({code:ZR.NOT_SUPPORTED_H264,message:GC({key:xC})})}},unpublish:{name:"stream",required:!0,instanceOf:zI,validate:function(e){if(e!==this.localStream_){if(this.localStream_)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_UNPUBLISH"})});this.log_.warn("Client currently has no published stream, please call publish() first.")}}},subscribe:[{name:"stream",required:!0,instanceOf:YI,validate:function(e){if(!e.getConnection())throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:CC})});if(this.notSubscribeWithoutH264Supported_)throw new ek({code:ZR.NOT_SUPPORTED_H264,message:GC({key:UC})})}},{name:"options",type:BI,properties:{audio:{type:$I},video:{type:$I}},validate:function(e){var t=e.audio,i=e.video;if(!(ew(t)||ew(i)||t||i))throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"SUBSCRIBE_ALL_FALSE"})})}}],unsubscribe:{name:"stream",required:!0,instanceOf:YI,validate:function(e){if(!e.getConnection())throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:CC})})}},switchRole:{name:"role",required:!0,values:[QT,KT],validate:function(){if(this.mode_!==YT)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_ROLE"})});if(!this.isJoined_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_OPERATION_SWITCH_ROLE"})})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:xI,validate:tV},appId:{type:UI,allowEmpty:!1},bizId:{type:UI,allowEmpty:!1},url:{type:xI,allowEmpty:!1}},validate:function(){if(this.isDestroyed_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:LC,data:{funName:"startPublishCDNStream"}})})}},startMixTranscode:{name:"config",required:!0,type:BI,properties:{mode:{type:xI,values:["preset-layout","manual"]},streamId:{type:xI,validate:tV},videoWidth:{type:UI,notLessThanZero:!0},videoHeight:{type:UI,notLessThanZero:!0},videoBitrate:{type:UI,notLessThanZero:!0,allowEmpty:!1},videoFramerate:{type:UI,validate:function(e,t,i,r){if(e<=0||e>30)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"MIX_PARAMS_VIDEO_FRAMERATE",link:{className:r,fnName:i}})})}},videoGop:{type:UI,validate:function(e,t,i,r){if(e<1||e>8)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"MIX_PARAMS_VIDEO_GOP",link:{className:r,fnName:i}})})}},audioSampleRate:{type:UI,notLessThanZero:!0},audioBitrate:{type:UI,validate:function(e,t,i,r){if(e<32||e>192)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"MIX_PARAMS_AUDIO_BITRATE",link:{className:r,fnName:i}})})}},audioChannels:{type:UI,values:[1,2]},backgroundColor:{type:UI},backgroundImage:{type:xI},mixUsers:{required:!0,type:"array",arrayItem:{require:!0,type:BI,properties:{userId:{required:!0,type:xI},roomId:{type:[xI,UI],validate:eV},pureAudio:{type:$I},width:{type:UI,notLessThanZero:!0},height:{type:UI,notLessThanZero:!0},locationX:{type:UI,notLessThanZero:!0},locationY:{type:UI,notLessThanZero:!0},zOrder:{type:UI},streamType:{type:xI,values:["main","auxiliary"]},renderMode:{type:UI,values:[0,1,2,4]}}}}},validate:function(e,t,i,r,n){var s=0,o=0,a=e.mixUsers,c=[];if(a.forEach((function(e,t){if(c.push(e.userId),!e.pureAudio){if(!e.zOrder||e.zOrder<1||e>15)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"MIX_PARAMS_USER_Z_ORDER",data:"config.mixUsers[".concat(t,"].zOrder"),link:{className:r,fnName:i}})});e.width+e.locationX>s&&(s=e.width+e.locationX),e.height+e.locationY>o&&(o=e.height+e.locationY)}})),c.indexOf(this.getUserId())<0)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"MIX_PARAMS_NOT_SELF",link:{className:r,fnName:i}})});if(e.videoWidth<s||e.videoHeight<o)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"MIX_PARAMS_USER_STREAM",link:{className:r,fnName:i}})})}},sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate:function(e){if(!gA)throw new ek({code:ZR.NOT_SUPPORTED,message:GC({key:VC})});if(!this.enableSEI_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"SEI_DISABLED"})});if(e.byteLength>1e3)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"SEI_OVERSIZE",data:e.byteLength})});if(0===e.byteLength)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"SEI_EMPTY"})});if(!this.uplinkConnection_)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"SEI_BEFORE_PUBLISH"})});if(!this.localStream_.hasVideo())throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"SEI_NOT_VIDEO"})});var t=this.uplinkConnection_.isH264;if(!t)throw new ek({code:ZR.NOT_SUPPORTED,message:GC({key:VC,data:t})})}},{name:"options",type:BI,properties:{seiPayloadType:{type:UI,values:[5,243]}}}]},oV={TRTC:nV,CLIENT:sV,LOCAL_STREAM:{switchDevice:[{name:"type",required:!0,type:xI,values:[wT,RT]},{name:"deviceId",required:!0,type:xI,validate:function(){if(this.screen_&&!this.audio_||this.audioSource_||this.videoSource_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_SWITCH_DEVICE"})});if(0===this.publishState_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_SWITCH_DEVICE_PUBLISHING"})})}}],setAudioCaptureVolume:{name:"volume",type:UI}},STREAM:{play:[{name:"elementId",required:!0,type:[xI,"HTMLDivElement"],validate:function(e,t,i){if(tw(e)){var r=document.getElementById(e);if(!r)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_ELEMENT_ID",data:{key:t,fnName:i}})});if(!(r instanceof HTMLDivElement))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_ELEMENT_ID_TYPE",data:{key:t,fnName:i,type:aw(r)}})})}}},{name:"options",type:BI,properties:{objectFit:{type:xI,values:["contain","cover","fill"]},muted:{type:$I},mirror:{type:$I}}}]}};function aV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return function(e,i,r){var n=r.value;return r.value=function(){for(var e=arguments.length,r=new Array(e),s=0;s<e;s++)r[s]=arguments[s];return uV.call(this,t,r,i,this.name_),n.apply(this,r)},r}}function cV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return function(e,i,n){var s=n.value;return n.value=o(r().mark((function e(){var n,o,a,c=arguments;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(n=c.length,o=new Array(n),a=0;a<n;a++)o[a]=c[a];return uV.call(this,t,o,i,this.name_),e.abrupt("return",s.apply(this,o));case 3:case"end":return e.stop()}}),e,this)}))),n}}function uV(e,t,i,r){try{for(var n=0;n<e.length;n++)dV.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r})}catch(e){throw Mw.error(e),e}}function dV(e){var t=this,i=e.rule,r=e.value,n=e.key,s=e.fnName,o=e.className;if(ew(r)){if(i.required)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_PARAMETER_REQUIRED",data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})})}else{if(Array.isArray(i.type)){if(!i.type.map((function(e){return e.toLowerCase()})).includes(aw(r)))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:EC,data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})})}else if(!ew(i.type)&&aw(r)!==i.type)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:EC,data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})});if(!1===i.allowEmpty){var a=iw(r)&&(0===r||Number.isNaN(r)),c=tw(r)&&""===r.trim();if(a||c)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_PARAMETER_EMPTY",data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})})}if(i.notLessThanZero&&iw(r)&&r<0)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"CANNOT_LESS_THAN_ZERO",data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})});if(tw(i.instanceOf)){if(!r||r.name_!==i.instanceOf)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:bC,data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})})}else if(ZC(i.instanceOf)&&!(r instanceof i.instanceOf))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:bC,data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})});if(i.values&&!i.values.includes(r))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_PARAMETER_RANGE",data:{key:n,rule:i,fnName:s,value:r},link:{className:o,fnName:s}})});var u=i.properties;QC(u)&&nw(r)&&Object.keys(u).forEach((function(e){dV.call(t,{rule:u[e],value:r&&r[e],key:"".concat(n,".").concat(e),fnName:s,className:o})}));var d=i.arrayItem;QC(d)&&sw(r)&&r.forEach((function(e,i){dV.call(t,{rule:d,value:e,key:"".concat(n,"[").concat(i,"]"),fnName:s,className:o})})),ZC(i.validate)&&i.validate.call(this,r,n,s,o,this)}}En({target:"Number",stat:!0},{isNaN:function(e){return e!=e}});var lV=(iV=cV.apply(void 0,b(oV.STREAM.play)),w((rV=function(){function e(t){a(this,e),this.name_="Stream",this.userId_=t.userId,this.isRemote_=t.isRemote,this.type_=t.type,this.log_=Mw.createLogger({id:"s".concat(t.seq?t.seq:"","|").concat(this.userId_),userId:ew(t.client)?void 0:t.client.getUserId(),sdkAppId:ew(t.client)?void 0:t.client.getSDKAppId(),isLocal:!this.isRemote_,type:this.isRemote_?this.type_:""}),this.client_=null,ew(t.client)||(this.client_=t.client),this.mediaStream_=null,this.div_=null,this.isPlaying_=!1,this.connection_=null,this.audioPlayer_=null,this.videoPlayer_=null,this.muted_=!1,this.objectFit_="cover",this.mirror_=!1,this.id_="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),this.audioOutputDeviceId_=0,this.audioVolume_=1,this.emitter_=gw(new bw,this.name_),this.connectionState_=rI,this.installEvents(),ew(t.mirror)||this.log_.warn('TRTC.createStream "mirror" option was deprecated since v4.12.1,please use localStream.play to set up preview mirror. refer to '.concat(eC,"/en/LocalStream.html#play. TRTC.createStream 接口的 mirror 选项从 v4.12.1 开始被废弃,请使用 localStream.play 设置本地流预览镜像,参考文档:").concat(eC,"/zh-cn/LocalStream.html#play。"))}var t,n,s,c,d;return u(e,[{key:"installEvents",value:function(){Tw.on(301,this.restartPlayback,this)}},{key:"uninstallEvents",value:function(){Tw.off(301,this.restartPlayback,this)}},{key:"getType",value:function(){return this.type_}},{key:"getLogger",value:function(){return this.log_}},{key:"isSubscribed",get:function(){return this.type_===eI&&this.connection_.isMainStreamSubscribed||this.type_===tI&&this.connection_.isAuxStreamSubscribed}},{key:"isMainVideoSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===eI&&e&&e.video}},{key:"isMainAudioSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===eI&&e&&e.audio}},{key:"isAuxVideoSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===tI&&e&&e.auxiliary}},{key:"isSmallVideoSubscribed",get:function(){var e=this.getSubscribedState();return this.type_===eI&&e&&e.smallVideo}},{key:"emitConnectionStateChanged",value:function(e){e.state!==this.connectionState_&&(e.state!==rI&&this.isRemote_&&!this.isSubscribed||(this.emitter_.emit("connection-state-changed",e),this.connectionState_=e.state))}},{key:"setConnection",value:function(e){this.connection_!==e&&(e instanceof XB?(null!==this.connection_&&this.connection_.off(NA,this.emitConnectionStateChanged,this),e.on(NA,this.emitConnectionStateChanged,this)):null===e&&this.connection_.off(NA,this.emitConnectionStateChanged,this),this.connection_=e)}},{key:"getConnection",value:function(){return this.connection_}},{key:"play",value:(d=o(r().mark((function e(t,i){var n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.log_.info("stream ".concat(this.isPlaying_?"update":"start to"," play with elementId: ").concat(t," and options: ").concat(JSON.stringify(i),".")),!this.isPlaying_){e.next=9;break}return i&&!ew(i.muted)&&(this.muted_=i.muted),i&&!ew(i.objectFit)&&(this.objectFit_=i.objectFit),this.isScreenShare()?this.mirror_=!1:i&&!ew(i.mirror)&&(this.mirror_=i.mirror),this.audioPlayer_&&this.audioPlayer_.setMuted(this.muted_),this.videoPlayer_&&(this.videoPlayer_.setObjectFit(this.objectFit_),this.videoPlayer_.setMirror(this.mirror_)),this.elementId_!==t&&(n=t,tw(t)&&(n=document.getElementById(t)),n.appendChild(this.div_),this.elementId_=t),e.abrupt("return");case 9:return this.isPlaying_=!0,(s=document.createElement("div")).setAttribute("id","player_".concat(this.id_)),s.setAttribute("style","width: 100%; height: 100%; position: relative; background-color: black; overflow: hidden;"),o=t,tw(t)&&(o=document.getElementById(t)),o.appendChild(s),this.elementId_=t,this.div_=s,this.isRemote_||(this.muted_=!0),i&&!ew(i.muted)&&(this.muted_=i.muted),this.isScreenShare()&&(this.objectFit_="contain"),i&&!ew(i.objectFit)&&(this.objectFit_=i.objectFit),this.isScreenShare()?this.mirror_=!1:(this.isRemote_||(this.mirror_=!0),i&&!ew(i.mirror)&&(this.mirror_=i.mirror)),Tw.emit(132,{stream:this}),e.next=26,Promise.all([this.playAudio(),this.playVideo()]);case 26:Tw.emit(100,{stream:this});case 27:case"end":return e.stop()}}),e,this)}))),function(e,t){return d.apply(this,arguments)})},{key:"playAudio",value:(c=o(r().mark((function e(){var t,n,s=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasAudio()&&(!this.isRemote_||this.isMainAudioSubscribed)){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getAudioTrack(),this.audioPlayer_||!t){e.next=17;break}return this.log_.info("create AudioPlayer and play"),this.audioPlayer_=new yL({stream:this,track:t,gainedTrack:null===(n=this.gain_)||void 0===n?void 0:n.audioTrack,div:this.div_,muted:this.muted_,outputDeviceId:this.audioOutputDeviceId_,volume:this.audioVolume_}),this.audioPlayer_.on(JA,(function(e){var t={type:wT,state:e.state,reason:e.reason};Tw.emit(101,i({stream:s},t)),s.emitter_.emit(GA,t)})),e.prev=7,e.next=10,this.audioPlayer_.play();case 10:e.next=17;break;case 12:throw e.prev=12,e.t0=e.catch(7),this.client_&&this.client_.getEnableAutoPlayDialog()&&new WL,this.emitter_.emit(qA,e.t0),e.t0;case 17:case"end":return e.stop()}}),e,this,[[7,12]])}))),function(){return c.apply(this,arguments)})},{key:"playVideo",value:(s=o(r().mark((function e(){var t,n=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasVideo()&&(!this.isRemote_||this.isMainVideoSubscribed||this.isAuxVideoSubscribed||this.isSmallVideoSubscribed)){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getVideoTrack(),this.videoPlayer_||!t){e.next=18;break}return Tw.emit(134,{stream:this}),this.log_.info("create VideoPlayer and play"),this.videoPlayer_=new GL({stream:this,track:t,div:this.div_,muted:this.muted_,objectFit:this.objectFit_,mirror:this.mirror_}),this.videoPlayer_.on(JA,(function(e){var t={type:RT,state:e.state,reason:e.reason};Tw.emit(101,i({stream:n},t)),n.emitter_.emit(GA,t)})),e.prev=8,e.next=11,this.videoPlayer_.play();case 11:e.next=18;break;case 13:throw e.prev=13,e.t0=e.catch(8),this.client_&&this.client_.getEnableAutoPlayDialog()&&new WL,this.emitter_.emit(qA,e.t0),e.t0;case 18:case"end":return e.stop()}}),e,this,[[8,13]])}))),function(){return s.apply(this,arguments)})},{key:"stopAudio",value:function(){this.audioPlayer_&&(this.log_.info("stop AudioPlayer"),this.audioPlayer_.stop(),this.audioPlayer_=null)}},{key:"stopVideo",value:function(){this.videoPlayer_&&(this.log_.info("stop VideoPlayer"),this.videoPlayer_.stop(),this.videoPlayer_=null)}},{key:"restartPlayback",value:function(){this.audioPlayer_&&!this.audioPlayer_.isPlaying&&this.restartAudio(),this.videoPlayer_&&!this.videoPlayer_.isPlaying&&this.restartVideo()}},{key:"restartAudio",value:function(){this.isPlaying_&&(this.stopAudio(),this.playAudio().catch((function(e){})))}},{key:"restartVideo",value:function(){this.isPlaying_&&(this.stopVideo(),this.playVideo().catch((function(e){})))}},{key:"stop",value:function(){this.isPlaying_&&(this.isPlaying_=!1,this.stopAudio(),this.stopVideo(),this.div_.parentNode.removeChild(this.div_))}},{key:"resume",value:(n=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isPlaying_){e.next=2;break}return e.abrupt("return");case 2:if(this.log_.info("resume"),!this.audioPlayer_){e.next=6;break}return e.next=6,this.audioPlayer_.resume();case 6:if(!this.videoPlayer_){e.next=9;break}return e.next=9,this.videoPlayer_.resume();case 9:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"close",value:function(){this.log_.info("close stream"),this.isPlaying_&&this.stop(),this.isRemote_||(this.mediaStream_&&(this.mediaStream_.preventEvent=1,this.mediaStream_.getTracks().forEach((function(e){e.stop()})),this.mediaStream_=null),this.uninstallEvents())}},{key:"muteAudio",value:function(){return this.addRemoteEvent(!0,wT),this.doEnableTrack(wT,!1)}},{key:"muteVideo",value:function(){return this.addRemoteEvent(!0,RT),this.doEnableTrack(RT,!1)}},{key:"unmuteAudio",value:function(){return this.addRemoteEvent(!1,wT),this.doEnableTrack(wT,!0)}},{key:"unmuteVideo",value:function(){return this.addRemoteEvent(!1,RT),this.doEnableTrack(RT,!0)}},{key:"addRemoteEvent",value:function(e,t){if(this.isRemote_&&this.client_){var i=this.client_.getUserId(),r="".concat(e?OT:LT," remote ").concat(t);ik(i,{eventId:t===wT?e?32785:32787:e?32784:32786,eventDesc:r,timestamp:(new Date).getTime(),userId:i,tinyId:this.client_.getTinyId(),remoteUserId:this.userId_,remoteTinyId:this.connection_.getTinyId()})}}},{key:"doEnableTrack",value:function(e,t){var i=!1;return e===wT?this.mediaStream_.getAudioTracks().forEach((function(e){i=!0,e.enabled=t})):this.mediaStream_.getVideoTracks().forEach((function(e){i=!0,e.enabled=t})),i}},{key:"getId",value:function(){return this.id_}},{key:"getUserId",value:function(){return this.userId_}},{key:"getTinyId",value:function(){return this.connection_?this.connection_.getTinyId():""}},{key:"isPlaying",value:function(){return this.isPlaying_}},{key:"setAudioOutput",value:(t=o(r().mark((function e(t){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.audioOutputDeviceId_=t,!this.audioPlayer_){e.next=4;break}return e.next=4,this.audioPlayer_.setSinkId(t);case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"setAudioVolume",value:function(e){this.audioVolume_=e,this.log_.info("setAudioVolume to ".concat(e)),this.audioPlayer_&&this.audioPlayer_.setVolume(e)}},{key:"getAudioLevel",value:function(){var e=0;return this.audioPlayer_&&(e=this.audioPlayer_.getAudioLevel()),e}},{key:"getInternalAudioLevel",value:function(){var e=0;return this.audioPlayer_&&(e=this.audioPlayer_.getInternalAudioLevel()),e}},{key:"hasAudio",value:function(){if(this.isRemote_){if(!this.connection_)return!1;var e=this.connection_.getTrackState();return this.type_===eI&&e.audio}return!!this.getAudioTrack()}},{key:"hasVideo",value:function(){if(this.isRemote_){if(!this.connection_)return!1;var e=this.connection_.getTrackState();return this.type_===tI?e.auxiliary:e.video}return!!this.getVideoTrack()}},{key:"getSubscribedState",value:function(){return this.isRemote_&&this.connection_?this.connection_.getSubscribeState():null}},{key:"getAudioTrack",value:function(){var e=null;if(this.mediaStream_){var t=this.mediaStream_.getAudioTracks();t.length>0&&(e=t[0])}return e}},{key:"getVideoTrack",value:function(){var e=null;if(this.mediaStream_){var t=this.mediaStream_.getVideoTracks();t.length>0&&(e=t[0])}return e}},{key:"getVideoFrame",value:function(){return this.videoPlayer_?this.videoPlayer_.getVideoFrame():null}},{key:"getMediaStream",value:function(){return this.mediaStream_}},{key:"setMediaStream",value:function(e){e!==this.mediaStream_&&(this.mediaStream_&&this.mediaStream_.getTracks().forEach((function(e){return e.stop()})),this.mediaStream_=e)}},{key:"updateVideoPlayingState",value:function(e){this.isPlaying_&&(e?(this.log_.info("playing state updated, play video"),this.playVideo().catch((function(e){}))):(this.log_.info("playing state updated, stop video"),this.stopVideo()))}},{key:"updateAudioPlayingState",value:function(e){this.isPlaying_&&(e?(this.log_.info("playing state updated, play audio"),this.playAudio().catch((function(e){}))):(this.log_.info("playing state updated, stop audio"),this.stopAudio()))}},{key:"on",value:function(e,t,i){this.emitter_.on(e,t,i)}},{key:"off",value:function(e,t,i){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}},{key:"isRemote",value:function(){return this.isRemote_}},{key:"isScreenShare",value:function(){return!this.isRemote_&&this.screen_||this.isRemote_&&this.getType()===kT}},{key:"getDiv",value:function(){return this.div_}},{key:"getObjectFit",value:function(){return this.objectFit_}},{key:"getMuted",value:function(){return this.muted_}},{key:"getClient",value:function(){return this.client_}}]),e}()).prototype,"play",[iV],Object.getOwnPropertyDescriptor(rV.prototype,"play"),rV.prototype),rV),hV=function(e){l(r,e);var t=_(r);function r(e){var n;a(this,r);var s={isRemote:!0,type:e.type},o=i(i({},e),s);return(n=t.call(this,o)).name_=YI,n.isStreamAddedEventEmitted_=!1,n.isAbleToCallSubscription_=!0,n}return u(r,[{key:"installEvents",value:function(){S(h(r.prototype),"installEvents",this).call(this),Tw.on(Cw,this.handleStreamSubscribed,this),Tw.on(ww,this.handleStreamUnsubscribed,this)}},{key:"uninstallEvents",value:function(){S(h(r.prototype),"uninstallEvents",this).call(this),Tw.off(Cw,this.handleStreamSubscribed,this),Tw.off(ww,this.handleStreamUnsubscribed,this)}},{key:"handleStreamSubscribed",value:function(e){e.client===this.client_&&e.stream===this&&this.connection_.getCurrentState()===oI&&this.emitConnectionStateChanged({prevState:rI,state:oI})}},{key:"handleStreamUnsubscribed",value:function(e){e.client===this.client_&&e.stream===this&&this.emitConnectionStateChanged({prevState:oI,state:rI})}},{key:"getType",value:function(){return S(h(r.prototype),"getType",this).call(this)}},{key:"getIsAbleToCallSubscription",value:function(){return this.isAbleToCallSubscription_}},{key:"setIsAbleToCallSubscription",value:function(e){this.isAbleToCallSubscription_=e}},{key:"setIsStreamAddedEventEmitted",value:function(e){this.isStreamAddedEventEmitted_=e}},{key:"getIsStreamAddedEventEmitted",value:function(){return this.isStreamAddedEventEmitted_}},{key:"getAudioTrack",value:function(){return this.connection_&&this.connection_.getTrackState().audio?S(h(r.prototype),"getAudioTrack",this).call(this):null}},{key:"getVideoTrack",value:function(){if(!this.connection_)return null;var e=this.connection_.getTrackState();return this.type_===eI&&!e.video||this.type_===tI&&!e.auxiliary?null:S(h(r.prototype),"getVideoTrack",this).call(this)}},{key:"close",value:function(){S(h(r.prototype),"close",this).call(this)}}]),r}(lV),mV=function(){function e(t){a(this,e),this.client_=t.client,this.subscribedStreams_=new Map,this.unsubscribedStreams_=new Map,this.subscriptedOptions_=new Map,this.autoRecoveryFlags_=new Map}var t,i,n;return u(e,[{key:"isEnabled",get:function(){return"webrtc"!==this.client_.getEnv()}},{key:"recover",value:(n=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=t.getUserId(),n=t.getType(),this.hasAutoRecoveryFlag(i,n)){e.next=5;break}return e.abrupt("return");case 5:if(s=this.getUnsubscribedStream(i,n)?"unsubscribe":"subscribe",e.prev=6,Mw.warn("recover() try to recover subscription [".concat(s,"][").concat(i,"][").concat(n,"]")),"subscribe"!==s){e.next=13;break}return e.next=11,this.recoverSubscription(i,t);case 11:e.next=15;break;case 13:return e.next=15,this.recoverUnsubscription(i,t);case 15:ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:CI}),Mw.warn("recover() recover successfully [".concat(s,"][").concat(i,"][").concat(n,"]")),e.next=23;break;case 19:e.prev=19,e.t0=e.catch(6),Mw.error("recover() recover failed [".concat(s,"][").concat(i,"][").concat(n,"]"),e.t0),ok.logFailedEvent({userId:this.client_.getUserId(),eventType:CI,error:e.t0});case 23:this.deleteAutoRecoveryFlag(i,n);case 24:case"end":return e.stop()}}),e,this,[[6,19]])}))),function(e){return n.apply(this,arguments)})},{key:"recoverSubscription",value:(i=o(r().mark((function e(t,i){var n,s,o,a,c;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.getOptions(t,i.getType()),s=this.getSubscribedStream(t,i.getType()),n&&s){e.next=4;break}return e.abrupt("return");case 4:o=this.getStreamMuteState(s),a=o.isAudioMuted,c=o.isVideoMuted,this.mergeStream(s,i),this.recoverPlayingState(s),a&&s.doEnableTrack(wT,!1),c&&s.doEnableTrack(RT,!1);case 9:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)})},{key:"recoverUnsubscription",value:(t=o(r().mark((function e(t,i){var n;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.getUnsubscribedStream(t,i.getType())){e.next=3;break}return e.abrupt("return");case 3:this.mergeStream(n,i);case 4:case"end":return e.stop()}}),e,this)}))),function(e,i){return t.apply(this,arguments)})},{key:"getStreamMuteState",value:function(e){var t={isAudioMuted:!1,isVideoMuted:!1},i=e.getMediaStream();return i&&(t.isAudioMuted=i.getAudioTracks().map((function(e){return e.enabled})).includes(!1),t.isVideoMuted=i.getVideoTracks().map((function(e){return e.enabled})).includes(!1)),t}},{key:"recoverPlayingState",value:function(e){var t=e.isPlaying(),i=e.getDiv();if(t&&i){var r=i.parentNode;e.stop(),e.play(r,{objectFit:e.getObjectFit(),muted:e.getMuted()})}}},{key:"mergeStream",value:function(e,t){var i=t.getConnection(),r=t.getMediaStream();e.setConnection(i),i.setRemoteStream(r.id,e),e.setMediaStream(r),e.updateAudioPlayingState(t.hasAudio()),e.updateVideoPlayingState(t.hasVideo())}},{key:"addSubscriptionRecord",value:function(e,t,i){var r=t.getType();if(this.subscribedStreams_.has(e))this.subscribedStreams_.get(e).set(r,t);else{var n=new Map;n.set(t.getType(),t),this.subscribedStreams_.set(e,n)}if(this.subscriptedOptions_.has(e))this.subscriptedOptions_.get(e).set(r,i);else{var s=new Map;s.set(t.getType(),i),this.subscriptedOptions_.set(e,s)}this.deleteUnsubscriptionRecord(e,r)}},{key:"addUnsubscriptionRecord",value:function(e,t){if(this.unsubscribedStreams_.has(e))this.unsubscribedStreams_.get(e).set(t.getType(),t);else{var i=new Map;i.set(t.getType(),t),this.unsubscribedStreams_.set(e,i)}this.deleteSubscriptionRecord(e,t.getType())}},{key:"getSubscribedStream",value:function(e,t){return this.subscribedStreams_.has(e)&&this.subscribedStreams_.get(e).has(t)?this.subscribedStreams_.get(e).get(t):null}},{key:"getOptions",value:function(e,t){return this.subscriptedOptions_.has(e)&&this.subscriptedOptions_.get(e).has(t)?this.subscriptedOptions_.get(e).get(t):null}},{key:"getUnsubscribedStream",value:function(e,t){return this.unsubscribedStreams_.has(e)&&this.unsubscribedStreams_.get(e).has(t)?this.unsubscribedStreams_.get(e).get(t):null}},{key:"deleteSubscriptionRecord",value:function(e,t){this.subscribedStreams_.has(e)&&this.subscribedStreams_.get(e).delete(t),this.subscriptedOptions_.has(e)&&this.subscriptedOptions_.get(e).delete(t)}},{key:"deleteUnsubscriptionRecord",value:function(e,t){this.unsubscribedStreams_.has(e)&&this.unsubscribedStreams_.get(e).delete(t)}},{key:"markAllStream",value:function(){for(var e=0,t=b(this.subscribedStreams_.entries());e<t.length;e++)for(var i=E(t[e],2),r=i[0],n=0,s=b(i[1].entries());n<s.length;n++){var o=E(s[n],1)[0];this.setAutoRecoveryFlag(r,o)}for(var a=0,c=b(this.unsubscribedStreams_.entries());a<c.length;a++)for(var u=E(c[a],2),d=u[0],l=0,h=b(u[1].entries());l<h.length;l++){var m=E(h[l],1)[0];this.setAutoRecoveryFlag(d,m)}}},{key:"setAutoRecoveryFlag",value:function(e,t){if(Mw.info("setAutoRecoveryFlag() mark [".concat(e,"][").concat(t,"]")),this.autoRecoveryFlags_.has(e))this.autoRecoveryFlags_.get(e).set(t);else{var i=new Map;i.set(t),this.autoRecoveryFlags_.set(e,i)}}},{key:"hasAutoRecoveryFlag",value:function(e,t){return!!this.isEnabled&&this.autoRecoveryFlags_.has(e)&&this.autoRecoveryFlags_.get(e).has(t)}},{key:"deleteAutoRecoveryFlag",value:function(e,t){this.autoRecoveryFlags_.has(e)&&this.autoRecoveryFlags_.get(e).delete(t)}},{key:"delete",value:function(e){this.unsubscribedStreams_.delete(e),this.subscribedStreams_.delete(e),this.subscriptedOptions_.delete(e),this.autoRecoveryFlags_.delete(e)}}]),e}(),pV=vC;En({target:"String",proto:!0,forced:_C("small")},{small:function(){return pV(this,"small","","")}});var fV,vV,gV=function(){function e(t){a(this,e),this.player_=t,this.canvas_=document.createElement("canvas"),this.canvasCtx_=this.canvas_.getContext("2d")}return u(e,[{key:"setCanvasRect",value:function(e,t){this.canvas_.width=e,this.canvas_.height=t}},{key:"drawVideoToCanvas",value:function(){var e=this.player_.getElement();this.canvasCtx_.drawImage(e,0,0,this.canvas_.width,this.canvas_.height)}},{key:"generateVideoTrackFromCanvasCapture",value:function(e){return this.canvas_.captureStream(e).getVideoTracks()[0]}},{key:"generateStreamFromTrack",value:function(e){var t=new MediaStream;return t.addTrack(e),t}},{key:"destroy",value:function(){this.player_.stop(),this.canvas_.width=0,this.canvas_.height=0,this.canvas_=null,this.canvasCtx_=null}},{key:"canvas",get:function(){return this.canvas_}},{key:"canvasCtx",get:function(){return this.canvasCtx_}},{key:"canDrawVideoToCanvas",get:function(){if(this.player_){var e=this.player_.getElement();if(e)return e.readyState===e.HAVE_ENOUGH_DATA}return!1}}]),e}(),_V=new Blob(["let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}"],{type:"application/javascript"}),yV=function(){function e(t){a(this,e);var i=t.videoTrack;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:i}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}return u(e,[{key:"initWorker",value:function(){try{this.worker=new Worker(URL.createObjectURL(_V)),Mw.info("init worker processor success")}catch(e){Mw.warn("init worker processor failed. ".concat(e.error))}}},{key:"setCanvasRect",value:function(e,t){this.width=e,this.height=t,this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.offscreen=this.canvas.transferControlToOffscreen(),this.worker.postMessage({action:"render",data:{canvas:this.offscreen,readable:this.bigReadable,writable:this.smallWritable}},[this.offscreen,this.bigReadable,this.smallWritable])}},{key:"generatorVideoTrack",value:function(){var e=new MediaStream([this.smallGenerator]);return null==e?void 0:e.getTracks()[0]}},{key:"destroy",value:function(){this.worker.terminate()}}]),e}(),SV=function(){function e(t){a(this,e),this.localStream_=t,this.player_=null,this.processor_=null,this.initOffscreenSuccess_=!1}var t;return u(e,[{key:"initialize",value:(t=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(RA()&&(null===(t=navigator)||void 0===t?void 0:t.hardwareConcurrency)>=6)){e.next=13;break}return e.prev=1,e.next=4,this.initOffscreen();case 4:this.initOffscreenSuccess_=!0,Mw.info("Initialize VideoGenerator successfully!"),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(1),this.initCanvas();case 11:e.next=14;break;case 13:this.initCanvas();case 14:case"end":return e.stop()}}),e,this,[[1,8]])}))),function(){return t.apply(this,arguments)})},{key:"generateSmallVideoTrack",value:function(e){var t,i=this.getSmallVideoProfile(e);return this.initOffscreenSuccess_?(this.processor_.setCanvasRect(i.width,i.height),t=this.processor_.generatorVideoTrack()):(this.processor_.setCanvasRect(i.width,i.height),this.player_.setRect({width:i.width,height:i.height}),t=this.processor_.generateVideoTrackFromCanvasCapture(i.frameRate),this.interval_=Qk.run(uC,this.render.bind(this),{fps:i.frameRate})),t}},{key:"render",value:function(){this.processor_.canDrawVideoToCanvas&&this.processor_.drawVideoToCanvas()}},{key:"destroy",value:function(){Qk.clearTask(this.interval_),this.processor_&&this.processor_.destroy()}},{key:"initOffscreen",value:function(){this.processor_=new yV({videoTrack:this.localStream_.getVideoTrack()})}},{key:"initCanvas",value:function(){this.player_=new GL({stream:this.localStream_,track:this.localStream_.getVideoTrack(),muted:!0,objectFit:"cover",mirror:!1}),this.player_.play().then((function(){Mw.info("VideoGenerator: play local video success")})).catch((function(){Mw.error("VideoGenerator: Failed to play local video")})),this.processor_=new gV(this.player_)}},{key:"getSmallVideoProfile",value:function(e){var t,i=this.localStream_.getVideoTrack(),r=this.localStream_.getVideoProfile(),n=i.getSettings(),s=n&&n.width&&n.height?{width:n.width,height:n.height}:r,o=s.width*s.height,a=e.width*e.height;return Mw.info("big stream resolution: ".concat(s.height,"*").concat(s.width," small stream resolution: ").concat(e.height,"*").concat(e.width," ")),o>a?t=o/a:(Mw.warn("Small stream resolution is larger than big stream, which is invalid. big: ".concat(s.width," * ").concat(s.height," small: ").concat(e.width," * ").concat(e.height)),t=o/19200),{width:parseInt(s.width/Math.sqrt(t)),height:parseInt(s.height/Math.sqrt(t)),frameRate:e.frameRate}}}]),e}();function EV(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{retries:5,timeout:2e3};return function(t,i,r){var n=Rw({retryFunction:r.value,settings:e,onError:e.onError,onRetrying:e.onRetrying,onRetryFailed:e.onRetryFailed});return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return n.apply(this,t)},r}}var bV,TV,IV={voiceActivityDetection:!1},CV=(fV=EV({retries:1,timeout:0,onRetrying:function(e){this.log_.warn("connection timeout, retrying [".concat(e,"]"))},onError:function(e,t,i){e.message.includes("timeout")?(this.reset(),this.initialize(),t()):i(e)}}),w((vV=function(e){l(T,e);var t,i,n,s,c,d,m,p,f,v,g,y,b=_(T);function T(e){var t;return a(this,T),(t=b.call(this,e)).localStream_=null,t.exchangeSDPTimeout_=-1,t.smallGenerator_=null,t.isSDPExchanging_=!1,t.ssrc_={audio:0,video:0,small:0},t.canvasTrack_=null,t}return u(T,[{key:"initialize",value:function(){S(h(T.prototype),"initialize",this).call(this),this.installEvents()}},{key:"reset",value:function(){this.closePeerConnection(),this.uninstallEvents(),this.clearExchangeSDPTimeout(),this.canvasTrack_=null,this.localStream_&&this.localStream_.clearCanvas()}},{key:"close",value:function(){S(h(T.prototype),"close",this).call(this),this.reset(),this.emitConnectionStateChangedEvent(rI),this.smallGenerator_&&(this.smallGenerator_.destroy(),this.smallGenerator_=null)}},{key:"installEvents",value:function(){this.emitter_.on(PA,this.handleError,this),this.emitter_.on(NA,this.handleConnectionStateChange,this)}},{key:"uninstallEvents",value:function(){this.emitter_.off(PA,this.handleError,this),this.emitter_.off(NA,this.handleConnectionStateChange,this)}},{key:"publish",value:(y=o(r().mark((function e(t){var i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localStream_=t,i=t.getMediaStream(),this.log_.info("is publishing stream: ".concat(t.getId())),n=this.localStream_.getAudioTrack(),s=this.localStream_.getVideoTrack(),n&&(o=this.localStream_.getGainedTrack(),this.peerConnection_.addTrack(o||n,i)),!s){e.next=14;break}if((_T||gT)&&ow(s)?(this.canvasTrack_=this.localStream_.genCanvasTrack(s),this.peerConnection_.addTrack(this.canvasTrack_,i)):this.peerConnection_.addTrack(s,i),!this.client_.getIsEnableSmallStream()){e.next=14;break}return this.smallGenerator_=new SV(this.localStream_),e.next=12,this.smallGenerator_.initialize();case 12:a=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_),this.peerConnection_.addTrack(a,i);case 14:return e.next=16,this.connect();case 16:return e.abrupt("return",t);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return y.apply(this,arguments)})},{key:"updateMediaSettings",value:function(e){var t=this,i=this.getMediaSettings(e);this.signalChannel_.sendWaitForResponse({command:"update_constraint_config",data:i,responseCommand:KR.UPDATE_CONSTRAINT_CONFIG_RES}).then((function(e){0!==e.data.code&&t.log_.warn(e.data.message)})).catch(this.log_.warn)}},{key:"getMediaSettings",value:function(e){var t=this,i=this.client_.getSystemResult().detail,r=i.isH264EncodeSupported,n=i.isVp8EncodeSupported,s="";r?s="H264":n&&(s="VP8");var o={videoCodec:s,videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0};return CA?e.getTracks().forEach((function(e){var i=e.getSettings();if(e.kind===wT){var r=1;i.channelCount&&(r=i.channelCount),o.audioChannel=r,o.audioBps=1e3*t.localStream_.getAudioBitrate(),o.audioFs=i.sampleRate}else e.kind===RT&&(t.client_.getIsEnableSmallStream()&&(o.smallVideoWidth=t.client_.smallStreamConfig.width,o.smallVideoHeight=t.client_.smallStreamConfig.height,o.smallVideoFps=t.client_.smallStreamConfig.framerate,o.smallVideoBps=1e3*t.client_.smallStreamConfig.bitrate),o.videoWidth=i.width,o.videoHeight=i.height,o.videoFps=i.frameRate,o.videoBps=1e3*t.localStream_.getVideoBitrate())})):o=this.getMediaSettingsFromProfile(o),this.log_.info("updateMediaSettings: "+JSON.stringify(o)),o}},{key:"getMediaSettingsFromProfile",value:function(e){var t=this.localStream_;if(t){if(t.getAudioTrack()){var i=t.getAudioProfile();e.audioChannel=i.channelCount,e.audioBps=1e3*i.bitrate,e.audioFs=i.sampleRate}if(t.getVideoTrack()){var r=t.getVideoProfile();e.videoWidth=r.width,e.videoHeight=r.height,e.videoFps=r.frameRate,e.videoBps=1e3*r.bitrate}}return e}},{key:"addTrack",value:(g=o(r().mark((function e(t){var i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.peerConnection_){e.next=25;break}if(t.kind===RT&&(_T||gT)&&ow(t)&&(t=this.canvasTrack_=this.localStream_.genCanvasTrack(t)),this.log_.info("is adding ".concat(t.kind," track to current published local stream")),!(hA()&&this.peerConnection_.getTransceivers().findIndex((function(e){return"stopped"===e.direction}))>=0)){e.next=7;break}return this.log_.warn("transceiver is stopping, negotiate sdp first"),e.next=7,this.updateOffer(FI,t);case 7:if(!(i=this.peerConnection_.getSenders().find((function(e){return e.track&&e.track.kind===t.kind})))){e.next=14;break}return this.log_.warn("sender already exists, remove sender first"),n=i.track,this.removeSender(i),e.next=14,this.updateOffer(FI,n);case 14:if(s=this.localStream_.getMediaStream(),this.peerConnection_.addTrack(t,s),t.kind!==RT||!this.client_.getIsEnableSmallStream()){e.next=22;break}return this.smallGenerator_=new SV(this.localStream_),e.next=20,this.smallGenerator_.initialize();case 20:o=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_),this.peerConnection_.addTrack(o,s);case 22:return e.next=24,this.updateOffer(VI,t);case 24:ik(this.userId_,{eventId:t.kind===wT?32769:32768,eventDesc:"add ".concat(t.kind," track to current published stream"),timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_});case 25:case"end":return e.stop()}}),e,this)}))),function(e){return g.apply(this,arguments)})},{key:"isNeedToResetOfferOrder",value:function(){if("plan-b"===this.sdpSemantics_||!this.peerConnection_||!this.peerConnection_.localDescription)return!1;for(var e=this.peerConnection_.localDescription.sdp,t=Tk(e),i=0;i<t.media.length;i++)if(0===t.media[i].mid&&t.media[i].type===RT)return!0;return!1}},{key:"removeSender",value:function(e){var t=null;hA()&&(t=this.peerConnection_.getTransceivers().find((function(t){return t.sender&&t.sender.track===e.track}))),this.peerConnection_.removeTrack(e),t&&ZC(t.stop)&&(this.log_.info("stop transceiver"),t.stop())}},{key:"removeTrack",value:(v=o(r().mark((function e(t){var i,n,s=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.peerConnection_||!lA()){e.next=15;break}if(t.kind===RT&&(_T||gT)&&this.canvasTrack_&&(t=this.canvasTrack_,this.localStream_.clearCanvas()),this.log_.info("is removing ".concat(t.kind," track from current published local stream")),t.kind!==RT||!this.isNeedToResetOfferOrder()){e.next=10;break}return this.reset(),this.initialize(),null===(i=this.localStream_.getMediaStream())||void 0===i||i.removeTrack(t),e.next=9,this.publish(this.localStream_);case 9:return e.abrupt("return");case 10:return(n=this.peerConnection_.getSenders()).forEach((function(e,i){t.kind===wT&&e.track===t&&s.removeSender(e),t.kind===RT&&e.track===t&&1===i&&(s.removeSender(e),n[2]&&s.removeSender(n[2]))})),e.next=14,this.updateOffer(FI,t);case 14:ik(this.userId_,{eventId:t.kind===wT?32771:32770,eventDesc:"remove ".concat(t.kind," track from current published stream"),timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_});case 15:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"replaceTrack",value:(f=o(r().mark((function e(t){var i,n,s,o,a,c,u;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.kind!==RT||!_T&&!gT||!this.canvasTrack_){e.next=2;break}return e.abrupt("return");case 2:if(mA()&&lA()){e.next=4;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"NOT_SUPPORTED_REPLACE_TRACK"})});case 4:if(this.peerConnection_){e.next=6;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:MC})});case 6:if(0!==(i=this.peerConnection_.getSenders()).length){e.next=9;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:MC})});case 9:n=C(i.entries()),e.prev=10,n.s();case 12:if((s=n.n()).done){e.next=28;break}if(o=E(s.value,2),a=o[0],!(c=o[1]).track||c.track.kind!==t.kind){e.next=26;break}if(this.log_.info("is replacing ".concat(2===a?"smallVideo":t.kind," track to current published local stream")),t.kind!==RT){e.next=25;break}if(1===a&&c.replaceTrack(t),2!==a||!this.smallGenerator_){e.next=25;break}return this.smallGenerator_.destroy(),this.smallGenerator_=new SV(this.localStream_),e.next=23,this.smallGenerator_.initialize();case 23:u=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig),c.replaceTrack(u);case 25:t.kind===wT&&c.replaceTrack(t);case 26:e.next=12;break;case 28:e.next=33;break;case 30:e.prev=30,e.t0=e.catch(10),n.e(e.t0);case 33:return e.prev=33,n.f(),e.finish(33);case 36:ik(this.userId_,{eventId:t.kind===wT?32783:32782,eventDesc:"replace ".concat(t.kind," track from current published stream"),timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_});case 37:case"end":return e.stop()}}),e,this,[[10,30,33,36]])}))),function(e){return f.apply(this,arguments)})},{key:"setBandwidth",value:(p=o(r().mark((function e(t,i,n){var s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isUplink_){e.next=2;break}return e.abrupt("return",n);case 2:if(pA()){e.next=4;break}return e.abrupt("return",i===RT?this.updateVideoBandwidthRestriction(n,t):this.updateAudioBandwidthRestriction(n,t));case 4:if(!(s=this.peerConnection_.getSenders().find((function(e){return e.track&&e.track.kind===i})))){e.next=20;break}return(o=s.getParameters()).encodings&&0!==o.encodings.length||(o.encodings=[{}]),"unlimited"===t?delete o.encodings[0].maxBitrate:o.encodings[0].maxBitrate=1e3*t,e.prev=9,e.next=12,s.setParameters(o);case 12:return this.log_.info(i+" bandwidth was set to "+t+" kbps"),e.abrupt("return",n);case 16:return e.prev=16,e.t0=e.catch(9),this.log_.info("failed to set bandwidth by setting maxBitrate: "+e.t0),e.abrupt("return",i===RT?this.updateVideoBandwidthRestriction(n,t):this.updateAudioBandwidthRestriction(n,t));case 20:return e.abrupt("return",n);case 21:case"end":return e.stop()}}),e,this,[[9,16]])}))),function(e,t,i){return p.apply(this,arguments)})},{key:"setSmallStreamBandwidth",value:(m=o(r().mark((function e(t,i){var n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isUplink_){e.next=2;break}return e.abrupt("return",i);case 2:if(pA()){e.next=4;break}return e.abrupt("return",this.updateSmallVideoBandwidthRestriction(i,t));case 4:if(!(n=this.peerConnection_.getSenders().filter((function(e){return e.track&&e.track.kind===RT}))[1])){e.next=20;break}return(s=n.getParameters()).encodings&&0!==s.encodings.length||(s.encodings=[{}]),"unlimited"===t?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=1e3*t,e.prev=9,e.next=12,n.setParameters(s);case 12:return this.log_.info("small stream bandwidth was set to "+t+" kbps"),e.abrupt("return",i);case 16:return e.prev=16,e.t0=e.catch(9),this.log_.info("failed to set small stream bandwidth by setting maxBitrate: "+e.t0),e.abrupt("return",this.updateSmallVideoBandwidthRestriction(i,t));case 20:return e.abrupt("return",i);case 21:case"end":return e.stop()}}),e,this,[[9,16]])}))),function(e,t){return m.apply(this,arguments)})},{key:"updateVideoBandwidthRestriction",value:function(e,t){var i="AS";return Sb&&(i="TIAS",t*=1e3),-1===e.indexOf("b="+i+":")?e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/,"m=video $1\r\nc=IN $2\r\nb="+i+":"+t+"\r\n"):e.replace(new RegExp("b="+i+":.*\r\n"),"b="+i+":"+t+"\r\n")}},{key:"updateAudioBandwidthRestriction",value:function(e,t){var i="AS";return Sb&&(i="TIAS",t*=1e3),e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb="+i+":"+t+"\r\n")}},{key:"updateSmallVideoBandwidthRestriction",value:function(e,t){var i="AS";Sb&&(i="TIAS",t*=1e3);var r=/m=video (.*)\r\nc=IN (.*)\r\n/g,n=[],s=r.exec(e);for(n.push(s);null!==s;)s=r.exec(e),n.push(s);var o=n[n.length-2],a=e.slice(0,o.index),c=e.slice(o.index);return-1===e.indexOf("b="+i+":")?a+(c=c.replace(/m=video (.*)\r\nc=IN (.*)\r\n/,"m=video $1\r\nc=IN $2\r\nb="+i+":"+t+"\r\n")):a+(c=c.replace(new RegExp("b="+i+":.*\r\n"),"b="+i+":"+t+"\r\n"))}},{key:"removeBandwidthRestriction",value:function(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}},{key:"removeVideoOrientation",value:function(e){return e.replace(/urn:3gpp:video-orientation/,"")}},{key:"connect",value:(d=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.exchangeSDP();case 3:return e.next=5,this.waitForPeerConnectionConnected();case 5:e.next=11;break;case 7:throw e.prev=7,e.t0=e.catch(0),this.closePeerConnection(!0),e.t0;case 11:case"end":return e.stop()}}),e,this,[[0,7]])}))),function(){return d.apply(this,arguments)})},{key:"exchangeSDP",value:(c=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,this.isSDPExchanging_=!0,e.next=4,this.createOffer();case 4:return this.log_.info("createOffer success, sending offer to remote server"),e.next=7,this.doExchangeSDP();case 7:this.isSDPExchanging_=!1,e.next=14;break;case 10:throw e.prev=10,e.t0=e.catch(0),this.isSDPExchanging_=!1,e.t0;case 14:case"end":return e.stop()}}),e,this,[[0,10]])}))),function(){return c.apply(this,arguments)})},{key:"createOffer",value:(s=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.peerConnection_.createOffer(IV);case 3:return t=e.sent,e.next=6,this.peerConnection_.setLocalDescription(t);case 6:this.updateSSRC(t.sdp),ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:_I,kind:"offer"}),e.next=14;break;case 10:throw e.prev=10,e.t0=e.catch(0),ok.logFailedEvent({userId:this.client_.getUserId(),eventType:_I,kind:"offer",error:e.t0}),e.t0;case 14:case"end":return e.stop()}}),e,this,[[0,10]])}))),function(){return s.apply(this,arguments)})},{key:"doExchangeSDP",value:function(){var e=this;return new Promise((function(t,i){e.exchangeSDPTimeout_=setTimeout((function(){e.signalChannel_.off(KR.PUBLISH_RESULT,n),e.clearExchangeSDPTimeout();var t=new ek({code:ZR.API_CALL_TIMEOUT,message:GC({key:"EXCHANGE_SDP_TIMEOUT"})});i(t)}),1e4);var n=function(){var n=o(r().mark((function n(s){var o,a,c;return r().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(r.prev=0,e.clearExchangeSDPTimeout(),o=s.data,a=o.code,c=o.message,0!==a){r.next=9;break}return r.next=6,e.acceptAnswer(s.data.data);case 6:t(),r.next=10;break;case 9:e.checkPublishResultCode(a,c);case 10:r.next=15;break;case 12:r.prev=12,r.t0=r.catch(0),i(r.t0);case 15:case"end":return r.stop()}}),n,null,[[0,12]])})));return function(e){return n.apply(this,arguments)}}(),s=e.getMediaSettings(e.localStream_.getMediaStream()),a={type:e.peerConnection_.localDescription.type,sdp:e.removeVideoOrientation(e.peerConnection_.localDescription.sdp),screen:e.localStream_.hasScreenTrack(),constraintConfig:s};e.signalChannel_.once(KR.PUBLISH_RESULT,n),e.log_.debug("sending sdp offer: "+a.sdp),e.signalChannel_.send("publish",a)}))}},{key:"setSDPDirection",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=Tk(e);return r.media.forEach((function(e){"all"!==i&&e.type!==i||(e.direction=t)})),Ik(r)}},{key:"updateOffer",value:(n=o(r().mark((function e(t,i){var n,s,o,a,c,u,d;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.peerConnection_.createOffer(IV);case 3:return n=e.sent,Sb&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),e.next=7,this.peerConnection_.setLocalDescription(n);case 7:return s=this.getMediaSettings(this.localStream_.getMediaStream()),o={action:t,trackId:i.id,kind:i.kind===RT?"bigVideo":i.kind,type:"offer",sdp:this.peerConnection_.localDescription.sdp,constraintConfig:s},this.log_.info("createOffer success, sending updated offer to remote server"),this.log_.debug("updatedOffer: "+o.sdp),e.next=13,this.signalChannel_.sendWaitForResponse({command:"publish_change",data:o,responseCommand:KR.UPDATE_OFFER_RESULT,timeout:1e4,commandDesc:"update offer"});case 13:return a=e.sent,c=a.data,u=c.code,d=c.message,0!==u&&this.checkPublishResultCode(u,d),e.next=18,this.acceptAnswer(a.data.data);case 18:this.updateSSRC(n.sdp),ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:_I,kind:"offer"}),e.next=27;break;case 22:throw e.prev=22,e.t0=e.catch(0),this.log_.error(e.t0),ok.logFailedEvent({userId:this.client_.getUserId(),eventType:_I,kind:"offer",error:e.t0}),e.t0;case 27:case"end":return e.stop()}}),e,this,[[0,22]])}))),function(e,t){return n.apply(this,arguments)})},{key:"acceptAnswer",value:(i=o(r().mark((function e(t){var i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=this.localStream_.getVideoBitrate(),n=this.localStream_.getAudioBitrate(),e.prev=2,s=this.removeVideoOrientation(t.sdp),e.next=6,this.setBandwidth(i,RT,s);case 6:return s=e.sent,e.next=9,this.setBandwidth(n,wT,s);case 9:if(s=e.sent,!this.client_.getIsEnableSmallStream()){e.next=15;break}return o=this.client_.smallStreamConfig,e.next=14,this.setSmallStreamBandwidth(o.bitrate,s);case 14:s=e.sent;case 15:return a={type:t.type,sdp:s},e.next=18,this.peerConnection_.setRemoteDescription(a);case 18:this.sei_&&this.sei_.handleEncodedStreams(),this.log_.debug("accepted answer: "+s),ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:yI,kind:"answer"}),e.next=28;break;case 23:throw e.prev=23,e.t0=e.catch(2),ok.logFailedEvent({userId:this.client_.getUserId(),eventType:yI,kind:"answer",error:e.t0}),this.log_.error("failed to accept remote answer "+e.t0),e.t0;case 28:case"end":return e.stop()}}),e,this,[[2,23]])}))),function(e){return i.apply(this,arguments)})},{key:"sendMutedFlag",value:function(e){var t={audio:e.audio,bigVideo:e.video,auxVideo:e.auxVideo};this.log_.info("send muted state: ".concat(JSON.stringify(t))),this.signalChannel_.send("mute_uplink",t)}},{key:"getIsReconnecting",value:function(){return this.isReconnecting_}},{key:"reconnect",value:(t=o(r().mark((function e(){var t,i,n=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(-1===this.reconnectionTimer_){e.next=3;break}return this.log_.warn("reconnect() uplink is reconnecting, ignore current reconnection"),e.abrupt("return");case 3:if(!(this.reconnectionCount_>=30)){e.next=12;break}return this.log_.warn("SDK has tried reconnect uplink for ".concat(30," times, but all failed, please check your network")),this.stopReconnection(),t=new ek({code:ZR.UPLINK_RECONNECTION_FAILED,message:GC({key:"UPLINK_RECONNECTION_FAILED"})}),ok.logFailedEvent({userId:this.client_.getUserId(),eventType:fI,error:t}),this.addEventInternal(32799,"uplink-connection reconnect fail"),this.emitConnectionStateChangedEvent(rI),this.emitter_.emit(PA,t),e.abrupt("return");case 12:if(this.signalChannel_.getCurrentState()===zR){e.next=16;break}return this.log_.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this.signalChannel_.once(3,this.reconnect,this),e.abrupt("return");case 16:if(this.reconnectionCount_++,e.prev=17,this.log_.warn("reconnect() try to reconnect uplink [".concat(this.reconnectionCount_,"/").concat(30,"]")),i=XC(this.reconnectionCount_),this.reconnectionTimer_=setTimeout((function(){n.log_.warn("reconnect() uplink reconnect timeout(".concat(i/1e3,"s), try again")),n.clearReconnectionTimer(),n.reconnect()}),i),!(this.isSDPExchanging_||this.peerConnection_&&this.peerConnection_.connectionState===aI)){e.next=23;break}return e.abrupt("return");case 23:return e.next=25,this.signalChannel_.sendWaitForResponse({command:XR,responseCommand:KR.UNPUBLISH_RESULT,enableLog:!1});case 25:return this.reset(),this.initialize(),e.next=29,this.publish(this.localStream_);case 29:ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:fI}),this.log_.warn("reconnect() uplink reconnect successfully"),this.addEventInternal(32798,"uplink-connection reconnect success"),this.stopReconnection(),this.localStream_.syncMuteState(),e.next=38;break;case 36:e.prev=36,e.t0=e.catch(17);case 38:case"end":return e.stop()}}),e,this,[[17,36]])}))),function(){return t.apply(this,arguments)})},{key:"clearExchangeSDPTimeout",value:function(){-1!==this.exchangeSDPTimeout_&&(clearTimeout(this.exchangeSDPTimeout_),this.exchangeSDPTimeout_=-1)}},{key:"clearReconnectionTimer",value:function(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}},{key:"handleError",value:function(e){e.getCode()===ZR.ICE_TRANSPORT_ERROR&&(this.isFirstConnection_&&(this.isFirstConnection_=!1,ok.logFailedEvent({userId:this.client_.getUserId(),eventType:pI,error:e})),this.isReconnecting_||this.startReconnection())}},{key:"handleConnectionStateChange",value:function(e){e.state===oI&&this.isFirstConnection_&&(this.isFirstConnection_=!1,ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:pI}),this.addEventInternal(32792,"uplink-connection is connected"))}},{key:"updateSSRC",value:function(e){var t=this;try{var i=0;Tk(e).media.forEach((function(e){if(e.type===wT){var r=e.ssrcs[0];r&&(t.ssrc_.audio=r.id)}else{var n=e.ssrcs[0];switch(i+=1){case 1:n&&(t.ssrc_.video=n.id);break;case 2:n&&(t.ssrc_.small=n.id)}}}))}catch(e){}}},{key:"getLocalStreamVideoTrackId",value:function(){if(this.peerConnection_){var e=this.peerConnection_.getSenders().filter((function(e){return e.track&&e.track.kind===RT}));if(e[0])return e[0].track.id}if(this.localStream_){var t=this.localStream_.getVideoTrack();if(t)return t.id}return""}},{key:"getSSRC",value:function(){return this.ssrc_}},{key:"checkPublishResultCode",value:function(e,t){if(0!==e)throw 1028===e?(this.log_.error(HC.NOT_SUPPORTED_H264ENCODE),new ek({code:ZR.NOT_SUPPORTED_H264,message:GC({key:xC})})):new ek({code:ZR.UNKNOWN,message:GC({key:$C,data:{signalResponse:KR.PUBLISH_RESULT,code:e,message:t}})})}},{key:"getLocalStream",value:function(){return this.localStream_}},{key:"sendSEI",value:function(e,t){this.sei_.push(e,t)}}]),T}(XB)).prototype,"publish",[fV],Object.getOwnPropertyDescriptor(vV.prototype,"publish"),vV.prototype),vV),wV=(bV=EV({retries:1,timeout:0,onRetrying:function(e){this.log_.warn("connection timeout, retrying [".concat(e,"]"))},onError:function(e,t,i){e.message.includes("timeout")?t():i(e)}}),w((TV=function(e){l(v,e);var t,n,s,c,d,m,p,f=_(v);function v(e){var t;return a(this,v),(t=f.call(this,e)).remoteStreams_=new Map,t.autoSubscribe=e.autoSubscribe,t.trackState_={audio:e.trackState.audio,video:e.trackState.video,auxiliary:e.trackState.auxiliary,smallVideo:e.trackState.smallVideo},t.ssrc_={audio:0,video:0,auxiliary:0},t.subscribeState_={audio:e.autoSubscribe,video:e.autoSubscribe,auxiliary:e.autoSubscribe,smallVideo:!1},t.isSDPExchanging_=!1,t.installEvents(),t}return u(v,[{key:"isMainStreamSubscribed",get:function(){return(this.subscribeState_.audio||this.subscribeState_.video||this.subscribeState_.smallVideo)&&(this.trackState_.audio||this.trackState_.video||this.trackState_.smallVideo)}},{key:"isAuxStreamSubscribed",get:function(){return this.subscribeState_.auxiliary&&this.trackState_.auxiliary}},{key:"isSmallStreamSubscribed",get:function(){return this.subscribeState_.smallVideo&&this.trackState_.smallVideo}},{key:"isBigStreamSubscribed",get:function(){return this.subscribeState_.video&&this.trackState_.video}},{key:"isStreamUnpublished",value:function(e){return e.getType()===VT?!this.trackState_.audio&&!this.trackState_.video:!this.trackState_.auxiliary}},{key:"initialize",value:function(){S(h(v.prototype),"initialize",this).call(this),this.peerConnection_.ontrack=this.onTrack.bind(this)}},{key:"close",value:function(){var e=this;S(h(v.prototype),"close",this).call(this),this.trackState_.audio=!1,this.trackState_.video=!1,this.trackState_.auxiliary=!1,this.emitConnectionStateChangedEvent(rI),this.remoteStreams_.forEach((function(t){var i=t;i.setConnection(null),i.uninstallEvents(),i.getIsStreamAddedEventEmitted()&&e.emitter_.emit(MA,{stream:i})})),this.remoteStreams_.clear(),this.uninstallEvents()}},{key:"installEvents",value:function(){var e=this;Tw.on(Iw,this.onRemoteStreamUpdate,this),this.emitter_.on(PA,(function(t){t.getCode()===ZR.ICE_TRANSPORT_ERROR&&(e.isFirstConnection_&&(e.isFirstConnection_=!1,ok.logFailedEvent({userId:e.client_.getUserId(),eventType:vI,error:t})),e.isReconnecting_||e.startReconnection())})),this.emitter_.on(NA,(function(t){t.state===oI&&e.isFirstConnection_&&(e.isFirstConnection_=!1,ok.logSuccessEvent({userId:e.client_.getUserId(),eventType:vI}),e.addEventInternal(32793,"downlink-connection is connected"))}))}},{key:"uninstallEvents",value:function(){Tw.removeListener(Iw,this.onRemoteStreamUpdate,this)}},{key:"onRemoteStreamUpdate",value:function(e){if(this.hitTest(e.tinyId)&&e.client===this.client_){this.updateTrackState(e.action,e.kind);var t=e.kind===kT?ZT:XT,i=this.remoteStreams_.get(t);if(!i)return;e.action===VI?this.handleRemoteAddTrack(e.kind,i):this.handleRemoteRemoveTrack(e.kind,i)}}},{key:"handleRemoteAddTrack",value:function(e,t){this.log_.info("remote add ".concat(e," track")),e===wT?t.updateAudioPlayingState(this.subscribeState_.audio):t.updateVideoPlayingState(e===kT?this.subscribeState_.auxiliary:this.subscribeState_.video||this.subscribeState_.smallVideo),t.getIsStreamAddedEventEmitted()?this.emitter_.emit(OA,{stream:t}):(this.emitter_.emit(AA,{stream:t}),this.currentState_===oI&&t.emitConnectionStateChanged({prevState:rI,state:oI}))}},{key:"handleRemoteRemoveTrack",value:function(e,t){t.getIsStreamAddedEventEmitted()&&(this.log_.info("remote remove ".concat(e," track")),e===kT||!this.trackState_.audio&&!this.trackState_.video?(this.log_.info("remote stream ".concat(t.getType()," removed")),this.currentState_===oI&&t.emitConnectionStateChanged({prevState:oI,state:rI}),this.emitter_.emit(MA,{stream:t})):(e===wT?t.updateAudioPlayingState(!1):(e!==AT||this.isSmallStreamSubscribed)&&t.updateVideoPlayingState(!1),this.emitter_.emit(OA,{stream:t})))}},{key:"updateTrackState",value:function(e,t){var i=e===VI;switch(t){case wT:this.trackState_.audio=i;break;case RT:this.trackState_.video=i;break;case kT:this.trackState_.auxiliary=i;break;case AT:this.trackState_.smallVideo=i}this.log_.info("trackState updated: ".concat(JSON.stringify(this.trackState_)))}},{key:"onTrack",value:function(e){var t=e.streams[0],i=e.track;if(this.log_.info("ontrack() kind: ".concat(i.kind," id: ").concat(i.id," streamId: ").concat(t.id)),this.sdpSemantics_===PI){var r=function(e){var t=hk.parse(e),i={audio:[],video:[]};return t.media.forEach((function(e){if(e.ssrcs){var t=e.ssrcs[0].id>>16&255;if(e.type===wT)i.audio.push(XT);else if(e.type==RT){var r=2===t?XT:ZT;i.video.push(r)}}})),i}(this.peerConnection_.remoteDescription.sdp);if(i.kind===wT){if(0===r.audio.length||t.id!==XT)return void this.log_.debug("skip this invalid audio track")}else if(-1===r.video.indexOf(t.id))return void this.log_.debug("skip this invalid video track: ".concat(i.id," msid: ").concat(t.id))}ok.logEvent({eventType:"ontrack",kind:i.kind});var n=!1,s=this.remoteStreams_.get(t.id),o=t.id===XT?eI:tI;if(ew(s)&&((s=new hV({type:o,userId:this.userId_,client:this.client_})).setConnection(this),this.remoteStreams_.set(t.id,s),n=!0),s.setMediaStream(t),i.kind===wT?s.updateAudioPlayingState(this.subscribeState_.audio):o===eI?s.updateVideoPlayingState(this.subscribeState_.video||this.subscribeState_.smallVideo):s.updateVideoPlayingState(this.subscribeState_.auxiliary),(o!==tI||this.trackState_.auxiliary)&&(o!==eI||this.trackState_.audio||this.trackState_.video)){var a=this.client_.getSubscriptionManager();a&&a.hasAutoRecoveryFlag(this.userId_,o)||(n?this.emitter_.emit(AA,{stream:s}):this.emitter_.emit(OA,{stream:s}))}}},{key:"addRRTRLine",value:function(e){var t=e.split("\r\n"),i=new Map;t.forEach((function(e,r){/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,e.match(/^a=rtcp-fb:\d+/)[0]+" rrtr")}));for(var r=b(i),n=0;n<r.length;n++){var s=E(r[n],2),o=s[0],a=s[1];t.splice(o+n,0,a)}return t.join("\r\n")}},{key:"addSPSDescription",value:function(e){var t=Tk(e);return t.media.forEach((function(e){e.type===RT&&e.fmtp.forEach((function(e){e.config+=";sps-pps-idr-in-keyframe=1"}))})),Ik(t)}},{key:"removeSDESDescription",value:function(e){var t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=Tk(e);return i.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!t.includes(e.uri)}))})),Ik(i)}},{key:"isSubscriptionStateNotChanged",value:function(e,t){return e.getType()===eI?(null==t?void 0:t.audio)===this.subscribeState_.audio&&(null==t?void 0:t.video)===this.subscribeState_.video&&this.isSubscribeSmall(t):e.getType()===tI?!ew(t.video)&&this.subscribeState_.auxiliary===t.video:void 0}},{key:"isSubscribeSmall",value:function(e){return ew(e.smallVideo)&&!this.subscribeState_.smallVideo}},{key:"subscribe",value:(p=o(r().mark((function e(t,i){var n,s,o,a,c,u;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,o=i.emitEvent,a=void 0===o||o,c=t.getType(),"new"!==(null===(n=this.peerConnection_)||void 0===n?void 0:n.connectionState)&&(null===(s=this.peerConnection_)||void 0===s?void 0:s.connectionState)!==aI){e.next=6;break}return e.next=6,this.waitForPeerConnectionConnected();case 6:if(!this.isSubscriptionStateNotChanged(t,i)){e.next=13;break}if(this.peerConnection_){e.next=11;break}return this.initialize(),e.next=11,this.connect();case 11:case 26:return a&&ew(i.smallVideo)&&this.emitter_.emit(LA,{stream:t,result:!0}),e.abrupt("return",t);case 13:if(c===VT?(ew(i.audio)||(this.subscribeState_.audio=i.audio),ew(i.video)||(this.subscribeState_.video=i.video),this.subscribeState_.smallVideo=(null==i?void 0:i.smallVideo)||!1,this.addEventInternal(this.subscribeState_.audio?32777:32779,this.subscribeState_.audio?"subscribe audio":"unsubscribe audio"),this.addEventInternal(this.subscribeState_.video?32777:32779,this.subscribeState_.video?"subscribe video":"unsubscribe video"),this.addEventInternal(this.subscribeState_.smallVideo?32803:32804,this.subscribeState_.smallVideo?"subscribe smallVideo":"unsubscribe smallVideo")):ew(i.video)||(this.subscribeState_.auxiliary=i.video),this.log_.info("subscribe ".concat(c," stream with options ").concat(JSON.stringify(i)," current state: ").concat(JSON.stringify(this.subscribeState_))),!this.peerConnection_&&!this.isSDPExchanging_){e.next=23;break}return u=LI,this.isMainStreamSubscribed||this.isAuxStreamSubscribed||(u=OI),e.next=20,this.sendSubscription(u);case 20:c===VT?(t.updateAudioPlayingState(this.subscribeState_.audio),t.updateVideoPlayingState(this.subscribeState_.video||this.subscribeState_.smallVideo)):t.updateVideoPlayingState(this.subscribeState_.auxiliary),e.next=26;break;case 23:return this.initialize(),e.next=26,this.connect();case 30:if(e.prev=30,e.t0=e.catch(0),!this.client_.getIsJoined()||!this.isStreamUnpublished(t)){e.next=35;break}throw this.log_.warn("".concat(e.t0.message," ").concat(JSON.stringify(this.trackState_))),new ek({code:ZR.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId_," unpublished stream")});case 35:throw e.t0;case 36:case"end":return e.stop()}}),e,this,[[0,30]])}))),function(e,t){return p.apply(this,arguments)})},{key:"unsubscribe",value:(m=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((i=t.getType())!==VT){e.next=10;break}if(this.isMainStreamSubscribed){e.next=5;break}return this.log_.info("main stream already unsubscribed"),e.abrupt("return",t);case 5:this.subscribeState_.audio=!1,this.subscribeState_.video=!1,this.subscribeState_.smallVideo=!1,e.next=14;break;case 10:if(this.isAuxStreamSubscribed){e.next=13;break}return this.log_.info("auxiliary stream already unsubscribed"),e.abrupt("return",t);case 13:this.subscribeState_.auxiliary=!1;case 14:return n=OI,(i===eI&&this.isAuxStreamSubscribed||i===tI&&this.isMainStreamSubscribed)&&(n=LI),this.log_.info("unsubscribe ".concat(i," stream with ").concat(JSON.stringify(this.subscribeState_))),e.next=19,this.sendSubscription(n);case 19:return t.updateVideoPlayingState(!1),t.updateAudioPlayingState(!1),n===OI&&((s=t.getMediaStream())&&s.getTracks().forEach((function(e){return s.removeTrack(e)})),this.closePeerConnection(),this.emitConnectionStateChangedEvent(rI)),this.addEventInternal(32779,"unsubscribe audio"),this.addEventInternal(32778,"unsubscribe video"),e.abrupt("return",t);case 25:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"sendSubscription",value:function(e){var t=this,i={srcTinyId:this.tinyId_,srcUserId:this.userId_},r="unsubscribe",n=KR.UNSUBSCRIBE_RESULT;return e===LI&&(i={audio:this.subscribeState_.audio,bigVideo:this.subscribeState_.video,auxVideo:this.subscribeState_.auxiliary,smallVideo:this.subscribeState_.smallVideo,srcTinyId:this.tinyId_},r="subscribe_change",n=KR.SUBSCRIBE_CHANGE_RESULT),this.signalChannel_.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then((function(i){var r=i.data;if(0!==r.code){var n=new ek({code:r.code,message:GC({key:"ERROR_MESSAGE",data:{type:e,message:r.message}})});throw t.log_.error(n),n}}))}},{key:"connect",value:(d=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.exchangeSDP();case 3:return e.next=5,this.waitForPeerConnectionConnected();case 5:e.next=11;break;case 7:throw e.prev=7,e.t0=e.catch(0),this.closePeerConnection(!0),e.t0;case 11:case"end":return e.stop()}}),e,this,[[0,7]])}))),function(){return d.apply(this,arguments)})},{key:"exchangeSDP",value:(c=o(r().mark((function e(){var t,i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,this.isSDPExchanging_=!0,e.next=4,this.createOffer();case 4:return this.log_.info("createOffer success, sending offer to remote server"),t=this.peerConnection_.localDescription,i=t.type,n=t.sdp,s={type:i,sdp:n,srcUserId:this.userId_,srcTinyId:this.tinyId_,audio:this.subscribeState_.audio,bigVideo:this.subscribeState_.video,auxVideo:this.subscribeState_.auxiliary,smallVideo:this.subscribeState_.smallVideo},Tw.emit(201,{client:this.client_,connection:this,userId:this.userId_,tinyId:this.tinyId_,role:20,subscribeState:this.subscribeState_,trackState:this.trackState_}),e.next=10,this.signalChannel_.sendWaitForResponse({command:"subscribe",commandDesc:"exchange sdp",data:s,responseCommand:KR.SUBSCRIBE_RESULT,timeout:1e4});case 10:if(o=e.sent,this.peerConnection_){e.next=15;break}throw a=new ek({code:ZR.INVALID_OPERATION,message:GC({key:"STREAM_UNSUBSCRIBED"})}),this.log_.warn(a),a;case 15:return e.next=17,this.onSubscribeResult(o);case 17:this.isSDPExchanging_=!1,e.next=24;break;case 20:throw e.prev=20,e.t0=e.catch(0),this.isSDPExchanging_=!1,e.t0;case 24:case"end":return e.stop()}}),e,this,[[0,20]])}))),function(){return c.apply(this,arguments)})},{key:"createOffer",value:(s=o(r().mark((function e(){var t,i;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={voiceActivityDetection:!1},"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype&&this.sdpSemantics_===PI?(this.peerConnection_.addTransceiver(wT,{direction:"recvonly"}),this.peerConnection_.addTransceiver(RT,{direction:"recvonly"}),this.peerConnection_.addTransceiver(RT,{direction:"recvonly"})):(t.offerToReceiveAudio=!0,t.offerToReceiveVideo=!0),e.next=4,this.peerConnection_.createOffer(t);case 4:return i=e.sent,e.next=7,oA();case 7:return e.sent.isH264DecodeSupported||(this.log_.warn("remove h264 desc from sdp"),i.sdp=wk(i.sdp)),i.sdp=this.addRRTRLine(i.sdp),i.sdp=this.addSPSDescription(i.sdp),i.sdp=Ck(i.sdp),this.sdpSemantics_===PI&&(i.sdp=this.removeSDESDescription(i.sdp)),e.next=16,this.peerConnection_.setLocalDescription(i);case 16:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"onSubscribeResult",value:(n=o(r().mark((function e(t){var n,s,o,a,c,u,d,l=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t&&t.data||{},s=n.code,o=n.message,a=void 0===o?"":o,c=t&&t.data&&t.data.data||{},u=c.type,d=c.sdp,77393!==s){e.next=5;break}throw this.log_.error(HC.NOT_SUPPORTED_H264DECODE),new ek({code:ZR.NOT_SUPPORTED_H264,message:GC({key:UC})});case 5:if(e.prev=5,0===s){e.next=8;break}throw new ek({code:s,message:GC({key:"EXCHANGE_SDP_FAILED",data:{errMsg:a}})});case 8:return this.log_.debug("accept remote answer: "+d),e.next=11,this.peerConnection_.setRemoteDescription({type:u,sdp:d});case 11:this.sei_&&(this.sei_.handleEncodedStreams(),this.sei_.onSEIMessage=function(e){l.emitter_.emit(DA,i(i({},e),{},{userId:l.userId_}))}),this.updateSSRC(d),e.next=19;break;case 15:throw e.prev=15,e.t0=e.catch(5),this.log_.error(e.t0),e.t0;case 19:case"end":return e.stop()}}),e,this,[[5,15]])}))),function(e){return n.apply(this,arguments)})},{key:"updateSSRC",value:function(e){var t=this;try{Tk(e).media.forEach((function(e){if(e.type===wT){var i=e.ssrcs.find((function(e){return e.value.includes(XT)}));i&&(t.ssrc_.audio=i.id)}else{var r=e.ssrcs.find((function(e){return e.value.includes(XT)})),n=e.ssrcs.find((function(e){return e.value.includes(ZT)}));r&&(t.ssrc_.video=r.id),n&&(t.ssrc_.auxiliary=n.id)}}))}catch(e){}}},{key:"setRemoteStream",value:function(e,t){this.remoteStreams_.set(e,t)}},{key:"getSubscribeState",value:function(){return this.subscribeState_}},{key:"getTrackState",value:function(){return this.trackState_}},{key:"getSSRC",value:function(){return this.ssrc_}},{key:"getMainStream",value:function(){return this.remoteStreams_.get(XT)}},{key:"getAuxStream",value:function(){return this.remoteStreams_.get(ZT)}},{key:"getMainStreamVideoTrackId",value:function(){var e=this.getMainStream();if(e){var t=e.getVideoTrack();if(t)return t.id}return""}},{key:"getAuxStreamVideoTrackId",value:function(){var e=this.getAuxStream();if(e){var t=e.getVideoTrack();if(t)return t.id}return""}},{key:"reconnect",value:(t=o(r().mark((function e(){var t,i,n=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(-1===this.reconnectionTimer_){e.next=3;break}return this.log_.warn("reconnect() downlink is reconnecting, ignore current reconnection"),e.abrupt("return");case 3:if(!(this.reconnectionCount_>=30)){e.next=12;break}return this.log_.warn("SDK has tried reconnect downlink [".concat(this.userId_,"] for ").concat(30," times, but all failed, please check your network")),this.stopReconnection(),t=new ek({code:ZR.DOWNLINK_RECONNECTION_FAILED,message:GC({key:"DOWNLINK_RECONNECTION_FAILED"})}),ok.logFailedEvent({userId:this.client_.getUserId(),eventType:gI,error:t}),this.addEventInternal(32802,"downlink-connection reconnect fail"),this.emitConnectionStateChangedEvent(rI),this.emitter_.emit(PA,t),e.abrupt("return");case 12:if(this.signalChannel_.getCurrentState()===zR){e.next=16;break}return this.log_.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this.signalChannel_.once(3,this.reconnect,this),e.abrupt("return");case 16:if(this.reconnectionCount_++,this.log_.warn("reconnect() try to reconnect downlink [".concat(this.reconnectionCount_,"/").concat(30,"]")),i=XC(this.reconnectionCount_),this.reconnectionTimer_=setTimeout((function(){n.log_.warn("reconnect() downlink [".concat(n.userId_,"] reconnect timeout(").concat(i/1e3,"s), try again")),n.clearReconnectionTimer(),n.reconnect()}),i),!(this.isSDPExchanging_||this.peerConnection_&&this.peerConnection_.connectionState===aI)){e.next=22;break}return e.abrupt("return");case 22:return e.prev=22,this.closePeerConnection(),this.initialize(),e.next=27,this.connect();case 27:this.stopReconnection(),this.log_.warn("reconnect() downlink reconnect successfully"),ok.logSuccessEvent({userId:this.client_.getUserId(),eventType:gI}),this.addEventInternal(32801,"downlink-connection reconnect success"),this.recoverSubscription(),e.next=36;break;case 34:e.prev=34,e.t0=e.catch(22);case 36:case"end":return e.stop()}}),e,this,[[22,34]])}))),function(){return t.apply(this,arguments)})},{key:"recoverSubscription",value:function(){var e=this,t=this.client_.getSubscriptionManager();t&&b(this.remoteStreams_.values()).forEach((function(i){t.hasAutoRecoveryFlag(e.userId_,i.getType())&&t.recover(i)}))}},{key:"getIsReconnecting",value:function(){return this.isReconnecting_}},{key:"getSubscribedMainStream",value:function(){var e=null;return this.isMainStreamSubscribed&&(e=this.remoteStreams_.get(XT)),e}},{key:"clearReconnectionTimer",value:function(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}},{key:"startReconnection",value:function(){var e=this.client_.getSubscriptionManager();if(e){var t,i=C(this.remoteStreams_.values());try{for(i.s();!(t=i.n()).done;){var r=t.value,n=r.getType();(n===eI&&(this.trackState_.audio||this.trackState_.video)||n===tI&&this.trackState_.auxiliary)&&e.setAutoRecoveryFlag(this.userId_,r.getType())}}catch(e){i.e(e)}finally{i.f()}}S(h(v.prototype),"startReconnection",this).call(this)}},{key:"getCurrentState",value:function(){return this.currentState_}},{key:"hasMainStream",value:function(){return this.trackState_.video||this.trackState_.audio||this.trackState_.smallVideo}},{key:"hasAuxStream",value:function(){return this.trackState_.auxiliary}}]),v}(XB)).prototype,"subscribe",[bV],Object.getOwnPropertyDescriptor(TV.prototype,"subscribe"),TV.prototype),TV),RV=function(){function e(){a(this,e),this.startTime=0,this.endTime=0,this.start()}return u(e,[{key:"start",value:function(){0===this.startTime&&(this.startTime=uw())}},{key:"stop",value:function(){0===this.endTime&&(this.endTime=uw())}},{key:"getDuration",value:function(){return 0===this.endTime?uw()-this.startTime:this.endTime-this.startTime}}]),e}(),kV=function(){function e(t){a(this,e),this.client_=t.client,this.intervalId_=-1,this.statsCalculator_=t.stats,this.prevStats_=null,this.renderFreezeMap_=new Map,this.remoteStreamMap_=new Map,this.dataFreezeMap_=new Map,this.monitorFreezeData_=new Map}var t,i,n;return u(e,[{key:"installEvents",value:function(){Tw.on(134,this.handlePlayVideoStart,this),Tw.on(130,this.onVideoTrackMuted,this),Tw.on(131,this.onVideoTrackUnmuted,this),Tw.on(116,this.handleStreamStopped,this),Tw.on(ww,this.handleStreamStopped,this),Tw.on(102,this.handleVideoPlaying,this)}},{key:"uninstallEvents",value:function(){Tw.off(134,this.handlePlayVideoStart,this),Tw.off(130,this.onVideoTrackMuted,this),Tw.off(131,this.onVideoTrackUnmuted,this),Tw.off(116,this.handleStreamStopped,this),Tw.off(ww,this.handleStreamStopped,this),Tw.off(102,this.handleVideoPlaying,this)}},{key:"start",value:function(){var e=this;-1===this.intervalId_&&(this.installEvents(),this.intervalId_=Qk.run(o(r().mark((function t(){return r().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.detectFPS();case 3:t.next=7;break;case 5:t.prev=5,t.t0=t.catch(0);case 7:case"end":return t.stop()}}),t,null,[[0,5]])}))),{delay:1e3}))}},{key:"stop",value:function(){-1!==this.intervalId_&&(this.uninstallEvents(),Qk.clearTask(this.intervalId_),this.intervalId_=-1,this.renderFreezeMap_.clear(),this.dataFreezeMap_.clear(),this.remoteStreamMap_.clear())}},{key:"onVideoTrackMuted",value:function(e){var t=e.stream;if(t.getClient()===this.client_&&t.isRemote()){var i=t.userId_,r=t.type_,n="".concat(i,"_").concat(r),s=this.dataFreezeMap_.get(n),o=new RV;s?s.durationItemList.push(o):this.dataFreezeMap_.set(n,{userId:i,type:r,durationItemList:[o],isFreezing:function(){var e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}}},{key:"onVideoTrackUnmuted",value:function(e){var t=e.stream;if(t.getClient()===this.client_&&t.isRemote()){var i=t.userId_,r=t.type_,n="".concat(i,"_").concat(r);this.stopDataFreeze({key:n,userId:i,type:r})}}},{key:"handleStreamStopped",value:function(e){var t=e.client,i=e.stream;if(t===this.client_){var r=i.getUserId(),n=i.getType(),s="".concat(r,"_").concat(n);this.stopDataFreeze({key:s,userId:r,type:n})}}},{key:"stopDataFreeze",value:function(e){var t=e.key,i=e.userId,r=e.type,n=this.dataFreezeMap_.get(t);if(n&&n.isFreezing()){var s=n.durationItemList[n.durationItemList.length-1];s.stop();var o=s.getDuration();o>500?(ok.logEvent({eventType:"videoFrozenCount",delta:o}),this.monitorFreezeData_.set(t,{userId:i,type:r,duration:o})):n.durationItemList.pop()}}},{key:"getTotalDuration",value:function(e){return e.reduce((function(e,t){var i=t.getDuration();return e+Math.min(i,5e3)}),0)}},{key:"getStats",value:(n=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l,h;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.client_.getConnections(),i={},n=C(t),e.prev=3,n.s();case 5:if((s=n.n()).done){e.next=20;break}if(o=E(s.value,2),a=o[0],(c=o[1]).getPeerConnection()){e.next=9;break}return e.abrupt("continue",18);case 9:return u=c.getSubscribeState(),d=c.getTrackState(),e.next=13,this.statsCalculator_.getReceiverStats(c);case 13:l=e.sent,(h={userId:l.userId,tinyId:a,hasVideo:d.video&&u.video,hasAuxiliary:d.auxiliary&&u.auxiliary,video:{framesDecoded:0},auxiliary:{framesDecoded:0}}).hasVideo&&(h.video.framesDecoded=l.video.framesDecoded),h.hasAuxiliary&&(h.auxiliary.framesDecoded=l.auxiliary.framesDecoded),i[l.userId]=h;case 18:e.next=5;break;case 20:e.next=25;break;case 22:e.prev=22,e.t0=e.catch(3),n.e(e.t0);case 25:return e.prev=25,n.f(),e.finish(25);case 28:return e.abrupt("return",i);case 29:case"end":return e.stop()}}),e,this,[[3,22,25,28]])}))),function(){return n.apply(this,arguments)})},{key:"detectFPS",value:(i=o(r().mark((function e(){var t,i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getStats();case 2:if(t=e.sent,this.prevStats_){e.next=6;break}return this.prevStats_=t,e.abrupt("return");case 6:e.t0=r().keys(t);case 7:if((e.t1=e.t0()).done){e.next=17;break}if(i=e.t1.value,this.prevStats_[i]){e.next=11;break}return e.abrupt("continue",7);case 11:n=t[i].tinyId,s=this.client_.getMutedStates(),t[i].hasVideo&&this.prevStats_[i].hasVideo&&s.has(n)&&!s.get(n).videoMuted&&(o=t[i].video.framesDecoded-this.prevStats_[i].video.framesDecoded,this.handleRenderFreeze({userId:i,type:eI,fps:o})),t[i].hasAuxiliary&&this.prevStats_[i].hasAuxiliary&&(a=t[i].auxiliary.framesDecoded-this.prevStats_[i].auxiliary.framesDecoded,this.handleRenderFreeze({userId:i,type:tI,fps:a})),e.next=7;break;case 17:this.prevStats_=t;case 18:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"handleRenderFreeze",value:(t=o(r().mark((function e(t){var i,n,s,o,a,c,u,d;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=t.userId,n=t.fps,s=t.type,o="".concat(i,"_").concat(s),a=this.renderFreezeMap_.get(o),n<=2?(c=uw(),a&&!a.isFreeze&&(a.freezeTimeline.push({startTime:c,endTime:void 0}),a.isFreeze=!0),a||this.renderFreezeMap_.set(o,{userId:i,type:s,isFreeze:!0,freezeTimeline:[{startTime:c,endTime:void 0}],renderFreezeTotal:0})):a&&a.isFreeze&&(a.isFreeze=!1,(u=a.freezeTimeline.pop()).endTime=uw(),d=u.endTime-u.startTime,a.freezeTimeline.push(u),a.renderFreezeTotal+=Math.min(5e3,d));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"handlePlayVideoStart",value:function(e){var t=e.stream;if(t.getClient()===this.client_&&t.isRemote()&&t.hasVideo()){var i="".concat(t.getUserId(),"_").concat(t.getType());this.remoteStreamMap_.has(i)?this.remoteStreamMap_.get(i).remoteStream=t:this.remoteStreamMap_.set(i,{isPlayingFired:!1,remoteStream:t})}}},{key:"handleVideoPlaying",value:function(e){var t=e.stream;if(t.isRemote()&&t.getClient()===this.client_){var i="".concat(t.getUserId(),"_").concat(t.getType());this.remoteStreamMap_.has(i)&&(this.remoteStreamMap_.get(i).isPlayingFired=!0)}}},{key:"getDataFreezeDuration",value:function(e){var t={dataFreeze:0,count:0},i=this.dataFreezeMap_.get(e);if(i){if(i.isFreezing()){var r=i.durationItemList[i.durationItemList.length-1];r.stop(),r.getDuration()<500&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}},{key:"getRenderFreezeDuration",value:function(e){var t=this.renderFreezeMap_.get(e),i=0,r=0;if(t)if(t.isFreeze){var n=uw()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(n,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}},{key:"getMonitorFreeze",value:function(){return this.monitorFreezeData_}},{key:"isBlackStream",value:function(e){return!!this.remoteStreamMap_.has(e)&&!this.remoteStreamMap_.get(e).isPlayingFired}},{key:"resetMonitor",value:function(){this.monitorFreezeData_.clear()}}]),e}(),AV=u((function e(t){a(this,e),this.userId=t.userId,this.tinyId=t.tinyId,this.role=20===t.role?QT:KT})),MV={exports:{}};!function(e){!function(t){function i(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,r,n,s,o){return i((a=i(i(t,e),i(n,o)))<<(c=s)|a>>>32-c,r);var a,c}function n(e,t,i,n,s,o,a){return r(t&i|~t&n,e,t,s,o,a)}function s(e,t,i,n,s,o,a){return r(t&n|i&~n,e,t,s,o,a)}function o(e,t,i,n,s,o,a){return r(t^i^n,e,t,s,o,a)}function a(e,t,i,n,s,o,a){return r(i^(t|~n),e,t,s,o,a)}function c(e,t){var r,c,u,d,l;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var h=1732584193,m=-271733879,p=-1732584194,f=271733878;for(r=0;r<e.length;r+=16)c=h,u=m,d=p,l=f,h=n(h,m,p,f,e[r],7,-680876936),f=n(f,h,m,p,e[r+1],12,-389564586),p=n(p,f,h,m,e[r+2],17,606105819),m=n(m,p,f,h,e[r+3],22,-1044525330),h=n(h,m,p,f,e[r+4],7,-176418897),f=n(f,h,m,p,e[r+5],12,1200080426),p=n(p,f,h,m,e[r+6],17,-1473231341),m=n(m,p,f,h,e[r+7],22,-45705983),h=n(h,m,p,f,e[r+8],7,1770035416),f=n(f,h,m,p,e[r+9],12,-1958414417),p=n(p,f,h,m,e[r+10],17,-42063),m=n(m,p,f,h,e[r+11],22,-1990404162),h=n(h,m,p,f,e[r+12],7,1804603682),f=n(f,h,m,p,e[r+13],12,-40341101),p=n(p,f,h,m,e[r+14],17,-1502002290),h=s(h,m=n(m,p,f,h,e[r+15],22,1236535329),p,f,e[r+1],5,-165796510),f=s(f,h,m,p,e[r+6],9,-1069501632),p=s(p,f,h,m,e[r+11],14,643717713),m=s(m,p,f,h,e[r],20,-373897302),h=s(h,m,p,f,e[r+5],5,-701558691),f=s(f,h,m,p,e[r+10],9,38016083),p=s(p,f,h,m,e[r+15],14,-660478335),m=s(m,p,f,h,e[r+4],20,-405537848),h=s(h,m,p,f,e[r+9],5,568446438),f=s(f,h,m,p,e[r+14],9,-1019803690),p=s(p,f,h,m,e[r+3],14,-187363961),m=s(m,p,f,h,e[r+8],20,1163531501),h=s(h,m,p,f,e[r+13],5,-1444681467),f=s(f,h,m,p,e[r+2],9,-51403784),p=s(p,f,h,m,e[r+7],14,1735328473),h=o(h,m=s(m,p,f,h,e[r+12],20,-1926607734),p,f,e[r+5],4,-378558),f=o(f,h,m,p,e[r+8],11,-2022574463),p=o(p,f,h,m,e[r+11],16,1839030562),m=o(m,p,f,h,e[r+14],23,-35309556),h=o(h,m,p,f,e[r+1],4,-1530992060),f=o(f,h,m,p,e[r+4],11,1272893353),p=o(p,f,h,m,e[r+7],16,-155497632),m=o(m,p,f,h,e[r+10],23,-1094730640),h=o(h,m,p,f,e[r+13],4,681279174),f=o(f,h,m,p,e[r],11,-358537222),p=o(p,f,h,m,e[r+3],16,-722521979),m=o(m,p,f,h,e[r+6],23,76029189),h=o(h,m,p,f,e[r+9],4,-640364487),f=o(f,h,m,p,e[r+12],11,-421815835),p=o(p,f,h,m,e[r+15],16,530742520),h=a(h,m=o(m,p,f,h,e[r+2],23,-995338651),p,f,e[r],6,-198630844),f=a(f,h,m,p,e[r+7],10,1126891415),p=a(p,f,h,m,e[r+14],15,-1416354905),m=a(m,p,f,h,e[r+5],21,-57434055),h=a(h,m,p,f,e[r+12],6,1700485571),f=a(f,h,m,p,e[r+3],10,-1894986606),p=a(p,f,h,m,e[r+10],15,-1051523),m=a(m,p,f,h,e[r+1],21,-2054922799),h=a(h,m,p,f,e[r+8],6,1873313359),f=a(f,h,m,p,e[r+15],10,-30611744),p=a(p,f,h,m,e[r+6],15,-1560198380),m=a(m,p,f,h,e[r+13],21,1309151649),h=a(h,m,p,f,e[r+4],6,-145523070),f=a(f,h,m,p,e[r+11],10,-1120210379),p=a(p,f,h,m,e[r+2],15,718787259),m=a(m,p,f,h,e[r+9],21,-343485551),h=i(h,c),m=i(m,u),p=i(p,d),f=i(f,l);return[h,m,p,f]}function u(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function d(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function l(e){var t,i,r="0123456789abcdef",n="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),n+=r.charAt(t>>>4&15)+r.charAt(15&t);return n}function h(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return u(c(d(e),8*e.length))}(h(e))}function p(e,t){return function(e,t){var i,r,n=d(e),s=[],o=[];for(s[15]=o[15]=void 0,n.length>16&&(n=c(n,8*e.length)),i=0;i<16;i+=1)s[i]=909522486^n[i],o[i]=1549556828^n[i];return r=c(s.concat(d(t)),512+8*t.length),u(c(o.concat(r),640))}(h(e),h(t))}function f(e,t,i){return t?i?p(t,e):l(p(t,e)):i?m(e):l(m(e))}e.exports?e.exports=f:t.md5=f}(R)}(MV);var OV,LV,PV=MV.exports,NV=function(){function e(t){a(this,e),this.client_=t.client,this.signalChannel_=t.signalChannel,this.log_=Mw.createLogger({id:"mix|"+this.client_.getUserId(),userId:t.client.getUserId(),sdkAppId:t.client.getSDKAppId()}),this.isMixing_=!1,this.config_=null,this.data_=null,this.remoteStreamMap_=new Map,this.installEvents()}var t,i,n,s;return u(e,[{key:"isPresetLayoutMode",get:function(){return this.config_&&this.config_.mode===NI}},{key:"installEvents",value:function(){Tw.on(Cw,this.onStreamSubscribed,this),Tw.on(ww,this.onStreamUnsubscribed,this),this.client_.on("stream-removed",this.onStreamRemoved,this)}},{key:"uninstallEvents",value:function(){Tw.off(Cw,this.onStreamSubscribed,this),Tw.off(ww,this.onStreamUnsubscribed,this),this.client_.off("stream-removed",this.onStreamRemoved,this)}},{key:"reset",value:function(){this.uninstallEvents(),this.isMixing_=!1,this.config_=null}},{key:"onStreamSubscribed",value:function(e){var t=e.client,i=e.stream;t===this.client_&&(this.remoteStreamMap_.set(i.getId(),{remoteStream:i,isUsed:!1}),this.isMixing_&&this.hasAvailablePlaceHolder()&&this.startMixTranscode(this.config_))}},{key:"onStreamUnsubscribed",value:function(e){var t=e.client,i=e.stream;t===this.client_&&this.onStreamRemoved({stream:i})}},{key:"onStreamRemoved",value:function(e){var t=e.stream;if(this.remoteStreamMap_.has(t.getId())){var i=this.remoteStreamMap_.get(t.getId()).isUsed;this.remoteStreamMap_.delete(t.getId()),this.isMixing_&&this.isPresetLayoutMode&&i&&this.startMixTranscode(this.config_)}}},{key:"startMixTranscode",value:(s=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.resetIsUsedFlag(),this.config_=t,i=this.getInputParam(t,this.remoteStreamMap_),n=this.getOutputParam(t),s=this.getOutputSessionId({config:t,roomId:this.client_.getRoomId(),userId:this.client_.getUserId()}),!this.isMixing_||!this.data_||s===this.data_.outputSessionId){e.next=10;break}return this.log_.info("startMixTranscode() streamId changed, stop mixing before start"),e.next=10,this.doStopMixTranscode();case 10:return e.next=12,this.doStartMixTranscode({outputSessionId:s,inputParam:i,outputParam:n});case 12:e.next=18;break;case 14:throw e.prev=14,e.t0=e.catch(0),this.resetIsUsedFlag(),e.t0;case 18:case"end":return e.stop()}}),e,this,[[0,14]])}))),function(e){return s.apply(this,arguments)})},{key:"doStartMixTranscode",value:(n=o(r().mark((function e(t){var i,n,s,o,a,c,u,d;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=t.outputSessionId,n=t.inputParam,s=t.outputParam,o={roomId:String(this.client_.getRoomId()),mcuRequestTime:Date.now(),outputSessionId:i,inputParam:n,outputParam:s},this.data_=o,this.log_.info("startMixTranscode: ".concat(JSON.stringify(o))),this.isMixing_=!0,e.prev=5,e.next=8,this.signalChannel_.sendWaitForResponse({command:"start_mcu_mix",data:o,timeout:5e3,responseCommand:KR.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"});case 8:if(a=e.sent,c=a.data,u=c.code,d=c.message,0===u){e.next=15;break}throw-102083===u&&(d="Please enable relayed-push in ".concat(ZI," and try later, refer to ").concat(tC,"tutorial-26-advanced-publish-cdn-stream.html")),this.log_.error("startMixTranscode failed, errCode: ".concat(u," errMsg: ").concat(d)),this.isMixing_=!1,new ek({code:ZR.START_MIX_TRANSCODE_FAILED,message:GC({key:"START_MIX_TRANSCODE_FAILED",data:{message:d},link:{className:"Client",fnName:"startMixTranscode"}})});case 15:e.next=21;break;case 17:throw e.prev=17,e.t0=e.catch(5),this.isMixing_=!1,e.t0;case 21:case"end":return e.stop()}}),e,this,[[5,17]])}))),function(e){return n.apply(this,arguments)})},{key:"reStartMixTranscode",value:function(){this.isMixing_&&this.startMixTranscode(this.config_)}},{key:"stopMixTranscode",value:(i=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isMixing_){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"MIX_TRANSCODE_NOT_STARTED"})});case 2:return e.next=4,this.doStopMixTranscode();case 4:this.resetIsUsedFlag();case 5:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"doStopMixTranscode",value:(t=o(r().mark((function e(){var t,i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={mcuRequestTime:Date.now(),outputSessionId:this.data_.outputSessionId,streamType:this.data_.outputParam.streamType},this.log_.info("stopMixTranscode: ".concat(JSON.stringify(t))),e.next=4,this.signalChannel_.sendWaitForResponse({command:"stop_mcu_mix",data:t,timeout:5e3,responseCommand:KR.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"});case 4:if(i=e.sent,n=i.data,s=n.code,o=n.message,0!==s){e.next=10;break}this.isMixing_=!1,e.next=12;break;case 10:throw this.log_.error("stopMixTranscode failed, errCode: ".concat(s," errMsg: ").concat(o)),new ek({code:ZR.STOP_MIX_TRANSCODE_FAILED,message:GC({key:"STOP_MIX_TRANSCODE_FAILED",data:{message:o},link:{className:"Client",fnName:"stopMixTranscode"}})});case 12:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"getOutputSessionId",value:function(e){var t=e.config,i=e.userId,r=e.roomId;return tw(t.streamId)&&t.streamId.length>0?t.streamId:PV("".concat(r,"_").concat(i,"_main"))}},{key:"getInputParam",value:function(e,t){var i=this,r=e.mixUsers.map((function(e){return{userId:e.userId,roomId:String(e.roomId||i.client_.getRoomId()),width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder,streamType:ew(e.streamType)||e.streamType!==tI?0:1,inputType:e.pureAudio?4:0,renderMode:e.renderMode||0}}));return e.mode===NI&&(r.forEach((function(e){if(e.userId===DI){var i=b(t.values()).find((function(e){return!e.isUsed}));i&&(e.userId=i.remoteStream.getUserId(),e.streamType=i.remoteStream.getType()===tI?1:0,i.isUsed=!0)}})),r=r.filter((function(e){return e.userId!==DI}))),r}},{key:"getOutputParam",value:function(e){var t=e.streamId||"";return{streamId:t,streamType:t.length>0?1:0,width:ew(e.videoWidth)?640:e.videoWidth,height:ew(e.videoHeight)?480:e.videoHeight,videoBps:e.videoBitrate||0,fps:e.videoFramerate||15,gop:e.videoGOP||2,audioSampleRate:e.audioSampleRate||48e3,audioBps:e.audioBitrate||64,audioChannels:e.audioChannels||1,backgroundColor:e.backgroundColor||0,backgroundImg:e.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}},{key:"hasAvailablePlaceHolder",value:function(){return!!this.isPresetLayoutMode&&this.data_.inputParam.length!==this.config_.mixUsers.length}},{key:"resetIsUsedFlag",value:function(){this.remoteStreamMap_.forEach((function(e){return e.isUsed=!1}))}}]),e}(),DV=function(){function e(t){a(this,e),this.client_=t.client,this.signalChannel_=t.signalChannel,this.isPublishingTencentCDN_=!1,this.publishTencentStreamRetryCount_=0,this.publishTencentStreamId_=void 0,this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}var t,i,n,s,c;return u(e,[{key:"setSignalChannel",value:function(e){this.signalChannel_=e.signalChannel}},{key:"getIsPublishingTencentCDN",value:function(){return this.isPublishingTencentCDN_}},{key:"getIsPublishingGivenCDN",value:function(){return this.isPublishingGivenCDN_}},{key:"generatePublishCDNStreamId",value:function(e){if(!e){var t="".concat(this.client_.getRoomId(),"_").concat(this.client_.getUserId(),"_main");return/^[A-Za-z\d_-]*$/.test(t)||(t=PV(t)),"".concat(this.client_.getSDKAppId(),"_").concat(t)}return e}},{key:"startPublishTencentCDN",value:(c=o(r().mark((function e(t){var i,n;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isPublishingTencentCDN_=!0,this.publishTencentStreamId_=t.streamId,this.client_.isJoined_){e.next=4;break}return e.abrupt("return");case 4:return i=this.generatePublishCDNStreamId(t.streamId),n={requestTime:Date.now(),sessionId:PV("".concat(this.client_.getRoomId(),"_").concat(this.client_.getUserId(),"_main")),streamId:i,streamType:0},this.publishTencentStreamRetryCount_=0,e.next=9,this.doStartPublishTencentCDN(n);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"doStartPublishTencentCDN",value:(s=o(r().mark((function e(t){var i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,Mw.info("startPublishTencentCDN: "+JSON.stringify(t)),e.next=4,this.signalChannel_.sendWaitForResponseWithRetry({command:"start_publishing",data:t,timeout:2e3,responseCommand:KR.START_PUBLISH_TENCENT_CDN_RES,commandDesc:"startPublishCDNStream",retries:2});case 4:if(i=e.sent,n=i.data,s=n.code,o=n.message,0===s){e.next=12;break}throw this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,-102083===s&&(o="Please enable relayed-push in ".concat(ZI," and try later, refer to ").concat(tC,"tutorial-26-advanced-publish-cdn-stream.html")),Mw.error("startPublishTencentCDN failed, errCode: ".concat(s,", errMsg: ").concat(o)),new ek({code:ZR.START_PUBLISH_CDN_FAILED,message:GC({key:RC,data:{message:o},link:{className:"Client",fnName:"startPublishCDNStream"}})});case 12:e.next=19;break;case 14:throw e.prev=14,e.t0=e.catch(0),this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,e.t0;case 19:case"end":return e.stop()}}),e,this,[[0,14]])}))),function(e){return s.apply(this,arguments)})},{key:"stopPublishTencentCDN",value:(n=o(r().mark((function e(){var t,i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={requestTime:Date.now(),sessionId:PV("".concat(this.client_.getRoomId(),"_").concat(this.client_.getUserId(),"_main"))},Mw.info("stopPublishTencentCDN: "+JSON.stringify(t)),e.next=4,this.signalChannel_.sendWaitForResponse({command:"stop_publishing",data:t,timeout:5e3,responseCommand:KR.STOP_PUBLISH_TENCENT_CDN_RES,commandDesc:"stopPublishCDNStream"});case 4:if(i=e.sent,n=i.data,s=n.code,o=n.message,0!==s){e.next=11;break}this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,e.next=19;break;case 11:if(-102069!==s){e.next=17;break}Mw.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.publishTencentStreamId_=void 0,this.isPublishingTencentCDN_=!1,e.next=19;break;case 17:throw Mw.error("stopPublishTencentCDN failed, errCode: ".concat(s," errMsg: ").concat(o)),new ek({code:ZR.STOP_PUBLISH_CDN_FAILED,message:GC({key:kC,data:{message:o},link:{className:"Client",fnName:"stopPublishCDNStream"}})});case 19:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"startPublishGivenCDN",value:(i=o(r().mark((function e(t){var i,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i={pushRequestTime:Date.now(),pushAppId:t.appId,pushBizId:t.bizId,pushCdnUrl:t.url,pushStreamType:VT,pushStreamId:this.publishTencentStreamId_},Mw.info("startPublishGivenCDN: "+JSON.stringify(i)),this.publishGivenCDNData_=i,this.isPublishingGivenCDN_=!0,this.client_.isJoined_){e.next=6;break}return e.abrupt("return");case 6:return e.prev=6,e.next=9,this.signalChannel_.sendWaitForResponse({command:"start_push_user_cdn",data:i,timeout:5e3,responseCommand:KR.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDNStream"});case 9:if(n=e.sent,s=n.data,o=s.code,a=s.message,0===o){e.next=16;break}throw Mw.error("startPublishGivenCDN failed, errCode: ".concat(o,", errMsg: ").concat(a)),this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,new ek({code:ZR.START_PUBLISH_CDN_FAILED,message:GC({key:RC,data:{message:a},link:{className:"Client",fnName:"startPublishCDNStream"}})});case 16:e.next=23;break;case 18:throw e.prev=18,e.t0=e.catch(6),this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,e.t0;case 23:case"end":return e.stop()}}),e,this,[[6,18]])}))),function(e){return i.apply(this,arguments)})},{key:"stopPublishGivenCDN",value:(t=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.publishGivenCDNData_,i=t.pushAppId,n=t.pushBizId,s=t.pushCdnUrl,o=t.pushStreamType,a={pushRequestTime:Date.now(),pushAppId:i,pushBizId:n,pushCdnUrl:s,pushStreamType:o},Mw.info("stopPublishGivenCDN: "+JSON.stringify(a)),e.next=5,this.signalChannel_.sendWaitForResponse({command:"stop_push_user_cdn",data:a,timeout:5e3,responseCommand:KR.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDNStream"});case 5:if(c=e.sent,u=c.data,d=u.code,l=u.message,0!==d){e.next=12;break}this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,e.next=14;break;case 12:throw Mw.error("stopPublishGivenCDN failed, errCode: ".concat(d," errMsg: ").concat(l)),new ek({code:ZR.STOP_PUBLISH_CDN_FAILED,message:GC({key:kC,data:{message:l},link:{className:"Client",fnName:"stopPublishCDNStream"}})});case 14:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"handleCDNConfigForJoinData",value:function(e){var t,i=e;if(this.isPublishingTencentCDN_){var r={};tw(i)&&(r=JSON.parse(i)),r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this.publishTencentStreamId_),i=JSON.stringify(r)}if(this.isPublishingGivenCDN_){var n=this.publishGivenCDNData_,s=n.pushAppId,o=n.pushBizId,a=n.pushCdnUrl,c=n.pushStreamType,u=n.pushStreamId;t={pushRequestTime:Date.now(),pushAppId:s,pushBizId:o,pushCdnUrl:a,pushStreamType:c,pushStreamId:u}}return{bussinessInfo:i,pushUserCdnInfo:t}}},{key:"reset",value:function(){this.isPublishingTencentCDN_=!1,this.publishTencentStreamRetryCount_=0,this.publishTencentStreamId_=void 0,this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}}]),e}(),xV=function(){function e(t){a(this,e),this.client_=t.client,this.durationMap_=new Map,this.installEvents()}return u(e,[{key:"installEvents",value:function(){Tw.on(Cw,this.handleSubscribed,this),Tw.on(Iw,this.handleStreamTrackUpdated,this),Tw.on(ww,this.handleStreamStopped,this),Tw.on(116,this.handleStreamStopped,this)}},{key:"uninstallEvents",value:function(){Tw.off(Cw,this.handleSubscribed,this),Tw.off(Iw,this.handleStreamTrackUpdated,this),Tw.off(ww,this.handleStreamStopped,this),Tw.off(116,this.handleStreamStopped,this)}},{key:"handleSubscribed",value:function(e){var t=e.client,i=e.stream;if(t===this.client_){var r=i.getUserId(),n=i.getType(),s="".concat(r,"_").concat(n);if(i.hasAudio())if(i.isMainAudioSubscribed){var o=new RV,a=this.durationMap_.get(s);a?this.isRecording(a.audio)||a.audio.push(o):this.durationMap_.set(s,{userId:r,type:n,audio:[o],video:[]})}else this.stopDurationItem(s,wT);if(i.hasVideo())if(n===eI&&i.isMainVideoSubscribed||n===tI&&i.isAuxVideoSubscribed){var c=new RV,u=this.durationMap_.get(s);u?this.isRecording(u.video)||u.video.push(c):this.durationMap_.set(s,{userId:r,type:n,audio:[],video:[c]})}else this.stopDurationItem(s,RT)}}},{key:"handleStreamStopped",value:function(e){var t=e.client,i=e.stream;if(this.clientHitTest(t)){var r=i.getUserId(),n=i.getType(),s="".concat(r,"_").concat(n);this.stopDurationItem(s,wT),this.stopDurationItem(s,RT)}}},{key:"handleStreamTrackUpdated",value:function(e){var t=e.client,i=e.userId,r=e.tinyId,n=e.kind,s=e.action;if(this.clientHitTest(t)&&this.client_.getConnections().has(r)){var o=n===kT?n:eI,a="".concat(i,"_").concat(o);if(s===VI){var c=this.client_.getConnections().get(r).getSubscribeState();if(n===wT&&!c.audio||n===RT&&!c.video||n===kT&&!c.auxiliary)return;var u=new RV,d=this.durationMap_.get(a);d?(n!==wT||this.isRecording(d.audio)||d.audio.push(u),n===wT||this.isRecording(d.video)||d.video.push(u)):this.durationMap_.set(a,{userId:i,type:o,audio:n===wT?[u]:[],video:n===wT?[]:[u]})}else this.stopDurationItem(a,n===wT?wT:RT)}}},{key:"isRecording",value:function(e){return e.findIndex((function(e){return 0===e.endTime}))>=0}},{key:"stopDurationItem",value:function(e,t){if(this.durationMap_.has(e)){var i=this.durationMap_.get(e)[t].find((function(e){return 0===e.endTime}));i&&i.stop()}}},{key:"clientHitTest",value:function(e){return this.client_===e}},{key:"getDuration",value:function(e,t){return this.durationMap_.has(e)?this.durationMap_.get(e)[t].reduce((function(e,t){return e+t.getDuration()}),0):0}},{key:"getDurationMap",value:function(){return this.durationMap_}},{key:"reset",value:function(){this.durationMap_.clear()}},{key:"destroy",value:function(){this.client_=null,this.uninstallEvents()}}]),e}(),UV=En,$V=O,BV=Lc.f;UV({target:"Object",stat:!0,forced:$V((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:BV});var VV=5e3,FV={msg_user_info:0,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0},jV=u((function e(t){a(this,e),this.str_identifier=String(t.userId),this.uint64_tinyid=Number(t.tinyId),this.uint32_role=t.role})),HV=(OV=EV({timeout:500,retries:3}),w((LV=function(){function e(t){var i=this;a(this,e),this.frameWorkType_=t.frameWorkType||30,this.client_=t.client,this.keyPrefix_="key_point",this.storageKey_="".concat(this.keyPrefix_,"_").concat(this.client_.getUserId()),this.log_=Mw.createLogger({id:"kpm|"+this.client_.getUserId(),userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId()}),Object.getOwnPropertyNames(this.__proto__).forEach((function(e){e.startsWith("handle")&&ZC(i[e])&&(i[e]=function(e){var t=e.fn,i=e.context;return o(r().mark((function e(){var n,s,o,a=arguments;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(e.prev=0,n=a.length,s=new Array(n),o=0;o<n;o++)s[o]=a[o];return e.next=4,t.apply(i||this,s);case 4:return e.abrupt("return",e.sent);case 7:e.prev=7,e.t0=e.catch(0),Mw.error("".concat(t.name,"() error observed ")+e.t0);case 10:case"end":return e.stop()}}),e,this,[[0,7]])})))}({fn:i[e],context:i}))})),this.initData(),this.installEvents(),this.intervalId_=Qk.run(cC,this.setStorage.bind(this),{delay:2e4})}var t,n,s;return u(e,[{key:"initData",value:function(){this.firstPublishedUserList_=[],this.networkQuality_={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this.basicInfo={string_sdk_version:Uo,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this.client_.getMode()?1:0,uint32_joining_duration:0,uint32_networkType:jI[YC()],uint32_framework:this.frameWorkType_},this.pathJoinRoom_={uint64_start_time:0,uint64_init_audio_start_time:0,uint64_init_audio_end_time:0,uint64_init_camera_start_time:0,uint64_init_camera_end_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_init_audio_ret:0,int32_init_camera_ret:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this.pathLeaveRoom_={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this.pathMainVideoMap_=new Map,this.pathMainAudioMap_=new Map,this.pathAuxiliaryMap_=new Map,this.localStreamStats_={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this.remoteStreamStatsMap_=new Map}},{key:"installEvents",value:function(){Tw.on(1,this.handleJoinStart,this),Tw.on(28,this.handleWSStart,this),Tw.on(29,this.handleWSEnd,this),Tw.on(2,this.handleJoinSendCMD,this),Tw.on(3,this.handleJoinReceivedCMDResponce,this),Tw.on(4,this.handleJoinSuccess,this),Tw.on(5,this.handleJoinFailed,this),Tw.on(24,this.handleReceivedPublishUserList,this),Tw.on(200,this.handleConnectionStateChanged,this),Tw.on(20,this.handleLeaveStart,this),Tw.on(22,this.handleLeaveSuccess,this),Tw.on(21,this.handleLeaveSendCMD,this),Tw.on(201,this.handleSendSubscribeCMD,this),Tw.on(102,this.handleVideoPlaying,this),Tw.on(103,this.handleAudioPlaying,this),Tw.on(300,this.handleNetworkQuality,this),Tw.on(23,this.handleHeartbeatStats,this),Tw.on(111,this.handleRemoteStreamAdded,this),Tw.on(112,this.handleRemoteStreamSubscribeStart,this),Tw.on(Cw,this.handleRemoteStreamSubscribed,this),Tw.on(133,this.handleVideoLoadedData,this),Tw.on(132,this.handlePlayStream,this),Tw.on(27,this.handlePublishStart,this),Tw.on(121,this.handleLocalStreamInitStart,this),Tw.on(122,this.handleLocalStreamInitEnd,this),Tw.on(123,this.handleLocalStreamInitFailed,this)}},{key:"uninstallEvents",value:function(){Tw.off(1,this.handleJoinStart,this),Tw.off(28,this.handleWSStart,this),Tw.off(29,this.handleWSEnd,this),Tw.off(2,this.handleJoinSendCMD,this),Tw.off(3,this.handleJoinReceivedCMDResponce,this),Tw.off(24,this.handleReceivedPublishUserList,this),Tw.off(200,this.handleConnectionStateChanged,this),Tw.off(20,this.handleLeaveStart,this),Tw.off(22,this.handleLeaveSuccess,this),Tw.off(4,this.handleJoinSuccess,this),Tw.off(5,this.handleJoinFailed,this),Tw.off(21,this.handleLeaveSendCMD,this),Tw.off(201,this.handleSendSubscribeCMD,this),Tw.off(102,this.handleVideoPlaying,this),Tw.off(103,this.handleAudioPlaying,this),Tw.off(300,this.handleNetworkQuality,this),Tw.off(23,this.handleHeartbeatStats,this),Tw.off(111,this.handleRemoteStreamAdded,this),Tw.off(112,this.handleRemoteStreamSubscribeStart,this),Tw.off(Cw,this.handleRemoteStreamSubscribed,this),Tw.off(133,this.handleVideoLoadedData,this),Tw.off(132,this.handlePlayStream,this),Tw.off(27,this.handlePublishStart,this),Tw.off(121,this.handleLocalStreamInitStart,this),Tw.off(122,this.handleLocalStreamInitEnd,this),Tw.off(123,this.handleLocalStreamInitFailed,this)}},{key:"destroy",value:function(){this.uninstallEvents(),Qk.clearTask(this.intervalId_),this.client_=null}},{key:"handleJoinStart",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_start_time&&(this.pathJoinRoom_.uint64_start_time=Date.now(),this.checkStorage())}},{key:"handleWSStart",value:function(e){var t=e.client;this.hitTest(t)&&0===this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_start_time&&(this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_start_time=Date.now())}},{key:"handleWSEnd",value:function(e){var t=e.client,i=e.error;this.hitTest(t)&&0===this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_end_time&&(this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this.pathJoinRoom_.int32_send_request_acc_ip_cmd_ret=i instanceof ek?Number(i.getExtraCode()||i.getCode()):ZR.UNKNOWN,this.pathJoinRoom_.int32_end_ret=2))}},{key:"handleJoinSendCMD",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_send_request_enter_room_cmd_start_time&&(this.pathJoinRoom_.uint64_send_request_enter_room_cmd_start_time=Date.now())}},{key:"handleJoinReceivedCMDResponce",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_send_request_enter_room_cmd_end_time&&(this.pathJoinRoom_.uint64_send_request_enter_room_cmd_end_time=Date.now(),this.pathJoinRoom_.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this.pathJoinRoom_.int32_end_ret=3))}},{key:"handleJoinSuccess",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_end_time&&(this.pathJoinRoom_.uint64_end_time=Date.now(),this.pathJoinRoom_.int32_end_ret=0)}},{key:"handleJoinFailed",value:function(e){var t=e.client;this.hitTest(t)&&(this.pathJoinRoom_.uint64_end_time=Date.now(),0===this.pathJoinRoom_.int32_end_ret&&(this.pathJoinRoom_.int32_end_ret=3),this.prepareReport(),this.report())}},{key:"handleReceivedPublishUserList",value:function(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_recv_userlist_time&&(this.pathJoinRoom_.uint64_recv_userlist_time=Date.now(),this.firstPublishedUserList_=e.data.data&&e.data.data.userList||[])}},{key:"handleConnectionStateChanged",value:function(e){var t=e.client,i=e.state,r=e.connection;if(this.hitTest(t)&&i===oI){this.client_.getUplinkConnection()===r&&0===this.pathJoinRoom_.uint64_send_first_video_frame_time&&this.localStreamStats_.publishStartTime>this.pathJoinRoom_.uint64_end_time&&this.localStreamStats_.publishStartTime-this.pathJoinRoom_.uint64_end_time<=100&&(this.pathJoinRoom_.uint64_send_first_video_frame_time=Date.now());var n=this.pathMainVideoMap_.get("".concat(r.getUserId(),"_").concat(eI));n&&0===n.statsToReport.uint64_pc_connected_time&&(n.statsToReport.uint64_pc_connected_time=Date.now())}}},{key:"handleLeaveStart",value:function(e){this.hitTest(e.client)&&(this.pathLeaveRoom_.uint64_start_time=Date.now())}},{key:"handleLeaveSuccess",value:function(e){this.hitTest(e.client)&&0===this.pathLeaveRoom_.uint64_end_time&&(this.pathLeaveRoom_.uint64_end_time=Date.now(),0!==this.pathJoinRoom_.uint64_end_time?this.basicInfo.uint32_joining_duration=this.pathLeaveRoom_.uint64_end_time-this.pathJoinRoom_.uint64_end_time:this.log_.warn("pathJoinRoom endTime is 0"),this.report())}},{key:"handleLeaveSendCMD",value:function(e){this.hitTest(e.client)&&(this.pathLeaveRoom_.uint64_send_request_exit_room_cmd_start_time=Date.now(),this.pathLeaveRoom_.uint64_send_request_exit_room_cmd_end_time=Date.now())}},{key:"handleRemoteStreamAdded",value:function(e){var t=e.client,r=e.stream;if(this.hitTest(t)){var n=r.getUserId(),s=r.getType(),o="".concat(n,"_").concat(s),a=this.remoteStreamStatsMap_.get(o);if(a)a.stream=r;else{var c={userId:n,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:i({},FV),stream:r};c.statsToReport.msg_user_info=new jV({userId:n,tinyId:r.getTinyId(),role:20}),c.statsToReport.uint32_stream_type=s===eI?2:7,this.remoteStreamStatsMap_.set(o,c)}}}},{key:"handleRemoteStreamSubscribeStart",value:function(e){var t=e.client,i=e.stream;if(this.hitTest(t)){var r=i.getUserId(),n=i.getType(),s="".concat(r,"_").concat(n),o=this.remoteStreamStatsMap_.get(s);o&&0===o.subscribeStartTime&&(o.subscribeStartTime=Date.now())}}},{key:"handleSendSubscribeCMD",value:function(e){if(this.hitTest(e.client)){var t=new jV(e),i=Date.now(),r="".concat(e.userId,"_").concat(eI);e.trackState.video&&e.subscribeState.video&&!this.pathMainVideoMap_.has(r)&&this.pathMainVideoMap_.set(r,{statsToReport:{msg_user_info:t,uint64_start_enter_time:this.pathJoinRoom_.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0,uint64_pc_connected_time:0},userId:e.userId,sendSubscribeCMDTime:i}),e.trackState.audio&&e.subscribeState.audio&&!this.pathMainAudioMap_.has(r)&&this.pathMainAudioMap_.set(r,{statsToReport:{msg_user_info:t,uint64_start_enter_time:this.pathJoinRoom_.uint64_start_time,uint64_play_first_frame_time:0},userId:e.userId,sendSubscribeCMDTime:i});var n="".concat(e.userId,"_").concat(tI);e.trackState.auxiliary&&e.subscribeState.auxiliary&&!this.pathAuxiliaryMap_.has(n)&&this.pathAuxiliaryMap_.set(n,{sendSubscribeCMDTime:i})}}},{key:"handleRemoteStreamSubscribed",value:function(e){var t=e.client,i=e.stream;if(this.hitTest(t)){var r=i.getUserId(),n=i.getType(),s="".concat(r,"_").concat(n),o=this.remoteStreamStatsMap_.get(s);o&&0===o.subscribedTime&&(o.subscribedTime=Date.now(),o.stream=i)}}},{key:"handlePlayStream",value:function(e){var t=e.stream;if(t.isRemote()&&t.getConnection()&&this.hitTest(t.getConnection().getClient())){var i=t.getConnection().getUserId(),r="".concat(i,"_").concat(t.getType());if(this.remoteStreamStatsMap_.has(r)){var n=this.remoteStreamStatsMap_.get(r);0===n.playStreamTime&&(n.playStreamTime=Date.now())}}}},{key:"handleVideoLoadedData",value:function(e){var t=e.stream;if(t.isRemote()&&t.getConnection()&&this.hitTest(t.getConnection().getClient())){var i=t.getConnection().getUserId(),r="".concat(i,"_").concat(t.getType());if(this.pathMainVideoMap_.has(r)){var n=this.pathMainVideoMap_.get(r);0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}}}},{key:"handleVideoPlaying",value:function(e){var t=e.stream;if(t.isRemote()&&t.getConnection()&&this.hitTest(t.getConnection().getClient())){var i=t.getConnection().getUserId(),r="".concat(i,"_").concat(t.getType()),n=Date.now();if(this.pathMainVideoMap_.has(r)){var s=this.pathMainVideoMap_.get(r);if(0===s.statsToReport.uint64_render_first_frame_time&&(s.statsToReport.uint64_render_first_frame_time=n),this.remoteStreamStatsMap_.has(r)){var o=this.remoteStreamStatsMap_.get(r),a=o.statsToReport,c=o.playStreamTime,u=o.subscribedTime;0===a.uint32_video_render_first&&c-u<=100&&(a.uint32_video_render_first=n-s.sendSubscribeCMDTime)}}if(t.getType()===tI&&this.pathAuxiliaryMap_.has(r)&&this.remoteStreamStatsMap_.has(r)){var d=this.remoteStreamStatsMap_.get(r),l=d.statsToReport,h=d.playStreamTime,m=d.subscribedTime;0===l.uint32_video_render_first&&h-m<=100&&(l.uint32_video_render_first=n-this.pathAuxiliaryMap_.get(r).sendSubscribeCMDTime)}}}},{key:"handleAudioPlaying",value:function(e){if(e.stream.isRemote()&&e.stream.getConnection()&&this.hitTest(e.stream.getConnection().getClient())){var t=e.stream.getConnection().getUserId(),i="".concat(t,"_").concat(e.stream.getType());if(this.pathMainAudioMap_.has(i)){var r=this.pathMainAudioMap_.get(i);0===r.statsToReport.uint64_play_first_frame_time&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}}}},{key:"handleNetworkQuality",value:function(e){var t=this;this.hitTest(e.client)&&(this.networkQuality_.totalUplinkLoss+=e.uplinkLoss,this.networkQuality_.totalUplinkRTT+=e.uplinkRTT,this.networkQuality_.count++,e.downlinkLossAndRTTMap.forEach((function(e){var i=e.rtt,r=e.loss,n=e.userId,s=t.networkQuality_.totalDownlinkRTTAndLossMap.get(n);s?(s.totalRTT+=i,s.totalLoss+=r,s.count++):t.networkQuality_.totalDownlinkRTTAndLossMap.set(n,{totalRTT:i,totalLoss:r,count:1})})))}},{key:"handleHeartbeatStats",value:function(e){var t=this;if(this.hitTest(e.client)){var i=e.stats,r=i.msg_up_stream_info,n=i.msg_down_stream_info;if(r.msg_video_status[0]){var s=r.msg_video_status[0],o=s.uint32_video_codec_bitrate,a=s.uint32_video_enc_fps,c=s.uint32_video_width,u=s.uint32_video_height;this.localStreamStats_.totalVideoBitrate+=o,this.localStreamStats_.totalVideoFPS+=a,this.localStreamStats_.totalVideoWidth+=c,this.localStreamStats_.totalVideoHeight+=u,this.localStreamStats_.videoCount++}var d=r.msg_audio_status.audioLevel;Math.floor(100*d)>0&&(this.localStreamStats_.totalAudioLevel+=d,this.localStreamStats_.audioLevelCount++),n.forEach((function(e){var i=e.msg_user_info,r=e.msg_audio_status,n=e.msg_video_status,s=i.str_identifier;if(n.forEach((function(e){var i=2===e.uint32_video_stream_type,r=7===e.uint32_video_stream_type,n="".concat(s,"_").concat(i?eI:tI);if(t.remoteStreamStatsMap_.has(n)){var o=t.remoteStreamStatsMap_.get(n);(i&&o.stream.isMainVideoSubscribed||r&&o.stream.isAuxVideoSubscribed)&&(o.totalVideoFPS+=e.uint32_video_receive_fps,o.totalVideoBitrate+=e.uint32_video_codec_bitrate,o.videoCount++,0===o.statsToReport.uint32_video_width&&(o.statsToReport.uint32_video_width=e.uint32_video_width),0===o.statsToReport.uint32_video_height&&(o.statsToReport.uint32_video_height=e.uint32_video_height))}})),r){var o="".concat(s,"_").concat(eI);if(t.remoteStreamStatsMap_.has(o)){var a=t.remoteStreamStatsMap_.get(o);a.stream.isMainAudioSubscribed&&(a.totalAudioBitrate+=r.uint32_audio_codec_bitrate,a.audioCount++,Math.floor(100*r.audioLevel)>0&&(a.totalAudioLevel+=r.audioLevel,a.audioLevelCount++))}}}))}}},{key:"handlePublishStart",value:function(e){var t=e.client;this.hitTest(t)&&0===this.localStreamStats_.publishStartTime&&(this.localStreamStats_.publishStartTime=Date.now())}},{key:"handleLocalStreamInitStart",value:function(e){var t=e.audio,i=e.video;t&&0===this.pathJoinRoom_.uint64_init_audio_start_time&&(this.pathJoinRoom_.uint64_init_audio_start_time=Date.now()),i&&0===this.pathJoinRoom_.uint64_init_camera_start_time&&(this.pathJoinRoom_.uint64_init_camera_start_time=Date.now())}},{key:"handleLocalStreamInitEnd",value:function(e){var t=e.audio,i=e.video;t&&0===this.pathJoinRoom_.uint64_init_audio_end_time&&(this.pathJoinRoom_.uint64_init_audio_end_time=Date.now()),i&&0===this.pathJoinRoom_.uint64_init_camera_end_time&&(this.pathJoinRoom_.uint64_init_camera_end_time=Date.now())}},{key:"handleLocalStreamInitFailed",value:function(e){var t=e.audio,i=e.video,r=e.error,n=r instanceof ek?r.getExtraCode()||r.getCode():{NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5}[r.name]||ZR.UNKNOWN;t&&0===this.pathJoinRoom_.uint64_init_audio_end_time&&(this.pathJoinRoom_.int32_init_audio_ret=n,this.pathJoinRoom_.uint64_init_audio_end_time=Date.now()),i&&0===this.pathJoinRoom_.uint64_init_camera_end_time&&(this.pathJoinRoom_.int32_init_camera_ret=n,this.pathJoinRoom_.uint64_init_camera_end_time=Date.now())}},{key:"hasVideoFlag",value:function(e){return this.firstPublishedUserList_.findIndex((function(t){return t.userId===e&&1&t.flag}))>=0}},{key:"hasAudioFlag",value:function(e){return this.firstPublishedUserList_.findIndex((function(t){return t.userId===e&&8&t.flag}))>=0}},{key:"hasAuxFlag",value:function(e){return this.firstPublishedUserList_.findIndex((function(t){return t.userId===e&&4&t.flag}))>=0}},{key:"hitTest",value:function(e){return e===this.client_}},{key:"checkStorage",value:(s=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!(t=Kk.getItem(this.storageKey_))){e.next=6;break}return e.next=5,this.upload(t);case 5:Kk.deleteItem(this.storageKey_);case 6:e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this.log_.warn(e.t0);case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return s.apply(this,arguments)})},{key:"setStorage",value:function(){this.prepareReport();var e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&Kk.setItem(this.storageKey_,e)}},{key:"prepareReport",value:function(){var e=this;if(this.networkQuality_.count>0&&(this.basicInfo.uint32_avg_rtt=Math.floor(this.networkQuality_.totalUplinkRTT/this.networkQuality_.count),this.basicInfo.uint32_avg_up_loss=Math.floor(this.networkQuality_.totalUplinkLoss/this.networkQuality_.count)),this.localStreamStats_.videoCount>0){this.localStreamStats_.statsToReport.uint32_video_big_capture_fps=Math.floor(this.localStreamStats_.totalVideoFPS/this.localStreamStats_.videoCount),this.localStreamStats_.statsToReport.uint32_video_big_bitrate=Math.floor(this.localStreamStats_.totalVideoBitrate/this.localStreamStats_.videoCount);var t=Math.floor(this.localStreamStats_.totalVideoWidth/this.localStreamStats_.videoCount),i=Math.floor(this.localStreamStats_.totalVideoHeight/this.localStreamStats_.videoCount);this.localStreamStats_.statsToReport.uint32_video_big_resolution=t<<16|i}this.localStreamStats_.audioLevelCount>0&&(this.localStreamStats_.statsToReport.uint32_audio_capture_db=Math.floor(this.localStreamStats_.totalAudioLevel/this.localStreamStats_.audioLevelCount*100)),this.remoteStreamStatsMap_.forEach((function(t,i){var r=t.userId;if(e.networkQuality_.totalDownlinkRTTAndLossMap.has(r)){var n=e.networkQuality_.totalDownlinkRTTAndLossMap.get(r),s=n.totalLoss,o=n.count;t.statsToReport.uint32_avg_down_loss=Math.floor(s/o)}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));var a=e.client_.getCallDurationCalculator();a&&(t.statsToReport.uint32_audio_play_time=a.getDuration(i,wT),t.statsToReport.uint32_video_play_time=a.getDuration(i,RT)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,VV);var c=e.client_.getBadCaseDetector();if(c){var u=c.getDataFreezeDuration(i),d=u.dataFreeze,l=u.count,h=c.getRenderFreezeDuration(i).renderFreeze;t.statsToReport.uint32_video_block_count=l,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(h,t.statsToReport.uint32_video_play_time),c.isBlackStream(i)&&0===t.statsToReport.uint32_video_avg_fps?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}(0===t.subscribeStartTime||t.subscribeStartTime-t.streamAddedTime>100||0===t.playStreamTime)&&(e.pathMainAudioMap_.delete(i),e.pathMainVideoMap_.delete(i),t.statsToReport.uint32_video_render_first=0)})),this.pathMainAudioMap_.forEach((function(t,i){e.hasAudioFlag(t.userId)?t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>VV&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+VV):e.pathMainAudioMap_.delete(i)})),this.pathMainVideoMap_.forEach((function(t,i){e.hasVideoFlag(t.userId)?t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>VV&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+VV):e.pathMainVideoMap_.delete(i)})),this.pathJoinRoom_.uint64_end_time-this.pathJoinRoom_.uint64_start_time>VV&&(this.pathJoinRoom_.uint64_end_time=this.pathJoinRoom_.uint64_start_time+VV)}},{key:"getReportData",value:function(){var e=this.client_.getSignalInfo();return{uint32_sdk_app_id:Number(this.client_.getSDKAppId()),msg_user_info:new jV({userId:this.client_.getUserId(),tinyId:this.client_.getTinyId(),role:this.client_.getRole()===QT?20:21}),msg_basic_info:this.basicInfo,uint32_acc_ip:dw(e.relayIp),uint32_client_ip:dw(e.clientIp,"small"),uint32_acc_port:0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Math.pow(2,31)),msg_path_enter_room:this.pathJoinRoom_,msg_path_exit_room:this.pathLeaveRoom_,msg_path_recv_video:b(this.pathMainVideoMap_.values()).map((function(e){return e.statsToReport})),msg_quality_statistics:b(this.remoteStreamStatsMap_.values()).map((function(e){return e.statsToReport})),str_room_name:String(this.client_.getRoomId()),msg_path_recv_audio:b(this.pathMainAudioMap_.values()).map((function(e){return e.statsToReport})),uint32_info_client_ip:dw(e.clientIp,"small"),error_code:[],msg_local_statistics:this.localStreamStats_.statsToReport}}},{key:"report",value:(n=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,t=this.getReportData(),e.next=4,this.upload(t);case 4:Kk.deleteItem(this.storageKey_),this.initData(),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this.log_.warn(e.t0);case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return n.apply(this,arguments)})},{key:"upload",value:(t=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(ST||0===t.msg_path_enter_room.uint64_start_time||[QI,KI,XI].findIndex((function(e){return e===location.host}))>=0)){e.next=2;break}return e.abrupt("return");case 2:return i=Number(this.client_.getSDKAppId()),n=zC(i,"jssdk_new_endreport"),e.next=6,Sw({url:n,body:JSON.stringify(t)});case 6:if("ok"===(s=e.sent).data){e.next=9;break}throw"key point upload failed: ".concat(s.data);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}()).prototype,"upload",[OV],Object.getOwnPropertyDescriptor(LV.prototype,"upload"),LV.prototype),LV);function WV(){return function(e,t,i){var n=i.value,s=new Set;return i.value=o(r().mark((function e(){var i,o,a,c,u=arguments;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!s.has(this)){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:SC,data:{name:t}})});case 2:for(e.prev=2,s.add(this),i=u.length,o=new Array(i),a=0;a<i;a++)o[a]=u[a];return e.next=7,n.apply(this,o);case 7:return c=e.sent,s.delete(this),e.abrupt("return",c);case 12:throw e.prev=12,e.t0=e.catch(2),s.delete(this),e.t0;case 16:case"end":return e.stop()}}),e,this,[[2,12]])}))),i}}function GV(e){return qV.apply(this,arguments)}function qV(){return(qV=o(r().mark((function e(t){var i,n,s,o,a,c,u,d,l,h,m,p,f;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=t.userId,n=t.sdkAppId,s=t.useStringRoomId,o=t.roomId,a=t.userSig,c={delta:0,count:[1,1],msg:[]},e.prev=2,(u=new FormData).append("userId",String(i)),u.append("sdkAppId",String(n)),u.append("isStrGroupId",s),u.append("groupId",String(o)),u.append("sdkVersion",Uo),u.append("userSig",String(a)),d=uw(),e.next=13,KV(u,c,n);case 13:return l=e.sent,c.delta=uw()-d,JV({stat:c,userId:i}),e.abrupt("return",l);case 19:throw e.prev=19,e.t0=e.catch(2),h=sw(e.t0)?e.t0[0]:e.t0,m=iw(h.code)?h.code:0,p="get websocket url failed: ".concat(h.message.includes("timeout")?"timeout":h.message),f=new ek({code:ZR.SCHEDULE_FAILED,extraCode:m,message:GC({key:IC,data:{error:p,code:m}})}),Mw.error(f),JV({stat:c,userId:i,roomId:o,error:f}),f;case 28:case"end":return e.stop()}}),e,null,[[2,19]])})))).apply(this,arguments)}function JV(e){var t=e.stat,i=e.userId,r=e.error;r?ok.logFailedEvent({eventType:AI,error:r,userId:i}):ok.logSuccessEvent({eventType:AI,delta:t.delta,userId:i}),ok.uploadEvent({log:"stat-schedule:"+JSON.stringify(t),userId:i})}function zV(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:VT;return t=JC(e)?i===VT?qI:JI:i===VT?WI:GI,"https://".concat(t,"/api/v1/config")}function YV(e,t,i){return new Promise((function(r,n){Sw({url:e,body:t,timeout:i.timeout}).then((function(e){0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var QV=function(e,t){return Rw({retryFunction:YV,settings:{retries:3,timeout:0},onError:t,onRetrying:e})};function KV(e,t,i){return new Promise((function(r,n){var s,o=null;(s=[QV((function(e){return t.count[0]=e+1}),(function(e,i){t.msg[0]=e.message,o||i()}))(zV(i,VT),e,{get timeout(){return 1e3*KC(2+t.count[0])}}),QV((function(e){return t.count[1]=e+1}),(function(e,i){t.msg[1]=e.message,o||i()}))(zV(i,FT),e,{get timeout(){return 1e3*KC(2+t.count[1])}})],new Promise((function(e,t){var i=[];s.forEach((function(r){r.then(e).catch((function(e){i.push(e),i.length===s.length&&t(i)}))}))}))).then((function(e){r(o=e)})).catch(n)}))}var XV,ZV,eF,tF,iF,rF,nF,sF,oF,aF,cF,uF,dF,lF,hF,mF,pF,fF,vF,gF,_F,yF=new(function(){function e(){a(this,e)}return u(e,[{key:"call",value:function(e,t){return ZC(this[e])?this[e](t):Promise.reject(new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"API_NOT_EXIST",data:{name:e}})}))}},{key:"updatePrivateMapKey",value:function(e){var t=e.privateMapKey;return e.client.setProperty("privateMapKey",t),Promise.resolve()}}]),e}()),SF=(XV=WV(),ZV=cV(oV.CLIENT.join),eF=WV(),tF=EV({retries:3}),iF=WV(),rF=cV(oV.CLIENT.publish),nF=WV(),sF=cV(oV.CLIENT.unpublish),oF=cV.apply(void 0,b(oV.CLIENT.subscribe)),aF=cV(oV.CLIENT.unsubscribe),cF=WV(),uF=cV(oV.CLIENT.switchRole),dF=cV(oV.CLIENT.startPublishCDNStream),lF=cV(oV.CLIENT.startMixTranscode),hF=aV.apply(void 0,b(oV.CLIENT.sendSEIMessage)),vF=(fF={timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}}).timesInSecond,gF=fF.maxSizeInSecond,_F=fF.getSize,mF=function(e,t,i){var r=i.value,n=new Map;return Tw.on(33,(function(e){var t=e.client;return n.delete(t)})),i.value=function(){var e=n.get(this);e||(e={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.set(this,e)),0===e.timestamp?e.timestamp=Date.now():Date.now()-e.timestamp>1e3&&(e.timestamp=Date.now(),e.callCountInSecond=0,e.totalSizeInSecond=0);for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];if(_F&&(e.totalSizeInSecond+=_F.apply(void 0,s)),0!==e.timestamp&&Date.now()-e.timestamp<1e3&&(e.callCountInSecond>=vF||e.totalSizeInSecond>gF))throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:FC,data:{isTimes:e.callCountInSecond>=vF,isSize:e.totalSizeInSecond>gF,name:t,timesInSecond:vF,maxSizeInSecond:gF}})});return e.callCountInSecond++,r.apply(this,s)},i},pF=function(){function e(t){var i,r;a(this,e),this.name_="Client",this.mode_=t.mode,this.sdpSemantics_="plan-b",ew(t.sdpSemantics)?function(){if(!("RTCRtpTransceiver"in window)||!("stop"in window.RTCRtpTransceiver.prototype))return!1;if(ew(window.RTCRtpTransceiver))return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;var e=new RTCPeerConnection,t=!1;try{e.addTransceiver(wT),t=!0}catch(e){}return e.close(),t}()&&(this.sdpSemantics_=PI):this.sdpSemantics_=t.sdpSemantics,this.sdkAppId_=t.sdkAppId,this.userId_=t.userId,this.log_=Mw.createLogger({id:"c".concat(t.seq,"|").concat(this.userId_),userId:this.userId_,sdkAppId:this.sdkAppId_}),this.userSig_=t.userSig,this.roomId_=0,this.useStringRoomId_=t.useStringRoomId||!1,this.pureAudioPushMode_=null,this.version_=t.version,this.log_.info("using sdpSemantics: "+this.sdpSemantics_),this.signalChannel_=null,this.role_=QT,this.privateMapKey_="",this.tinyId_=0,this.env_="",this.proxy_=null,this.connections_=new Map,this.mutedStates_=new Map,this.userMap_=new Map,this.syncUserListInterval_=-1,this.localStream_=null,this.uplinkConnection_=null,this.emitter_=gw(new bw,this.name_),this.isJoined_=!1,this.heartbeat_=-1,this.lastHeartBeatTime_=-1,this.stats_=new zA(this),this.joinTimeout_=-1,this.changeBigSmallRecords_=new Map,this.networkQuality_=null,this.badCaseDetector_=null,this.networkType_=YC(),this.autoSubscribe_=!!ew(t.autoSubscribe)||t.autoSubscribe,this.joinedTimestamp_=0,this.joinOptions_={},this.basis_=(r={browser:TT().name+"/"+TT().version,os:SA(),displayResolution:EA(),isScreenShareSupported:uA(),isWebRTCSupported:tA(),isGetUserMediaSupported:bA(),isWebAudioSupported:TA(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:(i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1},ew(window.AudioDecoder)||(i.AudioDecoder=!0),ew(window.AudioEncoder)||(i.AudioEncoder=!0),ew(window.VideoDecoder)||(i.VideoDecoder=!0),ew(window.VideoEncoder)||(i.VideoEncoder=!0),ew(window.ImageDecoder)||(i.ImageDecoder=!0),i),isMediaSessionSupported:"mediaSession"in navigator&&!ew(navigator.mediaSession.setActionHandler),isWebTransportSupported:!ew(window.WebTransport)},navigator.userAgent.includes("miniProgram")&&(r.browser="mini/".concat(r.browser)),r),this.initBussinessInfo_(t),this.publishedCDN_=!1,this.publishCDNData_=null,this.mixedMCU_=!1,this.mixTranscodeData_=null,this.checkSystemResult_=null,this.enableAudioVolumeEvaluation_=!1,this.audioVolumeIntervalId_=null,this.mixTranscodeManager_=null,this.publishCDNManager_=new DV({client:this}),this.keyPointManager_=new HV({client:this,frameWorkType:t.frameWorkType}),this.isPublishing_=!1,this.isEnableSmallStream_=!1,this.smallStreamConfig_={bitrate:100,frameRate:15,height:120,width:160},this.turnServers_=[],this.iceTransportPolicy_=t.iceTransportPolicy,this.schedule_={domains:null,iceServers:null,iceTransportPolicy:null},this.enableAutoPlayDialog_=!!ew(t.enableAutoPlayDialog)||t.enableAutoPlayDialog,this.signalInfo_={},this.enableSEI_=!ew(t.enableSEI)&&t.enableSEI,this.isDestroyed_=!1}var t,n,s,c,d,l,h,m,p,f,v,g,_,y,S,T,I,w,R,k,A,M,O,L,P,N,D;return u(e,[{key:"initBussinessInfo_",value:function(e){this.bussinessInfo_=e.bussinessInfo;var t={};if(tw(e.bussinessInfo)&&(t=JSON.parse(e.bussinessInfo)),!ew(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_PURE_AUDIO"})});this.pureAudioPushMode_=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this.pureAudioPushMode_}if(!ew(e.streamId)){if(!(tw(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_STREAMID"})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_streamid_main=e.streamId}if(!ew(e.userDefineRecordId)){if(null===e.userDefineRecordId.match(/^[A-Za-z0-9_-]{1,64}$/gi))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_USER_DEFINE_RECORDID"})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!ew(e.userDefinePushArgs)){if(!(tw(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_USER_DEFINE_PUSH_ARGS"})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}sk(t)||(this.bussinessInfo_=JSON.stringify(t))}},{key:"schedule",value:(D=o(r().mark((function e(t){var n;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,GV({userId:this.userId_,sdkAppId:this.sdkAppId_,roomId:t,useStringRoomId:this.useStringRoomId_,version:this.version_,userSig:this.userSig_});case 2:(n=e.sent)&&(this.log_.info("schedule: ".concat(JSON.stringify(n))),this.schedule_=i(i({},this.schedule_),n),Tw.emit(31,this.schedule_));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return D.apply(this,arguments)})},{key:"getSignalChannelUrl",value:function(){var e={mainUrl:"",backupUrl:""},t=qC();return t?e.mainUrl=e.backupUrl="wss://".concat(t,".rtc.qq.com"):this.proxy_?e.mainUrl=e.backupUrl=this.proxy_:Array.isArray(this.schedule_.domains)&&this.schedule_.domains.length>0&&(e.mainUrl=e.backupUrl="wss://".concat(this.schedule_.domains[0]),this.schedule_.domains[1]&&(e.backupUrl="wss://".concat(this.schedule_.domains[1]))),e}},{key:"getUserId",value:function(){return this.userId_}},{key:"getUserSig",value:function(){return this.userSig_}},{key:"getRole",value:function(){return this.role_}},{key:"getSignalInfo",value:function(){return this.signalInfo_}},{key:"getRoomId",value:function(){return this.roomId_}},{key:"getSDKAppId",value:function(){return this.sdkAppId_}},{key:"getTinyId",value:function(){return this.tinyId_}},{key:"getIceTransportPolicy",value:function(){return this.iceTransportPolicy_||this.schedule_.iceTransportPolicy||"all"}},{key:"initialize",value:function(){var e=this;this.log_.info("setup signal channel");var t=this.getSignalChannelUrl(),i=t.mainUrl,r=t.backupUrl;return this.signalChannel_=new ak({sdkAppId:this.sdkAppId_,userId:this.userId_,userSig:this.userSig_,url:i,backupUrl:r,client:this}),this.networkQuality_||(this.networkQuality_=new YA({connections:this.connections_,signalChannel:this.signalChannel_,userId:this.userId_,client:this}),this.networkQuality_.on(jA,(function(t){e.emitter_.emit(jA,t)}))),this.deviceDetector_||(this.deviceDetector_=new QA({client:this})),this.subscriptionManager_||(this.subscriptionManager_=new mV({client:this})),this.badCaseDetector_||(this.badCaseDetector_=new kV({client:this,stats:this.stats_})),this.callDurationCalculator_||(this.callDurationCalculator_=new xV({client:this})),this.mixTranscodeManager_||(this.mixTranscodeManager_=new NV({client:this,signalChannel:this.signalChannel_})),this.publishCDNManager_&&this.publishCDNManager_.setSignalChannel({signalChannel:this.signalChannel_}),this.signalChannel_.on(2,(function(t){e.log_.info("SignalChannel state changed from ".concat(t.prevState," to ").concat(t.state)),e.emitter_.emit("connection-state-changed",t)})),this.signalChannel_.on(4,(function(t){e.reset(),e.emitter_.emit(WA,t)})),this.signalChannel_.once(1,(function(t){e.tinyId_=t.signalInfo.tinyId,Tw.emit(29,{client:e})})),this.signalChannel_.on(KR.PEER_JOIN,this.onPeerJoin,this),this.signalChannel_.on(KR.PEER_LEAVE,this.onPeerLeave,this),this.signalChannel_.on(KR.UPDATE_REMOTE_MUTE_STAT,(function(t){Date.now()-e.lastHeartBeatTime_>=1e4&&e.doHeartbeat(),Tw.emit(24,{client:e,data:t.data}),e.onPublishedUserList(t.data),e.onUpdateRemoteMuteStat(t.data)})),this.signalChannel_.on(KR.CLIENT_BANNED,(function(t){var i,r=t.data.data.reason;if(ok.uploadEvent({log:"stat-banned:".concat(r),userId:e.userId_}),"banned"===r)i="you got banned by the admin";else if("kick"===r)i="duplicated userId joining the room";else if("room_disband"===r)i="the room has been disbanded by the admin",r=r.replace("_","-");else if("user_time_out"===r)return e.log_.warn("".concat(r," last heart beat time: ").concat(e.lastHeartBeatTime_," interval: ").concat(Date.now()-e.lastHeartBeatTime_,", visibility: ").concat(document.visibilityState)),void e.reJoin();e.log_["kick"===r?"error":"info"]("user was banned because of [".concat(r,"]")),e.reset(),e.emitter_.emit("client-banned",{reason:r,message:GC({key:"CLIENT_BANNED",data:{message:i,reason:r}})||r})})),Tw.emit(28,{client:this}),this.signalChannel_.connect()}},{key:"preJoin",value:(N=o(r().mark((function e(t){var i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.joinOptions_=t,e.next=3,aA();case 3:if(this.checkSystemResult_=e.sent,this.checkDestroy(),(i=qC())||(i=qT,this.proxy_&&(this.proxy_.startsWith("wss://trtc.rtc.qq.com")?i="trtc":this.proxy_.startsWith("wss://webrtc.qq.com")&&(i="webrtc"))),this.env_=i,ok.setConfig({env:i,sdkAppId:this.sdkAppId_,userId:this.userId_,roomId:t.roomId}),this.uploadTrtcStats(),n=this.checkSystemResult_.detail,s=n.isH264EncodeSupported,o=n.isVp8EncodeSupported,tA()&&(s||o)){e.next=13;break}throw new ek({code:ZR.NOT_SUPPORTED,message:GC({key:DC})});case 13:case"end":return e.stop()}}),e,this)}))),function(e){return N.apply(this,arguments)})},{key:"join",value:(P=o(r().mark((function e(t){var i,n=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=uw(),Tw.emit(1,{client:this,roomId:t.roomId}),ik(this.userId_,{eventId:32788,eventDesc:"joining room",timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_}),e.next=5,this.preJoin(t);case 5:return e.abrupt("return",new Promise(function(){var e=o(r().mark((function e(s,o){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n.joinReject_=o,e.prev=1,n.proxy_||n.schedule_.domains){e.next=5;break}return e.next=5,n.schedule(t.roomId);case 5:return n.checkDestroy(),e.next=8,n.initialize(t);case 8:return e.next=10,n.doJoin(t);case 10:n.signalInfo_=n.signalChannel_.getSignalInfo(),Tw.emit(4,{client:n}),n.joinedTimestamp_=uw(),ok.logSuccessEvent({userId:n.userId_,eventType:"delta-join",delta:n.joinedTimestamp_-i}),ok.logSuccessEvent({userId:n.userId_,eventType:"join"}),ok.uploadEvent({log:"stat-autoplay-dialog:".concat(n.enableAutoPlayDialog_),userId:n.userId_}),ok.uploadEvent({log:"stat-conv-".concat(ST,"-").concat(location.hostname),userId:n.userId_}),s(),e.next=26;break;case 20:e.prev=20,e.t0=e.catch(1),Tw.emit(5,{client:n,error:e.t0}),ok.logFailedEvent({userId:n.userId_,eventType:"join",error:e.t0}),n.reset(),o(e.t0);case 26:n.joinReject_=null;case 27:case"end":return e.stop()}}),e,null,[[1,20]])})));return function(t,i){return e.apply(this,arguments)}}()));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return P.apply(this,arguments)})},{key:"checkDestroy",value:function(){if(this.isDestroyed_)throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:LC,data:{funName:"join"}})})}},{key:"uploadTrtcStats",value:(L=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l,h,m,p;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,VF.getMicrophones();case 3:n=e.sent,t=n&&n.length,e.next=9;break;case 7:e.prev=7,e.t0=e.catch(0);case 9:return e.prev=9,e.next=12,VF.getCameras();case 12:s=e.sent,i=s&&s.length,e.next=18;break;case 16:e.prev=16,e.t1=e.catch(9);case 18:o={microphone:t,camera:i},a=this.checkSystemResult_.detail,c=a.isH264EncodeSupported,u=a.isVp8EncodeSupported,d=a.isH264DecodeSupported,l=a.isVp8DecodeSupported,h={webRTC:this.basis_.isWebRTCSupported,getUserMedia:this.basis_.isGetUserMediaSupported,webSocket:this.basis_.isWebSocketsSupported,screenShare:this.basis_.isScreenShareSupported,webAudio:this.basis_.isWebAudioSupported,h264Encode:c,h264Decode:d,vp8Encode:u,vp8Decode:l},m={browser:this.basis_.browser,os:this.basis_.os,trtc:h,devices:o},p={isWebCodecSupported:this.basis_.isWebCodecSupported,isMediaSessionSupported:this.basis_.isMediaSessionSupported,isWebTransportSupported:this.basis_.isWebTransportSupported},ok.uploadEvent({log:"trtcstats-"+JSON.stringify(m),userId:this.userId_}),this.log_.info("TrtcStats-"+JSON.stringify(m)),ok.uploadEvent({log:"trtcadvancedstats-"+JSON.stringify(p),userId:this.userId_});case 26:case"end":return e.stop()}}),e,this,[[0,7],[9,16]])}))),function(){return L.apply(this,arguments)})},{key:"doJoin",value:function(e){var t=this;return new Promise((function(i,r){t.roomId_=e.roomId,ew(e.role)||(t.role_=e.role),ew(e.privateMapKey)||(t.privateMapKey_=e.privateMapKey),t.log_.info("Join() => joining room: ".concat(e.roomId," useStringRoomId: ").concat(t.useStringRoomId_," mode: ").concat(t.mode_," role: ").concat(t.role_));var n={roomId:String(e.roomId),useStringRoomId:t.useStringRoomId_,privateMapKey:t.privateMapKey_,trtcRole:t.role_===QT?20:21,trtcScene:t.mode_===YT?2:1,sdpSemantics:t.sdpSemantics_,version:yw(t.version_),ua:navigator&&navigator.userAgent||"",autoSubscribe:t.autoSubscribe_,terminalType:yb?4:vb?2:pb?3:qb?12:Gb?5:Jb?13:1,netType:jI[YC()],bussinessInfo:t.bussinessInfo_};if(t.publishCDNManager_){var s=t.publishCDNManager_.handleCDNConfigForJoinData(t.bussinessInfo_),o=s.bussinessInfo,a=s.pushUserCdnInfo;Object.assign(n,{bussinessInfo:o,pushUserCdnInfo:a})}t.log_.debug("join room signal data: ".concat(JSON.stringify(n))),t.joinTimeout_=setTimeout((function(){t.log_.error("join room timeout observed"),r(new ek({code:ZR.JOIN_ROOM_FAILED,message:GC({key:"JOIN_ROOM_TIMEOUT"})}))}),5e3),Tw.emit(2,{client:t}),t.signalChannel_.once(5,(function(e){t.clearJoinTimeout(),Tw.emit(29,{client:t,error:e}),r(e)})),t.signalChannel_.send("join",n),t.signalChannel_.once(KR.JOIN_ROOM_RESULT,(function(e){t.clearJoinTimeout();var n=e.data,s=n.code,o=n.message,a=n.data;t.onPublishedUserList({data:{userList:a.publishers}}),Tw.emit(3,{client:t,code:s}),0===s?(t.isJoined_=!0,t.log_.info("Join room success, start heartbeat"),t.startHeartbeat(),t.badCaseDetector_&&t.badCaseDetector_.start(),t.syncUserList(),t.startSyncUserListInterval(),i()):(t.log_.error("Join room failed result: "+s+" error: "+o),r(new ek({code:ZR.JOIN_ROOM_FAILED,extraCode:s,message:GC({key:IC,data:{error:o,code:s}})})))}))}))}},{key:"reJoin",value:(O=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isJoined_){e.next=3;break}return this.log_.warn("reJoin abort"),e.abrupt("return");case 3:return this.isJoined_=!1,e.prev=4,this.log_.warn("reJoin pending: ".concat(this.joinOptions_.roomId)),this.subscriptionManager_&&this.subscriptionManager_.markAllStream(),this.signalChannel_.close(),e.next=10,this.signalChannel_.connect();case 10:return e.next=12,this.doJoin(i(i({},this.joinOptions_),{},{role:this.role_,privateMapKey:this.privateMapKey_}));case 12:this.log_.warn("reJoin success"),ok.logSuccessEvent({userId:this.userId_,eventType:"rejoin"}),this.checkConnectionsToReconnect(),this.republish(),this.mixTranscodeManager_&&this.mixTranscodeManager_.reStartMixTranscode(),e.next=25;break;case 19:e.prev=19,e.t0=e.catch(4),this.log_.warn("reJoin fail "+e.t0),this.reset(),ok.logFailedEvent({userId:this.userId_,eventType:"rejoin",error:e.t0}),this.emitter_.emit(WA,new ek({code:ZR.JOIN_ROOM_FAILED,message:GC({key:"REJOIN_ROOM_FAILED",data:{roomId:this.joinOptions_.roomId}})}));case 25:case"end":return e.stop()}}),e,this,[[4,19]])}))),function(){return O.apply(this,arguments)})},{key:"republish",value:function(){var e=this;if(this.uplinkConnection_&&this.localStream_&&!this.uplinkConnection_.getIsReconnecting()){this.log_.warn("republish pending");var t=this.localStream_;this.doUnpublish(t).then((function(){return e.publish(t)})).then((function(){return e.log_.warn("republish success")})).catch((function(t){return e.log_.warn("republish fail "+t)}))}}},{key:"leave",value:(M=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Tw.emit(20,{client:this}),ik(this.userId_,{eventId:32789,eventDesc:"leaving room",timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_}),e.prev=2,e.next=5,this.doHeartbeat();case 5:e.next=9;break;case 7:e.prev=7,e.t0=e.catch(2);case 9:this.doLeave(),Tw.emit(22,{client:this}),ok.logSuccessEvent({userId:this.userId_,eventType:"leave"}),t=Math.floor((uw()-this.joinedTimestamp_)/1e3),ok.logSuccessEvent({userId:this.userId_,eventType:"delta-leave",delta:t});case 14:case"end":return e.stop()}}),e,this,[[2,7]])}))),function(){return M.apply(this,arguments)})},{key:"doLeave",value:function(){this.isJoined_&&(Tw.emit(21,{client:this}),this.log_.info("leave() => leaving room"),this.signalChannel_.send("leave"),this.reset())}},{key:"clearNetworkQuality",value:function(){this.networkQuality_&&(this.networkQuality_.stop(),this.networkQuality_=null)}},{key:"closeConnections",value:function(){var e=this;this.connections_.forEach((function(t){e.closeDownLink(t.getTinyId())}))}},{key:"clearJoinTimeout",value:function(){clearTimeout(this.joinTimeout_),this.joinTimeout_=-1}},{key:"destroy",value:function(){var e,t,i;if(this.isJoined_)throw this.log_.warn(HC.INVALID_DESTROY),new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_DESTROY"})});this.isDestroyed_||(this.log_.info("destroy client"),this.joinReject_&&(this.joinReject_(new ek({code:ZR.INVALID_OPERATION,message:GC({key:LC,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.off("*"),null===(e=this.callDurationCalculator_)||void 0===e||e.destroy(),null===(t=this.keyPointManager_)||void 0===t||t.destroy(),null===(i=this.deviceDetector_)||void 0===i||i.destroy(),this.callDurationCalculator_=null,this.keyPointManager_=null,this.deviceDetector_=null,this.badCaseDetector_=null,this.publishCDNManager_=null,this.isDestroyed_=!0,Tw.emit(33,{client:this}))}},{key:"reset",value:function(){this.keyPointManager_&&this.keyPointManager_.prepareReport(),this.mixTranscodeManager_&&(this.mixTranscodeManager_.reset(),this.mixTranscodeManager_=null),this.publishCDNManager_&&this.publishCDNManager_.reset(),this.userMap_.clear(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.mutedStates_.clear(),this.clearNetworkQuality(),this.badCaseDetector_&&this.callDurationCalculator_&&this.uploadAllCallStats(),this.closeUplink(),this.isJoined_=!1,this.signalChannel_&&(this.log_.info("destroying SignalChannel"),this.signalChannel_.close(),this.signalChannel_=null),this.stats_.reset()}},{key:"startSyncUserListInterval",value:function(){-1===this.syncUserListInterval_&&(this.syncUserListInterval_=Qk.run(cC,this.syncUserList.bind(this)))}},{key:"stopSyncUserListInterval",value:function(){Qk.clearTask(this.syncUserListInterval_),this.syncUserListInterval_=-1}},{key:"syncUserList",value:(A=o(r().mark((function e(){var t,i=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.getUserList();case 3:t=e.sent,0!==this.userMap_.size&&this.userMap_.forEach((function(e){t.findIndex((function(t){return t.userId===e.userId}))<0&&(i.log_.info("peer leave detected: ".concat(e.userId)),i.cleanUser({userId:e.userId,tinyId:e.tinyId}))})),t.forEach((function(e){var t=e.userId;i.userMap_.has(t)||t===i.userId_||(i.userMap_.set(t,e),i.emitter_.emit(UA,{userId:t}))})),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this.log_.warn("sync user list failed: "+e.t0);case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return A.apply(this,arguments)})},{key:"getUserList",value:function(){return this.signalChannel_?this.signalChannel_.sendWaitForResponse({command:"get_user_list",responseCommand:KR.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((function(e){var t=e.data,i=t.code,r=t.message;if(0===i)return(t.data&&t.data.userList||[]).map((function(e){var t=e.userId,i=e.srcTinyId,r=e.role;return new AV({userId:t,tinyId:i,role:r})}));throw GC({key:$C,data:{signalResponse:KR.USER_LIST_RES,code:i,message:r}})})):[]}},{key:"publish",value:(k=o(r().mark((function e(t){var i,n,s,o,a=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.setPublishState(0),this.isPublishing_=!0,i=uw(),Tw.emit(27,{client:this,stream:t}),this.log_.info("publish() => publishing local stream"),n=new CV({userId:this.userId_,tinyId:this.tinyId_,client:this,isUplink:!0,signalChannel:this.signalChannel_,enableSEI:this.enableSEI_}),t.setConnection(n),n.initialize(),n.on(PA,(function(e){var t=e.getCode();t!==ZR.ICE_TRANSPORT_ERROR&&(t===ZR.UPLINK_RECONNECTION_FAILED&&a.closeUplink(),a.emitter_.emit(WA,e))})),e.prev=9,e.next=12,n.publish(t);case 12:this.localStream_=e.sent,this.localStream_.getBeautyStatus()&&this.log_.info("beauty stream is published successfully"),this.log_.info("local stream is published successfully"),this.isPublishing_=!1,t.setPublishState(1),this.uplinkConnection_=n,s=uw(),o=s-i,ok.logSuccessEvent({userId:this.userId_,eventType:dI}),ok.logSuccessEvent({userId:this.userId_,eventType:"delta-publish",delta:o}),t.hasAudio()&&ik(this.userId_,{eventId:32769,eventDesc:"publish audio track",timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_}),t.hasVideo()&&ik(this.userId_,{eventId:32768,eventDesc:"publish video track",timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_}),this.networkQuality_&&this.networkQuality_.setUplinkConnection(this.uplinkConnection_),this.deviceDetector_&&this.deviceDetector_.setLocalStream(this.localStream_),Tw.emit(120,{localStream:this.localStream_,client:this}),this.notPublishWithoutH264Supported_=!1,e.next=39;break;case 30:throw e.prev=30,e.t0=e.catch(9),e.t0 instanceof ek&&e.t0.getCode()===ZR.NOT_SUPPORTED_H264&&(this.notPublishWithoutH264Supported_=!0),t.setPublishState(-1),n.close(),this.log_.error("failed to publish stream "+e.t0),this.isPublishing_=!1,ok.logFailedEvent({userId:this.userId_,eventType:dI,error:e.t0}),e.t0;case 39:case"end":return e.stop()}}),e,this,[[9,30]])}))),function(e){return k.apply(this,arguments)})},{key:"unpublish",value:(R=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localStream_){e.next=2;break}return e.abrupt("return");case 2:return this.log_.info("unpublish() => unpublishing local stream"),e.prev=3,e.next=6,this.doUnpublish();case 6:ok.logSuccessEvent({userId:this.userId_,eventType:lI}),e.next=13;break;case 9:throw e.prev=9,e.t0=e.catch(3),ok.logFailedEvent({userId:this.userId_,eventType:lI,error:e.t0}),e.t0;case 13:case"end":return e.stop()}}),e,this,[[3,9]])}))),function(){return R.apply(this,arguments)})},{key:"doUnpublish",value:function(){var e=this;return this.signalChannel_.sendWaitForResponse({command:XR,commandDesc:"unpublish",responseCommand:KR.UNPUBLISH_RESULT}).then((function(){e.closeUplink()})).catch((function(){e.closeUplink()}))}},{key:"closeUplink",value:function(){this.uplinkConnection_&&(this.uplinkConnection_.getIsReconnecting()&&this.uplinkConnection_.stopReconnection(),this.uplinkConnection_.close(),this.uplinkConnection_=null,this.networkQuality_&&this.networkQuality_.setUplinkConnection(null),this.localStream_.hasAudio()&&ik(this.userId_,{eventId:32771,eventDesc:"unpublish audio track",timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_}),this.localStream_.hasVideo()&&ik(this.userId_,{eventId:32770,eventDesc:"unpublish video track",timestamp:qv(),userId:this.userId_,tinyId:this.tinyId_}),this.localStream_.setClient(null),this.localStream_.setConnection(null),this.localStream_=null,this.deviceDetector_&&this.deviceDetector_.setLocalStream(null))}},{key:"closeDownLink",value:function(e){var t=this.connections_.get(e);t&&(t.getIsReconnecting()&&t.stopReconnection(),this.subscriptionManager_&&this.subscriptionManager_.delete(t.getUserId()),t.close(),this.connections_.delete(e),this.mutedStates_.delete(e))}},{key:"subscribe",value:(w=o(r().mark((function e(t,i){var n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.log_.info("subscribe() => subscribe to [".concat(t.getUserId(),"] ").concat(t.getType()," stream with options: ").concat(JSON.stringify(i))),ew(i)&&(i={audio:!0,video:!0}),ew(i.video)&&(i.video=!0),ew(i.audio)&&(i.audio=!0),e.prev=4,n=t.getConnection(),Tw.emit(112,{client:this,stream:t}),e.next=9,n.subscribe(t,i);case 9:this.subscriptionManager_&&this.subscriptionManager_.addSubscriptionRecord(t.getUserId(),t,i),this.notSubscribeWithoutH264Supported_=!1,ok.logSuccessEvent({userId:this.userId_,eventType:hI}),e.next=22;break;case 14:throw e.prev=14,e.t0=e.catch(4),(s=e.t0 instanceof ek?e.t0.getCode():ZR.UNKNOWN)===ZR.NOT_SUPPORTED_H264&&(this.notSubscribeWithoutH264Supported_=!0),o=new ek({code:s,message:GC({key:"SUBSCRIBE_FAILED",data:{message:e.t0.message,stream:t}})}),ok.logFailedEvent({userId:this.userId_,eventType:hI,error:o}),this.log_.error(o),o;case 22:case"end":return e.stop()}}),e,this,[[4,14]])}))),function(e,t){return w.apply(this,arguments)})},{key:"unsubscribe",value:(I=o(r().mark((function e(t){var i;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.log_.info("unsubscribe() => unsubscribe to [".concat(t.getUserId(),"] ").concat(t.getType()," stream")),e.prev=1,i=t.getConnection(),e.next=5,i.unsubscribe(t);case 5:this.subscriptionManager_&&this.subscriptionManager_.addUnsubscriptionRecord(t.getUserId(),t),Tw.emit(ww,{client:this,stream:t}),ok.logSuccessEvent({userId:this.userId_,eventType:mI}),e.next=14;break;case 10:throw e.prev=10,e.t0=e.catch(1),ok.logFailedEvent({userId:this.userId_,eventType:mI,error:e.t0}),e.t0;case 14:case"end":return e.stop()}}),e,this,[[1,10]])}))),function(e){return I.apply(this,arguments)})},{key:"switchRole",value:(T=o(r().mark((function e(t){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.role_!==t){e.next=2;break}return e.abrupt("return");case 2:if(t!==KT||!this.localStream_){e.next=5;break}return e.next=5,this.unpublish(this.localStream_);case 5:return this.log_.info("switchRole() => switch role to: "+t),e.next=8,this.doSwitchRole(t);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return T.apply(this,arguments)})},{key:"doSwitchRole",value:function(e){var t,i,r=this,n={command:"change_role",data:{role:e===QT?20:21,privateMapKey:this.privateMapKey_},responseCommand:KR.SWITCH_ROLE_RES,retries:(null===(t=this.schedule_.config)||void 0===t||null===(i=t.retries)||void 0===i?void 0:i.switchRole)||1};return this.log_.info("switchRole signal data: "+JSON.stringify(n.data)),this.signalChannel_.sendWaitForResponseWithRetry(n).then((function(t){var i=t.data,n=i.code,s=i.message;if(0!==n)throw new ek({code:ZR.SWITCH_ROLE_FAILED,message:GC({key:"SWITCH_ROLE_FAILED",data:{errMsg:s,errCode:n}})});r.role_=e})).catch((function(e){throw e instanceof ek&&e.getCode()===ZR.API_CALL_TIMEOUT&&(e=new ek({code:ZR.SWITCH_ROLE_FAILED,message:GC({key:"SWITCH_ROLE_TIMEOUT"})})),r.log_.error(e),e}))}},{key:"on",value:function(e,t,i){this.emitter_.on(e,t,i)}},{key:"off",value:function(e,t,i){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}},{key:"getRemoteMutedState",value:function(){var e=this,t=[];return this.mutedStates_.forEach((function(r,n,s){var o=e.connections_.get(n);o&&t.push(i({userId:o.getUserId()},r))})),t}},{key:"getTransportStats",value:(S=o(r().mark((function e(){var t,i,n,s,o,a,c;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t={rtt:0,downlinksRTT:{}},!this.uplinkConnection_){e.next=6;break}return e.next=4,this.stats_.getSenderStats(this.uplinkConnection_);case 4:i=e.sent,t.rtt=i.rtt;case 6:n=C(this.connections_),e.prev=7,n.s();case 9:if((s=n.n()).done){e.next=17;break}return(o=E(s.value,2))[0],a=o[1],e.next=13,this.stats_.getReceiverStats(a);case 13:c=e.sent,t.downlinksRTT[c.userId]=c.rtt;case 15:e.next=9;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(7),n.e(e.t0);case 22:return e.prev=22,n.f(),e.finish(22);case 25:return e.abrupt("return",t);case 26:case"end":return e.stop()}}),e,this,[[7,19,22,25]])}))),function(){return S.apply(this,arguments)})},{key:"getLocalAudioStats",value:(y=o(r().mark((function e(){var t,i;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((t={})[this.userId_]={bytesSent:0,packetsSent:0},!this.uplinkConnection_){e.next=7;break}return e.next=5,this.stats_.getSenderStats(this.uplinkConnection_);case 5:i=e.sent,t[this.userId_]={bytesSent:i.audio.bytesSent,packetsSent:i.audio.packetsSent};case 7:return e.abrupt("return",t);case 8:case"end":return e.stop()}}),e,this)}))),function(){return y.apply(this,arguments)})},{key:"getLocalVideoStats",value:(_=o(r().mark((function e(){var t,i;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((t={})[this.userId_]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},!this.uplinkConnection_){e.next=7;break}return e.next=5,this.stats_.getSenderStats(this.uplinkConnection_);case 5:i=e.sent,t[this.userId_]={bytesSent:i.video.bytesSent,packetsSent:i.video.packetsSent,framesEncoded:i.video.framesEncoded,framesSent:i.video.framesSent,frameWidth:i.video.frameWidth,frameHeight:i.video.frameHeight};case 7:return e.abrupt("return",t);case 8:case"end":return e.stop()}}),e,this)}))),function(){return _.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(g=o(r().mark((function e(){var t,i,n,s,o,a,c,u;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t={},i=C(this.connections_),e.prev=2,i.s();case 4:if((n=i.n()).done){e.next=13;break}return(s=E(n.value,2))[0],o=s[1],a=o.getDelay(),c=a.audioDelay,e.next=9,this.stats_.getReceiverStats(o);case 9:(u=e.sent).hasAudio&&(t[u.userId]={bytesReceived:u.audio.bytesReceived,packetsReceived:u.audio.packetsReceived,packetsLost:u.audio.packetsLost,end2EndDelay:c});case 11:e.next=4;break;case 13:e.next=18;break;case 15:e.prev=15,e.t0=e.catch(2),i.e(e.t0);case 18:return e.prev=18,i.f(),e.finish(18);case 21:return e.abrupt("return",t);case 22:case"end":return e.stop()}}),e,this,[[2,15,18,21]])}))),function(){return g.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(v=o(r().mark((function e(){var t,i,n,s,o,a,c,u,d,l=arguments;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=l.length>0&&void 0!==l[0]?l[0]:eI,i={},n=C(this.connections_),e.prev=3,n.s();case 5:if((s=n.n()).done){e.next=15;break}return(o=E(s.value,2))[0],a=o[1],e.next=9,this.stats_.getReceiverStats(a);case 9:c=e.sent,u=a.getDelay(),d=u.videoDelay,t===eI&&c.hasVideo&&(i[c.userId]={bytesReceived:c.video.bytesReceived,packetsReceived:c.video.packetsReceived,packetsLost:c.video.packetsLost,framesDecoded:c.video.framesDecoded,frameWidth:c.video.frameWidth,frameHeight:c.video.frameHeight,end2EndDelay:d}),t===tI&&c.hasAuxiliary&&(i[c.userId]={bytesReceived:c.auxiliary.bytesReceived,packetsReceived:c.auxiliary.packetsReceived,packetsLost:c.auxiliary.packetsLost,framesDecoded:c.auxiliary.framesDecoded,frameWidth:c.auxiliary.frameWidth,frameHeight:c.auxiliary.frameHeight,end2EndDelay:d});case 13:e.next=5;break;case 15:e.next=20;break;case 17:e.prev=17,e.t0=e.catch(3),n.e(e.t0);case 20:return e.prev=20,n.f(),e.finish(20);case 23:return e.abrupt("return",i);case 24:case"end":return e.stop()}}),e,this,[[3,17,20,23]])}))),function(){return v.apply(this,arguments)})},{key:"getSdpSemantics",value:function(){return this.sdpSemantics_}},{key:"getIceServers",value:function(){return 0===this.turnServers_.length&&this.schedule_.iceServers?this.schedule_.iceServers:this.turnServers_}},{key:"getConnections",value:function(){return this.connections_}},{key:"getMutedStates",value:function(){return this.mutedStates_}},{key:"startHeartbeat",value:function(){-1===this.heartbeat_&&(this.log_.info("startHeartbeat..."),this.heartbeat_=Qk.run(cC,this.doHeartbeat.bind(this),{delay:2e3}))}},{key:"stopHeartbeat",value:function(){-1!==this.heartbeat_&&(this.log_.info("stopHeartbeat"),Qk.clearTask(this.heartbeat_),this.heartbeat_=-1,this.lastHeartBeatTime_=-1)}},{key:"doHeartbeat",value:(f=o(r().mark((function e(){var t,n,s,o,a;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.badCaseDetector_.getMonitorFreeze(),e.next=3,this.stats_.getStatsReport({uplinkConnection:this.uplinkConnection_,downlinkConnections:this.connections_,freezeMap:t});case 3:if(n=e.sent,Tw.emit(23,{client:this,stats:n}),this.badCaseDetector_.resetMonitor(),this.signalChannel_){e.next=8;break}return e.abrupt("return");case 8:s=this.signalChannel_.isConnected()?rk(this.userId_):[],o=i(i({str_sdk_version:this.version_,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId_,uint64_tinyid:this.tinyId_},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:jI[this.networkType_]}},n),{},{msg_event_msg:s}),this.signalChannel_.send("quality_report",o),a=Date.now(),this.lastHeartBeatTime_>0&&a-this.lastHeartBeatTime_>1e4&&this.log_.warn("heartbeat took ".concat(a-this.lastHeartBeatTime_)),this.lastHeartBeatTime_=a,!this.isRelayChanged_&&this.isRelayMaybeFailed()&&(this.reJoin(),this.isRelayChanged_=!0);case 15:case"end":return e.stop()}}),e,this)}))),function(){return f.apply(this,arguments)})},{key:"onRemoteStreamAdded",value:function(e){var t=e.content,i=t.userId,r=t.tinyId,n=t.audio,s=t.bigVideo,o=t.auxVideo,a=t.smallVideo;if(null!==i){this.userMap_.has(i)||(this.userMap_.set(i,new AV({userId:i,tinyId:r,role:QT})),this.emitter_.emit(UA,{userId:i}));var c=this.connections_.get(r);if(c){if(c.getIsReconnecting())return;this.log_.warn("duplicated stream-added observed, rebuild the connection"),c.close(),this.connections_.delete(r)}var u={audio:n,video:s,auxiliary:o,smallVideo:a};this.log_.info("remote peer [".concat(i,"] published stream. trackState: ").concat(JSON.stringify(u))),this.createDownlinkConnection({userId:i,tinyId:r,trackState:u})}else this.log_.warn("received null userId on stream added")}},{key:"createDownlinkConnection",value:function(e){var t=this,i=e.userId,r=e.tinyId,n=e.trackState,s=new wV({userId:i,tinyId:r,client:this,isUplink:!1,signalChannel:this.signalChannel_,autoSubscribe:this.autoSubscribe_,trackState:n,enableSEI:this.enableSEI_});this.connections_.set(r,s),this.installDownlinkEvents(s,i,r),this.autoSubscribe_?(s.initialize(),s.connect().catch((function(){!s.getMainStream()&&s.hasMainStream()&&t.initRemoteStream({type:eI,userId:i,downlinkConnection:s}),!s.getAuxStream()&&s.hasAuxStream()&&t.initRemoteStream({type:tI,userId:i,downlinkConnection:s})}))):(s.hasMainStream()&&this.initRemoteStream({type:eI,userId:i,downlinkConnection:s}),s.hasAuxStream()&&this.initRemoteStream({type:tI,userId:i,downlinkConnection:s}))}},{key:"initRemoteStream",value:function(e){var t=e.type,i=e.userId,r=e.downlinkConnection,n=new hV({type:t,userId:i,client:this});n.setConnection(r),r.setRemoteStream(t===eI?XT:ZT,n),n.setIsStreamAddedEventEmitted(!0),Tw.emit(111,{client:this,stream:n}),this.emitter_.emit(xA,{stream:n})}},{key:"installDownlinkEvents",value:function(e,t,i){var r=this;e.on(DA,(function(e){r.emitter_.emit("sei-message",e)})),e.on(AA,(function(e){e.stream.setIsStreamAddedEventEmitted(!0),Tw.emit(111,{client:r,stream:e.stream}),r.emitter_.emit(xA,{stream:e.stream})})),e.on(MA,(function(e){r.changeBigSmallRecords_.delete(e.stream.getUserId()),e.stream.stop(),e.stream.setIsStreamAddedEventEmitted(!1),r.subscriptionManager_&&r.subscriptionManager_.deleteAutoRecoveryFlag(e.stream.getUserId(),e.stream.getType()),Tw.emit(116,{client:r,stream:e.stream}),r.emitter_.emit("stream-removed",{stream:e.stream})})),e.on(OA,(function(e){Tw.emit(115,{client:r,stream:e.stream}),r.emitter_.emit("stream-updated",{stream:e.stream})})),e.on(LA,(function(e){Tw.emit(Cw,{client:r,stream:e.stream}),r.emitter_.emit("stream-subscribed",{stream:e.stream})})),e.on(PA,(function(e){var t=e.getCode();t!==ZR.ICE_TRANSPORT_ERROR&&(t===ZR.DOWNLINK_RECONNECTION_FAILED&&r.closeDownLink(i),r.emitter_.emit(WA,e))}))}},{key:"onPeerJoin",value:function(e){var t=e.data.data,i=t.srcTinyId,r=t.userId,n=t.role;this.userMap_.has(r)||(this.userMap_.set(r,new AV({userId:r,tinyId:i,role:n})),this.emitter_.emit(UA,{userId:r}))}},{key:"onPeerLeave",value:function(e){var t=e.data.data,i=t.srcTinyId,r=t.userId,n=t.reason,s=void 0===n?0:n;this.log_.info("peer leave [".concat(r,"]: ").concat(aC[s])),this.cleanUser({userId:r,tinyId:i})}},{key:"cleanUser",value:function(e){var t=e.userId,i=e.tinyId;this.userMap_.delete(t),this.closeDownLink(i),this.emitter_.emit("peer-leave",{userId:t})}},{key:"onPublishedUserList",value:function(e){var t=this;try{var i=e.data.userList.map((function(e){return e.userId}));this.connections_.forEach((function(e){var r=e.getUserId(),n=e.getTinyId();i.findIndex((function(e){return e===r}))<0&&(t.log_.info("peer unpublished detected [".concat(r,"]")),t.closeDownLink(n))})),e.data.userList.forEach((function(e){var i=e.userId,r=e.srcTinyId,n=e.flag;if(i!==t.userId_){var s=!!(1&n),o=!!(8&n),a=!!(4&n),c=!!(2&n),u=t.connections_.get(r);if(t.changeBigSmallRecords_.has(i)&&t.checkSubscribeBigSmallVideo(u,c),u){var d=u.getTrackState(),l=d.audio,h=d.video,m=d.auxiliary,p=d.smallVideo;!h&&s&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:VI,kind:RT}),!l&&o&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:VI,kind:wT}),!m&&a&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:VI,kind:kT}),!p&&c&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:VI,kind:AT}),h&&!s&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:FI,kind:RT}),l&&!o&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:FI,kind:wT}),m&&!a&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:FI,kind:kT}),p&&!c&&Tw.emit(Iw,{client:t,tinyId:r,userId:i,action:FI,kind:AT})}else t.log_.info("peer published detected [".concat(i,"]")),t.onRemoteStreamAdded({content:{audio:o,bigVideo:s,auxVideo:a,smallVideo:c,userId:i,tinyId:r}})}}))}catch(e){}}},{key:"onUpdateRemoteMuteStat",value:function(e){var t=this,i=e.data;(i&&i.userList||[]).forEach((function(e){var i=e.srcTinyId,r=e.userId;if(0!==i&&i!==t.tinyId_){var n=t.connections_.get(i);if(n){var s=n.getMainStream();if(s&&s.getIsStreamAddedEventEmitted()){var o=!!(1&e.flag),a=!!(8&e.flag),c=!!(2&e.flag),u=!!(64&e.flag),d=!!(16&e.flag),l=t.mutedStates_.get(i);if(void 0===l)return t.mutedStates_.set(i,{hasAudio:a,hasVideo:o,hasSmall:c,audioMuted:u,videoMuted:d}),o?d?t.emitter_.emit(BA,{userId:r}):t.emitter_.emit(FA,{userId:r}):t.emitter_.emit(BA,{userId:r}),void(a?u?t.emitter_.emit($A,{userId:r}):t.emitter_.emit(VA,{userId:r}):t.emitter_.emit($A,{userId:r}));var h=!u&&a;(!l.audioMuted&&l.hasAudio)!==h&&(h?t.emitter_.emit(VA,{userId:r}):t.emitter_.emit($A,{userId:r}));var m=!d&&o;(!l.videoMuted&&l.hasVideo)!==m&&(m?t.emitter_.emit(FA,{userId:r}):t.emitter_.emit(BA,{userId:r})),t.mutedStates_.set(i,{hasAudio:a,hasVideo:o,hasSmall:c,audioMuted:u,videoMuted:d})}}else t.mutedStates_.delete(i)}}))}},{key:"getEnv",value:function(){return this.env_}},{key:"getSubscriptionManager",value:function(){return this.subscriptionManager_}},{key:"startPublishCDNStream",value:(p=o(r().mark((function e(){var t,i=arguments;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=i.length>0&&void 0!==i[0]?i[0]:{},this.log_.info("startPublishCDNStream params: ".concat(JSON.stringify(t),"; isJoined: ").concat(this.isJoined_,"; isPublished: ").concat(!!this.localStream_)),this.localStream_){e.next=4;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:wC})});case 4:return e.next=6,this.publishCDNManager_.startPublishTencentCDN(t);case 6:if(!(t.appId&&t.bizId&&t.url)){e.next=9;break}return e.next=9,this.publishCDNManager_.startPublishGivenCDN(t);case 9:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{key:"stopPublishCDNStream",value:(m=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.publishCDNManager_.getIsPublishingTencentCDN()){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_OPERATION_STOP_PUBLISH_CDN"})});case 2:return this.log_.info("stopPublishCDNStream"),e.next=5,this.publishCDNManager_.stopPublishTencentCDN();case 5:if(!this.publishCDNManager_.getIsPublishingGivenCDN()){e.next=8;break}return e.next=8,this.publishCDNManager_.stopPublishGivenCDN();case 8:case"end":return e.stop()}}),e,this)}))),function(){return m.apply(this,arguments)})},{key:"startMixTranscode",value:(h=o(r().mark((function e(t){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isJoined_&&this.mixTranscodeManager_){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"START_MIX_TRANSCODE"})});case 2:return ew(t.mode)&&(t.mode="manual"),e.prev=3,this.log_.info("startMixTranscode with config ".concat(JSON.stringify(t))),ok.uploadEvent({log:"mix-transcode-mode:".concat(t.mode),userId:this.userId_}),e.next=8,this.mixTranscodeManager_.startMixTranscode(t);case 8:ok.logSuccessEvent({userId:this.userId_,eventType:wI}),e.next=15;break;case 11:throw e.prev=11,e.t0=e.catch(3),ok.logFailedEvent({userId:this.userId_,eventType:wI,error:e.t0}),e.t0;case 15:case"end":return e.stop()}}),e,this,[[3,11]])}))),function(e){return h.apply(this,arguments)})},{key:"stopMixTranscode",value:(l=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isJoined_&&this.mixTranscodeManager_){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"STOP_MIX_TRANSCODE"})});case 2:return e.prev=2,e.next=5,this.mixTranscodeManager_.stopMixTranscode();case 5:ok.logSuccessEvent({userId:this.userId_,eventType:RI}),e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(2),ok.logFailedEvent({userId:this.userId_,eventType:RI,error:e.t0}),e.t0;case 12:case"end":return e.stop()}}),e,this,[[2,8]])}))),function(){return l.apply(this,arguments)})},{key:"getSystemResult",value:function(){return this.checkSystemResult_}},{key:"enableAudioVolumeEvaluation",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!iw(t))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:AC})});if(this.log_.info("enableAudioVolumeEvaluation with interval: "+t),t<=0)return this.enableAudioVolumeEvaluation_=!1,Qk.clearTask(this.audioVolumeIntervalId_),void(this.audioVolumeIntervalId_=null);t=Math.floor(Math.max(t,16)),Tw.emit(32,{interval:t}),this.audioVolumeIntervalId_&&(Qk.clearTask(this.audioVolumeIntervalId_),this.audioVolumeIntervalId_=null),this.enableAudioVolumeEvaluation_=!0,this.audioVolumeIntervalId_=Qk.run(uC,(function(){var t=[];if(e.localStream_){var i=Math.floor(100*e.localStream_.getAudioLevel());t.push({userId:e.userId_,audioVolume:i,stream:e.localStream_})}e.connections_.forEach((function(e){var i=e.getSubscribedMainStream();if(i){var r=Math.floor(100*i.getAudioLevel());t.push({userId:e.getUserId(),audioVolume:r,stream:i})}})),e.emitter_.emit(HA,{result:t})}),{fps:1e3/t,backgroundTask:i})}},{key:"callExperimentalAPI",value:function(e,t){return yF.call(e,i({client:this},t))}},{key:"setProperty",value:function(e,t){var i="".concat(e,"_");ew(this[i])||(this[i]=t)}},{key:"uploadAllCallStats",value:function(){var e=this;this.callDurationCalculator_.getDurationMap().forEach((function(t,i){var r={userId:t.userId,type:t.type,duration:e.callDurationCalculator_.getDuration(i,RT),dataFreeze:e.badCaseDetector_.getDataFreezeDuration(i).dataFreeze,renderFreeze:e.badCaseDetector_.getRenderFreezeDuration(i).renderFreeze};ok.uploadEvent({log:"callStats-"+JSON.stringify(r),userId:e.userId_})})),this.badCaseDetector_.stop(),this.callDurationCalculator_.reset()}},{key:"enableSmallStream",value:(d=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isPublished()&&!this.isPublishing_){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"ENABLE_SMALL_STREAM_PUBLISHED"})});case 2:if(!IA()){e.next=7;break}this.setIsEnableSmallStream(!0),this.log_.info("SmallStream successfully enabled"),e.next=8;break;case 7:throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"NOT_SUPPORTED_SMALL_STREAM"})});case 8:case"end":return e.stop()}}),e,this)}))),function(){return d.apply(this,arguments)})},{key:"disableSmallStream",value:(c=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isPublished()&&!this.isPublishing_){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"DISABLE_SMALL_STREAM_PUBLISHED"})});case 2:this.setIsEnableSmallStream(!1),this.log_.info("SmallStream successfully disabled");case 4:case"end":return e.stop()}}),e,this)}))),function(){return c.apply(this,arguments)})},{key:"setSmallStreamProfile",value:function(e){var t=this;e&&e.framerate&&(e.frameRate=e.framerate),Object.keys(this.smallStreamConfig_).forEach((function(i){e[i]&&(t.smallStreamConfig_[i]=e[i])})),this.log_.info("setSmallStreamProfile: bitrate=".concat(this.smallStreamConfig_.bitrate,", frameRate=").concat(this.smallStreamConfig_.frameRate,", height=").concat(this.smallStreamConfig_.height,", width=").concat(this.smallStreamConfig_.width));var i=this.smallStreamConfig_,r=i.width,n=i.height,s=i.bitrate,o=i.frameRate;if(r<0||n<0||s<0||o<0)throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_SMALL_STREAM_PROFILE"})})}},{key:"setRemoteVideoStreamType",value:(s=o(r().mark((function e(t,i){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t instanceof hV){e.next=2;break}throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_PARAMETER_REMOTE_STREAM"})});case 2:if(t.getConnection()){e.next=4;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:CC})});case 4:if(t.getType()!==tI){e.next=6;break}return e.abrupt("return");case 6:e.t0=i,e.next="big"===e.t0||"small"===e.t0?9:12;break;case 9:return e.next=11,this.changeVideoType(t,i);case 11:case 12:return e.abrupt("break",13);case 13:case"end":return e.stop()}}),e,this)}))),function(e,t){return s.apply(this,arguments)})},{key:"changeVideoType",value:(n=o(r().mark((function e(t,i){var n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.getUserId(),s={stream:t,options:{video:"big"===i,smallVideo:"small"===i},isSubscribing:!1,reSubscribeCount:10},this.changeBigSmallRecords_.set(n,s),this.log_.info("set [".concat(n,"] ").concat(t.getType()," stream video prefer type: ").concat(i));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"checkSubscribeBigSmallVideo",value:(t=o(r().mark((function e(t,i){var n,s,o,a,c,u,d,l,h,m,p;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.isBigStreamSubscribed||t.isSmallStreamSubscribed){e.next=2;break}return e.abrupt("return");case 2:if(n=t.getUserId(),s=this.changeBigSmallRecords_.get(n)||{},o=t.getSubscribeState(),a=o.video,c=o.smallVideo,u=s.stream,d=s.options,l=s.isSubscribing,h=s.reSubscribeCount,!(d.video&&a||d.smallVideo&&c&&i)){e.next=8;break}return e.abrupt("return");case 8:if(!l){e.next=10;break}return e.abrupt("return");case 10:if(m={video:d.video,smallVideo:d.smallVideo},!(i&&t.isBigStreamSubscribed||t.isSmallStreamSubscribed)){e.next=30;break}if(e.prev=12,!(d&&u&&!l&&h>=1)){e.next=23;break}return s.isSubscribing=!0,s.reSubscribeCount=h-1,p=u.getConnection(),!i&&p.isSmallStreamSubscribed&&(m={video:!0,smallVideo:!1}),e.next=20,null==p?void 0:p.subscribe(u,m);case 20:this.log_.info("change [".concat(n,"] to ").concat(m.smallVideo?"small":"big"," video successfully. count ").concat(10-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=10;case 23:e.next=30;break;case 25:e.prev=25,e.t0=e.catch(12),this.log_.info("change [".concat(n,"] to ").concat(m.smallVideo?"small":"big"," video failed. count ").concat(10-s.reSubscribeCount,".")),s.isSubscribing=!1,0===h&&this.changeBigSmallRecords_.delete(n);case 30:case"end":return e.stop()}}),e,this,[[12,25]])}))),function(e,i){return t.apply(this,arguments)})},{key:"setIsEnableSmallStream",value:function(e){this.isEnableSmallStream_=e}},{key:"getIsEnableSmallStream",value:function(){return this.isEnableSmallStream_}},{key:"smallStreamConfig",get:function(){return this.smallStreamConfig_}},{key:"isPublished",value:function(){return!!this.localStream_}},{key:"getUplinkConnection",value:function(){return this.uplinkConnection_}},{key:"getLocalStream",value:function(){return this.localStream_}},{key:"getMode",value:function(){return this.mode_}},{key:"getBadCaseDetector",value:function(){return this.badCaseDetector_}},{key:"getCallDurationCalculator",value:function(){return this.callDurationCalculator_}},{key:"getIsJoined",value:function(){return this.isJoined_}},{key:"getAllConnections",value:function(){var e=b(this.connections_.values());return this.uplinkConnection_&&e.push(this.uplinkConnection_),e}},{key:"isRelayMaybeFailed",value:function(){var e=this.getAllConnections();if(0===e.length)return!1;for(var t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}},{key:"getUseStringRoomId",value:function(){return this.useStringRoomId_}},{key:"checkConnectionsToReconnect",value:function(){var e=this;this.getAllConnections().forEach((function(t){if(!t.getIsReconnecting()){var i=t.getPeerConnection();i&&i.connectionState===cI&&(e.log_.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}}))}},{key:"getEnableAutoPlayDialog",value:function(){return this.enableAutoPlayDialog_}},{key:"sendSEIMessage",value:function(e,t){this.uplinkConnection_.sendSEI(e,t)}},{key:"setProxyServer",value:function(e){if(this.log_.info("set proxy server: ".concat(JSON.stringify(e))),tw(e)){if(!e.startsWith("wss://"))throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_PROXY"})});this.proxy_=e}else if(QC(e)){var t=e.websocketProxy,i=e.loggerProxy;t&&(this.proxy_=t),i&&function(e){JT=e}(i)}}},{key:"setTurnServer",value:function(e){this.log_.info("set turn server: "+JSON.stringify(e));var t=[];Array.isArray(e)?e.forEach((function(e){return t.push(cw(e))})):QC(e)&&t.push(cw(e)),this.turnServers_=t}}]),e}(),w(pF.prototype,"join",[XV,ZV],Object.getOwnPropertyDescriptor(pF.prototype,"join"),pF.prototype),w(pF.prototype,"leave",[eF],Object.getOwnPropertyDescriptor(pF.prototype,"leave"),pF.prototype),w(pF.prototype,"getUserList",[tF],Object.getOwnPropertyDescriptor(pF.prototype,"getUserList"),pF.prototype),w(pF.prototype,"publish",[iF,rF],Object.getOwnPropertyDescriptor(pF.prototype,"publish"),pF.prototype),w(pF.prototype,"unpublish",[nF,sF],Object.getOwnPropertyDescriptor(pF.prototype,"unpublish"),pF.prototype),w(pF.prototype,"subscribe",[oF],Object.getOwnPropertyDescriptor(pF.prototype,"subscribe"),pF.prototype),w(pF.prototype,"unsubscribe",[aF],Object.getOwnPropertyDescriptor(pF.prototype,"unsubscribe"),pF.prototype),w(pF.prototype,"switchRole",[cF,uF],Object.getOwnPropertyDescriptor(pF.prototype,"switchRole"),pF.prototype),w(pF.prototype,"startPublishCDNStream",[dF],Object.getOwnPropertyDescriptor(pF.prototype,"startPublishCDNStream"),pF.prototype),w(pF.prototype,"startMixTranscode",[lF],Object.getOwnPropertyDescriptor(pF.prototype,"startMixTranscode"),pF.prototype),w(pF.prototype,"sendSEIMessage",[hF,mF],Object.getOwnPropertyDescriptor(pF.prototype,"sendSEIMessage"),pF.prototype),pF),EF=Rw({retryFunction:function(){var e=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!fA()){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,bF(t);case 4:if(i=e.sent,Mw.info("getUserMedia with constraints: "+JSON.stringify(i)),!i.audio){e.next=11;break}return e.next=9,VF.getMicrophones();case 9:n=e.sent,Mw.info("microphones: ".concat(JSON.stringify(n)));case 11:if(!i.video){e.next=16;break}return e.next=14,VF.getCameras();case 14:s=e.sent,Mw.info("cameras: ".concat(JSON.stringify(s)));case 16:return e.prev=16,e.next=19,navigator.mediaDevices.getUserMedia(i);case 19:return e.abrupt("return",e.sent);case 22:if(e.prev=22,e.t0=e.catch(16),"NotFoundError"!==e.t0.name){e.next=29;break}if(!s||0!==s.length){e.next=27;break}throw new ek({code:ZR.DEVICE_NOT_FOUND,message:GC({key:"CAMERA_NOT_FOUND"})});case 27:if(!n||0!==n.length){e.next=29;break}throw new ek({code:ZR.DEVICE_NOT_FOUND,message:GC({key:"MICROPHONE_NOT_FOUND"})});case 29:throw new ek({code:ZR.INITIALIZE_FAILED,name:e.t0.name,message:e.t0.message,constraint:e.t0.constraint});case 30:case"end":return e.stop()}}),e,null,[[16,22]])})));return function(t){return e.apply(this,arguments)}}(),settings:{retries:3,timeout:500},onError:function(e,t,i){"NotReadableError"===e.name?t():i(e)},onRetrying:function(e){Mw.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))}});function bF(e){return TF.apply(this,arguments)}function TF(){return(TF=o(r().mark((function e(t){var n,s,o,a,c,u;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n={echoCancellation:t.echoCancellation,autoGainControl:t.autoGainControl,noiseSuppression:t.noiseSuppression},t.audio){e.next=5;break}n=!1,e.next=15;break;case 5:if(sk(t.microphoneId)){e.next=9;break}n=i({deviceId:t.useExact?{exact:t.microphoneId}:t.microphoneId,sampleRate:t.sampleRate,channelCount:t.channelCount},n),e.next=15;break;case 9:return n=i({sampleRate:t.sampleRate,channelCount:t.channelCount},n),e.next=12,VF.getMicrophones();case 12:s=e.sent,(o=s.filter((function(e){return e.deviceId.length>0}))).length>0&&(n.deviceId={exact:o[0].deviceId});case 15:return c={ideal:t.width,max:t.width},u={ideal:t.height,max:t.height},Sb&&qb&&t.width*t.height<101376&&(c=t.width,u=t.height),a=!ew(t.facingMode)&&t.video?{facingMode:t.facingMode,width:c,height:u,frameRate:t.frameRate}:!sk(t.cameraId)&&t.video?{deviceId:t.useExact?{exact:t.cameraId}:t.cameraId,width:c,height:u,frameRate:t.frameRate}:!!t.video&&(!!ew(t.width)||{width:c,height:u,frameRate:t.frameRate}),e.abrupt("return",{audio:n,video:a});case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var IF=function(){var e=o(r().mark((function e(t){var i,n,s,o,a,c,u,d,l;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!fA()){e.next=2;break}return e.abrupt("return");case 2:if(i=null,!(dT&&lT<74||mT)){e.next=27;break}return n=wF(t),Mw.info("getDisplayMedia with constraints: "+JSON.stringify(n)),e.next=8,navigator.mediaDevices.getDisplayMedia(n);case 8:if(s=e.sent,!t.screenAudio){e.next=14;break}return Mw.warn("Your browser not support capture system audio"),e.abrupt("return",s);case 14:if(!t.audio){e.next=24;break}return o=CF(t),Mw.info("getUserMedia with constraints: "+JSON.stringify(o)),e.next=19,navigator.mediaDevices.getUserMedia(o);case 19:return i=e.sent,s.addTrack(i.getAudioTracks()[0]),e.abrupt("return",s);case 24:return e.abrupt("return",s);case 25:e.next=53;break;case 27:if(!t.screenAudio){e.next=37;break}return t.audioConstraints={echoCancellation:!0,noiseSuppression:!0,sampleRate:44100},a=wF(t),Mw.info("getDisplayMedia with constraints: "+JSON.stringify(a)),e.next=33,navigator.mediaDevices.getDisplayMedia(a);case 33:return c=e.sent,e.abrupt("return",c);case 37:return u=wF(t),Mw.info("getDisplayMedia with constraints: "+JSON.stringify(u)),e.next=41,navigator.mediaDevices.getDisplayMedia(u);case 41:if(d=e.sent,!t.audio){e.next=52;break}return l=CF(t),Mw.info("getUserMedia with constraints: "+JSON.stringify(l)),e.next=47,navigator.mediaDevices.getUserMedia(l);case 47:return i=e.sent,d.addTrack(i.getAudioTracks()[0]),e.abrupt("return",d);case 52:return e.abrupt("return",d);case 53:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function CF(e){var t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return ew(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}function wF(e){var t={},i={width:mT?{max:e.width}:{ideal:e.width,max:e.width},height:mT?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate};return ew(e.screenSource)||(i.displaySurface=e.screenSource),t.video=i,ew(e.audioConstraints)||(t.audio=e.audioConstraints),t}var RF,kF,AF,MF,OF,LF,PF,NF=new Map([["120p",{width:160,height:120,frameRate:15,bitrate:200}],["120p_2",{width:160,height:120,frameRate:15,bitrate:100}],["180p",{width:320,height:180,frameRate:15,bitrate:350}],["180p_2",{width:320,height:180,frameRate:15,bitrate:150}],["240p",{width:320,height:240,frameRate:15,bitrate:400}],["240p_2",{width:320,height:240,frameRate:15,bitrate:200}],["360p",{width:640,height:360,frameRate:15,bitrate:800}],["360p_2",{width:640,height:360,frameRate:15,bitrate:400}],["480p",{width:640,height:480,frameRate:15,bitrate:900}],["480p_2",{width:640,height:480,frameRate:15,bitrate:500}],["720p",{width:1280,height:720,frameRate:15,bitrate:1500}],["1080p",{width:1920,height:1080,frameRate:15,bitrate:2e3}],["1440p",{width:2560,height:1440,frameRate:30,bitrate:4860}],["4K",{width:3840,height:2160,frameRate:30,bitrate:9e3}]]),DF=new Map([["480p",{width:640,height:480,frameRate:5,bitrate:900}],["480p_2",{width:640,height:480,frameRate:30,bitrate:1e3}],["720p",{width:1280,height:720,frameRate:5,bitrate:1200}],["720p_2",{width:1280,height:720,frameRate:30,bitrate:3e3}],["1080p",{width:1920,height:1080,frameRate:5,bitrate:1600}],["1080p_2",{width:1920,height:1080,frameRate:30,bitrate:4e3}]]),xF=new Map([["standard",{sampleRate:48e3,channelCount:1,bitrate:40}],["standard-stereo",{sampleRate:48e3,channelCount:2,bitrate:64}],["high",{sampleRate:48e3,channelCount:1,bitrate:128}],["high-stereo",{sampleRate:48e3,channelCount:2,bitrate:192}]]),UF=(RF=cV.apply(void 0,b(oV.LOCAL_STREAM.switchDevice)),kF=EV({retries:10,timeout:3e3,onRetryFailed:function(e){ok.logFailedEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:II,error:e}),this.emitter_.emit(qA,new ek({code:ZR.DEVICE_AUTO_RECOVER_FAILED,message:e.message}))}}),AF=aV(oV.LOCAL_STREAM.setAudioCaptureVolume),w((MF=function(e){l(b,e);var t,s,c,d,m,p,f,v,g,y,E=_(b);function b(e){var t;a(this,b);var r=i(i({},e),{isRemote:!1,type:"local"});return(t=E.call(this,r)).name_=zI,t.client_=null,t.video_=e.video,t.audio_=e.audio,t.cameraId_=e.cameraId,t.cameraGroupId_="",t.facingMode_=e.facingMode,t.microphoneId_=e.microphoneId,t.microphoneGroupId_="",t.videoSource_=e.videoSource,t.audioSource_=e.audioSource,t.screen_=e.screen,t.screenSource_=e.screenSource,t.screenAudio_=e.screenAudio,t.audioProfile_={echoCancellation:!!ew(e.echoCancellation)||e.echoCancellation,autoGainControl:!!ew(e.autoGainControl)||e.autoGainControl,noiseSuppression:!!ew(e.noiseSuppression)||e.noiseSuppression,sampleRate:48e3,channelCount:1,bitrate:40},t.videoProfile_=NF.get("480p_2"),t.screenProfile_=DF.get("1080p"),t.videoSetting_=null,t.muteState_={video:!1,audio:!1,auxVideo:!1},t.beautyStatus_=!1,t.prevAudioRecoverTime_=0,t.prevVideoRecoverTime_=0,t.isAudioRecovering_=!1,t.isVideoRecovering_=!1,t.initState(),t.canvas_=null,t.canvasInterval_=null,t.gain_={audioTrack:null,source:null,gainNode:null},t.captureVolume_=100,t.log_.info("stream created: "+t.id_),t}return u(b,[{key:"initState",value:function(){this.isAddingTrack_=!1,this.isRemovingTrack_=!1,this.setIsReadyToPublish(!1),this.setPublishState(-1)}},{key:"installEvents",value:function(){S(h(b.prototype),"installEvents",this).call(this),Tw.on(120,this.onStreamPublished,this),Tw.on(135,this.onVideoTrackStopped,this),Tw.on(130,this.onVideoTrackStopped,this),Tw.on(137,this.onAudioTrackStopped,this),Tw.on(136,this.onAudioTrackStopped,this)}},{key:"uninstallEvents",value:function(){S(h(b.prototype),"uninstallEvents",this).call(this),Tw.off(120,this.onStreamPublished,this),Tw.off(135,this.onVideoTrackStopped,this),Tw.off(130,this.onVideoTrackStopped,this),Tw.off(137,this.onAudioTrackStopped,this),Tw.off(136,this.onAudioTrackStopped,this)}},{key:"initialize",value:function(){var e=this;return new Promise((function(t,i){if(vA())i(new ek({code:ZR.INVALID_OPERATION,message:GC({key:NC})}));else{if(ew(e.audio_)){var r=new MediaStream;return ew(e.audioSource_)||(r.addTrack(e.audioSource_),e.updateAudioPlayingState(!0)),ew(e.videoSource_)||(r.addTrack(e.videoSource_),e.updateVideoPlayingState(!0)),e.setMediaStream(r),ok.logSuccessEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:EI,kind:"custom"}),e.setIsReadyToPublish(!0),t()}e.screen_?(e.log_.info("initialize stream audio: "+e.audio_+" screenAudio: "+e.screenAudio_+" screen: "+e.screen_),IF({audio:e.audio_,screenAudio:e.screenAudio_,microphoneId:e.microphoneId_,screenSource:e.screenSource_,width:e.screenProfile_.width,height:e.screenProfile_.height,frameRate:e.screenProfile_.frameRate,sampleRate:e.audioProfile_.sampleRate,channelCount:e.audioProfile_.channelCount,autoGainControl:e.audioProfile_.autoGainControl,noiseSuppression:e.audioProfile_.noiseSuppression,echoCancellation:e.audioProfile_.echoCancellation}).then((function(i){e.setMediaStream(i),e.updateAudioPlayingState(e.audio_||e.screenAudio_),e.updateVideoPlayingState(!0);var r=e.getVideoTrack();return e.listenForScreenSharingStopped(r),e.setVideoContentHint("detail"),e.updateDeviceIdInUse(),e.setIsReadyToPublish(!0),e.log_.info(JSON.stringify(r.getSettings())),ok.logSuccessEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:EI,kind:"getDisplayMedia"}),t()})).catch((function(t){ok.logFailedEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:EI,kind:"getDisplayMedia",error:t}),e.log_.error("getDisplayMedia error observed "+t),i(t instanceof ek?t:new ek({code:ZR.INITIALIZE_FAILED,name:t.name,message:t.message}))}))):(Tw.emit(121,{stream:e,audio:e.audio_,video:e.video_}),e.log_.info("initialize stream audio: "+e.audio_+" video: "+e.video_),EF({audio:e.audio_,video:e.video_,facingMode:e.facingMode_,cameraId:e.cameraId_,microphoneId:e.microphoneId_,width:e.videoProfile_.width,height:e.videoProfile_.height,frameRate:e.videoProfile_.frameRate,sampleRate:e.audioProfile_.sampleRate,channelCount:e.audioProfile_.channelCount,autoGainControl:e.audioProfile_.autoGainControl,noiseSuppression:e.audioProfile_.noiseSuppression,echoCancellation:e.audioProfile_.echoCancellation}).then((function(i){return Tw.emit(122,{stream:e,audio:e.audio_,video:e.video_}),e.setMediaStream(i),i.getTracks().forEach((function(t){t.kind===RT&&CA&&(e.videoSetting_=t.getSettings()),wA&&e.log_.info("".concat(t.kind," capabilities: ").concat(JSON.stringify(t.getCapabilities())))})),e.updateAudioPlayingState(e.audio_),e.updateVideoPlayingState(e.video_),e.updateDeviceIdInUse(),e.log_.info("gotStream hasAudio: "+e.hasAudio()+" hasVideo: "+e.hasVideo()),e.setIsReadyToPublish(!0),ok.logSuccessEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:EI,kind:"getUserMedia"}),t()})).catch((function(t){Tw.emit(123,{stream:e,audio:e.audio_,video:e.video_,error:t}),ok.logFailedEvent({userId:e.client_?e.client_.getUserId():e.userId_,eventType:EI,kind:"getUserMedia",error:t}),e.log_.error("getUserMedia error observed "+t),i(t)})))}}))}},{key:"listenForScreenSharingStopped",value:function(e){var t=this;e.addEventListener("ended",(function(e){t.log_.info("screen sharing was stopped because the video track is ended"),t.emitter_.emit("screen-sharing-stopped")}))}},{key:"muteAudio",value:function(){var e=S(h(b.prototype),"muteAudio",this).call(this);return e&&(this.log_.info("localStream mute audio"),this.sendMutedFlag(wT,!0)),e}},{key:"muteVideo",value:function(){var e=S(h(b.prototype),"muteVideo",this).call(this);return e&&(this.log_.info("localStream mute video"),this.sendMutedFlag(RT,!0)),e}},{key:"unmuteAudio",value:function(){var e=S(h(b.prototype),"unmuteAudio",this).call(this);return e&&(this.log_.info("localStream unmute audio"),this.sendMutedFlag(wT,!1)),e}},{key:"unmuteVideo",value:function(){var e=S(h(b.prototype),"unmuteVideo",this).call(this);return e&&(this.log_.info("localStream unmute video"),this.sendMutedFlag(RT,!1)),e}},{key:"sendMutedFlag",value:function(e,t){this.setMuteState(e,t);var i=this.getConnection();if(i){i.sendMutedFlag(this.muteState_);var r=i.getUserId(),n=i.getTinyId(),s="".concat(t?OT:LT," local ").concat(e," track");ik(r,{eventId:e===wT?t?32772:32774:t?32773:32775,eventDesc:s,timestamp:qv(),userId:r,tinyId:n})}}},{key:"setMuteState",value:function(e,t){this.muteState_[e]=t,this.log_.info("set ".concat(e," muted state: [").concat(t?"mute":"unmute","]"))}},{key:"setAudioProfile",value:function(e){var t;"object"===n(e)?t=e:void 0===(t=xF.get(e))&&(t=xF.get("standard")),this.log_.info("setAudioProfile: "+JSON.stringify(t)),this.audioProfile_=i(i({},this.audioProfile_),t)}},{key:"setVideoProfile",value:(y=o(r().mark((function e(t){var n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.connection_||pA()){e.next=2;break}throw new ek({code:ZR.NOT_SUPPORTED,message:GC({key:"NOT_SUPPORTED_PROFILE"})});case 2:if(QC(t)?n=i(i({},this.videoProfile_),t):tw(t)&&(n=NF.get(t),ew(n)&&(n=NF.get("480p_2"))),n&&n.width*n.height>921600&&yT&&(n.width=1280,n.height=720,this.log_.warn("reset to 1280 * 720 on iOS 13~14")),this.log_.info("setVideoProfile "+JSON.stringify(n)),!(s=this.getVideoTrack())){e.next=9;break}return e.next=9,s.applyConstraints(n);case 9:if(o=this.videoProfile_.bitrate!==n.bitrate,this.videoProfile_=n,!o||!this.connection_){e.next=15;break}return e.next=14,this.connection_.setBandwidth(n.bitrate,RT);case 14:this.connection_.updateMediaSettings(this.mediaStream_);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return y.apply(this,arguments)})},{key:"getVideoBitrate",value:function(){return this.screen_?this.screenProfile_.bitrate:this.videoProfile_.bitrate}},{key:"getAudioBitrate",value:function(){return this.audioProfile_.bitrate}},{key:"setScreenProfile",value:function(e){var t=e;tw(e)&&(t=DF.get(e)||DF.get("1080p")),this.log_.info("setScreenProfile "+JSON.stringify(e)),this.screenProfile_=t}},{key:"getVideoProfile",value:function(){return this.screen_?this.screenProfile_:this.videoProfile_}},{key:"getAudioProfile",value:function(){return this.audioProfile_}},{key:"setVideoContentHint",value:function(e){var t=this.getVideoTrack();t&&"contentHint"in t&&(this.log_.info("set video track contentHint to: "+e),t.contentHint=e,t.contentHint!==e&&this.log_.warn("Invalid video track contentHint: "+e))}},{key:"switchDevice",value:(g=o(r().mark((function e(t,i){var n,s,o,a,c,u,d,l,h,m,p,f,v,g,_,y,S;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(n=t===wT)){e.next=8;break}if(this.microphoneId_!==i){e.next=4;break}return e.abrupt("return");case 4:this.microphoneId_=i,this.audio_=!0,e.next=12;break;case 8:if(this.cameraId_!==i){e.next=10;break}return e.abrupt("return");case 10:"user"===i||i===MT?this.facingMode_=i:this.cameraId_=i,this.video_=!0;case 12:if(this.getMediaStream()){e.next=14;break}return e.abrupt("return");case 14:return this.setIsReadyToPublish(!1),this.log_.info("switchDevice "+t+" to: "+i),n||((s=this.getVideoTrack())&&s.stop(),eT&&(o=this.getAudioTrack())&&(this.log_.info("stop audio track first in huawei env"),o.stop())),n&&(a=this.getAudioTrack(),c=this.getMicrophoneTrackMixed(),a&&a.stop(),c&&c.stop()),e.next=20,EF({audio:this.audio_&&t===wT||eT,video:this.video_&&t===RT,facingMode:"user"===i||i===MT?i:void 0,cameraId:this.cameraId_,microphoneId:this.microphoneId_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount,useExact:!0});case 20:if(u=e.sent,d=null,!n){e.next=27;break}(l=u.getAudioTracks()[0])&&this.isAudioTrackMixed()?(h=this.getAudioTrack(),m=VF.AudioMixerPlugin.getAudioTrackMap(),p=VF.AudioMixerPlugin.mix({targetTrack:l,sourceList:m.get(h.id).sourceList,trackList:m.get(h.id).trackList}),d=p):d=l,e.next=36;break;case 27:if(!(d=u.getVideoTracks()[0])||!this.isVideoTrackBeautified()){e.next=32;break}return e.next=31,this.generateBeautyTrack(d);case 31:d=e.sent;case 32:if(!(f=u.getAudioTracks()[0])||!eT){e.next=36;break}return e.next=36,this.replaceTrack_(f);case 36:return e.next=38,this.replaceTrack_(d);case 38:this.updateDeviceIdInUse(),(v=this.getConnection())&&(g=v.getUserId(),_=v.getTinyId(),y=32780,S="switch camera",n&&(y=32781,S="switch microphone"),ik(g,{eventId:y,eventDesc:S,timestamp:qv(),userId:g,tinyId:_})),this.log_.info("switch ".concat(n?"microphone":"camera"," success ")),this.setIsReadyToPublish(!0);case 43:case"end":return e.stop()}}),e,this)}))),function(e,t){return g.apply(this,arguments)})},{key:"addTrack",value:(v=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isAddingTrack_){e.next=2;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_ADD_TRACK_REPETITIVE"})});case 2:if(!this.isRemovingTrack_){e.next=4;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_ADD_TRACK_REMOVING"})});case 4:if(0!==this.publishState_){e.next=6;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_ADD_TRACK_PUBLISHING"})});case 6:if(i=this.getMediaStream()){e.next=9;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:OC})});case 9:if(!(t.kind===wT&&i.getAudioTracks().length>0||t.kind===RT&&i.getVideoTracks().length>0)){e.next=11;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_ADD_TRACK_NUMBER"})});case 11:if(t.kind===RT&&CA&&(n=t.getSettings(),!this.videoSetting_||n.width===this.videoSetting_.width&&n.height===this.videoSetting_.height||this.log_.warn("video resolution of the track (".concat(n.width," x ").concat(n.height,") shall be kept the same as the previous: ").concat(this.videoSetting_.width," x ").concat(this.videoSetting_.height,". It may cause abnormal Cloud Recording."))),e.prev=12,this.isAddingTrack_=!0,this.keepMuteState(t),i.addTrack(t),!(s=this.getConnection())){e.next=20;break}return e.next=20,s.addTrack(t);case 20:t.kind===wT?(this.audio_=!0,this.updateAudioPlayingState(!0)):(this.video_=!0,this.updateVideoPlayingState(!0)),this.isAddingTrack_=!1,e.next=29;break;case 24:throw e.prev=24,e.t0=e.catch(12),i.removeTrack(t),this.isAddingTrack_=!1,e.t0;case 29:case"end":return e.stop()}}),e,this,[[12,24]])}))),function(e){return v.apply(this,arguments)})},{key:"removeTrack",value:(f=o(r().mark((function e(t){var i,n;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.kind!==wT){e.next=2;break}throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_REMOVE_AUDIO_TRACK"})});case 2:if(!this.isAddingTrack_){e.next=4;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_REMOVE_AUDIO_ADDING"})});case 4:if(!this.isRemovingTrack_){e.next=6;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_REMOVE_AUDIO_ON"})});case 6:if(0!==this.publishState_){e.next=8;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_REMOVE_TRACK_PUBLISHING"})});case 8:if(i=this.getMediaStream()){e.next=11;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:OC})});case 11:if(-1!==i.getTracks().indexOf(t)){e.next=13;break}throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_REMOVE_TRACK_NOT_PUBLISHING"})});case 13:if(1!==i.getTracks().length){e.next=15;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_REMOVE_TRACK_NUMBER"})});case 15:if(e.prev=15,this.isRemovingTrack_=!0,!(n=this.getConnection())){e.next=21;break}return e.next=21,n.removeTrack(t);case 21:i.removeTrack(t),t.kind===wT?(this.audio_=!1,this.updateAudioPlayingState(!1)):(this.video_=!1,this.updateVideoPlayingState(!1)),this.isRemovingTrack_=!1,e.next=30;break;case 26:throw e.prev=26,e.t0=e.catch(15),this.isRemovingTrack_=!1,e.t0;case 30:case"end":return e.stop()}}),e,this,[[15,26]])}))),function(e){return f.apply(this,arguments)})},{key:"replaceTrack",value:(p=o(r().mark((function e(t){var i,n,s;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=this.getMediaStream()){e.next=3;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:"INVALID_INITIALIZE_LOCAL_STREAM"})});case 3:if(0!==this.publishState_){e.next=5;break}throw new ek({code:ZR.INVALID_OPERATION,message:GC({key:MC})});case 5:if(!(t.kind===wT&&i.getAudioTracks().length<=0||t.kind===RT&&i.getVideoTracks().length<=0)){e.next=7;break}throw new ek({code:ZR.INVALID_PARAMETER,message:GC({key:"INVALID_REMOVE_TRACK_NOT_PUBLISHED",data:t})});case 7:if(t.kind===RT&&CA&&(n=t.getSettings(),!this.videoSetting_||n.width===this.videoSetting_.width&&n.height===this.videoSetting_.height||this.log_.warn("video resolution of the track (".concat(n.width," x ").concat(n.height,") shall be kept the same as the previous: ").concat(this.videoSetting_.width," x ").concat(this.videoSetting_.height,". It may cause abnormal Cloud Recording."))),this.keepMuteState(t),t.kind!==wT){e.next=18;break}if(i.removeTrack(i.getAudioTracks()[0]),i.addTrack(t),S(h(b.prototype),"restartAudio",this).call(this),!this.gain_.gainNode){e.next=16;break}return this.reconnectGainNode(t),e.abrupt("return");case 16:e.next=21;break;case 18:i.removeTrack(i.getVideoTracks()[0]),i.addTrack(t),S(h(b.prototype),"restartVideo",this).call(this);case 21:if(!(s=this.getConnection())){e.next=25;break}return e.next=25,s.replaceTrack(t);case 25:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"recoverCapture",value:(m=o(r().mark((function e(t){var i,n,s,o,a,c,u,d,l,h,m,p,f,v,g,_,y;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.mediaStream_){e.next=2;break}return e.abrupt("return");case 2:return this.log_.warn("recoverCapture() trying "+JSON.stringify(t)),i=this.audio_&&t.audio,n=this.video_&&t.video,e.prev=5,e.next=8,VF.getCameras();case 8:return s=e.sent,e.next=11,VF.getMicrophones();case 11:if(o=e.sent,n&&0===s.length&&(n=!1,this.log_.warn("recoverCapture() video flag is true, but no camera detected, set video to false")),i&&0===o.length&&(i=!1,this.log_.warn("recoverCapture() audio flag is true, but no microphone detected, set audio to false")),!1!==i||!1!==n){e.next=17;break}return this.log_.warn("recoverCapture() both audio and video are false, aborted"),e.abrupt("return");case 17:return a=t&&s.findIndex((function(e){return e.deviceId===t.cameraId}))>=0,c=t&&o.findIndex((function(e){return e.deviceId===t.microphoneId}))>=0,e.next=21,EF({audio:i,video:n,cameraId:a?t.cameraId:void 0,microphoneId:c?t.microphoneId:void 0,facingMode:this.facingMode_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount});case 21:u=e.sent,d=u.getTracks(),l=0;case 24:if(!(l<d.length)){e.next=51;break}if((h=d[l]).kind!==wT||!this.isAudioTrackMixed()){e.next=37;break}if(m=this.getAudioTrack(),p=VF.AudioMixerPlugin.getAudioTrackMap(),(f=p.get(m.id)).hasMicrophone){e.next=33;break}return h.stop(),e.abrupt("continue",48);case 33:return v=VF.AudioMixerPlugin.mix({targetTrack:h,sourceList:f.sourceList,trackList:f.trackList}),e.next=36,this.replaceTrack_(v);case 36:return e.abrupt("continue",48);case 37:if(h.kind!==RT||!this.isVideoTrackBeautified()){e.next=44;break}return e.next=40,this.generateBeautyTrack(h);case 40:return g=e.sent,e.next=43,this.replaceTrack_(g);case 43:return e.abrupt("continue",48);case 44:return h.kind===wT&&(null===(_=this.getAudioTrack())||void 0===_||_.stop()),h.kind===RT&&(null===(y=this.getVideoTrack())||void 0===y||y.stop()),e.next=48,this.replaceTrack_(h);case 48:l++,e.next=24;break;case 51:this.updateDeviceIdInUse(),ok.logSuccessEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:II}),this.log_.warn("recoverCapture() successfully"),this.emitter_.emit("device-auto-recovered",{isCamera:t.video,isMicrophone:t.audio,cameraId:this.cameraId_,microphoneId:this.microphoneId_}),e.next=61;break;case 57:throw e.prev=57,e.t0=e.catch(5),this.log_.warn("recoverCapture() failed, "+e.t0),e.t0;case 61:case"end":return e.stop()}}),e,this,[[5,57]])}))),function(e){return m.apply(this,arguments)})},{key:"replaceTrack_",value:(d=o(r().mark((function e(t){var i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=this.mediaStream_.getAudioTracks(),n=this.mediaStream_.getVideoTracks(),!(t.kind===wT&&i.length<=0||t.kind===RT&&n.length<=0)){e.next=5;break}return this.log_.info("there is no previous ".concat(t.kind," track, replacement ignored")),e.abrupt("return");case 5:if(this.keepMuteState(t),t.kind!==wT){e.next=15;break}if(this.mediaStream_.removeTrack(i[0]),this.mediaStream_.addTrack(t),S(h(b.prototype),"restartAudio",this).call(this),!this.gain_.gainNode){e.next=13;break}return this.reconnectGainNode(t),e.abrupt("return");case 13:e.next=19;break;case 15:CA&&(s=t.getSettings(),!this.videoSetting_||s.width===this.videoSetting_.width&&s.height===this.videoSetting_.height||this.log_.warn("the resolution of video track to be replaced (".concat(s.width," x ").concat(s.height,") is different from the previous video settings (").concat(this.videoSetting_.width," x ").concat(this.videoSetting_.height,"). It may cause a cloud recording exception"))),this.mediaStream_.removeTrack(n[0]),this.mediaStream_.addTrack(t),S(h(b.prototype),"restartVideo",this).call(this);case 19:if(!(o=this.getConnection())){e.next=23;break}return e.next=23,o.replaceTrack(t);case 23:case"end":return e.stop()}}),e,this)}))),function(e){return d.apply(this,arguments)})},{key:"updateDeviceIdInUse",value:function(){var e=this;if(!this.mediaStream_)return this.cameraId_="",this.cameraGroupId_="",this.microphoneId_="",void(this.microphoneGroupId_="");CA&&this.mediaStream_.getTracks().forEach((function(t){if(t.kind===wT&&e.isAudioTrackMixed()){var i=e.getMicrophoneTrackMixed();if(i){var r=i.getSettings(),n=r.deviceId,s=r.groupId;n&&(e.microphoneId_=n,e.microphoneGroupId_=s)}}else if(t.kind===RT&&e.isVideoTrackBeautified()){var o=e.getBeautyOriginTrack();if(o){var a=o.getSettings(),c=a.deviceId,u=a.groupId;c&&(e.cameraId_=c,e.cameraGroupId_=u)}}else{var d=t.getSettings(),l=d.deviceId,h=d.groupId;l&&(t.kind===wT?(e.microphoneId_=l,e.microphoneGroupId_=h):t.kind!==RT||e.screen_||(e.cameraId_=l,e.cameraGroupId_=h))}}));var t=this.mediaStream_.getAudioTracks(),i=this.mediaStream_.getVideoTracks();t&&0===t.length&&(this.microphoneId_="",this.microphoneGroupId_=""),i&&0===i.length&&(this.cameraId_="",this.cameraGroupId_="")}},{key:"isAudioTrackMixed",value:function(){if(VF.AudioMixerPlugin){var e=VF.AudioMixerPlugin.getAudioTrackMap(),t=this.getAudioTrack();if(e&&t&&e.has(t.id))return!0}return!1}},{key:"getMicrophoneTrackMixed",value:function(){if(VF.AudioMixerPlugin){var e=VF.AudioMixerPlugin.getAudioTrackMap(),t=this.getAudioTrack();if(e&&t&&e.has(t.id)){var i=e.get(t.id);return i.hasMicrophone?i.microphoneTrack:null}}return null}},{key:"isVideoTrackBeautified",value:function(){if(VF.beautyTrackMap){var e=VF.beautyTrackMap,t=this.getVideoTrack();if(t&&e.has(t.id))return!0}return!1}},{key:"getBeautyOriginTrack",value:function(){if(VF.beautyTrackMap){var e=VF.beautyTrackMap,t=this.getVideoTrack();if(t&&e.has(t.id)){var i=e.get(t.id);if(i.originTrack)return i.originTrack}}return null}},{key:"generateBeautyTrack",value:(c=o(r().mark((function e(t){var i,n,s,o;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=null,n=this.getVideoTrack(),s=VF.beautyTrackMap.get(n.id),o=s.param,s.type){e.next=8;break}i=s.pluginInstance.generateBeautyTrack(t),e.next=22;break;case 8:e.t0=s.type,e.next="beauty"===e.t0?11:"virtual"===e.t0?13:"mixed"===e.t0?17:21;break;case 11:return i=s.pluginInstance.generateBeautyTrack(t),e.abrupt("break",22);case 13:return e.next=15,s.pluginInstance.generateVirtualTrack({videoTrack:t,type:o.type,img:o.img});case 15:case 19:return i=e.sent,e.abrupt("break",22);case 17:return e.next=19,s.pluginInstance.generateMixedTrack({videoTrack:t,type:o.type,img:o.img});case 21:return e.abrupt("break",22);case 22:return s.pluginInstance.deleteSource(n.id),this.log_.info("regenerate beauty track, track id = ".concat(t.id)),e.abrupt("return",i);case 25:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"getScreen",value:function(){return this.screen_}},{key:"hasScreenTrack",value:function(){if(this.screen_)return!0;var e=this.getVideoTrack();return!!e&&("detail"===e.contentHint||"text"===e.contentHint)}},{key:"getVideo",value:function(){return this.video_}},{key:"getAudio",value:function(){return this.audio_}},{key:"getCameraId",value:function(){return this.cameraId_}},{key:"getMicrophoneId",value:function(){return this.microphoneId_}},{key:"getMicrophoneGroupId",value:function(){return this.microphoneGroupId_}},{key:"getIsReadyToPublish",value:function(){return this.isReadyToPublish_}},{key:"setIsReadyToPublish",value:function(e){this.isReadyToPublish_=e}},{key:"setPublishState",value:function(e){this.publishState_=e}},{key:"setBeautyStatus",value:function(e){this.beautyStatus_=!!e}},{key:"getBeautyStatus",value:function(){return this.beautyStatus_}},{key:"onStreamPublished",value:function(e){var t=e.localStream,i=e.client;t===this&&(this.client_=i,this.log_.setUserId(i.getUserId()),this.log_.setSdkAppId(i.getSDKAppId()),this.syncMuteState())}},{key:"syncMuteState",value:function(){var e=this.getAudioTrack(),t=this.getVideoTrack();if(e){var i=!e.enabled;this.setMuteState(wT,i)}if(t){var r=!t.enabled;this.setMuteState(RT,r)}this.connection_&&this.connection_.sendMutedFlag(this.muteState_)}},{key:"keepMuteState",value:function(e){e instanceof MediaStreamTrack&&this.muteState_[e.kind]&&(e.enabled=!1,this.log_.warn("prev ".concat(e.kind," track is muted, keep mute state")))}},{key:"onVideoTrackStopped",value:(s=o(r().mark((function e(t){var i,n,s,o,a=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=t.stream,n=t.type,i===this&&this.video_&&this.cameraId_&&!this.isVideoRecovering_&&(!(qb&&mT||_b&&Number(vT)>=15.1)||n!==OT)){e.next=3;break}return e.abrupt("return");case 3:if(!(Date.now()-this.prevVideoRecoverTime_<2e3)){e.next=6;break}return setTimeout((function(){return a.onVideoTrackStopped({stream:i,type:n})}),2e3),e.abrupt("return");case 6:if(!(s=this.getVideoTrack())){e.next=14;break}return o=s.getSettings().deviceId,e.next=11,VF.getCameras();case 11:if(!(e.sent.findIndex((function(e){return e.deviceId===o}))<0)){e.next=14;break}return e.abrupt("return");case 14:n===OT?setTimeout((function(){var e=a.getVideoTrack();null!=e&&e.muted&&"visible"===document.visibilityState&&a.recoverVideoCapture(n)}),1e3):this.recoverVideoCapture(n);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"onAudioTrackStopped",value:(t=o(r().mark((function e(t){var i,n,s,o,a,c,u=this;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=t.stream,n=t.type,i===this&&this.audio_&&this.microphoneId_&&!this.isAudioRecovering_&&(!(qb&&mT||_b&&Number(vT)>=15.1)||n!==OT)){e.next=3;break}return e.abrupt("return");case 3:if(!(Date.now()-this.prevAudioRecoverTime_<2e3)){e.next=6;break}return setTimeout((function(){return u.onAudioTrackStopped({stream:i,type:n})}),2e3),e.abrupt("return");case 6:if(!(s=this.getAudioTrack())){e.next=14;break}return o=s.getSettings(),a=o.groupId,c=o.deviceId,e.next=11,VF.getMicrophones();case 11:if(!(e.sent.findIndex((function(e){return e.deviceId===c&&(ew(a)||a===e.groupId)}))<0)){e.next=14;break}return e.abrupt("return");case 14:n===OT?setTimeout((function(){var e=u.getAudioTrack();null!=e&&e.muted&&"visible"===document.visibilityState&&u.recoverAudioCapture(n)}),1e3):this.recoverAudioCapture(n);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"recoverAudioCapture",value:function(e){var t=this;this.prevAudioRecoverTime_=Date.now(),ok.uploadEvent({log:"stat-local-audio-".concat(e),userId:this.userId_}),this.isAudioRecovering_=!0,this.recoverCapture({audio:!0,video:!1,microphoneId:this.microphoneId_}).then((function(){t.isAudioRecovering_=!1})).catch((function(){t.isAudioRecovering_=!1}))}},{key:"recoverVideoCapture",value:function(e){var t=this;this.isVideoRecovering_||(this.prevVideoRecoverTime_=Date.now(),ok.uploadEvent({log:"stat-local-video-".concat(e),userId:this.userId_}),this.isVideoRecovering_=!0,this.recoverCapture({audio:!1,video:!0,cameraId:this.cameraId_}).then((function(){t.isVideoRecovering_=!1})).catch((function(){t.isVideoRecovering_=!1})))}},{key:"setAudioVolume",value:function(e){S(h(b.prototype),"setAudioVolume",this).call(this,e)}},{key:"clearCanvas",value:function(){this.canvasInterval_&&(Qk.clearTask(this.canvasInterval_),this.canvasInterval_=null,this.canvas_=null)}},{key:"genCanvasTrack",value:function(e){var t=this;this.log_.info("gen canvas track");var i=e.getSettings(),r=i.width,n=i.height,s=i.frameRate;this.canvas_=document.createElement("canvas");var o=this.canvas_.getContext("2d");return this.canvas_.width=r,this.canvas_.height=n,this.canvasInterval_=Qk.run(uC,(function(){if(t.hasVideo()){var e=t.getVideoTrack().getSettings();e.width===t.canvas_.width&&e.height===t.canvas_.height||(t.canvas_.width=e.width,t.canvas_.height=e.height)}t.videoPlayer_&&t.videoPlayer_.element_&&o.drawImage(t.videoPlayer_.element_,0,0,t.canvas_.width,t.canvas_.height)}),{fps:Math.max(15,s)}),this.canvas_.captureStream().getVideoTracks()[0]}},{key:"setClient",value:function(e){this.client_=e}},{key:"setAudioCaptureVolume",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!this.hasAudio()||t<0||!mA())return!1;if(this.captureVolume_===t)return!0;this.captureVolume_=t,this.log_.info("setCaptureVolume "+t),t/=100;var i=fw();if(this.gain_.gainNode)this.gain_.gainNode.gain.value=t;else{var r,n=new MediaStream;n.addTrack(this.getAudioTrack());var s=i.createMediaStreamDestination(),o=i.createMediaStreamSource(n),a=i.createGain();a.gain.value=t,o.connect(a),a.connect(s);var c=s.stream.getAudioTracks()[0],u=function(t){return e.log_.info("gained audio track ".concat(t))};c.onmute=function(){return u("muted")},c.onunmute=function(){return u("unmuted")},c.onended=function(){return u("ended")},this.gain_={source:o,audioTrack:c,gainNode:a},null===(r=this.connection_)||void 0===r||r.replaceTrack(c),S(h(b.prototype),"restartAudio",this).call(this)}return!0}},{key:"getGainedTrack",value:function(){return this.gain_.audioTrack}},{key:"reconnectGainNode",value:function(e){this.log_.warn("reconnect gain node");var t=new MediaStream;t.addTrack(e);var i=fw().createMediaStreamSource(t);i.connect(this.gain_.gainNode),this.gain_.source.disconnect(),this.gain_.source=i}},{key:"close",value:function(){this.setIsReadyToPublish(!1);var e=this.gain_,t=e.audioTrack,i=e.source,r=e.gainNode;r&&(i.disconnect(),r.disconnect(),t.onmute=null,t.onunmute=null,t.onended=null,t.stop(),this.gain_={source:null,gainNode:null,audioTrack:null}),S(h(b.prototype),"close",this).call(this)}}]),b}(lV)).prototype,"switchDevice",[RF],Object.getOwnPropertyDescriptor(MF.prototype,"switchDevice"),MF.prototype),w(MF.prototype,"recoverCapture",[kF],Object.getOwnPropertyDescriptor(MF.prototype,"recoverCapture"),MF.prototype),w(MF.prototype,"setAudioCaptureVolume",[AF],Object.getOwnPropertyDescriptor(MF.prototype,"setAudioCaptureVolume"),MF.prototype),MF),$F=0,BF=0,VF=new(OF=aV(oV.TRTC.createClient),LF=aV(oV.TRTC.createStream),w((PF=function(){function e(){a(this,e),this.name_="TRTC",this.VERSION=Uo,this.Logger={loggerManager:Mw,LogLevel:sC,setLogLevel:function(e){Mw.setLogLevel(e),e<=1&&function(){if(!ET())return!1;var e=localStorage.getItem(iC);e&&!function(e){var t=e.saveTime&&(new Date).getTime()-e.saveTime>=HI,i=!e.saveVersion||e.saveVersion!==Uo;return t||i}(JSON.parse(e))||(Mw.info("init debug info"),function(){var e=new XMLHttpRequest;if(e.open("GET","https://web.sdk.qcloud.com/trtc/webrtc/download/error-message/0.0.3/script.js",!1),e.send(null),4===e.readyState&&200===e.status){var t=document.createElement("script");t.type="text/javascript",t.text=e.responseText,document.body.appendChild(t),localStorage.setItem(iC,JSON.stringify({message:e.responseText,saveTime:(new Date).getTime(),saveVersion:Uo})),document.body.removeChild(t)}}())}()},enableUploadLog:function(){Mw.enableUploadLog()},disableUploadLog:function(){Mw.warn("disableUploadLog"),Mw.disableUploadLog()}}}var t,n,s,c,d;return u(e,[{key:"checkSystemRequirements",value:(d=o(r().mark((function e(){return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,aA();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e)}))),function(){return d.apply(this,arguments)})},{key:"isScreenShareSupported",value:function(){return uA()}},{key:"isSmallStreamSupported",value:function(){return IA()}},{key:"getDevices",value:(c=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!vA()&&!fA()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return e.kind!==$T||e.deviceId!=nC})).map((function(e,t){var i=e.label;e.label||(i=e.kind+"_"+t);var r={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(r.groupId=e.groupId),e.getCapabilities&&(r.getCapabilities=function(){return e.getCapabilities()}),r})));case 6:case"end":return e.stop()}}),e)}))),function(){return c.apply(this,arguments)})},{key:"getCameras",value:(s=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!vA()&&!fA()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return e.kind===BT})).map((function(e,t){var i=e.label;e.label||(i="camera_"+t);var r={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(r.groupId=e.groupId),e.getCapabilities&&(r.getCapabilities=function(){return e.getCapabilities()}),r})));case 6:case"end":return e.stop()}}),e)}))),function(){return s.apply(this,arguments)})},{key:"getMicrophones",value:(n=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!vA()&&!fA()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return e.kind===$T&&e.deviceId!==nC})).map((function(e,t){var i=e.label;e.label||(i="microphone_"+t);var r={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(r.groupId=e.groupId),e.getCapabilities&&(r.getCapabilities=function(){return e.getCapabilities()}),r})));case 6:case"end":return e.stop()}}),e)}))),function(){return n.apply(this,arguments)})},{key:"getSpeakers",value:(t=o(r().mark((function e(){var t;return r().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!vA()&&!fA()){e.next=2;break}return e.abrupt("return",[]);case 2:return e.next=4,navigator.mediaDevices.enumerateDevices();case 4:return t=e.sent,e.abrupt("return",t.filter((function(e){return"audiooutput"===e.kind})).map((function(e,t){var i=e.label;e.label||(i="speaker_"+t);var r={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(r.groupId=e.groupId),r})));case 6:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})},{key:"createClient",value:function(e){Ow&&(Ow=!1,Mw.getLogLevel()!=VF.Logger.LogLevel.NONE&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: "+"".concat(tC,"index.html")),console.info("* Changelog: https://cloud.tencent.com/document/product/647/38958"),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),Mw.info("TRTC Web SDK Version: 4.14.7"),Mw.info("UserAgent: "+navigator.userAgent),Mw.info("URL of current page: "+location.href));var t={version:this.VERSION},r=new SF(i(i(i({},t),e),{},{seq:++$F}));return Tw.emit(30,{client:r}),r}},{key:"createStream",value:function(e){return new UF(i(i({},e),{},{seq:++BF}))}}]),e}()).prototype,"createClient",[OF],Object.getOwnPropertyDescriptor(PF.prototype,"createClient"),PF.prototype),w(PF.prototype,"createStream",[LF],Object.getOwnPropertyDescriptor(PF.prototype,"createStream"),PF.prototype),PF);return VF}()}).call(this,i(7))},function(e,t){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(e){"object"==typeof window&&(i=window)}e.exports=i},function(e,t,i){i.d(t,"a",(function(){return o}));var r=i(0),n=i(3),s=i(4);function o(e){return r.d(e)&&s.a(Object(n.a)(e),"[native code]")}},function(e,t){var i,r,n=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(e){if(i===setTimeout)return setTimeout(e,0);if((i===s||!i)&&setTimeout)return i=setTimeout,setTimeout(e,0);try{return i(e,0)}catch(t){try{return i.call(null,e,0)}catch(t){return i.call(this,e,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:s}catch(e){i=s}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var c,u=[],d=!1,l=-1;function h(){d&&c&&(d=!1,c.length?u=c.concat(u):l=-1,u.length&&m())}function m(){if(!d){var e=a(h);d=!0;for(var t=u.length;t;){for(c=u,u=[];++l<t;)c&&c[l].run();l=-1,t=u.length}c=null,d=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===o||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function f(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];u.push(new p(e,t)),1!==u.length||d||a(m)},p.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=f,n.addListener=f,n.once=f,n.off=f,n.removeListener=f,n.removeAllListeners=f,n.emit=f,n.prependListener=f,n.prependOnceListener=f,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},function(e,t){var i=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,names:["value","uri","config"],format:function(e){return null!=e.config?"extmap:%s %s %s":"extmap:%s %s"}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_]*):(.*)/,names:["id","attribute","value"],format:"ssrc:%d %s:%s"},{push:"ssrcGroups",reg:/^ssrc-group:(\w*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))},function(e,t,i){var r=i(17);e.exports=function(e){var t,n={stun:(e||{}).stun||i(18),turn:(e||{}).turn||i(19)},s=(e||{}).stunCount||2,o=(e||{}).turnCount||0;function a(e,t){for(var i,s=[],o=[].concat(n[e]);o.length&&s.length<t;)i=Math.random()*o.length|0,s=s.concat(o.splice(i,1));return s.map((function(t){return"string"==typeof t||t instanceof String?r(e+":"+t):t}))}return t=[].concat(a("stun",s)),o&&(t=t.concat(a("turn",o))),t}},function(e,t,i){t.Interop=i(20)},function(e,t,i){const r=i(26)("h264-profile-level-id");r.log=console.info.bind(console),t.ProfileConstrainedBaseline=1,t.ProfileBaseline=2,t.ProfileMain=3,t.ProfileConstrainedHigh=4,t.ProfileHigh=5,t.Level1_b=0,t.Level1=10,t.Level1_1=11,t.Level1_2=12,t.Level1_3=13,t.Level2=20,t.Level2_1=21,t.Level2_2=22,t.Level3=30,t.Level3_1=31,t.Level3_2=32,t.Level4=40,t.Level4_1=41,t.Level4_2=42,t.Level5=50,t.Level5_1=51,t.Level5_2=52;class n{constructor(e,t){this.profile=e,this.level=t}}t.ProfileLevelId=n;const s=new n(1,31);class o{constructor(e){this._mask=~u("x",e),this._maskedValue=u("1",e)}isMatch(e){return this._maskedValue===(e&this._mask)}}class a{constructor(e,t,i){this.profile_idc=e,this.profile_iop=t,this.profile=i}}const c=[new a(66,new o("x1xx0000"),1),new a(77,new o("1xxx0000"),1),new a(88,new o("11xx0000"),1),new a(66,new o("x0xx0000"),2),new a(88,new o("10xx0000"),2),new a(77,new o("0x0x0000"),3),new a(100,new o("00000000"),5),new a(100,new o("00001100"),4)];function u(e,t){return(t[0]===e)<<7|(t[1]===e)<<6|(t[2]===e)<<5|(t[3]===e)<<4|(t[4]===e)<<3|(t[5]===e)<<2|(t[6]===e)<<1|(t[7]===e)<<0}function d(e={}){const t=e["level-asymmetry-allowed"];return 1===t||"1"===t}t.parseProfileLevelId=function(e){if("string"!=typeof e||6!==e.length)return null;const t=parseInt(e,16);if(0===t)return null;const i=255&t,s=t>>8&255,o=t>>16&255;let a;switch(i){case 11:a=0!=(16&s)?0:11;break;case 10:case 12:case 13:case 20:case 21:case 22:case 30:case 31:case 32:case 40:case 41:case 42:case 50:case 51:case 52:a=i;break;default:return r("parseProfileLevelId() | unrecognized level_idc:%s",i),null}for(const e of c)if(o===e.profile_idc&&e.profile_iop.isMatch(s))return new n(e.profile,a);return r("parseProfileLevelId() | unrecognized profile_idc/profile_iop combination"),null},t.profileLevelIdToString=function(e){if(0==e.level)switch(e.profile){case 1:return"42f00b";case 2:return"42100b";case 3:return"4d100b";default:return r("profileLevelIdToString() | Level 1_b not is allowed for profile:%s",e.profile),null}let t;switch(e.profile){case 1:t="42e0";break;case 2:t="4200";break;case 3:t="4d00";break;case 4:t="640c";break;case 5:t="6400";break;default:return r("profileLevelIdToString() | unrecognized profile:%s",e.profile),null}let i=e.level.toString(16);return 1===i.length&&(i="0"+i),`${t}${i}`},t.parseSdpProfileLevelId=function(e={}){const i=e["profile-level-id"];return i?t.parseProfileLevelId(i):s},t.isSameProfile=function(e={},i={}){const r=t.parseSdpProfileLevelId(e),n=t.parseSdpProfileLevelId(i);return Boolean(r&&n&&r.profile===n.profile)},t.generateProfileLevelIdForAnswer=function(e={},i={}){if(!e["profile-level-id"]&&!i["profile-level-id"])return r("generateProfileLevelIdForAnswer() | no profile-level-id in local and remote params"),null;const s=t.parseSdpProfileLevelId(e),o=t.parseSdpProfileLevelId(i);if(!s)throw new TypeError("invalid local_profile_level_id");if(!o)throw new TypeError("invalid remote_profile_level_id");if(s.profile!==o.profile)throw new TypeError("H264 Profile mismatch");const a=d(e)&&d(i),c=s.level,u=function(e,t){return 0===e?10!==t&&0!==t:0===t?10!==e:e<t}(l=c,h=o.level)?l:h;var l,h;const m=a?c:u;return r("generateProfileLevelIdForAnswer() | result: [profile:%s, level:%s]",s.profile,m),t.profileLevelIdToString(new n(s.profile,m))}},function(e,t,i){(function(e){var r=void 0!==e&&e||"undefined"!=typeof self&&self||window,n=Function.prototype.apply;function s(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new s(n.call(setTimeout,r,arguments),clearTimeout)},t.setInterval=function(){return new s(n.call(setInterval,r,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},s.prototype.unref=s.prototype.ref=function(){},s.prototype.close=function(){this._clearFn.call(r,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},i(15),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,i(7))},function(e,t,i){(function(e,t){!function(e,i){if(!e.setImmediate){var r,n,s,o,a,c=1,u={},d=!1,l=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,"[object process]"==={}.toString.call(e.process)?r=function(e){t.nextTick((function(){p(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(o="setImmediate$"+Math.random()+"$",a=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(o)&&p(+t.data.slice(o.length))},e.addEventListener?e.addEventListener("message",a,!1):e.attachEvent("onmessage",a),r=function(t){e.postMessage(o+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){p(e.data)},r=function(e){s.port2.postMessage(e)}):l&&"onreadystatechange"in l.createElement("script")?(n=l.documentElement,r=function(e){var t=l.createElement("script");t.onreadystatechange=function(){p(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):r=function(e){setTimeout(p,0,e)},h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),i=0;i<t.length;i++)t[i]=arguments[i+1];var n={callback:e,args:t};return u[c]=n,r(c),c++},h.clearImmediate=m}function m(e){delete u[e]}function p(e){if(d)setTimeout(p,0,e);else{var t=u[e];if(t){d=!0;try{!function(e){var t=e.callback,i=e.args;switch(i.length){case 0:t();break;case 1:t(i[0]);break;case 2:t(i[0],i[1]);break;case 3:t(i[0],i[1],i[2]);break;default:t.apply(void 0,i)}}(t)}finally{m(e),d=!1}}}}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,i(7),i(9))},function(e,t){class i extends AudioWorkletProcessor{constructor(){super(),this.audioLevel=0}static get parameterDescriptors(){return[{name:"averaging",defaultValue:.95},{name:"output",defaultValue:1}]}process(e,t,i){let r,n;r=i.averaging.length?i.averaging[0]:i.averaging,n=i.output.length?i.output[0]:i.output;const s=e[0],o=t[0],a=s[0];if(!a)return!0;const c=a.length;let u,d=0;for(let e=0;e<c;e++)u=a[e],d+=u*u;const l=Math.sqrt(d/c);if(this.audioLevel=Math.max(l,this.audioLevel*r),n)for(let e=0;e<s.length;e++){const t=s[e],i=o[e];for(let e=0;e<t.length;e++)i[e]=t[e]}return this.port.postMessage(this.audioLevel),!0}}registerProcessor("meter-processor",i)},function(e,t){var i=["stun:","turn:"];e.exports=function(e){var t,r,n=(e||{}).url||e,s={};return"string"==typeof n||n instanceof String?(n=n.trim(),(t=i[i.indexOf(n.slice(0,5))])?(r=(n=n.slice(5)).split("@"),s.username=e.username,s.credential=e.credential,r.length>1&&(n=r[1],r=r[0].split(":"),s.username=r[0],s.credential=(e||{}).credential||r[1]||""),s.url=t+n,s.urls=[s.url],s):e):e}},function(e){e.exports=JSON.parse('["stun.l.google.com:19302","stun1.l.google.com:19302","stun2.l.google.com:19302","stun3.l.google.com:19302","stun4.l.google.com:19302","stun.ekiga.net","stun.ideasip.com","stun.schlund.de","stun.stunprotocol.org:3478","stun.voiparound.com","stun.voipbuster.com","stun.voipstunt.com","stun.voxgratia.org"]')},function(e){e.exports=JSON.parse("[]")},function(e,t,i){var r=i(21),n=i(25);function s(){this.cache={mlB2UMap:{},mlU2BMap:{}}}e.exports=s,s.prototype.candidateToUnifiedPlan=function(e){var t=new RTCIceCandidate(e);return t.sdpMLineIndex=this.cache.mlB2UMap[t.sdpMLineIndex],t},s.prototype.candidateToPlanB=function(e){var t=new RTCIceCandidate(e);if(0===t.sdpMid.indexOf("audio"))t.sdpMid="audio";else{if(0!==t.sdpMid.indexOf("video"))throw new Error("candidate with "+t.sdpMid+" not allowed");t.sdpMid="video"}return t.sdpMLineIndex=this.cache.mlU2BMap[t.sdpMLineIndex],t},s.prototype.getFirstSendingIndexFromAnswer=function(e){if(!this.cache.answer)return null;var t=r.parse(this.cache.answer);if(t&&t.media&&Array.isArray(t.media))for(var i=0;i<t.media.length;i++)if(t.media[i].type==e&&(!t.media[i].direction||"sendrecv"===t.media[i].direction||"sendonly"===t.media[i].direction))return i;return null},s.prototype.toPlanB=function(e){var t=this;if("object"!=typeof e||null===e||"string"!=typeof e.sdp)return console.warn("An empty description was passed as an argument."),e;var i=r.parse(e.sdp);if(void 0===i.media||!Array.isArray(i.media)||0===i.media.length)return console.warn("The description has no media."),e;if(i.media.length<=3&&i.media.every((function(e){return-1!==["video","audio","data"].indexOf(e.mid)})))return console.warn("This description does not look like Unified Plan."),e;for(var n=e.sdp,s=!1,o=0;o<i.media.length;o++)i.media[o].rtp.forEach((function(e){if("NULL"===e.codec){s=!0;var i=r.parse(t.cache.offer);e.codec=i.media[o].rtp[0].codec}}));s&&(n=r.write(i)),this.cache[e.type]=n;var a=i.media;i.media=[];var c={},u=[];a.forEach((function(e){if(("string"!=typeof e.rtcpMux||"rtcp-mux"!==e.rtcpMux)&&"inactive"!==e.direction)throw new Error("Cannot convert to Plan B because m-lines without the rtcp-mux attribute were found.");if(void 0!==c[e.type]&&"inactive"!==c[e.type].direction||(c[e.type]=e),e.protocol!=c[e.type].protocol)throw new Error("Cannot convert to Plan B because m-lines have different protocols and this library does not have support for that");if(e.payloads!=c[e.type].payloads)throw new Error("Cannot convert to Plan B because m-lines have different payloads and this library does not have support for that")})),a.forEach((function(e){if("application"===e.type)return i.media.push(e),void u.push(e.mid);"object"==typeof e.sources&&Object.keys(e.sources).forEach((function(t){"object"!=typeof c[e.type].sources&&(c[e.type].sources={}),c[e.type].sources[t]=e.sources[t],void 0!==e.msid&&(c[e.type].sources[t].msid=e.msid)})),void 0!==e.ssrcGroups&&Array.isArray(e.ssrcGroups)&&(void 0!==c[e.type].ssrcGroups&&Array.isArray(c[e.type].ssrcGroups)||(c[e.type].ssrcGroups=[]),c[e.type].ssrcGroups=c[e.type].ssrcGroups.concat(e.ssrcGroups)),c[e.type]===e&&(e.mid=e.type,delete e.bundleOnly,delete e.msid,e.type==a[0].type?(u.unshift(e.type),i.media.unshift(e)):(u.push(e.type),i.media.push(e)))})),void 0!==i.groups&&i.groups.some((function(e){if("BUNDLE"===e.type)return e.mids=u.join(" "),!0})),i.msidSemantic={semantic:"WMS",token:"*"};var d=r.write(i);return new RTCSessionDescription({type:e.type,sdp:d})},s.prototype.toUnifiedPlan=function(e){var t=this;if("object"!=typeof e||null===e||"string"!=typeof e.sdp)return console.warn("An empty description was passed as an argument."),e;var i=r.parse(e.sdp);if(void 0===i.media||!Array.isArray(i.media)||0===i.media.length)return console.warn("The description has no media."),e;if(i.media.length>3||!i.media.every((function(e){return-1!==["video","audio","data"].indexOf(e.mid)})))return console.warn("This description does not look like Plan B."),e;var s=[];i.media.forEach((function(e){s.push(e.mid)}));var o,a,c=!1;if(void 0!==i.groups&&Array.isArray(i.groups)&&(c=i.groups.every((function(e){return"BUNDLE"!==e.type||n.apply(e.mids.sort(),[s.sort()])}))),!c){var u=!1;if(i.media.forEach((function(e){"inactive"!==e.direction&&(u=!0)})),u)throw new Error("Cannot convert to Unified Plan because m-lines that are not bundled were found.")}if("answer"===e.type)o="offer";else{if("offer"!==e.type)throw new Error("Type '"+e.type+"' not supported.");o="answer"}void 0!==this.cache[o]&&(a=r.parse(this.cache[o]));var d,l,h,m,p={audio:{},video:{}},f={},v=0,g=0,_={},y={},S={},E={};if(i.media.forEach((function(i){if(("string"!=typeof i.rtcpMux||"rtcp-mux"!==i.rtcpMux)&&"inactive"!==i.direction)throw new Error("Cannot convert to Unified Plan because m-lines without the rtcp-mux attribute were found.");if("application"!==i.type){var r=i.sources,n=i.ssrcGroups,s=i.port;if(void 0!==i.candidates&&(d=void 0!==d?d.concat(i.candidates):i.candidates),void 0!==l&&void 0!==i.iceUfrag&&l!=i.iceUfrag)throw new Error("Only BUNDLE supported, iceUfrag must be the same for all m-lines.\n\tLast iceUfrag: "+l+"\n\tNew iceUfrag: "+i.iceUfrag);if(void 0!==i.iceUfrag&&(l=i.iceUfrag),void 0!==h&&void 0!==i.icePwd&&h!=i.icePwd)throw new Error("Only BUNDLE supported, icePwd must be the same for all m-lines.\n\tLast icePwd: "+h+"\n\tNew icePwd: "+i.icePwd);if(void 0!==i.icePwd&&(h=i.icePwd),void 0!==m&&void 0!==i.fingerprint&&(m.type!=i.fingerprint.type||m.hash!=i.fingerprint.hash))throw new Error("Only BUNDLE supported, fingerprint must be the same for all m-lines.\n\tLast fingerprint: "+JSON.stringify(m)+"\n\tNew fingerprint: "+JSON.stringify(i.fingerprint));void 0!==i.fingerprint&&(m=i.fingerprint),y[i.type]=i.payloads,S[i.type]=i.rtcpFb,E[i.type]=i.rtp;var o={};void 0!==n&&Array.isArray(n)&&n.forEach((function(e){void 0!==e.ssrcs&&Array.isArray(e.ssrcs)&&e.ssrcs.forEach((function(t){void 0===o[t]&&(o[t]=[]),o[t].push(e)}))}));var c={};if("object"==typeof r)delete i.sources,delete i.ssrcGroups,delete i.candidates,delete i.iceUfrag,delete i.icePwd,delete i.fingerprint,delete i.port,delete i.mid,Object.keys(r).forEach((function(n){var u;"offer"!==e.type||r[n].msid?(void 0!==o[n]&&Array.isArray(o[n])&&o[n].some((function(e){return e.ssrcs.some((function(e){if("object"==typeof c[e])return u=c[e],!0}))})),"object"==typeof u?(u.sources[n]=r[n],delete r[n].msid):(u=Object.create(i),c[n]=u,void 0!==r[n].msid&&(u.msid=r[n].msid,delete r[n].msid),u.sources={},u.sources[n]=r[n],u.ssrcGroups=o[n],void 0!==a&&void 0!==a.media&&Array.isArray(a.media)&&a.media.forEach((function(e){"object"==typeof e.sources&&Object.keys(e.sources).forEach((function(t){t===n&&(u.mid=e.mid)}))})),void 0===u.mid&&(u.mid=[i.type,"-",n].join("")),u.candidates=d,u.iceUfrag=l,u.icePwd=h,u.fingerprint=m,u.port=s,f[u.mid]=u,_[g]=u.sources,t.cache.mlU2BMap[g]=v,void 0===t.cache.mlB2UMap[v]&&(t.cache.mlB2UMap[v]=g),g++)):p[i.type][n]=r[n]}));else{var u=i;u.candidates=d,u.iceUfrag=l,u.icePwd=h,u.fingerprint=m,u.port=s,f[u.mid]=u,t.cache.mlU2BMap[g]=v,void 0===t.cache.mlB2UMap[v]&&(t.cache.mlB2UMap[v]=g)}v++}else f[i.mid]=i})),i.media=[],s=[],"answer"===e.type)for(var b=0;b<a.media.length;b++){var T=a.media[b];delete T.msid,delete T.sources,delete T.ssrcGroups,void 0===_[b]?T.direction&&"sendrecv"!==T.direction?"sendonly"===T.direction&&(T.direction="inactive"):T.direction="recvonly":T.direction&&"sendrecv"!==T.direction?"recvonly"===T.direction&&(T.direction="sendonly"):T.direction="sendrecv",T.sources=_[b],T.candidates=d,T.iceUfrag=l,T.icePwd=h,T.fingerprint=m,T.rtp=E[T.type],T.payloads=y[T.type],T.rtcpFb=S[T.type],i.media.push(T),"string"==typeof T.mid&&s.push(T.mid)}else void 0!==a&&void 0!==a.media&&Array.isArray(a.media)&&a.media.forEach((function(e){s.push(e.mid),void 0!==f[e.mid]?i.media.push(f[e.mid]):(delete e.msid,delete e.sources,delete e.ssrcGroups,e.direction&&"sendrecv"!==e.direction||(e.direction="sendonly"),e.direction&&"recvonly"!==e.direction||(e.direction="inactive"),function(e){void 0!==e.setup&&("active"===e.setup?e.setup="passive":"passive"===e.setup&&(e.setup="active"))}(e),i.media.push(e))})),Object.keys(f).forEach((function(e){if(-1===s.indexOf(e))if(s.push(e),"recvonly"===f[e].direction){var t=!1;i.media.some((function(i){if(("sendrecv"===i.direction||"sendonly"===i.direction)&&i.type===f[e].type)return Object.keys(f[e].sources).forEach((function(t){i.sources[t]=f[e].sources[t]})),t=!0,!0})),t||i.media.push(f[e])}else i.media.push(f[e])}));["audio","video"].forEach((function(e){if(i&&i.media&&Array.isArray(i.media)){var r=null;if(Object.keys(p[e]).length>0&&null===(r=t.getFirstSendingIndexFromAnswer(e)))for(var n=0;n<i.media.length;n++)if(i.media[n].type===e){r=n;break}if(r&&i.media.length>r){var s=i.media[r];Object.keys(p[e]).forEach((function(t){s.sources&&s.sources[t]&&console.warn("Replacing an existing SSRC."),s.sources||(s.sources={}),s.sources[t]=p[e][t]}))}}})),void 0!==i.groups&&i.groups.some((function(e){if("BUNDLE"===e.type)return e.mids=s.join(" "),!0})),i.msidSemantic={semantic:"WMS",token:"*"};var I=r.write(i);return this.cache[e.type]=I,new RTCSessionDescription({type:e.type,sdp:I})}},function(e,t,i){var r=i(22);t.write=function(e,t){return void 0!==e&&void 0!==e.media&&Array.isArray(e.media)&&e.media.forEach((function(e){void 0!==e.sources&&0!==Object.keys(e.sources).length&&(e.ssrcs=[],Object.keys(e.sources).forEach((function(t){var i=e.sources[t];Object.keys(i).forEach((function(r){e.ssrcs.push({id:t,attribute:r,value:i[r]})}))})),delete e.sources),void 0!==e.ssrcGroups&&Array.isArray(e.ssrcGroups)&&e.ssrcGroups.forEach((function(e){void 0!==e.ssrcs&&Array.isArray(e.ssrcs)&&(e.ssrcs=e.ssrcs.join(" "))}))})),void 0!==e&&void 0!==e.groups&&Array.isArray(e.groups)&&e.groups.forEach((function(e){void 0!==e.mids&&Array.isArray(e.mids)&&(e.mids=e.mids.join(" "))})),r.write(e,t)},t.parse=function(e){var t=r.parse(e);return void 0!==t&&void 0!==t.media&&Array.isArray(t.media)&&t.media.forEach((function(e){void 0!==e.ssrcs&&Array.isArray(e.ssrcs)&&(e.sources={},e.ssrcs.forEach((function(t){e.sources[t.id]||(e.sources[t.id]={}),e.sources[t.id][t.attribute]=t.value})),delete e.ssrcs),void 0!==e.ssrcGroups&&Array.isArray(e.ssrcGroups)&&e.ssrcGroups.forEach((function(e){"string"==typeof e.ssrcs&&(e.ssrcs=e.ssrcs.split(" "))}))})),void 0!==t&&void 0!==t.groups&&Array.isArray(t.groups)&&t.groups.forEach((function(e){"string"==typeof e.mids&&(e.mids=e.mids.split(" "))})),t}},function(e,t,i){var r=i(23),n=i(24);t.write=n,t.parse=r.parse,t.parseFmtpConfig=r.parseFmtpConfig,t.parsePayloads=r.parsePayloads,t.parseRemoteCandidates=r.parseRemoteCandidates},function(e,t,i){var r=function(e){return String(Number(e))===e?Number(e):e},n=function(e,t,i){var n=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:n&&!t[e.name]&&(t[e.name]={});var s=e.push?{}:n?t[e.name]:t;!function(e,t,i,n){if(n&&!i)t[n]=r(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(t[i[s]]=r(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&t[e.push].push(s)},s=i(10),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(e){var t={},i=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(o).forEach((function(e){var t=e[0],o=e.slice(2);"m"===t&&(i.push({rtp:[],fmtp:[]}),r=i[i.length-1]);for(var a=0;a<(s[t]||[]).length;a+=1){var c=s[t][a];if(c.reg.test(o))return n(c,r,o)}})),t.media=i,t};var a=function(e,t){var i=t.split("=");return 2===i.length&&(e[i[0]]=r(i[1])),e};t.parseFmtpConfig=function(e){return e.split(/\;\s?/).reduce(a,{})},t.parsePayloads=function(e){return e.split(" ").map(Number)},t.parseRemoteCandidates=function(e){for(var t=[],i=e.split(" ").map(r),n=0;n<i.length;n+=3)t.push({component:i[n],ip:i[n+1],port:i[n+2]});return t}},function(e,t,i){var r=i(10),n=/%[sdv%]/g,s=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?r.push(i[t.name][o]):r.push(i[t.names[n]])}else r.push(i[t.name]);return s.apply(null,r)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c=["i","c","b","a"];e.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||a,n=t.innerOrder||c,s=[];return i.forEach((function(t){r[t].forEach((function(i){i.name in e&&null!=e[i.name]?s.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){s.push(o(t,i,e))}))}))})),e.media.forEach((function(e){s.push(o("m",r.m[0],e)),n.forEach((function(t){r[t].forEach((function(i){i.name in e&&null!=e[i.name]?s.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){s.push(o(t,i,e))}))}))}))})),s.join("\r\n")+"\r\n"}},function(e,t){e.exports=function e(t){if(!t)return!1;if(this.length!=t.length)return!1;for(var i=0,r=this.length;i<r;i++)if(this[i]instanceof Array&&t[i]instanceof Array){if(!e.apply(this[i],[t[i]]))return!1}else if(this[i]!=t[i])return!1;return!0}},function(e,t,i){(function(r){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),t.splice(n,0,i)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=i(27)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this,i(9))},function(e,t,i){e.exports=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,i){const r=t(this.namespace+(void 0===i?":":i)+e);return r.log=this.log,r}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let i;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),n=r.length;for(i=0;i<n;i++)r[i]&&("-"===(e=r[i].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let i,r;for(i=0,r=t.skips.length;i<r;i++)if(t.skips[i].test(e))return!1;for(i=0,r=t.names.length;i<r;i++)if(t.names[i].test(e))return!0;return!1},t.humanize=i(28),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((i=>{t[i]=e[i]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e.charCodeAt(t),i|=0;return t.colors[Math.abs(i)%t.colors.length]},t.enable(t.load()),t}},function(e,t){var i=1e3,r=6e4,n=60*r,s=24*n;function o(e,t,i,r){var n=t>=1.5*i;return Math.round(e/i)+" "+r+(n?"s":"")}e.exports=function(e,t){t=t||{};var a=typeof e;if("string"===a&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*s;case"hours":case"hour":case"hrs":case"hr":case"h":return o*n;case"minutes":case"minute":case"mins":case"min":case"m":return o*r;case"seconds":case"second":case"secs":case"sec":case"s":return o*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===a&&isFinite(e))return t.long?function(e){var t=Math.abs(e);return t>=s?o(e,t,s,"day"):t>=n?o(e,t,n,"hour"):t>=r?o(e,t,r,"minute"):t>=i?o(e,t,i,"second"):e+" ms"}(e):function(e){var t=Math.abs(e);return t>=s?Math.round(e/s)+"d":t>=n?Math.round(e/n)+"h":t>=r?Math.round(e/r)+"m":t>=i?Math.round(e/i)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},function(e,t,i){i.r(t);var r=i(1);class n{constructor(e){this.worker=e,this.handleEvents()}handleEvents(){this.worker.addEventListener("message",(e=>{var t;let i=e.data.data;setTimeout((()=>{this.worker.postMessage({type:"pong",id:i.id})}),Math.max(null!==(t=i.timeout)&&void 0!==t?t:0,4))}))}}t.default=function(e){try{new n(e)}catch(e){r.error("new WorkerSetTimeout failed")}}},function(e,t,i){i.r(t),i.d(t,"Logger",(function(){return Ls})),i.d(t,"Events",(function(){return Ps})),i.d(t,"createStream",(function(){return Ns})),i.d(t,"createClient",(function(){return Ds})),i.d(t,"setEnv",(function(){return xs})),i.d(t,"setVTRequestTimeout",(function(){return Us})),i.d(t,"useRoomChannelType",(function(){return $s})),i.d(t,"forcePlanBSimulcast",(function(){return Bs})),i.d(t,"setCustomUrl",(function(){return Vs})),i.d(t,"addProxies",(function(){return Fs})),i.d(t,"setCanary",(function(){return js})),i.d(t,"removeProxies",(function(){return Hs})),i.d(t,"checkSystemSupport",(function(){return Ws})),i.d(t,"supportScreenSharing",(function(){return Gs})),i.d(t,"isSmallStreamSupported",(function(){return qs})),i.d(t,"getPermissions",(function(){return Js})),i.d(t,"base64Decode",(function(){return zs})),i.d(t,"enumAudioInputDevices",(function(){return Ys})),i.d(t,"enumAudioOutputDevices",(function(){return Qs})),i.d(t,"enumVideoDevices",(function(){return Ks})),i.d(t,"version",(function(){return Xs})),i.d(t,"RenderProcess",(function(){return Zs}));var r={};i.r(r),i.d(r,"STREAM_ADDED",(function(){return w})),i.d(r,"STREAM_REMOVED",(function(){return R})),i.d(r,"STREAM_UPDATED",(function(){return k})),i.d(r,"STREAM_PUBLISHED",(function(){return A})),i.d(r,"STREAM_SUBSCRIBED",(function(){return M})),i.d(r,"MUTE_VIDEO",(function(){return O})),i.d(r,"UNMUTE_VIDEO",(function(){return L})),i.d(r,"MUTE_AUDIO",(function(){return P})),i.d(r,"UNMUTE_AUDIO",(function(){return N})),i.d(r,"ERROR",(function(){return D})),i.d(r,"PEER_JOINED",(function(){return x})),i.d(r,"PEER_LEAVED",(function(){return U})),i.d(r,"CLIENT_BANNED",(function(){return $})),i.d(r,"USER_KICKED",(function(){return B})),i.d(r,"TOKEN_WILL_EXPIRE",(function(){return V})),i.d(r,"TOKEN_EXPIRE",(function(){return F})),i.d(r,"ROOM_CLOSED",(function(){return j})),i.d(r,"SYNC_ROOM_COMPLETED",(function(){return H}));var n={};i.r(n),i.d(n,"VIDEO_TRACK_ENDED",(function(){return K})),i.d(n,"AUDIO_TRACK_ENDED",(function(){return X})),i.d(n,"VIDEO_TRACK_MUTE",(function(){return Z})),i.d(n,"AUDIO_TRACK_MUTE",(function(){return ee})),i.d(n,"VIDEO_TRACK_UNMUTE",(function(){return te})),i.d(n,"AUDIO_TRACK_UNMUTE",(function(){return ie})),i.d(n,"TRACK_UPDATE",(function(){return re})),i.d(n,"PLAYER_STATE_CHANGED",(function(){return ne})),i.d(n,"CONNECT_ERROR",(function(){return se})),i.d(n,"CONNECT_SUCCESS",(function(){return oe})),i.d(n,"CONNECT_RECONNECTING",(function(){return ae})),i.d(n,"PLAYER_VIDEO_RENDERED",(function(){return ce})),i.d(n,"PLAYER_AUDIO_RENDERED",(function(){return ue})),i.d(n,"AUDIO_LEVEL",(function(){return de})),i.d(n,"CLOSE",(function(){return le}));var s={};i.r(s),i.d(s,"add",(function(){return di})),i.d(s,"has",(function(){return li})),i.d(s,"clear",(function(){return hi})),i.d(s,"all",(function(){return mi})),i.d(s,"remove",(function(){return pi}));var o=i(0);function a(e){return 0===e}function c(e){return 1===e}function u(e){return"video"===e.kind}function d(e){return"audio"===e.kind}let l="production";const h="2.18.1-boom";let m,p=15,f=null;function v(){return p}let g=0,_=!1,y=[];function S(){return m}function E(){return g}const b={4096:1001,4097:1002,16385:4001,16386:4002,16387:4003,16388:4e3,16389:4004,16448:4005,16449:4006,16450:4007,65535:9e3},T="contact with BaiJiaYun for more information",I={1e3:{name:"local error",message:T},1001:{name:"param invalid",message:"参数类型错误"},1002:{name:"invalid operation",message:"非法操作"},1003:{name:"not support",message:"不支持"},4e3:{name:"join channel error",message:"进入频道失败"},4001:{name:"signal setup failed",message:"信令通道建立失败"},4002:{name:"signal error",message:"信令通道错误"},4003:{name:"ice transport error",message:"ICE Tansport 连接错误"},4004:{name:"create offer failed",message:"创建 sdp offer 失败"},4005:{name:"client banned",message:"用户被踢出"},4006:{name:"media server timeout",message:"媒体传输超时"},4007:{name:"subscription timeout",message:"订阅远端流超时"},4008:{name:"media publish error",message:"推流错误"},5e3:{name:"fetch fail",message:"网络请求失败,请检查网络状态"},5001:{name:"userSig error",message:"userSig 验证失败"},9e3:{name:"unknow",message:T},1010:{name:"permission deny",message:"权限验证失败"}};class C extends Error{constructor(e,t,i,r){if(super(),this.RTCType=S(),this.code=e,this.error=i,this.BRTCErrorFlag=!0,c(this.RTCType)&&i&&i.getCode){let e=b[i.getCode()];e&&(this.code=e)}this.eName=r||(I[this.code]?I[this.code].name:"BRTCError"),this.message=`[webrtc_type: ${this.RTCType}] [code: ${this.code}] [error_name: ${this.eName}] ${t||(I[this.code]?I[this.code].message:"unkown")}`}static instanceOf(e){return!(!e||!e.BRTCErrorFlag)}getCode(){return this.code}}const w="stream-added",R="stream-removed",k="stream-updated",A="stream-published",M="stream-subscribed",O="mute-video",L="unmute-video",P="mute-audio",N="unmute-audio",D="error",x="peer-joined",U="peer-leaved",$="client-banned",B="user-kicked",V="token-will-expire",F="token-expire",j="room-closed",H="sync-room-completed";function W(e,t){return!t&&o.i(e)&&!/^0[0-9]+/.test(e)&&/^[0-9]{1,15}$/g.test(e)?+e:e}var G=i(2);function q(e,t,i){if(o.d(e))return o.a(i)?e.apply(t,i):t!==G.m?e.call(t,i):i!==G.m?e(i):e()}var J=i(5);function z(){return Date.now()}function Y(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))}function Q(e=0){return z()+e}const K="video-track-ended",X="audio-track-ended",Z="video-track-mute",ee="audio-track-mute",te="video-track-unmute",ie="audio-track-unmute",re="track-update",ne="player-state-changed",se="connect-error",oe="connect-success",ae="connect-reconnecting",ce="player-video-rendered",ue="player-audio-rendered",de="audio-level",le="close";var he=i(1),me=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class pe{constructor(e,t,i){var r;this.element=e,this.options=t,this.logger=i,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor=null!==(r=t.backgroundColor)&&void 0!==r?r:"black",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!1===this.options.video)return;const e=this.stream.getVideoTrack();if(!e)return;if(!this.video){this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.video.style.objectFit=this.options.fit,this.video.id="video_"+this.stream.getStreamId(),this.container.appendChild(this.video),this.video.addEventListener("playing",(()=>{this.videoStatus="PLAYING",this.stream&&(this.stream.fire(ne,{type:"video",state:this.videoStatus,reason:"playing"}),this.log(`stream video playing, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})),this.video.addEventListener("pause",(()=>{this.videoStatus="PAUSED",this.stream&&(this.stream.fire(ne,{type:"video",state:this.videoStatus,reason:"pause"}),this.log(`stream video pause, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})),this.video.addEventListener("stalled",(()=>{this.videoStatus="PAUSED",this.stream&&(this.stream.fire(ne,{type:"video",state:this.videoStatus,reason:"stalled"}),this.log(`stream video stalled, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})),this.video.addEventListener("loadeddata",(()=>{this.stream&&(this.stream.fire(ce),this.log(`stream video loadeddata, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))}))}let t=new MediaStream;t.addTrack(e),this.video.srcObject=null,this.video.srcObject=t,this.videoStatus="STOPPED"}playAudio(){if(!1===this.options.audio)return;const e=this.stream.getAudioTrack();if(!e)return;this.audio||(this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id="audio_"+this.stream.getStreamId(),this.container.appendChild(this.audio),this.stream.getAudioDeviceId()&&this.setSinkId(this.stream.getAudioDeviceId()),this.audio.volume=o.f(this.stream.getAudioVolume())?this.stream.getAudioVolume():1,this.audio.addEventListener("playing",(()=>{this.audioStatus="PLAYING",this.stream&&(this.stream.fire(ne,{type:"audio",state:this.audioStatus,reason:"playing"}),this.log(`stream audio playing, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})),this.audio.addEventListener("pause",(()=>{this.audioStatus="PAUSED",this.stream&&(this.stream.fire(ne,{type:"audio",state:this.audioStatus,reason:"pause"}),this.log(`stream audio pause, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})),this.audio.addEventListener("stalled",(()=>{this.audioStatus="PAUSED",this.stream&&(this.stream.fire(ne,{type:"audio",state:this.audioStatus,reason:"stalled"}),this.log(`stream audio stalled, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})),this.audio.addEventListener("loadeddata",(()=>{this.stream&&(this.stream.fire(ue),this.log(`stream audio loadeddata, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"))})));let t=new MediaStream;t.addTrack(e),this.audio.srcObject=null,this.audio.srcObject=t,this.audioStatus="STOPPED"}setSinkId(e){return me(this,void 0,void 0,(function*(){this.audio&&o.d(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audio.volume=e)}play(e){return me(this,void 0,void 0,(function*(){this.stream=e,this.container.id="player_"+e.getStreamId(),this.stream.hasAudio()&&this.playAudio(),this.stream.hasVideo()&&this.playVideo();try{this.audio&&(yield this.audio.play()),this.video&&(yield this.video.play())}catch(e){this.log(`stream play error, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}, name: ${(null==e?void 0:e.name)||"unknow"}, message: ${(null==e?void 0:e.message)||"unknow"}`,"AbortError"===e.name?he.DEBUG:he.ERROR,"player"),this.stream.fire(ne,{type:"error",reason:e})}}))}replay(e,t=!0,i=!0){return me(this,void 0,void 0,(function*(){this.log(`stream replay, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player"),this.stream=e;try{this.stream.hasAudio()&&i&&this.playAudio(),this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasAudio()&&i&&(yield this.audio.play()),this.stream.hasVideo()&&t&&(yield this.video.play())}catch(e){this.log(`stream replay error, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}, name: ${(null==e?void 0:e.name)||"unknow"}, message: ${(null==e?void 0:e.message)||"unknow"}`,"AbortError"===e.name?he.DEBUG:he.ERROR,"player"),this.stream.fire(ne,{type:"error",reason:e})}}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){this.element.removeChild(this.container),this.audio&&(this.audio.srcObject=null),this.video&&(this.video.srcObject=null),this.audio=null,this.video=null,this.container=null,this.log(`stream player destroy, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player")}resume(){return me(this,void 0,void 0,(function*(){this.video&&this.video.play(),this.audio&&(yield function(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){}))}(),this.audio.play()),this.log(`stream player resume, userId: ${this.stream.getUserId()}, streamId: ${this.stream.getStreamId()}`,he.INFO,"player")}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){const e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}log(e,t,i){this.logger?this.logger.log(e,t,i):he.log(t,e,i)}}class fe{constructor(e=10){this.queue=[],this.win=e}addData(e,t){for(;this.queue.length>=this.win;)this.queue.shift();this.queue.push([Number(e),Number(t)])}reset(){this.queue.length=0}getPacketLossRate(){let e,t=this.queue.length;if(0==t)e=0;else if(t<this.win){let i=this.queue[t-1][0];e=this.queue[t-1][1]/i}else if(t===this.win){let i=Math.abs(this.queue[t-1][0]-this.queue[0][0]);e=Math.abs(this.queue[t-1][1]-this.queue[0][1])/i}else e=0;return e>=1&&(e=1),Number.isNaN(e)&&(e=0),Math.max(Math.round(100*e),0)}}class ve{constructor(e=1){this.sample=e,this.audioPackLost=new fe(2),this.videoPackLost=new fe(2),this.audioBytesBefore=this.audioBytesNow=0,this.videoBytesBefore=this.videoBytesNow=0,this.frameBefore=this.frameNow=0}addData(e,t,i,r,n,s,o){this.audioPackLost.addData(i,r),this.videoPackLost.addData(n,s),this.audioBytesBefore=this.audioBytesNow,this.audioBytesNow=e,this.videoBytesBefore=this.videoBytesNow,this.videoBytesNow=t,this.frameBefore=this.frameNow,this.frameNow=o}getAudioPacketLoss(){return this.audioPackLost.getPacketLossRate()}getVideoPacketLoss(){return this.videoPackLost.getPacketLossRate()}getAudioBitrate(){return this.audioBytesBefore?Math.max(Math.round(8*(this.audioBytesNow-this.audioBytesBefore)/1e3/this.sample),0):0}getVideoBitrate(){return this.videoBytesBefore?Math.max(Math.round(8*(this.videoBytesNow-this.videoBytesBefore)/1e3/this.sample),0):0}getFrameRate(){return this.frameBefore?Math.max(Math.round((this.frameNow-this.frameBefore)/this.sample),0):0}destroy(){this.sample=null,this.audioPackLost=null,this.videoPackLost=null,this.audioBytesBefore=this.audioBytesNow=null,this.videoBytesBefore=this.videoBytesNow=null,this.frameBefore=this.frameNow=null}}function ge(e,t,i){if(!e)return;const{length:r}=e;if(r)if(i)for(let i=r-1;i>=0&&t(e[i],i)!==G.d;i--);else for(let i=0;i<r&&t(e[i],i)!==G.d;i++);}function _e(e,t){e[e.length]=t}function ye(e,t){!function(e,t,i){o.a(t)?ge(t,(function(t){i(e,t)})):i(e,t)}(e,t,_e)}function Se(e,t,i){let r=0;return ge(e,(function(n,s){(i===G.d?n==t:n===t)&&(e.splice(s,1),r++)}),G.l),r}function Ee(e,t,i){return function(e,t,i){let r=G.f;return ge(e,(function(e,n){if(i===G.d?e==t:e===t)return r=n,G.d})),r}(e,t,i)>=0}function be(e){return o.a(e)?e:q(G.a.slice,e)}class Te{constructor(e,t){this.type=e,this.phase=Te.PHASE_CURRENT,t&&(this.originalEvent=t)}preventDefault(){const e=this;if(!e.isPrevented){const{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=G.l}return e}stopPropagation(){const e=this;if(!e.isStoped){const{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=G.l}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}}Te.PHASE_CURRENT=0,Te.PHASE_UPWARD=1,Te.PHASE_DOWNWARD=G.f;var Ie=i(4);const Ce={};function we(e){return e!==G.m}function Re(e){return we(e)?Object.keys(e):[]}function ke(e,t){for(let i in e)if(t(e[i],i)===G.d)break}function Ae(e,t){return o.h(e)?o.h(t)?(ke(t,(function(t,i){e[i]=t})),e):e:t}function Me(e,t,i){return Ae(Ae(e,t),i)}function Oe(e,t){let i=e;return o.a(e)?t?(i=[],ge(e,(function(e,r){i[r]=Oe(e,t)}))):i=e.slice():o.h(e)&&(i={},ke(e,(function(e,r){i[r]=t?Oe(e,t):e}))),i}function Le(e,t,i){let r;return function(e,t){const i=Ce.hasOwnProperty(e)?Ce[e]:Ce[e]=e.split(G.h);for(let e=0,r=i.length-1;e<=r&&t(i[e],e===r)!==G.d;e++);}(t,(function(t,i){if(e==G.g)return r=G.m,G.d;{let n=e[t],s=n!==G.m;i?r=s?n:G.m:e=n}})),r===G.m&&(r=i),r}function Pe(e){let t=[];const i=(e,i)=>{i=o.d(i)?i():null==i?"":i,t[t.length]=encodeURIComponent(e)+"="+encodeURIComponent(i)};return(o.a(e)||o.e(e))&&(o.a(e)?ge(e,((e,t)=>{i(t,e)})):ke(e,((e,t)=>{i(t,e)}))),t.join("&").replace(/%20/g,"+")}class Ne{constructor(e){this.ns=e||G.d,this.listeners={}}fire(e,t,i){let r=this,n=o.i(e)?r.parse(e):e,s=r.listeners[n.type],a=G.l;if(s){s=Oe(s);const e=t&&t[0]instanceof Te?t[0]:G.m;ge(s,(function(o){if(!Ue(n.ns,o,G.l)||!Ee(s,o)||i&&!i(n,t,o))return;e&&(e.listener=o.fn);let c=q(o.fn,o.ctx,t);return e&&(e.listener=G.m),o.num=o.num?o.num+1:1,o.num===o.max&&r.off(n,o.fn),e&&(c===G.d?e.prevent().stop():e.isStoped&&(c=G.d)),c===G.d?a=G.d:void 0}))}return a}on(e,t){const i=this,r=i.listeners,n=o.d(t)?{fn:t}:t;if(o.h(n)&&o.d(n.fn)){const t=o.i(e)?i.parse(e):e;n.ns=t.ns,ye(r[t.type]||(r[t.type]=[]),n)}return this}one(e,t){return o.d(t)?t={fn:t,max:1}:t.max=1,this.on(e,t)}off(e,t){const i=this,r=i.listeners;if(e){const n=o.i(e)?i.parse(e):e,s=n.type,a=n.ns,c=xe(t),u=function(e,t){ge(e,(function(t,i){c(t)&&e.splice(i,1)}),G.l),e.length||delete r[t]},d=function(e,t){ge(e,(function(t,i){Ue(a,t)&&e.splice(i,1)}),G.l),e.length||delete r[t]};s?r[s]&&u(r[s],s):a&&ke(r,d)}else i.listeners={}}has(e,t){let i=this.listeners,r=o.i(e)?this.parse(e):e,n=r.type,s=r.ns,a=G.l,c=xe(t);return n?i[n]&&ge(i[n],(function(e){if(c(e))return a=G.d})):s&&ke(i,(function(e){return ge(e,(function(e){if(Ue(s,e))return a=G.d})),a})),!a}parse(e){const t={type:e,ns:G.c};if(this.ns){const i=Ie.b(e,G.h);i>=0&&(t.type=Ie.c(e,0,i),t.ns=Ie.c(e,i+1))}return t}}function De(){return G.l}function xe(e){return o.d(e)?function(t){return e===t.fn}:De}function Ue(e,t,i){const{ns:r}=t;return r&&e?r===e:i?G.l:G.d}function $e(e,t,i){let r;return function(){let n=this;if(!r){const s=be(arguments);i&&q(e,n,s),r=setTimeout((function(){r=G.m,i||q(e,n,s)}),t)}}}var Be=i(3);class Ve extends class{constructor(e,t){this.audioWorkletNode=new AudioWorkletNode(e,t)}connect(e){this.audioWorkletNode.connect(e)}getNode(){return this.audioWorkletNode}disconnect(){this.audioWorkletNode.disconnect()}getParameters(e){const t=this.audioWorkletNode.parameters;if(o.d(t.get))return t.get(e);t.forEach(((t,i)=>{if(i===e)return t}))}}{constructor(e){super(e,"meter-processor"),this.audioLevel=0,this.audioWorkletNode.port.onmessage=e=>{this.audioLevel=e.data}}getAudioLevel(){return this.audioLevel}}const Fe="\nfunction webpackBootstrapFunc (modules) {\n var installedModules = {};\n function __webpack_require__(moduleId) {\n if(installedModules[moduleId])\n return installedModules[moduleId].exports;\n var module = installedModules[moduleId] = {\n i: moduleId,\n l: false,\n exports: {}\n };\n modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n module.l = true;\n return module.exports;\n }\n __webpack_require__.m = modules;\n __webpack_require__.c = installedModules;\n __webpack_require__.i = function(value) { return value; };\n __webpack_require__.d = function(exports, name, getter) {\n if(!__webpack_require__.o(exports, name)) {\n Object.defineProperty(exports, name, {\n configurable: false,\n enumerable: true,\n get: getter\n });\n }\n };\n __webpack_require__.r = function(exports) {\n Object.defineProperty(exports, '__esModule', { value: true });\n };\n __webpack_require__.n = function(module) {\n var getter = module && module.__esModule ?\n function getDefault() { return module['default']; } :\n function getModuleExports() { return module; };\n __webpack_require__.d(getter, 'a', getter);\n return getter;\n };\n __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n __webpack_require__.p = \"/\";\n __webpack_require__.oe = function(err) { console.error(err); throw err; };\n var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE);\n return f.default || f;\n}\n";function je(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function He(e,t,r){const n={};n[r]=[];let s=t.toString();const o=s.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!o)return n;const a=o[1];let c,u=new RegExp("(\\\\n|\\W)"+je(a)+"\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");for(;c=u.exec(s);)"dll-reference"!==c[3]&&n[r].push(c[3]);for(u=new RegExp("\\("+je(a)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)',"g");c=u.exec(s);)e[c[2]]||(n[r].push(c[1]),e[c[2]]=i(c[1]).m),n[c[2]]=n[c[2]]||[],n[c[2]].push(c[4]);const d=Object.keys(n);for(let e=0;e<d.length;e++)for(let t=0;t<n[d[e]].length;t++)l=n[d[e]][t],isNaN(1*l)||(n[d[e]][t]=1*n[d[e]][t]);var l;return n}function We(e){return Object.keys(e).reduce((function(t,i){return t||e[i].length>0}),!1)}var Ge=function(e,t){t=t||{};const r={main:i.m},n=t.all?{main:Object.keys(r.main)}:function(e,t){const i={main:[t]},r={main:[]},n={main:{}};for(;We(i);){const t=Object.keys(i);for(let s=0;s<t.length;s++){let o=t[s],a=i[o].pop();if(n[o]=n[o]||{},n[o][a]||!e[o][a])continue;n[o][a]=!0,r[o]=r[o]||[],r[o].push(a);let c=He(e,e[o][a],o),u=Object.keys(c);for(let e=0;e<u.length;e++)i[u[e]]=i[u[e]]||[],i[u[e]]=i[u[e]].concat(c[u[e]])}}return r}(r,e);let s="";Object.keys(n).filter((function(e){return"main"!==e})).forEach((function(e){let t=0;for(;n[e][t];)t++;n[e].push(t),r[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",s=s+"var "+e+" = ("+Fe.replace("ENTRY_MODULE",JSON.stringify(t))+")({"+n[e].map((function(t){return JSON.stringify(t)+": "+r[e][t].toString()})).join(",")+"});\n"})),s=t.simple?"("+r.main[e].toString().replace(/^function(module, exports) {\\n*/,"")+")(null, null)":s+"new (("+Fe.replace("ENTRY_MODULE",JSON.stringify(e))+")({"+n.main.map((function(e){return JSON.stringify(e)+": "+r.main[e].toString()})).join(",")+"}))(self);";const o=new window.Blob([s],{type:"text/javascript"});return t.bare?o:(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(o)},qe=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const Je={averaging:.95};let ze;const Ye="function"==typeof AudioWorkletNode;let Qe;class Ke{constructor(e={}){this.options=Me({},Je,e),this.readyed=!1,ze||function(){let e=window.AudioContext||window.webkitAudioContext;if(ze=new e,Ye){const e=Ge(16,{simple:!0});Qe=ze.audioWorklet.addModule(e)}}()}ready(){return qe(this,void 0,void 0,(function*(){this.readyed||(Ye?yield new Promise((e=>{Qe.then((()=>{this.createWorkletNode(),e()}))})):this.createScriptProcessorNode(),this.node.connect(ze.destination),this.readyed=!0,"suspended"===ze.state&&this.resume())}))}createWorkletNode(){this.node=new Ve(ze);const e=this.node.getParameters("output"),t=this.node.getParameters("averaging");e.value=0,t.value=this.options.averaging}createScriptProcessorNode(){const e=ze.createScriptProcessor(2048,1,1);e.onaudioprocess=t=>{const i=t.inputBuffer.getChannelData(0);let r=0;for(let e=0;e<i.length;e++)r+=i[e]*i[e];const n=Math.sqrt(r/i.length);e.volume=Math.max(n,e.volume*e.averaging)},e.volume=0,e.averaging=this.options.averaging,this.node=e}connect(e){return qe(this,void 0,void 0,(function*(){if("audio"===e.kind){if(this.readyed||(yield this.ready()),e===this.track)return;this.disconnect(),this.track=e,this.mediaStream=new MediaStream,this.mediaStream.addTrack(this.track),this.mediaSourceNode=ze.createMediaStreamSource(this.mediaStream),Ye?this.mediaSourceNode.connect(this.node.getNode()):this.mediaSourceNode.connect(this.node)}}))}getVolume(){return this.node?Ye?this.node.getAudioLevel():this.node.volume:0}disconnect(){this.mediaSourceNode&&(this.mediaSourceNode.disconnect(),this.mediaSourceNode=null),this.track=null,this.mediaStream=null}resume(){return qe(this,void 0,void 0,(function*(){if(ze&&"suspended"===ze.state)return ze.resume()}))}destroy(){this.disconnect(),this.node&&(this.node.disconnect(),this.node=null),this.readyed=!1}}function Xe(e,t){return o.g(e)?+e:t!==G.m?t:0}function Ze(e,t,i=!1){const r=t.split("."),n=e.split(".");for(let e=0;e<n.length;e++){if(i&&e==n.length-1&&Xe(n[e])>=Xe(r[e]))return n.length>=r.length;if(Xe(n[e])>Xe(r[e]))return!0;if(Xe(n[e])<Xe(r[e]))return!1;if(e===r.length-1&&e===n.length-1)return i;if(e===r.length-1)return!0;if(e===n.length-1)return!1}return!0}var et;function tt(e){return o.i(e)&&e.split(".").shift()||""}!function(e){e.ALIPAY="alipay",e.WECHAT="wechat",e.DING_TALK="dingtalk",e.BAIDU_APP="baiduApp",e.BAIDU="baidu",e.UC="uc",e.QQ="qq",e.QQ_APP="qqApp",e.IE="ie",e.EDGE="edge",e.CHROME="chrome",e.FIREFOX="firefox",e.OPERA="opera",e.SAFARI="safari",e.NEW_EDGE="newEdge"}(et||(et={}));const it=[[et.ALIPAY,/alipay/],[et.WECHAT,/micromessenger/],[et.DING_TALK,/dingtalk[ \/]([\d_.]+)/],[et.BAIDU_APP,/baiduboxapp/],[et.BAIDU,/baidubrowser/],[et.BAIDU,/bdbrowser/],[et.UC,/ucbrowser/],[et.UC,/ucweb/],[et.QQ,/qqbrowser[ \/]([\d_.]+)/],[et.QQ_APP,/qq/],[et.IE,/iemobile[ \/]([\d_.]+)/],[et.IE,/msie[ \/]([\d_.]+)/],[et.IE,/trident[ \/]([\d_.]+)/,4],[et.EDGE,/edge[ \/]([\d_.]+)/],[et.NEW_EDGE,/edg[ \/]([\d_.]+)/],[et.CHROME,/chrome[ \/]([\d_.]+)/],[et.FIREFOX,/firefox[ \/]([\d_.]+)/],[et.OPERA,/opera(?:.*version)?[ \/]([\d_.]+)/],[et.SAFARI,/version[ \/]([\d_.]+) safari/],[et.SAFARI,/version[ \/]([\d_.]+) \S* safari/],[et.SAFARI,/safari/]],rt={},nt={},st=function(e){let t,i;return ge(it,(r=>{let n=r[1].exec(e);if(n)return t=r[0],i=n[1],i&&(i=i.replace(/_/g,"."),r[2]&&(i=parseInt(i,10)+r[2]+".0")),!1})),{name:t||"",version:i||"",majorVersion:(rt[t]||tt)(i),checkVersion:nt[t]||Ze}}((navigator.userAgent||"").toLowerCase());st.name&&(st[st.name]=!0);var ot=st;function at(e){if(o.i(e))return e;if(o.h(e)){if(o.i(e.message))return e.message;if(o.i(e.msg))return e.msg;if(o.d(e.toString))return e.toString()}return"unknow"}class ct{constructor(e,t,i){this.task=e,this.timeout=t,this.interval=i}start(){const e=this;e.stop();let t=e.timeout;const i=e.interval,r=function(){!1!==e.task()&&e.timer?e.timer=setTimeout(r,e.interval):e.stop()};null==t&&(t=i),e.timer=setTimeout(r,t)}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}updateInterval(e){this.interval=e}isStarted(){return!!this.timer}destroy(){this.stop(),this.task=this.timeout=this.interval=null}}function ut(e){if(e&&C.instanceOf(e))return e.getCode();const t=at(e);return"request timeout"===t?9001:"stream has already destroyed"===t?4010:9e3}function dt(e){if(e){if(C.instanceOf(e))return null;if(o.d(e.getCode))return e.getCode();if(we(e.code))return e.code}return null}var lt=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class ht{constructor(e,t,i,r,n){if(this.uid=i,this.type=e,this.stream=n,this.webrtcType=r,this.iceStartTS=0,this.destroyed=!1,this.sid=t||Y(),this.emitter=new Ne(!0),this.reportCollector=new ve(2),this.audioTrackEventHandler={ended:()=>{this.audioMuteTimer&&(clearTimeout(this.audioMuteTimer),this.audioMuteTimer=null),this.emitter&&this.fire(X),this.log(`${this.sid} Stream audioTrack ended, userId: ${this.uid}`,he.DEBUG,"stream")},mute:()=>{this.getAudioOn()&&(this.audioMuteTimer&&clearTimeout(this.audioMuteTimer),this.audioMuteTimer=setTimeout((()=>{this.log(`${this.sid} Stream audioTrack mute, userId: ${this.uid}`,this.isLocalStream()?he.WARN:he.DEBUG,"stream"),this.fire(ee),this.audioMuteTimer=null}),3e3))},unmute:()=>{this.audioMuteTimer?(clearTimeout(this.audioMuteTimer),this.audioMuteTimer=null):(this.log(`${this.sid} Stream audioTrack unmute, userId: ${this.uid}`,he.DEBUG,"stream"),this.fire(ie))}},this.videoTrackEventHandler={ended:()=>{this.videoMuteTimer&&(clearTimeout(this.videoMuteTimer),this.videoMuteTimer=null),this.emitter&&this.fire(K),this.log(`${this.sid} Stream videoTrack ended, userId: ${this.uid}`,he.DEBUG,"stream")},mute:()=>{this.getVideoOn()&&(this.videoMuteTimer&&clearTimeout(this.videoMuteTimer),this.videoMuteTimer=setTimeout((()=>{this.log(`${this.sid} Stream videoTrack mute, userId: ${this.uid}`,this.isLocalStream()?he.WARN:he.DEBUG,"stream"),this.fire(Z),this.videoMuteTimer=null}),3e3))},unmute:()=>{this.videoMuteTimer?(clearTimeout(this.videoMuteTimer),this.videoMuteTimer=null):(this.log(`${this.sid} Stream videoTrack unmute, userId: ${this.uid}`,he.DEBUG,"stream"),this.fire(te))}},this.stream&&this.isLocalStream()&&this.addTrackEvents(),this.debounceReplay=$e((()=>{this.playing&&this.player&&this.player.replay(this)}),100),(this.isLocalStream()||c(this.webrtcType)||(ot.safari||ot.firefox)&&a(this.webrtcType))&&!ot.dingtalk){try{this.soundMeter=new Ke}catch(e){this.soundMeter=null}this.audioLevelTimer=new ct((()=>{this.fire(de,this.getAudioLevel())}),0,1e3)}this.playing=!1}isStream(e){return this.stream===e}isLocalStream(){return this.type===ht.STREAM_TYPE_LOCAL}isScreenStream(){return!1}isPlaying(){return this.playing}isDestroyed(){return this.destroyed}getWebRTCType(){return this.webrtcType}getUserId(){return this.uid}setUserId(e){this.uid=e}getStreamId(){return this.sid}setStreamId(e){this.sid=e}getStream(){return this.stream}setStream(e,t){this.removeTrackEvents(),this.removeHandleEvents(),this.stream=t,this.webrtcType=e,this.isLocalStream()&&this.addTrackEvents(),this.handleEvents(),this.playing&&this.player&&this.debounceReplay(),this.log("setStream, userId: "+this.uid,he.DEBUG,"stream")}getClient(){return this.client}setClient(e){this.client=e}syncClientOptions(e){o.f(e.audioLevelInterval)&&this.audioLevelTimer&&this.audioLevelTimer.updateInterval(e.audioLevelInterval)}setLogger(e){this.logger=e}setCollection(e){this.collection=e}getCollection(){return this.collection}setVolumeMeter(){this.audioTrack&&this.soundMeter&&this.soundMeter.connect(this.audioTrack),this.audioLevelTimer&&!this.audioLevelTimer.isStarted()&&this.audioLevelTimer.start()}hasVideo(){return!!this.stream&&(this.isLocalStream()?!!this.videoTrack:this.stream.hasVideo())}hasAudio(){return!!this.stream&&(this.isLocalStream()?!!this.audioTrack:this.stream.hasAudio())}getVideoOn(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(a(this.webrtcType))return this.stream.getVideoEnable();if(c(this.webrtcType)){if(this.isLocalStream()&&this.videoTrack)return this.videoTrack.enabled;if(!this.isLocalStream()&&t){let e=!1;return ge(t.getRemoteMutedState(),((t,i)=>{const r=this.getUserId();if(o.f(r)&&W(t.userId,!1)===r||o.i(r)&&W(t.userId,!0)===r)return e=!t.videoMuted,!1})),e}}return!1}getAudioOn(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(a(this.webrtcType))return this.stream.getAudioEnable();if(c(this.webrtcType)){if(this.isLocalStream()&&this.audioTrack)return this.audioTrack.enabled;if(!this.isLocalStream()&&t){let e=!1;return ge(t.getRemoteMutedState(),((t,i)=>{const r=this.getUserId();if(o.f(r)&&W(t.userId,!1)===r||o.i(r)&&W(t.userId,!0)===r)return e=!t.audioMuted,!1})),e}}return!1}get audioTrack(){return this.stream?this.stream.getAudioTrack():null}get videoTrack(){return this.stream?this.stream.getVideoTrack():null}getAudioTrack(){if(this.stream)return this.audioTrack}getVideoTrack(){if(this.stream)return this.videoTrack}getMediaStream(){if(this.stream)return a(this.webrtcType)?this.stream.getStream():c(this.webrtcType)?this.stream.mediaStream_:void 0}muteVideo(){return lt(this,void 0,void 0,(function*(){if(this.hasVideo())try{return this.type===ht.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.muteVideo():c(this.webrtcType)&&this.stream.muteVideo():this.type===ht.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.muteVideo(),this.stutter&&this.stutter.resetVideo()),this.playing&&this.player&&this.player.muteVideo()),this.reportAction("videoDisable",0,null,null,{stream:this.getActionStreamId()}),!0}catch(e){return this.reportAction("videoDisable",ut(e),null,null,{stream:this.getActionStreamId()},dt(e)),!1}return!1}))}unmuteVideo(){return lt(this,void 0,void 0,(function*(){if(this.hasVideo())try{return this.type===ht.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.unmuteVideo():c(this.webrtcType)&&this.stream.unmuteVideo():this.type===ht.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.unmuteVideo(),this.stutter&&this.stutter.resetVideo()),this.playing&&this.player&&this.player.unmuteVideo()),this.reportAction("videoEnable",0,null,null,{stream:this.getActionStreamId()}),!0}catch(e){return this.reportAction("videoEnable",ut(e),null,null,{stream:this.getActionStreamId()},dt(e)),!1}return!1}))}muteAudio(){return lt(this,void 0,void 0,(function*(){if(this.hasAudio())try{return this.type===ht.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.muteAudio():c(this.webrtcType)&&this.stream.muteAudio():this.type===ht.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.muteAudio(),this.stutter&&this.stutter.resetAudio()),this.playing&&this.player&&this.player.muteAudio()),this.reportAction("audioDisable",0,null,null,{stream:this.getActionStreamId()}),!0}catch(e){return this.reportAction("audioDisable",ut(e),null,null,{stream:this.getActionStreamId()},dt(e)),!1}return!1}))}unmuteAudio(){return lt(this,void 0,void 0,(function*(){if(this.hasAudio())try{return this.type===ht.STREAM_TYPE_LOCAL?a(this.webrtcType)?yield this.stream.unmuteAudio():c(this.webrtcType)&&this.stream.unmuteAudio():this.type===ht.STREAM_TYPE_REMOTE&&(a(this.webrtcType)&&(yield this.stream.unmuteAudio(),this.stutter&&this.stutter.resetAudio()),this.playing&&this.player&&this.player.unmuteAudio()),this.reportAction("audioEnable",0,null,null,{stream:this.getActionStreamId()}),!0}catch(e){return this.reportAction("audioEnable",ut(e),null,null,{stream:this.getActionStreamId()},dt(e)),!1}return!1}))}play(e,t){return lt(this,void 0,void 0,(function*(){if(t=Object.assign({fit:"contain",muted:!1,audio:!0,video:!0},t||{}),!this.stream)throw new C(1002,"没有流可以播放");if(!e)throw new C(1002,"videoId 值非法");if(this.playing)this.log(`${this.sid} stream is already playing, userId: ${this.uid}`,he.WARN,"stream");else{if(o.i(e)){const t="#"+e;if(!(e=document.querySelector(t)))return void this.log(`${this.sid} stream cannot play because of cannot found the container, videoId: ${t}, userId: ${this.uid}`,he.ERROR,"stream")}this.player&&this.player.destroy(),this.player=new pe(e,t,this.logger),this.playing=!0;try{yield this.player.play(this)}catch(e){throw this.log(`${this.sid} stream play error, userId: ${this.uid}, error: ${at(e)}`,he.ERROR,"stream"),e}this.log(`${this.sid} stream play, userId: ${this.uid}, options: ${JSON.stringify(t)}`,he.INFO,"stream")}}))}replay(){return lt(this,void 0,void 0,(function*(){if(!this.stream)throw new C(1002,"没有流可以播放");this.playing&&this.player?yield this.player.replay(this):this.log(`${this.sid} stream is not playing, userId: ${this.uid}`,he.WARN,"stream")}))}resume(){return lt(this,void 0,void 0,(function*(){if(this.player){try{yield this.player.resume(),this.playing=!0}catch(e){throw e}this.log(`${this.sid} stream resume, userId: ${this.uid}`,he.DEBUG,"stream")}this.soundMeter&&this.soundMeter.resume()}))}stop(){this.player&&(this.player.destroy(),this.player=null,this.log(`${this.sid} stream stop, userId: ${this.uid}`,he.DEBUG,"stream")),this.playing=!1}close(){this.stop(),this.stream&&(this.removeHandleEvents(),this.removeTrackEvents(),a(this.webrtcType)?this.stream.destroy():c(this.webrtcType)&&this.stream.close(),this.log(`${this.sid} stream close, userId: ${this.uid}`,he.DEBUG,"stream")),this.emitter&&(this.client=null,this.stutter&&(this.stutter.destroy(),this.stutter=null),this.reportCollector&&(this.reportCollector.destroy(),this.reportCollector=null),this.fire(le),this.emitter.off(),this.emitter=null),this.soundMeter&&(this.soundMeter.destroy(),this.soundMeter=null),this.audioLevelTimer&&(this.audioLevelTimer.destroy(),this.audioLevelTimer=null),this.debounceReplay=null,this.audioTrackEventHandler=null,this.videoTrackEventHandler=null,this.destroyed=!0}destroy(){this.close()}getAudioLevel(){return this.stream?this.stream.getAudioLevel()||(this.soundMeter?this.soundMeter.getVolume():0):0}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}on(e,t){return this.emitter&&this.emitter.on(e,{fn:t,ctx:this}),this}one(e,t){return this.emitter&&this.emitter.on(e,{fn:t,ctx:this,max:1}),this}has(e,t){return!!this.emitter&&this.emitter.has(e,t)}off(e,t){return this.emitter&&this.emitter.off(e,t),this}getAudioDeviceId(){return this.audioDeviceId}getAudioVolume(){return this.audioVolume}getVideoFrame(){if(this.hasVideo()&&this.player&&this.playing)return this.player.getVideoFrame();throw new C(1002,"流没有 videoTrack 或者没有播放")}getMSIP(){return a(this.webrtcType)&&this.stream&&this.stream.getMsmsIP()||""}setICEStartTS(e){this.iceStartTS=e}getMediaNodeIp(){return this.stream&&a(this.webrtcType)?this.stream.getSelectedMsmsIP():""}addTrackEvents(){this.addAudioTrackEvents(),this.addVideoTrackEvents()}removeTrackEvents(){this.removeAudioTrackEvents(),this.removeVideoTrackEvents()}addVideoTrackEvents(){if(this.hasVideo()){let e=this.videoTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceVideoTrack()||e),e&&ke(this.videoTrackEventHandler,((t,i)=>{e.addEventListener(i,t)}))}}removeVideoTrackEvents(){if(this.hasVideo()){let e=this.videoTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceVideoTrack()||e),e&&ke(this.videoTrackEventHandler,((t,i)=>{e.removeEventListener(i,t)}))}this.videoMuteTimer&&(clearTimeout(this.videoMuteTimer),this.videoMuteTimer=null)}addAudioTrackEvents(){if(this.hasAudio()){let e=this.audioTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceAudioTrack()||e),e&&ke(this.audioTrackEventHandler,((t,i)=>{e.addEventListener(i,t)}))}}removeAudioTrackEvents(){if(this.stream&&this.stream._volumeMeter&&(this.stream._volumeMeter.disconnect(),this.stream._volumeMeter=null),this.hasAudio()){let e=this.audioTrack;a(this.webrtcType)&&this.isLocalStream()&&(e=this.stream.getSourceAudioTrack()||e),e&&ke(this.audioTrackEventHandler,((t,i)=>{e.removeEventListener(i,t)}))}this.audioMuteTimer&&(clearTimeout(this.audioMuteTimer),this.audioMuteTimer=null)}removeHandleEvents(){this.stream&&a(this.webrtcType)&&this.stream.off()}handleEvents(){this.stream&&a(this.webrtcType)&&(this.stream.on("stream-connection-error",(()=>{this.stream&&this.fire(se);const e={stream:this.getActionStreamId(),flow:this.type===ht.STREAM_TYPE_LOCAL?1:2,msip:this.stream.getMsmsIP()||""};this.type===ht.STREAM_TYPE_LOCAL?e.user=Object(Be.a)(this.getUserId()):e.remote_id=Object(Be.a)(this.getUserId()),this.reportAction("mediaChannelDisconnect",4003,null,null,e)})),this.stream.on("stream-disconnected",(()=>{this.stream&&this.fire(se);const e={stream:this.getActionStreamId(),flow:this.type===ht.STREAM_TYPE_LOCAL?1:2,msip:this.stream.getMsmsIP()||""};this.type===ht.STREAM_TYPE_LOCAL?e.user=Object(Be.a)(this.getUserId()):e.remote_id=Object(Be.a)(this.getUserId()),this.reportAction("mediaChannelDisconnect",4003,null,null,e)})),this.stream.on("stream-connection-success",(()=>{this.stream&&this.fire(oe);const e={stream:this.getActionStreamId(),flow:this.type===ht.STREAM_TYPE_LOCAL?1:2,msip:this.stream.getMsmsIP()||""};this.type===ht.STREAM_TYPE_LOCAL?e.user=Object(Be.a)(this.getUserId()):e.remote_id=Object(Be.a)(this.getUserId()),this.reportAction("mediaChannelConnect",0,this.iceStartTS,Q(),e)})),this.stream.on("stream-reconnecting",(()=>{this.stream&&this.fire(ae)})),this.stream.on("stream-replaced",(e=>{this.stream&&this.player&&this.player.replay(this,!!e.video,!!e.audio),e.video&&this.fire(re,{type:"video",track:e.video}),e.audio&&this.fire(re,{type:"audio",track:e.audio})})),this.stream.on("stream-update",(e=>{(null==e?void 0:e.trackUpdate)&&(this.stream&&this.player&&this.player.replay(this),this.audioTrack&&this.fire(re,{type:"audio",track:this.audioTrack}),this.videoTrack&&this.fire(re,{type:"video",track:this.videoTrack}))})),this.stream.on("video-adaptation-changed",(e=>{this.isLocalStream()&&this.reportAction("videoAdaptationChanged",0,null,null,{stream:this.getActionStreamId(),adaptation:JSON.stringify(e)})})),this.stream.on("stream-audio-level",(e=>{this.audioLevelTimer&&(this.audioLevelTimer.destroy(),this.audioLevelTimer=null),this.soundMeter&&(this.soundMeter.destroy(),this.soundMeter=null),this.fire(de,e)})),this.stream.on("stream-video-adaption",(e=>{this.fire("stream-video-adaption",{videoEnable:e.video_enable})})),this.stream.on("stream-sei-message",(e=>{this.fire("stream-sei-message",{data:e.data,payloadType:e.payload})})))}reportAction(e,t,i,r,n,s){this.collection&&this.collection.action(e,t,i,r,n,s)}getAudioRTPStats(e){if(!e)return{};for(let t=0;t<e.rtps.length;t++)if("audio"===e.rtps[t].kind)return e.rtps[t]}getVideoRTPStats(e,t=!0){var i,r,n,s,o,a,c,u;if(e){let d;for(let l=0;l<e.rtps.length;l++)if("video"===e.rtps[l].kind){if(t&&"r1"===e.rtps[l].rid)return e.rtps[l];if(!t&&"r0"===e.rtps[l].rid)return e.rtps[l];d?t?((null===(i=d.resolution)||void 0===i?void 0:i.width)<(null===(r=e.rtps[l].resolution)||void 0===r?void 0:r.width)||(null===(n=d.resolution)||void 0===n?void 0:n.height)<(null===(s=e.rtps[l].resolution)||void 0===s?void 0:s.height))&&(d=e.rtps[l]):((null===(o=d.resolution)||void 0===o?void 0:o.width)>(null===(a=e.rtps[l].resolution)||void 0===a?void 0:a.width)||(null===(c=d.resolution)||void 0===c?void 0:c.height)>(null===(u=e.rtps[l].resolution)||void 0===u?void 0:u.height))&&(d=e.rtps[l]):d=e.rtps[l]}return d}return{}}log(e,t,i){this.logger?this.logger.log(e,t,i):he.log(t,e,i)}getActionStreamId(){return c(this.webrtcType)?Object(Be.a)(this.getUserId()):this.getStreamId()}setAudioEncodeDataPipe(e){a(this.webrtcType)&&this.stream&&this.stream.setAudioEncodeDataPipe(e)}setVideoEncodeDataPipe(e){a(this.webrtcType)&&this.stream&&this.stream.setVideoEncodeDataPipe(e)}requestKeyFrame(){a(this.webrtcType)&&this.stream&&this.stream.requestKeyFrame()}}ht.STREAM_TYPE_LOCAL=0,ht.STREAM_TYPE_REMOTE=1;class mt{constructor(e,t=6){this.win=t,this.threshold=e,this.packetLoss=new fe(this.win)}add(e,t){this.packetLoss.addData(e,t)}judge(){return this.packetLoss.getPacketLossRate()>this.threshold}getAvgLoss(){return this.packetLoss.getPacketLossRate()}destroy(){this.win=this.threshold=this.packetLoss=null}reset(){this.packetLoss&&this.packetLoss.reset()}}class pt{constructor(e,t=6){this.win=t,this.threshold=e,this.queue=[],this.maxFrameRate=0}updateMaxFrameRate(e){e>this.maxFrameRate&&(this.maxFrameRate=e)}add(e){this.updateMaxFrameRate(e),this.queue.push(e),this.queue.length>this.win&&this.queue.shift()}judge(){if(!this.queue.length)return!1;const e=this.queue.reduce(((e,t)=>e+t),0);return this.maxFrameRate<=5?e/this.queue.length<=Math.floor(.4*this.maxFrameRate):e/this.queue.length<=this.threshold}destroy(){this.win=this.threshold=this.queue=null}reset(){this.queue.length=0}}class ft{constructor(e,t=6){this.win=t,this.threshold=e,this.delayInvalidCount=0}add(e){-1===e||e>this.threshold?this.delayInvalidCount++:this.delayInvalidCount=0}judge(){return this.delayInvalidCount>this.win}destroy(){this.win=this.threshold=this.delayInvalidCount=null}reset(){this.delayInvalidCount=0}}class vt{constructor(e=1,t=48e3){this.channel=e,this.sampleRate=t,this.concealedSamples=0,this.totalSamplesReceived=0,this.concealmentEvents=0,this.totalAudioEnergy=0,this.totalSamplesDuration=0,this.silentConcealedSamples=0,this.samplesFactor=0,this.eventFactor=0,this.level=0,this.slientPercent=0}add(e,t,i,r,n,s){t!==this.totalSamplesReceived?this.samplesFactor=(e-this.concealedSamples)/(t-this.totalSamplesReceived):this.samplesFactor=0,i!==this.concealmentEvents?(this.eventFactor=(e-this.concealedSamples)/(i-this.concealmentEvents),this.eventFactor=1e3*this.eventFactor/(this.channel*this.sampleRate)):this.eventFactor=0,n!==this.totalSamplesDuration?this.level=(r-this.totalAudioEnergy)/(n-this.totalSamplesDuration):this.level=0,e&&(this.slientPercent=s/e),this.concealedSamples=e,this.totalSamplesReceived=t,this.concealmentEvents=i,this.totalAudioEnergy=r,this.totalSamplesDuration=n,this.silentConcealedSamples=s}judge(){return this.eventFactor>80||this.samplesFactor>.2}reset(){this.concealedSamples=0,this.totalSamplesReceived=0,this.concealmentEvents=0,this.totalAudioEnergy=0,this.totalSamplesDuration=0,this.silentConcealedSamples=0,this.samplesFactor=0,this.eventFactor=0,this.level=0,this.slientPercent=0}}class gt{constructor(e,t,i={}){this.threshold=e,this.isPush=t,this.options=i,this.audioPacketLossStutter=new mt(t?this.threshold.audio_loss_rate_threshold:this.threshold.down_audio_loss_rate_threshold),this.videoPacketLossStutter=new mt(t?this.threshold.video_loss_rate_threshold:this.threshold.down_video_loss_rate_threshold),this.frameRateStutter=new pt(this.threshold.send_frame_rate_threshold),this.audioframeDelayStutter=new ft(this.threshold.audio_frame_render_interval_threshold),this.videoframeDelayStutter=new ft(this.threshold.video_frame_render_interval_threshold),ot.chrome&&!this.isPush&&(this.audioStutter=new vt(this.options.channel,this.options.sampleRate))}addFrameRate(e){this.frameRateStutter.add(e)}addAudioLoss(e,t){this.audioPacketLossStutter.add(e,t)}addVideoLoss(e,t){this.videoPacketLossStutter.add(e,t)}addAudioFrameDelay(e){this.audioframeDelayStutter.add(e)}addVideoFrameDelay(e){this.videoframeDelayStutter.add(e)}addAudioStutterData(e,t,i,r,n,s){this.audioStutter&&this.audioStutter.add(e,t,i,r,n,s)}judgeAudioStutter(){return!this.isPush&&this.audioStutter?this.audioStutter.judge():this.audioPacketLossStutter.judge()||this.audioframeDelayStutter.judge()}judegVideoStutter(){return this.videoPacketLossStutter.judge()||this.frameRateStutter.judge()&&this.videoPacketLossStutter.getAvgLoss()>10||this.videoframeDelayStutter.judge()}destroy(){this.audioPacketLossStutter.destroy(),this.videoPacketLossStutter.destroy(),this.frameRateStutter.destroy(),this.audioframeDelayStutter.destroy(),this.videoframeDelayStutter.destroy(),this.audioPacketLossStutter=this.videoPacketLossStutter=this.audioframeDelayStutter=this.videoframeDelayStutter=this.frameRateStutter=this.audioStutter=null}resetAudio(){this.audioStutter&&this.audioStutter.reset(),this.audioPacketLossStutter&&this.audioPacketLossStutter.reset(),this.audioframeDelayStutter&&this.audioframeDelayStutter.reset()}resetVideo(){this.videoPacketLossStutter&&this.videoPacketLossStutter.reset(),this.frameRateStutter&&this.frameRateStutter.reset(),this.videoPacketLossStutter&&this.videoPacketLossStutter.reset(),this.videoframeDelayStutter&&this.videoframeDelayStutter.reset()}}var _t=i(6),yt=i.n(_t);const St=he.DEBUG,Et=he.INFO,bt=he.WARN,Tt=he.ERROR,It=void 0!==typeof console?console:null,Ct=/BRTC/.test(Object(Be.a)((function(){})))?St:bt;function wt(e,t,i,r){let n=[];return o.f(S())&&n.push(S()),i&&n.push(i),r&&n.push(r),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function Rt(){if(window){const e=window.BRTC_LOG_LEVEL;if(e>=St&&e<=6)return e}return Ct}const kt={[St]:function(e,t,i,r=[]){It&&Rt()<=St&&(r.unshift(wt("DEBUG",e,t,i)),It.log.apply(It.log,r))},[Et]:function(e,t,i,r=[]){It&&Rt()<=Et&&(r.unshift(wt("INFO",e,t,i)),It.log.apply(It.log,r))},[bt]:function(e,t,i,r=[]){It&&Rt()<=bt&&(r.unshift(wt("WARN",e,t,i)),It.warn.apply(It.warn,r))},[Tt]:function(e,t,i,r=[]){It&&Rt()<=Tt&&(r.unshift(wt("ERROR",e,t,i)),It.error.apply(It.error,r))}};var At,Mt;!function(e){e.CAMERA="camera",e.SCREEN="screen",e.FILE="file"}(At||(At={})),function(e){e[e.PACKETS_LOST_SCALE=1]="PACKETS_LOST_SCALE"}(Mt||(Mt={}));var Ot=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class Lt extends ht{constructor(e,t,i,r){super(ht.STREAM_TYPE_REMOTE,r,e,t,i),this.audioVolume=1,a(this.webrtcType)&&this.handleEvents(),this.subscribed=!1,this.unpublished=!1,this.stream&&a(this.webrtcType)&&(this.videoOn=this.stream.getVideoEnable(),this.audioOn=this.stream.getAudioEnable()),this.log(`${this.sid} RemoteStream create, userId: ${this.uid}`,St,"stream")}setStream(e,t){super.setStream(e,t),this.stream&&a(this.webrtcType)&&(this.videoOn=this.stream.getVideoEnable(),this.audioOn=this.stream.getAudioEnable())}isSubscribed(){return this.subscribed}isUnpublish(){return this.unpublished}getType(){var e;if(!this.stream)return"main";if(a(this.webrtcType)){const e=this.stream.getType();return e===At.SCREEN||e===At.FILE?"assist":"main"}return c(this.webrtcType)?"auxiliary"===(null===(e=this.stream)||void 0===e?void 0:e.getType())?"assist":"main":void 0}setAudioOutput(e){return Ot(this,void 0,void 0,(function*(){this.audioDeviceId=e,this.stream&&this.playing&&this.player&&(yield this.player.setSinkId(this.audioDeviceId),this.reportAction("deviceChange",0,null,null,{type:"speaker",device_id:e,stream:this.getActionStreamId()}),this.log(`${this.sid} RemoteStream setAudioOutput, userId: ${this.uid}, deviceId: ${e}`,Et,"stream"))}))}setAudioVolume(e){this.audioVolume=e,this.playing&&this.player&&(this.player.setVolume(this.audioVolume),this.log(`${this.sid} RemoteStream setAudioVolume, userId: ${this.uid}, volume: ${e}`,Et,"stream"))}play(e,t={}){const i=Object.create(null,{play:{get:()=>super.play}});return Ot(this,void 0,void 0,(function*(){this.audioDeviceId&&this.setAudioOutput(this.audioDeviceId);try{yield i.play.call(this,e,t),t.muted||this.setAudioVolume(this.audioVolume)}catch(e){throw e}}))}getStats(){var e;return Ot(this,void 0,void 0,(function*(){const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(t){if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),i=this.getVideoRTPStats(e);return{videoBytesReceived:Le(i,"statistics.bytesReceived",0),videoPacketsReceived:Le(i,"statistics.packetsReceived",0),videoPacketsLost:Le(i,"statistics.packetsLost",0),videoNacksCount:Le(i,"statistics.googNacksSent",0),audioBytesReceived:Le(t,"statistics.bytesReceived",0),audioPacketsReceived:Le(t,"statistics.packetsReceived",0),audioPacketsLost:Le(t,"statistics.packetsLost",0),audioNacksCount:Le(t,"statistics.googNacksSent",0),width:Le(i,"resolution.width",0),height:Le(i,"resolution.height",0),rtt:Le(e,"transport.0.rtt",0),framesDecoded:Le(i,"statistics.framesDecoded",0)}}if(c(this.webrtcType)){let e=yield t.getRemoteVideoStats();if(!this.client)throw new C(1010,"已被取消订阅");let i=yield t.getRemoteAudioStats();if(!this.client)throw new C(1010,"已被取消订阅");let r=yield t.getTransportStats(),n=e[this.uid],s=i[this.uid];return{videoBytesReceived:Le(n,"bytesReceived",0),videoPacketsReceived:Le(n,"packetsReceived",0),videoPacketsLost:Le(n,"packetsLost",0),videoNacksCount:0,audioBytesReceived:Le(s,"bytesReceived",0),audioPacketsReceived:Le(s,"packetsReceived",0),audioPacketsLost:Le(s,"packetsLost",0),audioNacksCount:0,width:Le(n,"frameWidth",0),height:Le(n,"frameHeight",0),rtt:Le(r,"rtt",0),framesDecoded:Le(n,"framesDecoded",0)}}}return{}}))}getReportStats(e){var t,i,r;return Ot(this,void 0,void 0,(function*(){if(!this.stutter){const r=this.getAudioTrack(),n={};if(r&&o.d(r.getSettings)){const e=r.getSettings();n.channels=null!==(t=e.channelCount)&&void 0!==t?t:1,n.sampleRate=null!==(i=e.sampleRate)&&void 0!==i?i:48e3}this.stutter=new gt(e,!1,n)}let n={bandwidth:{upload:0,download:0},bitrate:{audio:{upload:0,download:0},video:{upload:0,download:0}},packetLoss:{audio:{upload:0,download:0},video:{upload:0,download:0}},resolution:{width:0,height:0},framerate:0,audioLevel:0,transport:[{ip:"",type:"",localIp:"",localCandidateType:"",remoteCandidateType:"",networkType:"",rtt:0}],quality:{audio:{jitter:0,interruptionCount:0,interruptionDuration:0},video:{jitter:0,interruptionCount:0,interruptionDuration:0}},statistics:{audio:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0},video:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0,framesEncoded:0,framesDecoded:0,framesSent:0},bweforvideo:{googAvailableReceiveBandwidth:0,googAvailableSendBandwidth:0,googRetransmitBitrate:0,googTransmitBitrate:0,googTargetEncBitrate:0},ice:{packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0}},cpu:{appCpu:0,systemCpu:0}};const s=null===(r=this.client)||void 0===r?void 0:r.getClient();if(s)if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),i=this.getVideoRTPStats(e);n.audioLevel=this.getAudioLevel(),e.bandwidth&&(n.bandwidth=e.bandwidth),e.bitrate&&(n.bitrate=e.bitrate),e.packetLoss&&(n.packetLoss=e.packetLoss),e.transport&&(n.transport=e.transport),e.bweforvideo&&(n.statistics.bweforvideo={googAvailableReceiveBandwidth:e.bweforvideo.availableReceiveBandwidth,googAvailableSendBandwidth:e.bweforvideo.availableSendBandwidth,googRetransmitBitrate:e.bweforvideo.retransmitBitrate,googTransmitBitrate:e.bweforvideo.transmitBitrate,googTargetEncBitrate:e.bweforvideo.targetEncBitrate}),e.ice&&(n.statistics.ice=e.ice),t&&(n.quality.audio=t.qa,n.statistics.audio=t.statistics),i&&(n.quality.video=i.qa,n.statistics.video=i.statistics,n.resolution=i.resolution,n.framerate=i.framerate),this.stutter.addFrameRate(Le(n,"framerate",0)),this.stutter.addVideoLoss(Le(n,"statistics.video.packetsReceived",0),Le(n,"statistics.video.packetsLost",0)),this.stutter.addAudioLoss(Le(n,"statistics.audio.packetsReceived",0),Le(n,"statistics.audio.packetsLost",0)),this.stutter.addAudioFrameDelay(Le(n,"quality.audio.frameDelay",0)),this.stutter.addVideoFrameDelay(Le(n,"quality.video.frameDelay",0)),this.stutter.addAudioStutterData(Le(n,"statistics.audio.concealedSamples",0),Le(n,"statistics.audio.totalSamplesReceived",0),Le(n,"statistics.audio.concealmentEvents",0),Le(n,"statistics.audio.totalAudioEnergy",0),Le(n,"statistics.audio.totalSamplesDuration",0),Le(n,"statistics.audio.silentConcealedSamples",0)),!this.firstAudioShow&&Le(n,"statistics.audio.packetsReceived",0)>0&&(this.reportAction("firstAudioPlay",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(z()-this.subscribeTS,0),remote_id:Object(Be.a)(this.getUserId()),has_player:!!this.player,speaker_device_id:this.audioDeviceId||"default"}),this.firstAudioShow=!0),!this.firstVideoShow&&Le(n,"statistics.video.framesDecoded",0)>0&&(this.reportAction("firstVideoShow",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(z()-this.subscribeTS,0),remote_id:Object(Be.a)(this.getUserId()),has_player:!!this.player}),this.firstVideoShow=!0)}else{let e=yield s.getRemoteVideoStats();if(!this.client)throw new C(1010,"已被取消订阅");let t=yield s.getRemoteAudioStats();if(!this.client)throw new C(1010,"已被取消订阅");let i=yield s.getTransportStats(),r=e[this.uid],o=t[this.uid];this.reportCollector.addData(Le(o,"bytesReceived",0),Le(r,"bytesReceived",0),Le(o,"packetsReceived",0),Le(o,"packetsLost",0),Le(r,"packetsReceived",0),Le(r,"packetsLost",0),Le(r,"framesDecoded",0)),n.bitrate.audio.download=this.reportCollector.getAudioBitrate(),n.bitrate.video.download=this.reportCollector.getVideoBitrate(),n.packetLoss.audio.download=this.reportCollector.getAudioPacketLoss(),n.packetLoss.video.download=this.reportCollector.getVideoPacketLoss(),n.framerate=this.reportCollector.getFrameRate(),n.resolution.width=Le(r,"frameWidth",0),n.resolution.height=Le(r,"frameHeight",0),n.transport[0].rtt=Math.round(Le(i,"rtt",0)),n.audioLevel=this.getAudioLevel(),n.bandwidth.download=this.reportCollector.getAudioBitrate()+this.reportCollector.getVideoBitrate(),n.statistics.audio.bytesReceived=Le(o,"bytesReceived",0),n.statistics.audio.packetsReceived=Le(o,"packetsReceived",0),n.statistics.audio.packetsLost=Le(o,"packetsLost",0),n.statistics.video.bytesReceived=Le(r,"bytesReceived",0),n.statistics.video.packetsReceived=Le(r,"packetsReceived",0),n.statistics.video.framesDecoded=Le(r,"framesDecoded",0),n.statistics.video.packetsLost=Le(r,"packetsLost",0),this.stutter.addFrameRate(n.framerate),this.stutter.addVideoLoss(n.statistics.video.packetsReceived+n.statistics.video.packetsLost,n.statistics.video.packetsLost),this.stutter.addAudioLoss(n.statistics.audio.packetsReceived+n.statistics.audio.packetsLost,n.statistics.audio.packetsLost),!this.firstAudioShow&&Le(o,"packetsReceived",0)>0&&(this.reportAction("firstAudioPlay",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(z()-this.subscribeTS,0),remote_id:Object(Be.a)(this.getUserId()),has_player:!!this.player,speaker_device_id:this.audioDeviceId||"default"}),this.firstAudioShow=!0),!this.firstVideoShow&&Le(r,"framesDecoded",0)>0&&(this.reportAction("firstVideoShow",0,null,null,{stream:this.getActionStreamId(),duration:Math.max(z()-this.subscribeTS,0),remote_id:Object(Be.a)(this.getUserId()),has_player:!!this.player}),this.firstVideoShow=!0)}return n}))}getExtraReport(){if(this.stutter){const e=this.stutter.judgeAudioStutter(),t=this.stutter.judegVideoStutter();return{event:e||t?1:0,audio_stutter:this.getAudioOn()&&this.getAudioSubscribed()&&e?1:0,video_stutter:this.getVideoOn()&&this.getVideoSubscribed()&&t?1:0,downLink:0}}}onMediaUpdate(e){if(!this.stream||!a(this.webrtcType))return;const t=this.stream.getVideoEnable()&&this.stream.hasVideo(),i=this.stream.getAudioEnable()&&this.stream.hasAudio(),r=t!==this.videoOn,n=i!==this.audioOn;if(this.videoOn=t,this.audioOn=i,r){const i=t?L:O;this.log(`client event ${i}, userId: ${e.getUserId()}, streamUserId: ${this.uid}`,Et,"client"),e.fire(i,{stream:this})}if(n){const t=i?N:P;this.log(`client event ${t}, userId: ${e.getUserId()}, streamUserId: ${this.uid}`,Et,"client"),e.fire(t,{stream:this})}}onSubscribe(){this.firstVideoShow=!1,this.firstAudioShow=!1,this.subscribeTS=z(),this.addTrackEvents(),this.subscribed=!0,this.player&&this.playing&&this.replay(),this.setVolumeMeter()}onUnsubscribe(){this.removeTrackEvents(),this.subscribed=!1}setUnpublish(){this.unpublished=!0}hasSmallStream(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(a(this.webrtcType))return this.stream.getSimulcast()>1;if(c(this.webrtcType)&&t){let e=!1;return ge(t.getRemoteMutedState(),((t,i)=>{const r=this.getUserId();if(o.f(r)&&W(t.userId,!1)===r||o.i(r)&&W(t.userId,!0)===r)return e=!!t.hasSmall,!1})),e}return!1}getVideoAdaptionEnable(){return!(!a(this.webrtcType)||!this.stream)&&this.stream.getVideoAdaptionEnable()}destroy(){this.subscribed=!1,super.destroy()}getVideoSubscribed(){var e,t;return a(this.webrtcType)?this.stream.getVideoSubscribed():null!==(t=null===(e=this.subscribeOptions)||void 0===e?void 0:e.videoEnable)&&void 0!==t&&t}getAudioSubscribed(){var e,t;return a(this.webrtcType)?this.stream.getAudioSubscribed():null!==(t=null===(e=this.subscribeOptions)||void 0===e?void 0:e.audioEnable)&&void 0!==t&&t}}var Pt=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const Nt=[w,R,k,A,M,O,L,P,N,D,x,U,$,B,V,F,j,H],Dt={1:{[w]:"stream-added",[R]:"stream-removed",[k]:"stream-updated",[A]:"",[M]:"stream-subscribed",[O]:"mute-video",[L]:"unmute-video",[P]:"mute-audio",[N]:"unmute-audio",[x]:"peer-join",[U]:"peer-leave",[$]:"client-banned",[D]:"error"},0:{[w]:"stream-added",[R]:"stream-removed",[k]:"",[A]:"",[M]:"",[O]:"",[L]:"",[P]:"",[N]:"",[D]:"error",[x]:"peer-joined",[U]:"peer-leaved",[$]:"peer-rejoined",[B]:"evicted",[V]:"token-will-expire",[F]:"token-expire",[j]:"room-closed",[H]:"sync-room-completed"}},xt={0:{[w]:function(e){let t=new Lt(W(e.getUserId(),this.useStringUserId),this.webrtcType,e,e.getStreamId());return t.setLogger(this.logger),this.addRemoteStream(t),this.logger.info(`${w}, userId: ${this.userId}, streamUserId: ${t.getUserId()}, streamId: ${t.getStreamId()}`,"client"),{stream:t}},[R]:function(e){let t=this.removeRemoteStream(e.getUserId(),e.getStreamId());return t||(t=new Lt(W(e.getUserId(),this.useStringUserId),this.webrtcType,e,e.getStreamId()),t.setLogger(this.logger)),t.setUnpublish(),this.logger.info(`${R}, userId: ${this.userId}, streamUserId: ${t.getUserId()}, streamId: ${t.getStreamId()}`,"client"),{stream:t}},[D]:function(e){var t;let i=4002;"error-room"===e&&(i=4001);const r=this.getActiveProxy();return this.reportAction("signalChannelDisconnect",i,0,0,{proxy:{url:r?r.activeUrl||r.url||r.dcurl:"",location:r&&null!==(t=r.location)&&void 0!==t?t:""}}),this.logger.error(`${D}, userId: ${this.userId}, error: ${at(i)}`,"client"),new C(i)},[x]:function(e){const t=W(e,this.useStringUserId);return this.logger.info(`${x}, userId: ${this.userId}, peerId: ${t}`,"client"),{userId:t}},[U]:function(e){let t=this.removeRemoteStream(e);t&&t.setUnpublish();const i=W(e,this.useStringUserId);return this.logger.info(`${U}, userId: ${this.userId}, peerId: ${i}`,"client"),{userId:i}},[$]:function(e){return Pt(this,void 0,void 0,(function*(){this.logger.error(`${$}, userId: ${this.userId}`,"client");try{yield this.leave("rejoined")}catch(e){}return(null==e?void 0:e.userId)&&(e.userId=Xe(e.userId)),e}))},[B]:function(e){return Pt(this,void 0,void 0,(function*(){try{yield this.leave("evicted")}catch(e){}return this.logger.error(`${B}, userId: ${this.userId}`,"client"),new C(4009)}))},[V]:function(e){return this.logger.warn(`${V}, userId: ${this.userId}`,"client"),{seconds:e.seconds}},[F]:function(e){return Pt(this,void 0,void 0,(function*(){try{yield this.leave("token_expire")}catch(e){}return this.logger.error(`${F}, userId: ${this.userId}`,"client"),new C(5002)}))},[j]:function(e){return Pt(this,void 0,void 0,(function*(){try{yield this.leave("room_close")}catch(e){}return this.logger.error(`${j}, userId: ${this.userId}`,"client"),new C(5003)}))}},1:{[w]:function(e){let t=new Lt(W(e.stream.getUserId(),this.useStringUserId),this.webrtcType,e.stream,e.stream.getId());return t.setLogger(this.logger),this.addRemoteStream(t),this.logger.info(`${w}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),this.isJoinning?(t._brtcAddEventPadding_=!0,!1):{stream:t}},[R]:function(e){let t=this.removeRemoteStream(e.stream.getUserId(),e.stream.getId());return t||(t=new Lt(W(e.stream.getUserId(),this.useStringUserId),this.webrtcType,e.stream),t.setLogger(this.logger)),t.setUnpublish(),this.logger.info(`${R}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t}},[k]:function(e){let t=this.getRemoteStream(e.stream.getUserId(),e.stream.getId());return!!t&&(t.setStream(this.webrtcType,e.stream),this.logger.info(`${k}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[M]:function(e){let t=this.getRemoteStream(e.stream.getUserId(),e.stream.getId());return t.setStream(this.webrtcType,e.stream),this.logger.info(`${M}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t}},[O]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${O}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[L]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${L}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[P]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${P}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[N]:function(e){let t=this.getRemoteStream(e.userId);return!!t&&(this.logger.info(`${N}, userId: ${this.userId}, streamUserId: ${t.getUserId()}`,"client"),{stream:t})},[D]:function(e){let t=9e3;return/DTLS Transport connection timeout/i.test(e)&&(t=4002),this.reportAction("signalChannelDisconnect",t),this.logger.error(`${D}, userId: ${this.userId}, error: ${at(t)}`,"client"),new C(t,null,e)},[x]:function(e){const t=W(e.userId,this.useStringUserId);return this.logger.info(`${x}, userId: ${this.userId}, peerId: ${t}`,"client"),{userId:t}},[U]:function(e){let t=this.removeRemoteStream(e.userId);t&&t.setUnpublish();const i=W(e.userId,this.useStringUserId);return this.logger.info(`${U}, userId: ${this.userId}, peerId: ${i}`,"client"),{userId:i}},[$]:function(e){return Pt(this,void 0,void 0,(function*(){let t=(e.message||"").indexOf("account admin")>-1?"evicted":"rejoined";try{yield this.leave(t)}catch(e){}return this.logger.error(`${$}, userId: ${this.userId}, reason: ${t}`,"client"),"rejoined"===t?new C(4005):[B,new C(4009)]}))}}};class Ut{constructor(e=0){this.code=65535&e}enableAuth(){return!!(1&this.code)}canPushAudio(){return!!(2&this.code)}canPushVideo(){return!!(4&this.code)}canUseWhiteboard(){return!!(8&this.code)}}const $t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Bt(e){let t,i,r,n,s,o,a,c="",u=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");e.length%4;)e+="=";for(;u<e.length;)n=$t.indexOf(e.charAt(u++)),s=$t.indexOf(e.charAt(u++)),o=$t.indexOf(e.charAt(u++)),a=$t.indexOf(e.charAt(u++)),t=n<<2|s>>4,i=(15&s)<<4|o>>2,r=(3&o)<<6|a,c+=String.fromCharCode(t),64!==o&&(c+=String.fromCharCode(i)),64!==a&&(c+=String.fromCharCode(r));return function(e){let t="",i=0,r=0,n=0,s=0;for(;i<e.length;)r=e.charCodeAt(i),r<128?(t+=String.fromCharCode(r),i++):r>191&&r<224?(n=e.charCodeAt(i+1),t+=String.fromCharCode((31&r)<<6|63&n),i+=2):(n=e.charCodeAt(i+1),s=e.charCodeAt(i+2),t+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&s),i+=3);return t}(c)}const Vt={"120p":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:200},"240p":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1e3},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4680},"4k":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Ft={1:{standard:{sampleRate:48e3,channelCount:1,bitrate:40},high:{sampleRate:48e3,channelCount:1,bitrate:192},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},0:{standard:{sampleRate:48e3,channelCount:1,bitrate:40},high:{sampleRate:48e3,channelCount:1,bitrate:128},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}}},jt={"480p":{width:640,height:480,frameRate:5,bitrate:500},"480p_2":{width:640,height:480,frameRate:30,bitrate:600},"720p":{width:1280,height:720,frameRate:5,bitrate:800},"720p_2":{width:1280,height:720,frameRate:30,bitrate:2e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1200},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:3e3}},Ht={19200:{max:300,min:30},76800:{max:500,min:50},307200:{max:1e3,min:100},921600:{max:3e3,min:300},2073600:{max:5e3,min:500},3686400:{max:8e3,min:1e3},8294400:{max:15e3,min:3e3}},Wt={bitrate:70,height:120,width:160};function Gt(e,t,i,r){if(!o.f(t)||!o.f(i)||0===t||0===i)return e;const n=e.getVideoTracks()[0];if(!n||"function"!=typeof n.getCapabilities)return e;const s=n.getConstraints();return s.frameRate=r||s.frameRate,n.applyConstraints(s),e}const qt=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices):navigator&&navigator.getUserMedia?navigator.getUserMedia.bind(window.navigator):null;const Jt=navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia?navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices):navigator&&navigator.getDisplayMedia?navigator.getDisplayMedia.bind(window.navigator):null;function zt(e){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(!Jt)throw new Error("not support");const t={video:{frameRate:e.fps},audio:!!e.audio,selfBrowserSurface:"include"},i=yield Jt(t);return o.c(e.video)?i:o.h(e.video)?Gt(i,e.video.width,e.video.height,e.fps):i}))}const Yt=[["iphone",/iphone os ([\d_.]+)/],["ipad",/ipad; cpu os ([\d_.]+)/],["itouch",/itouch; cpu os ([\d_.]+)/],["android",/android ([\d_.]+)/],["wp",/windows phone ([\d_.]+)/],["windows",/windows nt ([\d_.]+)/],["linux",/linux/],["mac",/mac os x ([\d_.]+)/]],Qt=function(e){let t,i;return ge(Yt,(r=>{let n=r[1].exec(e);if(n)return t=r[0],i=n[1],i&&(i=i.replace(/_/g,".")),!1})),{name:t||"",version:i||""}}((navigator.userAgent||"").toLowerCase());Qt.name&&(Qt[Qt.name]=!0,{iphone:1,ipad:1,itouch:1}[Qt.name]&&(Qt.ios=!0));var Kt=Qt;function Xt(){if(Kt.android||Kt.ios)return!1;if(ot.chrome){if(ot.checkVersion(ot.majorVersion,"72",!0))return!0;if(ot.checkVersion(ot.majorVersion,"55"))return!1}else{if(ot.safari&&ot.checkVersion(ot.majorVersion,"13",!0))return!0;if(ot.firefox&&ot.checkVersion(ot.majorVersion,"60",!0))return!0;if(ot.edge&&ot.checkVersion(ot.majorVersion,"11"))return!0;if(ot.newEdge)return!0}return Object(o.d)(Jt)}function Zt(e){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(e.screen){if(ot.chrome){if(ot.checkVersion(ot.majorVersion,"72",!0))return yield zt(e);if(ot.checkVersion(ot.majorVersion,"55"))return yield function(e){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){throw new Error("not support")}))}()}else{if(ot.firefox&&ot.checkVersion(ot.majorVersion,"60",!0))return yield function(e){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(!qt)throw new Error("not support");const t={video:{mediaSource:"window",width:null,height:null,frameRate:null},audio:!!e.audio};o.i(e.mediaSource)&&(t.video.mediaSource=e.mediaSource),!o.c(e.video)&&o.f(e.video.width)&&e.video.width>0&&(t.video.width={min:e.video.width,max:e.video.width}),!o.c(e.video)&&o.f(e.video.height)&&e.video.height>0&&(t.video.height={min:e.video.height,max:e.video.height}),o.f(e.fps)&&e.fps>0&&(t.video.frameRate={min:e.fps,max:e.fps});const i=yield qt(t);return o.c(e.video)?i:Gt(i,e.video.width,e.video.height,e.fps)}))}(e);if(ot.edge&&ot.checkVersion(ot.majorVersion,"11")||ot.newEdge||ot.safari&&ot.checkVersion(ot.majorVersion,"13",!0)||Xt())return yield zt(e)}throw new Error("not support")}return yield function(e){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(!qt)throw new Error("not support");!o.c(e.video)&&o.i(e.video.deviceId)&&(e.video.deviceId={exact:e.video.deviceId}),!o.c(e.audio)&&o.i(e.audio.deviceId)&&(e.audio.deviceId={exact:e.audio.deviceId});const t=yield qt(e);return o.c(e.video)?t:o.h(e.video)?Gt(t,e.video.width,e.video.height,e.fps):t}))}(e)}))}function ei(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))}class ti{constructor(e={}){this.TRACE=he.TRACE,this.DEBUG=he.DEBUG,this.INFO=he.INFO,this.WARN=he.WARN,this.ERROR=he.ERROR,this.FATAL=he.FATAL,this.options=Me({uploadLevel:he.getUploadLevel()},e),this.canUpload=!0}enableUploadLog(){this.canUpload=!0}disableUploadLog(){this.canUpload=!1}setUploadLevel(e){this.options.uploadLevel=e}fatal(e,t,i=!1){(he.FATAL>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.FATAL,t),he.fatal(e,t)}error(e,t,i=!1){he.error(e,t),(he.ERROR>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.ERROR,t)}warn(e,t,i=!1){he.warn(e,t),(he.WARN>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.WARN,t)}info(e,t,i=!1){he.info(e,t),(he.INFO>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.INFO,t)}call(e,t,i=!1){he.call(e,t),(he.INFO>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.INFO,t)}debug(e,t,i=!1,r=!1){he.debug(e,t),r||(he.DEBUG>=this.options.uploadLevel||i)&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.DEBUG,t)}trace(e,t,i=!1){he.trace(e,t),he.TRACE>=this.options.uploadLevel&&i&&this.canUpload&&this.options.onUpload&&he.canUploadLog()&&this.options.onUpload(e,he.TRACE,t)}log(e,t,i,r=!1){switch(t){case he.TRACE:this.trace(e,i,r);break;case he.DEBUG:this.debug(e,i,r);break;case he.INFO:this.info(e,i,r);break;case he.WARN:this.warn(e,i,r);break;case he.ERROR:this.error(e,i,r);break;case he.FATAL:this.fatal(e,i,r);break;default:this.debug(e,i,r)}}}const ii="notify";const ri={maxRetry:0,requestTimeout:5e3,responseTimeout:5e3,duplicatesTimeout:5e3};function ni(...e){let t="";for(let i=0;i<e.length;i++)e[i]&&(t+=e[i]);return t}class si extends Ne{constructor(e,t,i={},r){super(!1),this.packer=e,this.options=Me({},ri,i),this.requestID=0,this.notifyId=0,this.reqMap=new Map,this.resMap=new Map,this.reqKeyMap=new Map,this.logger=r||new ti,this.onmessageHandler=e=>{this.onmessage(e)},t&&this.handlTransport(t)}handlTransport(e){this.transport&&(Object(o.d)(this.transport.removeListener)?this.transport.removeListener(this.onmessageHandler):Object(o.d)(this.transport.removeEventListener)?this.transport.removeEventListener(this.onmessageHandler):Object(o.d)(this.transport.onmessage)&&(this.transport.onmessage=null)),e&&(Object(o.d)(e.addListener)?e.addListener("onmessage",this.onmessageHandler):Object(o.d)(e.addEventListener)?e.addEventListener("onmessage",this.onmessageHandler):e.onmessage=this.onmessageHandler,this.transport=e)}send(e){Object(o.d)(this.transport.send)?this.transport.send(e):Object(o.d)(this.transport.write)?this.transport.write(e):Object(o.d)(this.transport.postMessage)&&this.transport.postMessage(e)}request(e,t={},i={}){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(!this.transport)throw new Error(`request ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);return new Promise(((r,n)=>{var s,o;if(i.key&&this.reqKeyMap.has(i.key)){const r=this.reqKeyMap.get(i.key);clearTimeout(r.timer),this.logger.warn(`request ${e}, params: ${JSON.stringify(t)} canceled because there is call new request whoes key is same as before`),r.reject(new Error("request canceled because there is call new request which key is same as before")),this.reqMap.delete(ni(r.id)),this.reqKeyMap.delete(i.key)}const a=this.requestID++;i.dest&&(t.dest=i.dest),this.options.peerId&&(t.from=this.options.peerId);const c={resolve:r,reject:n,id:a,dest:i.dest,timer:null,retryCount:0,maxRetry:null!==(s=i.maxRetry)&&void 0!==s?s:this.options.maxRetry,errorRetry:null!==(o=i.errorRetry)&&void 0!==o&&o,method:e,params:t,message:this.packer.pack({method:e,params:t},a),timestamp:z(),key:i.key,timeout:i.timeout,timeoutFn:()=>{c.retryCount>=c.maxRetry?(this.reqMap.delete(ni(c.id)),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key),this.logger.error(`request ${e}, params: ${JSON.stringify(t)} timeout`),n(new Error("request timeout"))):(c.retryCount++,c.timer=setTimeout(c.timeoutFn,i.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${e}, params: ${JSON.stringify(t)}, count: ${c.retryCount}`),this.send(c.message))},needRetry:i.needRetry};c.timer=setTimeout(c.timeoutFn,i.timeout||this.options.requestTimeout*(c.retryCount+1)),this.reqMap.set(ni(c.id),c),c.key&&this.reqKeyMap.set(c.key,c),this.send(c.message)}))}))}reply(e,t,i){var r;this.options.peerId&&(t&&(t.from=this.options.peerId),i&&(i.from=this.options.peerId));const n=this.packer.pack({result:t,error:i},e.id),s={id:e.id,message:n,timer:null},o=ni(e.id,null===(r=e.params)||void 0===r?void 0:r.from);this.options.responseTimeout&&(s.timer=setTimeout((()=>{this.resMap.delete(o)}),this.options.responseTimeout),this.resMap.set(o,s)),this.send(s.message)}notify(e,t={},i){if(!this.transport)throw new Error(`notify ${e}, params: ${JSON.stringify(t)} failed, transport has closed or not set`);const r=this.notifyId++;i&&(t.dest=i),this.options.peerId&&(t.from=this.options.peerId),this.send(this.packer.pack({method:e,params:t,seq:r}))}onmessage(e){var t;if(this.transport)if(we(e))if(Object(o.i)(e)){let i;try{i=this.packer.unpack(e)}catch(t){return void this.logger.error(`unpack message error, message: ${e}, error: ${at(t)}`,"RpcBuilder")}const r=i.id,n=i.method,s=null!==(t=i.params)&&void 0!==t?t:{},o=s.dest;if(s.dest,we(this.options.peerId)&&this.options.peerId===o)return void this.logger.warn("ignored the message which send from me, message: "+e);if(we(r))if(n){const t=this.resMap.get(ni(r,o));t?(this.logger.warn(`request: ${e} has replyed in ${this.options.responseTimeout}ms, send same again`),this.send(t.message)):this.fire("request",[i])}else{const t=i.error,o=i.result;if((null==t?void 0:t.dest)!==this.options.peerId||(null==o?void 0:o.dest)!==this.options.peerId)return void this.logger.warn("ignored the message which not sent for me, message: "+e);const a=ni(r),c=this.reqMap.get(a);if(c){if(clearTimeout(c.timer),t){if(this.logger.error(`[request error] request: ${c.message}, response: ${e}, consume: ${z()-c.timestamp}`),c.errorRetry&&c.retryCount<c.maxRetry&&(!c.needRetry||c.needRetry(t)))return c.retryCount++,c.timer=setTimeout(c.timeoutFn,c.timeout||this.options.requestTimeout),this.logger.warn(`retry request ${c.method}, params: ${JSON.stringify(c.params)}, count: ${c.retryCount}`),c.id=this.requestID++,c.message=this.packer.pack({method:n,params:s},c.id),void this.send(c.message);c.reject(t)}else this.logger.debug(`[request success] method: ${c.method}, id: ${c.id}, consume: ${z()-c.timestamp}`),c.resolve(o);this.reqMap.delete(a),c.key&&this.reqKeyMap.has(c.key)&&this.reqKeyMap.delete(c.key)}else this.logger.warn("no request for the response: "+e)}else this.fire(ii,[n,s,i.seq])}else this.fire("binary",[e]);else this.logger.warn("message is not defined","RpcBuilder")}destroy(){this.off(),this.handlTransport(),this.reqMap&&(this.reqMap.forEach((e=>{clearTimeout(e.timer),e.reject("transport closed")})),this.reqMap.clear(),this.reqMap=null),this.reqKeyMap&&(this.reqKeyMap.clear(),this.reqKeyMap=null),this.resMap&&(this.resMap.forEach((e=>{clearTimeout(e.timer)})),this.resMap.clear(),this.resMap=null),this.packer=null,this.transport=null}getPacker(){return this.packer}getTransport(){return this.transport}setTransport(e){this.handlTransport(e)}resetRequest(){this.reqMap&&this.reqMap.forEach((e=>{clearTimeout(e.timer),e.timer=setTimeout(e.timeoutFn,e.timeout||this.options.requestTimeout*(e.retryCount+1)),this.send(e.message)}))}}class oi extends class{constructor(){}}{constructor(){super()}pack(e,t){const i={jsonrpc:"2.0"};if(e.method)i.method=e.method,e.params&&(i.params=e.params),we(t)&&(i.id=t),e.seq&&(i.seq=e.seq);else if(we(t)){if(e.error){if(e.result)throw new TypeError("Both result and error are defined");i.error=e.error}else{if(!e.result)throw new TypeError("No result or error is defined");i.result=e.result}i.id=t}return JSON.stringify(i)}unpack(e){const t=JSON.parse(e);if("2.0"!==t.jsonrpc)throw new TypeError(`Invalid JsonRPC version ${t.jsonrpc}: ${e}`);if(!we(t.method)){if(!we(t.id))throw new TypeError("Invalid message: "+e);const i=we(t.error),r=we(t.result);if(r&&i)throw new TypeError("Both result and error are defined: "+e);if(!r&&!i)throw new TypeError("No result or error is defined: "+e)}return t}}const ai={videoAdaption:"stream-video-adaption"},ci=new Map;function ui(e){return e&&o.i(e)}function di(e){o.a(e)?ge(e,(e=>{ui(e)&&ci.set(e,z())})):ui(e)&&ci.set(e,z()),function(){const e=ci.keys();for(let t of e)z()-ci.get(t)>=6e5&&ci.delete(t)}()}function li(e){return ci.has(e)&&z()-ci.get(e)<6e5}function hi(){ci.clear()}function mi(){const e=ci.keys(),t=[];for(let i of e)z()-ci.get(i)<6e5?t.push(i):ci.delete(i);return t}function pi(e){ci.delete(e)}var fi;class vi extends Ne{constructor(e,t){var i,r,n,s,o,a;super(!0),this.type=e.type,this.client=e.client,this.userId=e.userId,this.streamId=null!==(i=e.streamId)&&void 0!==i?i:ei(),this.videoOn=null!==(r=e.videoOn)&&void 0!==r&&r,this.audioOn=null!==(n=e.audioOn)&&void 0!==n&&n,this.videoEnable=null!==(s=e.videoEnable)&&void 0!==s&&s,this.audioEnable=null!==(o=e.audioEnable)&&void 0!==o&&o,this.msmsIPs=[],this.audioLevelInterval=null!==(a=e.audioLevelInterval)&&void 0!==a?a:1e3,this.iceconnectionstatechangeTimer=null,this.dtlsconnectionstatechangeTimer=null,this.dtlsConnectionTimeout=null,this.destroyed=!1,this.isMsSupportDatachannel=!0,null==this.type&&(/^screen-/.test(this.streamId)?this.type=At.SCREEN:this.type=At.CAMERA),this.logger=t||new ti,this.packer=new oi}getUserId(){return this.userId}getStreamId(){return this.streamId}hasVideo(){return this.videoOn}hasAudio(){return this.audioOn}getVideoEnable(){return this.videoEnable}getAudioEnable(){return this.audioEnable}getMsmsIP(){return this.msmsIPs.join("")||""}update(e){let t=!1;return this.audioOn&&e.audio_enable&&!this.audioEnable&&this.collector&&this.collector.restartAudioLevelTimer(),o.c(e.videoOn)&&this.videoOn!==e.videoOn&&(this.videoOn=e.videoOn,t=!0),o.c(e.audioOn)&&this.audioOn!==e.audioOn&&(this.audioOn=e.audioOn,t=!0),o.c(e.video_enable)&&this.videoEnable!==e.video_enable&&(this.videoEnable=e.video_enable,t=!0),o.c(e.audio_enable)&&this.audioEnable!==e.audio_enable&&(this.audioEnable=e.audio_enable,t=!0),t&&this.fire("stream-update"),t}getVideoTrack(){const e=this.getStream();if(e)return e.getVideoTracks()[0]}getAudioTrack(){const e=this.getStream();if(e)return e.getAudioTracks()[0]}getValueFromStats(e,t){if(this.stats)for(let i of this.stats.rtps)if(i.ssrc===e)return Le(i,t)}getStats(){var e;if(this.collector){const t=this.collector.getStats();for(let i of t.rtps)"video"===i.kind&&(!this.stats&&"none"!==i.qualityLimitationReason||this.stats&&(null===(e=this.stats.rtps)||void 0===e?void 0:e.length)&&i.qualityLimitationReason!==this.getValueFromStats(i.ssrc,"qualityLimitationReason"))&&this.fire("video-adaptation-changed",[{rid:i.rid,reason:i.qualityLimitationReason}]);this.stats=t}return this.stats}startCollecting(){this.collector&&this.collector.start()}stopCollecting(){this.collector&&this.collector.stop()}getAudioLevel(){var e;return this.collector&&null!==(e=this.collector.getAudioLevel())&&void 0!==e?e:0}updateAudioLevelInterval(e){this.audioLevelInterval=e,this.collector&&this.collector.updateAudioLevelInterval(e)}handlerEvent(){if(this.iceconnectionstatechangeTimer&&(clearTimeout(this.iceconnectionstatechangeTimer),this.iceconnectionstatechangeTimer=null),this.dtlsconnectionstatechangeTimer&&(clearTimeout(this.dtlsconnectionstatechangeTimer),this.dtlsconnectionstatechangeTimer=null),this.peer.oniceconnectionstatechange=e=>{this.iceconnectionstatechangeTimer&&(clearTimeout(this.iceconnectionstatechangeTimer),this.iceconnectionstatechangeTimer=null),"disconnected"===e?(this.iceconnectionstatechangeTimer=setTimeout((()=>{this.logger.error(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice disconnected`),this.fire("stream-connection-error"),this.iceconnectionstatechangeTimer=null}),5e3),this.fire("stream-reconnecting")):"failed"===e?(this.logger.error(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice failed`),this.fire("stream-connection-error")):"connected"===e?(this.logger.info(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice connected`),this.fire("stream-connection-success")):this.logger.info(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} ice ${e}`)},this.peer.ondtlsstatechange=e=>{"closed"===e||"failed"===e?this.dtlsconnectionstatechangeTimer=setTimeout((()=>{this.logger.error(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} dtls ${e}`),this.fire("stream-connection-error")}),5e3):(this.logger.info(`userId: ${this.getUserId()}, streamId: ${this.getStreamId()} dtls ${e}`),"connected"===e&&(this.dtlsConnectionTimeout&&(clearTimeout(this.dtlsConnectionTimeout),this.dtlsConnectionTimeout=null),"udp"===this.getSelectedMsmsIPProtocol()&&pi(this.getSelectedMsmsIP())))},this.peer.onicecandidate=e=>{this.client&&this.client.syncIcecandidate(this,e)},this.isMsSupportDatachannel){this.rpc&&this.rpc.destroy();const e={send:e=>{this.peer.send(e)},onmessage:null};this.peer.onmessage=t=>{e.onmessage&&e.onmessage(t.data)},this.rpc=new si(this.packer,e,{},this.logger),this.rpc.on("binary",(e=>{this.fire("binary",[e])})),this.rpc.on(ii,((e,t,i)=>{ai[e]?("videoAdaption"===e&&(t.video_enable=!t.video_enable),this.fire(ai[e],[t])):this.fire(ii,[{method:e,params:t}])})),this.rpc.on("request",(e=>{this.fire("request",[e])}))}}requestKeyFrame(){this.hasVideo()&&this.getVideoEnable()&&this.request("requestKeyFrame")}request(e,t={}){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(this.rpc)return this.rpc.request(e,t);this.logger.error(`no rpc channel to request, method: ${e}, params: ${JSON.stringify(t)}`)}))}reply(e,t,i){if(this.rpc)return this.rpc.reply(e,t,i);this.logger.error(`no rpc channel to reply, request: ${JSON.stringify(e)}, result: ${JSON.stringify(t)}, error: ${JSON.stringify(i)}`)}notify(e,t={}){if(this.rpc)return this.rpc.notify(e,t);this.logger.error(`no rpc channel to notify, method: ${e}, params: ${JSON.stringify(t)}`)}close(){this.rpc&&this.rpc.destroy(),this.peer&&(this.peer.destroy(),this.peer=null),this.collector&&(this.stopCollecting(),this.collector.destroy(),this.collector=null),this.iceconnectionstatechangeTimer&&(clearTimeout(this.iceconnectionstatechangeTimer),this.iceconnectionstatechangeTimer=null),this.dtlsconnectionstatechangeTimer&&(clearTimeout(this.dtlsconnectionstatechangeTimer),this.dtlsconnectionstatechangeTimer=null),this.dtlsConnectionTimeout&&(clearTimeout(this.dtlsConnectionTimeout),this.dtlsConnectionTimeout=null)}setLogger(e){this.logger=e}getType(){return this.type}isConnecting(){return!!this.peer}isDestroyed(){return this.destroyed}setAudioEncodeDataPipe(e){this.onAudioEncodeDataPipe=e,this.encodedDataProcesser&&this.encodedDataProcesser.setAudioEncodeDataPipe(e)}setVideoEncodeDataPipe(e){this.onVideoEncodeDataPipe=e,this.encodedDataProcesser&&this.encodedDataProcesser.setVideoEncodeDataPipe(e)}hasEncodedDataProcesser(e={}){return(e.enableSEI&&"h264"===this.options.vcodec.toLocaleLowerCase()||this.onVideoEncodeDataPipe||this.onAudioEncodeDataPipe)&&(null===RTCRtpSender||void 0===RTCRtpSender?void 0:RTCRtpSender.prototype.createEncodedStreams)}getSelectedMsmsIP(){return this.peer?this.peer.getRemoteIP()||this.collector.getRemoteIP()||this.msmsIPs[0]:""}getSelectedMsmsIPProtocol(){return this.peer&&(this.peer.getPairProtocol()||this.collector.getCurrentPairProtocol())||"udp"}isConnected(){var e;return null===(e=this.peer)||void 0===e?void 0:e.isConnected()}startDtlsConnectionTimeout(){ot.firefox||(this.dtlsConnectionTimeout&&clearTimeout(this.dtlsConnectionTimeout),this.dtlsConnectionTimeout=setTimeout((()=>{this.peer&&"connected"===this.peer.iceConnectionState&&"connected"!==this.peer.dtlsConnectionState&&"udp"===this.getSelectedMsmsIPProtocol()&&(di(this.getSelectedMsmsIP()),this.fire("stream-connection-error"))}),8e3))}}!function(e){e[e.RECEIVE_BANDWIDTH=0]="RECEIVE_BANDWIDTH",e[e.SEND_BANDWIDTH=1]="SEND_BANDWIDTH",e[e.REMOTE_ADDRESS=2]="REMOTE_ADDRESS",e[e.TRANSPORT_TYPE=3]="TRANSPORT_TYPE",e[e.LOCAL_ADDRESS=4]="LOCAL_ADDRESS",e[e.ACTIVE_CONNECTION=5]="ACTIVE_CONNECTION",e[e.SSRC=6]="SSRC",e[e.PACKETS_RECEIVED=7]="PACKETS_RECEIVED",e[e.PACKETS_SENT=8]="PACKETS_SENT",e[e.PACKETS_LOST=9]="PACKETS_LOST",e[e.BYTES_RECEIVED=10]="BYTES_RECEIVED",e[e.BYTES_SENT=11]="BYTES_SENT",e[e.FRAME_HEIGHT_RECEIVED=12]="FRAME_HEIGHT_RECEIVED",e[e.FRAME_WIDTH_RECEIVED=13]="FRAME_WIDTH_RECEIVED",e[e.FRAME_HEIGHT_SENT=14]="FRAME_HEIGHT_SENT",e[e.FRAME_WIDTH_SENT=15]="FRAME_WIDTH_SENT",e[e.FRAME_RATE_RECEIVED=16]="FRAME_RATE_RECEIVED",e[e.FRAME_RATE_SENT=17]="FRAME_RATE_SENT",e[e.AUDIO_INPUT_LEVEL=18]="AUDIO_INPUT_LEVEL",e[e.AUDIO_OUTPUT_LEVEL=19]="AUDIO_OUTPUT_LEVEL",e[e.AUDIO_LEVEL=20]="AUDIO_LEVEL",e[e.CURRENT_ROUND_TRIP_TIME=21]="CURRENT_ROUND_TRIP_TIME",e[e.REMOTE_CANDIDATE_TYPE=22]="REMOTE_CANDIDATE_TYPE",e[e.LOCAL_CANDIDATE_TYPE=23]="LOCAL_CANDIDATE_TYPE",e[e.IP=24]="IP",e[e.PORT=25]="PORT",e[e.PROTOCOL=26]="PROTOCOL",e[e.JITTER_BUFFER_DELAY=27]="JITTER_BUFFER_DELAY",e[e.JITTER_BUFFER_EMITTED_COUNT=28]="JITTER_BUFFER_EMITTED_COUNT",e[e.MEDIA_TYPE=29]="MEDIA_TYPE",e[e.JITTER_BUFFER_MS=30]="JITTER_BUFFER_MS",e[e.INTER_FRAME_DELAY_MAX=31]="INTER_FRAME_DELAY_MAX",e[e.CURRENT_DELAY_MS=32]="CURRENT_DELAY_MS",e[e.AVAILABLE_RECEIVE_BANDWIDTH=33]="AVAILABLE_RECEIVE_BANDWIDTH",e[e.AVAILABLE_SEND_BANDWIDTH=34]="AVAILABLE_SEND_BANDWIDTH",e[e.RETRANSMIT_BITRATE=35]="RETRANSMIT_BITRATE",e[e.TRANSMIT_BITRATE=36]="TRANSMIT_BITRATE",e[e.TARGET_ENC_BITRATE=37]="TARGET_ENC_BITRATE",e[e.FRAME_RATE_INPUT=38]="FRAME_RATE_INPUT",e[e.ENCODE_USAGE_PERCENT=39]="ENCODE_USAGE_PERCENT",e[e.RENDER_DELAY_MS=40]="RENDER_DELAY_MS",e[e.TARGET_DELAY_MS=41]="TARGET_DELAY_MS",e[e.FRAME_RATE_OUTPUT=42]="FRAME_RATE_OUTPUT",e[e.RID=43]="RID",e[e.FRAMERATE_MEAN=44]="FRAMERATE_MEAN",e[e.AVAILABLE_INCOMING_BITRATE=45]="AVAILABLE_INCOMING_BITRATE",e[e.AVAILABLE_OUTGOING_BITRATE=46]="AVAILABLE_OUTGOING_BITRATE",e[e.ROUND_TRIP_TIME=47]="ROUND_TRIP_TIME",e[e.JITTER=48]="JITTER",e[e.PLI_COUNT=49]="PLI_COUNT",e[e.FIR_COUNT=50]="FIR_COUNT",e[e.NACK_COUNT=51]="NACK_COUNT",e[e.TIMESTAMP=52]="TIMESTAMP",e[e.FRAME_DECODED=53]="FRAME_DECODED",e[e.FRAME_ENCODED=54]="FRAME_ENCODED",e[e.FRAME_PER_SECOND=55]="FRAME_PER_SECOND",e[e.FRAME_SENT=56]="FRAME_SENT",e[e.FRAME_RECEIVED=57]="FRAME_RECEIVED",e[e.FRAME_WIDTH=58]="FRAME_WIDTH",e[e.FRAME_HEIGHT=59]="FRAME_HEIGHT",e[e.HUGE_FRAMES_SENT=60]="HUGE_FRAMES_SENT",e[e.ACCELERATE_RATE=61]="ACCELERATE_RATE",e[e.DECODING_PLC=62]="DECODING_PLC",e[e.DECODING_PLCCNG=63]="DECODING_PLCCNG",e[e.CONCEALED_SAMPLES=64]="CONCEALED_SAMPLES",e[e.TOTAL_SAMPLES_RECEIVED=65]="TOTAL_SAMPLES_RECEIVED",e[e.CONCEALMENT_EVENTS=66]="CONCEALMENT_EVENTS",e[e.TOTAL_AUDIO_ENERGY=67]="TOTAL_AUDIO_ENERGY",e[e.TOTAL_SAMPLES_DURATION=68]="TOTAL_SAMPLES_DURATION",e[e.SILENT_CONCEALED_SAMPLES=69]="SILENT_CONCEALED_SAMPLES",e[e.INSERTED_SAMPLES_FOR_DECELERATION=70]="INSERTED_SAMPLES_FOR_DECELERATION",e[e.REMOVED_SAMPLES_FOR_ACCELERATION=71]="REMOVED_SAMPLES_FOR_ACCELERATION",e[e.QUALITY_LIMITATION_REASON=72]="QUALITY_LIMITATION_REASON",e[e.QUALITY_LIMITATION_DURATIONS=73]="QUALITY_LIMITATION_DURATIONS",e[e.REQUESTS_SENT=74]="REQUESTS_SENT",e[e.RESPONSES_RECEIVED=75]="RESPONSES_RECEIVED"}(fi||(fi={}));const gi={[fi.RECEIVE_BANDWIDTH]:"googAvailableReceiveBandwidth",[fi.SEND_BANDWIDTH]:"googAvailableSendBandwidth",[fi.REMOTE_ADDRESS]:"googRemoteAddress",[fi.TRANSPORT_TYPE]:"googTransportType",[fi.LOCAL_ADDRESS]:"googLocalAddress",[fi.ACTIVE_CONNECTION]:"googActiveConnection",[fi.SSRC]:"ssrc",[fi.PACKETS_RECEIVED]:"packetsReceived",[fi.PACKETS_SENT]:"packetsSent",[fi.PACKETS_LOST]:"packetsLost",[fi.BYTES_RECEIVED]:"bytesReceived",[fi.BYTES_SENT]:"bytesSent",[fi.FRAME_HEIGHT_RECEIVED]:"googFrameHeightReceived",[fi.FRAME_WIDTH_RECEIVED]:"googFrameWidthReceived",[fi.FRAME_HEIGHT_SENT]:"googFrameHeightSent",[fi.FRAME_WIDTH_SENT]:"googFrameWidthSent",[fi.FRAME_RATE_RECEIVED]:"googFrameRateReceived",[fi.FRAME_RATE_SENT]:"googFrameRateSent",[fi.AUDIO_INPUT_LEVEL]:"audioInputLevel",[fi.AUDIO_OUTPUT_LEVEL]:"audioOutputLevel",[fi.AUDIO_LEVEL]:"audioLevel",[fi.CURRENT_ROUND_TRIP_TIME]:"currentRoundTripTime",[fi.REMOTE_CANDIDATE_TYPE]:"googRemoteCandidateType",[fi.LOCAL_CANDIDATE_TYPE]:"googLocalCandidateType",[fi.IP]:["address","ip"],[fi.PORT]:"port",[fi.PROTOCOL]:"protocol",[fi.JITTER_BUFFER_DELAY]:"jitterBufferDelay",[fi.JITTER_BUFFER_EMITTED_COUNT]:"jitterBufferEmittedCount",[fi.MEDIA_TYPE]:"mediaType",[fi.JITTER_BUFFER_MS]:"googJitterBufferMs",[fi.INTER_FRAME_DELAY_MAX]:"googInterframeDelayMax",[fi.CURRENT_DELAY_MS]:"googCurrentDelayMs",[fi.AVAILABLE_RECEIVE_BANDWIDTH]:"googAvailableReceiveBandwidth",[fi.AVAILABLE_SEND_BANDWIDTH]:"googAvailableSendBandwidth",[fi.RETRANSMIT_BITRATE]:"googRetransmitBitrate",[fi.TRANSMIT_BITRATE]:"googTransmitBitrate",[fi.TARGET_ENC_BITRATE]:"googTargetEncBitrate",[fi.FRAME_RATE_INPUT]:"googFrameRateInput",[fi.ENCODE_USAGE_PERCENT]:"googEncodeUsagePercent",[fi.RENDER_DELAY_MS]:"googRenderDelayMs",[fi.TARGET_DELAY_MS]:"googTargetDelayMs",[fi.FRAME_RATE_OUTPUT]:"googFrameRateOutput",[fi.RID]:"rid",[fi.AVAILABLE_INCOMING_BITRATE]:"availableIncomingBitrate",[fi.AVAILABLE_OUTGOING_BITRATE]:"availableOutgoingBitrate",[fi.ROUND_TRIP_TIME]:"roundTripTime",[fi.JITTER]:"jitter",[fi.PLI_COUNT]:"pliCount",[fi.FIR_COUNT]:"firCount",[fi.NACK_COUNT]:["nackCount","googNacksReceived"],[fi.TIMESTAMP]:"timestamp",[fi.FRAME_DECODED]:"framesDecoded",[fi.FRAME_ENCODED]:"framesEncoded",[fi.FRAME_PER_SECOND]:"framesPerSecond",[fi.FRAME_SENT]:"framesSent",[fi.FRAME_RECEIVED]:"framesReceived",[fi.FRAME_WIDTH]:"frameWidth",[fi.FRAME_HEIGHT]:"frameHeight",[fi.FRAMERATE_MEAN]:"framerateMean",[fi.HUGE_FRAMES_SENT]:"hugeFramesSent",[fi.ACCELERATE_RATE]:"googAccelerateRate",[fi.DECODING_PLC]:"googDecodingPLC",[fi.DECODING_PLCCNG]:"googDecodingPLCCNG",[fi.CONCEALED_SAMPLES]:"concealedSamples",[fi.TOTAL_SAMPLES_RECEIVED]:"totalSamplesReceived",[fi.CONCEALMENT_EVENTS]:"concealmentEvents",[fi.TOTAL_AUDIO_ENERGY]:"totalAudioEnergy",[fi.TOTAL_SAMPLES_DURATION]:"totalSamplesDuration",[fi.SILENT_CONCEALED_SAMPLES]:"silentConcealedSamples",[fi.INSERTED_SAMPLES_FOR_DECELERATION]:"insertedSamplesForDeceleration",[fi.REMOVED_SAMPLES_FOR_ACCELERATION]:"removedSamplesForAcceleration",[fi.QUALITY_LIMITATION_REASON]:"qualityLimitationReason",[fi.QUALITY_LIMITATION_DURATIONS]:"qualityLimitationDurations",[fi.REQUESTS_SENT]:"requestsSent",[fi.RESPONSES_RECEIVED]:"responsesReceived"},_i=Me(gi,{[fi.IP]:"address"}),yi=Me(gi,{[fi.IP]:"address"}),Si=Me(gi,{[fi.IP]:"address"}),Ei=Me(gi,{[fi.IP]:"address"});var bi={[et.FIREFOX]:_i,[et.CHROME]:gi,[et.SAFARI]:yi,[et.OPERA]:Si,[et.WECHAT]:Ei};const Ti=bi[ot.name]||bi[et.CHROME];function Ii(e,t){return o.d(e.stat)?e.stat(t):e[t]}function Ci(e,t){if(e){const i=function(e){const t=Ti[e];if(t)return t;he.warn(`The property '${e}' isn't supported!`)}(t);if(i){if(o.a(i)){for(let t=0;t<i.length;t++){const r=Ii(e,i[t]);if(r)return r}return}return Ii(e,i)}}return 0}function wi(e,t){let i=Ci(e,t);return o.f(i)||(i=Number(i)),isNaN(i)?0:Math.max(0,i)}function Ri(e,t,i,r=1e3){let n=wi(e,i),s=wi(t,i),o=Math.max(0,n-s),a=wi(e,fi.TIMESTAMP),c=wi(t,fi.TIMESTAMP);const u=Math.max(r,a-c)||r;return Math.round(8*o/u)}class ki{constructor(e,t,i){this.id=e,this.kind=t,this.interval=i,this.stats={type:"",loss:{packetsTotal:0,packetsLost:0,packetsTotalLost:0},bitrate:{download:0,upload:0},resolution:{width:0,height:0},framerate:0,jitter:0,interruptionCount:0,interruptionDuration:0,bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,framesEncoded:0,framesSent:0,framesDecoded:0,interframeDelayMax:0,currentDelayMs:0,rtt:0,sentPacketRate:0,recvPacketRate:0,pliCount:0,firCount:0,nacksCount:0,frameRateInput:0,encodeUsagePercent:0,targetDelayMs:0,renderDelayMs:0,frameRateOutput:0,frameRateDecoded:0,frameRateEncoded:0,jitterReceived:0,rid:"",accelerateRate:0,decodingPLC:0,decodingPLCCNG:0,hugeFramesSent:0,concealedSamples:0,totalSamplesReceived:0,concealmentEvents:0,totalAudioEnergy:0,totalSamplesDuration:0,silentConcealedSamples:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0,qualityLimitationReason:"none",qualityLimitationDurations:{bandwidth:0,cpu:0,other:0,none:0}},this.supportExtra=!1,this.uploadPacketLostScale=1}getKind(){return this.kind}getId(){return this.id}processOutboundRTP(e,t){const i=Ci(e,fi.RID);i&&(this.stats.rid=i);const r=wi(e,fi.PACKETS_SENT);this.stats.packetsSent=r,this.stats.packetsReceived=0;const n=wi(t,fi.PACKETS_SENT),s=Math.max(0,r-n);if(!this.supportExtra){const i=wi(e,fi.PACKETS_LOST),r=wi(t,fi.PACKETS_LOST),n=Math.max(0,i-r),o=wi(e,fi.NACK_COUNT),a=wi(t,fi.NACK_COUNT),c=Math.max(0,o-a);this.stats.loss={packetsTotal:Math.max(s-c,n,1),packetsLost:n,packetsTotalLost:i}}if(this.stats.sentPacketRate=s/this.interval*1e3,this.stats.pliCount=wi(e,fi.PLI_COUNT),this.stats.firCount=wi(e,fi.FIR_COUNT),this.stats.nacksCount=wi(e,fi.NACK_COUNT),this.stats.bytesSent=wi(e,fi.BYTES_SENT),this.stats.bytesReceived=0,this.stats.bitrate={download:0,upload:Ri(e,t,fi.BYTES_SENT,this.interval)},"video"===this.kind){const i=wi(e,fi.FRAME_ENCODED),r=wi(t,fi.FRAME_ENCODED);this.stats.framesEncoded=i;const n=wi(e,fi.FRAME_SENT);n&&(this.stats.framesSent=n),this.stats.frameRateEncoded=Math.round(Math.max(i-r,0)/this.interval*1e3),this.stats.hugeFramesSent=wi(e,fi.HUGE_FRAMES_SENT);const s={height:wi(e,fi.FRAME_HEIGHT),width:wi(e,fi.FRAME_WIDTH)};s.width&&s.height&&(this.stats.resolution=s);const o=wi(e,fi.FRAMERATE_MEAN);if(o)this.stats.framerate=Math.round(o);else{let i=wi(e,fi.FRAME_PER_SECOND);if(!i){let r=wi(e,fi.TIMESTAMP)-wi(t,fi.TIMESTAMP);if(r>0){const n=wi(e,fi.FRAME_SENT),s=wi(e,fi.FRAME_ENCODED);n?i=(n-wi(t,fi.FRAME_SENT))/r*1e3:s&&(i=(s-wi(t,fi.FRAME_ENCODED))/r*1e3)}}this.stats.framerate=Math.round(i||0)}this.stats.qualityLimitationReason=Ci(e,fi.QUALITY_LIMITATION_REASON)||"none";const a=Ci(e,fi.QUALITY_LIMITATION_DURATIONS);a&&(this.stats.qualityLimitationDurations=a)}}processInboundRTP(e,t){const i=wi(e,fi.PACKETS_RECEIVED);this.stats.packetsReceived=i,this.stats.packetsSent=0;const r=wi(t,fi.PACKETS_RECEIVED),n=Math.max(0,i-r),s=wi(e,fi.PACKETS_LOST),o=wi(t,fi.PACKETS_LOST),a=Math.max(0,s-o);if(this.stats.loss={packetsTotal:n+a,packetsLost:a,packetsTotalLost:s},this.stats.recvPacketRate=n/this.interval*1e3,this.stats.pliCount=wi(e,fi.PLI_COUNT),this.stats.firCount=wi(e,fi.FIR_COUNT),this.stats.nacksCount=wi(e,fi.NACK_COUNT),this.stats.bytesReceived=wi(e,fi.BYTES_RECEIVED),this.stats.bytesSent=0,this.stats.bitrate={upload:0,download:Ri(e,t,fi.BYTES_RECEIVED,this.interval)},"video"===this.kind){const i=wi(e,fi.FRAME_DECODED),r=wi(t,fi.FRAME_DECODED);this.stats.framesDecoded=i,this.stats.frameRateDecoded=Math.round(Math.max(i-r,0)/this.interval*1e3);const n={height:wi(e,fi.FRAME_HEIGHT),width:wi(e,fi.FRAME_WIDTH)};n.width&&n.height&&(this.stats.resolution=n);const s=wi(e,fi.FRAMERATE_MEAN);if(s)this.stats.framerate=Math.round(s);else{let i=wi(e,fi.FRAME_PER_SECOND);if(!i){let r=wi(e,fi.TIMESTAMP)-wi(t,fi.TIMESTAMP);if(r>0){const n=wi(e,fi.FRAME_RECEIVED),s=wi(e,fi.FRAME_DECODED);n?i=(n-wi(t,fi.FRAME_RECEIVED))/r*1e3:s&&(i=(s-wi(t,fi.FRAME_DECODED))/r*1e3)}}this.stats.framerate=Math.round(i||0)}}}processRemoteInboundRTP(e){this.stats.rtt=Math.floor(1e3*wi(e,fi.ROUND_TRIP_TIME)),"audio"===this.kind&&(this.stats.jitterReceived=wi(e,fi.JITTER))}processTrack(e,t){const i=wi(e,fi.JITTER_BUFFER_DELAY);if(i&&t){const r=-wi(t,fi.JITTER_BUFFER_DELAY)+i,n=-wi(t,fi.JITTER_BUFFER_EMITTED_COUNT)+wi(e,fi.JITTER_BUFFER_EMITTED_COUNT);n>0&&(this.stats.jitter=Math.round(1e3*r/n))}if("video"===this.kind){const t={height:wi(e,fi.FRAME_HEIGHT),width:wi(e,fi.FRAME_WIDTH)};t.width&&t.height&&(this.stats.resolution=t);const i=wi(e,fi.FRAME_SENT);i&&(this.stats.framesSent=i)}else"audio"===this.kind&&(this.stats.concealedSamples=wi(e,fi.CONCEALED_SAMPLES),this.stats.totalSamplesReceived=wi(e,fi.TOTAL_SAMPLES_RECEIVED),this.stats.concealmentEvents=wi(e,fi.CONCEALMENT_EVENTS),this.stats.totalAudioEnergy=wi(e,fi.TOTAL_AUDIO_ENERGY),this.stats.totalSamplesDuration=wi(e,fi.TOTAL_SAMPLES_DURATION),this.stats.silentConcealedSamples=wi(e,fi.SILENT_CONCEALED_SAMPLES),this.stats.insertedSamplesForDeceleration=wi(e,fi.INSERTED_SAMPLES_FOR_DECELERATION),this.stats.removedSamplesForAcceleration=wi(e,fi.REMOVED_SAMPLES_FOR_ACCELERATION))}processMediaSource(e,t){"audio"===this.kind&&(this.stats.totalAudioEnergy=wi(e,fi.TOTAL_AUDIO_ENERGY),this.stats.totalSamplesDuration=wi(e,fi.TOTAL_SAMPLES_DURATION))}processExtraOutboundRTP(e,t){const i=wi(e,fi.PACKETS_SENT),r=wi(t,fi.PACKETS_SENT),n=Math.max(0,i-r),s=wi(e,fi.PACKETS_LOST),o=wi(t,fi.PACKETS_LOST),a=Math.max(0,s-o),c=wi(e,fi.NACK_COUNT),u=wi(t,fi.NACK_COUNT),d=Math.max(0,c-u);this.stats.loss={packetsTotal:Math.max(n-d,a,1),packetsLost:a,packetsTotalLost:s},"video"===this.kind&&(this.stats.frameRateInput=wi(e,fi.FRAME_RATE_INPUT),this.stats.encodeUsagePercent=wi(e,fi.ENCODE_USAGE_PERCENT)),this.supportExtra=!0}processExtraInboundRTP(e,t){"video"===this.kind?(this.stats.interframeDelayMax=wi(e,fi.INTER_FRAME_DELAY_MAX),this.stats.renderDelayMs=wi(e,fi.RENDER_DELAY_MS),this.stats.targetDelayMs=wi(e,fi.TARGET_DELAY_MS),this.stats.frameRateOutput=wi(e,fi.FRAME_RATE_OUTPUT)):(this.stats.currentDelayMs=wi(e,fi.CURRENT_DELAY_MS),this.stats.accelerateRate=wi(e,fi.ACCELERATE_RATE),this.stats.decodingPLC=wi(e,fi.DECODING_PLC),this.stats.decodingPLCCNG=wi(e,fi.DECODING_PLCCNG)),this.supportExtra=!0}getStats(e){const t={packetsSent:this.stats.packetsSent,packetsReceived:this.stats.packetsReceived,bytesSent:this.stats.bytesSent,bytesReceived:this.stats.bytesReceived,packetsLost:this.stats.loss.packetsTotalLost,recvPacketRate:this.stats.recvPacketRate,sentPacketRate:this.stats.sentPacketRate,googRtt:this.stats.rtt};e?("video"===this.kind?(t.googEncodeUsagePercent=this.stats.encodeUsagePercent,t.googFrameRateInput=this.stats.frameRateInput,t.googNacksReceived=this.stats.nacksCount,t.googPlisReceived=this.stats.pliCount,t.googFirsReceived=this.stats.firCount,t.framesEncoded=this.stats.framesEncoded,t.framesSent=this.stats.framesSent,t.hugeFramesSent=this.stats.hugeFramesSent):(t.googJitterReceived=this.stats.jitterReceived,t.totalAudioEnergy=this.stats.totalAudioEnergy,t.totalSamplesDuration=this.stats.totalSamplesDuration,t.googNacksReceived=this.stats.nacksCount),this.stats.loss.packetsLost=Math.floor(this.stats.loss.packetsLost*this.uploadPacketLostScale),this.stats.loss.packetsTotalLost=Math.floor(this.stats.loss.packetsTotalLost*this.uploadPacketLostScale),t.packetsLost=this.stats.loss.packetsTotalLost):"video"===this.kind?(t.googInterframeDelayMax=this.stats.interframeDelayMax,t.googPlisSent=this.stats.pliCount,t.googFirsSent=this.stats.firCount,t.googFrameRateDecoded=this.stats.frameRateDecoded,t.googFrameRateOutput=this.stats.frameRateOutput,t.googNacksSent=this.stats.nacksCount,t.googJitterBufferMs=this.stats.jitter,t.googRenderDelayMs=this.stats.renderDelayMs,t.googTargetDelayMs=this.stats.targetDelayMs,t.framesDecoded=this.stats.framesDecoded):(t.googJitterBufferMs=this.stats.jitter,t.googAccelerateRate=this.stats.accelerateRate,t.googDecodingPLC=this.stats.decodingPLC,t.googDecodingPLCCNG=this.stats.decodingPLCCNG,t.googNacksSent=this.stats.nacksCount,t.concealedSamples=this.stats.concealedSamples,t.concealmentEvents=this.stats.concealmentEvents,t.totalSamplesReceived=this.stats.totalSamplesReceived,t.totalAudioEnergy=this.stats.totalAudioEnergy,t.totalSamplesDuration=this.stats.totalSamplesDuration,t.silentConcealedSamples=this.stats.silentConcealedSamples,t.insertedSamplesForDeceleration=this.stats.insertedSamplesForDeceleration,t.removedSamplesForAcceleration=this.stats.removedSamplesForAcceleration);const i={ssrc:this.id,rid:this.stats.rid,kind:this.kind,loss:this.stats.loss,statistics:t,bitrate:this.stats.bitrate,qa:{jitter:this.stats.jitter,interruptionCount:0,interruptionDuration:0,frameDelay:"video"===this.kind?this.stats.interframeDelayMax:this.stats.currentDelayMs}};return"video"===this.kind&&(i.framerate=this.stats.framerate,i.resolution=this.stats.resolution,i.qualityLimitationReason=this.stats.qualityLimitationReason,i.qualityLimitationDurations=this.stats.qualityLimitationDurations),i}setUploadPacketLostScale(e){this.uploadPacketLostScale=e}}function Ai(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}var Mi=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class Oi{constructor(e,t=1e3,i=!0,r=1e3){this.pc=e,this.interval=t,this.isPush=i,this.audioLevelInterval=r,this.uploadPacketLostScale=1,this.rtpsMap=new Map,this.conferenceStats={bandwidth:{download:0,upload:0},transport:[],bitrate:{download:0,upload:0,audio:{download:0,upload:0},video:{download:0,upload:0}},packetLoss:{audio:{total:0,download:0,upload:0},video:{total:0,download:0,upload:0}}},this.bweforvideo={availableReceiveBandwidth:0,availableSendBandwidth:0,targetEncBitrate:0,transmitBitrate:0,retransmitBitrate:0},this.iceStats={packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0},this.iceDownloadBitrate=0,this.iceUploadBitrate=0,this.previousReport=null,this.audioLevel=0,this.statsTimer=new ct((()=>{this.collectStats()}),0,this.interval),this.extraTimer=new ct((()=>{this.collectExtraStats()}),this.interval,this.interval),this.audioLevelTimer=new ct((()=>{this.collectAudioLevel()}),this.interval,this.audioLevelInterval)}getKind(e){return e.kind||e.mediaType}processCandidate(e,t){let i=wi(t,fi.AVAILABLE_INCOMING_BITRATE),r=wi(t,fi.AVAILABLE_OUTGOING_BITRATE);if((i||r)&&(this.conferenceStats.bandwidth={upload:Math.max(r,0),download:Math.max(i,0)}),o.d(e.get)){let i=e.get(t.remoteCandidateId),r=e.get(t.localCandidateId);if(i&&r){let e=Ci(i,fi.IP),n=`${e}:${Ci(i,fi.PORT)}`,s=Ci(r,fi.IP),o=`${s}:${Ci(r,fi.PORT)}`,a=Ci(i,fi.PROTOCOL);e&&(this.remoteIP=e),s&&(this.localIP=s),a&&(this.pairProtocol=a);let c=this.conferenceStats.transport.find((e=>e.ip===n&&e.type===a&&e.localIp===o));c?(c.localCandidateType=r.candidateType,c.remoteCandidateType=i.candidateType,c.networkType=r.networkType,c.rtt=Math.round(1e3*wi(t,fi.CURRENT_ROUND_TRIP_TIME))):this.conferenceStats.transport.push({ip:n,type:a,localIp:o,localCandidateType:r.candidateType,remoteCandidateType:i.candidateType,networkType:r.networkType,rtt:Math.round(1e3*wi(t,fi.CURRENT_ROUND_TRIP_TIME))})}}this.iceStats.bytesSent=wi(t,fi.BYTES_SENT),this.iceStats.bytesReceived=wi(t,fi.BYTES_RECEIVED),this.iceStats.packetsSent=wi(t,fi.PACKETS_SENT),this.iceStats.packetsReceived=wi(t,fi.PACKETS_RECEIVED),this.iceStats.requestsSent=wi(t,fi.REQUESTS_SENT),this.iceStats.responsesReceived=wi(t,fi.RESPONSES_RECEIVED),this.previousCandidateStats&&(this.iceDownloadBitrate=Ri(t,this.previousCandidateStats,fi.BYTES_RECEIVED,this.interval),this.iceUploadBitrate=Ri(t,this.previousCandidateStats,fi.BYTES_SENT,this.interval)),this.previousCandidateStats=t}processReport(e){e.forEach((t=>{if("candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state)this.processCandidate(e,t);else if(this.isPush&&"outbound-rtp"===t.type){const e=this.previousReport.get(t.id),i=wi(t,fi.SSRC);if(i){let r=this.rtpsMap.get(i);r||(r=new ki(i,this.getKind(t),this.interval),this.rtpsMap.set(i,r),r.setUploadPacketLostScale(this.uploadPacketLostScale)),r.processOutboundRTP(t,e)}}else if(this.isPush||"inbound-rtp"!==t.type){if("track"===t.type){const e=this.previousReport.get(t.id);if(this.rtpsMap.forEach((i=>{i.getKind()===this.getKind(t)&&i.processTrack(t,e)})),"audio"===this.getKind(t)){const e=Ci(t,fi.AUDIO_LEVEL);we(e)&&(this.audioLevel=Xe(e))}}else if("remote-inbound-rtp"===t.type){const e=wi(t,fi.SSRC);if(e){let i=this.rtpsMap.get(e);i||(i=new ki(e,this.getKind(t),this.interval),this.rtpsMap.set(e,i),i.setUploadPacketLostScale(this.uploadPacketLostScale)),i.processRemoteInboundRTP(t)}}else if("media-source"===t.type){if("audio"===this.getKind(t)){const e=Ci(t,fi.AUDIO_LEVEL);we(e)&&(this.audioLevel=Xe(e))}if(this.isPush){const e=this.previousReport.get(t.id);this.rtpsMap.forEach((i=>{i.getKind()===this.getKind(t)&&i.processMediaSource(t,e)}))}}}else{const e=this.previousReport.get(t.id),i=wi(t,fi.SSRC);if(i){let r=this.rtpsMap.get(i);r||(r=new ki(i,this.getKind(t),this.interval),this.rtpsMap.set(i,r),r.setUploadPacketLostScale(this.uploadPacketLostScale)),r.processInboundRTP(t,e)}if("audio"===this.getKind(t)){const e=Ci(t,fi.AUDIO_LEVEL);we(e)&&(this.audioLevel=Xe(e))}}}))}processExtraStats(e){for(let t in e){if(!e.hasOwnProperty(t))continue;const i=e[t];if(!i)continue;if("VideoBwe"===i.type&&(this.bweforvideo.availableReceiveBandwidth=wi(i,fi.AVAILABLE_RECEIVE_BANDWIDTH),this.bweforvideo.availableSendBandwidth=wi(i,fi.AVAILABLE_SEND_BANDWIDTH),this.bweforvideo.retransmitBitrate=wi(i,fi.RETRANSMIT_BITRATE),this.bweforvideo.targetEncBitrate=wi(i,fi.TARGET_ENC_BITRATE),this.bweforvideo.transmitBitrate=wi(i,fi.TRANSMIT_BITRATE)),"ssrc"!==i.type&&"outboundrtp"!==i.type&&"inboundrtp"!==i.type&&"track"!==i.type)continue;if(i.isRemote||i.remoteSource)continue;const r=this.previousExtraReport[t];let n=wi(i,fi.SSRC);if("track"===i.type&&Array.isArray(i.ssrcIds)&&(n=Number(i.ssrcIds[0])),n){const e=this.rtpsMap.get(n);e&&(this.isPush?e.processExtraOutboundRTP(i,r):e.processExtraInboundRTP(i,r))}}}collectStats(){return Mi(this,void 0,void 0,(function*(){let e=yield this.pc.getStats();e&&(o.d(e.result)&&(e=e.result()),this.previousReport&&this.processReport(e),this.previousReport=e)}))}collectExtraStats(){this.pc.getStats((e=>{if(e){if(o.d(e.result)&&(e=e.result()),o.d(e.forEach)){const t=[];e.forEach((e=>{t.push(e)})),e=t}this.previousExtraReport&&this.processExtraStats(e),this.previousExtraReport=e}}),(e=>{this.extraTimer.stop()}))}collectAudioLevel(){return Mi(this,void 0,void 0,(function*(){let e=yield this.pc.getStats();if(e){if(o.d(e.result)&&(e=e.result()),o.d(e.forEach)){const t=[];e.forEach((e=>{t.push(e)})),e=t}let t=!1;e.forEach((e=>{if("track"===e.type){if("audio"===this.getKind(e)){t=!0;const i=Ci(e,fi.AUDIO_LEVEL);we(i)&&(this.audioLevel=Xe(i))}}else if("inbound-rtp"===e.type){if("audio"===this.getKind(e)){t=!0;const i=Ci(e,fi.AUDIO_LEVEL);we(i)&&(this.audioLevel=Xe(i))}}else if("media-source"===e.type&&"audio"===this.getKind(e)){t=!0;const i=Ci(e,fi.AUDIO_LEVEL);we(i)&&(this.audioLevel=Xe(i))}})),this.onAudioLevel&&t?this.onAudioLevel(this.audioLevel):!t&&this.audioLevelTimer&&this.audioLevelTimer.stop()}}))}start(){this.statsTimer.isStarted()||this.statsTimer.start(),ot.chrome&&(this.extraTimer.isStarted()||this.extraTimer.start(),this.audioLevelTimer&&!this.audioLevelTimer.isStarted()&&this.audioLevelInterval<1e3&&this.audioLevelTimer.start())}restartAudioLevelTimer(){this.audioLevelTimer&&!this.audioLevelTimer.isStarted()&&this.audioLevelInterval<1e3&&this.audioLevelTimer.start()}stop(){this.statsTimer&&this.statsTimer.stop(),this.extraTimer&&this.extraTimer.stop(),this.audioLevelTimer&&this.audioLevelTimer.stop()}updateAudioLevelInterval(e){this.audioLevelInterval=e,this.audioLevelTimer&&(this.audioLevelTimer.updateInterval(e),!this.audioLevelTimer.isStarted()&&e<1e3?this.audioLevelTimer.start():e>=1e3&&this.audioLevelTimer.stop())}destroy(){this.stop(),this.statsTimer&&this.statsTimer.destroy(),this.extraTimer&&this.extraTimer.destroy(),this.audioLevelTimer&&this.audioLevelTimer.destroy(),this.statsTimer=null,this.extraTimer=null,this.audioLevelTimer=null,this.pc=null,this.previousReport=null,this.previousExtraReport=null,this.rtpsMap&&this.rtpsMap.clear(),this.conferenceStats={bandwidth:{download:0,upload:0},transport:[],bitrate:{download:0,upload:0,audio:{download:0,upload:0},video:{download:0,upload:0}},packetLoss:{audio:{total:0,download:0,upload:0},video:{total:0,download:0,upload:0}}},this.bweforvideo={availableReceiveBandwidth:0,availableSendBandwidth:0,targetEncBitrate:0,transmitBitrate:0,retransmitBitrate:0}}getAudioLevel(){return this.audioLevel}getStats(){let e=0,t=0,i=0,r=0,n=0,s=0,o={audio:{download:0,upload:0},video:{download:0,upload:0}},a={audio:{download:0,upload:0},video:{download:0,upload:0}};const c=[];this.rtpsMap.forEach((u=>{const d=u.getStats(this.isPush);e+=d.bitrate.download,t+=d.bitrate.upload,"video"===d.kind?(n+=d.bitrate.download,s+=d.bitrate.upload,this.isPush?(o.video.upload+=d.loss.packetsTotal,a.video.upload+=d.loss.packetsLost):(o.video.download+=d.loss.packetsTotal,a.video.download+=d.loss.packetsLost)):(i+=d.bitrate.download,r+=d.bitrate.upload,this.isPush?(o.audio.upload+=d.loss.packetsTotal,a.audio.upload+=d.loss.packetsLost):(o.audio.download+=d.loss.packetsTotal,a.audio.download+=d.loss.packetsLost)),c.push(d)}));let u={availableSendBandwidth:this.bweforvideo.availableSendBandwidth,availableReceiveBandwidth:this.bweforvideo.availableReceiveBandwidth,retransmitBitrate:this.bweforvideo.retransmitBitrate,transmitBitrate:this.bweforvideo.transmitBitrate,targetEncBitrate:this.bweforvideo.targetEncBitrate};const d=this.conferenceStats.transport;return{bandwidth:this.conferenceStats.bandwidth,bitrate:{upload:t,download:e,audio:{upload:r,download:i},video:{upload:s,download:n},ice:{upload:this.iceUploadBitrate,download:this.iceDownloadBitrate}},packetLoss:{audio:{total:Ai(a.audio.download+a.audio.upload,o.audio.download+o.audio.upload),download:Ai(a.audio.download,o.audio.download),upload:Ai(a.audio.upload,o.audio.upload)},video:{total:Ai(a.video.download+a.video.upload,o.video.download+o.video.upload),download:Ai(a.video.download,o.video.download),upload:Ai(a.video.upload,o.video.upload)}},transport:d,bweforvideo:u,ice:this.iceStats,rtps:c}}getLocalIP(){return this.localIP}getRemoteIP(){return this.remoteIP}getCurrentPairProtocol(){return this.pairProtocol}setUploadPacketLostScale(e){this.uploadPacketLostScale=e,this.rtpsMap.forEach((t=>{t.setUploadPacketLostScale(e)}))}}var Li=i(11),Pi=i.n(Li),Ni=i(12);const Di=new(i.n(Ni).a.Interop);var xi,Ui,$i,Bi;!function(e){e.SEND_ONLY="sendonly",e.RECV_ONLY="recvonly",e.SEND_RECV="sendrecv",e.INACTIVE="inactive"}(xi||(xi={})),function(e){e.VIDEO="video",e.AUDIO="audio",e.APPLICATION="application"}(Ui||(Ui={})),function(e){e[e.ADD=0]="ADD",e[e.REMOVE=1]="REMOVE"}($i||($i={})),function(e){e.VIDEO_INPUT="videoinput",e.AUDIO_INPUT="audioinput",e.AUDIO_OUTPUT="audiooutput"}(Bi||(Bi={}));var Vi,Fi=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};!function(e){e[e.PLAN_B=0]="PLAN_B",e[e.UNIFIED_PLAN=1]="UNIFIED_PLAN"}(Vi||(Vi={}));class ji extends Ne{constructor(e={},t=Vi.UNIFIED_PLAN){var i;super(!0);const r=null!==(i=e.iceServers)&&void 0!==i?i:[];this.options=Me({},{iceServers:r.concat(Pi()()),sdpSemantics:"unified-plan"},e),this.sdpType=t,this.candidategatheringdone=!1,this.localIcecandidatePadding=[],this.remoteIcecandidatePadding=[],this.uuid=ei(),this.direction=xi.SEND_RECV,this.pc=new RTCPeerConnection(this.options),this.pc.onicecandidate=e=>{let t=e.candidate;t&&(this.sdpType===Vi.PLAN_B&&(t=Di.candidateToUnifiedPlan(t)),this._onicecandidate&&this.candidategatheringdone?this._onicecandidate(t):this.localIcecandidatePadding.push(t))},this.pc.onsignalingstatechange=e=>{if("stable"===this.signalingState)for(;this.remoteIcecandidatePadding.length;)this.pc.addIceCandidate(this.remoteIcecandidatePadding.shift())},this.pc.onnegotiationneeded=e=>{this.onnegotiationneeded&&this.onnegotiationneeded()},this.pc.oniceconnectionstatechange=e=>{this.oniceconnectionstatechange&&this.oniceconnectionstatechange(this.iceConnectionState)}}createChannel(e={}){this.channel=this.pc.createDataChannel(this.uuid,e),this.channel.onmessage=e=>{this.onmessage&&q(this.onmessage,this,[e])}}getLocalSessionDescriptor(){return this.pc.localDescription}getRemoteSessionDescriptor(){return this.pc.remoteDescription}setOffer(e){return Fi(this,void 0,void 0,(function*(){let t=new RTCSessionDescription({type:"offer",sdp:e});yield this.pc.setLocalDescription(t)}))}setAnwser(e){return Fi(this,void 0,void 0,(function*(){let t=new RTCSessionDescription({type:"answer",sdp:e});this.sdpType===Vi.PLAN_B&&(t=Di.toPlanB(t)),yield this.pc.setRemoteDescription(t),this.handleDtlsTransport()}))}resetAnswer(e){return Fi(this,void 0,void 0,(function*(){const t=this.getLocalSessionDescriptor();yield this.pc.createOffer(),yield this.pc.setLocalDescription(t),yield this.setAnwser(e)}))}addIceCandidate(e){"stable"===this.signalingState?this.pc.addIceCandidate(e):this.remoteIcecandidatePadding.push(e)}offer(e){return Fi(this,void 0,void 0,(function*(){let t=yield this.pc.createOffer(e);return this.sdpType===Vi.PLAN_B&&(t=Di.toPlanB(t)),t.sdp}))}answer(e){return Fi(this,void 0,void 0,(function*(){let t=new RTCSessionDescription({type:"offer",sdp:e});this.sdpType===Vi.PLAN_B&&(t=Di.toPlanB(t)),yield this.pc.setRemoteDescription(t);let i=yield this.pc.createAnswer();return this.sdpType===Vi.PLAN_B&&(t=Di.toPlanB(t)),this.handleDtlsTransport(),i.sdp}))}getMediaStream(){return this.stream}getSenders(){return this.pc.getSenders()}getReceivers(){return this.pc.getReceivers()}getPeerConnection(){return this.pc}send(e){this.channel?this.channel.send(e):he.error("can not send data because of no channel in DataChannel")}destroy(e=!1){this.pc&&(e&&this.stream&&this.stream.getTracks().forEach((e=>{e.stop()})),this.pc.onicecandidate=null,this.pc.onsignalingstatechange=null,this.pc.onnegotiationneeded=null,this.pc.oniceconnectionstatechange=null,this.dtlsTransport&&(this.dtlsTransport.onstatechange=null),this.pc.close(),this.pc=null,this.stream=null,this.dtlsTransport=null)}get onicecandidate(){return this._onicecandidate}set onicecandidate(e){if(this._onicecandidate=e,!this.candidategatheringdone)for(;this.localIcecandidatePadding.length;)this._onicecandidate(this.localIcecandidatePadding.shift());this.candidategatheringdone=!0}get signalingState(){var e;return null===(e=this.pc)||void 0===e?void 0:e.signalingState}get iceConnectionState(){var e;return null===(e=this.pc)||void 0===e?void 0:e.iceConnectionState}get dtlsConnectionState(){var e;return null===(e=this.dtlsTransport)||void 0===e?void 0:e.state}isConnected(){return"connected"===this.iceConnectionState&&"connected"===this.dtlsConnectionState}getLocalIP(){var e;const t=null===(e=this.dtlsTransport)||void 0===e?void 0:e.iceTransport;if(t&&o.d(t.getSelectedCandidatePair)){const e=t.getSelectedCandidatePair().local;if(e)return e.address}}getRemoteIP(){var e;const t=null===(e=this.dtlsTransport)||void 0===e?void 0:e.iceTransport;if(t&&o.d(t.getSelectedCandidatePair)){const e=t.getSelectedCandidatePair().remote;if(e)return e.address}}getPairProtocol(){var e;const t=null===(e=this.dtlsTransport)||void 0===e?void 0:e.iceTransport;if(t&&o.d(t.getSelectedCandidatePair)){const e=t.getSelectedCandidatePair().remote;if(e)return e.protocol}}handleDtlsTransport(){ge(this.getSenders(),(e=>{if(e.transport)return this.dtlsTransport=e.transport,!1})),this.dtlsTransport||ge(this.getReceivers(),(e=>{if(e.transport)return this.dtlsTransport=e.transport,!1})),this.dtlsTransport&&(this.dtlsTransport.onstatechange=e=>{this.ondtlsstatechange&&this.ondtlsstatechange(this.dtlsTransport.state)})}}var Hi=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class Wi extends ji{constructor(e={}){super(e),this.direction=xi.SEND_ONLY}addStream(e,t,i=49152){var r,n;if(this.stream=e,!this.pc.addTransceiver||ot.chrome&&!ot.checkVersion(ot.majorVersion,"72",!0))if(this.pc.addTrack){const e=this.stream.getAudioTracks()[0],t=this.stream.getVideoTracks()[0];e&&this.pc.addTrack(e,this.stream),t&&this.pc.addTrack(t,this.stream)}else this.pc.addStream(this.stream);else{const e=this.stream.getAudioTracks()[0],s=this.stream.getVideoTracks()[0];if(e&&this.pc.addTransceiver(e,{streams:[this.stream],sendEncodings:[{active:!0,maxBitrate:i}]}),s){const e=[];if(o.a(t))for(let i=0;i<t.length;i++)e.push({active:null===(r=t[i].active)||void 0===r||r,scaleResolutionDownBy:t[i].scale,maxBitrate:t[i].bitrate,rid:null!==(n=t[i].rid)&&void 0!==n?n:"r"+i});this.pc.addTransceiver(s,{direction:xi.SEND_ONLY,streams:[this.stream],sendEncodings:e})}}}setEncodings(e){const t=this.pc.getSenders();if(!t.length)return;const i=t.find((e=>e.track.kind===Ui.VIDEO));if(!i)return;if(!i.track)return;const r=i.getParameters();if(!r)return;const n=r.encodings;n.length!==e.length&&he.warn("encodings length not match to parameters");const s=Math.min(n.length,e.length);for(let t=0;t<s;t++)o.f(e[t].scale)&&(n[t].scaleResolutionDownBy=e[t].scale),o.f(e[t].bitrate)&&(n[t].maxBitrate=e[t].bitrate),o.c(e[t].active)&&(n[t].active=e[t].active);r.encodings=n,i.setParameters(r)}setScalabilityMode(e){const t=this.pc.getSenders();if(!t.length)return;const i=t.find((e=>e.track.kind===Ui.VIDEO));if(!i)return;if(!i.track)return;const r=i.getParameters();if(!r)return;const n=r.encodings,s=n.length;for(let t=0;t<s;t++)n[t].scalabilityMode=e.replace(/^S/,"L").replace(/T[4-9]/,"T3");r.encodings=n,i.setParameters(r)}enableVideoLayer(e,t){const i=this.pc.getSenders();if(!i.length)return;const r=i.find((e=>e.track.kind===Ui.VIDEO));if(!r)return;if(!r.track)return;const n=r.getParameters();if(!n)return;const s=n.encodings,o=s.length;let a=!1;for(let i=0;i<o;i++)if(i===t){a=!0,s[i].active=e;break}a&&(n.encodings=s,r.setParameters(n))}offer(){const e=Object.create(null,{offer:{get:()=>super.offer}});return Hi(this,void 0,void 0,(function*(){return e.offer.call(this,{offerToReceiveAudio:!1,offerToReceiveVideo:!1})}))}replaceTrack(e){return Hi(this,void 0,void 0,(function*(){const t=this.getSenders().find((t=>t.track.kind===e.kind));if(t&&(yield t.replaceTrack(e)),this.stream){const t="video"===e.kind?this.stream.getVideoTracks()[0]:this.stream.getAudioTracks()[0];this.stream.removeTrack(t),this.stream.addTrack(e)}}))}}function Gi(e=[],t=!0){return function(i){return o.a(i.media)&&(ge(i.media,(i=>{o.a(i.candidates)&&ge(i.candidates,(i=>{Ie.d(i.ip,"172")||Ie.d(i.ip,"192")?t&&!Ee(e,i.ip)&&e.push(i.ip):Ee(e,i.ip)||e.push(i.ip)}))})),he.debug(`[sdpOperator msmsIP] hold: ${JSON.stringify(e)}, hasLocal: ${t}`)),i}}function qi(e,t,i,r,n){return function(s){return o.a(s.media)&&ge(s.media,(s=>{if(s.type===i){let i;if("*"===n){const t=[],i=[];ge(s.rtcpFb,(n=>{if(!Ee(t,n.payload)){const s={payload:n.payload,type:e};r&&(s.subtype=r),i.push(s),t.push(n.payload)}})),s.rtcpFb=s.rtcpFb.concat(i).sort(((e,t)=>e.payload-t.payload))}else{const a=s.payloads.split(" ");if(!a.length)return!0;if(i=Xe(a[0]),o.i(n)&&ge(s.rtp,(e=>{if(e.codec.toLocaleLowerCase()===n.toLocaleLowerCase())return i=e.payload,!1})),t===$i.ADD){let t=!1;if(ge(s.rtcpFb,(n=>{if(n.payload===i&&n.type===e&&n.subtype==r)return t=!0,!1})),!t){const t={payload:i,type:e};r&&(t.subtype=r),s.rtcpFb?s.rtcpFb.push(t):s.rtcpFb=[t]}}else t===$i.REMOVE&&o.a(s.rtcpFb)&&(s.rtcpFb=s.rtcpFb.filter((t=>!(t.payload===i&&t.type===e&&t.subtype==r))))}he.debug(`[sdpOperator rtcpFB] payload: ${i}, attr: ${e}, operator: ${t}, mediaType: ${s.type}, subAttr: ${r}, codec: ${n}`)}})),s}}function Ji(e,t){return function(i){return o.a(i.media)&&ge(i.media,(i=>{i.type===t&&(i.bandwidth=[{type:"AS",limit:e}],he.debug(`[sdpOperator bandwidth] bandwidth: ${e}, mediaType: ${i.type}`))})),i}}function zi(e,t){return function(i){return i.direction&&(i.direction=e),o.a(i.media)&&ge(i.media,(i=>{if("application"===i.type)return!0;t&&i.type!==t||(i.direction=e,he.debug(`[sdpOperator direction] direction: ${e}, mediaType: ${i.type}`))})),i}}function Yi(e,t,i){return function(r){return o.a(r.media)&&ge(r.media,(r=>{if("application"===r.type)return!0;if(!o.f(t)){const e=new Array(256);if(o.a(r.ext)){ge(r.ext,(t=>{e[t.value]=!0}));for(let i=1;i<e.length;i++)if(!e[i]){t=i;break}}else t=1}i&&i!==r.type||(o.a(r.ext)?r.ext.push({value:t,uri:e}):r.ext=[{value:t,uri:e}],he.debug(`[sdpOperator addExtmap] id: ${t}, uri: ${e}, mediaType: ${r.type}`))})),r}}function Qi(e,t="&"){const i={};if(o.i(e)&&e.indexOf("=")>=0){let r=e.charAt(0),n="?"===r||"#"===r?1:0;n>0&&(e=e.substr(n)),ge(function(e,t){const i=[];return o.f(e)&&(e+=""),e&&o.i(e)&&ge(e.split(t),((e,t)=>{(e=e.trim())&&i.push(e)})),i}(e,t),(e=>{var t;let r=e.split("=");if(2===r.length){let e=null===(t=r[0])||void 0===t?void 0:t.trim();e&&(i[e]=decodeURIComponent(r[1]))}}))}return i}function Ki(e,t="&"){const i=[];return o.e(e)&&ke(e,((e,t)=>{i.push(t+"="+encodeURIComponent(o.h(e)?JSON.stringify(e):e))})),i.join(t)}function Xi(e,t,i,r,n,s){return function(a){return o.a(a.media)&&ge(a.media,(a=>{if(a.type!==e)return!0;if(!o.f(n)&&r){let e=!1;if(ge(a.rtp,(t=>{if(t.codec.toLocaleLowerCase()===r.toLocaleLowerCase())return e=!0,!1})),!e)return!0;n=Xe(a.payloads.split(" ").shift())}if(!o.f(n))return!0;let c=null;if(ge(a.fmtp,(e=>{s&&s(e)?c=e:s||e.payload!==n||(c=e)})),c){const e=Qi(c.config,";");e[t]=Object(Be.a)(i),c.config=Ki(e,";")}else a.fmtp?a.fmtp.push({payload:n,config:`${t}=${Object(Be.a)(i)}`}):a.fmtp=[{payload:n,config:`${t}=${Object(Be.a)(i)}`}];he.debug(`[sdpOperator fmptConfig] key: ${t}, value: ${i}, codec: ${r}, payload: ${n}, mediaType: ${a.type}`)})),a}}const Zi=/(.*)/,er={v:[{name:"version",reg:/^(\d*)$/,format:"%s"}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name",reg:Zi,format:"%s"}],i:[{name:"description",reg:Zi,format:"%s"}],u:[{name:"uri",reg:Zi,format:"%s"}],e:[{name:"email",reg:Zi,format:"%s"}],p:[{name:"phone",reg:Zi,format:"%s"}],z:[{name:"timezones",reg:Zi,format:"%s"}],r:[{name:"repeats",reg:Zi,format:"%s"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/,format:"%s"},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/,format:"%s"},{name:"icelite",reg:/^(ice-lite)/,format:"%s"},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){let t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/,format:"%s"},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){let t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/,format:"%s"},{name:"rtcpRsize",reg:/^(rtcp-rsize)/,format:"%s"},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/,format:"%s"},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){let t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",reg:Zi,names:["value"],format:"%s"}]};function tr(e,t){if(o.a(er[e]))if("a"===e){const i=er[e].pop();er[e].push(...t),er[e].push(i)}else er[e].push(...t);else er[e]=t}const ir=["v","o","s","i","u","e","p","c","b","t","r","z","a"],rr=["i","c","b","a"],nr=e=>/^([a-z])=(.*)/.test(e);function sr(e){return String(Number(e))===e?Number(e):e}function or(e,t,i){const r=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:r&&!t[e.name]&&(t[e.name]={});const n=e.push?{}:r?t[e.name]:t;!function(e,t,i,r){if(r&&!i)t[r]=sr(e[1]);else for(let r=0;r<i.length;r+=1)null!=e[r+1]&&(t[i[r]]=sr(e[r+1]))}(i.match(e.reg),n,e.names,e.name),e.push&&t[e.push].push(n)}const ar=/%[sdv%]/g;function cr(e){let t=1;const i=arguments,r=i.length;return e.replace(ar,(function(e){if(t>=r)return e;const n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n)+"";case"%v":return""}}))}function ur(e,t,i){const r=[e+"="+(o.d(t.format)?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(let e=0;e<t.names.length;e+=1){const n=t.names[e];t.name?r.push(i[t.name][n]):r.push(i[t.names[e]])}else r.push(i[t.name]);return cr.apply(null,r)}function dr(e){const t={},i=[];let r=t;return e.split(/(\r\n|\r|\n)/).filter(nr).forEach((e=>{const t=e[0],n=e.slice(2);"m"===t&&(i.push({rtp:[],fmtp:[]}),r=i[i.length-1]);for(let e=0;e<(er[t]||[]).length;e+=1){const i=er[t][e];if(i.reg.test(n))return or(i,r,n)}})),t.media=i,t}function lr(e,t={outerOrder:ir,innerOrder:rr}){null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));const i=[];return t.outerOrder.forEach((t=>{er[t].forEach((r=>{r.name in e&&null!=e[r.name]?i.push(ur(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((e=>{i.push(ur(t,r,e))}))}))})),e.media.forEach((e=>{i.push(ur("m",er.m[0],e)),t.innerOrder.forEach((t=>{er[t].forEach((r=>{r.name in e&&null!=e[r.name]?i.push(ur(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(ur(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"}const hr=/^([a-z])=(.*)/;function mr(...e){let t=[],i=[];const r=function(r){if(t.length){let e=r.split(/(\r\n|\r|\n)/).filter((e=>hr.test(e)));for(let i=0;i<t.length;i++)t[i]&&(e=t[i](e));r=e.join("\r\n")}if(e.length){let t=dr(r);for(let i=0;i<e.length;i++)e[i]&&(t=e[i](t));r=lr(t)}if(i.length){let e=r.split(/(\r\n|\r|\n)/).filter((e=>hr.test(e)));for(let t=0;t<i.length;t++)i[t]&&(e=i[t](e));r=e.join("\r\n")+"\r\n"}return r};return r.before=(...e)=>(t=t.concat(e),r),r.after=(...e)=>(i=i.concat(e),r),r}function pr(e,t,i){return function(r){return o.a(r.media)&&ge(r.media,(r=>{if(r.type===t){let t=[];if(ge(r.rtp,(i=>{i.codec.toLocaleLowerCase()===e.toLocaleLowerCase()&&t.push(i.payload)})),!t.length)return!0;let n=t[0];i&&ge(r.fmtp,(e=>{if(Ee(t,e.payload)&&Ie.b(e.config,i)>-1)return n=e.payload,!1}));const s=r.payloads.split(" ");Se(s,Object(Be.a)(n),!0),s.unshift(Object(Be.a)(n)),r.payloads=s.join(" "),he.debug(`[sdpOperator preferCodec] codec: ${e}, mediaType: ${r.type}, fmpt: ${i}`)}})),r}}function fr(e,t,i){return function(r){return o.a(r.media)&&ge(r.media,(r=>{if("application"===r.type)return!0;t&&t!==r.type||!o.a(r.ext)||(r.ext=r.ext.filter((t=>!(o.f(i)&&t.value===i||Ie.b(t.uri,e)>-1))),he.debug(`[sdpOperator removeExtmap] ext: ${e}, mediaType: ${r.type}, value: ${i}`))})),r}}function vr(e,t){return function(i){let r=!1;return o.a(i.media)&&ge(i.media,(t=>{if(t.type===e)return r=!0,!1})),t(r),i}}function gr(e,...t){let i,r=0;for(i of t)r+=i.length;let n=new e(r),s=0;for(i of t)n.set(i,s),s+=i.length;return n}console.log.bind(console),console.log.bind(console);const _r="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;class yr{constructor(e,t=!0){this.buffer=e,this.data=new DataView(e.buffer),this.pos=0,this.size=e.byteLength,this.littleEndian=!t}readUint8(){return this.data.getUint8(this.pos++)}readUint16(){const e=this.data.getUint16(this.pos,this.littleEndian);return this.pos+=2,e}readUint24(){return this.readUint16()<<8|this.readUint8()}readUint32(){const e=this.data.getUint32(this.pos,this.littleEndian);return this.pos+=4,e}readUint64(){const e=BigInt(this.readUint32()),t=BigInt(this.readUint32());return this.littleEndian?t<<BigInt(32)|e:e<<BigInt(32)|t}readInt8(){return this.data.getInt8(this.pos++)}readInt16(){const e=this.data.getInt16(this.pos,this.littleEndian);return this.pos+=2,e}readInt32(){const e=this.data.getInt32(this.pos,this.littleEndian);return this.pos+=4,e}readInt64(){const e=BigInt(this.readInt32()),t=BigInt(this.readInt32());return this.littleEndian?t<<BigInt(32)|e:e<<BigInt(32)|t}readFloat(){const e=this.data.getFloat32(this.pos,this.littleEndian);return this.pos+=4,e}readDouble(){const e=this.data.getFloat64(this.pos,this.littleEndian);return this.pos+=8,e}readHex(e=1){let t="";for(let i=0;i<e;i++){const e=this.readUint8().toString(16);t+=1===e.length?"0"+e:e}return t}readString(e=1){let t="";if(e){let i=this.pos;for(let t=0;t<e&&0===this.buffer[this.pos+t];t++)i++;t=function(e,t,i){const r=(t>>>=0)+i;let n=t,s="";for(;e[n>>>0]&&!(n>=r);)++n;if(n-t>16&&e.subarray&&_r&&!("function"==typeof SharedArrayBuffer&&e.buffer instanceof SharedArrayBuffer))return _r.decode(e.subarray(t>>>0,n>>>0));for(;t<n;){let i=e[t++>>>0];if(!(128&i)){s+=String.fromCharCode(i);continue}let r=63&e[t++>>>0];if(192==(224&i)){s+=String.fromCharCode((31&i)<<6|r);continue}let n=63&e[t++>>>0];if(i=224==(240&i)?(15&i)<<12|r<<6|n:(7&i)<<18|r<<12|n<<6|63&e[t++>>>0],i<65536)s+=String.fromCharCode(i);else{let e=i-65536;s+=String.fromCharCode(55296|e>>10,56320|1023&e)}}return s}(this.buffer,i,e)}return this.pos+=e,t}getPos(){return this.pos}seek(e){e>this.size&&(this.pos=this.size),this.pos=e}skip(e){this.seek(this.pos+e)}remainingSize(){return this.size-this.pos}readBuffer(e){e=Math.min(e,this.remainingSize());const t=this.buffer.slice(this.pos,this.pos+e);return this.pos+=e,t}appendBuffer(e){this.buffer=gr(Uint8Array,this.buffer,e),this.data=new DataView(this.buffer),this.size+=e.byteLength}}var Sr=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const Er={send:!0,layers:1,payloadType:243,enableSVC:!1,enableSEI:!0};class br{constructor(e={}){this.options=Me({},Er,e),this.queue=[],this.next=0;for(let e=0;e<this.options.layers;e++)this.queue.push([]);this.encodeStreamMap=new Map,this.ssrcCaches=new Map}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0;const r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:i++;break;case 1:2!==i&&3!==i||t++,i=0;break;default:i=0}return t}pushNumber(e,t){const i=t/255|0,r=t%255;for(let t=0;t<i;t++)e.push(255);e.push(r)}readNumber(e){let t=0,i=e.readUint8();for(;255===i;)t+=255,i=e.readUint8();return t+=i,t}encodeSEINalu(e,t){const i=[0,0,0,1,6];this.pushNumber(i,t),this.pushNumber(i,e.byteLength);const r=new Uint8Array(i.length+e.byteLength);return r.set(i,0),r.set(new Uint8Array(e),i.length),r.buffer}decodeSEINalu(e){if(this.onmessage){const t=new yr(e);0===t.readUint24()&&t.skip(1),t.skip(1);const i=this.readNumber(t),r=this.readNumber(t);this.onmessage(t.readBuffer(r),i)}}changeNRI(e,t){let i;t=3-(t=Math.min(t,3));let r={offset:0,startCode:0};for(;(i=this.getNextNaluStart(e,r.offset)).offset>-1&&(r=this.getNextNaluStart(e,i.offset+i.startCode),e[i.offset+i.startCode]=159&e[i.offset+i.startCode]|t<<5,-1!==r.offset););}encodeVideoFrame(e,t){return Sr(this,void 0,void 0,(function*(){if(this.options.onVideoEncodeDataPipe)try{const t=yield this.options.onVideoEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){he.error("decodeVideoFrame fail, "+at(e))}const i=e.getMetadata();let r=this.ssrcCaches.get(i.synchronizationSource);if(!r){if(r=this.queue[this.next++],!r)return void t.enqueue(e);this.ssrcCaches.set(i.synchronizationSource,r)}if(r.length&&!this.isEmptyFrame(e)){if(i.temporalIndex)return void t.enqueue(e);const n=9-this.getNaluCount(e.data);if(n<=0)return void t.enqueue(e);e.data=gr(Uint8Array,...[new Uint8Array(e.data)].concat(r.splice(0,n))).buffer}t.enqueue(e)}))}encodeAudioFrame(e,t){return Sr(this,void 0,void 0,(function*(){if(!this.isEmptyFrame(e)&&this.options.onAudioEncodeDataPipe)try{const t=yield this.options.onAudioEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){he.error("decodeVideoFrame fail, "+at(e))}t.enqueue(e)}))}getNextSEIStart(e,t){let i=0;for(let r=t;r<e.length;r++)switch(e[r]){case 0:i++;break;case 1:if((2===i||3===i)&&6===e[r+1])return r-i;i=0;break;default:i=0}return-1}getNextNaluStart(e,t){let i=0;for(let r=t;r<e.length;r++)switch(e[r]){case 0:i++;break;case 1:if(2===i||3===i)return{offset:r-i,startCode:i+1};i=0;break;default:i=0}return{offset:-1,startCode:0}}decodeVideoFrame(e,t){return Sr(this,void 0,void 0,(function*(){if(!this.isEmptyFrame(e)){if(this.options.onVideoEncodeDataPipe)try{const t=yield this.options.onVideoEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){he.error("decodeVideoFrame fail, "+at(e))}const t=new Uint8Array(e.data);let i=0,r=-1;for(;(r=this.getNextSEIStart(t,i))>-1;){if(i=this.getNextNaluStart(t,r+3).offset,!(i>-1)){this.decodeSEINalu(t.slice(r));break}this.decodeSEINalu(t.slice(r,i))}}t.enqueue(e)}))}decodeAudioFrame(e,t){return Sr(this,void 0,void 0,(function*(){if(!this.isEmptyFrame(e)&&this.options.onAudioEncodeDataPipe)try{const t=yield this.options.onAudioEncodeDataPipe(e);o.b(t)&&(e.data=t)}catch(e){he.error("decodeVideoFrame fail, "+at(e))}t.enqueue(e)}))}start(e){this.abort=new AbortController,this.transports=e;let t=!1,i=!1;ge(e,(e=>{const r=e.createEncodedStreams();e.track.kind===Ui.VIDEO?!this.options.enableSEI&&!this.options.onVideoEncodeDataPipe||t?r.readable.pipeTo(r.writable,{signal:this.abort.signal}):(t=!0,this.transformStreamVideo=new TransformStream({transform:this.options.send?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)}),r.readable.pipeThrough(this.transformStreamVideo).pipeTo(r.writable,{signal:this.abort.signal}).catch((e=>{}))):e.track.kind===Ui.AUDIO&&this.options.onAudioEncodeDataPipe&&!i?(i=!0,this.transformStreamAudio=new TransformStream({transform:this.options.send?this.encodeAudioFrame.bind(this):this.decodeAudioFrame.bind(this)}),r.readable.pipeThrough(this.transformStreamAudio).pipeTo(r.writable,{signal:this.abort.signal}).catch((e=>{}))):r.readable.pipeTo(r.writable,{signal:this.abort.signal}),this.encodeStreamMap.set(e,r)}))}stop(){if(this.abort)try{this.abort.abort("none")}catch(e){}this.abort=null,this.transformStreamVideo=null,this.transformStreamAudio=null,this.encodeStreamMap&&this.encodeStreamMap.clear(),this.ssrcCaches&&this.ssrcCaches.clear(),this.next=0}restart(){this.stop(),this.start(this.transports)}isStarting(){return!!this.abort}push(e,t){if(!this.options.enableSEI)throw new Error("not support");const i=new Uint8Array(this.encodeSEINalu(e,t||this.options.payloadType));ge(this.queue,(e=>{e.push(i),e.length>100&&e.shift()}))}setAudioEncodeDataPipe(e){this.options.onAudioEncodeDataPipe=e}setVideoEncodeDataPipe(e){this.options.onVideoEncodeDataPipe=e}destroy(){this.stop(),this.queue=null,this.encodeStreamMap=null,this.ssrcCaches=null}}function Tr(e){return function(t){if(o.a(t.media)){let i=!1;ge(t.media,(e=>{if(o.a(e.candidates)&&(i=e.candidates.some((e=>"tcp"===e.transport||"udp"===e.transport&&!li(e.ip))),i))return!1})),i&&ge(t.media,(e=>{o.a(e.candidates)&&(e.candidates=e.candidates.filter((e=>"tcp"===e.transport||"udp"===e.transport&&!li(e.ip))))}));let r=!1;ge(t.media,(e=>{if(o.a(e.candidates)&&(r=e.candidates.some((e=>"udp"===e.transport)),r))return!1})),e(r)}return t}}var Ir=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};tr("a",[{name:"rembFlags",reg:/^remb-flags:\s?(\d+)/,format:"remb-flags: %s"},{name:"packetlostScale",reg:/^packetlost-scale:\s?(\d+)/,format:"packetlost-scale: %s"}]);const Cr={acodec:"opus",vcodec:"h264",audioBitrate:40960,simulcast:1,stereo:!1,encodings:[{scale:1,bitrate:512e3,fps:15}],usePlanBSimulcast:ot.chrome&&!ot.checkVersion(ot.majorVersion,"87",!0),redAudio:!1,profile:"42e01f"};let wr;const Rr=ot.edge&&ot.checkVersion(ot.majorVersion,"79",!0)||ot.firefox&&ot.checkVersion(ot.majorVersion,"34",!0)||ot.opera&&ot.checkVersion(ot.majorVersion,"52",!0)||ot.safari&&ot.checkVersion(ot.majorVersion,"11",!0);class kr extends vi{constructor(e,t,i){if(super({client:t,type:e.type,userId:e.userId,streamId:e.streamId,videoOn:e.videoOn,audioOn:e.audioOn,videoEnable:e.videoEnable,audioEnable:e.audioEnable,audioLevelInterval:e.audioLevelInterval},i),this.options=Me({},Cr,e),this.published=!1,this.options.mediaStream){const e=this.getVideoTrack(),t=this.getAudioTrack();this.videoOn=!!e,this.videoOn?this.videoEnable=e.enabled:this.videoEnable=!1,this.audioOn=!!t,this.audioOn?this.audioEnable=t.enabled:this.audioEnable=!1}}addStream(e){const t=this.options.mediaStream;return this.options.mediaStream=e,t}getStream(){if(this.options)return this.options.mediaStream}setUserId(e){this.userId=e}isPublished(){return this.published}setEncodings(e){this.options.encodings=e,this.options.simulcast=e.length}getEncodings(){return this.options.encodings}getSimulcast(){return this.options.simulcast}processOffer(e,t={iceServers:[]}){var i;return Ir(this,void 0,void 0,(function*(){if(!this.options.mediaStream)throw new Error("not has mediaStream to publish!");e&&(this.client=e),this.oldPeer&&(this.oldPeer.destroy(),this.oldPeer=null),this.oldPeer=this.peer,this.oldPeer&&(this.oldPeer.oniceconnectionstatechange=null,this.oldPeer.onicecandidate=null,this.oldPeer.ondtlsstatechange=null),this.collector&&this.collector.destroy(),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser=null),this.peer=new Wi({iceServers:null!==(i=t.iceServers)&&void 0!==i?i:[],rtcpMuxPolicy:"require",encodedInsertableStreams:this.hasEncodedDataProcesser(t)}),this.isMsSupportDatachannel&&this.peer.createChannel(),this.handlerEvent(),this.peer.addStream(this.options.mediaStream,this.options.encodings,this.options.audioBitrate);let r=yield this.peer.offer(),n=0;for(let e=0;e<this.options.encodings.length;e++)n+=this.options.encodings[e].bitrate;return this.options.encodings.length>1&&(n=Math.ceil(1.2*n)),r=mr(pr(this.options.acodec,Ui.AUDIO),pr(this.options.vcodec,Ui.VIDEO,this.options.profile),Ji(Math.ceil(this.options.audioBitrate/1024),Ui.AUDIO),Ji(Math.ceil(n/1024),Ui.VIDEO),zi(xi.SEND_ONLY),this.options.stereo?Xi(Ui.AUDIO,"stereo",1,this.options.acodec):null,this.options.stereo?Xi(Ui.AUDIO,"sprop-stereo",1,this.options.acodec):null,this.options.redAudio?Yi("urn:boom:audio-stacked-rtp",null,Ui.AUDIO):null,fr("urn:ietf:params:rtp-hdrext:sdes:mid"),qi("nack",$i.ADD,Ui.AUDIO),this.options.simulcast>1&&this.options.usePlanBSimulcast?function(e=2){return function(t){return e<2||ge(t.media,(t=>{if(t.type===Ui.VIDEO){const i=(t.ssrcs||[]).find((e=>"msid"===e.attribute));if(!i)return;const[r,n]=i.value.split(" "),s=Xe(i.id);let o;ge(t.ssrcGroups||[],(e=>{if("FID"===e.semantics){const t=e.ssrcs.split(/\s+/);if(Xe(t[0])===s)return o=Xe(t[1]),!1}}));const a=t.ssrcs.find((e=>"cname"===e.attribute));if(!a)return;const c=a.value,u=[],d=[];for(let t=0;t<e;t++)u.push(s+t),o&&d.push(o+t);t.ssrcGroups=[],t.ssrcs=[],t.ssrcGroups.push({semantics:"SIM",ssrcs:u.join(" ")});for(let e=0;e<u.length;e++)t.ssrcs.push({id:u[e],attribute:"cname",value:c}),t.ssrcs.push({id:u[e],attribute:"msid",value:`${r} ${n}`}),t.ssrcs.push({id:u[e],attribute:"label",value:n}),t.ssrcs.push({id:u[e],attribute:"mslabel",value:r});for(let e=0;e<d.length;e++){const i=u[e],s=d[e];t.ssrcs.push({id:s,attribute:"cname",value:c}),t.ssrcs.push({id:s,attribute:"msid",value:`${r} ${n}`}),t.ssrcs.push({id:s,attribute:"label",value:n}),t.ssrcs.push({id:s,attribute:"mslabel",value:r}),t.ssrcGroups.push({semantics:"FID",ssrcs:`${i} ${s}`})}he.debug("[sdpOperator planBSimulcast] simulcast: "+e)}})),t}}():null,ot.firefox&&this.options.simulcast>1?function(e){return o.a(e.media)&&ge(e.media,(e=>{e.type===Ui.VIDEO&&e.simulcast&&(delete e.ssrcs,delete e.ssrcGroups,he.debug("[sdpOperator removeSSRC]"))})),e}:null,(ot.safari||ot.wechat&&Kt.ios)&&"h264"===this.options.vcodec?function(e="640c1f",t="42e01f"){return function(i){return o.a(i.media)&&ge(i.media,(i=>{i.type===Ui.VIDEO&&(ge(i.fmtp,(i=>{i.config&&i.config.indexOf("profile-level-id="+e)>-1&&(i.config=i.config.replace(e,t))})),he.debug(`[sdpOperator profileReplace] profile: ${e}, replace: ${t}`))})),i}}("640c1f","42e01f"):null)(r),yield this.peer.setOffer(r),this.options.simulcast>1&&this.options.usePlanBSimulcast&&this.peer.setEncodings(this.options.encodings),this.collector=new Oi(this.peer.getPeerConnection(),1e3,!0,this.audioLevelInterval),this.collector.onAudioLevel=e=>{this.fire("stream-audio-level",[e])},this.logger.debug(`localstream streamId: ${this.getStreamId()}, offer: ${"\n"+r}`),r}))}processAnswer(e,t={enableSEI:!1,enableSVC:!1}){return Ir(this,void 0,void 0,(function*(){let i=!1,r=!1,n={};const s=mr(Gi(this.msmsIPs,!1),this.isMsSupportDatachannel?vr(Ui.APPLICATION,(e=>{i=e})):null,Tr((e=>{r=e})),function(e,t){return function(i){return t[e]=i[e],i}}("packetlostScale",n));if(e=s(e),t.enableSVC){let t="";e=e.replace(/scalability-mode=([A-Z0-9_]{4,});?/g,(e=>(t=e.split("=")[1].replace(/^S/,"L").replace(/T[4-9]/,"T3"),"scalability-mode="+t))),t&&(";"===t[t.length-1]&&(t=t.slice(0,t.length-1)),this.peer.setScalabilityMode(t))}if(!i&&this.isMsSupportDatachannel)throw this.isMsSupportDatachannel=!1,this.logger.error(`msms ${this.getMsmsIP()} not support datachannel, should retry, localstream streamId: ${this.getStreamId()}`),new Error("msms not support datachannel, should retry");this.logger.debug(`localstream streamId: ${this.getStreamId()}, answer: ${"\n"+e}`),yield this.peer.setAnwser(e),this.oldPeer&&(this.oldPeer.destroy(),this.oldPeer=null),this.hasEncodedDataProcesser(t)&&(this.encodedDataProcesser=new br({send:!0,layers:this.options.simulcast||1,enableSEI:t.enableSEI&&"h264"===this.options.vcodec.toLocaleLowerCase(),enableSVC:!1,onAudioEncodeDataPipe:this.onAudioEncodeDataPipe,onVideoEncodeDataPipe:this.onVideoEncodeDataPipe}),this.encodedDataProcesser.start(this.peer.getSenders())),r&&this.startDtlsConnectionTimeout(),n.packetlostScale&&this.collector&&this.collector.setUploadPacketLostScale(Xe(n.packetlostScale,1))}))}muteVideo(){return Ir(this,void 0,void 0,(function*(){this.hasVideo()&&this.getVideoEnable()&&(Rr?(this.emptyVideoTrack||(this.emptyVideoTrack=function(){let e=document.createElement("canvas");return!!e.captureStream&&e.captureStream().getTracks()[0]}()),this.emptyVideoTrack?(this.sourceVideoTrack=yield this.replaceTrack(this.emptyVideoTrack),this.sourceVideoTrack.enabled=!1,this.emptyVideoTrack.enabled=!1):this.getVideoTrack().enabled=!1):this.getVideoTrack().enabled=!1,this.videoEnable=!1,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{video_enable:!1},"videoEnableControl_"+this.streamId)),this.logger.info("localstream muteVideo"))}))}unmuteVideo(){return Ir(this,void 0,void 0,(function*(){this.hasVideo()&&!this.getVideoEnable()&&(Rr&&this.sourceVideoTrack?(yield this.replaceTrack(this.sourceVideoTrack,!0),this.sourceVideoTrack.enabled=!0,this.emptyVideoTrack&&(this.emptyVideoTrack.enabled=!0),this.sourceVideoTrack=null):this.getVideoTrack().enabled=!0,this.videoEnable=!0,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{video_enable:!0},"videoEnableControl_"+this.streamId)),this.logger.info("localstream unmuteVideo"))}))}muteAudio(){return Ir(this,void 0,void 0,(function*(){this.hasAudio()&&this.getAudioEnable()&&(Rr?(this.emptyAudioTrack||(this.emptyAudioTrack=function(){let e=wr||(AudioContext?(wr=new AudioContext,wr):void 0);return!!e&&e.createMediaStreamDestination().stream.getAudioTracks()[0]}()),this.emptyAudioTrack?(this.sourceAudioTrack=yield this.replaceTrack(this.emptyAudioTrack),this.sourceAudioTrack.enabled=!1,this.emptyAudioTrack.enabled=!1):this.getAudioTrack().enabled=!1):this.getAudioTrack().enabled=!1,this.audioEnable=!1,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{audio_enable:!1},"audioEnableControl_"+this.streamId)),this.logger.info("localstream muteAudio"))}))}unmuteAudio(){return Ir(this,void 0,void 0,(function*(){this.hasAudio()&&!this.getAudioEnable()&&(Rr&&this.sourceAudioTrack?(yield this.replaceTrack(this.sourceAudioTrack,!0),this.sourceAudioTrack.enabled=!0,this.emptyAudioTrack&&(this.emptyAudioTrack.enabled=!0),this.sourceAudioTrack=null):this.getAudioTrack().enabled=!0,this.audioEnable=!0,this.peer&&this.published&&this.client&&(yield this.client.updateStream(this,{audio_enable:!0},"audioEnableControl_"+this.streamId)),this.logger.info("localstream unmuteAudio"))}))}getSourceVideoTrack(){return this.sourceVideoTrack}getSourceAudioTrack(){return this.sourceAudioTrack}addTrack(){return Ir(this,void 0,void 0,(function*(){}))}removeTrack(){return Ir(this,void 0,void 0,(function*(){}))}replaceTrack(e,t=!1){return Ir(this,void 0,void 0,(function*(){const i="video"===e.kind;let r;const n=i?this.getVideoTrack():this.getAudioTrack();if(i&&!this.getVideoEnable()&&!t&&this.sourceVideoTrack)r=this.sourceVideoTrack,this.sourceVideoTrack=e,e.enabled=this.getVideoEnable();else if(i||this.getAudioEnable()||t||!this.sourceAudioTrack){if(r=n,this.peer)yield this.peer.replaceTrack(e);else{const t=this.getStream();t.removeTrack(n),t.addTrack(e)}e.enabled=r.enabled}else r=this.sourceAudioTrack,this.sourceAudioTrack=e,e.enabled=this.getAudioEnable();const s={};return"audio"===e.kind?s.audio=e:"video"===e.kind&&(s.video=e),this.fire("stream-replaced",[s]),this.logger.info(`LocalStream replaceTrack, streamId: ${this.getStreamId()}, kind: ${e.kind}, label: ${e.label}, force: ${t}`),r}))}destroy(e=!0){if(this.logger.info(`localStream destroy, streamId: ${this.getStreamId()}, stopTrack: ${e}`),e){const e=this.getVideoTrack(),t=this.getAudioTrack();e&&e.stop(),t&&t.stop(),this.sourceVideoTrack&&this.sourceVideoTrack!==e&&this.sourceVideoTrack.stop(),this.emptyVideoTrack&&this.emptyVideoTrack!==e&&this.emptyVideoTrack.stop(),this.sourceAudioTrack&&this.sourceAudioTrack!==t&&this.sourceAudioTrack.stop(),this.emptyAudioTrack&&this.emptyAudioTrack!==t&&this.emptyAudioTrack.stop()}else this.emptyVideoTrack&&this.emptyVideoTrack.stop(),this.emptyAudioTrack&&this.emptyAudioTrack.stop();this.oldPeer&&(this.oldPeer.destroy(),this.oldPeer=null),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser.destroy()),this.close(),this.options=null,this.emptyVideoTrack=null,this.sourceVideoTrack=null,this.emptyAudioTrack=null,this.sourceAudioTrack=null,this.destroyed=!0,this.off()}getOptions(){return this.options}validStreamType(e){return e===At.CAMERA?At.CAMERA:e===At.SCREEN?At.SCREEN:e===At.FILE?At.FILE:At.CAMERA}setOptions(e){Me(this.options,e),e.type&&(this.type=this.validStreamType(e.type))}getVideoEnable(){const e=this.getVideoTrack();return!!e&&e.enabled}getAudioEnable(){const e=this.getAudioTrack();return!!e&&e.enabled}resetEncodings(e){return Ir(this,void 0,void 0,(function*(){if(e.length!==this.options.encodings.length)throw this.logger.error(`the length of encodings must be equals before, encodings: ${JSON.stringify(e)}, before: ${JSON.stringify(this.options.encodings)}`),new Error("the length of encodings must be equals before");for(let t=0;t<e.length;t++)Me(this.options.encodings[t],e[t]);if(this.peer){this.peer.setEncodings(this.options.encodings);let e=this.options.encodings.reduce(((e,t)=>e+Math.ceil(t.bitrate/1e3)),0);const t=dr(this.peer.getRemoteSessionDescriptor().sdp);if(ge(t.media,(t=>{var i;"video"===t.type&&((null===(i=t.bandwidth[0])||void 0===i?void 0:i.limit)&&(t.bandwidth[0].limit=e),ge(t.fmtp,(t=>{t.config.indexOf("x-google-max-bitrate")>-1&&(t.config=t.config.split(";").map((t=>t.indexOf("x-google-max-bitrate")>-1?"x-google-max-bitrate="+e:t.indexOf("x-google-start-bitrate")>-1?"x-google-start-bitrate="+e:t.indexOf("x-google-min-bitrate")>-1?"x-google-min-bitrate="+Math.floor(.8*e):t)).join(";"))})))})),yield this.peer.resetAnswer(lr(t)),this.peer&&this.published){const t={videoAS:e};let i=-1,r=-1,n=-1;for(let e=0;e<this.options.encodings.length;e++)i<this.options.encodings[e].width&&(i=this.options.encodings[e].width,n=this.options.encodings[e].fps),r<this.options.encodings[e].height&&(r=this.options.encodings[e].height);this.hasAudio()&&o.f(this.options.audioBitrate)&&(e+=Math.ceil(this.options.audioBitrate/1e3),t.audioAS=Math.ceil(this.options.audioBitrate/1e3)),yield this.request("setrate",Object.assign(Object.assign({rate:e},t),{width:i,height:r,fps:n}))}}}))}sendSEIMessage(e,t){if(this.encodedDataProcesser)return this.encodedDataProcesser.push(e,t);throw new Error("not support")}}class Ar{constructor(e=5){this.count=e,this.audioBytesArray=[],this.videoBytesArray=[]}addData(e,t){this.audioBytesArray.push(e),this.audioBytesArray.length>this.count&&this.audioBytesArray.shift(),this.videoBytesArray.push(t),this.videoBytesArray.length>this.count&&this.videoBytesArray.shift()}judgeAudioMuted(){if(this.audioBytesArray.length===this.count){for(let e=0;e<this.count;e++)if(0!==this.audioBytesArray[e])return!1;return!0}return!1}judgeVideoMuted(){if(this.videoBytesArray.length===this.count){for(let e=0;e<this.count;e++)if(0!==this.videoBytesArray[e])return!1;return!0}return!1}resetVideo(){this.videoBytesArray=[]}resetAudio(){this.audioBytesArray=[]}destroy(){this.audioBytesArray=[],this.videoBytesArray=[]}}var Mr=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class Or extends ht{constructor(e,t){super(ht.STREAM_TYPE_LOCAL,t),this.streamDeviceOption=e,this.videoProfile="480p",this.audioProfile="standard",this.screenProfile="1080p",e.screen?(this.streamCodecOption=Oe(jt["1080p"],!0),this.streamCodecOption.width=null,this.streamCodecOption.height=null):this.streamCodecOption=Oe(Vt["480p"],!0),this.muteDetect=new Ar,this.muteDetectAudioMuted=!1,this.muteDetectVideoMuted=!1,this.log(`${this.sid} create LocalStream, userId: ${this.uid}, options: ${JSON.stringify(e)}`,he.DEBUG,"stream")}constraintBitrate(){let e,t=this.streamCodecOption.width*this.streamCodecOption.height;t&&o.f(t)&&(ke(Ht,((i,r)=>{if(t<=+r)return e=i,!1})),e&&(this.streamCodecOption.bitrate<e.min&&(this.streamCodecOption.bitrate=e.min),this.streamCodecOption.bitrate>e.max&&(this.streamCodecOption.bitrate=e.max)))}applyConstraint(){var e;const t=null===(e=this.client)||void 0===e?void 0:e.getClient(),i=this.getVideoTrack();if(i){const e=i.getConstraints();if(e.width=this.streamCodecOption.width,e.height=this.streamCodecOption.height,e.frameRate=this.streamCodecOption.frameRate,i.applyConstraints(e),t)if(a(this.webrtcType)){const e=this.client.getEncodings(this);this.stream.resetEncodings(e)}else c(this.webrtcType)&&t.setVideoProfile({bitrate:this.streamCodecOption.bitrate})}}setPrivileges(e){this.privileges=e}isScreenStream(){return!!this.streamDeviceOption.screen}setVideoProfile(e){this.videoProfile=e,Me(this.streamCodecOption,Vt[e]||{}),this.applyConstraint(),this.log(`${this.sid} LocalStream setVideoProfile, userId: ${this.uid}, profile: ${e}`,he.INFO,"stream")}setScreenProfile(e){this.screenProfile=e,Me(this.streamCodecOption,jt[e]||{}),this.log(`${this.sid} LocalStream setScreenProfile, userId: ${this.uid}, profile: ${e}`,he.INFO,"stream")}setAudioProfile(e){this.audioProfile=e,this.log(`${this.sid} LocalStream setAudioProfile, userId: ${this.uid}, profile: ${e}`,he.INFO,"stream")}setVideoEncoderConfiguration(e){if(ke(e,((t,i)=>{if("profile"===i){if(!o.i(t))throw new C(1001,i+" 的值不是 string 类型")}else{if(!o.f(t))throw new C(1001,i+" 的值不是 number 类型");if(t<=0)throw new C(1001,i+" 的值非法,必须是大于 0 的整数");e[i]=Math.floor(t)}})),Me(this.streamCodecOption,e),this.streamCodecOption.width*this.streamCodecOption.height>8294400)throw this.streamCodecOption=Oe(Vt["480p"],!0),new C(1001,"暂不支持4k以上分辨率");this.constraintBitrate(),this.applyConstraint(),this.log(`${this.sid} LocalStream setVideoEncoderConfiguration, userId: ${this.uid}, options: ${JSON.stringify(e)}`,he.INFO,"stream")}getAudioBandwidth(){return Ft[this.webrtcType||0][this.audioProfile].bitrate}init(){var e;return Mr(this,void 0,void 0,(function*(){let t,i=S();o.f(i)||(i=0);let r=Ft[i],n=new MediaStream;if(this.streamDeviceOption.audioSource||this.streamDeviceOption.videoSource)this.streamDeviceOption.audioSource?(n.addTrack(this.streamDeviceOption.audioSource),this.streamDeviceOption.audio=!0):this.streamDeviceOption.audio=!1,this.streamDeviceOption.videoSource?(n.addTrack(this.streamDeviceOption.videoSource),this.streamDeviceOption.video=!0):this.streamDeviceOption.video=!1;else{let e;this.streamDeviceOption.screen?e={screen:!0,audio:this.streamDeviceOption.audio,width:this.streamCodecOption.width,height:this.streamCodecOption.height,fps:this.streamCodecOption.frameRate}:(e={audio:!1,video:!1,fps:this.streamCodecOption.frameRate},this.streamDeviceOption.video&&(e.video={width:{ideal:this.streamCodecOption.width,max:this.streamCodecOption.width},height:{ideal:this.streamCodecOption.height,max:this.streamCodecOption.height},deviceId:this.streamDeviceOption.cameraId,frameRate:this.streamCodecOption.frameRate}),this.streamDeviceOption.audio&&(e.audio={deviceId:this.streamDeviceOption.microphoneId,echoCancellation:!0,channelCount:r[this.audioProfile].channelCount},o.c(this.streamDeviceOption.autoGainControl)&&(e.audio.autoGainControl=this.streamDeviceOption.autoGainControl),o.c(this.streamDeviceOption.echoCancellation)&&(e.audio.echoCancellation=this.streamDeviceOption.echoCancellation),o.c(this.streamDeviceOption.noiseSuppression)&&(e.audio.noiseSuppression=this.streamDeviceOption.noiseSuppression))),n=yield Zt(e)}if(a(i))t=new kr({type:this.streamDeviceOption.type,userId:Object(Be.a)(this.uid),streamId:this.sid,mediaStream:n,audioOn:this.streamDeviceOption.audio,videoOn:this.streamDeviceOption.video,usePlanBSimulcast:!(ot.firefox||ot.chrome&&ot.checkVersion(ot.majorVersion,"86"))||_,profile:null!==(e=this.streamCodecOption.profile)&&void 0!==e?e:"42e01f",stereo:/stereo/.test(this.audioProfile)});else if(c(i)){let e={};(this.streamDeviceOption.video||this.streamDeviceOption.screen)&&(e.videoSource=n.getVideoTracks()[0]),this.streamDeviceOption.audio&&(e.audioSource=n.getAudioTracks()[0]),t=yt.a.createStream(e),t.setAudioProfile(this.audioProfile),t.setVideoProfile(this.streamCodecOption),yield t.initialize()}this.log(`${this.sid} LocalStream init success, userId: ${this.uid}, streamDeviceOption: ${JSON.stringify(this.streamDeviceOption)}, streamCodecOption: ${JSON.stringify(this.streamCodecOption)}, audioProfile: ${this.audioProfile}`,he.INFO,"stream"),this.setStream(i,t),this.soundMeter&&(yield this.soundMeter.ready()),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint),this.setVolumeMeter()}))}setVideoHint(e){this.streamDeviceOption.videoHint=e;const t=this.getVideoTrack();t&&(t.contentHint=this.streamDeviceOption.videoHint)}setAudioHint(e){this.streamDeviceOption.audioHint=e;const t=this.getAudioTrack();t&&(t.contentHint=this.streamDeviceOption.audioHint)}switchWebRTC(e){return Mr(this,void 0,void 0,(function*(){if(this.webrtcType!==e&&c(e)){const t=Ft[e],i=this.audioTrack,r=this.videoTrack;let n=null,s=null;a(this.webrtcType)&&(n=this.stream.getSourceAudioTrack(),s=this.stream.getSourceVideoTrack());let o={videoSource:s||r,audioSource:n||i},c=yt.a.createStream(o);c.setAudioProfile(t[this.audioProfile]),c.setVideoProfile(this.streamCodecOption),yield c.initialize(),this.log(`${this.sid} LocalStream switch success, userId: ${this.uid}`,he.DEBUG,"stream"),this.stream.destroy(!1),this.setStream(e,c),s&&s!==r&&this.fire(re,{type:"video",track:s}),n&&n!==i&&this.fire(re,{type:"audio",track:n})}}))}addTrack(e){return Mr(this,void 0,void 0,(function*(){if(this.privileges&&this.privileges.enableAuth()){if(d(e)&&!this.privileges.canPushAudio())throw new C(1011,"没有音频推送权限");if(u(e)&&!this.privileges.canPushVideo())throw new C(1012,"没有视频推送权限")}if(!this.stream)throw new C(1002,"流未初始化");if(d(e)&&this.hasAudio())throw new C(1002,"当前已有一个 audioTrack");if(u(e)&&this.hasVideo())throw new C(1002,"当前已有一个 videoTrack");try{yield this.stream.addTrack(e),d(e)?(this.addAudioTrackEvents(),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint)):u(e)&&(this.addVideoTrackEvents(),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint)),this.log(`${this.sid} LocalStream addTrack, userId: ${this.uid}`,he.DEBUG,"stream")}catch(e){throw new C(9e3,"addTrack 失败",e)}}))}removeTrack(e){return Mr(this,void 0,void 0,(function*(){if(!this.stream)throw new C(1002,"流未初始化");if(d(e)&&!this.hasAudio())throw new C(1002,"当前没有 audioTrack 可以移除");if(u(e)&&!this.hasVideo())throw new C(1002,"当前没有 videoTrack 可以移除");d(e)?this.removeAudioTrackEvents():u(e)&&this.removeVideoTrackEvents();try{yield this.stream.removeTrack(e),this.log(`${this.sid} LocalStream removeTrack, userId: ${this.uid}`,he.DEBUG,"stream")}catch(e){throw new C(9e3,"removeTrack 失败",e)}}))}replaceTrack(e,t=!1){return Mr(this,void 0,void 0,(function*(){if(!(e instanceof MediaStreamTrack||t))throw new C(1002,"参数 track 不是 MediaStreamTrack 实例");if(!this.stream)throw new C(1002,"流未初始化");if(d(e)){if(!this.hasAudio())throw new C(1002,"流没有 audioTrack");this.removeAudioTrackEvents()}else if(u(e)){if(!this.hasVideo())throw new C(1002,"流没有 videoTrack");this.removeVideoTrackEvents()}(a(this.webrtcType)||c(this.webrtcType))&&(yield this.stream.replaceTrack(e)),d(e)?(this.addAudioTrackEvents(),this.setVolumeMeter(),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint),this.muteDetectAudioMuted=!1,this.muteDetect.resetAudio()):u(e)&&(this.addVideoTrackEvents(),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint),this.muteDetectVideoMuted=!1,this.muteDetect.resetVideo()),this.fire(re,{type:e.kind,track:e}),this.log(`${this.sid} LocalStream replaceTrack, userId: ${this.uid}`,he.DEBUG,"stream")}))}switchDevice(e,t){return Mr(this,void 0,void 0,(function*(){if(!o.i(t))throw new C(1001,"deviceId 类型错误");if("audio"===e&&!this.streamDeviceOption.microphoneId)throw new C(1002,"当前的 audioTrack 不是来自于麦克风设备");if("video"===e&&!this.streamDeviceOption.cameraId)throw new C(1002,"当前的 videoTrack 不是来自于摄像头设备");if(!this.stream)throw new C(1002,"流未初始化");{let i,r;if("audio"===e){let e=S();o.f(e)||(e=0);const n={deviceId:t,echoCancellation:!0,channelCount:Ft[e][this.audioProfile].channelCount};o.c(this.streamDeviceOption.autoGainControl)&&(n.autoGainControl=this.streamDeviceOption.autoGainControl),o.c(this.streamDeviceOption.echoCancellation)&&(n.echoCancellation=this.streamDeviceOption.echoCancellation),o.c(this.streamDeviceOption.noiseSuppression)&&(n.noiseSuppression=this.streamDeviceOption.noiseSuppression);const s=yield Zt({audio:n,video:!1});this.streamDeviceOption.microphoneId=t,i=s.getAudioTracks()[0],r=this.getAudioTrack(),this.reportAction("deviceChange",0,null,null,{type:"microphone",device_id:t,stream:this.getActionStreamId()})}else if("video"===e){const e=yield Zt({audio:!1,video:{width:this.streamCodecOption.width,height:this.streamCodecOption.height,deviceId:t},fps:this.streamCodecOption.frameRate});this.streamDeviceOption.cameraId=t,i=e.getVideoTracks()[0],r=this.getVideoTrack(),this.reportAction("deviceChange",0,null,null,{type:"camera",device_id:t,stream:this.getActionStreamId()})}"audio"===e?this.removeAudioTrackEvents():"video"===e&&this.removeVideoTrackEvents(),yield this.replaceTrack(i),r&&r.stop(),"audio"===e?(this.addAudioTrackEvents(),this.streamDeviceOption.audioHint&&this.setAudioHint(this.streamDeviceOption.audioHint),this.muteDetectAudioMuted=!1,this.muteDetect.resetAudio()):"video"===e&&(this.addVideoTrackEvents(),this.streamDeviceOption.videoHint&&this.setVideoHint(this.streamDeviceOption.videoHint),this.muteDetectVideoMuted=!1,this.muteDetect.resetVideo()),this.playing&&this.player&&("audio"===e?this.player.replay(this,!1,!0):"video"===e&&this.player.replay(this,!0,!1)),this.log(`${this.sid} LocalStream switchDevice, userId: ${this.uid}, type: ${e}, deviceId: ${t}`,he.DEBUG,"stream")}}))}play(e,t={}){const i=Object.create(null,{play:{get:()=>super.play}});return Mr(this,void 0,void 0,(function*(){t.muted=!0,yield i.play.call(this,e,t)}))}getStats(){var e;return Mr(this,void 0,void 0,(function*(){const t=null===(e=this.client)||void 0===e?void 0:e.getClient();if(t){if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),i=this.getVideoRTPStats(e);return{videoBytesSent:Le(i,"statistics.bytesSent",0),videoPacketsSent:Le(i,"statistics.packetsSent",0),videoPacketsLost:Le(i,"statistics.packetsLost",0),videoNacksCount:Le(i,"statistics.googNacksReceived",0),audioBytesSent:Le(t,"statistics.bytesSent",0),audioPacketsSent:Le(t,"statistics.packetsSent",0),audioPacketsLost:Le(t,"statistics.packetsLost",0),audioNacksCount:Le(t,"statistics.googNacksReceived",0),width:Le(i,"resolution.width",0),height:Le(i,"resolution.height",0),rtt:Le(e,"transport.0.rtt",0),framesEncoded:Le(i,"statistics.framesEncoded",0),framesSent:Le(i,"statistics.framesSent",0)}}if(c(this.webrtcType)){let e=yield t.getLocalVideoStats();if(!this.client)throw new C(1010,"已被取消推流");let i=yield t.getLocalAudioStats();if(!this.client)throw new C(1010,"已被取消推流");let r=yield t.getTransportStats(),n=e[this.uid],s=i[this.uid];return{videoBytesSent:Le(n,"bytesSent",0),videoPacketsSent:Le(n,"packetsSent",0),videoPacketsLost:Le(n,"packetsLost",0),videoNacksCount:0,audioBytesSent:Le(s,"bytesSent",0),audioPacketsSent:Le(s,"packetsSent",0),audioPacketsLost:Le(s,"packetsLost",0),audioNacksCount:0,width:Le(n,"frameWidth",0),height:Le(n,"frameHeight",0),rtt:Le(r,"rtt",0),framesEncoded:Le(n,"framesEncoded",0),framesSent:Le(n,"framesSent",0)}}}return{}}))}getReportStats(e){var t;return Mr(this,void 0,void 0,(function*(){this.stutter||(this.stutter=new gt(e,!0));let i={bandwidth:{upload:0,download:0},bitrate:{audio:{upload:0,download:0},video:{upload:0,download:0}},packetLoss:{audio:{upload:0,download:0},video:{upload:0,download:0}},resolution:{width:0,height:0},framerate:0,audioLevel:0,transport:[{ip:"",type:"",localIp:"",localCandidateType:"",remoteCandidateType:"",networkType:"",rtt:0}],quality:{audio:{jitter:0,interruptionCount:0,interruptionDuration:0},video:{jitter:0,interruptionCount:0,interruptionDuration:0}},statistics:{audio:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0},video:{bytesReceived:0,bytesSent:0,packetsReceived:0,packetsSent:0,packetsLost:0,framesEncoded:0,framesDecoded:0,framesSent:0},bweforvideo:{googAvailableReceiveBandwidth:0,googAvailableSendBandwidth:0,googRetransmitBitrate:0,googTransmitBitrate:0,googTargetEncBitrate:0},ice:{packetsSent:0,packetsReceived:0,bytesSent:0,bytesReceived:0,requestsSent:0,responsesReceived:0}},cpu:{appCpu:0,systemCpu:0}};const r=null===(t=this.client)||void 0===t?void 0:t.getClient();if(r){if(a(this.webrtcType)){let e=this.stream.getStats();const t=this.getAudioRTPStats(e),r=this.getVideoRTPStats(e);i.audioLevel=this.getAudioLevel(),e.bandwidth&&(i.bandwidth=e.bandwidth),e.bitrate&&(i.bitrate=e.bitrate),e.packetLoss&&(i.packetLoss=e.packetLoss),e.transport&&(i.transport=e.transport),e.bweforvideo&&(i.statistics.bweforvideo={googAvailableReceiveBandwidth:e.bweforvideo.availableReceiveBandwidth,googAvailableSendBandwidth:e.bweforvideo.availableSendBandwidth,googRetransmitBitrate:e.bweforvideo.retransmitBitrate,googTransmitBitrate:e.bweforvideo.transmitBitrate,googTargetEncBitrate:e.bweforvideo.targetEncBitrate}),e.ice&&(i.statistics.ice=e.ice),t&&(i.quality.audio=t.qa,i.statistics.audio=t.statistics),r&&(i.quality.video=r.qa,i.statistics.video=r.statistics,i.resolution=r.resolution,i.framerate=r.framerate),this.stutter.addFrameRate(Le(i,"framerate",0)),this.stutter.addVideoLoss(Le(i,"statistics.video.packetsSent",0),Le(i,"statistics.video.packetsLost",0)),this.stutter.addAudioLoss(Le(i,"statistics.audio.packetsSent",0),Le(i,"statistics.audio.packetsLost",0)),this.muteDetect.addData(i.bitrate.audio.upload,i.bitrate.video.upload)}else{let e=yield r.getLocalVideoStats();if(!this.client)throw new C(1010,"已被取消推流");let t=yield r.getLocalAudioStats();if(!this.client)throw new C(1010,"已被取消推流");let n=yield r.getTransportStats(),s=e[this.uid],o=t[this.uid];this.reportCollector.addData(Le(o,"bytesSent",0),Le(s,"bytesSent",0),Le(o,"packetsSent",0),0,Le(s,"packetsSent",0),0,Le(s,"framesEncoded",0)),i.bitrate.audio.upload=this.reportCollector.getAudioBitrate(),i.bitrate.video.upload=this.reportCollector.getVideoBitrate(),i.packetLoss.audio.upload=this.reportCollector.getAudioPacketLoss(),i.packetLoss.video.upload=this.reportCollector.getVideoPacketLoss(),i.audioLevel=this.getAudioLevel(),i.framerate=this.reportCollector.getFrameRate(),i.resolution.width=Le(s,"frameWidth",0),i.resolution.height=Le(s,"frameHeight",0),i.transport[0].rtt=Le(n,"rtt",0),i.bandwidth.upload=this.reportCollector.getAudioBitrate()+this.reportCollector.getVideoBitrate(),i.statistics.audio.bytesSent=Le(o,"bytesSent",0),i.statistics.audio.packetsSent=Le(o,"packetsSent",0),i.statistics.video.bytesSent=Le(s,"bytesSent",0),i.statistics.video.packetsSent=Le(s,"packetsSent",0),i.statistics.video.framesSent=Le(s,"framesSent",0),i.statistics.video.framesEncoded=Le(s,"framesEncoded",0),this.stutter.addFrameRate(Le(i,"framerate",0)),this.stutter.addVideoLoss(Le(i,"statistics.video.packetsSent",0),Le(i,"statistics.video.packetsLost",0)),this.stutter.addAudioLoss(Le(i,"statistics.audio.packetsSent",0),Le(i,"statistics.audio.packetsLost",0)),ot.newEdge&&ot.checkVersion(ot.majorVersion,"112",!0)||this.muteDetect.addData(i.bitrate.audio.upload,i.bitrate.video.upload)}if(this.hasAudio()&&this.getAudioOn()&&a(this.webrtcType)&&this.stream.isConnected()){const e=this.muteDetect.judgeAudioMuted();e&&!this.muteDetectAudioMuted?(this.muteDetectAudioMuted=!0,this.fire(ee),this.log(`${this.sid} Stream audioTrack detect mute, userId: ${this.uid}`,he.WARN,"stream")):!e&&this.muteDetectAudioMuted&&(this.muteDetectAudioMuted=!1,this.fire(ie),this.log(`${this.sid} Stream audioTrack detect unmute, userId: ${this.uid}`,he.WARN,"stream"))}if(this.hasVideo()&&this.getVideoOn()&&a(this.webrtcType)&&this.stream.isConnected()){const e=this.muteDetect.judgeVideoMuted();e&&!this.muteDetectVideoMuted?(this.muteDetectVideoMuted=!0,this.fire(Z),this.log(`${this.sid} Stream videoTrack detect mute, userId: ${this.uid}`,he.WARN,"stream")):!e&&this.muteDetectVideoMuted&&(this.muteDetectVideoMuted=!1,this.fire(te),this.log(`${this.sid} Stream videoTrack detect unmute, userId: ${this.uid}`,he.WARN,"stream"))}}return i}))}unmuteVideo(){const e=Object.create(null,{unmuteVideo:{get:()=>super.unmuteVideo}});return Mr(this,void 0,void 0,(function*(){return this.muteDetectVideoMuted=!1,Object(J.a)((()=>{const e=this.getVideoTrack();e&&e.muted&&this.fire(Z)})),e.unmuteVideo.call(this)}))}unmuteAudio(){const e=Object.create(null,{unmuteAudio:{get:()=>super.unmuteAudio}});return Mr(this,void 0,void 0,(function*(){return this.muteDetectAudioMuted=!1,Object(J.a)((()=>{const e=this.getAudioTrack();e&&e.muted&&this.fire(ee)})),e.unmuteAudio.call(this)}))}getExtraReport(){if(this.stutter){const e=this.stutter.judgeAudioStutter(),t=this.stutter.judegVideoStutter();return{event:e||t?1:0,audio_stutter:this.getAudioOn()&&e?1:0,video_stutter:this.getVideoOn()&&t?1:0,blockOp:0}}}getStreamCodecOption(){return this.streamCodecOption}destroy(){this.stream&&(this.videoTrack&&this.videoTrack.stop(),this.audioTrack&&this.audioTrack.stop(),super.destroy()),this.muteDetect&&this.muteDetect.destroy()}getSourceVideoTrack(){return a(this.webrtcType)&&this.stream.getSourceVideoTrack()||this.getVideoTrack()}getSourceAudioTrack(){return a(this.webrtcType)&&this.stream.getSourceAudioTrack()||this.getAudioTrack()}sendSEIMessage(e,t={}){var i,r,n;if(a(this.webrtcType))this.stream.sendSEIMessage(e,null!==(i=t.payloadType)&&void 0!==i?i:243);else if(c(this.webrtcType)){const i=null===(r=this.client)||void 0===r?void 0:r.getClient();if(i)try{i.sendSEIMessage(e,{seiPayloadType:null!==(n=t.payloadType)&&void 0!==n?n:243})}catch(e){throw new C(1002,at(e),e)}}}}!function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);s>3&&o&&Object.defineProperty(t,i,o)}([function(e,t,i,r){return function(n,s,a){let c=a.value;const u=[];return a.value=function(){const n=z(),a=be(arguments),d=e(n,u,a);if(0==d)return u.push(t(n,a)),u.length>i&&u.shift(),q(c,this,a);throw o.i(d)&&(r=d),new C(1002,`${s} ${null!=r?r:"方法执行超出频率限制"}`)},a}}(((e,t,i)=>{if(i[0].byteLength>1e3)return"单次最大发送 1000 Bytes";const r=t.length;if(!r)return!1;let n=Math.max(r-30,0);const s=t[n].now;if(30==r&&e-s<1e3)return"每秒最大调用次数 30 次";let o=i[0].byteLength;for(let i=r-1;i>=n;i--)if(o+=t[i].size,o>8e3)return e-t[i].now<1e3&&"每秒最多发送 8000 Bytes";return!1}),((e,t)=>({now:e,size:t[0].byteLength})),30,"单次最大发送 1000 Bytes, 每秒最大调用次数 30 次,每秒最多发送 8000 Bytes")],Or.prototype,"sendSEIMessage",null);class Lr{constructor(e){this.timeout=e}then(e,t){this.resolve=e,this.reject=t,this.startTime=Date.now(),this.timer=setTimeout((()=>{this.resolve(Date.now()-this.startTime),this.timer=null}),1e3*this.timeout)}stop(e=!0){this.timer&&(clearTimeout(this.timer),this.timer=null,this.resolve&&e?this.resolve(Date.now()-this.startTime):this.reject&&!e&&this.reject(Date.now()-this.startTime))}reset(e){e&&(this.timeout=e),this.timer&&(clearTimeout(this.timer),this.timer=setTimeout((()=>{this.resolve(Date.now()-this.startTime),this.timer=null}),1e3*this.timeout))}}let Pr,Nr;const Dr=navigator.userAgent||"";Pr=Dr.match(/NetType\/\w+/)?Dr.match(/NetType\/\w+/)[0]:"NetType/other",Pr=Pr.toLowerCase().replace("nettype/","");const xr={ethernet:"ethernet",wifi:"wifi","5g":"5g","4g":"4g","3g":"3g","3gnet":"3g","2g":"2g","slow-2g":"2g"};if(Nr=xr[Pr],!Nr){let e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;e&&(Nr=xr[e.type],Nr||(Nr=xr[e.effectiveType]))}Nr||(Nr="unknown");var Ur={name:Nr},$r=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};let Br="";function Vr(e=!1){return Br||function(e,t=!1){let i=t?"https://brtc-open.baijiayun.com":"https://brtc-api.baijiayun.com";return"development"===l?i=t?"https://brtc-opentest.baijiayun.com":"https://brtc-apitest.baijiayun.com":"beta"===l&&(i=t?"https://brtc-openbeta.baijiayun.com":"https://brtc-apibeta.baijiayun.com"),i+"/vrm/api/auth/token/vt"}(0,e)}function Fr(e){return Ki(e)||""}function jr(e,t,i=[]){return $r(this,void 0,void 0,(function*(){return new Promise(((r,n)=>{let s=0;const a=[e].concat(i),c=a.length,u=3*c;let d=0;!function i(){return $r(this,void 0,void 0,(function*(){s++;try{let i=null,n=null;AbortController&&(n=new AbortController,i=n.signal);let s=yield Promise.race([fetch(a[d%c],{body:JSON.stringify(t),cache:"no-cache",credentials:"same-origin",headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",mode:"cors",redirect:"follow",referrer:"no-referrer",signal:i}),new Lr(v())]).catch((e=>{throw e}));if(o.f(s))throw n&&n.abort(),new Error(`fetch ${e}, data: ${JSON.stringify(t)} timeout`);if(s.status>=400)throw new Error("response code: "+s.status);r(s.json())}catch(e){s<u?(yield new Lr(1),d++,i()):n(e)}}))}()}))}))}function Hr(e,t,i=[]){return $r(this,void 0,void 0,(function*(){return new Promise(((r,n)=>{let s=0;const a=[e].concat(i),c=a.length,u=3*c;let d=0;!function i(){return $r(this,void 0,void 0,(function*(){s++;try{let i=null,n=null;AbortController&&(n=new AbortController,i=n.signal);let s=yield Promise.race([fetch(`${a[d%c]}?${Fr(t)}`,{cache:"no-cache",credentials:"same-origin",headers:{Accept:"application/json","Content-Type":"application/json"},method:"GET",mode:"cors",redirect:"follow",referrer:"no-referrer",signal:i}),new Lr(v())]).catch((e=>{throw e}));if(o.f(s))throw n&&n.abort(),new Error(`fetch ${e}, data: ${JSON.stringify(t)} timeout`);if(s.status>=400)throw new Error("response code: "+s.status);r(s.json())}catch(e){s<u?(yield new Lr(1),d++,i()):n(e)}}))}()}))}))}var Wr;class Gr extends ji{constructor(e,t){if(super(),this.url=e,this.channelOptions=t,!o.d(null==t?void 0:t.processOffer))throw new Error("processOffer required");this.createChannel(this.channelOptions),this.channel.onopen=e=>{this.onopen&&q(this.onopen,this,[e])},this.channel.onclose=e=>{this.onclose&&q(this.onclose,this,[e])},this.channel.onerror=e=>{this.close(),this.onerror&&q(this.onerror,this,[e])},this.channel.onbufferedamountlow=e=>{this.channelOptions.onbufferedamountlow&&q(this.channelOptions.onbufferedamountlow,this,[e])},this.oniceconnectionstatechange=e=>{"disconnected"!==e&&"failed"!==e||this.onclose&&q(this.onclose,this,[new Event("ice "+e)])},this.connect()}connect(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){try{const e=yield this.offer({offerToReceiveAudio:!1,offerToReceiveVideo:!1});yield this.setOffer(e);const t=yield this.channelOptions.processOffer(this.url,e);yield this.setAnwser(t)}catch(e){he.error("DataChannel request answer failed"),this.close(),this.onerror&&this.onerror(e)}}))}send(e){this.channel?this.channel.send(o.i(e)||o.b(e)?e:JSON.stringify(e)):he.error("can not send data because of no channel in DataChannel")}close(){this.channel&&(this.channel.onopen=null,this.channel.onclose=null,this.channel.onerror=null,this.channel.onbufferedamountlow=null,this.channel.close(),this.channel=null),this.destroy()}clear(){this.close()}}!function(e){e[e.NONE=0]="NONE",e[e.OPEN=1]="OPEN",e[e.ERROR=2]="ERROR",e[e.CLOSE=3]="CLOSE",e[e.CLOSING=4]="CLOSING",e[e.TIMEOUT=5]="TIMEOUT",e[e.CONNECTING=6]="CONNECTING"}(Wr||(Wr={}));const qr="send";var Jr=class extends Ne{constructor(e,t){var i;super(!0),Me(this,e),this.native||(this.native=WebSocket),this.status=Wr.NONE,this.queue=[],this.isReconnect=!1,e.retryCount>0&&(this.retryIndex=0),this.logger=t||new ti,this.logLevel=null!==(i=this.logLevel)&&void 0!==i?i:this.logger.TRACE,this.connectCount=0}isOpen(){return this.status===Wr.OPEN}isConnecting(){return this.status===Wr.CONNECTING}getStatus(){return this.status}connect(e,t){const i=this;if(this.server=e,this.proxys=t,this.connectCount=0,i.status===Wr.OPEN||i.status===Wr.CONNECTING||i.status===Wr.CLOSING)return;let r=[e];t&&t.length&&(r=r.concat(t));let n=-1;const s=function(){i.nextStartTimer=null,i.status===Wr.CONNECTING?function(e,t){i.connectCount++;let r=i.nativeOptions;i.native===WebSocket&&(r=i.nativeOptions.protocols),i.logger.debug(`${i.tag||"Transport"} connecting url: ${e.url}`);const n=z(),s=new i.native(e.url,r);let a,c=function(i){a&&clearTimeout(a),s.onopen=s.onerror=null,t(s,e,i)};s.onopen=function(e){var t;i.consume=null!==(t=null==e?void 0:e.consume)&&void 0!==t?t:z()-n,c(Wr.OPEN)},s.onerror=function(){c(Wr.ERROR)},i.timeout>0&&(a=setTimeout((function(){a=null,s.onerror=null,s.onopen=null,o.d(s.close)&&s.close(),c(Wr.TIMEOUT)}),i.timeout))}(r[++n],(function(e,s,c){if(i.status===Wr.CONNECTING)if(c===Wr.OPEN){if(i.url=s.url,i.socket=e,i.status=Wr.OPEN,e.onmessage=function(e){i.status===Wr.OPEN&&(i.logger.log(`${i.tag||"Transport"} Received: ${o.i(e.data)?e.data:"binary"}`,i.logLevel),i.onReceive&&o.i(e.data)&&i.onReceive(JSON.parse(e.data)),i.onmessage&&i.onmessage(e.data),i.fire("message",[e.data]))},e.onclose=function(r){if(i.status===Wr.OPEN)if(i.connectOnClose&&i.retryCount>0){if(i.status=Wr.NONE,i.onReconnecting&&(i.onReconnecting(),i.status===Wr.CLOSING||i.status===Wr.CLOSE))return;i.fire("reconnecting"),i.isReconnect=!0,i.logger.warn((i.tag||"Transport")+" reconnecting"),e.clear&&e.clear(),i.connect(s,t)}else i.onClose&&i.onClose(r),i.fire("close",[r])},i.retryCount>0&&(i.retryIndex=0),i.onOpen&&(i.logger.debug(`${i.tag||"Transport"} ${i.isReconnect?"reconnect":"connect"} success`),i.onOpen({server:s,reconnect:i.isReconnect})),i.fire("open",[{server:s,reconnect:i.isReconnect}]),i.queue.length)for(;i.queue.length;){const t=i.queue.shift(),r=o.i(t)||o.b(t)?t:JSON.stringify(t);e.send(r),i.logger.log(`${i.tag||"Transport"} Sent: ${o.b(t)?"binary":r}`,i.logLevel),i.onSend&&i.onSend(r),i.fire(qr,[r])}}else if(n===r.length-1){if(i.retryCount>0&&i.retryIndex++<i.retryCount-1)return n=-1,void a();switch(i.status=c){case Wr.ERROR:i.logger.error(`${i.tag||"Transport"} ${i.isReconnect?"reconnect":"connect"} error`),i.onError&&i.onError({server:s}),i.fire("error",[{server:s}]);break;case Wr.TIMEOUT:i.logger.error(`${i.tag||"Transport"} ${i.isReconnect?"reconnect":"connect"} timeout`),i.onTimeout&&i.onTimeout({server:s}),i.fire("timeout",[{server:s}])}}else a();else if(i.status===Wr.CLOSING){let t=!1;if(c===Wr.OPEN&&i.refreshQueueOnClose&&i.queue.length){for(;i.queue.length;){const t=i.queue.shift(),r=o.i(t)||o.b(t)?t:JSON.stringify(t);e.send(r),i.logger.log(`${i.tag||"Transport"} Sent: ${o.b(t)?"binary":r}`,i.logLevel),i.onSend&&i.onSend(r),i.fire(qr,[r])}t=!0}t?setTimeout((()=>{e.close(),i.status=Wr.CLOSE}),1e3):(e.close(),i.status=Wr.CLOSE)}})):i.status===Wr.CLOSING&&(i.status=Wr.CLOSE)},a=function(){i.interval>0?i.nextStartTimer=setTimeout(s,i.interval):s()};i.status=Wr.CONNECTING,s()}send(e){if(this.status!==Wr.OPEN&&this.status!==Wr.CLOSING)return this.queueMax>0&&this.queue.length===this.queueMax&&this.queue.shift(),void this.queue.push(e);const t=this.socket;if(t){const i=o.i(e)||o.b(e)?e:JSON.stringify(e);t.send(i),this.logger.log(`${this.tag||"Transport"} Sent: ${o.b(e)?"binary":i}`,this.logLevel),this.onSend&&this.onSend(i),this.fire(qr,[i])}}close(){const e=this.socket;if(this.socket=null,this.status=Wr.CLOSING,e){let t=!1;if(this.refreshQueueOnClose&&this.queue.length){for(;this.queue.length;)this.send(this.queue.shift());t=!0}e.onmessage=e.onclose=null,t?setTimeout((()=>{e.close(),this.status=Wr.CLOSE}),1e3):(e.close(),this.status=Wr.CLOSE)}this.nextStartTimer&&(clearTimeout(this.nextStartTimer),this.nextStartTimer=null)}reconnect(){this.status!==Wr.CONNECTING&&(this.close(),this.status===Wr.CLOSING?setTimeout((()=>{this.status=Wr.CLOSE,this.connect(this.server,this.proxys)}),1e3):this.connect(this.server,this.proxys))}getSocket(){return this.socket}getConsume(){return Math.max(this.consume||0,0)}getConnectCount(){return this.connectCount}},zr=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};let Yr,Qr,Kr,Xr,Zr=[],en=60,tn=180,rn=10,nn=0,sn=0;const on={sniffer:function(e){const t=Q();return{result:{receiver:e,send:t,costTime:Math.max(t-e,0)}}}};function an(){!Yr||!Zr.length||nn>=rn||function(){return zr(this,void 0,void 0,(function*(){if(!Zr.length||nn>=rn)return;const e=Zr[sn++];sn>=Zr.length&&(sn=0,nn++);let t=!1;he.info("start run probe task, server: "+JSON.stringify(e));const i=new Lr(15);return Promise.race([i,new Promise(((r,n)=>{const s=new Jr({tag:`Probe ${e.address} ${e.location}`,retryCount:0,connectOnClose:!1,onClose:()=>{s.close(),Qr=null,!t&&Xr&&Xr(9002,"probe failed",e),r(0)},onError:i=>{s.close(),Qr=null,!t&&Xr&&Xr(9002,"probe failed",e),n(i)},onOpen:()=>{t=!0,i.reset(en)},native:Gr,nativeOptions:{processOffer:function(e,t){return zr(this,void 0,void 0,(function*(){return jr(e,{style:1,platform:"Web",session:{type:"offer",sdp:t}}).then((e=>{if(0===(null==e?void 0:e.code)&&e.data)return e.data.sdp}))}))},ordered:!1},logLevel:he.DEBUG});s.onmessage=e=>zr(this,void 0,void 0,(function*(){if(e&&o.i(e)){const t=Q();try{const i=JSON.parse(e);if(on[null==i?void 0:i.method]){let e=yield on[i.method](t);e=Me({id:i.id,version:"2.0"},e),s.send(JSON.stringify(e))}}catch(e){}}})),Qr=s,s.connect({url:e.address})}))]).then((i=>(Qr&&(Qr.close(),Qr=null),i&&!t&&Xr&&Xr(9002,"probe failed",e),he.info("end run probe task success, server: "+JSON.stringify(e)),i))).catch((t=>{Qr&&(Qr.close(),Qr=null),he.info("end run probe task error, server: "+JSON.stringify(e))}))}))}().then((()=>zr(this,void 0,void 0,(function*(){yield new Lr(tn),an()}))))}function cn(){Kr&&Kr().then((e=>{if(e.data){const t=e.data.urls;o.f(e.data.duration)&&(en=e.data.duration),o.f(e.data.intervalDataChannel)&&(tn=e.data.intervalDataChannel),o.f(e.data.maxLoopNum)&&(rn=e.data.maxLoopNum),o.a(t)&&(Zr=t,he.info(`run probe task, duration: ${en}, intervalDataChannel: ${tn}, maxLoopNum: ${rn}`),an())}})).catch((e=>{Yr=!1,Qr&&(Qr.close(),Qr=null),nn=0,sn=0,Zr=[]}))}function un(){return!!(ot.chrome&&ot.checkVersion(ot.majorVersion,"69")||ot.firefox&&ot.checkVersion(ot.majorVersion,"46")||ot.newEdge&&ot.checkVersion(ot.majorVersion,"80"))}const dn={heartbeat:15e3,requestTimeout:15e3,maxRetry:3,packer:oi,retryInterval:500,connectTimeout:1e4,connectOnClose:!0,requestMaxRetry:0};class ln extends Ne{constructor(e,t,i,r){var n,s;super(!0),this.server=e,this.proxys=i,this.options=Me({},dn,t),this.logger=r||new ti,this.heartbeatTimer=new ct((()=>{this.heartbeat()}),this.options.heartbeat,this.options.heartbeat),this.packer=new this.options.packer,this.transport=new Jr({native:null!==(n=this.options.transport)&&void 0!==n?n:WebSocket,onSend:e=>{this.fire("onsend",[e])},onReceive:e=>{this.fire("onreceive",[e])},onOpen:e=>{this.fire(e.reconnect?"reconnected":"connected"),this.heartbeatTimer&&this.heartbeatTimer.start()},onClose:()=>{this.fire("close"),this.heartbeatTimer&&this.heartbeatTimer.stop()},onError:()=>{this.fire("error"),this.heartbeatTimer&&this.heartbeatTimer.stop()},onTimeout:()=>{this.fire("timeout"),this.heartbeatTimer&&this.heartbeatTimer.stop()},onReconnecting:()=>{this.fire("reconnecting"),this.heartbeatTimer&&this.heartbeatTimer.stop()},connectOnClose:this.options.connectOnClose,retryCount:this.options.maxRetry,nativeOptions:null!==(s=this.options.transportOptions)&&void 0!==s?s:{},tag:this.options.tag,interval:this.options.retryInterval,timeout:this.options.connectTimeout,logLevel:this.options.logLevel},this.logger),this.rpc=new si(this.packer,this.transport,{requestTimeout:this.options.requestTimeout,responseTimeout:this.options.requestTimeout,peerId:this.options.peerId,maxRetry:this.options.requestMaxRetry},this.logger),this.rpc.on("binary",(e=>{this.fire("binary",[e])})),this.rpc.on(ii,((e,t,i)=>{this.fire(ii,[e,t,i])})),this.rpc.on("request",(e=>{this.fire("request",[e])})),Object(J.a)((()=>{this.transport&&this.transport.connect(this.server,this.proxys)}))}request(e,t={},i){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){return this.rpc.request(e,t,i)}))}reply(e,t,i){return this.rpc.reply(e,t,i)}notify(e,t={}){return this.rpc.notify(e,t)}sendBinary(e){const t=this.transport.getSocket();t&&t.send(e)}getConsume(){return this.transport?this.transport.getConsume():0}getTransportConnectCount(){return this.transport?this.transport.getConnectCount():0}getTransportStatus(){return this.transport?this.transport.getStatus():Wr.NONE}destroy(){this.off(),this.rpc&&this.rpc.destroy(),this.transport&&this.transport.close(),this.transport=null,this.rpc=null,this.packer=null,this.heartbeatTimer&&this.heartbeatTimer.destroy(),this.heartbeatTimer=null}resetRequest(){this.rpc&&this.rpc.resetRequest()}changeTransport(e){var t;this.transport&&(this.transport.onSend=this.transport.onReceive=this.transport.onOpen=this.transport.onClose=this.transport.onError=this.transport.onTimeout=this.transport.onReconnecting=null,this.transport.close(),e.onSend=e=>{this.fire("onsend",[e])},e.onReceive=e=>{this.fire("onreceive",[e])},e.onOpen=e=>{this.fire(e.reconnect?"reconnected":"connected"),this.heartbeatTimer&&this.heartbeatTimer.start()},e.onClose=()=>{this.fire("close"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.onError=()=>{this.fire("error"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.onTimeout=()=>{this.fire("timeout"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.onReconnecting=()=>{this.fire("reconnecting"),this.heartbeatTimer&&this.heartbeatTimer.stop()},e.connectOnClose=this.options.connectOnClose,e.retryCount=this.options.maxRetry,e.nativeOptions=null!==(t=this.options.transportOptions)&&void 0!==t?t:{},e.tag=this.options.tag,e.interval=this.options.retryInterval,e.timeout=this.options.connectTimeout,e.logLevel=this.options.logLevel,this.transport=e,this.rpc&&this.rpc.setTransport(e))}getLogger(){return this.logger}}var hn=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class mn extends ln{constructor(e,t,i,r){super({url:e},t,null,r),this.notified=-1,this.seq=0,this.sessionId=null,this.syncRoomLock=!1,this.retryQueue=[],this.proxy=i}resetTimeout(){this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout((()=>{this.resetTimer=null,this.fire("timeout"),this.destroy()}),4*this.options.heartbeat)}syncNotify(){return hn(this,void 0,void 0,(function*(){this.fire("session-close")}))}request(e,t,i){const r=Object.create(null,{request:{get:()=>super.request}});return hn(this,void 0,void 0,(function*(){const n=this.seq++;return this.syncRoomLock&&"syncRoom"!==e?(this.logger.warn(`session closed, waiting for sync room, method: ${e}, params: ${JSON.stringify(t)}`),new Promise(((i,r)=>{this.retryQueue.push({method:e,params:t,resolve:i,reject:r,id:n})}))):(this.syncRoomLock||"syncRoom"!==e||(this.syncRoomLock=!0),r.request.call(this,e,t,i).then((t=>(this.resetTimeout(),!this.sessionId&&t.sessionId&&(this.sessionId=t.sessionId),"syncRoom"===e&&(this.syncRoomLock=!1,this.retryQueue.length&&(this.retryQueue=this.retryQueue.filter((e=>"recover"!==e.method)),this.retryQueue.sort(((e,t)=>e.id-t.id)),ge(this.retryQueue,(e=>{e.params.sessionId=this.sessionId,this.logger.info(`retry the retryQueue request, ${e.method}, params: ${JSON.stringify(e.params)}`),this.request(e.method,e.params).then((t=>{e.resolve(t)})).catch((t=>{e.reject(t)}))})),this.retryQueue=[])),t))).catch((i=>{if("request timeout"!==at(i)&&this.resetTimeout(),99===(null==i?void 0:i.code))return this.sessionId&&this.sessionId!==t.sessionId?(this.logger.warn(`the request session has closed but the seesion is update after sync room, retry request again, ${e}, params: ${JSON.stringify(t)}`),t.sessionId=this.sessionId,this.request(e,t)):(this.syncRoomLock||(this.sessionId=null,this.syncRoomLock=!0,this.fire("session-close")),this.logger.warn(`the session has closed, push the request into retry queue, ${e}, params: ${JSON.stringify(t)}`),new Promise(((i,r)=>{this.retryQueue.push({method:e,params:t,resolve:i,reject:r,id:n})})));throw i})))}))}heartbeat(){this.request("ping",{sessionId:this.sessionId}).then((e=>{this.resetTimeout()})).catch((e=>{this.logger.error("channel heartbeat error: "+JSON.stringify(e))}))}destroy(){this.seq=null,this.notified=null,this.sessionId=null,this.retryQueue=null,this.syncRoomLock=null,this.resetTimer&&(clearTimeout(this.resetTimer),this.resetTimer=null),super.destroy()}getProxy(){return this.proxy}updateProxy(e){this.proxy=e}}var pn=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};function fn(e,t){return"application/x-www-form-urlencoded"===e?function(e){return Pe(e)||""}(t):"multipart/form-data"===e?function(e){const t=new FormData;return e&&ke(e,((e,i)=>{t.append(encodeURIComponent(i),encodeURIComponent(e))})),t}(t):JSON.stringify(t)}function vn(e,t,i,r={}){return pn(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{let a=0;!function c(){return pn(this,void 0,void 0,(function*(){a++;try{const s={Accept:"application/json","Content-Type":i||"application/json"};ke(r,((e,t)=>{s[t]=e}));let a=null,c=null;AbortController&&(c=new AbortController,a=c.signal);const u=yield Promise.race([fetch(e,{body:fn(i,t),cache:"no-cache",credentials:"same-origin",headers:s,method:"POST",mode:"cors",redirect:"follow",referrer:"no-referrer",signal:a}),new Lr(8)]);if(o.f(u))throw c&&c.abort(),new Error(`fetch ${e}, data: ${JSON.stringify(t)} timeout`);n(u.json())}catch(e){a<3?(yield new Lr(1),c()):s(e)}}))}()}))}))}const gn={joinUser:"peer-joined",leaveUser:"peer-leaved",roomClosed:"room-closed",roomError:"error",updateStats:"update-stats",updateUser:"peer-update",publishStream:"stream-added",unpublishStream:"stream-removed",onIceCandidate:"ice-candidate",streamUpdate:"stream-update",streamError:"stream-error",streamDisconnected:"stream-disconnected",evicted:"evicted",userRejoined:"peer-rejoined",tokenWillExpire:"token-will-expire",tokenExpire:"token-expire",changeSignalNode:"server-proxy-change",rebuildMediaRelation:"media-server-changed"};class _n{constructor(e,t){this.data=new t(e),this.valid=0,this.tail=0,this.length=0,this.pos=0,this.size=e,this.constructorFunction=t}write(e){const t=e.length;if(!(t>this.size)){if(this.tail+t>this.size){const i=this.size-this.tail,r=t-i;this.data.set(e.subarray(0,i),this.tail),this.data.set(e.subarray(i),0),this.tail=r}else this.data.set(e,this.tail),this.tail+=t;if(this.length+t>this.size){const e=this.length+t-this.size;if(this.valid+e>this.size){const t=e-(this.size-this.valid);this.valid=t}else this.valid+=e;this.length=this.size}else this.length+=t}}read(e){if(0===this.length)return;e>this.length&&(e=this.length);const t=new this.constructorFunction(e);if(this.valid+e>this.size){const i=this.size-this.valid,r=e-i;t.set(this.data.subarray(this.valid,this.valid+i),0),t.set(this.data.subarray(0,r),i),this.valid=r}else t.set(this.data.subarray(this.valid,this.valid+e),0),this.valid+=e;return this.length-=e,this.pos+=e,t}readByRange(e,t){if(e<=t){const i=new this.constructorFunction(t-e);return i.set(this.data.subarray(e,t),0),i}{const i=new this.constructorFunction(this.size-e+t);return i.set(this.data.subarray(e),0),i.set(this.data.subarray(0,t),this.size-e),i}}getCurrentPointer(){return this.valid}readByte(){if(this.length>0){let e;return this.valid>=this.size?(this.valid=1,e=this.data[0]):e=this.data[this.valid++],this.length-=1,this.pos+=1,e}}getByteByIndex(e){if(this.length>e){let t;if(this.valid+e>=this.size){const i=e-(this.size-this.valid);t=this.data[i]}else t=this.data[this.valid+e];return t}}getSize(){return this.size}getLength(){return this.length}getPos(){return this.pos}getRemainingSize(){return this.size-this.length}back(e){e>this.size-this.length?(this.pos-=this.size-this.length,this.valid=this.tail,this.length=this.size):(this.valid<e?this.valid=this.size-(e-this.valid):this.valid-=e,this.length+=e,this.pos-=e)}skip(e){this.length<e?(this.valid=this.tail=0,this.pos+=this.length,this.length=0):(this.valid+e>this.size?this.valid=e-(this.size-this.valid):this.valid+=e,this.length-=e,this.pos+=e)}clear(){this.valid=this.tail=this.length=this.pos=0}}var yn;!function(e){e[e.COLON=58]="COLON",e.COLON_CHAR=":",e[e.COMMA=44]="COMMA",e.COMMA_CHAR=",",e[e.SPACE=32]="SPACE",e.SPACE_CHAR=" "}(yn||(yn={}));class Sn{constructor(e){this.options=e,this.ringBuffer=new _n(e.bufferSize,Uint8Array)}isDigit(e){return e>=48&&e<=57}static encode(e,t){const i=o.f(t)&&t>=0?`${e.length+`${t}${yn.SPACE_CHAR}`.length}${yn.COLON_CHAR}${t}${yn.SPACE_CHAR}`:`${e.length}${yn.COLON_CHAR}`,r=new Uint8Array(i.length+e.length+1);let n;for(n=0;n<i.length;n++)r[n]=i.charCodeAt(n);return r.set(e,n),r[n+e.length]=yn.COMMA,r}decode(e){e&&this.ringBuffer.write(e);let t=0,i=0,r=this.ringBuffer.getCurrentPointer();if(this.ringBuffer.getLength()>=3){if(48===this.ringBuffer.getByteByIndex(0)&&this.isDigit(this.ringBuffer.getByteByIndex(1)))throw new Error("find leading zeros!");if(!this.isDigit(this.ringBuffer.getByteByIndex(0)))throw new Error("the netstring must start with a number");for(;this.ringBuffer.getLength()&&this.isDigit(this.ringBuffer.getByteByIndex(0));){if(i>9)throw new Error("length is more than 9 digits");t=10*t+(this.ringBuffer.readByte()-48),i++}if(!this.ringBuffer.getLength())return void this.ringBuffer.back(i);if(this.ringBuffer.readByte()!==yn.COLON)throw new Error("miss the colon");if(i++,t+1<=this.ringBuffer.getLength()){let e=0,i=t;if(this.options.enableCommand){for(;this.ringBuffer.getLength()&&this.isDigit(this.ringBuffer.getByteByIndex(0));)e=10*e+(this.ringBuffer.readByte()-48),i--;if(this.ringBuffer.readByte()!==yn.SPACE)throw new Error("miss the space");i--}if(this.ringBuffer.getByteByIndex(i)!==yn.COMMA)throw new Error("miss the comma");const n=this.ringBuffer.read(i);this.ringBuffer.skip(1);const s=this.ringBuffer.readByRange(r,this.ringBuffer.getCurrentPointer());this.options.onDecodeText&&this.options.onDecodeText(this,{payload:n,serialized:s,cmd:this.options.enableCommand?e:void 0}),this.decode()}else this.ringBuffer.back(i)}}destroy(){this.ringBuffer=null,this.options=null}}const En="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function bn(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");let t,i,r,n,s,o,a,c=0,u=0;for(;e.length%4;)e+="=";const d=new Uint8Array(.75*e.length);for(;c<e.length;)t=En.indexOf(e.charAt(c++)),i=En.indexOf(e.charAt(c++)),r=En.indexOf(e.charAt(c++)),n=En.indexOf(e.charAt(c++)),s=t<<2|i>>4,o=(15&i)<<4|r>>2,a=(3&r)<<6|n,d[u++]=s,64!==r&&(d[u++]=o),64!==n&&(d[u++]=a);return d}const Tn={};ge(["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"],((e,t)=>{Tn[e]=t}));class In{constructor(e){this.count=e,this.queue=[]}push(e){this.queue.push(e),this.queue.length>this.count&&this.queue.shift()}clear(){this.queue.length=0}isFull(){return this.queue.length===this.count}getValue(){if(!this.queue.length)return 0;let e=0;for(let t=0;t<this.queue.length;t++)e+=this.queue[t];return e/this.queue.length}}function Cn(e,t,i){return e<t?e=t:e>i&&(e=i),e}var wn=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const Rn={mode:"text",enableCommand:!1,binaryCommand:19,pingCommand:1,pingAckCommand:2,streamCount:1,textCommandStart:20,textCommandEnd:Math.pow(2,31)-1,commandTimeout:3e4,bufferSize:1048576,enablePing:!1,pingInterval:5e3};class kn{constructor(e,t={}){this.url=e,this.options=Me({},Rn,t),t.textDecoder?this.textDecoder=t.textDecoder:o.d(TextDecoder)?this.textDecoder=new TextDecoder:"text"===this.options.mode&&he.warn("has not textDecoder to use, support binary only"),t.textEncoder?this.textEncoder=t.textEncoder:o.d(TextEncoder)&&"text"===this.options.mode?this.textEncoder=new TextEncoder:"text"===this.options.mode&&he.warn("has not textEncoder to use, support binary only"),this.textCommandPointer=this.options.textCommandStart,this.commandMap=new Map,this.pingStartTimestamp=new Map,this.commandQueue=[],this.streams=[],this.readers=[],this.writers=[],this.streamReaderMap=new Map,this.streamWriterMap=new Map,this.netStrings=[],this.currentWriteStreams=1,this.rtt=new In(5),"stream"===this.options.mode&&(this.options.streamCount=1),this.options.streamCount>1&&(this.options.enableCommand=!0),this.options.enablePing&&(this.pingTimer=new ct((()=>{this.ping()}),1e3,this.options.pingInterval)),this.connect().catch((e=>{he.error(`WebTransportWS connect error because of error: ${e}, url: ${this.url}`),this.onerror&&q(this.onerror,this,[e]),this.pingTimer&&this.pingTimer.stop()}))}read(e,t){return wn(this,void 0,void 0,(function*(){"text"===this.options.mode&&(this.netStrings[t]=new Sn({bufferSize:this.options.bufferSize,onDecodeText:this.onDecodeMessage.bind(this),enableCommand:this.options.enableCommand,index:t}));let i=!1;for(;;)try{const{value:r,done:n}=yield e.read();if(n){i=n;break}if("text"===this.options.mode)try{this.netStrings[t].decode(r)}catch(e){he.error("decode message error, "+e),this.onclose&&q(this.onclose,this,[new Error("decode message error")]);break}else this.onmessage&&q(this.onmessage,this,[{data:r.buffer}])}catch(e){i||he.error("read data error, "+e);break}Se(this.readers,e),this.readers.length||this.onclose&&q(this.onclose,this,[new Error("readableStream closed")])}))}handleRead(){ge(this.readers,((e,t)=>{this.read(e,t)}))}readDatagram(){return wn(this,void 0,void 0,(function*(){let e=!1;for(;;)try{const{value:t,done:i}=yield this.datagramReader.read();if(i){e=!0;break}try{this.onDatagramMessage(t)}catch(e){he.error("parse datagram data error, "+e)}}catch(t){e||he.error("read datagram data error, "+t);break}}))}connect(){return wn(this,void 0,void 0,(function*(){const e={};o.c(this.options.allowPooling)&&(e.allowPooling=this.options.allowPooling),o.a(this.options.serverCertificateHashes)&&(e.serverCertificateHashes=[],ge(this.options.serverCertificateHashes,(t=>{o.i(t.value)?e.serverCertificateHashes.push({algorithm:t.algorithm,value:bn(t.value)}):e.serverCertificateHashes.push({algorithm:t.algorithm,value:t.value})}))),this.transport=new WebTransport(this.url.replace(/^webtransport:/,"https:"),e),this.transport.closed.then((()=>{he.info("WebTransportWS closed gracefully, url: "+this.url),this.onclose&&q(this.onclose,this,[{}]),this.pingTimer&&this.pingTimer.stop()})).catch((e=>{he.error(`WebTransportWS closed because of error: ${e}, url: ${this.url}`),this.onerror&&q(this.onerror,this,[e]),this.onclose&&q(this.onclose,this,[e]),this.pingTimer&&this.pingTimer.stop()}));const t=z();yield this.transport.ready;const i=z()-t;this.datagramReader=this.transport.datagrams.readable.getReader(),this.datagramWriter=this.transport.datagrams.writable.getWriter();const r=yield this.transport.createBidirectionalStream(),n=r.readable.getReader(),s=r.writable.getWriter();this.streams.push(r),this.readers.push(n),this.writers.push(s),this.streamReaderMap.set(r,n),this.streamWriterMap.set(r,s),yield Promise.all(this.writers.map((e=>e.ready))),this.handleRead(),this.options.enablePing&&this.readDatagram(),this.onopen&&q(this.onopen,this,[{consume:i}]),this.pingTimer&&this.pingTimer.start()}))}getTextCommand(){if(this.options.enableCommand){const e=this.textCommandPointer++;return this.textCommandPointer>this.options.textCommandEnd&&(this.textCommandPointer=this.options.textCommandStart),e}return-1}createPacket(e,t){const i=new Uint8Array(1+t.length);return i[0]=e,i.set(t,1),i}ping(){if(this.datagramWriter){const e=z(),t=new Float64Array(1);t[0]=e,this.pingStartTimestamp.set(e,setTimeout((()=>{this.pingStartTimestamp.delete(e);const t=z()-e;this.rtt.push(t),o.d(this.options.onPing)&&this.options.onPing(this,t)}),5e3));try{this.datagramWriter.write(this.createPacket(this.options.pingCommand,new Uint8Array(t.buffer)))}catch(e){he.error("send ping error, "+e),this.pingTimer&&this.pingTimer.stop()}}}onDatagramMessage(e){if(!e.length)return;const t=e[0],i=e.slice(1);if(t===this.options.pingAckCommand){const e=new Float64Array(i.buffer);if(this.pingStartTimestamp.has(e[0])){clearTimeout(this.pingStartTimestamp.get(e[0]));const t=z()-e[0];this.rtt.push(t),this.pingStartTimestamp.delete(e[0]),o.d(this.options.onPing)&&this.options.onPing(this,t)}}else t===this.options.pingCommand?(e[0]=this.options.pingAckCommand,this.datagramWriter.write(e)):this.onmessage&&this.onmessage&&q(this.onmessage,this,[{data:i}])}onDecodeMessage(e,t){if(t.cmd>=this.options.textCommandStart&&t.cmd<=this.options.textCommandEnd||t.cmd===this.options.binaryCommand)if(this.options.streamCount>1){if(this.commandMap.get(t.cmd))return;for(this.onmessage&&q(this.onmessage,this,[{data:t.cmd!==this.options.binaryCommand&&this.textDecoder?this.textDecoder.decode(t.payload):t.payload.buffer}]),this.commandMap.set(t.cmd,!0),this.commandQueue.push({cmd:t.cmd,timestamp:z()});this.commandQueue.length&&z()-this.commandQueue[0].timestamp>this.options.commandTimeout;)this.commandMap.delete(this.commandQueue[0].cmd),this.commandQueue.shift()}else this.onmessage&&q(this.onmessage,this,[{data:t.cmd!==this.options.binaryCommand&&this.textDecoder?this.textDecoder.decode(t.payload):t.payload.buffer}]);else we(t.cmd)||this.onmessage&&q(this.onmessage,this,[{data:this.textDecoder?this.textDecoder.decode(t.payload):t.payload.buffer}])}send(e){if(o.b(e))return void this.sendBinary(e);if(!this.writers.length)return void he.error("can not send data because of no writer in WebTransportWS");const t=o.i(e)?e:JSON.stringify(e);try{const e=Sn.encode(this.textEncoder.encode(t),this.getTextCommand());ge(this.writers,(t=>{t.write(e)}))}catch(e){he.error("send data error, "+e),this.onclose&&q(this.onclose,this,[e]),this.pingTimer&&this.pingTimer.stop()}}sendBinary(e){const t=new Uint8Array(e);try{ge(this.writers,(e=>{e.write("text"===this.options.mode?Sn.encode(t,this.options.binaryCommand):t)}))}catch(e){he.error("send binary data error, "+e),this.onclose&&q(this.onclose,this,[e]),this.pingTimer&&this.pingTimer.stop()}}getCurrentWriteStreams(){return this.currentWriteStreams}setCurrentWriteStreams(e){return wn(this,void 0,void 0,(function*(){if(!(this.options.streamCount<2))if(this.currentWriteStreams=Cn(e,1,this.options.streamCount),this.currentWriteStreams<this.streams.length){for(let e=this.currentWriteStreams;e<this.streams.length;e++){const t=this.streams[e],i=this.streamReaderMap.get(t),r=this.streamWriterMap.get(t);i&&(yield i.cancel(),Se(this.readers,i),this.streamReaderMap.delete(t)),r&&(yield r.close(),Se(this.writers,r),this.streamWriterMap.delete(t))}this.netStrings=this.netStrings.slice(0,this.currentWriteStreams),this.streams=this.streams.slice(0,this.currentWriteStreams)}else if(this.currentWriteStreams>this.streams.length)for(let e=this.streams.length;e<this.currentWriteStreams;e++){const t=yield this.transport.createBidirectionalStream(),i=t.readable.getReader(),r=t.writable.getWriter();this.read(i,e),yield r.ready,this.streams.push(t),this.readers.push(i),this.writers.push(r),this.streamReaderMap.set(t,i),this.streamWriterMap.set(t,r)}}))}getRTT(){return this.rtt.getValue()}close(){this.readers.forEach((e=>{e.cancel()})),this.datagramReader&&this.datagramReader.cancel(),this.transport&&(this.transport.close(),this.transport=null),this.netStrings&&(ge(this.netStrings,(e=>{e.destroy()})),this.netStrings=[]),this.pingTimer&&(this.pingTimer.destroy(),this.pingTimer=null),this.textEncoder&&(this.textEncoder=null),this.textDecoder&&(this.textDecoder=null),this.pingStartTimestamp&&(this.pingStartTimestamp.forEach((e=>{clearTimeout(e)})),this.pingStartTimestamp.clear(),this.pingStartTimestamp=null),this.commandMap&&this.commandMap.clear(),this.streams=[],this.readers=[],this.writers=[],this.datagramReader=null,this.commandQueue=[],this.streamReaderMap.clear(),this.streamWriterMap.clear()}clear(){this.close()}}var An,Mn=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const On={enableRace:!0,forceWS:!1,forceDC:!1,forceWT:!1},Ln="function"==typeof(null===(An=G.e)||void 0===An?void 0:An.WebTransport)&&ot.chrome&&ot.checkVersion(ot.majorVersion,"97",!0);let Pn=[];class Nn extends Ne{constructor(e,t,i={},r){super(!1),this.options=Me({},On,t),this.closed=!1,this.icefull=!1,this.isConnecting=!1,this.connectCount=0,this.isLeaving=!1,this.rpc=i,this.logger=r||new ti,this.proxies=this.preprocessProxy(e)}preprocessProxy(e){return e=e.map((e=>{if(e.wturl&&e.url){const t=Oe(e,!0),i=Oe(e,!0);return t.wturl="",i.url="",[i,t]}return[Oe(e,!0)]})).reduce(((e,t)=>e.concat(t)),[]),Ln||(e=e.filter((e=>!e.wturl))),e}isDataChannel(e){return 0!==e.indexOf("wss:")&&0!==e.indexOf("ws:")}isWebTransport(e){return 0===e.indexOf("webtransport:")}getTransport(e){return this.isWebTransport(e)?kn:this.isDataChannel(e)?Gr:null}getTransportOptions(e){return this.isWebTransport(e)?{enableCommand:!0,textCommand:1,streamCount:2,autoStream:!0,enablePing:!0,onPing:(e,t)=>{t>160?e.setCurrentWriteStreams(2):e.setCurrentWriteStreams(e.getRTT()<60?1:2)}}:this.isDataChannel(e)?{processOffer:(e,t)=>Mn(this,void 0,void 0,(function*(){return vn(e,{type:"offer",sdp:t}).then((e=>e.sdp))}))}:{}}getUrl(e){return e.activeUrl=e.url||e.dcurl||e.wturl,Ln&&this.options.enableWT&&!this.options.forceWS&&e.wturl&&(e.activeUrl=e.wturl),o.h(e.suffix)?function(e,t,i){null==i&&(i=document.URL);let r=function(e){var t;const i=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],r={},n=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e);let s=14;for(;s--;)r[i[s]]=null!==(t=n[s])&&void 0!==t?t:"";return{protocol:r.protocol,file:r.file,host:r.host,port:r.port,user:r.user,password:r.password,origin:`${r.protocol}://${r.authority}`,pathname:r.path,search:"?"+r.query,hash:r.anchor?"#"+r.anchor:""}}(i),n=Qi(r.search);return Me(n,e),n=Pe(n),i=r.origin+r.pathname,n&&(i+="?"+n),i+=r.hash}(e.suffix,0,e.activeUrl):e.activeUrl}raceConnect(){return Mn(this,void 0,void 0,(function*(){let e=Pn.concat(this.proxies);if(this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}else if(this.options.forceDC){const t=e.filter((e=>!!e.dcurl));t.length&&(e=t)}else if(this.options.forceWT&&Ln&&this.options.enableWT){const t=e.filter((e=>!!e.wturl));t.length&&(e=t)}if(!this.options.enableWT){const t=e.filter((e=>!e.wturl||!!e.url));t.length&&(e=t)}this.connectingTimers={};const t=".connecting"+Math.random();return new Promise(((i,r)=>{let n=!1;this.connectCount=0;const s=(e,s)=>{n?e.destroy():this.closed?(ke(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.warn("signal open after call close function, reject"),r("signal has already closed")):(n=!0,ke(this.connectingTimers,((e,t)=>{clearTimeout(e.timer),e.channel&&t!=s&&e.channel.destroy()})),this.connectingTimers={},e.off(t),this.connectCount=e.getTransportConnectCount(),i(e))};let o=0;const a=()=>{++o===e.length&&(ke(this.connectingTimers,(e=>{e.channel&&e.channel.destroy()})),this.connectingTimers={},this.logger.error("connect all proxies failed"),r("connect all proxies failed"))},c=(e,i)=>{const r=new mn(e,{maxRetry:5,transport:this.getTransport(e),transportOptions:this.getTransportOptions(e),tag:"Signal",logLevel:he.DEBUG},i,this.logger);r.one("connected"+t,(()=>{i.consume=r.getConsume(),this.connectCount=r.getTransportConnectCount(),s(r,e)})).one("reconnected"+t,(()=>{i.consume=r.getConsume(),this.connectCount=r.getTransportConnectCount(),s(r,e)})).one("error"+t,(()=>{this.connectCount=r.getTransportConnectCount(),a()})).one("timeout"+t,(()=>{this.connectCount=r.getTransportConnectCount(),a()})),this.connectingTimers[e].channel=r};ge(e,(e=>{const t=e.delay?Xe(e.delay):0,i=this.getUrl(e);this.connectingTimers[i]={timer:setTimeout((()=>{c(i,e)}),t)}}))}))}))}queueConnect(){return Mn(this,void 0,void 0,(function*(){let e=Pn.concat(this.proxies);if(this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}else if(this.options.forceDC){const t=e.filter((e=>!!e.dcurl));t.length&&(e=t)}else if(this.options.forceWT&&Ln&&this.options.enableWT){const t=e.filter((e=>!!e.wturl));t.length&&(e=t)}if(!this.options.enableWT){const t=e.filter((e=>!e.wturl||!!e.url));t.length&&(e=t)}const t=".connecting"+Math.random();return new Promise(((i,r)=>{let n=0;this.connectCount=0;const s=()=>{this.closed&&r("signal has closed");const o=e[n],a=this.getUrl(o),c=this.connectingChannel=new mn(a,{maxRetry:3,transport:this.getTransport(a),transportOptions:this.getTransportOptions(a),tag:"Signal",logLevel:he.DEBUG},o,this.logger);c.one("connected"+t,(()=>{c.off(t),this.connectingChannel=null,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),i(c)})).one("reconnected"+t,(()=>{c.off(t),this.connectingChannel=null,o.consume=c.getConsume(),this.connectCount+=c.getTransportConnectCount(),i(c)})).one("error"+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=null,this.logger.error(`queue connect proxy: ${n} ${a} error`),this.fire("state-notify",[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} error`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,r("connect all proxies failed")):setTimeout((()=>{s()}),1e3)})).one("timeout"+t,(()=>{this.connectCount+=c.getTransportConnectCount(),c.destroy(),this.connectingChannel=null,this.logger.error(`queue connect proxy: ${n} ${a} timeout`),this.fire("state-notify",[{level:this.logger.ERROR,msg:`queue connect proxy: ${n} ${a} timeout`}]),n++,n>=e.length?(this.logger.error("connect all proxies failed"),n=0,r("connect all proxies failed")):setTimeout((()=>{s()}),1e3)}))};s()}))}))}tryConnectOtherProxy(e){this.proxies.length>1?(hi(),Se(this.proxies,this.getProxy()),ye(this.proxies,this.getProxy()),this.logger.info("try to connect other proxies"),this.connect().then((()=>{this.fire("reconnected"),this.channel.syncNotify()})).catch((t=>{this.logger.error("connect other proxies failed"),this.fire(e)}))):this.fire(e)}tryChangeSelectedProxy(e){if(!e.length)return;if(Pn=e=this.preprocessProxy(e),this.options.forceWS){const t=e.filter((e=>!!e.url));t.length&&(e=t)}else if(this.options.forceDC){const t=e.filter((e=>!!e.dcurl));t.length&&(e=t)}else if(this.options.forceWT&&Ln&&this.options.enableWT){const t=e.filter((e=>!!e.wturl));t.length&&(e=t)}if(!this.options.enableWT){const t=e.filter((e=>!e.wturl||!!e.url));t.length&&(e=t)}let t,i=0;const r=(e,t)=>{this.closed?e.close():(this.logger.info(`change selected proxy success from proxy: ${JSON.stringify(this.channel.getProxy())} to proxy: ${JSON.stringify(t)}`),t.consume=e.getConsume(),this.channel.updateProxy(t),this.channel.changeTransport(e),this.channel.syncNotify(),this.fire("proxy-changed"))},n=r=>{this.logger.error("try change selected proxy error, proxy: "+JSON.stringify(r)),i++,i>=e.length||setTimeout((()=>{t()}),1e3)};t=()=>{if(this.closed)return;const s=e[i],o=this.getUrl(s);if(this.channel.getProxy().activeUrl===s.activeUrl)return this.logger.warn("try to change selected proxy to current, ignore, proxy "+JSON.stringify(s)),i++,i>=e.length?void 0:(i++,void t());const a=new Jr({native:this.getTransport(o),nativeOptions:this.getTransportOptions(o),connectOnClose:!0,retryCount:3,interval:500,timeout:1e4,onOpen:()=>{r(a,s)},onReconnecting:()=>{r(a,s)},onClose:()=>{n(s)},onError:()=>{n(s)},onTimeout:()=>{n(s)}},this.channel.getLogger());a.connect({url:o})},t()}connect(){return Mn(this,void 0,void 0,(function*(){if(!this.proxies.length)return new Error("not has any proxy to connect");this.isConnecting=!0,this.options.enableRace?this.channel=yield this.raceConnect():this.channel=yield this.queueConnect(),this.channel.on("error",(()=>{this.logger.error("proxy connect error, proxy: "+JSON.stringify(this.getProxy())),this.fire("error")})).on("close",(()=>{this.logger.error("proxy connect close, proxy: "+JSON.stringify(this.getProxy())),this.fire("close")})).on("timeout",(()=>{this.logger.error("proxy connect timeout, proxy: "+JSON.stringify(this.getProxy())),this.fire("timeout")})).on("connected",(()=>{this.fire("connected")})).on("reconnecting",(()=>{this.fire("reconnecting")})).on("reconnected",(()=>{if(this.isLeaving)return;this.fire("reconnected"),this.channel.syncNotify();const e=this.channel.getProxy();e&&(e.consume=this.channel.getConsume())})).on(ii,((e,t,i)=>{i&&i<this.channel.notified?this.logger.warn(`skip notify: ${i}, now notified: ${this.channel.notified}, method: ${e}, params: ${JSON.stringify(t)}`):(i&&i===this.channel.notified?this.logger.warn(`repeated receive notify: ${i}, method: ${e}, params: ${JSON.stringify(t)}`):i&&this.channel.notified>-1&&i-this.channel.notified>1&&this.logger.warn(`skip to notify: ${i}, now notified: ${this.channel.notified}, method: ${e}, params: ${JSON.stringify(t)}`),this.channel.notified=i,this.channel.resetTimeout(),gn[e]?this.fire(gn[e],[t]):this.fire(ii,[{method:e,params:t}]))})).on("request",(e=>Mn(this,void 0,void 0,(function*(){if(this.rpc[e.method]){this.channel.resetTimeout();const{error:t,result:i}=yield this.rpc[e.method](e);this.channel.reply(e,i,t)}})))).on("session-close",(()=>{this.fire("session-close")})),this.isConnecting=!1,this.logger.info("connect proxy success, proxy: "+JSON.stringify(this.channel.getProxy()))}))}request(e,t){return Mn(this,void 0,void 0,(function*(){return this.channel.request(e,t)}))}join(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("joinRoom",e).then((e=>(this.channel.resetTimeout(),this.icefull=e.icefull,this.isLeaving=!1,e)))}))}leave(e){return Mn(this,void 0,void 0,(function*(){return this.isLeaving=!0,this.channel.request("leaveRoom",e,{timeout:3e3}).then((e=>(this.isLeaving=!1,e)))}))}evictUser(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("evictUser",e)}))}publish(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("publishStream",e)}))}unpublish(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("unpublishStream",e)}))}controlStream(e,t){return Mn(this,void 0,void 0,(function*(){return this.channel.request("controlStream",e,t)}))}subscribe(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("subscribeStream",e)}))}unsubscribe(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("unsubscribeStream",e)}))}addIceCandidate(e){return Mn(this,void 0,void 0,(function*(){return this.icefull?this.channel.request("addIceCandidate",e):Promise.resolve({})}))}syncRoom(e){return Mn(this,void 0,void 0,(function*(){return this.channel.sessionId=null,this.channel.request("syncRoom",e).then((e=>(this.icefull=e.icefull,this.channel.resetRequest(),e)))}))}setBitrate(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("setrate",e)}))}pullUsers(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("getUserList",e)}))}queryUser(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("queryUser",e)}))}getMediaServers(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("getServers",e)}))}setMediaRelation(e){return Mn(this,void 0,void 0,(function*(){return this.channel.request("setMediaRelation",e)}))}close(){this.connectingChannel&&this.connectingChannel.destroy(),Re(this.connectingTimers).length&&(ke(this.connectingTimers,(e=>{clearTimeout(e.timer),e.channel&&e.channel.destroy()})),this.connectingTimers={}),this.channel&&this.channel.destroy(),this.closed=!0,this.off()}getSessionId(){var e;return null===(e=this.channel)||void 0===e?void 0:e.sessionId}getProxy(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getProxy()}getConnectCount(){return this.connectCount}getConnectedProxyConsume(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getConsume()}getConnectStatus(){var e;return null===(e=this.channel)||void 0===e?void 0:e.getTransportStatus()}}class Dn{constructor(e,t){this.userId=e,this.info=t,this.streams=new Map}getUserId(){return this.userId}getUserInfo(){return this.info}getStreams(){return this.streams}getStream(e){return this.streams.get(e)}addStream(e){this.streams.set(e.getStreamId(),e)}removeStream(e){if(!this.streams)return;const t=this.streams.get(e);return t?(this.streams.delete(e),t):void 0}updateInfo(e){this.info=e}destroy(){this.streams&&(this.streams.forEach((e=>{e.close()})),this.streams.clear()),this.streams=null,this.info=null,this.userId=null}}var xn=i(13);function Un(e=[],t=[],i){return function(r){var n;e=e.map((e=>e.toLocaleUpperCase()));let s=!1;if(ge(r.media,(r=>{if(s&&(delete r.fingerprint,delete r.setup,delete r.icePwd,delete r.iceUfrag,delete r.iceOptions),r.fingerprint&&r.icePwd&&r.iceUfrag&&(s=!0),"application"===r.type)return!0;const n=[],o=[],a=[],c=Xe(r.payloads.split(" ").shift());let u=[c];const d=r.rtp.filter((e=>e.payload===c));if((null==d?void 0:d.length)&&!Ee(e,d[0].codec.toLocaleUpperCase())&&e.push(d[0].codec.toLocaleUpperCase()),ge(r.rtp,(t=>{Ee(e,t.codec.toLocaleUpperCase())&&!Ee(u,t.payload)&&u.push(t.payload)})),i){const e=u.slice();let t=0,n=0;ge(r.fmtp,(e=>{const r=/profile-level-id/.test(e.config);if(/profile(-level)?-id/.test(e.config)&&Ee(u,e.payload)){let s=e.config.match(/profile(-level)?-id=([0-9a-f]+)/),o="";s&&(t++,o=s[2],r?xn.isSameProfile({"profile-level-id":o},{"profile-level-id":i})||(n++,Se(u,e.payload)):o!==i&&(n++,Se(u,e.payload)))}})),u.length&&t!==n||(u=e)}ge(r.fmtp,(e=>{if(/^apt=/.test(e.config)){const t=e.config.match(/^apt=(\d+)$/)[1];Ee(u,Xe(t))||Se(u,e.payload)}})),ge(r.rtp,(e=>{Ee(u,e.payload)&&n.push(e)})),ge(r.fmtp,(e=>{if(Ee(u,e.payload))o.push(e);else if(/^apt=/.test(e.config)){const t=e.config.match(/^apt=(\d+)$/)[1];Ee(u,Xe(t))&&o.push(e)}})),ge(r.rtcpFb,(e=>{Ee(u,e.payload)&&a.push(e)})),r.payloads=u.join(" "),r.rtp=n,r.fmtp=o,r.rtcpFb=a;const l=t.filter((e=>e.kind===r.type)).map((e=>e.value));r.ext=r.ext.filter((e=>!Ee(l,e.uri)))})),(null===(n=r.media)||void 0===n?void 0:n.length)>1){let e=-1;for(let t=0;t<r.media.length;t++){const i=r.media[t];if(i.fingerprint&&i.icePwd&&i.iceUfrag){e=t;break}}e>0&&r.media.unshift(r.media.splice(e,1)[0])}return he.debug(`[sdpOperator shrink]: holdCodec: ${JSON.stringify(e)}, removeHeaderExtensions: ${JSON.stringify(t)}, profile: ${i}`),r}}class $n extends ji{constructor(e={}){super(e),this.direction=xi.RECV_ONLY,"ontrack"in this.pc?this.pc.ontrack=e=>{this.stream=e.streams[0],this.ontrack&&this.ontrack(e.track)}:"onaddstream"in this.pc&&(this.pc.onaddstream=e=>{this.stream=e.stream})}getMediaStream(){if(this.stream)return this.stream;if(this.pc)if(this.pc.getReceivers){this.stream=new MediaStream;const e=this.pc.getReceivers();let t=!1,i=!1;e.forEach((e=>{e.track&&"video"===e.track.kind&&!t&&(this.stream.addTrack(e.track),t=!0),e.track&&"audio"===e.track.kind&&!i&&(this.stream.addTrack(e.track),i=!0)}))}else this.stream=this.pc.getRemoteStreams()[0];return this.stream}}var Bn=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const Vn={videoOn:!1,audioOn:!1,videoEnable:!1,audioEnable:!1,simulcast:1,redAudio:!1};class Fn extends vi{constructor(e,t,i){super({client:t,type:e.type,userId:e.userId,streamId:e.streamId,videoOn:e.videoOn,audioOn:e.audioOn,videoEnable:e.videoEnable,audioEnable:e.audioEnable,audioLevelInterval:e.audioLevelInterval},i),this.options=Me({},Vn,e),this.videoAdaptionEnable=!1}getStream(){if(this.peer)return this.peer.getMediaStream()}getProfile(){return this.profile}setProfile(e){this.profile=e}processOffer(e=!0,t=!0,i={iceServers:[]}){var r;return Bn(this,void 0,void 0,(function*(){if(!this.options.audioOn&&!this.options.videoOn)throw new Error("not has any media track when subscribing");if(this.peer&&(this.peer.oniceconnectionstatechange=null,this.peer.onicecandidate=null,this.peer.ondtlsstatechange=null,this.peer.destroy()),this.collector&&this.collector.destroy(),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser=null),this.peer=new $n({iceServers:null!==(r=i.iceServers)&&void 0!==r?r:[],rtcpMuxPolicy:"require",encodedInsertableStreams:this.hasEncodedDataProcesser(i)}),this.isMsSupportDatachannel&&this.peer.createChannel(),this.handlerEvent(),this.hasAudioKind=this.options.audioOn&&e,this.hasVideoKind=this.options.videoOn&&t,!this.hasAudioKind&&!this.hasVideoKind)throw new Error("must has a media kind when subscribing");let n=yield this.peer.offer({offerToReceiveAudio:this.hasAudioKind,offerToReceiveVideo:this.hasVideoKind});return n=mr(pr(this.options.acodec,Ui.AUDIO),pr(this.options.vcodec,Ui.VIDEO,this.options.profile),zi(xi.RECV_ONLY),this.options.stereo?Xi(Ui.AUDIO,"stereo",1,this.options.acodec):null,this.options.stereo?Xi(Ui.AUDIO,"sprop-stereo",1,this.options.acodec):null,fr("urn:ietf:params:rtp-hdrext:sdes:mid",Ui.AUDIO),this.options.redAudio?Yi("urn:boom:audio-stacked-rtp",null,Ui.AUDIO):null,qi("nack",$i.ADD,Ui.AUDIO))(n),yield this.peer.setOffer(n),this.collector=new Oi(this.peer.getPeerConnection(),1e3,!1,this.audioLevelInterval),this.collector.onAudioLevel=e=>{this.fire("stream-audio-level",[e])},this.logger.debug(`remotestream ${this.getUserId()} ${this.getStreamId()} offer: ${"\n"+n}`),n}))}processAnswer(e,t={enableSEI:!1}){return Bn(this,void 0,void 0,(function*(){let i=!1,r=!1;const n=mr(Gi(this.msmsIPs,!1),this.isMsSupportDatachannel?vr(Ui.APPLICATION,(e=>{i=e})):null,Tr((e=>{r=e})));if(e=n(e),!i&&this.isMsSupportDatachannel)throw this.isMsSupportDatachannel=!1,this.logger.error(`msms ${this.getMsmsIP()} not support datachannel, should retry, remotestream userId: ${this.getUserId()}, streamId: ${this.getStreamId()}`),new Error("msms not support datachannel, should retry");this.logger.debug(`remotestream userId: ${this.getUserId()}, streamId: ${this.getStreamId()}, answer: ${"\n"+e}`),yield this.peer.setAnwser(e),this.videoAdaptionEnable=!1,this.hasEncodedDataProcesser(t)&&(this.encodedDataProcesser=new br({send:!1,enableSEI:t.enableSEI&&"h264"===this.options.vcodec.toLocaleLowerCase(),onAudioEncodeDataPipe:this.onAudioEncodeDataPipe,onVideoEncodeDataPipe:this.onVideoEncodeDataPipe}),this.encodedDataProcesser.onmessage=(e,t)=>{this.fire("stream-sei-message",[{data:e,payload:t}])},this.encodedDataProcesser.start(this.peer.getReceivers())),r&&this.startDtlsConnectionTimeout()}))}setVideoSubscribed(e){this.videoSubscribed=e}setAudioSubscribed(e){this.audioSubscribed=e}getVideoSubscribed(){return this.videoSubscribed}getAudioSubscribed(){return this.audioSubscribed}getHasAudioKind(){return this.hasAudioKind}getHasVideoKind(){return this.hasVideoKind}muteAudio(){return Bn(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasAudioKind&&this.audioSubscribed&&(yield this.client.updateStream(this,{audio_enable:!1},"audioEnableControl_"+this.streamId),this.audioSubscribed=!1)}))}unmuteAudio(){return Bn(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasAudioKind&&!this.audioSubscribed&&(yield this.client.updateStream(this,{audio_enable:!0},"audioEnableControl_"+this.streamId),this.audioSubscribed=!0)}))}muteVideo(){return Bn(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasVideoKind&&this.videoSubscribed&&(yield this.client.updateStream(this,{video_enable:!1},"videoEnableControl_"+this.streamId),this.videoSubscribed=!1)}))}unmuteVideo(){return Bn(this,void 0,void 0,(function*(){this.client&&this.peer&&this.hasVideoKind&&!this.videoSubscribed&&(yield this.client.updateStream(this,{video_enable:!0},"videoEnableControl_"+this.streamId),this.videoSubscribed=!0)}))}destroy(){this.logger.info(`remotestream destroy userId: ${this.getUserId()}, streamId: ${this.getStreamId()}`),this.encodedDataProcesser&&(this.encodedDataProcesser.destroy(),this.encodedDataProcesser=null),this.close(),this.options=null,this.off(),this.destroyed=!0}getOptions(){return this.options}getSimulcast(){return this.options.simulcast}updateCodec(e){let t=!1;return o.i(e.acodec)&&this.options.acodec!==e.acodec&&(this.options.acodec=e.acodec,t=!0),o.i(e.vcodec)&&this.options.vcodec!==e.vcodec&&(this.options.vcodec=e.vcodec,t=!0),o.f(e.simulcast)&&this.options.simulcast!==e.simulcast&&(this.options.simulcast=e.simulcast),t}handlerEvent(){super.handlerEvent(),this.on("stream-video-adaption",(e=>{this.videoAdaptionEnable=e.video_enable,this.logger.info(`video adaption, enable: ${this.videoAdaptionEnable}, userId: ${this.getUserId()}, streamId: ${this.getStreamId()}`)}))}getVideoAdaptionEnable(){return this.videoAdaptionEnable}isSubscribed(){return!!this.peer&&(this.audioSubscribed||this.videoSubscribed)}}function jn(){const e=z();return function(){return z()-e}}function Hn(e){return function(t){return(null==e?void 0:e.length)&&(t.udpBlacklist=e.join(" ")),t}}tr("a",[{name:"udpBlacklist",reg:/^udp-blacklist:\s?(.*)/,format:"udp-blacklist: %s"}]);var Wn=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const Gn={forceWS:!1,enableRace:!1},qn=["red","ulpfec","rtx","flexfec-03","CN"],Jn=[{kind:"audio",value:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{kind:"video",value:"urn:ietf:params:rtp-hdrext:toffset"},{kind:"video",value:"urn:3gpp:video-orientation"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"},{kind:"video",value:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"}];class zn extends Ne{constructor(e,t){super(!0),this.udpIPBlackList=s,this.options=Me({},Gn,e),this.joined=!1,this.hasMoreUser=!0,this.userMap=new Map,this.iceServers=[],this.pullUserIds=[],this.joinedUsersMap=new Map,this.logger=t||new ti}parseUser(e){const t=e.value,i=[],r=[];ge(t,(e=>{var t;this.pullUserIds.push(e.userId);const n=new Dn(e.userId,e.info.userinfo);r.push(n),(null===(t=e.streams)||void 0===t?void 0:t.length)&&ge(e.streams,(t=>{var r,s,o,a;const c=new Fn({type:null===(r=t.params.ext)||void 0===r?void 0:r.streamType,stereo:null===(s=t.params.ext)||void 0===s?void 0:s.stereo,userId:e.userId,streamId:t.streamId,acodec:t.params.acodec,vcodec:t.params.vcodec,profile:null===(o=t.params.ext)||void 0===o?void 0:o.profile,videoOn:t.params.video,audioOn:t.params.audio,videoEnable:t.params.video_enable,audioEnable:t.params.audio_enable,simulcast:null!==(a=t.params.simulcast)&&void 0!==a?a:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);i.push(c),n.addStream(c)})),this.userMap.set(n.getUserId(),n)})),Object(J.a)((()=>{this.joined&&(ge(r,(e=>{this.fire("peer-joined",[e.getUserId()])})),ge(i,(e=>{const t=this.userMap.get(e.getUserId());t&&t.getStream(e.getStreamId())&&this.fire("stream-added",[e])})))}))}syncUser(e){var t;return Wn(this,void 0,void 0,(function*(){if(null===(t=e.raw)||void 0===t?void 0:t.streams){const t=e.raw.streams||[];this.userMap.get(this.userId).getStreams().forEach((e=>{Ee(t,e.getStreamId())||this.unpublish(e).then((()=>{this.publish(e)}))}))}const i=e.value,r=[],n=[],s=[],o=[],a=[],c=[],u=new Map;if(this.userMap.forEach(((e,t)=>{t!==this.userId&&(n.push(t),e.getStreams().forEach((e=>{e.isConnecting()&&!Ee(c,t)&&c.push(t)})))})),ge(i,(e=>{var t,i,n;if(e.userId===this.userId)return!0;this.pullUserIds.push(e.userId),u.set(e.userId,!0),Se(c,e.userId);let d=this.userMap.get(e.userId);if(d)if(d.updateInfo(e.info),null===(t=e.streams)||void 0===t?void 0:t.length){const t=[];d.getStreams().forEach(((e,i)=>{e instanceof Fn&&t.push(e)})),ge(e.streams,(i=>{var r,n,a,c;let u=d.getStream(i.streamId);if(u)u.update(i.params)&&o.push(u),Se(t,u);else{const t=new Fn({type:null===(r=i.params.ext)||void 0===r?void 0:r.streamType,stereo:null===(n=i.params.ext)||void 0===n?void 0:n.stereo,userId:e.userId,streamId:i.streamId,acodec:i.params.acodec,vcodec:i.params.vcodec,profile:null===(a=i.params.ext)||void 0===a?void 0:a.profile,videoOn:i.params.video,audioOn:i.params.audio,videoEnable:i.params.video_enable,audioEnable:i.params.audio_enable,simulcast:null!==(c=i.params.simulcast)&&void 0!==c?c:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);d.addStream(t),s.push(t)}})),a.push(...t)}else null===(i=d.getStreams())||void 0===i||i.forEach(((e,t)=>{e instanceof Fn&&a.push(e)}));else d=new Dn(e.userId,e.info.userinfo),r.push(e.userId),(null===(n=e.streams)||void 0===n?void 0:n.length)&&ge(e.streams,(t=>{var i,r,n,o;const a=new Fn({type:null===(i=t.params.ext)||void 0===i?void 0:i.streamType,stereo:null===(r=t.params.ext)||void 0===r?void 0:r.stereo,userId:e.userId,streamId:t.streamId,acodec:t.params.acodec,vcodec:t.params.vcodec,profile:null===(n=t.params.ext)||void 0===n?void 0:n.profile,videoOn:t.params.video,audioOn:t.params.audio,videoEnable:t.params.video_enable,audioEnable:t.params.audio_enable,simulcast:null!==(o=t.params.simulcast)&&void 0!==o?o:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);d.addStream(a),s.push(a)})),this.userMap.set(d.getUserId(),d)})),c.length&&this.hasMoreUser){const e=Math.ceil(c.length/100);for(let t=0;t<e;t++){if(this.signal.getConnectStatus()!==Wr.OPEN)return;const{values:e}=yield this.signal.queryUser({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),queryId:c.slice(100*t,Math.max(100*t+100,c.length))});ge(e,(e=>{var t,i;let r=this.userMap.get(e.userId);if(!r)return!0;if(u.set(e.userId,!0),r.updateInfo(e.info),null===(t=e.streams)||void 0===t?void 0:t.length){const t=[];r.getStreams().forEach(((e,i)=>{e instanceof Fn&&t.push(e)})),ge(e.streams,(i=>{var n,a,c;let u=r.getStream(i.streamId);if(u)u.update(i.params)&&o.push(u),Se(t,u);else{const t=new Fn({type:null===(n=i.params.ext)||void 0===n?void 0:n.streamType,userId:e.userId,streamId:i.streamId,acodec:i.params.acodec,vcodec:i.params.vcodec,profile:null===(a=i.params.ext)||void 0===a?void 0:a.profile,videoOn:i.params.video,audioOn:i.params.audio,videoEnable:i.params.video_enable,audioEnable:i.params.audio_enable,simulcast:null!==(c=i.params.simulcast)&&void 0!==c?c:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);r.addStream(t),s.push(t)}})),a.push(...t)}else null===(i=r.getStreams())||void 0===i||i.forEach(((e,t)=>{e instanceof Fn&&a.push(e)}))}))}}ge(a,(e=>{this.fire("stream-removed",[e]),e.close();const t=this.userMap.get(e.getUserId());t&&t.removeStream(e.getStreamId())})),ge(n,(e=>{var t;if(u.get(e))return!0;const i=this.userMap.get(e);i&&(null===(t=i.getStreams())||void 0===t||t.forEach((e=>{this.fire("stream-removed",[e])})),this.fire("peer-leaved",[e]),i.destroy(),this.userMap.delete(e))})),ge(r,(e=>{this.fire("peer-joined",[e])})),ge(s,(e=>{this.fire("stream-added",[e])})),ge(o,(e=>{this.fire("stream-update",[e])}))}))}join(e,t,i,r=null,n=!1,s=!1){var a,c;return Wn(this,void 0,void 0,(function*(){if(this.roomId=e,this.userId=t.id,this.silence=s,this.isBig=n,i&&(this.options.token=i),!(null===(a=this.options.proxies)||void 0===a?void 0:a.length))throw new Error("not has any proxy to connect");if(!this.options.token)throw new Error("not has token to connect");if(this.joined)throw new Error("has already connected");ge(this.options.proxies,(e=>{if(e.suffix={token:this.options.token},this.options.ip&&(e.suffix.ip=this.options.ip),this.options.location&&(e.suffix.location=this.options.location),o.h(this.options.canary)){let t="";ke(this.options.canary,((e,i)=>{t+=`${i},${e},`})),e.suffix.canary=t.slice(0,t.length-1)}})),this.signal=new Nn(this.options.proxies,{forceWS:this.options.forceWS,enableRace:this.options.enableRace,forceDC:this.options.forceDC,forceWT:this.options.forceWT,enableWT:this.options.enableWT},this.getRpc(),this.logger),this.handleEvents();const u=jn();yield this.signal.connect();const d=u(),l=Me({},t.info);l.create=!0,l.network=Ur.name,l.platform="Web",hi();try{const e=jn(),i=yield this.signal.join({roomId:this.roomId,userId:this.userId,isBig:n?1:0,silence:s,info:l,sessionId:r}),a=e();o.a(i.iceservers)&&ge(i.iceservers,(e=>{e.urls||(e.urls=e.url),this.iceServers.push(e)})),this.joined=!0,this.callId=(null===(c=i.raw)||void 0===c?void 0:c.callId)||"";const u=new Dn(this.userId,t.info);return this.userMap.set(u.getUserId(),u),this.pullUserIds=[],this.joinedUsersMap.clear(),this.hasMoreUser=i.value.length<i.total,this.parseUser(i),this.hasMoreUser||(this.pullUserIds=[]),this.logger.info(`joined: sessionId: ${i.sessionId}, callId: ${i.raw.callId}`),{sessionId:i.sessionId,callId:i.raw.callId,connectConsume:d,joinConsume:a,usedProxyConsume:this.signal.getConnectedProxyConsume(),connectCount:this.signal.getConnectCount()}}catch(e){throw this.logger.error(`join room failed: ${at(e)}, proxy: ${JSON.stringify(this.getActiveProxy())}`),this.signal.close(),e}}))}leave(){var e;return Wn(this,void 0,void 0,(function*(){this.signal&&(this.logger.info("leaved: sessionId: "+((null===(e=this.signal)||void 0===e?void 0:e.getSessionId())||"")),yield this.signal.leave({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId()||""}),this.signal.close(),this.signal=null,this.joined=!1)}))}publish(e,t){var i;return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(e.isDestroyed())throw new Error("stream has already destroyed");e.setLogger(this.logger),e.setUserId(this.userId),e.updateAudioLevelInterval(this.options.audioLevelInterval),this.logger.info(`publish: ${this.userId} ${e.getStreamId()} options: ${JSON.stringify(t)}`),t&&e.setOptions(t),t=e.getOptions();let r=yield e.processOffer(this,{iceServers:this.iceServers,enableSEI:this.options.enableSEI,enableSVC:this.options.enableSVC});const n=mr(Un(qn.concat([e.getOptions().acodec,e.getOptions().vcodec]),Jn,e.getOptions().profile),this.options.enableSVC&&"vp8"===t.vcodec.toLocaleLowerCase()&&o.i(t.encodings[0].scalabilityMode)?Xi(Ui.VIDEO,"scalability-mode",t.encodings[0].scalabilityMode,t.vcodec):null,Hn(mi()),this.options.enableAdaption?("rembFlags",s=Mt.PACKETS_LOST_SCALE,function(e){return e.rembFlags=s,e}):null).after((this.options.enableTCC,null));var s;e.published=!0;const a={};if(e.hasAudio()&&(a.audio={codec:t.acodec&&t.acodec.toLocaleUpperCase()||"OPUS",bitrate:Math.ceil(t.audioBitrate/1024)}),e.hasVideo()&&t.encodings.length){let e=0,r=-1,n=-1,s=-1;for(let o=0;o<t.encodings.length;o++)e+=null!==(i=t.encodings[o].bitrate)&&void 0!==i?i:0,r<t.encodings[o].width&&(r=t.encodings[o].width,s=t.encodings[o].fps),n<t.encodings[o].height&&(n=t.encodings[o].height);a.video={w:r,h:n,fps:s,codec:t.vcodec&&t.vcodec.toLocaleUpperCase()||"H264",bitrate:Math.ceil(e/1024)}}const{sdpAnswer:c}=yield this.signal.publish({roomId:this.roomId,userId:this.userId,streamId:e.getStreamId(),sessionId:this.signal.getSessionId(),options:{sdpOffer:n(r),audio:e.hasAudio(),video:e.hasVideo(),audio_enable:e.getAudioEnable(),video_enable:e.getVideoEnable(),attribute:a,simulcast:t.simulcast,ext:{streamType:e.getType(),stereo:e.hasAudio()&&t.stereo}}});yield e.processAnswer(c,{enableSEI:this.options.enableSEI,enableSVC:this.options.enableSVC}),this.userMap.get(this.userId).addStream(e),e.startCollecting()}))}unpublish(e){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(e.isDestroyed())throw new Error("stream has already destroyed");this.logger.info(`unpublish: ${e.getUserId()} ${e.getStreamId()}`),e.published=!1,e.close(),this.signal.unpublish({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId()}),this.userMap.get(this.userId).removeStream(e.getStreamId())}))}updateStream(e,t,i){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");this.logger.info(`updateStream: ${e.getUserId()} ${e.getStreamId()} options: ${JSON.stringify(t)}`),yield this.signal.controlStream({roomId:this.roomId,userId:this.userId,streamId:e.getStreamId(),sessionId:this.signal.getSessionId(),options:t},{key:i,maxRetry:3,errorRetry:!0,needRetry:e=>!!e&&(33===e.code||11===e.code||21===e.code||23===e.code||13===e.code)})}))}preferProfile(e,t){return Wn(this,void 0,void 0,(function*(){if(!(e instanceof Fn))throw new Error("stream not remotestream instance");if(e.isDestroyed())throw new Error("stream has already destroyed");if(!(t>=e.getSimulcast()))return this.updateStream(e,{profile:t},"preferProfile_"+e.getStreamId());this.logger.warn(`preferProfile: ${e.getUserId()} ${e.getStreamId()} not support, simulcast: ${e.getSimulcast()}, profile: ${t}`)}))}subscribe(e,t={audio:!0,video:!0,profile:0}){var i,r;return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(!(e instanceof Fn))throw new Error("stream not remotestream instance");if(e.isDestroyed())throw new Error("stream has already destroyed");this.logger.info(`subscribe: ${e.getUserId()} ${e.getStreamId()} options: ${JSON.stringify(t)}`);const n=e.getOptions();let s=yield e.processOffer(t.audio,t.video,{iceServers:this.iceServers,enableSEI:this.options.enableSEI});const a={sdpOffer:mr(Un(qn.concat([e.getOptions().acodec,e.getOptions().vcodec]),Jn,e.getOptions().profile),Hn(mi())).after(this.options.enableTCC?e=>{const t=e.findIndex((e=>Ie.d(e,"m=")));return t>-1?(e.splice(t,0,"a=adaption:1"),e.splice(t+1,0,"a=brtcversion:2.0")):(e.push("a=adaption:1"),e.push("a=brtcversion:2.0")),e}:null)(s),audio:e.hasAudio()&&t.audio,video:e.hasVideo()&&t.video,audio_enable:e.hasAudio()&&t.audio&&(null===(i=t.audioEnable)||void 0===i||i),video_enable:e.hasVideo()&&t.video&&(null===(r=t.videoEnable)||void 0===r||r)};n.simulcast>1&&(a.profile=o.f(t.profile)?t.profile:n.simulcast-1);const{sdpAnswer:c}=yield this.signal.subscribe({roomId:this.roomId,userId:this.userId,streamId:e.getStreamId(),sessionId:this.signal.getSessionId(),options:a});yield e.processAnswer(c,{enableSEI:this.options.enableSEI}),e.setAudioSubscribed(a.audio_enable),e.setVideoSubscribed(a.video_enable),e.subscribeOptions=t,e.startCollecting()}))}unsubscribe(e){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(e.isDestroyed())throw new Error("stream has already destroyed");this.logger.info(`unsubscribe: ${e.getUserId()} ${e.getStreamId()}`),e.close(),this.signal.unsubscribe({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId()})}))}setBitrate(e,t){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");e.isPublished()?yield this.signal.setBitrate({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId(),rate:t}):this.logger.warn(`can not setBitrate because of stream not publish, ${e.getUserId()} ${e.getStreamId()}`)}))}syncIcecandidate(e,t){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");yield this.signal.addIceCandidate({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),streamId:e.getStreamId(),candidate:t})}))}syncRoom(){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");const e=this.userMap.get(this.userId);if(e){const t=Me({},e.getUserInfo());t.create=!0,t.network=Ur.name,t.platform="Web";try{const e=yield this.signal.syncRoom({roomId:this.roomId,userId:this.userId,isBig:this.isBig?1:0,silence:this.silence,sessionId:null,info:t});this.pullUserIds=[],this.joinedUsersMap.clear(),this.hasMoreUser=e.value.length<e.total,yield this.syncUser(e),this.hasMoreUser||(this.pullUserIds=[]),this.fire("sync-room-completed")}catch(e){this.fire("error"),this.destroy()}}}))}pullUsers(e=120){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(!this.hasMoreUser)throw new Error("no more user to request");e=Cn(e,1,120),this.logger.info("pullUsers, count: "+e);try{const t=yield this.signal.pullUsers({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),count:e,cursor:this.pullUserIds[this.pullUserIds.length-1]||""}),i=t.value;if(i.length){const e=[],r=[];ge(i,(t=>{var i;if(this.joinedUsersMap.has(t.userId))return this.hasMoreUser=!1,this.pullUserIds=[],!1;this.pullUserIds.push(t.userId);const n=new Dn(t.userId,t.info.userinfo);r.push(n),(null===(i=t.streams)||void 0===i?void 0:i.length)&&ge(t.streams,(i=>{var r,s,o;const a=new Fn({type:null===(r=i.params.ext)||void 0===r?void 0:r.streamType,userId:t.userId,streamId:i.streamId,acodec:i.params.acodec,vcodec:i.params.vcodec,profile:null===(s=i.params.ext)||void 0===s?void 0:s.profile,videoOn:i.params.video,audioOn:i.params.audio,videoEnable:i.params.video_enable,audioEnable:i.params.audio_enable,simulcast:null!==(o=i.params.simulcast)&&void 0!==o?o:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);e.push(a),n.addStream(a)})),this.userMap.set(n.getUserId(),n)})),this.hasMoreUser&&(this.hasMoreUser=t.total>this.userMap.size),ge(r,(e=>{this.fire("peer-joined",[e.getUserId()])})),ge(e,(e=>{const t=this.userMap.get(e.getUserId());t&&t.getStream(e.getStreamId())&&this.fire("stream-added",[e])}))}else this.hasMoreUser=!1,this.pullUserIds=[]}catch(t){if(10===(null==t?void 0:t.code))return this.pullUserIds.pop(),this.pullUsers(e);throw t}return{hasMoreUser:this.hasMoreUser}}))}queryUsers(e){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");if(!o.a(e))throw new Error("userId must be string value array");if(!e.length)throw new Error("userId must not be empty array");if(!this.silence||!this.isBig)throw new Error("not support because of not silence and big room mode");if(this.logger.info("queryUsers, userIds: "+JSON.stringify(e)),!(e=e.filter((e=>e!==this.userId))).length)throw new Error("userIds must not only has self userId");const{values:t}=yield this.signal.queryUser({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),queryId:e}),i=[];return ge(t,(e=>{var t;(null===(t=null==e?void 0:e.streams)||void 0===t?void 0:t.length)&&ge(e.streams,(t=>{var r,n,s;const o=new Fn({type:null===(r=t.params.ext)||void 0===r?void 0:r.streamType,userId:e.userId,streamId:t.streamId,acodec:t.params.acodec,vcodec:t.params.vcodec,profile:null===(n=t.params.ext)||void 0===n?void 0:n.profile,videoOn:t.params.video,audioOn:t.params.audio,videoEnable:t.params.video_enable,audioEnable:t.params.audio_enable,simulcast:null!==(s=t.params.simulcast)&&void 0!==s?s:1,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);i.push(o),this.logger.debug(`stream added: ${e.userId} ${t.streamId}`)}))})),i}))}getMediaServers(){var e;return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");const t=yield this.signal.getMediaServers({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId()}),i=[];return(null===(e=t.servers)||void 0===e?void 0:e.length)&&ge(t.servers,(e=>{var t;(null===(t=e.data)||void 0===t?void 0:t.length)&&ge(e.data,(t=>{i.push({addr:t.addr,location:e.location,score:t.score})}))})),i.sort(((e,t)=>e.score-t.score))}))}setMediaServer(e,t){return Wn(this,void 0,void 0,(function*(){if(!this.joined)throw new Error("client not joined");t||(t=this.userId),yield this.signal.setMediaRelation({roomId:this.roomId,userId:this.userId,sessionId:this.signal.getSessionId(),selectUserId:t,node:e})}))}request(e,t){return Wn(this,void 0,void 0,(function*(){return this.signal.request(e,t)}))}getCallId(){return this.callId}destroy(){this.userMap&&(this.userMap.forEach((e=>{e.destroy()})),this.userMap.clear()),this.userMap=null,this.joinedUsersMap&&this.joinedUsersMap.clear(),this.joinedUsersMap=null,this.pullUserIds=[],this.signal&&(this.signal.close(),this.signal=null),this.joined=!1,this.off()}handleEvents(){this.signal.on("error",(()=>{this.logger.error("signal error"),this.fire("error")})).on("close",(()=>{this.logger.error("signal close"),this.fire("error")})).on("timeout",(()=>{this.logger.error("signal timeout"),this.fire("error")})).on("reconnected",(()=>{this.fire("reconnected")})).on("peer-joined",(e=>{let t=this.userMap.get(e.userId);t?t.updateInfo(e.info||{}):(t=new Dn(e.userId,e.info),this.userMap.set(t.getUserId(),t)),this.logger.debug("peer joined: "+t.getUserId()),this.joinedUsersMap.set(e.userId,!0),this.fire("peer-joined",[t.getUserId()])})).on("peer-leaved",(e=>{if(e.userId===this.userId)return;const t=this.userMap.get(e.userId);this.joinedUsersMap.delete(e.userId),t&&(this.userMap.delete(t.getUserId()),t.getStreams().forEach((e=>{this.fire("stream-removed",[e])})),this.logger.debug("peer leaved: "+t.getUserId()),this.fire("peer-leaved",[t.getUserId()]),t.destroy(),this.pullUserIds.length&&Se(this.pullUserIds,e.userId))})).on("room-closed",(()=>{this.logger.error("room closed"),this.fire("room-closed"),this.destroy()})).on("error",(()=>{this.logger.error("room error"),this.fire("error"),this.destroy()})).on("stream-added",(e=>{var t,i,r;if(e.userId===this.userId)return;let n=this.userMap.get(e.userId);n||(n=new Dn(e.userId,e.info),this.userMap.set(n.getUserId(),n));const s=n.getStream(e.streamId);if(s)if(s instanceof Fn){this.logger.warn(`stream added but has old stream, updated: ${n.getUserId()} ${e.streamId}`);let t=s.update(e.params);t&&this.fire("stream-update",[s]),t=s.updateCodec(e.params),t&&(this.logger.warn(`retry subscribe stream because of the stream's codec has updated, ${n.getUserId()} ${e.streamId}`),this.subscribe(s,{audio:s.getHasAudioKind(),video:s.getHasVideoKind(),audioEnable:s.getAudioSubscribed(),videoEnable:s.getVideoSubscribed()}).then((()=>{s.fire("stream-update",[{trackUpdate:!0}])})))}else this.logger.warn(`stream added but the streamId is same of localstream, ignored: ${n.getUserId()} ${e.streamId}`);else{this.logger.debug(`stream added: ${n.getUserId()} ${e.streamId}`);const s=new Fn({type:null===(t=e.params.ext)||void 0===t?void 0:t.streamType,stereo:null===(i=e.params.ext)||void 0===i?void 0:i.stereo,userId:n.getUserId(),streamId:e.streamId,acodec:e.params.acodec,vcodec:e.params.vcodec,profile:null===(r=e.params.ext)||void 0===r?void 0:r.profile,audioOn:e.params.audio,videoOn:e.params.video,audioEnable:e.params.audio_enable,videoEnable:e.params.video_enable,simulcast:e.params.simulcast,audioLevelInterval:this.options.audioLevelInterval},this,this.logger);n.addStream(s),this.fire("stream-added",[s])}})).on("stream-removed",(e=>{if(e.userId===this.userId)return;let t=this.userMap.get(e.userId);if(t){const i=e.streams||[];e.streamId&&!Ee(i,e.streamId)&&i.push(e.streamId),this.logger.debug(`stream removed: ${t.getUserId()} ${JSON.stringify(i)}`),ge(i,(e=>{const i=t.removeStream(e);i&&(this.fire("stream-removed",[i]),i.close())}))}})).on("stream-update",(e=>{const t=this.userMap.get(e.userId);if(t){const i=t.getStream(e.streamId);if(i){const r=i.update(e.params);this.logger.debug(`stream updated: ${t.getUserId()} ${e.streamId} options: ${JSON.stringify(e.params)}, updated: ${r}`),r&&this.fire("stream-update",[i])}}})).on("stream-error",(e=>{this.logger.error("stream error "+JSON.stringify(e.error)),this.fire("media-error",[e.error])})).on("stream-disconnected",(e=>{if(e.userId!==this.userId)return;const t=this.userMap.get(e.userId),i=t.getStream(e.streamId);i&&(this.logger.error(`stream disconnection: ${t.getUserId()} ${e.streamId}`),i.fire("stream-disconnected"))})).on("evicted",(e=>{if(this.isBig&&this.silence)return void(e.userId===this.userId&&(this.fire("evicted"),this.logger.error("peer evicted: "+this.userId)));const t=this.userMap.get(e.userId);t&&(t.getUserId()===this.userId?(t.getStreams().forEach((e=>{e.close()})),this.fire("evicted")):(t.getStreams().forEach((e=>{this.fire("stream-removed",[e])})),this.logger.error("peer evicted: "+t.getUserId()),this.userMap.delete(t.getUserId()),this.fire("peer-leaved",[t.getUserId()]),t.destroy()))})).on("peer-rejoined",(e=>{this.fire("peer-rejoined",[{userId:e.userId,platform:e.info.platform,device:e.info.device,ip:e.info.ip}]),this.logger.warn("peer rejoied: "+e.userId)})).on("token-expire",(()=>{this.logger.error("token expire"),this.fire("token-expire")})).on("token-will-expire",(e=>{this.logger.warn("token will expire"),this.fire("token-will-expire",[e.seconds])})).on("session-close",(()=>{this.logger.error("session closed, retry syncRoom"),this.syncRoom()})).on(ii,(e=>{this.logger.debug("notify: "+JSON.stringify(e)),this.fire(ii,[e])})).on("state-notify",(e=>{this.fire("state-notify",[e])})).on("server-proxy-change",(e=>{o.a(e.nodes)&&(ge(e.nodes,(e=>{if(e.suffix={token:this.options.token},this.options.ip&&(e.suffix.ip=this.options.ip),this.options.location&&(e.suffix.location=this.options.location),o.h(this.options.canary)){let t="";ke(this.options.canary,((e,i)=>{t+=`${i},${e},`})),e.suffix.canary=t.slice(0,t.length-1)}})),this.signal.tryChangeSelectedProxy(e.nodes))})).on("proxy-changed",(()=>{this.fire("proxy-changed")})).on("media-server-changed",(()=>{this.userMap.forEach((e=>{e.getStreams().forEach((e=>{e instanceof kr&&e.isPublished()?this.unpublish(e).then((()=>{this.publish(e)})):e instanceof Fn&&e.isSubscribed()&&this.subscribe(e,e.subscribeOptions).then((()=>{e.fire("stream-update",[{trackUpdate:!0}])}))}))}))}))}getRpc(){return{sessionClosed:()=>(Object(J.a)((()=>{this.syncRoom()})),{result:0})}}getActiveProxy(){return this.signal.getProxy()}}class Yn{constructor(e=500,t=50){this.interval=e,this.threshold=t,this.lastTime=z(),this.cpu=[0],this.delay=0,this.timer=new ct((()=>{this.process()}),0,this.interval)}process(){let e=1,t=z();this.delay=Math.max(t-this.lastTime-this.interval,0);let i=this.threshold;this.delay>this.interval+500&&(i*=this.delay/this.interval);let r=1;for(;r<100;)t>this.lastTime+r*i&&e++,r++;this.cpu.push(e),this.cpu.length>20&&this.cpu.shift(),this.lastTime=t}getCPU(){return Math.max(...this.cpu)}getDelay(){return this.delay}start(){this.timer.start()}stop(){this.timer.stop(),this.cpu=[0]}destroy(){this.timer.destroy(),this.cpu=[0]}}const Qn={callId:"",diffNTP:0,comments:""};class Kn{constructor(e){this.url=e.url,this.options=Me({},Qn,e),this.seq=0,this.transport=new Jr({tag:"Collection",interval:3e3,connectOnClose:!0,native:Gr,nativeOptions:{processOffer:(e,t)=>function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){const i={type:"offer",sdp:t,token:this.options.token,device_id:this.options.deviceId,trace_id:this.options.traceId,platform:"Web",appid:this.options.appId,room:this.options.roomId,user:this.options.userId,version:this.options.version,webrtcType:this.options.webrtcType,comments:this.options.comments};return this.options.clientIp&&(i.client_ip=this.options.clientIp),vn(e,i).then((e=>e.sdp)).catch((e=>{var t;throw this.options.report&&this.options.report({code:1,msg:"Collection request answer failed, error: "+(null!==(t=null==e?void 0:e.message)&&void 0!==t?t:"")}),e}))}))},onReceive:e=>{this.resetTimeout()},onClose:()=>{this.options.report&&this.options.report({code:2,msg:"Collection channel closed"})},onError:()=>{this.options.report&&this.options.report({code:3,msg:"Collection channel error"})},onTimeout:()=>{this.options.report&&this.options.report({code:4,msg:"Collection channel timeout"})},onOpen:e=>{this.options.report&&this.options.report({code:0,msg:"Collection channel opened"})},retryCount:2e3,refreshQueueOnClose:!0,timeout:1e4,queueMax:1800}),this.cpuSimulator=new Yn,this.cpuSimulator.start(),this.transport.connect({url:`${this.url}/${ei()}`})}resetTimeout(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}setTimeout(){this.timeout||(this.timeout=setTimeout((()=>{this.transport&&(this.transport.reconnect(),this.options.report&&this.options.report({code:5,msg:"Collection reconnect"})),this.timeout=null}),2e4))}setCallId(e){this.options.callId=e}heartbeat(){const e={type:"heart",callId:this.options.callId,ts:z()+this.options.diffNTP,seq:this.seq++};this.transport.send(JSON.stringify(e)),this.setTimeout()}action(e,t,i,r,n,s){if(!this.transport)return;const o=z(),a={type:"action",callId:this.options.callId,ts:o+this.options.diffNTP,action:e,sendTs:(i||o)+this.options.diffNTP,receiveTs:(r||o)+this.options.diffNTP,success:t>0?0:1,eid:ei(),seq:this.seq++};t>0&&(a.errorCode=t),null!=s&&(a.vErrorCode=s),n&&(a.options=n),this.transport.send(JSON.stringify(a)),this.setTimeout()}stats(e,t,i,r,n,s=0){if(!this.transport)return;t&&(t.cpu={systemCpu:this.cpuSimulator.getCPU(),systemDelay:this.cpuSimulator.getDelay()});const o={type:"stats",callId:this.options.callId,stream:e,flow:i?"push":"pull",ts:z()+this.options.diffNTP,seq:this.seq++,stats:t};i||(o.remote=r),n&&ke(n,((e,t)=>{o[t]=e})),this.transport.send(JSON.stringify(o)),this.setTimeout()}log(e,t,i={}){const r={type:"sdklog",ts:z()+this.options.diffNTP,seq:this.seq++,level:t,log:e,extend:i};this.transport.send(JSON.stringify(r)),this.setTimeout()}destroy(){this.transport&&(this.transport.close(),this.transport=null),this.cpuSimulator&&(this.cpuSimulator.destroy(),this.cpuSimulator=null)}}function Xn(e){return new Promise(((t,i)=>{navigator.mediaDevices.enumerateDevices().then((i=>{t(function(e,t){const i=[];let r=0;for(let n of t)if(n.kind==e||"all"==e){let e={label:"",groupId:n.groupId,deviceId:n.deviceId,kind:n.kind};""===n.label?(r++,"videoinput"==n.kind?e.label="Camera-"+r:"audioinput"==n.kind?e.label="Mic-"+r:"audiooutput"==n.kind?e.label="Speaker-"+r:(r--,e.label="unknown device")):e.label=n.label,e.deviceId&&i.push(e)}return i}(e,i))})).catch((e=>{i(e)}))}))}function Zn(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){let e=yield Xn(Bi.AUDIO_INPUT),t={};return e.filter((e=>("default"===e.deviceId&&(t=e),"default"!==e.deviceId&&"communications"!==e.deviceId))).map(((e,i)=>({name:e.label,deviceId:e.deviceId,groupId:e.groupId,index:i,kind:"audioinput",default:e.groupId===t.groupId&&t.label&&t.label.indexOf(e.label)>-1})))}))}function es(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){const e=yield Xn(Bi.VIDEO_INPUT);let t={};return e.filter((e=>("default"===e.deviceId&&(t=e),"default"!==e.deviceId&&"communications"!==e.deviceId))).map(((e,i)=>({name:e.label,deviceId:e.deviceId,groupId:e.groupId,index:i,kind:"videoinput",default:e.groupId===t.groupId&&t.label&&t.label.indexOf(e.label)>-1})))}))}function ts(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){let e=yield Xn(Bi.AUDIO_OUTPUT),t={};return e.filter((e=>("default"===e.deviceId&&(t=e),"default"!==e.deviceId&&"communications"!==e.deviceId))).map(((e,i)=>({name:e.label,deviceId:e.deviceId,groupId:e.groupId,index:i,kind:"audiooutput",default:e.groupId===t.groupId&&t.label&&t.label.indexOf(e.label)>-1})))}))}const is={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,b:11,c:12,d:13,e:14,f:15},rs=void 0!==window.localStorage;let ns=G.b,ss=G.b;G.b,rs&&(ns=function(e,t){if(o.e(e))ke(e,((e,t)=>{ns(t,e)}));else try{localStorage[e]=t}catch(e){}},ss=function(e){let t;try{t=localStorage[e]}catch(e){}return t});const os=ns,as=ss;var cs=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class us{constructor(e){var t,i,r,n;if(this.mode="rtc",this.codec="h264",this.audioCodec="opus",this.comments="",!e||!o.i(e.appId))throw new C(1001,"appId 类型错误,请检查");this.options=e,e.comments&&(this.comments=e.comments.substring(0,64)),this.brtcAppId=e.appId,this.deviceId=as("brtc_device_id"),this.deviceId||(this.deviceId=Y(),os("brtc_device_id",this.deviceId)),this.codec=null!==(t=e.codec)&&void 0!==t?t:"h264",this.roomType=null!==(i=e.roomType)&&void 0!==i?i:"normal",this.webrtcType=0,this.emitter=new Ne(!0),this.promiseHoldMap={},this.remoteStreamMap={},this.publishStream=null,this.sessionId=null,this.publishOnly=!!e.publishOnly,this.useStringUserId=!!e.useStringUserId,this.isJoinning=!1,this.role=null!==(r=e.role)&&void 0!==r?r:"anchor",this.diffNTP=0,this.options.audioLevelInterval=null!==(n=this.options.audioLevelInterval)&&void 0!==n?n:1e3,this.isEnableSmallStream=!1,this.smallStreamCodecOption=Me({},Wt),this.destroyed=!1,this.publishNamespace=".client_publish_stream_close"+Math.random(),this.enableSVC=!1,this.logger=new ti({uploadLevel:he.getUploadLevel(),onUpload:(e,t,i)=>{this.collection&&this.collection.log(e,t,{tag:i||"brtc"})}}),this.reportTimer=new ct(this.reportStats.bind(this),2e3,2e3),this.ondevicechangeHandler=$e((e=>{this.reportDeviceList()}),200);try{navigator.mediaDevices.addEventListener("devicechange",this.ondevicechangeHandler)}catch(e){this.logger.error("bind devicechange event handler failed, userId: "+this.userId,"client")}this.logger.info(`create client, userId: ${this.userId}, mode: ${this.mode}, codec: ${this.codec}`,"client")}reportDeviceList(){return cs(this,void 0,void 0,(function*(){if(this.collection){const[e,t,i]=yield Promise.all([Zn(),ts(),es()]),r=i.concat(e).concat(t);this.reportAction("deviceEnumerate",0,null,null,{list:r.map((e=>({device_id:e.deviceId,group_id:e.groupId,name:e.name,kind:e.kind,default:e.default})))})}}))}getBRTCRoomId(){return`${this.roomId}@${this.brtcAppId}`}clearObject(){a(this.webrtcType)&&this.client?this.client.destroy():c(this.webrtcType)&&this.client&&this.client.off("*"),this.client=null,this.sessionId=null,this.publishStream=null,this.remoteStreamMap={},this.reportTimer&&this.reportTimer.stop(),this.collection&&(this.collection.destroy(),this.collection=null)}joinFailReport(e=0,t="",i){const r={appid:this.brtcAppId,rid:this.getBRTCRoomId(),uid:this.userId,sig:this.userSig,err_code:e,msg:t};i&&(r.ext=i),function(e){$r(this,void 0,void 0,(function*(){const t=Me({os:Kt.name,sdk_ver:h,os_ver:Kt.version,network_type:Ur.name,device:`${Kt.name}/${Kt.version} ${ot.name}/${ot.version}`},e);return fetch(`${"production"===l?"https://qs.baijiayun.com/brtcsdkreport":"https://test-qs.baijiayun.com/brtcsdkreport"}?${Fr(t)}`,{cache:"no-cache",credentials:"same-origin",headers:{Accept:"text/plain","Content-Type":"text/plain"},method:"GET",mode:"cors",redirect:"follow",referrer:"no-referrer"})}))}(r)}getVT(){return cs(this,void 0,void 0,(function*(){let e=yield function(e){return $r(this,void 0,void 0,(function*(){const t={app_id:e.appId,room_id:e.roomId,user_id:e.userId,sig:e.sign,ts:Math.floor((new Date).getTime()/1e3),platform:"Web",version:h,device_id:e.deviceId};return e.comments&&(t.comments=e.comments),e.clientIP&&(t.client_ip=e.clientIp),jr(Vr(),t,[Vr(!0)])}))}({appId:this.brtcAppId,sign:this.userSig,roomId:this.roomId,userId:this.userId,comments:this.comments,clientIP:this.clientIP,deviceId:this.deviceId}).catch((e=>{throw this.joinFailReport(5e3,"userSig 验证接口请求失败"),new C(5e3,"userSig 验证接口请求失败")}));if(200!==e.code)throw this.joinFailReport(5e3,"userSig 验证接口请求失败",{code:e.code,msg:e.msg}),new C(5e3,e.msg);return this.token=e.data.ut,this.traceId=e.data.trace,this.reportThreshold=e.data.report.rtc,this.masterResSettings=e.data.settings,this.masterResSettings.sdk_video_svc_mode&&(this.masterResSettings.sdk_video_svc_mode=this.masterResSettings.sdk_video_svc_mode.replace(/T[4-9]/,"T3")),this.reportTimer.updateInterval(1e3*this.reportThreshold.meet_call_quality_upload_rate_interval),this.logger&&o.f(this.reportThreshold.sdk_log_level)&&this.logger.setUploadLevel(this.reportThreshold.sdk_log_level),e}))}getUserId(){return this.userId}join(e,t,i,r={}){var n,s,u,d,l,p,v,g,_;return cs(this,void 0,void 0,(function*(){if(this.destroyed)throw new C(1002,"client 已调用 destroy 方法");if(this.isJoinning)throw new C(1002,"正在 join,请勿重复调用");if(this.client)throw new C(1002,"重复 join,请先调用 leave");if(!o.i(e))throw this.joinFailReport(1001,"roomId 类型错误,请检查",{roomId:e}),new C(1001,"roomId 类型错误,请检查");if(this.useStringUserId){if(!o.i(t))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:t}),new C(1001,"userId 类型错误,请检查");if(!/^[0-9a-zA-Z-_]{1,64}$/.test(t))throw this.joinFailReport(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符",{userId:t}),new C(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符")}else{if(!o.f(t))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:t}),new C(1001,"userId 类型错误,请检查");if(t>Math.pow(2,31)-1||t<-Math.pow(2,31)||Math.floor(t)!==t)throw this.joinFailReport(1001,"userId 为 int32 整型",{userId:t}),new C(1001,"userId 为 int32 整型")}if(!o.i(i))throw new C(1001,"sig 类型错误,请检查");this.roomId=e,this.userId=t,this.userSig=i,this.joinConfig=r,this.isJoinning=!0;const S=jn(),b=jn();let T=yield this.getVT();const I=b();let R,k=0,A=0,M=0,O=0,L="WebSocket";this.joinConfig.role&&(this.role=this.joinConfig.role);const P=Q();try{let e=this.token.split(".");if(3!==e.length||!o.i(e[1])||!e[1])throw this.logger.error("client join fail, userId: "+this.userId,"client"),this.joinFailReport(5001,"ut 格式错误",{ut:this.token}),new C(5001,this.userSig);if(R=JSON.parse(Bt(e[1])),!o.f(R.sub)&&!/^[0-9a-zA-Z-_]{1,64}$/.test(R.sub))throw this.joinFailReport(5001,"ut user_id 类型错误,请检查",{sub:R.sub}),new C(5001,"user_id 类型错误,请检查");if(this.userId!==W(R.sub,this.useStringUserId))throw this.joinFailReport(5001,"签名的 userId 与传入的 userId 不符",{userId:this.userId,sub:R.sub}),new C(5001,"签名的 userId 与传入的 userId 不符");if(this.brtcAppId!==R.u)throw this.joinFailReport(5001,"签名的 appId 与传入的 appId 不符",{appId:this.brtcAppId,u:R.u}),new C(5001,"签名的 appId 与传入的 appId 不符");if(this.roomId!==R.r)throw this.joinFailReport(5001,"签名的 roomId 与传入的 roomId 不符",{roomId:this.roomId,r:R.r}),new C(5001,"签名的 roomId 与传入的 roomId 不符");if(this.vloudProxy=R.s,this.webrtcAppId=R.c,this.webrtcType=R.m,this.sign=R.sig,a(this.webrtcType)&&(this.sign=this.token),o.h(R.canary)&&(this.canary=R.canary),c(this.webrtcType)&&o.i(this.webrtcAppId)&&!/^[0-9]+$/.test(this.webrtcAppId))throw this.joinFailReport(5001,"trtc appId 类型错误",{appId:this.webrtcAppId}),new C(5001,"trtc appId 类型错误,请检查");this.privileges=new Ut(o.f(R.p)?R.p:0),N=this.webrtcType,m=N}catch(e){if(this.isJoinning=!1,C.instanceOf(e))throw new C(e.code,e.message);throw this.joinFailReport(5001,"userSig 验证失败"),new C(5001,"userSig 验证请求失败")}var N,D,x;try{let e=T.data.services;if(!1===e.ip_accurate&&e.ip_url)try{const t=yield Hr(e.ip_url,{});if(200!==t.code||!(null===(n=t.data)||void 0===n?void 0:n.ip))throw new C(5004,"ip 请求失败");{this.clientIP=t.data.ip;const i=yield this.getVT();e=i.data.services}}catch(t){this.joinFailReport(5004,"ip request failed, use before",{ip:e.ip}),this.logger.warn("ip request failed, use before","client")}else this.clientIP=e.ip;if(e.timestamp&&(this.diffNTP=e.timestamp-Q()),e.collection&&(this.collection=new Kn({url:e.collection,appId:this.brtcAppId,roomId:this.getBRTCRoomId(),callId:null,userId:Object(Be.a)(this.userId),diffNTP:this.diffNTP,webrtcType:this.webrtcType,version:h,comments:this.comments,clientIp:this.clientIP,traceId:this.traceId,deviceId:this.deviceId,token:this.token,report:e=>{this.joinFailReport(6e3+(o.f(e.code)?e.code:0),"collection 连接错误",e)}})),this.destroyed)throw new C(4013,"client 已调用 destroy 方法");if(a(this.webrtcType)){const t=y||[];this.enableSVC=(!!(null===(s=this.masterResSettings)||void 0===s?void 0:s.sdk_svc_enabled)||function(e,t){if(!e)return!1;const i=Math.floor(1);return!(i>=e.length)&&1==(is[e[e.length-1-i].toLocaleLowerCase()]>>0&1)}(null===(u=this.masterResSettings)||void 0===u?void 0:u.extend))&&(ot.chrome||ot.edge)&&ot.checkVersion(ot.majorVersion,"111",!0),this.client=new zn({proxies:t.concat(e.proxies),forceWS:1===E(),forceDC:2===E(),forceWT:3===E(),enableRace:!1,enableWT:!!(null===(d=this.masterResSettings)||void 0===d?void 0:d.sdk_quic_enabled),audioLevelInterval:this.options.audioLevelInterval,enableTCC:!!(null===(l=this.masterResSettings)||void 0===l?void 0:l.sdk_tcc_enabled),enableAdaption:!!(null===(p=this.masterResSettings)||void 0===p?void 0:p.sdk_video_adaption_enabled),enableSEI:!!this.options.enableSEI,enableSVC:this.enableSVC,canary:f||this.canary||null,ip:this.clientIP},this.logger),this.handleEvent();let i=yield this.client.join(this.getBRTCRoomId(),{id:Object(Be.a)(this.userId),info:{version:h,device:`${Kt.name}/${Kt.version} ${ot.name}/${ot.version}`,ua:navigator.userAgent,role:this.role,comments:this.comments}},this.token,this.sessionId,"big"===this.roomType,!0===this.options.silence);this.sessionId=i.sessionId,k=i.connectConsume,M=i.joinConsume,O=i.connectCount,A=i.usedProxyConsume,this.collection&&this.collection.setCallId(i.callId);const r=this.client.getActiveProxy(),n=r.activeUrl||r.url||r.dcurl;/^webtransport:\/\//.test(n)?L="WebTransport":/^https?:\/\//.test(n)&&(L="DataChannel"),this.reportAction("signalChannelConnect",0,P,Q(),{proxy:{url:n,location:null!==(v=r.location)&&void 0!==v?v:"",consume:A}})}else c(this.webrtcType)&&(this.collection&&this.collection.setCallId(R.l),this.client=yt.a.createClient({mode:this.mode,sdkAppId:+this.webrtcAppId,userId:Object(Be.a)(this.userId),userSig:this.sign,useStringRoomId:!0,autoSubscribe:!1,enableAutoPlayDialog:!1,enableSEI:this.options.enableSEI}),M=Math.max(Q()-P,0),this.isEnableSmallStream?this.client.enableSmallStream():this.client.disableSmallStream(),this.handleEvent(),yield this.client.join({roomId:this.getBRTCRoomId()}),this.reportAction("signalChannelConnect",0,P,Q()));if(this.destroyed)throw new C(4013,"client 已调用 destroy 方法");this.reportTimer.isStarted()||this.reportTimer.start();const t={version:h,device:`${Kt.name}/${Kt.version} ${ot.name}/${ot.version}`,network:Ur.name,platform:"Web",role:this.role,ua:navigator.userAgent||"",vtConsume:I,usedProxyConsume:A,connectConsume:k,joinConsume:M,connectCount:O,totalConsume:S(),proxyType:L};this.reportAction("joinRoom",0,P,Q(),t),this.logger.info(`client join suceess, userId: ${this.userId}, userSig: ${this.userSig}, data: ${JSON.stringify(t)}`,"client"),this.isJoinning=!1,this.reportDeviceList(),c(this.webrtcType)&&Object(J.a)((()=>{ke(this.remoteStreamMap,(e=>{ge(e,(e=>{e._brtcAddEventPadding_&&(delete e._addEventPadding_,this.fire(w,{stream:e}))}))}))}));try{D=()=>cs(this,void 0,void 0,(function*(){return e.detectors?function(e,t,i,r){return $r(this,void 0,void 0,(function*(){return Hr(r,{sig:e,room_id:t,user_id:i})}))}(this.userSig,this.roomId,this.userId,e.detectors):Promise.reject("no url to post")})),x=this.joinFailReport.bind(this),Yr||(Kr=D,Xr=x,Yr=!0,cn())}catch(e){}}catch(e){this.isJoinning=!1;let t=at(e),i=function(e,t){return C.instanceOf(e)?e.getCode():4e3}(e);if("request timeout"===t?i=4011:"connect all proxies failed"===t&&(i=4012),a(this.webrtcType)){const e=null===(g=this.client)||void 0===g?void 0:g.getActiveProxy();e&&(t=`error: ${t}, url: ${e.url||e.dcurl}, location: ${null!==(_=e.location)&&void 0!==_?_:""}`)}throw this.reportAction("joinRoom",i,P,Q(),{version:h,device:`${Kt.name}/${Kt.version} ${ot.name}/${ot.version}`,network:Ur.name,platform:"Web",role:this.role,ua:navigator.userAgent||"",msg:t},dt(e)),this.clearObject(),this.joinFailReport(i,"client join failed, "+t,{vError:dt(e)}),this.logger.error(`client join fail, userId: ${this.userId}, error: ${at(e)}`,"client"),new C(4e3,"client join 失败",e)}}))}leave(e="none"){return cs(this,void 0,void 0,(function*(){if(!this.client)throw new C(1002,"没有 joined");let t=Q();try{if(this.publishStream&&("rejoined"!==e&&"evicted"!==e&&"room_close"!==e&&(yield this.unpublish(this.publishStream)),this.publishStream.close()),Re(this.remoteStreamMap).length)for(let e in this.remoteStreamMap)ge(this.remoteStreamMap[e],(e=>{e.destroy()}))}catch(e){}try{a(this.webrtcType)?"rejoined"!==e&&"evicted"!==e&&"room_close"!==e&&(yield this.client.leave()):c(this.webrtcType)&&(yield this.client.leave()),this.reportAction("leaveRoom",0,t,Q(),{reason:e}),this.logger.info("client leave success, userId: "+this.userId,"client"),this.clearObject()}catch(i){throw this.reportAction("leaveRoom",ut(i),t,Q(),{reason:e},dt(i)),this.logger.error(`client leave fail, userId: ${this.userId}, error: ${at(i)}`,"client"),this.clearObject(),new C(ut(i),"client leave 失败",i)}}))}clear(){try{if(this.publishStream){if(a(this.webrtcType)){let e=this.publishStream.getStream();this.client.unpublish(e)}else c(this.webrtcType)&&this.client&&this.client.unpublish(this.publishStream.getStream());this.publishStream.setClient(null),this.publishStream.setCollection(null),this.publishStream.setPrivileges(null),this.publishStream=null}if(Re(this.remoteStreamMap).length)for(let e in this.remoteStreamMap)ge(this.remoteStreamMap[e],(e=>{e.destroy()}));a(this.webrtcType)?this.client&&this.client.leave():c(this.webrtcType)&&this.client&&this.client.leave()}catch(e){}this.clearObject()}_publish(e,t=0){var i,r;return cs(this,void 0,void 0,(function*(){let n=e.getStream();try{yield this.client.publish(n,{acodec:this.audioCodec,vcodec:this.codec,simulcast:this.isEnableSmallStream?2:1,encodings:this.getEncodings(e),audioBitrate:1024*e.getAudioBandwidth()})}catch(n){if(t>=(null!==(i=this.reportThreshold.brtc_flow_retry_times)&&void 0!==i?i:3)-1)throw n;yield new Lr(null!==(r=this.reportThreshold.brtc_flow_retry_interval)&&void 0!==r?r:1),yield this._publish(e,++t)}}))}publish(e){return cs(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("publish, client 未 join,请先执行 join"),new C(1002,"client 未 join,请先执行 join");if("audience"===this.role)throw this.logger.error("publish, audience(观众)不支持推流,请先执行 switchRole 切换角色为 anchor(主播)"),new C(1002,"audience(观众)不支持推流,请先执行 switchRole 切换角色为 anchor(主播)");if(!(e instanceof Or))throw this.logger.error("publish, stream 参数错误"),new C(1001,"stream 参数错误");if(e.hasAudio()&&this.privileges.enableAuth()&&!this.privileges.canPushAudio())throw this.logger.error("publish, 没有音频推送权限"),new C(1011,"没有音频推送权限");if(e.hasVideo()&&this.privileges.enableAuth()&&!this.privileges.canPushVideo())throw this.logger.error("publish, 没有视频推送权限"),new C(1012,"没有视频推送权限");if(!e.getStream())throw this.logger.error("publish, LocalStream 未初始化"),new C(1002,"LocalStream 未初始化");if(!e.hasAudio()&&!e.hasVideo())throw this.logger.error("publish, LocalStream 至少需要一个媒体轨道"),new C(1002,"LocalStream 至少需要一个媒体轨道");if(this.publishStream&&this.publishStream!==e)throw this.logger.error("publish, 当前已在推流,请先执行 unpublish 取消之前的 localstream 推流再推新的 localstream"),new C(1002,"当前已在推流,请先执行 unpublish 取消之前的 localstream 推流再推新的 localstream");e.setUserId(this.userId),e.setLogger(this.logger),this.webrtcType!==e.getWebRTCType()&&(yield e.switchWebRTC(this.webrtcType));let t=Q();e.setICEStartTS(t),this.logger.info("user call publish, streamId: "+e.getStreamId());let i={};e.hasAudio()&&(i.audio={codec:this.audioCodec.toLocaleUpperCase(),bitrate:e.getAudioBandwidth()}),e.hasVideo()&&(i.video={w:e.streamCodecOption.width,h:e.streamCodecOption.height,fps:e.streamCodecOption.frameRate,bitrate:e.streamCodecOption.bitrate,codec:this.codec.toLocaleUpperCase()});try{if(e.getAudioOn()&&this.reportAction("audioEnable",0,null,null,{stream:e.getActionStreamId()}),e.getVideoOn()&&this.reportAction("videoEnable",0,null,null,{stream:e.getActionStreamId()}),a(this.webrtcType))yield this._publish(e),this.fire(A,{stream:e});else if(c(this.webrtcType)){if(this.isEnableSmallStream){const t=this.getEncodings(e);this.client.setSmallStreamProfile({width:t[0].width,height:t[0].height,framerate:e.getStreamCodecOption().frameRate,bitrate:this.smallStreamCodecOption.bitrate})}yield this.client.publish(e.getStream()),this.fire(A,{stream:e})}this.publishStream=e,e.setClient(this),e.setCollection(this.collection),e.setPrivileges(this.privileges),e.syncClientOptions(this.options),this.publishNamespace&&e.has(this.publishNamespace)&&e.off(this.publishNamespace),e.on(le+this.publishNamespace,(()=>{this.publishStream===e&&(this.publishStream=null)})),this.reportAction("publish",0,t,Q(),{cameraId:e.streamDeviceOption.cameraId||"track",microphoneId:e.streamDeviceOption.microphoneId||"track",stream:e.getActionStreamId(),audio:e.hasAudio(),video:e.hasVideo(),audio_enable:e.getAudioOn(),video_enable:e.getVideoOn(),attribute:i,msip:e.getMSIP()}),this.logger.info("client publish success, userId: "+this.userId,"client")}catch(r){throw this.reportAction("publish",ut(r),t,Q(),{cameraId:e.streamDeviceOption.cameraId,microphoneId:e.streamDeviceOption.microphoneId,stream:e.getActionStreamId(),audio:e.hasAudio(),video:e.hasVideo(),audio_enable:e.getAudioOn(),video_enable:e.getVideoOn(),attribute:i,msip:e.getMSIP()},dt(r)),this.logger.error(`client publish fail, userId: ${this.userId}, error: ${at(r)}`,"client"),new C(ut(r),"推流失败",r)}}))}unpublish(e){return cs(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("unpublish, client 未 join,请先执行 join"),new C(1002,"client 未 join,请先执行 join");if(!(e instanceof Or))throw this.logger.error("unpublish, stream 参数错误"),new C(1001,"stream 参数错误");if(!this.publishStream)throw this.logger.error("unpublish, stream 未发布"),new C(1002,"stream 未发布");let t=Q(),i=e.getActionStreamId();this.logger.info("user call unpublish, streamId: "+e.getStreamId());try{if(a(this.webrtcType)){let t=e.getStream();yield this.client.unpublish(t)}else c(this.webrtcType)&&(yield this.client.unpublish(e.getStream()));this.reportAction("unpublish",0,t,Q(),{stream:i}),e.setClient(null),e.setCollection(null),e.setPrivileges(null),this.publishStream=null,this.logger.info("client unpublish success, userId: "+this.userId,"client")}catch(e){throw this.publishStream=null,this.reportAction("unpublish",ut(e),t,Q(),{stream:i},dt(e)),this.logger.error(`client unpublish fail, userId: ${this.userId}, error: ${at(e)}`,"client"),new C(ut(e),"取消推流失败",e)}}))}_subscribe(e,t,i=0){var r,n;return cs(this,void 0,void 0,(function*(){let s=e.getStream();if(!s)throw new C(4010,"stream 已被销毁");try{yield Promise.race([yield this.client.subscribe(s,{audio:t.audio,video:t.video,audioEnable:!(!1===t.audioEnable),videoEnable:!(!1===t.videoEnable),profile:"small"===t.streamType?0:1}).then((()=>(e.onSubscribe(),0))),new Lr(10)]).then((t=>{if(t)throw new C(4007,`订阅流 ${e.getUserId()} 超时`)}))}catch(s){if(i>=(null!==(r=this.reportThreshold.brtc_flow_retry_times)&&void 0!==r?r:3)-1||s&&!1===s.retry)throw s;yield new Lr(null!==(n=this.reportThreshold.brtc_flow_retry_interval)&&void 0!==n?n:1),this.logger.warn(`client retry subscribe, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()}`),yield this._subscribe(e,t,++i)}}))}subscribe(e,t={audio:!0,video:!0}){return cs(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("subscribe, client 未 join,请先执行 join"),new C(1002,"client 未 join,请先执行 join");if(!(e instanceof Lt))throw this.logger.error("subscribe, stream 参数错误"),new C(1001,"stream 参数错误");if(!e.getStream())throw this.logger.error("subscribe, stream 已被销毁"),new C(1002,"stream 已被销毁");if(this.publishOnly)throw this.logger.error("subscribe, 当前 client 已被设置为只能 publish 流"),new C(1002,"当前 client 已被设置为只能 publish 流");if(!t.audio&&!t.video)throw this.logger.error("subscribe, 音频和视频至少需要订阅一个"),new C(1002,"音频和视频至少需要订阅一个");if(e.isUnpublish())throw this.logger.error("subscribe, stream 已不存在,无法再次订阅"),new C(1002,"stream 已不存在,无法再次订阅");o.i(t.streamType)||(t.streamType="big");let i=Q();e.setICEStartTS(i),e.onUnsubscribe(),this.logger.info(`user call subscribe, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()}`);try{a(this.webrtcType)?(yield this._subscribe(e,t),e.subscribeOptions=t,this.fire(M,{stream:e}),this.reportAction("subscribe",0,i,Q(),{audio:t.audio,video:t.video,stream:e.getActionStreamId(),msip:e.getMSIP(),remote_id:Object(Be.a)(e.getUserId())}),this.fire(k,{stream:e})):c(this.webrtcType)&&("small"===t.streamType&&(yield this.client.setRemoteVideoStreamType(e.getStream(),t.streamType)),yield Promise.race([new Promise(((i,r)=>{this.promiseHoldMap[e.getUserId()]={resolve:i,reject:r},this.client.subscribe(e.getStream(),t)})),new Lr(10)]).then((t=>{if(t)throw delete this.promiseHoldMap[e.getUserId()],new C(4007,`订阅流 ${e.getUserId()} 超时`)})),e.onSubscribe(),e.subscribeOptions=t,this.reportAction("subscribe",0,i,Q(),{audio:t.audio,video:t.video,stream:e.getActionStreamId(),msip:e.getMSIP(),remote_id:Object(Be.a)(e.getUserId())})),this.logger.info(`client subscribe success, userId: ${this.userId}, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()} options: ${JSON.stringify(t)}`,"client")}catch(r){if(this.logger.error(`client subscribe fail, userId: ${this.userId}, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()} error: ${at(r)}`,"client"),this.reportAction("subscribe",ut(r),i,Q(),{audio:t.audio,video:t.video,stream:e.getActionStreamId(),msip:e.getMSIP(),remote_id:Object(Be.a)(e.getUserId())},dt(r)),C.instanceOf(r))throw new C(r.code,r.message);throw new C(ut(r),null,r)}}))}unsubscribe(e){return cs(this,void 0,void 0,(function*(){if(!this.client)throw this.logger.error("unsubscribe, client 未 join,请先执行 join"),new C(1002,"client 未 join,请先执行 join");if(!(e instanceof Lt))throw this.logger.error("unsubscribe, stream 参数错误"),new C(1001,"stream 参数错误");if(!e.getStream())throw this.logger.error("unsubscribe, stream 已被销毁"),new C(1002,"stream 已被销毁");if(this.publishOnly)throw this.logger.error("unsubscribe, 当前 client 已被设置为只能 publish 流"),new C(1002,"当前 client 已被设置为只能 publish 流");let t=Q(),i=e.getActionStreamId();this.logger.info(`user call unsubscribe, streamUserId: ${e.getUserId()}, streamId: ${e.getStreamId()}`);try{if(a(this.webrtcType)){let t=e.getStream();yield this.client.unsubscribe(t)}else c(this.webrtcType)&&(yield this.client.unsubscribe(e.getStream()));e.onUnsubscribe(),e.subscribeOptions=null,this.reportAction("unsubscribe",0,t,Q(),{stream:i,remote_id:Object(Be.a)(e.getUserId())}),this.logger.info(`client unsubscribe success, userId: ${this.userId}, streamUserId: ${e.getUserId()}`,"client")}catch(r){throw e.onUnsubscribe(),this.reportAction("unsubscribe",ut(r),t,Q(),{stream:i,remote_id:Object(Be.a)(e.getUserId())},dt(r)),this.logger.error(`client unsubscribe fail, userId: ${this.userId}, streamUserId: ${e.getUserId()}, error: ${at(r)}`,"client"),new C(ut(r),"unsubscribe",r)}}))}enableSmallStream(){return cs(this,void 0,void 0,(function*(){if(!un())throw new C(1002,"不支持大小流");this.publishStream&&this.logger.warn("enableSmallStream 不支持在 publish 之后设置, userId: "+this.userId,"client"),this.isEnableSmallStream=!0,this.client&&c(this.webrtcType)&&this.client.enableSmallStream()}))}disableSmallStream(){return cs(this,void 0,void 0,(function*(){if(this.publishStream)throw new C(1002,"不支持在 publish 之后设置");this.isEnableSmallStream=!1,this.client&&c(this.webrtcType)&&this.client.disableSmallStream()}))}setRemoteVideoStreamType(e,t){return cs(this,void 0,void 0,(function*(){if(!e.isSubscribed())throw new C(1002,"只能在订阅之后设置");if(!e.getStream())throw new C(1002,"流已不存在");try{if(a(this.webrtcType)){let i=e.getStream();yield this.client.preferProfile(i,"big"===t?1:0)}else c(this.webrtcType)&&(yield this.client.setRemoteVideoStreamType(e.getStream(),t))}catch(t){throw this.logger.error(`client setRemoteVideoStreamType fail, userId: ${this.userId}, streamUserId: ${e.getUserId()}, error: ${at(t)}`,"client"),new C(9e3,"setRemoteVideoStreamType",t)}}))}setSmallStreamProfile(e){Me(this.smallStreamCodecOption,e)}switchRole(e){return cs(this,void 0,void 0,(function*(){this.role=e}))}pullUsers(e=120){return cs(this,void 0,void 0,(function*(){if(!this.client)throw new C(1002,"client 未 join,请先执行 join");if(!a(this.webrtcType))throw new C(1002,"not support");return this.client.pullUsers(e)}))}queryUsers(e){return cs(this,void 0,void 0,(function*(){if(!a(this.webrtcType))throw new C(1002,"不支持的操作");if(!this.client)throw new C(1002,"client 未 join,请先执行 join");if(!o.a(e))throw new C(1001,"需要传入 userIds 参数");return this.useStringUserId?ge(e,(e=>{if(!o.i(e))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:e}),new C(1001,"userId 类型错误,请检查");if(!/^[0-9a-zA-Z-_]{1,64}$/.test(e))throw this.joinFailReport(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符",{userId:e}),new C(1001,"userId 只能为以下字符:0-9、a-z、A-Z、-、_,且不能超过 64 个字符")})):ge(e,(e=>{if(!o.f(e))throw this.joinFailReport(1001,"userId 类型错误,请检查",{userId:e}),new C(1001,"userId 类型错误,请检查");if(e>Math.pow(2,31)-1||e<-Math.pow(2,31)||Math.floor(e)!==e)throw this.joinFailReport(1001,"userId 为 int32 整型",{userId:e}),new C(1001,"userId 为 int32 整型")})),ge(e,(e=>{if(e===this.userId)throw new C(1002,"不能传自己的 userId")})),(yield this.client.queryUsers(e.map((e=>Object(Be.a)(e))))).map((e=>{let t=new Lt(W(e.getUserId(),this.useStringUserId),this.webrtcType,e,e.getStreamId());const i=t.getUserId(),r=t.getStreamId();t.setLogger(this.logger),t.setClient(this),t.setCollection(this.collection),t.syncClientOptions(this.options);const n=this.remoteStreamMap[i]||[];if(n.length){let e=-1;if(ge(n,((t,i)=>{if(t.getStreamId()===r)return e=i,!1})),e>-1)return t.destroy(),n[e]}return n.push(t),this.remoteStreamMap[i]=n,t.on(le,(()=>{let e=this.remoteStreamMap[i];if(e&&e.length){let t=-1;ge(e,((e,i)=>{if(e.getStreamId()===r)return t=i,!1})),t>-1&&e.splice(t,1),0===e.length&&delete this.remoteStreamMap[i]}})),t}))}))}getMediaServers(){return cs(this,void 0,void 0,(function*(){if(!this.client)throw new C(1002,"client 未 join,请先执行 join");return this.client.getMediaServers()}))}setMediaServer(e,t){return cs(this,void 0,void 0,(function*(){if(!a(this.webrtcType))throw new C(1002,"不支持的操作");return this.client.setMediaServer(e,Object(Be.a)(t))}))}handleEvent(){let e=this,t=Dt[e.webrtcType],i=xt[e.webrtcType],r=this.publishOnly?[]:Nt;function n(t,r){e.client.on(t,(function(){let t=q(i[r],e,be(arguments));t&&o.d(t.then)?t.then((t=>{!1!==t&&(o.a(t)&&2===t.length?e.fire(t[0],t[1]):e.fire(r,t),e.logger.debug(`client event ${r}, userId: ${e.userId}`,"client"))})):!1!==t&&(o.a(t)&&2===t.length?e.fire(t[0],t[1]):e.fire(r,t),e.logger.debug(`client event ${r}, userId: ${e.userId}`,"client"))}))}ge(r,(e=>{t[e]&&(o.a(t[e])?ge(t[e],((t,i)=>{n(t,e)})):o.i(t[e])&&t[e]&&n(t[e],e))})),a(e.webrtcType)?e.client.on("media-error",(t=>{e.fire(D,new C(4008))})).on("reconnected",(()=>{var t;const i=e.client.getActiveProxy();e.reportAction("signalChannelConnect",0,0,0,{proxy:{url:i.url||i.dcurl,location:null!==(t=i.location)&&void 0!==t?t:""}})})).on("proxy-changed",(()=>{var t;const i=e.client.getActiveProxy();e.reportAction("changeSignalNode",0,0,0,{proxy:{url:i.url||i.dcurl,location:null!==(t=i.location)&&void 0!==t?t:""}})})).on("state-notify",(e=>{this.joinFailReport(8e3,"state notify, "+e.msg,e)})).on("stream-update",(t=>{const i=this.getRemoteStream(t.getUserId(),t.getStreamId());i?i.onMediaUpdate(this):e.logger.warn(`stream update but not found the remotestream, userId: ${this.getUserId()}, streamUserId: ${t.getUserId()}, streamId: ${t.getStreamId()}`)})):c(e.webrtcType)&&(e.on(M,(t=>{e.promiseHoldMap[t.stream.getUserId()]&&(e.promiseHoldMap[t.stream.getUserId()].resolve(0),delete e.promiseHoldMap[t.stream.getUserId()])})),e.client.on("sei-message",(e=>{const{userId:t,data:i,seiPayloadType:r}=e,n=this.getRemoteStream(t);n&&n.fire("stream-sei-message",{data:i,payloadType:r})}))),e.publishOnly&&(a(e.webrtcType)?e.client.on("stream-added",(e=>{e.destroy()})):c(this.webrtcType)&&e.client.on(w,(e=>{e.stream.close()}))),this.logger.info(`userId: ${this.userId}, publishOnly: ${this.publishOnly}`),this.logger.debug(`add event hanlder success, userId: ${this.userId}, events: ${r.join(",")}`,"client")}fire(e,t){this.emitter&&(e===D&&this.clear(),this.emitter.fire(e,t?[t]:void 0))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this.logger.debug(`client on, userId: ${this.userId}, type: ${e}`,"client"),this}one(e,t){return this.emitter.on(e,{fn:t,ctx:this,max:1}),this.logger.debug(`client one, userId: ${this.userId}, type: ${e}`,"client"),this}off(e,t){return this.emitter&&(this.emitter.off(e,t),this.logger.debug(`client off, userId: ${this.userId}, type: ${e}`,"client")),this}setPublishOnly(e){this.publishOnly=e,this.logger.info(`client publish only, userId: ${this.userId}, value: ${e}`,"client")}destroy(e){return cs(this,void 0,void 0,(function*(){if(this.emitter&&(this.emitter.off(),this.emitter=null),e?this.clear():this.client&&(yield this.leave()),this.publishStream=null,this.remoteStreamMap={},this.reportTimer&&(this.reportTimer.destroy(),this.reportTimer=null),this.ondevicechangeHandler)try{navigator.mediaDevices.removeEventListener("devicechange",this.ondevicechangeHandler),this.ondevicechangeHandler=null}catch(e){}this.destroyed=!0,this.logger.info("client destroy, userId: "+this.userId,"client")}))}addRemoteStream(e){e.setClient(this),e.setCollection(this.collection),e.syncClientOptions(this.options);const t=this.remoteStreamMap[e.getUserId()]||[];if(t.length){let i=-1;ge(t,((t,r)=>{if(t.getStreamId()===e.getStreamId())return i=r,!1})),i>-1&&(t[i].destroy(),t.splice(i,1))}t.push(e),this.remoteStreamMap[e.getUserId()]=t}removeRemoteStream(e,t){let i,r=this.remoteStreamMap[e];if(r&&r.length)if(t){let n=-1;ge(r,((e,i)=>{if(e.getStreamId()===t)return n=i,!1})),n>-1&&(i=r[n],r.splice(n,1),i.destroy()),0===r.length&&(this.remoteStreamMap[e]=null)}else ge(r,(e=>{e.destroy()})),this.remoteStreamMap[e]=null;return i}getRemoteStream(e,t){const i=this.remoteStreamMap[e];let r;if(i&&i.length)if(t){let e=-1;ge(i,((i,r)=>{if(i.getStreamId()===t)return e=r,!1})),e>-1&&(r=i[e])}else ge(i,(e=>{if("main"===e.getType())return r=e,!1}));return r}getActiveProxy(){var e;return null===(e=this.client)||void 0===e?void 0:e.getActiveProxy()}getClient(){return this.client}reportStats(){if(!this.collection)return;let e=!0;if(this.publishStream&&(e=!1,this.publishStream.getReportStats(this.reportThreshold).then((e=>{this.collection.stats(this.publishStream.getActionStreamId(),e,!0,null,this.publishStream.getExtraReport())})).catch((function(e){}))),Re(this.remoteStreamMap).length){e=!1;for(let e in this.remoteStreamMap)ge(this.remoteStreamMap[e],(e=>{e.isSubscribed()&&e.getReportStats(this.reportThreshold).then((t=>{this.collection.stats(e.getActionStreamId(),t,!1,Object(Be.a)(e.getUserId()),e.getExtraReport())})).catch((function(e){}))}))}e&&this.collection.heartbeat()}reportAction(e,t,i,r,n,s){this.collection&&this.collection.action(e,t,i,r,n,s)}getEncodings(e){const t=e.getStreamCodecOption(),i=e.getSourceVideoTrack();let r=t.width,n=t.height,s=t.frameRate;if(i&&i.getSettings){const e=i.getSettings();o.f(e.width)&&(r=e.width),o.f(e.height)&&(n=e.height),o.f(e.frameRate)&&(s=Math.floor(e.frameRate))}if(this.isEnableSmallStream&&(!ot.chrome||r>=398&&n>=308)){const e=Math.min(Math.max(Math.max(Xe((r/this.smallStreamCodecOption.width).toFixed(2)),Xe((n/this.smallStreamCodecOption.height).toFixed(2))),1),10);return[{scale:e,bitrate:1024*this.smallStreamCodecOption.bitrate,fps:t.frameRate||s,width:Math.ceil((t.width||r)/e),height:Math.ceil((t.height||n)/e),rid:"r0",scalabilityMode:this.enableSVC?this.masterResSettings.sdk_video_svc_mode:"L1T1"},{scale:1,bitrate:1024*t.bitrate,fps:t.frameRate||s,width:t.width||r,height:t.height||n,rid:"r1",scalabilityMode:this.enableSVC?this.masterResSettings.sdk_video_svc_mode:"L1T1"}]}return this.isEnableSmallStream&&ot.chrome&&(r<398||n<308)&&this.logger.warn("无法开启大小流因为需要视频宽度大于 398,高度大于 308"),[{scale:1,bitrate:1024*t.bitrate,fps:t.frameRate||s,width:t.width||r,height:t.height||n,scalabilityMode:this.enableSVC?this.masterResSettings.sdk_video_svc_mode:"L1T1"}]}}class ds extends class{constructor(e,t,i){this.gl=e,this.width=t,this.height=i,this.texture=this.gl.createTexture()}getTexture(){return this.texture}bind(e){o.f(e)&&this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture)}setSize(e,t){this.width=e,this.height=t}setUnpackAlignment(){this.width%8==0?this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,8):this.width%4==0?this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,4):this.width%2==0?this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,2):this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,1)}destroy(){this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}{constructor(e,t,i,r=!1){super(e,t,i),this.useMultisample=r}init(){this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.width,this.height,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.useMultisample?(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR)):(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE))}fill(e){this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.setUnpackAlignment(),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e)}}class ls{constructor(e,t,i,r){this.gl=e,this.width=t,this.height=i,this.useMultisample=r,this.init()}init(){this.framebuffer=this.gl.createFramebuffer(),this.colorBuffer=this.gl.createRenderbuffer(),this.texture=new ds(this.gl,this.width,this.height,this.useMultisample),this.texture.bind(),this.texture.init(),this.useMultisample?(this.renderbuffer=this.gl.createFramebuffer(),this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,this.colorBuffer),this.gl.renderbufferStorageMultisample(this.gl.RENDERBUFFER,4,this.gl.RGBA8,this.width,this.height),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.renderbuffer),this.gl.framebufferRenderbuffer(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.RENDERBUFFER,this.colorBuffer),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.framebuffer),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.texture.getTexture(),0)):(this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,this.colorBuffer),this.gl.renderbufferStorage(this.gl.RENDERBUFFER,this.gl.DEPTH_COMPONENT16,this.width,this.height),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.framebuffer),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.texture.getTexture(),0),this.gl.framebufferRenderbuffer(this.gl.FRAMEBUFFER,this.gl.DEPTH_ATTACHMENT,this.gl.RENDERBUFFER,this.colorBuffer)),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null)}toVertices(){return[-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0]}length(){return 4}viewport(){this.gl.viewport(0,0,this.width,this.height)}destroy(){this.framebuffer&&(this.gl.deleteFramebuffer(this.framebuffer),this.framebuffer=null),this.renderbuffer&&(this.gl.deleteFramebuffer(this.renderbuffer),this.renderbuffer=null),this.colorBuffer&&(this.gl.deleteRenderbuffer(this.colorBuffer),this.colorBuffer=null),this.texture&&this.texture.destroy()}getTexture(){return this.texture}getFrameBuffer(){return this.useMultisample?this.renderbuffer:this.framebuffer}getResolution(){return[1/this.width,1/this.height]}getWidth(){return this.width}getHeight(){return this.height}bind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.getFrameBuffer())}clear(){this.gl.clear(this.gl.COLOR_BUFFER_BIT|this.gl.DEPTH_BUFFER_BIT)}resize(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this.destroy(),this.init())}}class hs{constructor(e){this.gl=e.getGL(),this.width=e.getWidth(),this.height=e.getHeight(),this.frame=new ls(this.gl,this.width,this.height,!1),this.enabled=!0}ready(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){return!0}))}resize(e,t){this.width=e,this.height=t,this.frame.resize(e,t)}getTarget(){return this.frame}setEnabled(e){this.enabled=e}getEnabled(){return this.enabled}getVertices(){return[-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0]}}class ms extends class{constructor(e,t,i){this.gl=e,this.vertexShader=t,this.fragmentShader=i,this.vertexShader&&this.vertexShader.compile(e),this.fragmentShader&&this.fragmentShader.compile(e)}link(){this._program=this.gl.createProgram(),this.gl.attachShader(this._program,this.vertexShader.shader),this.gl.attachShader(this._program,this.fragmentShader.shader),this.gl.linkProgram(this._program)}stop(){this.vertexShader.stop(this.gl),this.fragmentShader.stop(this.gl),this.gl.deleteProgram(this._program),this.vertexShader=null,this.fragmentShader=null,this._program=null}bind(){this.gl.useProgram(this._program)}get program(){return this._program}}{constructor(e,t,i,r=!0){super(e,t,i),this.enableColor=r}link(){super.link(),this.aPoint=this.gl.getAttribLocation(this.program,"point"),this.aColor=this.gl.getAttribLocation(this.program,"color"),this.enableColor?(this.gl.enableVertexAttribArray(this.aPoint),this.gl.enableVertexAttribArray(this.aColor)):this.gl.enableVertexAttribArray(this.aPoint)}bind(){super.bind(),this.enableColor?(this.gl.vertexAttribPointer(this.aPoint,3,this.gl.FLOAT,!1,7*Float32Array.BYTES_PER_ELEMENT,0),this.gl.vertexAttribPointer(this.aColor,4,this.gl.FLOAT,!1,7*Float32Array.BYTES_PER_ELEMENT,3*Float32Array.BYTES_PER_ELEMENT)):this.gl.vertexAttribPointer(this.aPoint,3,this.gl.FLOAT,!1,7*Float32Array.BYTES_PER_ELEMENT,0)}}class ps{constructor(e,t){this.type=e,this._shader=null,this._source=t,this.compiled=!1}compile(e){this.compiled||(this._shader=e.createShader(this.type),e.shaderSource(this._shader,this._source),e.compileShader(this._shader),this.compiled=!0)}stop(e){e.deleteShader(this._shader),this._shader=null}get shader(){return this._shader}}class fs extends ps{constructor(e,t){super(e.VERTEX_SHADER,t)}}class vs extends ps{constructor(e,t){super(e.FRAGMENT_SHADER,t)}}class gs extends ms{constructor(e){super(e,new fs(e,"precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 point;\nattribute vec4 color;\nvarying vec4 v_color;\n\nvoid main(void){\n gl_Position = vec4(point, 1.0);\n v_color = color;\n}\n"),new vs(e,"precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 v_color;\nuniform sampler2D u_Sampler;\n\nuniform vec2 singleStepOffset;\nuniform vec4 params;\nuniform float brightness;\n\nconst vec3 W = vec3(0.299, 0.587, 0.114);\n\nconst mat3 saturateMatrix = mat3(\n 1.1102, -0.0598, -0.061,\n -0.0774, 1.0826, -0.1186,\n -0.0228, -0.0228, 1.1772);\n\nvec2 blurCoordinates[24];\n\nfloat hardLight(float color) {\n if (color <= 0.5) {\n color = color * color * 2.0;\n }\n else {\n color = 1.0 - ((1.0 - color)*(1.0 - color) * 2.0);\n }\n return color;\n}\n\nvoid main() {\n\n vec2 coord = v_color.xy;\n \n vec3 centralColor = texture2D(u_Sampler, coord).rgb;\n blurCoordinates[0] = coord.xy + singleStepOffset * vec2(0.0, -10.0);\n blurCoordinates[1] = coord.xy + singleStepOffset * vec2(0.0, 10.0);\n blurCoordinates[2] = coord.xy + singleStepOffset * vec2(-10.0, 0.0);\n blurCoordinates[3] = coord.xy + singleStepOffset * vec2(10.0, 0.0);\n blurCoordinates[4] = coord.xy + singleStepOffset * vec2(5.0, -8.0);\n blurCoordinates[5] = coord.xy + singleStepOffset * vec2(5.0, 8.0);\n blurCoordinates[6] = coord.xy + singleStepOffset * vec2(-5.0, 8.0);\n blurCoordinates[7] = coord.xy + singleStepOffset * vec2(-5.0, -8.0);\n blurCoordinates[8] = coord.xy + singleStepOffset * vec2(8.0, -5.0);\n blurCoordinates[9] = coord.xy + singleStepOffset * vec2(8.0, 5.0);\n blurCoordinates[10] = coord.xy + singleStepOffset * vec2(-8.0, 5.0);\n blurCoordinates[11] = coord.xy + singleStepOffset * vec2(-8.0, -5.0);\n blurCoordinates[12] = coord.xy + singleStepOffset * vec2(0.0, -6.0);\n blurCoordinates[13] = coord.xy + singleStepOffset * vec2(0.0, 6.0);\n blurCoordinates[14] = coord.xy + singleStepOffset * vec2(6.0, 0.0);\n blurCoordinates[15] = coord.xy + singleStepOffset * vec2(-6.0, 0.0);\n blurCoordinates[16] = coord.xy + singleStepOffset * vec2(-4.0, -4.0);\n blurCoordinates[17] = coord.xy + singleStepOffset * vec2(-4.0, 4.0);\n blurCoordinates[18] = coord.xy + singleStepOffset * vec2(4.0, -4.0);\n blurCoordinates[19] = coord.xy + singleStepOffset * vec2(4.0, 4.0);\n blurCoordinates[20] = coord.xy + singleStepOffset * vec2(-2.0, -2.0);\n blurCoordinates[21] = coord.xy + singleStepOffset * vec2(-2.0, 2.0);\n blurCoordinates[22] = coord.xy + singleStepOffset * vec2(2.0, -2.0);\n blurCoordinates[23] = coord.xy + singleStepOffset * vec2(2.0, 2.0);\n\n float sampleColor = centralColor.g * 22.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[0]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[1]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[2]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[3]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[4]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[5]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[6]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[7]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[8]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[9]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[10]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[11]).g;\n sampleColor += texture2D(u_Sampler, blurCoordinates[12]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[13]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[14]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[15]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[16]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[17]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[18]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[19]).g * 2.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[20]).g * 3.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[21]).g * 3.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[22]).g * 3.0;\n sampleColor += texture2D(u_Sampler, blurCoordinates[23]).g * 3.0;\n\n sampleColor = sampleColor / 62.0;\n\n float highPass = centralColor.g - sampleColor + 0.5;\n\n for (int i = 0; i < 5; i++) {\n highPass = hardLight(highPass);\n }\n float lumance = dot(centralColor, W);\n float alpha = pow(lumance, params.r);\n vec3 smoothColor = centralColor + (centralColor - vec3(highPass)) * alpha * 0.1;\n\n smoothColor.r = clamp(pow(smoothColor.r, params.g), 0.0, 1.0);\n smoothColor.g = clamp(pow(smoothColor.g, params.g), 0.0, 1.0);\n smoothColor.b = clamp(pow(smoothColor.b, params.g), 0.0, 1.0);\n\n vec3 screen = vec3(1.0) - (vec3(1.0) - smoothColor) * (vec3(1.0) - centralColor);\n vec3 lighten = max(smoothColor, centralColor);\n vec3 softLight = 2.0 * centralColor * smoothColor + centralColor * centralColor - 2.0 * centralColor * centralColor * smoothColor;\n\n gl_FragColor = vec4(mix(centralColor, screen, alpha), 1.0);\n gl_FragColor.rgb = mix(gl_FragColor.rgb, lighten, alpha);\n gl_FragColor.rgb = mix(gl_FragColor.rgb, softLight, params.b);\n\n vec3 satcolor = gl_FragColor.rgb * saturateMatrix;\n gl_FragColor.rgb = mix(gl_FragColor.rgb, satcolor, params.a);\n gl_FragColor.rgb = vec3(gl_FragColor.rgb + vec3(brightness));\n}"))}link(){super.link(),this.samplerLocation=this.gl.getUniformLocation(this.program,"u_Sampler"),this.paramsLocation=this.gl.getUniformLocation(this.program,"params"),this.brightnessLocation=this.gl.getUniformLocation(this.program,"brightness"),this.singleStepOffsetLocation=this.gl.getUniformLocation(this.program,"singleStepOffset")}bindTexture(e=0){this.gl.uniform1i(this.samplerLocation,e)}setBrightness(e){this.gl.uniform1f(this.brightnessLocation,.37*(-.5+e))}setParams(e,t){this.gl.uniform4fv(this.paramsLocation,[1-.8*e,1-.6*e,.1+.45*t,.1+.45*t])}setSize(e,t){this.gl.uniform2fv(this.singleStepOffsetLocation,[2/e,2/t])}setOpacity(e=.5){this.gl.uniform1f(this.opacityLocation,e)}}class _s extends ms{constructor(e){super(e,new fs(e,"precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 point;\nattribute vec4 color;\nvarying vec4 v_color;\n\nvoid main(void){\n gl_Position = vec4(point, 1.0);\n v_color = color;\n}\n"),new vs(e,"precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 v_color;\nuniform sampler2D u_Sampler;\nuniform float opacity;\n\nvoid main () {\n vec4 color = texture2D(u_Sampler, v_color.xy);\n color.a = color.a * opacity;\n gl_FragColor = color;\n}\n"))}link(){super.link(),this.samplerLocation=this.gl.getUniformLocation(this.program,"u_Sampler"),this.opacityLocation=this.gl.getUniformLocation(this.program,"opacity")}bindTexture(e=0){this.gl.uniform1i(this.samplerLocation,e)}setOpacity(e=1){(e<0||e>1)&&(e=1),this.gl.uniform1f(this.opacityLocation,e)}}function ys(){return!("object"==typeof window&&we(window.document))}class Ss{constructor(){this.id=0,this.taskMap=new Map;const e=Ge(29);this.worker=new Worker(e),this.workerUrl=e,this.worker.addEventListener("message",(e=>{const t=e.data,i=t.type,r=t.id;if("pong"===i){const e=this.taskMap.get(r);e&&e(!0)}}))}setTimeout(e,t=0){const i=this.id++;return this.taskMap.set(i,e),this.worker.postMessage({type:"ping",data:{timeout:t,id:i}}),i}clearTimeout(e){this.taskMap.delete(e)}destroy(){this.worker&&(this.worker.terminate(),this.worker=null),this.workerUrl&&(URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.taskMap&&(this.taskMap.clear(),this.taskMap=null)}}let Es,bs=0;function Ts(){return Es?(bs++,Es):(Es=new Ss,bs=1,Es)}function Is(){0!==bs&&(bs--,0===bs&&(Es.destroy(),Es=null))}class Cs{constructor(e,t=!0){this.started=!1,this.interval=e,this.highPerformance=t,this.a=.2,this.b=4,this.equivalent=50,this.timestamp=0,this.compute(),this.messageChannel=new MessageChannel,this.handleEvent(),this.timeoutNext=e=>{e?this.workerTimer=null:this.timer=null,this.running=!1,this.count++,this.onClock&&this.onClock(),this.nextTick()},ys()||"hidden"!==document.visibilityState||(this.workerSetTimeout=Ts()),this.running=!1}compute(e=!0){this.interval>0&&(this.beta=Math.ceil(this.equivalent*(1-this.b/this.interval)/(this.a-this.b)),this.alpha=Math.floor(this.equivalent/this.interval-this.beta),e&&(this.count=0))}timeoutTick(){this.workerSetTimeout&&"hidden"===document.visibilityState&&this.interval<1e3?this.workerTimer=this.workerSetTimeout.setTimeout(this.timeoutNext,this.interval):this.timer=setTimeout(this.timeoutNext,this.interval)}nextTick(){if(this.started&&!this.running)if(this.running=!0,this.interval>4||!this.highPerformance)this.timeoutTick();else if(this.interval<=0)this.messageChannel.port1.postMessage(null);else{const e=z();e-this.timestamp>this.equivalent&&(this.count=0,this.timestamp=e),this.count<this.beta?this.messageChannel.port1.postMessage(null):this.timeoutTick()}}start(){this.started||(this.started=!0,this.timestamp=z(),this.nextTick())}stop(){this.started=!1,this.timer&&(clearTimeout(this.timer),this.timer=null),this.workerTimer&&this.workerSetTimeout&&this.workerSetTimeout.clearTimeout(this.workerTimer),this.running=!1}isStarted(){return this.started}setInterval(e){this.interval=Math.max(e,0),this.compute()}getInterval(){return this.interval}isZeroTimeout(){return this.interval<4}destroy(){this.stop(),this.workerSetTimeout&&(Is(),this.workerSetTimeout=null),this.onVisibilityChange&&(document.removeEventListener("visibilitychange",this.onVisibilityChange),this.onVisibilityChange=null)}handleEvent(){this.messageChannel.port2.onmessage=()=>{this.started&&(this.running=!1,this.count++,this.onClock&&this.onClock(),this.nextTick())},ys()||(this.onVisibilityChange=$e((e=>{"hidden"===document.visibilityState?(this.workerSetTimeout=Ts(),this.timer&&(clearTimeout(this.timer),this.timer=null,this.running=!1),this.nextTick()):(this.workerTimer&&(this.workerSetTimeout.clearTimeout(this.workerTimer),this.workerTimer=null,this.running=!1),this.timer&&(clearTimeout(this.timer),this.timer=null,this.running=!1),Is(),this.workerSetTimeout=null,this.nextTick())}),20),document.addEventListener("visibilitychange",this.onVisibilityChange))}}class ws{constructor(e,t=0,i=0,r=!0){this.task=e,this.timeout=t,this.interval=i,this.autoInterval=r,this.count=0,this.emptyCount=0,this.timestamp=0,this.started=!1,this.clock=new Cs(this.interval),this.clock.onClock=()=>{if(!this.started)return;this.count++,!1===this.task()&&this.stop();const e=z();if(this.autoInterval&&e-this.timestamp>50){const t=this.emptyCount/this.count;0===this.emptyCount?this.clock.setInterval(Math.max(this.clock.getInterval()>>1,this.interval)):t<.1?this.clock.setInterval(this.clock.getInterval()-1):t>.2?this.clock.setInterval(Math.min(this.clock.getInterval()+1,20)):t>.5&&this.clock.setInterval(this.clock.getInterval()<<1),this.count=0,this.emptyCount=0,this.timestamp=e}}}start(){this.started=!0,this.timeout?this.startTimer=setTimeout((()=>{this.count=0,this.emptyCount=0,this.timestamp=z(),this.clock.start(),this.startTimer=null}),this.timeout):(this.count=0,this.emptyCount=0,this.timestamp=z(),this.clock.start())}stop(){this.started=!1,this.startTimer&&(clearTimeout(this.startTimer),this.startTimer=null),this.clock.stop()}isStarted(){return this.started}emptyTask(){this.emptyCount++}isZeroTimeout(){var e;return null===(e=this.clock)||void 0===e?void 0:e.isZeroTimeout()}restart(){this.clock&&(this.stop(),this.clock.setInterval(this.interval),this.start())}destroy(){this.stop(),this.task=null,this.timeout=null,this.interval=null}}class Rs extends ms{constructor(e){super(e,new fs(e,"precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 point;\nattribute vec4 color;\nvarying vec4 v_color;\n\nvoid main(void){\n gl_Position = vec4(point, 1.0);\n v_color = color;\n}\n"),new vs(e,"precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 v_color;\nuniform sampler2D u_Sampler;\n\nvoid main () {\n gl_FragColor = texture2D(u_Sampler, v_color.xy);\n}\n"))}link(){super.link(),this.samplerLocation=this.gl.getUniformLocation(this.program,"u_Sampler")}bindTexture(e=0){this.gl.uniform1i(this.samplerLocation,e)}}class ks extends hs{constructor(e){super(e),this.program=new Rs(this.gl),this.program.link()}render(e,t,i=0){return this.program.bind(),e.bind(i),this.program.bindTexture(i),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,t,4),{nextUnit:i+1,nextStartIndex:t+4}}destroy(){this.program.stop()}}var As,Ms=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};!function(e){e.I420="I420",e.NV12="NV12",e.ABGR="ABGR",e.IMAGE_BIT_MAP="IMAGE_BIT_MAP"}(As||(As={}));class Os{constructor(e=300,t=150){this.width=e,this.height=t,this.sourceHeight=e,this.sourceHeight=t,this.cropTop=0,this.cropLeft=0,this.renders=[],this.verticalFlipEnabled=!1,this.horizontalFlipEnabled=!1,this.generateVertex(),this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,ot.safari&&(document.body.appendChild(this.canvas),this.canvas.style.position="absolute",this.canvas.style.left="-99999px"),this.gl=this.canvas.getContext("webgl2",{alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),this.gl||(this.gl=this.canvas.getContext("webgl",{alpha:!0,antialias:!0,preserveDrawingBuffer:!0})),this.VAO=this.gl.createBuffer(),this.VAO||he.fatal("顶点缓冲区创建失败"),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.VAO),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.enable(this.gl.BLEND),this.gl.clearColor(0,0,0,0),this.gl.clearDepth(1),this.gl.viewport(0,0,e,t),this.gl.blendFuncSeparate(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA,this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA),this.sourceTexture=new ds(this.gl,this.sourceWidth,this.sourceHeight),this.sourceTexture.bind(0),this.sourceTexture.init(),this.supportTrackProcessor="undefined"!=typeof MediaStreamTrackProcessor&&!1,this.supportTrackProcessor||(this.video=document.createElement("video"),this.video.loop=!0,this.video.autoplay=!0,this.video.onloadedmetadata=()=>{this.renderTimer&&this.renderTimer.start()}),this.copyRender=new ks(this)}generateVertex(){this.verticalFlipEnabled&&this.horizontalFlipEnabled?this.vertex=[-1,1,0,1,0,0,0,-1,-1,0,1,1,0,0,1,1,0,0,0,0,0,1,-1,0,0,1,0,0]:this.verticalFlipEnabled?this.vertex=[-1,1,0,0,0,0,0,-1,-1,0,0,1,0,0,1,1,0,1,0,0,0,1,-1,0,1,1,0,0]:this.horizontalFlipEnabled?this.vertex=[-1,1,0,1,1,0,0,-1,-1,0,1,0,0,0,1,1,0,0,1,0,0,1,-1,0,0,0,0,0]:this.vertex=[-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0]}bufferVertices(){let e=[-1,1,0,0+this.cropLeft,1-this.cropTop,0,0,-1,-1,0,0+this.cropLeft,0+this.cropTop,0,0,1,1,0,1-this.cropLeft,1-this.cropTop,0,0,1,-1,0,1-this.cropLeft,0+this.cropTop,0,0,-1,1,0,0,1,0,0,-1,-1,0,0,0,0,0,1,1,0,1,1,0,0,1,-1,0,1,0,0,0];e=e.concat(this.vertex),this.waterMarkProgram&&this.waterMarkTexture&&this.waterMarkEnabled&&(e=e.concat(this.waterMarkVertex)),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(e),this.gl.STATIC_DRAW)}generateWaterMarkVertex(){let e=this.waterMark.width,t=this.waterMark.height;const i=e>1||t>1;e&&!t?(t=this.imageElement.height*e/this.imageElement.width,t<1&&(t=t*this.width/this.height)):!e&&t?(e=this.imageElement.width*t/this.imageElement.height,e<1&&(e=e*this.height/this.width)):e||t||(e=100,t=this.imageElement.height*e/this.imageElement.width,t<1&&(t=t*this.width/this.height));let r=this.waterMark.left||0,n=this.waterMark.top||0;i?e=e/this.width*2:e*=2,i?t=t/this.height*2:t*=2,r<=1&&r>=0?r*=2:r=r/this.width*2,n<=1&&n>=0?n*=2:n=n/this.height*2,this.waterMarkVertex=[-1+r,1-n,0,0,1,0,0,-1+r,1-n-t,0,0,0,0,0,-1+r+e,1-n,0,1,1,0,0,-1+r+e,1-n-t,0,1,0,0,0]}resize(e,t,i,r){this.width=e,this.height=t,this.supportTrackProcessor&&i&&r?(this.sourceWidth=i,this.sourceHeight=r):(this.sourceWidth=e,this.sourceHeight=t),this.canvas.width=e,this.canvas.height=t,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.sourceTexture&&(this.sourceTexture.setSize(this.sourceWidth,this.sourceHeight),this.sourceTexture.init()),this.rgbaFrame&&this.rgbaFrame.resize(e,t);for(let i=0;i<this.renders.length;i++)this.renders[i].resize(e,t);this.copyRender.resize(e,t),this.generateWaterMarkVertex(),this.waterMarkTexture.fill(this.imageElement)}render(e,t,i){const r=this.renders.filter((e=>e.getEnabled()));if(r.length)for(let t=0;t<r.length;t++)t===r.length-1?this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null):this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r[t].getTarget()),r[t].render(e,t===r.length-1?8:0===t?0:4,i++),e=r[t].getTarget().getTexture();else this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.copyRender.render(e,8,i++),e=this.copyRender.getTarget().getTexture();this.waterMarkProgram&&this.waterMarkTexture&&this.waterMarkEnabled&&0!==this.waterMark.width&&0!==this.waterMark.height&&(this.waterMarkProgram.bind(),this.waterMarkTexture.bind(this.format===As.IMAGE_BIT_MAP?0:3),this.waterMarkProgram.bindTexture(this.format===As.IMAGE_BIT_MAP?0:3),this.waterMarkProgram.setOpacity(o.f(this.waterMark.opacity)?this.waterMark.opacity:1),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,12,4))}readVideoFrame(){return Ms(this,void 0,void 0,(function*(){if(!this.abortRequest)try{const{done:e,value:t}=yield this.videoFrameReader.read();if(e)return;t&&(yield this.renderVideoFrame(t)),this.readVideoFrame()}catch(e){throw console.log(e),new C(9e3,"read videoFrame failed!")}}))}renderVideoFrame(e){return Ms(this,void 0,void 0,(function*(){e.displayWidth===this.width&&e.displayHeight===this.height&&e.codedWidth===this.sourceWidth&&e.codedHeight===this.sourceHeight||(this.resize(e.displayWidth,e.displayHeight,e.codedWidth,e.codedHeight),this.cropLeft=e.visibleRegion.left/e.visibleRegion.width,this.cropTop=e.visibleRegion.top/e.visibleRegion.height),this.bufferVertices(),this.sourceTexture.fill(e),e.close(),this.render(this.sourceTexture,0,1)}))}renderHTMLVideoElement(e){return Ms(this,void 0,void 0,(function*(){(e.videoWidth>10&&e.videoWidth!==this.width||e.videoHeight>10&&e.videoHeight!==this.height)&&this.resize(e.videoWidth,e.videoHeight),this.bufferVertices(),this.sourceTexture.fill(e),this.render(this.sourceTexture,0,1)}))}addRender(e){this.renders.push(e)}removeRender(e){for(let t=0;t<this.renders.length;t++)if(this.renders[t]===e)return void this.renders.splice(t,1)}getGL(){return this.gl}getWidth(){return this.width}getHeight(){return this.height}enableVerticalFlip(e){this.verticalFlipEnabled=e,this.generateVertex()}enableHorizontalFlip(e){this.horizontalFlipEnabled=e,this.generateVertex()}onWaterMarkLoaded(){this.waterMarkProgram||(this.waterMarkProgram=new _s(this.gl),this.waterMarkProgram.link()),this.waterMarkTexture?(this.waterMarkTexture.setSize(this.imageElement.width,this.imageElement.height),this.waterMarkTexture.init()):(this.waterMarkProgram.bind(),this.waterMarkTexture=new ds(this.gl,this.imageElement.width,this.imageElement.height,!1),this.waterMarkTexture.bind(this.format===As.IMAGE_BIT_MAP?0:3),this.waterMarkTexture.init(),this.waterMarkProgram.bindTexture(this.format===As.IMAGE_BIT_MAP?0:3)),this.waterMarkTexture.fill(this.imageElement),this.generateWaterMarkVertex()}setWaterMark(e){const t=!this.waterMark||this.waterMark.url!==e.url;this.waterMark=Me(this.waterMark||{},e),this.waterMark.url&&t?(this.imageElement||(this.imageElement=document.createElement("img"),this.imageElement.crossOrigin="Anonymous",this.imageElement.onload=this.onWaterMarkLoaded.bind(this)),this.imageElement.src=this.waterMark.url):this.generateWaterMarkVertex(),we(this.waterMarkEnabled)||(this.waterMarkEnabled=!0)}enableWaterMark(e){this.waterMarkEnabled=e}pipe(e,t){var i;if("video"!==e.kind)throw new C(1002,"track 不是一个 video track");if(this.inputTrack=e,this.abortRequest=!1,t)this.trackFps=t;else{const t=e.getConstraints();this.trackFps=null!==(i=t.frameRate)&&void 0!==i?i:15}if(this.captureStream=this.canvas.captureStream(this.trackFps),this.outputTrack=this.captureStream.getVideoTracks()[0],this.supportTrackProcessor)this.mediaStreamTrackProcessor=new MediaStreamTrackProcessor({track:this.inputTrack}),this.videoFrameReader=this.mediaStreamTrackProcessor.readable.getReader(),this.readVideoFrame();else{let e=new MediaStream;e.addTrack(this.inputTrack),this.video.srcObject=e,this.video.play().catch((e=>{he.error("play video failed")})),this.renderTimer&&this.renderTimer.destroy(),this.renderTimer=new ws((()=>{this.renderHTMLVideoElement(this.video)}),0,Math.max(1e3/this.trackFps,30))}}getOutputTrack(){return this.outputTrack}stop(){this.renderTimer&&this.renderTimer.stop(),this.captureStream&&(this.captureStream=null),this.mediaStreamTrackProcessor&&(this.mediaStreamTrackProcessor=null),this.video&&(this.video.srcObject=null)}static isSupport(){const e=document.createElement("canvas"),t=e.getContext("webgl");return!!e.captureStream&&!!t}}Os.VIDEO_FORMAT=As,Os.Renders={BeautyRender:class extends hs{constructor(e){super(e),this.program=new gs(this.gl),this.program.link(),this.opacity=.99,this.ruddy=.5,this.beauty=.5,this.brightness=.5}render(e,t,i=0){return this.program.bind(),e.bind(i),this.program.bindTexture(i),this.program.setSize(this.width,this.height),this.program.setParams(this.beauty,this.ruddy),this.program.setBrightness(this.brightness),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,t,4),{nextUnit:i+1,nextStartIndex:t+4}}setOpacity(e){this.opacity=e}setBrightness(e){this.brightness=e}setBeauty(e){this.beauty=e}setRuddy(e){this.ruddy=e}destroy(){this.program.stop()}}};Object(he.setDefaultTag)("brtc"),he.enableUploadLog(),he.setUploadLevel("production"===l?he.INFO:he.DEBUG);const Ls=Me({},he,{setLevel:function(e){he.setLevel(e),yt.a.Logger.setLogLevel(e)}}),Ps={Client:r,Stream:n};function Ns(e){return new Or(e)}function Ds(e){return new us(e)}function xs(e){l=e,he.info("set env "+e)}function Us(e){!function(e){p=e}(e)}function $s(e){!function(e){g=e}(e),he.info("set roomChannelType "+e)}function Bs(e){!function(e){_=e}(e),he.info("set forcePlanBSimulcast "+e)}function Vs(e){!function(e){Br=e}(e),he.info("set customUrl "+e)}function Fs(e){!function(e=[]){y=y.concat(e)}(e),he.info("set proxies "+JSON.stringify(e))}function js(e){f=e}function Hs(){y=[],he.info("remove proxies")}function Ws(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){return yield yt.a.checkSystemRequirements()}))}function Gs(){return Xt()}function qs(){return un()}const Js=function(){return function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if("permissions"in navigator)try{let e=yield Promise.all([navigator.permissions.query({name:"camera"}),navigator.permissions.query({name:"microphone"})]);if(e.some((e=>"prompt"===e.state)))(yield navigator.mediaDevices.getUserMedia({video:!0,audio:!0})).getTracks().forEach((e=>e.stop()));else if(e.some((e=>"denied"===e.state)))throw new C(1010,"获取设备权限失败")}catch(e){throw new C(1010,"获取设备权限失败",e)}else try{(yield navigator.mediaDevices.getUserMedia({video:!0,audio:!0})).getTracks().forEach((e=>e.stop()))}catch(e){throw new C(1010,"获取设备权限失败",e)}}))},zs=Bt,Ys=Zn,Qs=ts,Ks=es;window.brtcLogPlugin=function(e,t,i){kt[t]?kt[t](i,"TencentLog"):Ls.info(i,"TencentLog")},Ls.setLevel(he.WARN);const Xs=h,Zs=Os;console.log(`******************************************************************************\n* 欢迎使用 BRTC(v${h}) Web SDK - 百家云实时音视频通信\n* API 文档:https://docs.baijiayun.com/open/\n******************************************************************************`)}]);var BRTC=getDefaultExportFromCjs(BRTC$2.exports),BRTC$1=_mergeNamespaces({__proto__:null,default:BRTC},[BRTC$2.exports]),BoomCoreErrorCode$1;class BoomError$2 extends Error{constructor(e,t,i){let r;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,r="string"==typeof t?t:JSON.stringify(t),this.message=r,i&&(this.name=i)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}}!function(e){e[e.BloudLock=28]="BloudLock",e[e.ShareScreenNoPermission=100]="ShareScreenNoPermission",e[e.ShareScreenCanceled=101]="ShareScreenCanceled",e[e.ShareScreenOtherError=102]="ShareScreenOtherError",e[e.ShareScreenContentHintError=103]="ShareScreenContentHintError",e[e.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",e[e.BrtcShareSigError=105]="BrtcShareSigError",e[e.ToggleShareScreenError=106]="ToggleShareScreenError",e[e.BrtcCreateStreamError=107]="BrtcCreateStreamError",e[e.BrtcSubscribeError=108]="BrtcSubscribeError",e[e.BrtcPublishError=109]="BrtcPublishError",e[e.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",e[e.BrtcUnPublishError=111]="BrtcUnPublishError",e[e.RepeatJoinError=112]="RepeatJoinError",e[e.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",e[e.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",e[e.JoinUserInfoError=115]="JoinUserInfoError",e[e.JoinTypeError=116]="JoinTypeError",e[e.JoinBrtcError=117]="JoinBrtcError",e[e.JoinBloudError=118]="JoinBloudError",e[e.UpdateCustomStatsError=119]="UpdateCustomStatsError",e[e.CreateBloudError=120]="CreateBloudError"}(BoomCoreErrorCode$1||(BoomCoreErrorCode$1={}));const ShareScreenNoPermission=new BoomError$2(BoomCoreErrorCode$1.ShareScreenNoPermission,"没有打开共享屏幕录制权限","no share permission"),ShareScreenCanceled=new BoomError$2(BoomCoreErrorCode$1.ShareScreenCanceled,"取消共享屏幕","cancel share"),ShareScreenOtherError=e=>new BoomError$2(BoomCoreErrorCode$1.ShareScreenOtherError,e);new BoomError$2(BoomCoreErrorCode$1.ShareScreenContentHintError,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed");const ShareScreenClientJoinedError=new BoomError$2(BoomCoreErrorCode$1.ShareScreenClientJoinedError,"共享屏幕brtc client入会失败","share client join failed"),BrtcShareSigError=new BoomError$2(BoomCoreErrorCode$1.BrtcShareSigError,"brtcShareSig为空","brtc share sig is empty"),ToggleShareScreenError=e=>new BoomError$2(BoomCoreErrorCode$1.ToggleShareScreenError,e,"toggle share has error"),RepeatJoinError$1=new BoomError$2(BoomCoreErrorCode$1.RepeatJoinError,"正在 join,请勿重复调用","repeat join error"),ProxiesUrlTypeError=new BoomError$2(BoomCoreErrorCode$1.ProxiesUrlTypeError,"proxies url 必须为字符串","get bloud proxies param error"),getBloudProxiesUrlError=e=>new BoomError$2(BoomCoreErrorCode$1.getBloudProxiesUrlError,e,"get bloud proxies error"),JoinUserInfoError=new BoomError$2(BoomCoreErrorCode$1.JoinUserInfoError,"userinfo传递错误,请检查"),JoinTypeError=new BoomError$2(BoomCoreErrorCode$1.JoinTypeError,"type传递错误,请检查"),JoinBrtcError=e=>new BoomError$2(BoomCoreErrorCode$1.JoinBrtcError,e,"join brtc error"),BrtcCreateStreamError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcCreateStreamError,"brtc 创建本地流失败"),BrtcPublishError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcPublishError,e,"brtc pub failed"),BrtcUnsubscribeError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcUnsubscribeError,e,"brtc sub failed"),BrtcUnPublishError=e=>new BoomError$2(BoomCoreErrorCode$1.BrtcUnsubscribeError,e,"brtc unpub failed");var BoomMeetingErrorCode$1,StreamErrorMap$1;!function(e){e[e.BmJoinError=200]="BmJoinError",e[e.BMLeaveError=201]="BMLeaveError",e[e.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",e[e.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",e[e.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",e[e.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",e[e.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",e[e.BmChangeMasterError=207]="BmChangeMasterError",e[e.BmUpdateManagerError=208]="BmUpdateManagerError",e[e.BmEvictUserError=209]="BmEvictUserError",e[e.BmUpdateUserError=210]="BmUpdateUserError",e[e.BmSetAudioOffError=211]="BmSetAudioOffError",e[e.BmSetVideoOffError=212]="BmSetVideoOffError",e[e.BmSetMsgOffError=213]="BmSetMsgOffError",e[e.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",e[e.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",e[e.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",e[e.BmCheckDeviceError=217]="BmCheckDeviceError"}(BoomMeetingErrorCode$1||(BoomMeetingErrorCode$1={})),function(e){e[e.createStream=1302]="createStream",e[e.noCameraDevice=1303]="noCameraDevice",e[e.noMicroDevice=1304]="noMicroDevice",e[e.noSpeakerDevice=1305]="noSpeakerDevice",e[e.openCamera=1301]="openCamera",e[e.cameraNotAuth=1314]="cameraNotAuth",e[e.cameraOccupy=1315]="cameraOccupy",e[e.openMicro=1302]="openMicro",e[e.micNotAuth=1317]="micNotAuth",e[e.micOccupy=1319]="micOccupy",e[e.streamDisconnected=1320]="streamDisconnected",e[e.syncFail=1321]="syncFail",e[e.getStreamFail=1322]="getStreamFail",e[e.streamConnectError=1323]="streamConnectError",e[e.streamReconnectSuccess=1324]="streamReconnectSuccess",e[e.streamReconnectFailed=1325]="streamReconnectFailed",e[e.shareStreamConnectError=1326]="shareStreamConnectError",e[e.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",e[e.shareStreamConnectFailed=1328]="shareStreamConnectFailed"}(StreamErrorMap$1||(StreamErrorMap$1={}));class BCClient{constructor(e){this.emitters=[],this.name="",this.type=SING_MODE,this.appId="",this.brtcAppId="",this.roomId="",this.tarCreate=!1,this.userinfo={},this.userId="",this.isJoining=!1,this.collection="",this.limit=0,this.token="",this.customToken="",this.create=!1,this.host="",this.getProxiesUrl="",this.secret="",this.enableRace=!1,this.disableMediaEngine=!1,this.roomType=1,this.audioCodec="opus",this.codec="h264",this.hasBloudJoined=!1,this.brtcSig="",this.shareContentHint="detail",this.identity="",this.isBig="0",this.brtcJoined=!1,this.joinReady=!1,this.joinBrtc=()=>new Promise(((e,t)=>{this.brtcClient.join(this.roomId,this.userId,this.sig).then((()=>(info$1("join brtc succeed"),this.brtcJoined=!0,e(!0)))).catch((e=>(console.log("brtc入会失败01",e),this.isJoining=!1,t(JoinBrtcError(e.message)))))})),this.joinBloud=()=>new Promise(((e,t)=>{SingleMode.singleModeJoin(this,(()=>this.addBloudEvent())).then((()=>(info$1("join bloud succeed"),this.hasBloudJoined=!0,e(!0)))).catch((e=>(error$2("bloud入会失败02","",[e]),this.isJoining=!1,t(e))))})),this.handleBloudSharePubFailed=()=>{error$2("bloud share stream unpublish failed, interval retry");let e=setInterval((()=>__awaiter$1(this,void 0,void 0,(function*(){clearInterval(e),yield this.bloudShareScreenStream.unpublish(!1).then((()=>{this.bloudShareScreenStream=void 0})).catch((()=>{this.handleBloudSharePubFailed()}))}))),2e3)},this.emitter=new Emitter$1(!0),addEvent2Bloud(),window.BRTC=BRTC$1}setShareSig(e){this.brtcShareSig=e}clearObject(){this.client&&(this.client.close(),this.client.removeAllListeners()),this.client=null,this.collection&&(this.collection.close(),this.collection=null)}join(e){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise(((t,i)=>__awaiter$1(this,void 0,void 0,(function*(){if(this.isJoining)return Promise.reject(RepeatJoinError$1);if(this.client)return Promise.reject(RepeatJoinError$1);if("string"!=typeof e.getProxiesUrl)return Promise.reject(ProxiesUrlTypeError);if(!e.userinfo||e.userinfo&&"object"!=typeof e.userinfo)return Promise.reject(JoinUserInfoError);if("number"!=typeof e.type||1!==e.type&&2!==e.type)return Promise.reject(JoinTypeError);if(this.userId=e.userId,this.roomId=e.room,this.roomType=e.roomType,this.collection=e.collection,this.userinfo=e.userinfo,this.getProxiesUrl=e.getProxiesUrl,this.appId=e.appId,this.brtcAppId=e.brtcAppId,this.type=e.type,this.tarCreate=e.create,this.limit=e.limit,this.secret=e.secret,this.enableRace=e.enableRace,this.token=e.token,this.customToken=e.customToken,this.name=e.name,this.brtcSig=e.sig,this.identity=e.identity,this.isBig=e.is_big,this.sig=e.sig,Global.token=e.token,this.isJoining=!0,this.type===SING_MODE&&(yield SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))),this.type===MIX_MODE){this.disableMediaEngine=!0;try{this.brtcClient=BRTC$2.exports.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,audioLevelInterval:200,roomType:"big",silence:!0}),this.createShareBrtcClient(),this.addBrtcEvent(),this.fire("brtc-bound",!0),BRTC$2.exports.setVTRequestTimeout(5),yield this.joinRoom().then((()=>(this.isJoining=!1,this.fire(BCEvent$2.JOIN_READY),t(!0)))).catch((e=>(error$2("join room error","",this.userId,[JSON.stringify(e)]),i(e))))}catch(e){return this.isJoining=!1,error$2("join room error",LOGGER_TAG_CLIENT$1,this.userId,[e]),i(e)}}}))))}))}joinRoom(){return new Promise(((e,t)=>{let i=!1,r=!1;this.joinBloud().then((()=>{if(i=!0,r)return e(!0)})).catch((e=>t(e))),this.joinBrtc().then((()=>{if(r=!0,i)return e(!0)})).catch((e=>t(e)))}))}createShareBrtcClient(){return this.shareBrtcClient||(this.shareBrtcClient=BRTC$2.exports.createClient({codec:"h264",appId:this.brtcAppId,useStringUserId:!0,roomType:"big",silence:!0}),this.shareBrtcClient.on("error",(e=>{this.fire("share-brtc-error",e)}))),this.shareBrtcClient}_getBloudProxiesUrl(e){return new Promise(((t,i)=>{request({url:`${this.getProxiesUrl}/proxies?token=${e}`}).then((i=>{t({proxies:i.proxies,token:e})})).catch((e=>{i(getBloudProxiesUrlError(e))}))}))}on(e,t){return this.emitter.on(e,{fn:t,ctx:this}),this}fire(e,t){this.emitter&&this.emitter.fire(e,t?[t]:void 0)}changeMaster(e,t=!1){return this.client.changeMaster(e,t).catch((e=>e))}getMaster(){return this.client.getMaster()}syncUser(e){return this.client.syncUser(e)}getCreator(){return this.client.getCreator()}getName(){return this.client.getName()}close(){var e;return __awaiter$1(this,void 0,void 0,(function*(){this.leaveBrtcRoom(),null===(e=this.client)||void 0===e||e.close(),this.leaveShare()}))}getMsgSeq(){return this.client.getMsgSeq()}evictUser(e,t){return this.client.evictUser2(this.getMaster(),e,t)}updateUser(e,t){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.updateUser(e,t)}))}getLimits(){return this.client.getLimits()}getSwitch(){return this.client.getSwitch()}syncRoom(){return this.client.syncRoom()}update(e){return this.client.update(e)}getUsers(e,t,i){return __awaiter$1(this,void 0,void 0,(function*(){let{participants:r,total:n}=yield this.client.getUsers(e,t,i),s=new Map;return r.forEach((e=>{let t=BCUser.toUser(e,this.type);s.set(t.userId,t)})),{users:s,total:n}}))}getUsersList(e,t,i,r){return __awaiter$1(this,void 0,void 0,(function*(){let{participants:n,total:s,pageIndex:o}=yield this.client.getUsersList(e,i,t,r),a=new Map;return n.forEach((e=>{let t=BCUser.toUser(e,this.type);a.set(t.userId,t)})),{users:a,total:s,pageIndex:o}}))}getTotalUsers(){return this.client.getTotalUsers()}sendMessage(e,t){return this.client.sendMessage(e,t)}customMessage(e,t){return this.client.customMessage(e,t)}getMessages(e,t){return this.client.getMessages(e,t)}getLocalParticipant(){var e;return null===(e=this.client)||void 0===e?void 0:e.getLocalParticipant()}getAudioOff(){return this.client.getAudioOff()}getSelfOpenAudio(){return this.client.getSelfOpenAudio()}getVideoOff(){return this.client.getVideoOff()}getMsgOff(){return this.client.getMsgOff()}getLock(){return this.client.getLock()}getRoomInfo(){let e=Object.assign({},this.client.options);return delete e.token,e}setAudioOff(e,t){return this.client.setAudioOff(e,t)}setVideoOff(e){return this.client.setVideoOff(e)}setMsgOff(e){return this.client.setMsgOff(e)}setSwitch(e){return this.client.setSwitch(e)}setLock(e){return this.client.setLock(e)}publish(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.publish(e).catch((e=>Promise.reject(BrtcPublishError(JSON.stringify(e)))))}))}unpublish(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.unpublish(e).catch((e=>Promise.reject(BrtcUnPublishError(JSON.stringify(e)))))}))}subscribe(e,t={audio:!0,video:!0}){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.subscribe(e,t).catch((e=>Promise.reject(e)))}))}unsubscribe(e){return __awaiter$1(this,void 0,void 0,(function*(){return this.brtcClient.unsubscribe(e).catch((e=>Promise.reject(BrtcUnsubscribeError(JSON.stringify(e)))))}))}addBloudEvent(){let e=this,t=BloudParameterHandlerMap;each$3(bloudEvents,(i=>{!function(i,r){e.client.on(i,(function(){let i=execute$1(t[r],e,toArray(arguments));e.fire(r,i)}))}(i,i)}))}addBrtcEvent(){const e=this;each$3(BrtcEvents,(t=>{var i;i=t,e.brtcClient.on(i,(t=>{e.fire(i,t)}))}))}clearBrtcEvent(){this.brtcClient.off()}leave(){return __awaiter$1(this,void 0,void 0,(function*(){return console.log("离开会议","userId =>",this.userId,"roomId =>",this.roomId,"userInfo =>",this.userinfo),yield SingleMode.singleModeLeave(this),this.leaveBrtcRoom()}))}leaveBrtcRoom(){return __awaiter$1(this,void 0,void 0,(function*(){if(console.log("离开brtc调用堆栈!!!!!"),this.brtcClient&&(this.brtcClient.off(),yield this.brtcClient.leave(),yield this.brtcClient.destroy(),this.brtcClient=null),this.shareBrtcClient){try{this.shareBrtcClient.off(),yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(),this.shareBrtcClient=null}}))}leaveShare(){return __awaiter$1(this,void 0,void 0,(function*(){if(this.shareBrtcClient){try{yield this.shareBrtcClient.leave()}catch(e){}this.shareBrtcClient.destroy(),this.shareBrtcClient=null}}))}getEventList(){return BCEvent$2}createRecorder(e){return this.client.Recorder(e)}createSpeakerDetector(){return this.client.SpeakerDetector()}createLocalStream(e,t){return __awaiter$1(this,void 0,void 0,(function*(){if(!BRTC$2.exports.isSmallStreamSupported())return error$2("simulcast is not supported"),Promise.reject("simulcast is not supported");yield this.brtcClient.enableSmallStream(),this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return BRTC$2.exports.createStream(e)}catch(e){return Promise.reject(e)}}))}createPBLocalStream(e,t){return __awaiter$1(this,void 0,void 0,(function*(){this.brtcClient.setSmallStreamProfile({width:320,height:180,bitrate:100});try{return BRTC$2.exports.createStream(e)}catch(e){return Promise.reject(BrtcCreateStreamError(JSON.stringify(e)))}}))}creteBloudLocalStream(e,t){return this.client.Stream({audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t,screen:!1})}createBloudScreenStream(e,t){return this.client.Stream({screen:!0,audio:!0,video:!0,audio_enable:e.audio_enable,video_enable:e.video_enable,id:t})}updateCustomStats(e,t=!1){return info$1("updateCustomStats","updateCustomStats","",[" customstats => ",JSON.stringify(e),"replace => ",t]),this.client.updateCustomStats({customStats:e},t)}getCustomStats(){var e;return null===(e=this.client)||void 0===e?void 0:e.getCustomStats()}getDuration(){var e;return null===(e=this.client)||void 0===e?void 0:e.duration}toggleShareScreen(e,t,i){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise(((t,r)=>__awaiter$1(this,void 0,void 0,(function*(){if(e)try{let e;e=i?yield BRTC$2.exports.createStream({video:!!i.videoSource,audio:!!i.audioSource,videoSource:i.videoSource,audioSource:i.audioSource,screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail"}):yield BRTC$2.exports.createStream({screen:!0,videoHint:"motion"===this.shareContentHint?"motion":"detail"});const r="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:r.frameRate,bitrate:r.bitrate});try{yield e.init()}catch(e){throw error$2("brtc stream init failed","","",[e]),new Error(e)}yield this.publishShareStream(e),t(!0)}catch(e){String(e).includes("Permission denied by system")?(error$2("没有打开共享屏幕录制权限",e,"userId =>",this.userId),r(ShareScreenNoPermission)):String(e).includes("Permission denied")?(info$1("点击了取消共享屏幕, userId=>",this.userId,"nickname =>",this.name),r(ShareScreenCanceled)):(error$2("开启共享屏幕失败","","",[JSON.stringify(e)]),r(ShareScreenOtherError("开启共享屏幕失败,请重试")))}else yield this.unpublishShareStream(),t(!0)}))))}))}shareHTMLMedia(e,t){return __awaiter$1(this,void 0,void 0,(function*(){if(e&&t)try{const e=BRTC$2.exports.createStream({audio:t.audio,video:t.video,videoSource:t.videoSource,audioSource:t.audioSource,videoHint:"motion"}),i="motion"===this.shareContentHint?{frameRate:15,bitrate:4e3}:{frameRate:5,bitrate:4e3};e.setVideoEncoderConfiguration({width:1920,height:1080,frameRate:i.frameRate,bitrate:i.bitrate}),yield e.init(),yield this.publishShareStream(e)}catch(e){return Promise.reject(ToggleShareScreenError(JSON.stringify(e)))}e||(yield this.unpublishShareStream())}))}publishShareStream(e){return __awaiter$1(this,void 0,void 0,(function*(){if(this.shareBrtcClient||this.createShareBrtcClient(),!this.brtcShareSig)return console.error("brtcShareSig为空"),Promise.reject(BrtcShareSigError);{yield this.shareBrtcClient.join(this.roomId,`${this.userId}_screen`,this.brtcShareSig).catch((e=>(error$2("共享屏幕入会失败","","",[JSON.stringify(e),this.brtcShareSig]),Promise.reject(ShareScreenClientJoinedError)))),e.on("video-track-ended",(()=>{this.handleShareStreamEnded()})),yield this.shareBrtcClient.publish(e).catch((e=>{error$2("共享屏幕流推流失败","","",["err =>",JSON.stringify(e)])})),this.shareBrtcClient.on("sync-room-completed",(()=>{this.fire(BCEvent$2.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));let t=e.getAudioOn(),i=e.getVideoOn();this.shareScreenStream=e,this.createAndPubBloudShareStream(t,i),setTimeout((()=>{Promise.resolve(!0)}),200)}}))}createAndPubBloudShareStream(e,t){this.bloudShareScreenStream=this.createBloudScreenStream({audio_enable:e,video_enable:t},`${this.userId}_screen`),this.bloudShareScreenStream.publish({video_enable:t,audio_enable:e})}replaceShareStreamVideoTrack(e){this.shareScreenStream?this.shareScreenStream.replaceTrack(e):error$2("当前没有开启共享屏幕,无法替换track")}unpublishShareStream(){return __awaiter$1(this,void 0,void 0,(function*(){return new Promise((e=>__awaiter$1(this,void 0,void 0,(function*(){try{yield this.bloudShareScreenStream.unpublish(!1).then((()=>{this.bloudShareScreenStream=void 0})).catch((e=>{error$2("bloud share stream unpublish failed"),this.handleBloudSharePubFailed()})),yield this.shareBrtcClient.unpublish(this.shareScreenStream).catch((e=>{error$2("取消共享屏幕出错","","",[JSON.stringify(e)])}))}catch(e){console.log("取消共享兼容处理",e)}setTimeout((()=>__awaiter$1(this,void 0,void 0,(function*(){var t,i;yield null===(t=this.shareBrtcClient)||void 0===t?void 0:t.leave().catch((e=>{error$2("shareBrtcClient leave error","","",[JSON.stringify(e)])})),null===(i=this.shareScreenStream)||void 0===i||i.destroy(),this.shareScreenStream=void 0,e(!0)}))),500)}))))}))}setShareScreenContentHint(e){this.shareContentHint=e}releaseRoom(){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.release()}))}handleShareStreamEnded(){setTimeout((()=>{var e;this.shareScreenStream&&"live"===(null===(e=this.shareScreenStream.getVideoTrack())||void 0===e?void 0:e.readyState)||(error$2("share stream video track ended"),this.fire("toggle-screen-share",!1))}),2e3)}setCustomUrl(e){BRTC$2.exports.setCustomUrl(e)}bloudReconnect(){return __awaiter$1(this,void 0,void 0,(function*(){yield this.client.leave(),yield SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))}))}searchUsers(e,t,i){return __awaiter$1(this,void 0,void 0,(function*(){const{participants:r}=yield this.client.searchUsers(e,t,i);let n=new Map;return r.forEach((e=>{let t=BCUser.toUser(e,this.type);n.set(t.userId,t)})),{users:n}}))}queryUsers(e){return __awaiter$1(this,void 0,void 0,(function*(){const{participants:t}=yield this.client.queryUsers(e);let i=new Map;return t.forEach((e=>{let t=BCUser.toUser(e,this.type);i.set(t.userId,t)})),{users:i}}))}handleBloudRejoin(){return __awaiter$1(this,void 0,void 0,(function*(){return SingleMode.singleModeJoin(this,(()=>this.addBloudEvent()))}))}}const PLAYER_STATE_CHANGED="player-state-changed";class Player{constructor(e,t){this.element=e,this.options=t,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.backgroundColor="#202020",this.container.style.overflow="hidden",e.appendChild(this.container)}playVideo(){if(!this.video){if(!this.stream.getVideoTrack())return;this.video=document.createElement("video"),this.video.autoplay=!0,this.video.playsInline=!0,this.video.muted=this.options.muted,this.video.style.width="100%",this.video.style.height="100%",this.video.style.position="absolute";let e="";this.options.rotateX&&(e=`rotateX(${this.options.rotateX}deg)`),this.options.rotateY&&(e=`${e} rotateY(${this.options.rotateY}deg)`),e&&(this.video.style.transform=e),this.video.style.objectFit=this.options.fit,this.video.id=`video_${this.stream.getStreamId()}_big`,this.container.appendChild(this.video),this.video.addEventListener("playing",(()=>{this.videoStatus="PLAYING",this.stream.fire(PLAYER_STATE_CHANGED,{type:"video",state:this.videoStatus,reason:"playing"}),info$1("stream video playing",LOGGER_TAG_PLAYER,this.stream.getUserId())})),this.video.addEventListener("pause",(()=>{this.videoStatus="PAUSED",this.stream.fire(PLAYER_STATE_CHANGED,{type:"video",state:this.videoStatus,reason:"pause"}),info$1("stream video pause",LOGGER_TAG_PLAYER,this.stream.getUserId())})),this.video.addEventListener("stalled",(()=>{this.videoStatus="PAUSED",this.stream.fire(PLAYER_STATE_CHANGED,{type:"video",state:this.videoStatus,reason:"stalled"}),info$1("stream video stalled",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e,this.videoStatus="STOPPED"}play(e){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e,this.container.id=`player_${e.getStreamId()}_big_container`,this.stream.hasVideo()&&this.playVideo();try{this.video&&(yield this.video.play())}catch(e){this.stream.fire(PLAYER_STATE_CHANGED,{type:"error",reason:e})}}))}replay(e,t=!0,i=!0){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e;try{this.stream.hasVideo()&&t&&this.playVideo(),this.stream.hasVideo()&&t&&(yield this.video.play())}catch(e){this.stream.fire(PLAYER_STATE_CHANGED,{type:"error",reason:e})}debug$1("stream replay",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}muteVideo(){this.video&&(this.video.srcObject=void 0,this.videoStatus="STOPPED")}unmuteVideo(){if(this.video&&this.stream&&"STOPPED"===this.videoStatus){let e=new MediaStream;e.addTrack(this.stream.getVideoTrack()),this.video.srcObject=e}}destroy(){this.element.removeChild(this.container),this.video=null,this.container=null,debug$1("stream player destroy",LOGGER_TAG_PLAYER,this.stream.getUserId())}resume(){return __awaiter$1(this,void 0,void 0,(function*(){this.video&&this.video.play(),debug$1("stream player resume",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}getVideoFrame(){if(this.video&&"STOPPED"!==this.videoStatus){const e=document.createElement("canvas");return e.width=this.video.videoWidth,e.height=this.video.videoHeight,e.getContext("2d").drawImage(this.video,0,0),e.toDataURL("image/png")}}}function func$1(e){return typeof e===RAW_FUNCTION$3}const TRUE$3=!0,FALSE$3=!1,NULL$3=null,UNDEFINED$3=void 0,MINUS_ONE$3=-1,RAW_UNDEFINED$3="undefined",RAW_FUNCTION$4="function",RAW_DOT$3=".",WINDOW$3=typeof window!==RAW_UNDEFINED$3?window:UNDEFINED$3,GLOBAL$3=typeof global$2!==RAW_UNDEFINED$3?global$2:WINDOW$3,EMPTY_FUNCTION$4=function(){};Object.freeze({}),Object.freeze([]);const EMPTY_STRING$3="";function func$4(e){return typeof e===RAW_FUNCTION$4}function array$3(e){return Array.isArray(e)}function object$3(e){return e!==NULL$3&&"object"==typeof e}function string$3(e){return"string"==typeof e}function number$3(e){return"number"==typeof e&&!isNaN(e)}function execute$3(e,t,i){if(func$4(e))return array$3(i)?e.apply(t,i):t!==UNDEFINED$3?e.call(t,i):i!==UNDEFINED$3?e(i):e()}function each$1$2(e,t,i){if(!e)return;const{length:r}=e;if(r)if(i)for(let i=r-1;i>=0&&t(e[i],i)!==FALSE$3;i--);else for(let i=0;i<r&&t(e[i],i)!==FALSE$3;i++);}function nativePush$3(e,t){e[e.length]=t}function addItem$3(e,t,i){array$3(t)?each$1$2(t,(function(t){i(e,t)})):i(e,t)}function push$3(e,t){addItem$3(e,t,nativePush$3)}function indexOf$1$2(e,t,i){let r=MINUS_ONE$3;return each$1$2(e,(function(e,n){if(i===FALSE$3?e==t:e===t)return r=n,FALSE$3})),r}function has$3(e,t,i){return indexOf$1$2(e,t,i)>=0}class CustomEvent$3{constructor(e,t){this.type=e,this.phase=CustomEvent$3.PHASE_CURRENT,t&&(this.originalEvent=t)}preventDefault(){const e=this;if(!e.isPrevented){const{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=TRUE$3}return e}stopPropagation(){const e=this;if(!e.isStoped){const{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=TRUE$3}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}}function toString$3(e,t){return e!=NULL$3&&e.toString?e.toString():t!==UNDEFINED$3?t:EMPTY_STRING$3}function slice$3(e,t,i){return number$3(i)?t===i?EMPTY_STRING$3:e.slice(t,i):e.slice(t)}function indexOf$5(e,t,i){return e.indexOf(t,i!==UNDEFINED$3?i:0)}function each$5(e,t){for(let i in e)if(t(e[i],i)===FALSE$3)break}function copy$3(e,t){let i=e;return array$3(e)?t?(i=[],each$1$2(e,(function(e,r){i[r]=copy$3(e,t)}))):i=e.slice():object$3(e)&&(i={},each$5(e,(function(e,r){i[r]=t?copy$3(e,t):e}))),i}CustomEvent$3.PHASE_CURRENT=0,CustomEvent$3.PHASE_UPWARD=1,CustomEvent$3.PHASE_DOWNWARD=MINUS_ONE$3;const TRACE=0,INFO$3=2,WARN$3=3,FATAL$3=5;let defaultTag="bjy";const nativeConsole$4=typeof console!==RAW_UNDEFINED$3?console:NULL$3,defaultLogLevel$3=/bjy/.test(toString$3(EMPTY_FUNCTION$4))?INFO$3:WARN$3,stylePrefix$3=WINDOW$3&&/edge|msie|trident/i.test(WINDOW$3.navigator.userAgent)?EMPTY_STRING$3:"%c",printLog$3=nativeConsole$4?stylePrefix$3?function(e,t,i,r){r?nativeConsole$4.log(stylePrefix$3+e,i,t,r):nativeConsole$4.log(stylePrefix$3+e,i,t)}:function(e,t,i){i?nativeConsole$4.log(e,t,i):nativeConsole$4.log(e,t)}:EMPTY_FUNCTION$4;function getLogLevel$3(){if(GLOBAL$3){const e=GLOBAL$3.BJY_LOG_LEVEL;if(e>=TRACE&&e<=FATAL$3)return e}return defaultLogLevel$3}function getStyle$3(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function warn$3(e,t){getLogLevel$3()<=WARN$3&&printLog$3(`${t||defaultTag} warn`,e,getStyle$3("#f90"))}function fatal$3(e,t){if(getLogLevel$3()<=FATAL$3)throw new Error(`[${t||defaultTag} fatal]: ${e}`)}class Emitter$3{constructor(e){this.ns=e||FALSE$3,this.listeners={}}fire(e,t,i){let r=this,n=string$3(e)?r.parse(e):e,s=r.listeners[n.type],o=TRUE$3;if(s){s=copy$3(s);const e=t&&t[0]instanceof CustomEvent$3?t[0]:UNDEFINED$3;each$1$2(s,(function(a){if(!matchNamespace$3(n.ns,a,TRUE$3)||!has$3(s,a)||i&&!i(n,t,a))return;e&&(e.listener=a.fn);let c=execute$3(a.fn,a.ctx,t);return e&&(e.listener=UNDEFINED$3),a.num=a.num?a.num+1:1,a.num===a.max&&r.off(n,a.fn),e&&(c===FALSE$3?e.prevent().stop():e.isStoped&&(c=FALSE$3)),c===FALSE$3?o=FALSE$3:void 0}))}return o}on(e,t){const i=this,r=i.listeners,n=func$4(t)?{fn:t}:t;if(object$3(n)&&func$4(n.fn)){const t=string$3(e)?i.parse(e):e;n.ns=t.ns,push$3(r[t.type]||(r[t.type]=[]),n)}else"development"===process$2.env.NODE_ENV&&fatal$3('emitter.on(type, listener) invoke failed:\n\n"listener" is expected to be a Function or an EmitterOptions.\n');return this}one(e,t){return func$4(t)?t={fn:t,max:1}:t.max=1,this.on(e,t)}off(e,t){const i=this,r=i.listeners;if(e){const n=string$3(e)?i.parse(e):e,s=n.type,o=n.ns,a=createMatchListener$3(t),c=function(e,t){each$1$2(e,(function(t,i){a(t)&&e.splice(i,1)}),TRUE$3),e.length||delete r[t]},u=function(e,t){each$1$2(e,(function(t,i){matchNamespace$3(o,t)&&e.splice(i,1)}),TRUE$3),e.length||delete r[t]};s?r[s]&&c(r[s],s):o&&each$5(r,u),"development"===process$2.env.NODE_ENV&&arguments.length>1&&t==NULL$3&&warn$3(`emitter.off(type, listener) is invoked, but "listener" is ${t}.`)}else i.listeners={},"development"===process$2.env.NODE_ENV&&arguments.length>0&&warn$3(`emitter.off(type) is invoked, but "type" is ${e}.`)}has(e,t){let i=this.listeners,r=string$3(e)?this.parse(e):e,n=r.type,s=r.ns,o=TRUE$3,a=createMatchListener$3(t);return n?i[n]&&each$1$2(i[n],(function(e){if(a(e))return o=FALSE$3})):s&&each$5(i,(function(e){return each$1$2(e,(function(e){if(matchNamespace$3(s,e))return o=FALSE$3})),o})),!o}parse(e){const t={type:e,ns:EMPTY_STRING$3};if(this.ns){const i=indexOf$5(e,RAW_DOT$3);i>=0&&(t.type=slice$3(e,0,i),t.ns=slice$3(e,i+1))}return t}}function matchTrue$3(){return TRUE$3}function createMatchListener$3(e){return func$4(e)?function(t){return e===t.fn}:matchTrue$3}function matchNamespace$3(e,t,i){const{ns:r}=t;return r&&e?r===e:i?TRUE$3:FALSE$3}class AudioPlayer extends Emitter$3{constructor(e,t){super(),this.audioLevel=1,this.element=e,this.options=t}playAudio(){if(!this.audio){if(!this.stream.getAudioTrack())return;this.audio=document.createElement("audio"),this.audio.autoplay=!0,this.audio.playsInline=!0,this.audio.muted=this.options.muted,this.audio.id=`audio_${this.stream.getStreamId()}_back`,this.element.appendChild(this.audio),this.stream.getAudioDeviceId()&&this.setSinkId(this.stream.getAudioDeviceId()),this.audio.volume=this.audioLevel,this.audio.addEventListener("playing",(()=>{this.audioStatus="PLAYING",this.stream.fire(PLAYER_STATE_CHANGED,{type:"audio",state:this.audioStatus,reason:"playing"}),this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"playing"}]),info$1("stream audio playing",LOGGER_TAG_PLAYER,this.stream.getUserId())})),this.audio.addEventListener("pause",(()=>{this.audioStatus="PAUSED",this.stream.fire(PLAYER_STATE_CHANGED,{type:"audio",state:this.audioStatus,reason:"pause"}),this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"pause"}]),info$1("stream audio pause",LOGGER_TAG_PLAYER,this.stream.getUserId())})),this.audio.addEventListener("stalled",(()=>{this.audioStatus="PAUSED",this.stream.fire(PLAYER_STATE_CHANGED,{type:"audio",state:this.audioStatus,reason:"stalled"}),this.fire(PLAYER_STATE_CHANGED,[{type:"audio",state:this.audioStatus,reason:"stalled"}]),info$1("stream audio stalled",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e,this.audioStatus="STOPPED"}setSinkId(e){return __awaiter$1(this,void 0,void 0,(function*(){this.audio&&func$1(this.audio.setSinkId)&&(yield this.audio.setSinkId(e))}))}setVolume(e){this.audio&&(this.audioLevel=e,this.audio.volume=e)}play(e){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e,this.stream.hasAudio()&&this.playAudio();try{this.audio&&(yield this.audio.play())}catch(e){this.stream.fire(PLAYER_STATE_CHANGED,{type:"error",reason:e})}}))}replay(e,t=!0,i=!0){return __awaiter$1(this,void 0,void 0,(function*(){this.stream=e;try{this.stream.hasAudio()&&i&&this.playAudio(),this.stream.hasAudio()&&i&&(yield this.audio.play())}catch(e){this.stream.fire(PLAYER_STATE_CHANGED,{type:"error",reason:e})}debug$1("stream replay",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}muteAudio(){this.audio&&(this.audio.srcObject=void 0,this.audioStatus="STOPPED")}unmuteAudio(){if(this.audio&&this.stream&&"STOPPED"===this.audioStatus){let e=new MediaStream;e.addTrack(this.stream.getAudioTrack()),this.audio.srcObject=e}}destroy(){this.element.removeChild(this.audio),this.audio=null,debug$1("stream player destroy",LOGGER_TAG_PLAYER,this.stream.getUserId())}resume(){return __awaiter$1(this,void 0,void 0,(function*(){this.audio&&this.audio.play(),debug$1("stream player resume",LOGGER_TAG_PLAYER,this.stream.getUserId())}))}}const enumAudioInputDevices=BRTC$2.exports.enumAudioInputDevices,enumAudioOutputDevices=BRTC$2.exports.enumAudioOutputDevices,enumVideoDevices=BRTC$2.exports.enumVideoDevices,getPermissions=BRTC$2.exports.getPermissions,checkSystemSupport=BRTC$2.exports.checkSystemSupport,createStream=BRTC$2.exports.createStream;class BoomError$1 extends Error{constructor(e,t,i,r){super(),this.code=e,this.error=i,this.BoomErrorFlag=!0,this.eName=r,this.message=t}static instanceOf(e){return!(!e||!e.BoomErrorFlag)}getCode(){return this.code}}const LOCAL_ERROR=1e3,INVALID_PARAMETER=1001,INVALID_OPERATION=1002,CLIENT_BANNED=4005,USER_NOT_EXIT=9001,DEBUG$1=1,WARN$1=3,EMPTY_FUNCTION$1=function(){};function formatLog(e,t,i,r){let n=[];return i&&n.push(i),r&&n.push(r),`[${(new Date).toLocaleTimeString("chinese",{hour12:!1})}] <${e}> [${n.join("|")}] ${t}`}function info(e,t,i,r=[]){r.unshift(formatLog("INFO",e,t,i)),console.log(...r)}function warn$1(e,t,i,r=[]){r.unshift(formatLog("WARN",e,t,i)),console.log(...r)}function error$1(e,t,i,r=[]){r.unshift(formatLog("ERROR",e,t,i)),console.log(...r)}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}/BRTC/.test(EMPTY_FUNCTION$1.toString());var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,i,r,n;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=__values(s),a=o.next();!a.done;a=o.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(isFunction(c))try{c()}catch(e){n=e instanceof UnsubscriptionError?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var d=__values(u),l=d.next();!l.done;l=d.next()){var h=l.value;try{execFinalizer(h)}catch(e){n=null!=n?n:[],e instanceof UnsubscriptionError?n=__spreadArray(__spreadArray([],__read(n)),__read(e.errors)):n.push(e)}}}catch(e){i={error:e}}finally{try{l&&!l.done&&(r=d.return)&&r.call(d)}finally{if(i)throw i.error}}}if(n)throw new UnsubscriptionError(n)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&arrRemove(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),EMPTY_SUBSCRIPTION=Subscription.EMPTY;function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}var config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},timeoutProvider={setTimeout:function(e,t){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];var n=timeoutProvider.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,__spreadArray([e,t],__read(i))):setTimeout.apply(void 0,__spreadArray([e,t],__read(i)))},clearTimeout:function(e){var t=timeoutProvider.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}var context=null;function errorContext(e){if(config.useDeprecatedSynchronousErrorHandling){var t=!context;if(t&&(context={errorThrown:!1,error:null}),e(),t){var i=context,r=i.errorThrown,n=i.error;if(context=null,r)throw n}}else e()}var Subscriber=function(e){function t(t){var i=e.call(this)||this;return i.isStopped=!1,t?(i.destination=t,isSubscription(t)&&t.add(i)):i.destination=EMPTY_OBSERVER,i}return __extends(t,e),t.create=function(e,t,i){return new SafeSubscriber(e,t,i)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),_bind=Function.prototype.bind;function bind(e,t){return _bind.call(e,t)}var ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,i,r){var n,s,o=e.call(this)||this;isFunction(t)||!t?n={next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=r?r:void 0}:o&&config.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},n={next:t.next&&bind(t.next,s),error:t.error&&bind(t.error,s),complete:t.complete&&bind(t.complete,s)}):n=t;return o.destination=new ConsumerObserver(n),o}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var i=new e;return i.source=this,i.operator=t,i},e.prototype.subscribe=function(e,t,i){var r=this,n=isSubscriber(e)?e:new SafeSubscriber(e,t,i);return errorContext((function(){var e=r,t=e.operator,i=e.source;n.add(t?t.call(n,i):i?r._subscribe(n):r._trySubscribe(n))})),n},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var i=this;return new(t=getPromiseCtor(t))((function(t,r){var n=new SafeSubscriber({next:function(t){try{e(t)}catch(e){r(e),n.unsubscribe()}},error:r,complete:t});i.subscribe(n)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,i){var r;t.subscribe((function(e){return r=e}),(function(e){return i(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}var ObjectUnsubscribedError=createErrorClass((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),Subject=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return __extends(t,e),t.prototype.lift=function(e){var t=new AnonymousSubject(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new ObjectUnsubscribedError},t.prototype.next=function(e){var t=this;errorContext((function(){var i,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var n=__values(t.currentObservers),s=n.next();!s.done;s=n.next()){s.value.next(e)}}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}}}))},t.prototype.error=function(e){var t=this;errorContext((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var i=t.observers;i.length;)i.shift().error(e)}}))},t.prototype.complete=function(){var e=this;errorContext((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,r=i.hasError,n=i.isStopped,s=i.observers;return r||n?EMPTY_SUBSCRIPTION:(this.currentObservers=null,s.push(e),new Subscription((function(){t.currentObservers=null,arrRemove(s,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,r=t.thrownError,n=t.isStopped;i?e.error(r):n&&e.complete()},t.prototype.asObservable=function(){var e=new Observable;return e.source=this,e},t.create=function(e,t){return new AnonymousSubject(e,t)},t}(Observable),AnonymousSubject=function(e){function t(t,i){var r=e.call(this)||this;return r.destination=t,r.source=i,r}return __extends(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:EMPTY_SUBSCRIPTION},t}(Subject),BehaviorSubject=function(e){function t(t){var i=e.call(this)||this;return i._value=t,i}return __extends(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var i=e.prototype._subscribe.call(this,t);return!i.closed&&t.next(this._value),i},t.prototype.getValue=function(){var e=this,t=e.hasError,i=e.thrownError,r=e._value;if(t)throw i;return this._throwIfClosed(),r},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Subject);Object.freeze({}),Object.freeze([]);const LOGGER_TAG_CLIENT="c";var MODEL_SORT_ENUM_STAND,MODEL_SORT_ENUM_ZY,STREAM_TYPE;!function(e){e[e.SCREEN=0]="SCREEN",e[e.MASTER=1]="MASTER",e[e.LOCAL=2]="LOCAL",e[e.MANAGER_AUDIO_VIDEO=3]="MANAGER_AUDIO_VIDEO",e[e.MANAGER_AUDIO=4]="MANAGER_AUDIO",e[e.MANAGER_VIDEO=5]="MANAGER_VIDEO",e[e.MANAGER=6]="MANAGER",e[e.RAISE_HAND=7]="RAISE_HAND",e[e.RAISE_AUDIO=8]="RAISE_AUDIO",e[e.RAISE_VIDEO=9]="RAISE_VIDEO",e[e.GUEST_AUDIO_VIDEO=10]="GUEST_AUDIO_VIDEO",e[e.GUEST_AUDIO=11]="GUEST_AUDIO",e[e.GUEST_VIDEO=12]="GUEST_VIDEO",e[e.GUEST=13]="GUEST",e[e.SIGNAL=14]="SIGNAL",e[e.COMMONUSER_AUDIO_VIDEO=15]="COMMONUSER_AUDIO_VIDEO",e[e.COMMONUSER_AUDIO=16]="COMMONUSER_AUDIO",e[e.COMMONUSER_VIDEO=17]="COMMONUSER_VIDEO",e[e.OTHER=18]="OTHER"}(MODEL_SORT_ENUM_STAND||(MODEL_SORT_ENUM_STAND={})),function(e){e[e.SCREEN=0]="SCREEN",e[e.RAISE_AUDIO=1]="RAISE_AUDIO",e[e.RAISE_VIDEO=2]="RAISE_VIDEO",e[e.LOCAL=3]="LOCAL",e[e.MASTER_AUDIO_VIDEO=4]="MASTER_AUDIO_VIDEO",e[e.MANAGER_AUDIO_VIDEO=5]="MANAGER_AUDIO_VIDEO",e[e.AUDIO_VIDEO=6]="AUDIO_VIDEO",e[e.MASTER_AUDIO=7]="MASTER_AUDIO",e[e.MANAGER_AUDIO=8]="MANAGER_AUDIO",e[e.AUDIO=9]="AUDIO",e[e.MASTER_VIDEO=10]="MASTER_VIDEO",e[e.MANAGER_VIDEO=11]="MANAGER_VIDEO",e[e.VIDEO=12]="VIDEO",e[e.MASTER=13]="MASTER",e[e.MANAGER=14]="MANAGER",e[e.GUEST=15]="GUEST",e[e.COMMON_USER=16]="COMMON_USER",e[e.SIGNAL=17]="SIGNAL",e[e.OTHER=18]="OTHER"}(MODEL_SORT_ENUM_ZY||(MODEL_SORT_ENUM_ZY={})),function(e){e[e.SUB_MAIN=0]="SUB_MAIN",e[e.SINGLE=1]="SINGLE",e[e.SHARE=2]="SHARE",e[e.OTHER=3]="OTHER"}(STREAM_TYPE||(STREAM_TYPE={}));const STREAM_SUFFIX_SCREEN="_screen",MOBILE_STREAM_SUFFIX_SCREEN="screen-",SIGNAL_SUFFIX="xinhao_",RECEIVE_SUBSCRIBE_MESSAGE="sub-message",USER_SORT_NUM_CHANGE="user-sort-num-change",BIND_ELEMENT="bind-element",HANDLE_STREAM_CONNECT_ERROR="stream-connect-error",RAISE_HAND="raise-hand",MANUAL_SUBSCRIPTION="manual-subscription",UNSUBSCRIBE_STREAM="unsubscribe-stream",CHANG_IS_GUEST="change-is-guest",BIND_BIG_ELEMENT="bind-big-element",NO_CONTAINER="no-container",MODEL_SORT_NUM_CHANGE="model-sort-num-change",ADD_PULL_USER="add-pull-user",SET_VOLUME="set-volume";function mitt(e){return{all:e=e||new Map,on:function(t,i){var r=e.get(t);r?r.push(i):e.set(t,[i])},off:function(t,i){var r=e.get(t);r&&(i?r.splice(r.indexOf(i)>>>0,1):e.set(t,[]))},emit:function(t,i){var r=e.get(t);r&&r.slice().map((function(e){e(i)})),(r=e.get("*"))&&r.slice().map((function(e){e(t,i)}))}}}class BoomEmitter{static getInstance(){return BoomEmitter.emitter||(BoomEmitter.emitter=mitt()),BoomEmitter.emitter}}function getSortNum(e){return 2===_selfSortType?sortZY(e):sortStand(e)}function sortStand(e){let t;return t=e.isToupingma?MODEL_SORT_ENUM_STAND.SCREEN:e.isMaster?MODEL_SORT_ENUM_STAND.MASTER:e.isLocal?MODEL_SORT_ENUM_STAND.LOCAL:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO_VIDEO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_STAND.MANAGER_AUDIO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_STAND.MANAGER_VIDEO:e.isManager?MODEL_SORT_ENUM_STAND.MANAGER:e.raiseHand?MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?MODEL_SORT_ENUM_STAND.RAISE_AUDIO:e.raiseVideoHands?MODEL_SORT_ENUM_STAND.RAISE_VIDEO:!e.isCommonUser&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO_VIDEO:!e.isCommonUser&&e.audioEnable?MODEL_SORT_ENUM_STAND.GUEST_AUDIO:!e.isCommonUser&&e.videoEnable?MODEL_SORT_ENUM_STAND.GUEST_VIDEO:e.isCommonUser?e.isSignal?MODEL_SORT_ENUM_STAND.SIGNAL:e.isCommonUser&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO_VIDEO:e.isCommonUser&&e.videoEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_VIDEO:e.isCommonUser&&e.audioEnable?MODEL_SORT_ENUM_STAND.COMMONUSER_AUDIO:MODEL_SORT_ENUM_STAND.OTHER:MODEL_SORT_ENUM_STAND.GUEST,t}function sortZY(e){let t;return t=e.isToupingma?MODEL_SORT_ENUM_ZY.SCREEN:e.raiseHand?MODEL_SORT_ENUM_STAND.RAISE_HAND:e.raiseAudioHands?MODEL_SORT_ENUM_ZY.RAISE_AUDIO:e.raiseVideoHands?MODEL_SORT_ENUM_ZY.RAISE_VIDEO:e.isLocal?MODEL_SORT_ENUM_ZY.LOCAL:e.isMaster&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO_VIDEO:e.isManager&&e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO_VIDEO:e.audioEnable&&e.videoEnable?MODEL_SORT_ENUM_ZY.AUDIO_VIDEO:e.isMaster&&e.audioEnable?MODEL_SORT_ENUM_ZY.MASTER_AUDIO:e.isManager&&e.audioEnable?MODEL_SORT_ENUM_ZY.MANAGER_AUDIO:e.audioEnable?MODEL_SORT_ENUM_ZY.AUDIO:e.isMaster&&e.videoEnable?MODEL_SORT_ENUM_ZY.MASTER_VIDEO:e.isManager&&e.videoEnable?MODEL_SORT_ENUM_ZY.MANAGER_VIDEO:e.videoEnable?MODEL_SORT_ENUM_ZY.VIDEO:e.isMaster?MODEL_SORT_ENUM_ZY.MASTER:e.isManager?MODEL_SORT_ENUM_ZY.MANAGER:e.isCommonUser?MODEL_SORT_ENUM_ZY.COMMON_USER:e.isSignal?MODEL_SORT_ENUM_ZY.SIGNAL:MODEL_SORT_ENUM_ZY.GUEST,t}BoomEmitter.emitter=void 0,BoomEmitter.removeEmitter=()=>{var e,t,i,r,n,s,o,a,c,u,d,l,h;null===(e=BoomEmitter.emitter)||void 0===e||e.off(RECEIVE_SUBSCRIBE_MESSAGE),null===(t=BoomEmitter.emitter)||void 0===t||t.off(USER_SORT_NUM_CHANGE),null===(i=BoomEmitter.emitter)||void 0===i||i.off(HANDLE_STREAM_CONNECT_ERROR),null===(r=BoomEmitter.emitter)||void 0===r||r.off(RAISE_HAND),null===(n=BoomEmitter.emitter)||void 0===n||n.off(UNSUBSCRIBE_STREAM),null===(s=BoomEmitter.emitter)||void 0===s||s.off(MANUAL_SUBSCRIPTION),null===(o=BoomEmitter.emitter)||void 0===o||o.off(CHANG_IS_GUEST),null===(a=BoomEmitter.emitter)||void 0===a||a.off(BIND_ELEMENT),null===(c=BoomEmitter.emitter)||void 0===c||c.off(BIND_BIG_ELEMENT),null===(u=BoomEmitter.emitter)||void 0===u||u.off(NO_CONTAINER),null===(d=BoomEmitter.emitter)||void 0===d||d.off(MODEL_SORT_NUM_CHANGE),null===(l=BoomEmitter.emitter)||void 0===l||l.off(ADD_PULL_USER),null===(h=BoomEmitter.emitter)||void 0===h||h.off(SET_VOLUME),BoomEmitter.emitter=void 0};class BMUser{constructor(e,t=!1){var i;this.streamModels=new Map,this.sortNum=100,this.raiseVideoHands=!1,this.raiseAudioHands=!1,this.raiseHand=!1,this.isAudience=!1,this.isCommonUser=!1,this.inBackground=!1,this.raiseHandTime=0,this.userId=e.userId,this.userInfo=e.userInfo,this.nickName=e.nickname,this.isMaster=!!e.isMaster,this.isManager=!!e.isManager,this.isToupingma=!!e.isToupingma,this.isLocal=t,this.hasMultiple=!!e.hasMultiple,this.isCreate=!!e.isCreate,this.hasShare=!!e.hasShare,this.avatar=null===(i=e.userInfo)||void 0===i?void 0:i.avatar,this.permission=e.permission,this.raiseAudioHands=!!e.raiseAudioHands,this.raiseVideoHands=!!e.raiseVideoHands,this.raiseHand=!!e.raiseHand,this.isAudience=!!e.isAudience,this.isCommonUser=!!e.isCommonUser,this.inBackground=!!e.inBackground,this.audienceEnableSpeaking=!!e.audienceEnableSpeaking,this.raiseHandTime=e.raiseHandTime||0;const r={operation:"none",user:this};this.watcher=new BehaviorSubject(r),this.updateSortNum(!1)}get isWeb(){return!(!this.userInfo.pos||!this.userInfo.pos.includes("web")&&!this.userInfo.pos.includes("pc"))}setup(e,t,i){this.isLocal=!0,this.userId=e,this.userInfo=t,this.nickName=i||t.nickname,this.avatar=t.avatar}getMainStreamModel(){return this.streamModels.get(this.userId)}get nickname(){return this.nickName}getShareStreamModel(){return this.streamModels.get(`${this.userId}${STREAM_SUFFIX_SCREEN}`)}get audioEnable(){const e=this.getMainStreamModel();return!!e&&e._audio_enable}get isMixer(){return this.userId.includes("-mixer-")}get videoEnable(){const e=this.getMainStreamModel();return!!e&&e._video_enable}get isSharing(){let e=!1;for(let t of this.streamModels.values())if(t.isShare){e=!0;break}return e}get isSignal(){var e;return!!(null===(e=this.userId)||void 0===e?void 0:e.startsWith(SIGNAL_SUFFIX))}checkLocalHasMaster(){return this.isMaster||this.isManager}addStream(e,t){this.streamModels.set(e,t),this.watcher.next({operation:"changeShare",user:this})}removeStream(e){this.streamModels.delete(e),e.includes(STREAM_SUFFIX_SCREEN)&&info("删除的是共享屏幕的流:","","",["streamId =>",e]),setTimeout((()=>{this.watcher.next({operation:"changeShare",user:this})}),400)}getID(){return this.userId}getNickName(){return this.nickName}getUserInfo(){return this.userInfo}getStreams(){return this.streamModels}updateUserInfo(e,t={},i){var r,n,s,o,a,c;const u=null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.customInfo,d=(null==u?void 0:u.updateKeys)||[];let l=!1,h="none";info("updateUserInfo =>","updateUser",e.userId,["updateKeys",d.toString(),"permission",null===(n=e.permission)||void 0===n?void 0:n.permission,"isMaster =>",this.isMaster,"isManager =>",this.isManager]);const m=i.getLocalParticipant().isMaster||i.getLocalParticipant().isManager;if(this.nickName!==e.nickname&&(h="changeNickName"),this.isMaster||!this.isManager||e.permission.getManage()||(h="removeManager",this.isManager=!1),this.isMaster||this.isManager||!e.permission.getManage()||-1!=d.indexOf("changeMaster")||(h="getManager",this.isManager=!0),e.userinfo.pos)this.userInfo=e.userinfo;else{const t=this.userInfo.pos;this.userInfo=e.userinfo,this.userInfo.pos=t}(d.includes("changeMaster")||d.includes("permission"))&&(e.permission=t.getPermission()),d.includes("raiseHandsAudio")&&(this.raiseAudioHands=u.raiseHandsAudio,h="raiseHandsAudio",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsAudio",user:this}),l=!0),d.includes("raiseHandsVideo")&&(this.raiseVideoHands=u.raiseHandsVideo,h="raiseHandsVideo",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHandsVideo",user:this}),l=!0),d.includes("raiseHand")&&(this.raiseHand=u.raiseHand,this.raiseHandTime=u.raiseHandTime,h="raiseHand",BoomEmitter.emitter.emit(RAISE_HAND,{status:"raiseHand",user:this}),l=!0),1!==i.conferenceMode&&this.isAudience&&d.includes("permission")&&(-1!==(null===(o=null===(s=t.params)||void 0===s?void 0:s.customInfo)||void 0===o?void 0:o.permission.indexOf("A"))&&(i.enableAudienceSpeakingWatcher.next(!0),this.audienceEnableSpeaking=!0,h="audienceEnableSpeaking",i.bmLiveVM.handleAudienceEnable()),-1===(null===(c=null===(a=t.params)||void 0===a?void 0:a.customInfo)||void 0===c?void 0:c.permission.indexOf("A"))&&(i.enableAudienceSpeakingWatcher.next(!1),this.audienceEnableSpeaking=!1,h="audienceEnableSpeaking",i.bmLiveVM.handleAudienceDisable())),d.includes("inBackground")&&(h="inBackground",this.inBackground=u.inBackground),this.nickName=e.nickname,this.permission=e.permission;let p=!this.isCommonUser;if(this.isCommonUser=!e.permission.getSubscribe(),p!==!this.isCommonUser&&(info(`身份有发生过变化,从${p?"嘉宾":"普通参会者"} => ${this.isCommonUser?"普通参会者":"嘉宾"}`),BoomEmitter.emitter.emit(CHANG_IS_GUEST,{user:this,isGuest:!this.isCommonUser,preIsGuest:p})),h&&this.watcher.next({operation:h,user:this}),!l||l&&(m||this.isLocal)){const e=!l||l&&!(m||this.isLocal);this.updateSortNum(!0,e)}}hasManager(){return this.isManager||this.isMaster}getNicknameSuffix(){let e="";return this.isLocal&&this.isMaster?e="(我、主持人)":this.isLocal&&this.isManager?e="(我、联席主持人)":this.isLocal?e="(我)":this.isMaster?e="(主持人)":this.isManager?e="(联席主持人)":this.isSharing&&!this.isToupingma?e="的共享屏幕":this.isSharing&&this.isToupingma&&(e="(仅共享屏幕)"),e}updateSortNum(e=!0,t=!1){let i=getSortNum(this);this.setSortNum(i,e,t)}setSortNum(e,t,i){this.sortNum!==e&&(this.sortNum=e,t&&BoomEmitter.emitter.emit(USER_SORT_NUM_CHANGE,{isCommon:this.isCommonUser,shouldDelay:i}))}}const TRUE=!0,FALSE=!1,NULL=null,UNDEFINED=void 0,MINUS_ONE=-1,RAW_UNDEFINED="undefined",RAW_FUNCTION="function",RAW_DOT=".",WINDOW=typeof window!==RAW_UNDEFINED?window:UNDEFINED,GLOBAL=typeof global!==RAW_UNDEFINED?global:WINDOW,EMPTY_FUNCTION=function(){};Object.freeze({}),Object.freeze([]);const EMPTY_STRING="";function func(e){return typeof e===RAW_FUNCTION}function array(e){return Array.isArray(e)}function object(e){return e!==NULL&&"object"==typeof e}function string(e){return"string"==typeof e}function number(e){return"number"==typeof e&&!isNaN(e)}function execute(e,t,i){if(func(e))return array(i)?e.apply(t,i):t!==UNDEFINED?e.call(t,i):i!==UNDEFINED?e(i):e()}function slice(e,t,i){return number(i)?t===i?EMPTY_STRING:e.slice(t,i):e.slice(t)}function indexOf$1(e,t,i){return e.indexOf(t,i!==UNDEFINED?i:0)}function has$1(e,t){return indexOf$1(e,t)>=0}function toString(e,t){return e!=NULL&&e.toString?e.toString():t!==UNDEFINED?t:EMPTY_STRING}function isNative(e){return func(e)&&has$1(toString(e),"[native code]")}typeof setImmediate===RAW_FUNCTION&&isNative(setImmediate)&&setImmediate,typeof MessageChannel===RAW_FUNCTION&&isNative(MessageChannel);const notGetTalkInterval=3e5;function handleTime(e){let t=new Date(e),i=new Date,r=t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,n=t.getDate()<10?"0"+t.getDate():t.getDate(),s=t.getHours()<10?"0"+t.getHours():t.getHours(),o=t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes();return i.setHours(0,0,0,0)==t.setHours(0,0,0,0)?s+":"+o:r+"月"+n+"日 "+s+":"+o}function sortStreamModelsOrUser(e,t=!1){return e.sort(((e,i)=>t?i.sortNum-e.sortNum:e.sortNum-i.sortNum))}function getIsCommonUser(e){return!getPermission(e,"s")}function getIsManager(e){return getPermission(e,"m")}function getIsMaster(e){return getPermission(e,"o")}function getPermission(e,t){return e.toLowerCase().includes(t)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}var freeGlobal="object"==typeof global$3&&global$3&&global$3.Object===Object&&global$3,freeGlobal$1=freeGlobal,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal$1||freeSelf||Function("return this")(),root$1=root,Symbol$1=root$1.Symbol,Symbol$2=Symbol$1,objectProto$1=Object.prototype,hasOwnProperty=objectProto$1.hasOwnProperty,nativeObjectToString$1=objectProto$1.toString,symToStringTag$1=Symbol$2?Symbol$2.toStringTag:void 0;function getRawTag(e){var t=hasOwnProperty.call(e,symToStringTag$1),i=e[symToStringTag$1];try{e[symToStringTag$1]=void 0;var r=!0}catch(e){}var n=nativeObjectToString$1.call(e);return r&&(t?e[symToStringTag$1]=i:delete e[symToStringTag$1]),n}var objectProto=Object.prototype,nativeObjectToString=objectProto.toString;function objectToString(e){return nativeObjectToString.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$2?Symbol$2.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag}var reWhitespace=/\s/;function trimmedEndIndex(e){for(var t=e.length;t--&&reWhitespace.test(e.charAt(t)););return t}var reTrimStart=/^\s+/;function baseTrim(e){return e?e.slice(0,trimmedEndIndex(e)+1).replace(reTrimStart,""):e}function isObject(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var NAN=NaN,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;function toNumber(e){if("number"==typeof e)return e;if(isSymbol(e))return NAN;if(isObject(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=isObject(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=baseTrim(e);var i=reIsBinary.test(e);return i||reIsOctal.test(e)?freeParseInt(e.slice(2),i?2:8):reIsBadHex.test(e)?NAN:+e}var now=function(){return root$1.Date.now()},now$1=now,FUNC_ERROR_TEXT="Expected a function",nativeMax=Math.max,nativeMin=Math.min;function debounce(e,t,i){var r,n,s,o,a,c,u=0,d=!1,l=!1,h=!0;if("function"!=typeof e)throw new TypeError(FUNC_ERROR_TEXT);function m(t){var i=r,s=n;return r=n=void 0,u=t,o=e.apply(s,i)}function p(e){return u=e,a=setTimeout(v,t),d?m(e):o}function f(e){var i=e-c;return void 0===c||i>=t||i<0||l&&e-u>=s}function v(){var e=now$1();if(f(e))return g(e);a=setTimeout(v,function(e){var i=t-(e-c);return l?nativeMin(i,s-(e-u)):i}(e))}function g(e){return a=void 0,h&&r?m(e):(r=n=void 0,o)}function _(){var e=now$1(),i=f(e);if(r=arguments,n=this,c=e,i){if(void 0===a)return p(c);if(l)return clearTimeout(a),a=setTimeout(v,t),m(c)}return void 0===a&&(a=setTimeout(v,t)),o}return t=toNumber(t)||0,isObject(i)&&(d=!!i.leading,s=(l="maxWait"in i)?nativeMax(toNumber(i.maxWait)||0,t):s,h="trailing"in i?!!i.trailing:h),_.cancel=function(){void 0!==a&&clearTimeout(a),u=0,r=c=n=a=void 0},_.flush=function(){return void 0===a?o:g(now$1())},_}var numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}const ignoreUserId=["-mixer-","-rtmpmixer-","record#","robot_","stt_"],BLOUD_PAGE_SIZE=500,PERMISSION_NOT_COMMON="RWPSAVMO,RWPSAVM,RWPSAV";class BMUserVM{constructor(e,t,i){this.userList=new Map,this.audiencesList=new Map,this.signalList=new Map,this.commonUserList=new Map,this.userListWatcher=new BehaviorSubject(Array.from(this.userList.values())),this.audiencesListWatcher=new BehaviorSubject(Array.from(this.audiencesList.values())),this.commonUserListWatcher=new BehaviorSubject(Array.from(this.commonUserList.values())),this.signalListWatcher=new BehaviorSubject(Array.from(this.signalList.values())),this.masterUserWatcher=new BehaviorSubject(null),this.getForceUserWatcher=new BehaviorSubject(!1),this.commTimer=200,this.addBCUser=(e,t=!1)=>{var i;const r=this.addUser(e);if(!this.room.bmStreamVm.streamModels.get(e.userId)){const t=this.getUser(e.userId);t?this.room.bmStreamVm.createStreamModel(t):error$1(`there is no user named ${e.userId}, and create streamModel failed!!!`)}{const r=this.room.bmStreamVm.streamModels.get(e.userId);r&&(e.stream.size?e.stream.forEach((i=>__awaiter$2(this,void 0,void 0,(function*(){var n,s;if(i.screen){const i={id:r.userId,isScreen:!0,isWeb:r.isWeb};if(t){const t=new Map;t.set(e.userId,i),yield null===(n=this.room)||void 0===n?void 0:n.processUser(t)}else null===(s=this.room)||void 0===s||s.addUser2Queue(i)}else{const{video_enable:e,audio_enable:t}=i;r&&r.updateBloudStream({video:e,audio:t,isScreen:i.screen},this.room.bmStreamVm)}})))):(r.bloudStream&&r.updateBloudStream(void 0,this.room.bmStreamVm),null===(i=this.room)||void 0===i||i.bmStreamVm.removeShareStreamModelByUId(e.userId)))}return r&&r.isMaster&&this.masterUserWatcher.next(r),null==r||r.updateSortNum(!1),r},this.updateAllSort=()=>{this.updateUserSort(),this.updateCommonUserSort()},this.updateSortByType=e=>{var t,i;(null===(t=this.room)||void 0===t?void 0:t.isSingleColumns)||e.isCommon?(null===(i=this.room)||void 0===i?void 0:i.isBig)&&e.shouldDelay?this.updateDelayCommonUserSort():this.updateCommonUserSort():this.updateUserSort()},this.updateUserSort=debounce((()=>{const e=this.sortUsers();this.userListWatcher.next(BMUserVM.filterUsers(e))}),200,{maxWait:1e3}),this.updateCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),this.commTimer,{maxWait:12e3}),this.updateDelayCommonUserSort=debounce((()=>{const e=this.sortCommonUsers();this.commonUserListWatcher.next(BMUserVM.filterUsers(e))}),12e4,{maxWait:12e4}),this.updateAudienceUserSort=()=>{const e=this.sortAudiences();this.audiencesListWatcher.next(BMUserVM.filterUsers(e))},this.updateSignalUserSort=()=>{const e=this.sortSignalUsers();this.signalListWatcher.next(e)},this.transBloudUsers=(e,t="",i=!1,r=0)=>__awaiter$2(this,void 0,void 0,(function*(){const n=new Map;yield this.getAllUsers(e,n,t,i).catch((()=>r<3?(error$1("get bloud user error, retry"),r+=1,void this.transBloudUsers(e,t,i,r)):void error$1("get current page of bloud users after 10 times final failed","","",[" page ",e," permission ",t]))),yield this.initUserList(n),n.clear();let s=[];for(let e of this.userList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands||e.raiseHand)&&s.push(e);for(let e of this.commonUserList.values())(e.raiseVideoHands||e.raiseAudioHands)&&s.push(e);this.room.roomInfo.setRaiseHandsList(s),this.updateAllSort(),this.room.bmStreamVm.updateModelSort()})),this.boomCore=e,this.localUser=t,this.room=i,BoomEmitter.emitter||error$1("init boom emitter error"),BoomEmitter.emitter.on(CHANG_IS_GUEST,this.handleUserRoleChange.bind(this)),BoomEmitter.emitter.on(USER_SORT_NUM_CHANGE,this.updateSortByType)}handleUserRoleChange(e){var t,i,r;return __awaiter$2(this,void 0,void 0,(function*(){const{user:n,isGuest:s,preIsGuest:o}=e,a=null===(t=this.room)||void 0===t?void 0:t.roomInfo.isBigRoom;info("handleUserRoleChange","",n.userId,["isGuest =>",s,"preIsGuest =>",o,"isBigRoom =>",a]);if(1===(null===(i=this.room)||void 0===i?void 0:i.userListColumns)||(o?this.userList.delete(n.userId):this.commonUserList.delete(n.userId),s?this.userList.set(n.userId,n):this.commonUserList.set(n.userId,n)),a)if(s)n.isLocal&&(yield this.initUsers());else{const e=null===(r=this.room)||void 0===r?void 0:r.getLocalParticipant().isCommonUser;if(n.isLocal&&(this.handleUnSubCommonUser(),this.handleCommonUserChange(),this.commonUserList.set(n.userId,n)),e){const e=n.getMainStreamModel();e&&e.unSubscribeStream(),n.isLocal||this.commonUserList.delete(n.userId)}}this.updateAllSort()}))}addUser(e){var t;const i=this.getUser(e.userId);if(i)return info("该用户已经加入房间",LOGGER_TAG_CLIENT,e.userId),this.updateUser(i,e),null;let r;return this.boomCore.userId==e.userId?(this.updateUser(this.localUser,e),r=this.localUser):r=this.toBMUser(e),1===(null===(t=this.room)||void 0===t?void 0:t.userListColumns)?this.commonUserList.set(r.userId,r):r.isAudience?this.audiencesList.set(r.userId,r):r.isSignal?this.signalList.set(r.userId,r):r.isCommonUser?this.commonUserList.set(r.userId,r):this.userList.set(r.userId,r),r}removeUser(e){let t=this.userList.delete(e);return t||(t=this.signalList.delete(e)),t||(t=this.audiencesList.delete(e)),t||(t=this.commonUserList.delete(e)),t||warn$1("userList中未找到该用户, 移除无效",LOGGER_TAG_CLIENT,e),t}videoEnable(e){const t=this.getUser(e);if(t)return t.videoEnable;throw new BoomError$1(USER_NOT_EXIT,"用户不存在")}audioEnable(e){const t=this.getUser(e);if(t)return t.audioEnable;throw new BoomError$1(USER_NOT_EXIT,"用户不存在")}checkIsMaster(e){if(!e)return!1;const t=this.boomCore.getMaster();return!!t&&t===e}checkLocalHasMaster(){return this.localUser.isMaster||this.localUser.isManager}checkUserHasMaster(e){const t=this.userList.get(e);return!!t&&t.permission.getManage()}getUser(e){let t;return t=(null==e?void 0:e.startsWith(SIGNAL_SUFFIX))?this.signalList.get(e):this.userList.get(e),t||(t=this.commonUserList.get(e)),t||(t=this.audiencesList.get(e)),t}getAllUsers(e,t,i="",r=!1){return __awaiter$2(this,void 0,void 0,(function*(){let n;if(r){let{users:t,total:r}=yield this.boomCore.getUsersList(e,i,BLOUD_PAGE_SIZE);n=t}else{let{users:t,total:r}=yield this.boomCore.getUsers(e,i,BLOUD_PAGE_SIZE);n=t}n.forEach((e=>{t.set(e.userId,e)}))}))}initUserList(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){const r=e.get(this.localUser.userId);if(r){const e=this.addUser(r);if(!(null===(t=this.room)||void 0===t?void 0:t.bmStreamVm.getStreamModelByUId(r.userId))){const e=this.getUser(r.userId);e?null===(i=this.room)||void 0===i||i.bmStreamVm.createStreamModel(e):error$1("there is no local streamModel exits, and create failed!!!")}(null==e?void 0:e.isMaster)&&this.masterUserWatcher.next(e)}e.delete(this.localUser.userId),e&&e.size>0&&this.addBcUsersMap(e)}))}addBcUsersMap(e,t=!1){e.forEach((e=>{this.addBCUser(e,t)}))}updateMaster(e,t,i){const r=this.getUser(e);r&&(r.isManager&&(r.isManager=!1),r.isMaster=!0,r.updateSortNum());const n=this.getUser(t);return n&&(n.isMaster=!1,i&&(n.isManager=!0),n.updateSortNum()),r||n||error$1("未找到该用户, updateMaster未生效",LOGGER_TAG_CLIENT,e,["masterId => ",e,"oldMasterId => ",t]),{master:r,oldMaster:n}}managerChangeToGuest(e){const t=this.getUser(e);return t?t.isManager?(t.permission.setManage(!1),t.permission.setSubscribe(!0),this.boomCore.updateUser(e,{customInfo:{permission:t.permission.get()}}),t.watcher.next({operation:"getGuest",user:t}),this.updateAllSort()):error$1("该用户不是管理员,无法设置为嘉宾",LOGGER_TAG_CLIENT,e):error$1("未找到该用户, managerChangeToGuest未生效",LOGGER_TAG_CLIENT,e),t}updateManager(e,t,i=!0){const r=this.getUser(e);return r?(r.permission.setManage(t),r.permission.setSubscribe(t),this.boomCore.updateUser(e,{customInfo:{permission:r.permission.get()}}),r.watcher.next({operation:t?"getManager":"removeManager",user:r}),this.updateAllSort()):error$1("userList中未找到该用户, updateManager未生效",LOGGER_TAG_CLIENT,e),r}getLocalUser(){return this.localUser}updateUser(e,t){var i,r,n,s,o;const a=this.checkIsMaster(t.userId),c=((null===(i=t.permission)||void 0===i?void 0:i.getManage())||getIsManager(null===(r=t.permission)||void 0===r?void 0:r.permission))&&!((null===(n=t.permission)||void 0===n?void 0:n.getOwn())||getIsMaster(null===(s=t.permission)||void 0===s?void 0:s.permission));let u="none";const d=e.isMaster;e.isManager!==c&&(u=c?"getManager":"removeManager"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),10),d!==a&&(u=a?"getMaster":"removeMaster"),"none"!==u&&setTimeout((()=>{e.watcher.next({operation:u,user:e})}),100);e.raiseHand!==t.customInfo.raiseHand&&setTimeout((()=>{e.watcher.next({operation:"raiseHand",user:e})}),300);e.nickname!==t.nickname&&setTimeout((()=>{e.watcher.next({operation:"changeNickName",user:e})}),300),e.userInfo=t.userinfo,e.nickName=t.nickname,e.userId=t.userId,e.permission=t.permission,e.avatar=t.userinfo.avatar,e.isToupingma=t.userinfo.pos.includes("_toupingma"),e.isMaster=a,e.isCreate=this.boomCore.getCreator()===t.userId,e.isAudience=!t.permission.getAudio(),e.isCommonUser=!t.permission.getSubscribe(),e.isManager=c,e.inBackground=!!(null===(o=null==t?void 0:t.customInfo)||void 0===o?void 0:o.inBackground),e.updateSortNum()}updateLocalUserPermission(e){const t=this.getLocalUser();t.isMaster=getIsMaster(e),t.isManager=!getIsMaster(e)&&getIsManager(e),t.isCommonUser=getIsCommonUser(e),t.watcher.next({operation:"none",user:t})}toBMUser(e){var t,i;let r={};r.userInfo=e.userinfo,r.nickname=e.nickname,r.userId=e.userId,r.streamModels=[],r.permission=e.permission,r.stream=e.stream,r.isToupingma=!(!e.userinfo.pos||!e.userinfo.pos.includes("_toupingma")),r.isMaster=this.checkIsMaster(r.userId),r.isAudience=!e.permission.getAudio(),r.isCommonUser=!e.permission.getSubscribe()||getIsCommonUser(e.permission.permission),r.raiseAudioHands=e.customInfo.raiseHandsAudio,r.raiseVideoHands=e.customInfo.raiseHandsVideo,r.raiseHand=e.customInfo.raiseHand,r.raiseHandTime=e.customInfo.raiseHandTime,r.inBackground=e.customInfo.inBackground,r.isCreate=this.boomCore.getCreator()===e.userId;let n=this.boomCore.getLocalParticipant();if(!n)throw new BoomError$1(INVALID_PARAMETER,"BCUserVM addUser时未找到本地用户");return n.getID()==r.userId&&(r.isLocal=!0),!(null===(t=r.permission)||void 0===t?void 0:t.getManage())&&!getIsManager(null===(i=r.permission)||void 0===i?void 0:i.permission)||r.isMaster||(r.isManager=!0),new BMUser(r,r.isLocal)}sortUsers(){return sortStreamModelsOrUser(Array.from(this.userList.values()))}sortAudiences(){return sortStreamModelsOrUser(Array.from(this.audiencesList.values()))}sortCommonUsers(){return sortStreamModelsOrUser(Array.from(this.commonUserList.values()))}sortSignalUsers(){return sortStreamModelsOrUser(Array.from(this.signalList.values()))}static filterUsers(e){return e.filter((e=>!ignoreUserId.some((t=>e.userId.includes(t)))))}initUsers(){var e;return __awaiter$2(this,void 0,void 0,(function*(){const t=yield this.getTotalUserNumber(),i=Math.ceil(t/BLOUD_PAGE_SIZE);let r=0;const n=[],s=e=>__awaiter$2(this,void 0,void 0,(function*(){e<i&&(yield this.transBloudUsers(e-1))})),o=e=>__awaiter$2(this,void 0,void 0,(function*(){for(const t of e)yield t(),yield sleep(50)}));if(this.localUser.isCommonUser&&(null===(e=this.room)||void 0===e?void 0:e.isBig))this.commonUserList.set(this.localUser.userId,this.localUser),yield this.transBloudUsers(-1,PERMISSION_NOT_COMMON,!0);else{for(;r<i;)n.push(s.bind(null,r)),r+=1;o(n)}}))}handleUnSubCommonUser(){this.commonUserList.forEach((e=>{const t=e.getMainStreamModel();(null==t?void 0:t.hasPulled)&&t.unSubscribeStream()}))}handleCommonUserChange(){let e=new Map;this.room.bmStreamVm.streamModels.forEach((t=>{t.getUser().isCommonUser&&!t.isLocal||e.set(t.userId,t)})),this.room.bmStreamVm.streamModels=e,this.commonUserList.clear()}getUsers(e,t,i="RWPAV"){return __awaiter$2(this,void 0,void 0,(function*(){const{users:r,total:n}=yield this.boomCore.getUsers(e,i,t),s=[];return r.forEach((e=>{const t=this.toBMUser(e);s.push(t)})),{userList:s,total:n}}))}getUsersList(e,t,i="",r=!1){var n,s;return __awaiter$2(this,void 0,void 0,(function*(){const{users:o,total:a,pageIndex:c}=yield this.boomCore.getUsersList(e,i,t,r),u=[];return o.forEach((e=>{const t=this.toBMUser(e);u.push(t)})),r&&(null===(n=this.room)||void 0===n?void 0:n.roomInfo.totalWaitRoomUserWatcher.value)!==a&&(null===(s=this.room)||void 0===s||s.roomInfo.totalWaitRoomUserWatcher.next(a)),{userList:u,total:a,pageIndex:c}}))}getTotalUserNumber(){return __awaiter$2(this,void 0,void 0,(function*(){const{total:e}=yield this.boomCore.getUsers(0,"",1);return e}))}clearUsers(){this.userList.clear(),this.commonUserList.clear(),this.audiencesList.clear(),this.signalList.clear()}searchUsers(e,t){return __awaiter$2(this,void 0,void 0,(function*(){try{const{users:i}=yield this.boomCore.searchUsers(e,t,!1);let r=[],n=[];return i.forEach((e=>{const t=this.userList.get(e.userId);if(t)return void r.push(t);const i=this.commonUserList.get(e.userId);i&&n.push(i)})),{userList:r,commonUserList:n}}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"boomCore.searchUsers发生错误:"+(null==e?void 0:e.message)))}}))}searchWaitRoomUsers(e,t){return __awaiter$2(this,void 0,void 0,(function*(){try{const{users:i}=yield this.boomCore.searchUsers(e,t,!0),r=[];return i.forEach((e=>{const t=this.toBMUser(e);r.push(t)})),r}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"search wait room users error"))}}))}}class BMMessageInfo{constructor(e){this.isMeetingNotice=!1,this.userId=e.userId,this.message=e.message,this.role=e.role,this.isLocal=e.isLocal,this.avatar=e.avatar,this.nickName=e.nickName,this.to=e.to,this.isDanger=e.isDanger,this.seq=e.seq,this.failed=e.failed;let t=!1;e.isMeetingNotice&&(t=!0),this.isMeetingNotice=t,e.sendTime?(this.timeStamp=e.sendTime,this.time=handleTime(this.timeStamp)):(this.timeStamp=(new Date).getTime(),this.time=handleTime(this.timeStamp))}}var BCEvent;!function(e){e.ROOM_CONNECTED="room-connected",e.ROOM_RECONNECTING="room-reconnecting",e.ROOM_RECONNECTED="room-reconnected",e.ROOM_SYNC="room-synced",e.JOINUSER="participant-joined",e.LEAVEUSER="participant-left",e.ROOMERROR="room-error",e.UNPUBLISH="participant-unpublished",e.PUBLISHED="participant-published",e.SENDMESSAGE="new-message",e.CUSTOMMESSAGE="custom-message",e.STREAMERROR="error-media",e.STREAMDISCONNECTED="stream-disconnected",e.EVICTED="participant-evicted",e.UPDATESTATS="update-stats",e.CUSTOMSTATS="update-custom-stats",e.UPDATEUSER="participant-update",e.CHANGEMASTER="change-master",e.USERREJOINED="user-rejoined",e.TOKENWILLEXPIRE="token-will-expire",e.TOKENEXPIRE="token-expire",e.ICECANDIDATE="onIceCandidate",e.STREAMUPDATE="stream-update",e.UPDATE="update",e.ANALYSISDATA="analysis-data",e.ANALYSISERROR="analysis-error",e.STARTANALYSIS="start-analyze",e.STOPANALYSIS="stop-analyze",e.REPORTINFO="info-reported",e.STREAM_ADDED="stream-added",e.STREAM_REMOVED="stream-removed",e.STREAM_UPDATED="stream-updated",e.BLOUD_STREAM_UPDATED="bloud-stream-update",e.MOVE_USER_ROOM="move-user-room",e.STREAM_PUBLISHED="stream-published",e.STREAM_SUBSCRIBED="stream-subscribed",e.MUTE_VIDEO="mute-video",e.UNMUTE_VIDEO="unmute-video",e.MUTE_AUDIO="mute-audio",e.UNMUTE_AUDIO="unmute-audio",e.ERROR="error",e.PEER_JOINED="peer-joined",e.PEER_LEAVED="peer-leaved",e.CLIENT_BANNED="client-banned",e.USER_KICKED="user-kicked",e.TOKEN_WILL_EXPIRE="token-will-expire",e.TOKEN_EXPIRE="token-expire",e.ROOM_CLOSED="room-closed",e.NETWORK_ERROR="network-error",e.BRTC_SYNC_ROOM_COMPLETED="sync-room-completed",e.BRTC_ROOM_ROCONNECTING="brtc-room-reconnecting",e.BRTC_ROOM_RECONNECTED="brtc-room-reconnected",e.JOIN_READY="join-ready",e.BRTC_SHARE_SYNC_ROOM_COMPLETED="brtc-share-sync-room-completed",e.LEAVE_USERS="leaveUsers"}(BCEvent||(BCEvent={}));var BCEvent$1=BCEvent,BoomCoreErrorCode;function isShareStream(e){const t=e.getStreamId();return e.getUserId().endsWith(STREAM_SUFFIX_SCREEN)||t.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()}class BoomError extends Error{constructor(e,t,i){let r;super(),this.boom_error_flag_="__BOOM_ERROR___",this.code=e,r="string"==typeof t?t:JSON.stringify(t),this.message=r,i&&(this.name=i)}toString(){return JSON.stringify({code:this.code,message:this.message})}getCode(){return this.code}getMessage(){return this.message}}!function(e){e[e.BloudLock=28]="BloudLock",e[e.ShareScreenNoPermission=100]="ShareScreenNoPermission",e[e.ShareScreenCanceled=101]="ShareScreenCanceled",e[e.ShareScreenOtherError=102]="ShareScreenOtherError",e[e.ShareScreenContentHintError=103]="ShareScreenContentHintError",e[e.ShareScreenClientJoinedError=104]="ShareScreenClientJoinedError",e[e.BrtcShareSigError=105]="BrtcShareSigError",e[e.ToggleShareScreenError=106]="ToggleShareScreenError",e[e.BrtcCreateStreamError=107]="BrtcCreateStreamError",e[e.BrtcSubscribeError=108]="BrtcSubscribeError",e[e.BrtcPublishError=109]="BrtcPublishError",e[e.BrtcUnsubscribeError=110]="BrtcUnsubscribeError",e[e.BrtcUnPublishError=111]="BrtcUnPublishError",e[e.RepeatJoinError=112]="RepeatJoinError",e[e.ProxiesUrlTypeError=113]="ProxiesUrlTypeError",e[e.getBloudProxiesUrlError=114]="getBloudProxiesUrlError",e[e.JoinUserInfoError=115]="JoinUserInfoError",e[e.JoinTypeError=116]="JoinTypeError",e[e.JoinBrtcError=117]="JoinBrtcError",e[e.JoinBloudError=118]="JoinBloudError",e[e.UpdateCustomStatsError=119]="UpdateCustomStatsError",e[e.CreateBloudError=120]="CreateBloudError"}(BoomCoreErrorCode||(BoomCoreErrorCode={})),new BoomError(BoomCoreErrorCode.ShareScreenNoPermission,"没有打开共享屏幕录制权限","no share permission"),new BoomError(BoomCoreErrorCode.ShareScreenCanceled,"取消共享屏幕","cancel share"),new BoomError(BoomCoreErrorCode.ShareScreenContentHintError,"设置 共享屏幕视频流的 contentHint 失效","set share video contentHint failed"),new BoomError(BoomCoreErrorCode.ShareScreenClientJoinedError,"共享屏幕brtc client入会失败","share client join failed"),new BoomError(BoomCoreErrorCode.BrtcShareSigError,"brtcShareSig为空","brtc share sig is empty");const RepeatJoinError=new BoomError(BoomCoreErrorCode.RepeatJoinError,"正在 join,请勿重复调用","repeat join error");new BoomError(BoomCoreErrorCode.ProxiesUrlTypeError,"proxies url 必须为字符串","get bloud proxies param error"),new BoomError(BoomCoreErrorCode.JoinUserInfoError,"userinfo传递错误,请检查"),new BoomError(BoomCoreErrorCode.JoinTypeError,"type传递错误,请检查");const updateCustomStatsError=e=>new BoomError(BoomCoreErrorCode.UpdateCustomStatsError,e,"bloud updateCustomStats failed");var BoomMeetingErrorCode;!function(e){e[e.BmJoinError=200]="BmJoinError",e[e.BMLeaveError=201]="BMLeaveError",e[e.BmSetRemoteVideoEnable=202]="BmSetRemoteVideoEnable",e[e.BmSetRemoteAudioEnable=203]="BmSetRemoteAudioEnable",e[e.BmSetLocalVideoEnable=204]="BmSetLocalVideoEnable",e[e.BmSetLocalAudioEnable=205]="BmSetLocalAudioEnable",e[e.BmSetLocalSpeakerEnable=206]="BmSetLocalSpeakerEnable",e[e.BmChangeMasterError=207]="BmChangeMasterError",e[e.BmUpdateManagerError=208]="BmUpdateManagerError",e[e.BmEvictUserError=209]="BmEvictUserError",e[e.BmUpdateUserError=210]="BmUpdateUserError",e[e.BmSetAudioOffError=211]="BmSetAudioOffError",e[e.BmSetVideoOffError=212]="BmSetVideoOffError",e[e.BmSetMsgOffError=213]="BmSetMsgOffError",e[e.BmUpdateCustomStatsError=214]="BmUpdateCustomStatsError",e[e.BmChangeVideoProfileError=215]="BmChangeVideoProfileError",e[e.BmChangeAudioProfileError=216]="BmChangeAudioProfileError",e[e.BmCheckDeviceError=217]="BmCheckDeviceError"}(BoomMeetingErrorCode||(BoomMeetingErrorCode={}));const BmLeaveError=e=>new BoomError(BoomMeetingErrorCode.BMLeaveError,e,"boommeeting leave failed"),BmSetRemoteVideoEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetRemoteVideoEnable,e,"开关对端摄像头失败"),BmSetRemoteAudioEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetRemoteAudioEnable,e,"开关对端麦克风发生失败"),BmSetLocalVideoEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalVideoEnable,e,"开关本地摄像头失败"),BmSetLocalAudioEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalAudioEnable,e,"开关本地麦克风失败"),BmSetLocalSpeakerEnable=e=>new BoomError(BoomMeetingErrorCode.BmSetLocalSpeakerEnable,e,"开关扬声器失败"),BmChangeMasterError=e=>new BoomError(BoomMeetingErrorCode.BmChangeMasterError,e,"转移主持人发生错误"),BmUpdateManagerError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateManagerError,e,"改变联席主持人发生错误"),BmEvictUserError=e=>new BoomError(BoomMeetingErrorCode.BmEvictUserError,e,"踢出用户发生错误"),BmUpdateUserError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateUserError,e,"更新用户信息发生错误"),BmSetAudioOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetAudioOffError,e,"全员静音发生错误"),BmSetVideoOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetVideoOffError,e,"全员禁用摄像头发生错误"),BmSetMsgOffError=e=>new BoomError(BoomMeetingErrorCode.BmSetMsgOffError,e,"全员禁用聊天发生错误"),BmUpdateCustomStatsError=e=>new BoomError(BoomMeetingErrorCode.BmUpdateCustomStatsError,e,"更新房间自定义属性状态发生错误"),BmChangeVideoProfileError=e=>new BoomError(BoomMeetingErrorCode.BmChangeVideoProfileError,e,"远程调节对方视频发生错误"),BmChangeAudioProfileError=e=>new BoomError(BoomMeetingErrorCode.BmChangeAudioProfileError,e,"远程调节对方音频发生错误"),BmCheckDeviceError=e=>new BoomError(BoomMeetingErrorCode.BmCheckDeviceError,e,"远程检测对方设备发生错误");var StreamErrorMap;!function(e){e[e.createStream=1302]="createStream",e[e.noCameraDevice=1303]="noCameraDevice",e[e.noMicroDevice=1304]="noMicroDevice",e[e.noSpeakerDevice=1305]="noSpeakerDevice",e[e.openCamera=1301]="openCamera",e[e.cameraNotAuth=1314]="cameraNotAuth",e[e.cameraOccupy=1315]="cameraOccupy",e[e.openMicro=1302]="openMicro",e[e.micNotAuth=1317]="micNotAuth",e[e.micOccupy=1319]="micOccupy",e[e.streamDisconnected=1320]="streamDisconnected",e[e.syncFail=1321]="syncFail",e[e.getStreamFail=1322]="getStreamFail",e[e.streamConnectError=1323]="streamConnectError",e[e.streamReconnectSuccess=1324]="streamReconnectSuccess",e[e.streamReconnectFailed=1325]="streamReconnectFailed",e[e.shareStreamConnectError=1326]="shareStreamConnectError",e[e.shareStreamConnectSuccess=1327]="shareStreamConnectSuccess",e[e.shareStreamConnectFailed=1328]="shareStreamConnectFailed"}(StreamErrorMap||(StreamErrorMap={}));const BMCreateStreamError=e=>new BoomError(StreamErrorMap.createStream,`采集${e}流失败,请重试`),getStreamError=e=>new BoomError(StreamErrorMap.getStreamFail,`当前${e}不可用, 请确保您的${e}连接正确, 或更换其他${e}`),BMOpenCameraError=()=>new BoomError(StreamErrorMap.openCamera,"打开摄像头失败"),BMCameraNotAuthError=()=>new BoomError(StreamErrorMap.cameraNotAuth,"摄像头设备未授权, 无法开启视频, 启动摄像头失败, 请在系统或浏览器“设置-隐私”中允许使用摄像头"),BMCameraOccupyError=()=>new BoomError(StreamErrorMap.cameraOccupy,"当前摄像头被占用, 请检查或切换其他摄像头"),BMOpenMicroError=()=>new BoomError(StreamErrorMap.openMicro,"打开麦克风失败"),BMMicNotAuthError=()=>new BoomError(StreamErrorMap.micNotAuth,"麦克风设备未授权, 无法开启麦克风, 启动麦克风失败, 请在系统或浏览器“设置-隐私”中允许使用麦克风"),BMMicOccupyError=()=>new BoomError(StreamErrorMap.micOccupy,"当前麦克风被占用, 请检查或切换其他麦克风"),BMStreamDisconnectedError=e=>new BoomError(StreamErrorMap.streamDisconnected,`${e}连接已断开,正在重试,请稍后`),BmSyncStreamFailError=()=>new BoomError(StreamErrorMap.syncFail,"状态同步异常,请重试, 麦克风和摄像头已自动关闭"),BMStreamConnectError=()=>new BoomError(StreamErrorMap.streamConnectError,"网络连接异常,正在重试"),BMShareStreamConnectError=()=>new BoomError(StreamErrorMap.shareStreamConnectError,"共享屏幕网络连接异常,正在重试"),BMStreamReconnectSuccess$1=(e,t)=>{let i="";if(e&&t?i="麦克风和摄像头":e?i="麦克风":t&&(i="摄像头"),i)return new BoomError(StreamErrorMap.streamReconnectSuccess,`网络连接成功, ${i}已自动打开`)},BMShareStreamReconnectSuccess=()=>new BoomError(StreamErrorMap.shareStreamConnectSuccess,"共享屏幕网络连接成功, 已自动打开"),BMStreamReconnectFailed=()=>new BoomError(StreamErrorMap.streamReconnectFailed,"网络连接失败,请检查网络,麦克风和摄像头已自动关闭"),BMShareStreamReconnectFailed=()=>new BoomError(StreamErrorMap.streamReconnectFailed,"共享屏幕网络连接失败,请检查网络,共享屏幕已自动关闭");function checkStreamIsNormal(e){var t,i,r,n;if(e&&!e.isLocal){(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(i=e.stream)||void 0===i?void 0:i.getVideoTrack())||e.audioEnable&&!(null===(n=null===(r=e.stream)||void 0===r?void 0:r.isSubscribed)||void 0===n?void 0:n.call(r)))&&setTimeout((()=>{var t,i,r,n;(e.isDisplay&&e.videoEnable&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoOn())&&!(null===(i=e.stream)||void 0===i?void 0:i.getVideoTrack())||e.audioEnable&&!(null===(n=null===(r=e.stream)||void 0===r?void 0:r.isSubscribed)||void 0===n?void 0:n.call(r)))&&(warn$1("用户流检测,但是流订阅出现了问题,需要重新订阅","用户流检测",e.userId,[" nickname => ",e.nickname,"isDisplay =>",e.isDisplay]),e.hasPulled=!1,e.pulledStreamType="small",e.sendMessage2Room())}),2e3)}}function handleBloudReconnectStreamEvent(e){var t,i;const r=e.getLocalStreamModel();if(r&&!(null==r?void 0:r.stream))e.bloudStream&&(info("brtc 已经没有流了,bloud 的流要取消掉"),e.bloudStream.unpublish(),r.updateBloudStream(void 0,e),e.bloudStream=null);else if(r&&r.stream){info("brtc 流已经重推上去了,bloud要重新发推流的逻辑");const t=r.stream.getAudioOn(),i=r.stream.getVideoOn();e.publishBloudStream(t,i).then((()=>{info("brtc stream repub success bloud repub success, notify reconnect success"),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess(t,i))}))}if(e.localIsShare){const r=null===(t=e.room)||void 0===t?void 0:t.boomCore.shareScreenStream;if(r){const t=r.getAudioOn(),n=r.getVideoOn();try{null===(i=e.room)||void 0===i||i.boomCore.createAndPubBloudShareStream(t,n)}catch(e){error$1("bloud 共享屏幕流,断网重连重推流失败")}}}}const handleReconnectedStream=debounce((e=>{if(e.networkState.bloud&&e.networkState.brtc)try{e.streamQueue.restart()}catch(t){e.streamQueue.setQueueProcessor(e.queueProcessor),e.streamQueue.restart()}}),300);function handleStreamPublished(e,t,i,r){const n=e.stream;if(info("本地推流","本地推流",n.getUserId()),n){const e=t.getLocalStreamModel();if(e&&t.updateStreamModel(e,n),r[BCEvent$1.STREAM_PUBLISHED].next({published:!0,model:e}),1===i.conferenceMode){i.getLocalParticipant().isAudience&&t.getStreamModels().forEach((e=>{e.sendMessage2Room()}))}}else r[BCEvent$1.STREAM_PUBLISHED].next({published:!1})}function handleBloudStreamPublished(e,t,i){info("bloud publish stream","","",[e]),handleBloudStreamPubAUpdate(e,t,!0),i[BCEvent$1.PUBLISHED].next(e)}function handleBloudStreamPubAUpdate(e,t,i=!1){var r;info("bloud stream update","","",[JSON.stringify(e)]);const n=e.userId,s=e.isScreen,o=t.streamModels.get(n);if(o)if(s){const e={id:n,isWeb:o.isWeb,isScreen:s};null===(r=t.room)||void 0===r||r.addUser2Queue(e)}else o.updateBloudStream(e,t,i),o.getUser().updateSortNum()}function handleBloudStreamUnPublished(e,t,i){info("bloud unpublish stream","","",[e]),handleBloudStreamUnpublish(e,t),i[BCEvent$1.UNPUBLISH].next(e)}function handleBloudStreamUnpublish(e,t){var i,r,n;const s=e.userId;if(e.isScreen){const e=t.shareStreamModels.get(s);if(e){const i=e.stream;i?(t.remoteStreamUnpublished(i),i.destroy()):t.removeShareStreamModelByUId(s);const r={id:s,isWeb:e.isWeb,isScreen:!0};null===(n=t.room)||void 0===n||n.streamQueue.removeUsers([r])}}else{const e=t.streamModels.get(s);if(e){e.updateBloudStream(void 0,t);const n=e.stream;n&&(null===(i=t.room.audioPlayer)||void 0===i||i.removeStream(n),t.remoteStreamUnpublished(n),n.destroy());const o={id:s,isWeb:e.isWeb,isScreen:!1};null===(r=t.room)||void 0===r||r.streamQueue.removeUsers([o])}}}function handleShareStreamFailed(e,t){setTimeout((()=>__awaiter$2(this,void 0,void 0,(function*(){info("handle republish share stream");try{const i=e.boomCore.shareScreenStream;if(i){const r=i.getAudioOn(),n=i.getVideoOn();yield e.boomCore.shareBrtcClient.publish(i),yield e.boomCore.createAndPubBloudShareStream(r,n),info("handle republish share stream success"),t.localShareError.next(BMShareStreamReconnectSuccess())}}catch(e){error$1("handle republish share stream failed , now unpublish"),t.localShareError.next(BMShareStreamReconnectFailed()),yield t.toggleShareScreen(!1,void 0)}}))),1e3)}function handleRoomConnected(e,t,i,r,n=!0){var s;return __awaiter$2(this,void 0,void 0,(function*(){info("room-connected",t.getLocalParticipant().userId,"room-connected",["roomId =>",t.roomInfo.roomID," local permission => ",e.permission]);const o=e.permission,a=e.total;o&&i.updateLocalUserPermission(o),t.isInWaitRoom=e.joinwait;const c=e.waitroom;t.roomInfo.isOpenWaitRoom.next(c),t.forceId=null===(s=e.customStats.forceOn)||void 0===s?void 0:s.user,yield handleInitRoomInfo(e,t),t.roomInfo.totalUserWatcher.next(a),n&&r[BCEvent$1.ROOM_CONNECTED].next(e)}))}function handleInitJoinRoomUsers(e){return __awaiter$2(this,void 0,void 0,(function*(){info("join ready init users"),e.isInWaitRoom||(e.forceId&&(yield e.getForceUser(e.forceId)),yield e.userVM.initUsers())}))}function handleRoomUpdated(e,t){info("update-stats "," ","",["options => ",JSON.stringify(e.options)]),e.options&&"audiooff"==e.options[0]||"selfopenaudio"==e.options[1]?t.roomInfo.setAudioOff(e.room.audiooff,e.room.selfopenaudio):e.options&&"lock"==e.options[0]?t.roomInfo.setlock(e.room.lock):e.options&&"waitroom"==e.options[0]&&t.roomInfo.isOpenWaitRoom.next(e.stats.waitroom)}function handleInitRoomInfo(e,t){return __awaiter$2(this,void 0,void 0,(function*(){t.roomInfo.msgSeq=e.msgSeq,e.customStats&&t.roomInfo.initCustomStats(e.customStats)}))}function exitUserUpdateStream(e,t,i,r,n){var s;e.updateUser(t,i);const o=i.stream,a=r.streamModels.get(t.userId);if(a||error$1("bmUserVM中存在该用户,但是bmStreamModelVM中不存在该用户,佛了"),!o.size){(null==a?void 0:a.bloudStream)&&(a.updateBloudStream(void 0,r),n.streamQueue.removeUsers([{id:t.userId,isScreen:!1},{id:t.userId,isScreen:!0}]));const e=r.shareStreamModels.get(t.userId);e&&!e.isLocal&&(null===(s=e.stream)||void 0===s||s.destroy(),r.removeShareStreamModel(e))}o.get(`${t.userId}_screen`)&&n.addUser2Queue({id:t.userId,isScreen:!0,isWeb:t.isWeb});const c=o.get(t.userId);c&&(null==a||a.updateBloudStream({audio:c.audio_enable,video:c.video_enable,isScreen:!1},r))}function addUsers(e,t,i,r){e.isSingleColumns?t.commonUserList.forEach((n=>{const s=i.get(n.userId);if(s)return i.delete(n.userId),void exitUserUpdateStream(t,n,s,r,e);t.commonUserList.delete(n.userId),r.streamModels.delete(n.userId),r.shareStreamModels.delete(n.userId)})):t.userList.forEach((n=>{const s=i.get(n.userId);if(s)return exitUserUpdateStream(t,n,s,r,e),void(n.isCommonUser?t.userList.delete(n.userId):i.delete(n.userId));t.userList.delete(n.userId),r.streamModels.delete(n.userId),r.shareStreamModels.delete(n.userId)})),e.userVM.addBcUsersMap(i)}function handleRoomSync(e,t,i,r){return __awaiter$2(this,void 0,void 0,(function*(){const n=t.getLocalParticipant().userId,{users:s}=yield t.boomCore.queryUsers([n]),o=s.get(n);o&&i.updateUser(i.localUser,o);const a=t.getLocalParticipant().isCommonUser;if(t.isBig&&a){const{users:e}=yield t.boomCore.getUsersList(0,PERMISSION_NOT_COMMON,500);addUsers(t,i,e,r)}else{const e=(yield t.userVM.getTotalUserNumber())/BLOUD_PAGE_SIZE;let n=new Map;for(let i=0;i<e;i++){let{users:e}=yield t.boomCore.getUsers(i-1,"",BLOUD_PAGE_SIZE);e.forEach((e=>{n.set(e.userId,e)}))}addUsers(t,i,n,r)}yield handleInitRoomInfo(e,t),t.userVM.updateAllSort(),t.bmStreamVm.updateModelSort()}))}function handleBrtcRoomReconnecting(e,t,i){info("brtc room reconnecting"),t.networkState.brtc=!1,t.streamWSReconnectWatcher.next(!1),i[BCEvent$1.BRTC_ROOM_ROCONNECTING].next(e)}function handleBrtcRoomReconnected(e,t,i){info("brtc room reconnected"),t.networkState.brtc=!0,handleReconnectedStream(t),i[BCEvent$1.BRTC_ROOM_RECONNECTED].next(e)}function handleBloudRoomReconnecting(e,t,i){info("bloud room reconnecting"),t.networkState.bloud=!1,t.bloudWSReconnectWatcher.next(!1),i[BCEvent$1.ROOM_RECONNECTING].next(e)}function handleBloudRoomReconnected(e,t,i){return __awaiter$2(this,void 0,void 0,(function*(){t.hasSyncPermission?(info("bloud room reconnected"),t.bloudWSReconnectWatcher.next(!1),i[BCEvent$1.MOVE_USER_ROOM].next(null),yield t.syncRoom().then((()=>{t.hasSyncPermission=!0,i[BCEvent$1.ROOM_RECONNECTED].next(e)})).catch((e=>{error$1("sync room error",JSON.stringify(e));if(43===e.code)return t.hasSyncPermission=!1,void i[BCEvent$1.USERREJOINED].next(e);t.hasSyncPermission=!1,i[BCEvent$1.NETWORK_ERROR].next(e)}))):i[BCEvent$1.NETWORK_ERROR].next(e)}))}function handleBloudRoomSync(e,t,i,r,n){return __awaiter$2(this,void 0,void 0,(function*(){info("bloud sync room completed"),yield handleRoomSync(e,i,t,r),handleBloudReconnectStreamEvent(r),i.networkState.bloud=!0,handleReconnectedStream(i),i.bloudWSReconnectWatcher.next(!0),n[BCEvent$1.ROOM_SYNC].next(e)}))}function handleParticipantJoin(e,t,i,r,n,s){var o,a,c,u,d,l,h,m,p,f,v,g,_;const y=null===(a=null===(o=null==e?void 0:e.participant)||void 0===o?void 0:o.params)||void 0===a?void 0:a.info.sync,S=e.mode;info("用户入会","用户入会",e.user.userId,["sync => ",y,"mode =>",S]);const E=t.room.isBig&&i.streamModels.size>1e3;let b=!1;if(y){let i=t.userList.get(e.user.userId);if(i||(i=t.commonUserList.get(e.user.userId)),i)return void(i.inBackground!=!!(null===(u=null===(c=e.user)||void 0===c?void 0:c.customInfo)||void 0===u?void 0:u.inBackground)&&(i.inBackground=!!(null===(l=null===(d=e.user)||void 0===d?void 0:d.customInfo)||void 0===l?void 0:l.inBackground),i.watcher.next({operation:"inBackground",user:i})))}1===S&&(null===(h=t.room)||void 0===h?void 0:h.isBig)&&(t.commonUserList.delete(e.user.userId),i.streamModels.delete(e.user.userId));if(getIsCommonUser(e.user.permission.permission)){t.userList.get(e.user.userId)&&(t.userList.delete(e.user.userId),i.streamModels.delete(e.user.userId),b=!0)}else{const r=t.commonUserList.get(e.user.userId);(null===(m=t.room)||void 0===m?void 0:m.isSingleColumns)||r&&(t.commonUserList.delete(e.user.userId),i.streamModels.delete(e.user.userId),b=!0)}let T=t.addBCUser(e.user);if(T){T.inBackground!=!!(null===(f=null===(p=e.user)||void 0===p?void 0:p.customInfo)||void 0===f?void 0:f.inBackground)&&(T.inBackground=!!(null===(g=null===(v=e.user)||void 0===v?void 0:v.customInfo)||void 0===g?void 0:g.inBackground),T.watcher.next({operation:"inBackground",user:T}));let o=!1;if(ignoreUserId.forEach((e=>{(null==T?void 0:T.userId.includes(e))&&(o=!0)})),b?t.updateAllSort():(null===(_=t.room)||void 0===_?void 0:_.isSingleColumns)?t.updateCommonUserSort():T?T.isCommonUser?E?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),i.updateModelSort(),!o){if(1!==e.mode){const e=new BMMessageInfo({isMeetingNotice:!0,userId:T.userId,message:T.nickName+"加入"+(2==r.roomType?"直播":"会议")});n.addMessage(e,!0)}s[BCEvent$1.JOINUSER].next({user:T,mode:S,data:e})}}}function handleLeaveUsers(e,t,i,r,n,s,o){var a;const c=e.userIds;info("bloud leave users","","",["userIds =>",c]),c.length&&(c.forEach((e=>{const a=leaveUser(e,t,i,n);a&&sendLeveNotification(a,s,o,r,!0,0)})),(null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():t.updateAllSort(),n.updateModelSort())}function handleParticipantLeft(e,t,i,r,n,s,o){var a;info(`bloud participant left ===>${e.userId}, ${e.mode}`);const c=1===e.mode,u=e.userId,d=i.isBig&&n.streamModels.size>1e3;if(u){const l=leaveUser(u,t,i,n);if((null===(a=t.room)||void 0===a?void 0:a.isSingleColumns)?t.updateCommonUserSort():l?l.isCommonUser?d?t.updateDelayCommonUserSort():t.updateCommonUserSort():t.updateUserSort():t.updateAllSort(),n.updateModelSort(),c)return void r[BCEvent$1.LEAVEUSER].next({user:l,mode:e.mode,data:e});l&&sendLeveNotification(l,s,o,r,1!==e.mode,e.mode)}else warn$1("participant-left触发=======>但是该用户信息不存在",LOGGER_TAG_CLIENT,null,[e.userId]),r[BCEvent$1.LEAVEUSER].next({user:e.userId,mode:e.mode,data:e})}function sendLeveNotification(e,t,i,r,n,s){let o=!1;if(ignoreUserId.forEach((t=>{(null==e?void 0:e.userId.includes(t))&&(o=!0)})),!o){if(n){const r=new BMMessageInfo({isMeetingNotice:!0,userId:e.userId,message:(null==e?void 0:e.nickName)+"离开"+(2==t.roomType?"直播":"会议")});i.addMessage(r,!0)}r[BCEvent$1.LEAVEUSER].next({user:e,mode:s})}}function leaveUser(e,t,i,r){const n=t.getUser(e);return t.removeUser(e),i.streamQueue.removeUsers([{id:e,isScreen:!1},{id:e,isScreen:!0}]),r.removeStreamModelByUId(e),r.removeShareStreamModelByUId(e),i.roomInfo.removeRaiseHandUser(e),i.roomInfo.removeVideoRaiseHandUser(e),i.roomInfo.removeSimpleRaiseHandUser(e),n}function handleChangeMaster(e,t,i,r,n){info("changeMaster =>","changeMaster","",["master: => ",e.master,"oldMaster =>",e.oldMaster]);const s=e.master,o=e.oldMaster,a=e.isKeep;if(s){let c=t.updateMaster(s,o,a);c.master&&(c.master.watcher.next({operation:"getMaster",user:c.master}),i.userVM.masterUserWatcher.next(c.master)),c.oldMaster&&(c.oldMaster.watcher.next({operation:"removeMaster",user:c.oldMaster}),a&&c.oldMaster.watcher.next({operation:"getManager",user:c.oldMaster}));const u=n.getStreamModelByUId(o),d=n.getStreamModelByUId(s);null==u||u.updateSortNum(),null==d||d.updateSortNum(),r[BCEvent$1.CHANGEMASTER].next({master:c.master,oldMaster:c.oldMaster,data:e})}else warn$1("change-master触发=======>但是房间内找不到master",LOGGER_TAG_CLIENT,null,s),r[BCEvent$1.CHANGEMASTER].next(null)}function handleEvict(e,t,i,r,n){const s=t.getUser(e.userId);if(info("踢出用户 => ","evict ",null==s?void 0:s.userId,["nickname => ",null==s?void 0:s.nickName]),null==s?void 0:s.isToupingma){const e=i.getShareStreamModelByUId(s.userId);e&&i.removeShareStreamModel(e)}else r.bmStreamVm.removeStreamModelByUId(e.userId);r.userVM.removeUser(e.userId),r.userVM.updateAllSort(),i.updateModelSort(),t.audiencesListWatcher.next(Array.from(t.audiencesList.values())),t.signalListWatcher.next(Array.from(t.signalList.values())),n[BCEvent$1.EVICTED].next(e)}function handleUpdateUser(e,t,i,r,n){var s,o;if(info("用户信息被改变","",null===(s=e.user)||void 0===s?void 0:s.userId),null===(o=e.user)||void 0===o?void 0:o.userId){let s=t.getUser(e.user.userId),o=r.getStreamModelByUId(e.user.userId);s?s.updateUserInfo(e.user,e.participant,i):console.warn("participant-update: bmUser is null"),o&&o.updateSortNum(!0),n[BCEvent$1.UPDATEUSER].next({bmUser:s,params:e.participant.params})}}const handleUserRejoined=debounce(((e,t,i)=>{e[t.USERREJOINED].next(i)}),1e3);function handleMoveUserRoom(e,t,i,r){return __awaiter$2(this,void 0,void 0,(function*(){info("bloud move user room","","",[i]);const n=i.toWait;if(e.isInWaitRoom=n,n){e.handleResetOtherStreamStatus(),t.userList.clear(),t.userListWatcher.next([]),t.commonUserList.clear(),t.commonUserListWatcher.next([]),e.bmStreamVm.streamModels.clear(),e.messageWatcher.next({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1});const i=e.bmStreamVm.localModel;i&&e.bmStreamVm.streamModels.set(i.userId,i),e.bmStreamVm.streamModelsWatcher.next([]),e.bmStreamVm.shareStreamModels.clear(),e.bmStreamVm.shareStreamModelsWatcher.next([]),e.roomInfo.raiseHandsWatcher.next([]),e.roomInfo.raiseVideoHandsWatcher.next([]),e.roomInfo.raiseSimpleHandsWatcher.next([])}else{yield handleRoomConnected(i.info,e,t,r,!1);const{audioOff:n,selfopenaudio:s,lock:o}=i.info;o!==e.roomInfo.lock&&e.roomInfo.setlock(o),n===e.roomInfo.audioOff&&s===e.roomInfo.selfopenaudio||e.roomInfo.setAudioOff(n,s),yield handleInitJoinRoomUsers(e)}r[BCEvent$1.MOVE_USER_ROOM].next(n)}))}function handleSendMessage(e,t,i,r){var n,s,o,a,c,u,d,l,h;let m=Object.assign({},e);if(m.message){if(m.message="string"==typeof m.message?JSON.parse(m.message):m.message,info("new-message","","",[" method => ",m.message.method]),"send-talk"===m.message.method){const r=m.user===(null===(n=t.getLocalUser())||void 0===n?void 0:n.userId),p=(null===(o=null===(s=m.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.status)||"",f=null===(u=null===(c=null===(a=m.message)||void 0===a?void 0:a.params)||void 0===c?void 0:c.stream)||void 0===u?void 0:u.avatar,v=e.seq,g=new BMMessageInfo({userId:m.user,message:p,isLocal:r,avatar:f,to:m.to,seq:v,nickName:null===(h=null===(l=null===(d=m.message)||void 0===d?void 0:d.params)||void 0===l?void 0:l.stream)||void 0===h?void 0:h.nickname,sendTime:(new Date).getTime()});i.addMessage(g,!1)}r[BCEvent$1.SENDMESSAGE].next(m)}}function handleCustomMessage(e,t,i){var r,n,s,o,a,c,u,d,l,h,m,p,f;let v=Object.assign({},e);if(v.message)if(v.message="string"==typeof v.message?JSON.parse(v.message):v.message,info("custom-message","","",[" method => ",v.message.method]),"video-force-change"==v.message.method){const e="enabled"==v.message.params.status;info(`远端控制本地摄像头: ${e}`),t.messageWatcher.next({type:MessageType.VIDEO_FORCE_CHANGE,status:e,fromUserId:v.user})}else if("audio-force-change"==v.message.method){let e;e="checkUserAudio"==v.message.params.status?v.message.params.status:"enabled"==v.message.params.status,info(`远端控制本地麦克风: ${e}`),t.messageWatcher.next({type:MessageType.AUDIO_FORCE_CHANGE,status:e,fromUserId:v.user,isNotCancelRootReport:null===(r=v.message.params)||void 0===r?void 0:r.isNotCancelRootReport})}else if("raise-hands"===v.message.method)t.raiseHandleRespWatcher.next(v.message.params);else if("give-like"===v.message.method)null===(n=t.roomVM)||void 0===n||n.giveLikeList.push({userId:v.user,nickName:null===(a=null===(o=null===(s=v.message)||void 0===s?void 0:s.params)||void 0===o?void 0:o.stream)||void 0===a?void 0:a.nickname,time:(new Date).getTime(),type:null===(d=null===(u=null===(c=v.message)||void 0===c?void 0:c.params)||void 0===u?void 0:u.stream)||void 0===d?void 0:d.type}),null===(l=t.roomVM)||void 0===l||l.giveLikeListWatcher.next(null===(h=t.roomVM)||void 0===h?void 0:h.giveLikeList);else if("resp-to-check-devices"===v.message.method)(null===(m=v.message)||void 0===m?void 0:m.params)&&(v.message.params.fromUserId=v.user),i[BCEvent$1.CUSTOMMESSAGE].next(v);else if("usercount"===v.message.method){if(v.message.params){let e=null===(f=null===(p=v.message)||void 0===p?void 0:p.params)||void 0===f?void 0:f.total;e?(e=Number(e),e<0&&(warn$1("服务返回的usercount为负数,"+e),e=0)):(warn$1("服务未返回usercount,"+e),e=0),t.roomInfo.totalUserWatcher.next(e)}}else if("waitusercount"===v.message.method){if(v.message.params){const e=v.message.params.total;t.roomInfo.totalWaitRoomUserWatcher.next(e)}}else i[BCEvent$1.CUSTOMMESSAGE].next(v)}let reconnectFailed=0,shareReconnectFailed=0;const NETWORK_ERROR_QUEUE=new Set;function handleBRTCRoomError(e,t,i,r,n){return __awaiter$2(this,void 0,void 0,(function*(){error$1("brtc error","brtc error","",[(new Date).toLocaleTimeString(),JSON.stringify(e),e.getCode()]);if(4002===e.getCode()){t.BRTCConnectFailed=!0,t.networkState.brtc=!1,warn$1("brtc 信令通道错误,需要重新走入会","brtc error",""),t.streamWSReconnectWatcher.next(!1);try{yield i.brtcClient.leave("room_close")}catch(e){error$1("brtc 离会失败")}setTimeout((()=>__awaiter$2(this,void 0,void 0,(function*(){t.handleResetOtherStreamStatus(),yield reconnectBrtcWS(i,t,n,e).catch((t=>{info("brtc断网重连失败, 处理一下退会逻辑","","",[JSON.stringify(t)]),n[BCEvent$1.ERROR].next(e)}))}))),1e3)}else n[BCEvent$1.ERROR].next(e)}))}function reconnectBrtcWS(e,t,i,r){return __awaiter$2(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{setTimeout((()=>{info("brtc重连"),e.brtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>__awaiter$2(this,void 0,void 0,(function*(){info("brtc断网重连成功, 重新处理拉流和推流"),t.networkState.brtc=!0,setTimeout((()=>{t.brtcNetEnableWatcher.next(!0)}),2e3),handleReconnectedStream(t),t.BRTCConnectFailed=!1,reconnectFailed=0,yield t.handleRePushSelf(),t.streamWSReconnectWatcher.next(!0),n(!0)})))).catch((n=>{const o=n.getCode();info("断网重连入会失败","","",[n,o]),reconnectFailed<=10?(reconnectFailed+=1,e.brtcClient.isJoinning=!1,setTimeout((()=>{reconnectBrtcWS(e,t,i,r)}),2e3)):(error$1("brtc断网重连失败,处理一下退会"),reconnectFailed=0,i[BCEvent$1.ERROR].next(r),s(!1))}))}),7e3)}))}))}function reconnectBRTCShareWS(e){return __awaiter$2(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{setTimeout((()=>{info("共享屏幕重连"),e.shareBrtcClient.join(e.roomId,e.userId,e.brtcSig).then((()=>{shareReconnectFailed=0,t(!0)})).catch((t=>{const i=t.getCode();if(info("共享屏幕断网重连入会失败","","",[t,i]),!(shareReconnectFailed<=3))throw error$1("共享屏幕用户重连失败,处理一下取消共享屏幕"),shareReconnectFailed=0,new Error("共享屏幕重连失败");shareReconnectFailed+=1,reconnectBRTCShareWS(e)}))}),7e3)}))}))}function handleBloudError(e,t,i,r,n){return __awaiter$2(this,void 0,void 0,(function*(){error$1("network-error","network-error","local-client",["本地链接出现问题","netconnectiong => ",e.netConnecting]),e.netConnecting?yield handleBloudRoomReconnected(r,e,n):n[BCEvent$1.NETWORK_ERROR].next(r)}))}function handleCustomStats(e,t,i){let r=null==e?void 0:e.updateKeys;info("update-custom-stats"," "," ",["updateKeys => ",JSON.stringify(r)]),((null==r?void 0:r.includes("chatNotice"))||(null==r?void 0:r.includes("chatNoticeRich"))||(null==r?void 0:r.includes("fileUpdateLook"))||(null==r?void 0:r.includes("fileUpdateDown"))||(null==r?void 0:r.includes("fileUpdateEdit"))||(null==r?void 0:r.includes("fileUpdateModel"))||(null==r?void 0:r.includes("screenShareModel"))||(null==r?void 0:r.includes("onlyOnePersonShare"))||(null==r?void 0:r.includes("chatEnable"))||(null==r?void 0:r.includes("giveLikeEnable"))||(null==r?void 0:r.includes("cloudRecord"))||(null==r?void 0:r.includes("joinAudioEnable"))||(null==r?void 0:r.includes("joinVideoEnable"))||(null==r?void 0:r.includes("userListEnable"))||(null==r?void 0:r.includes("audioEnable"))||(null==r?void 0:r.includes("videoEnable"))||(null==r?void 0:r.includes("modifyNameEnable"))||(null==r?void 0:r.includes("backgroundAIEnable"))||(null==r?void 0:r.includes("recordEnable"))||(null==r?void 0:r.includes("joinMicrophoneDisable"))||(null==r?void 0:r.includes("joinCameraDisable"))||(null==r?void 0:r.includes("raiseHandEnable"))||(null==r?void 0:r.includes("forceOpenUserMic"))||(null==r?void 0:r.includes("forceOpenUserCamera"))||(null==r?void 0:r.includes("joinCueVoice")))&&t.roomInfo.updateOperationPermission(e.customStats),((null==r?void 0:r.includes("chatNotice"))||(null==r?void 0:r.includes("chatNoticeRich")))&&t.roomInfo.chatNoticeWatcher.next(e),i[BCEvent$1.CUSTOMSTATS].next(e)}var dist={},eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,r,s,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new n(r,s||e,o),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,r,n=[];if(0===this._eventsCount)return n;for(r in e=this._events)t.call(e,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,o=new Array(s);n<s;n++)o[n]=r[n].fn;return o},a.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,n,s,o){var a=i?i+e:e;if(!this._events[a])return!1;var c,u,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,n),!0;case 5:return d.fn.call(d.context,t,r,n,s),!0;case 6:return d.fn.call(d.context,t,r,n,s,o),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var h,m=d.length;for(u=0;u<m;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,r);break;case 4:d[u].fn.call(d[u].context,t,r,n);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,r,n){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||n&&!a.once||r&&a.context!==r||o(this,s);else{for(var c=0,u=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[s]=1===u.length?u[0]:u:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(eventemitter3);var pTimeout$1={exports:{}},pFinally$1=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))));const pFinally=pFinally$1;class TimeoutError extends Error{constructor(e){super(e),this.name="TimeoutError"}}const pTimeout=(e,t,i)=>new Promise(((r,n)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void r(e);const s=setTimeout((()=>{if("function"==typeof i){try{r(i())}catch(e){n(e)}return}const s=i instanceof Error?i:new TimeoutError("string"==typeof i?i:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),n(s)}),t);pFinally(e.then(r,n),(()=>{clearTimeout(s)}))}));pTimeout$1.exports=pTimeout,pTimeout$1.exports.default=pTimeout,pTimeout$1.exports.TimeoutError=TimeoutError;var priorityQueue={},lowerBound$1={};function lowerBound(e,t,i){let r=0,n=e.length;for(;n>0;){const s=n/2|0;let o=r+s;i(e[o],t)<=0?(r=++o,n-=s+1):n=s}return r}Object.defineProperty(lowerBound$1,"__esModule",{value:!0}),lowerBound$1.default=lowerBound,Object.defineProperty(priorityQueue,"__esModule",{value:!0});const lower_bound_1=lowerBound$1;class PriorityQueue{constructor(){Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]})}enqueue(e,t){const i={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(i);const r=lower_bound_1.default(this._queue,i,((e,t)=>t.priority-e.priority));this._queue.splice(r,0,i)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}priorityQueue.default=PriorityQueue,Object.defineProperty(dist,"__esModule",{value:!0});const EventEmitter=eventemitter3.exports,p_timeout_1=pTimeout$1.exports,priority_queue_1=priorityQueue,empty=()=>{},timeoutError=new p_timeout_1.TimeoutError;class PQueue extends EventEmitter{constructor(e){var t,i,r,n;if(super(),Object.defineProperty(this,"_carryoverConcurrencyCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isIntervalIgnored",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalCap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_intervalEnd",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_intervalId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queueClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_concurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isPaused",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_resolveEmpty",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_resolveIdle",{enumerable:!0,configurable:!0,writable:!0,value:empty}),Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_throwOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:priority_queue_1.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(i=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==i?i:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(n=null===(r=e.interval)||void 0===r?void 0:r.toString())&&void 0!==n?n:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother()}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=empty,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=empty)}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={},i=null){return new Promise(((r,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const s=void 0===this._timeout&&void 0===t.timeout?e():p_timeout_1.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(timeoutError),i&&i("resolve-timeout")}));i&&i("resolving"),r(await s),this._isPaused?i&&i("resolve-paused"):i&&i("resolve")}catch(e){this._isPaused?i&&i("resolve-paused"):i&&i("resolve"),n(e)}this._next()}),t),this._tryToStartAnother()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}var _default=dist.default=PQueue;class Pqueue{constructor(e,t=!0){this.queue=new _default({concurrency:e,autoStart:t,carryoverConcurrencyCount:!0,timeout:3e3,completeAction:e=>{console.log("task complete",e)}}),this.queueArray=[],this.isTaskPending=t}addQueue(e,t,i=0,r=""){this.queue.isPaused&&this.queue.start();let n={};n.taskID=t,n.status="pending",this.queue.add(e,{priority:i,timeout:3e3},(e=>{if(n.status=e,"resolve"===n.status||"resolve-paused"===n.status||"resolve-timeout"===n.status){const e=this.queueArray.findIndex((e=>n.taskID===e.taskID));-1!==e&&this.queueArray.splice(e,1)}})),this.queueArray.push(n)}clearQueue(){this.queue.clear(),this.queueArray=[],this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{console.log("clearQueue全部完事")}))}startQueue(){this.queue.start()}pauseQueue(){return this.queue.pause(),console.log(`size:${this.size()}`),this.isTaskPending=!1,this.queue.onEmpty().then((e=>{})),this.queue.onIdle().then((e=>{})),this.queueArray}size(){return this.queue.size}pending(){return this.queue.pending}checkTaskStatus(){return this.isTaskPending}setTaskStatus(e){this.isTaskPending=e}onIdle(){return this.queue.onIdle()}onEmpty(){return this.queue.onEmpty()}}const streamPullQueue=new Pqueue(4),eventQueue=new Pqueue(10);var MessageType;function attachEvents(e,t,i,r,n){info("attachEvents init");let s={};return e.on("toggle-screen-share",(()=>{error$1("share stream video track ended, now unpublish share stream"),i.localShareError.next(BMShareStreamReconnectFailed()),i.toggleShareScreen(!1,void 0).then((()=>{}))})),e.on("client-banned",(()=>__awaiter$2(this,void 0,void 0,(function*(){yield n.boomCore.leaveShare()})))),e.on("share-brtc-error",(t=>__awaiter$2(this,void 0,void 0,(function*(){if(4002===t.getCode())try{info("brtc share client disconnected, reconnecting"),yield e.shareBrtcClient.leave("room_close"),reconnectBRTCShareWS(e).then((()=>__awaiter$2(this,void 0,void 0,(function*(){info("brtc share client reconnected, retry repub share stream"),yield sleep(1e3);const t=e.shareScreenStream.getAudioOn(),i=e.shareScreenStream.getVideoOn();e.shareBrtcClient.publish(e.shareScreenStream),e.createAndPubBloudShareStream(t,i)})))).catch((e=>{throw new Error("共享屏幕重新入会失败")}))}catch(e){i.toggleShareScreen(!1,void 0).then((()=>{})).catch((e=>{error$1("共享发生错误退会失败","","",[JSON.stringify(e)])}))}})))),Object.values(BCEvent).forEach((e=>{s[e]=new BehaviorSubject(null)})),Object.values(BCEvent).forEach((o=>{switch(o){case BCEvent.STREAM_PUBLISHED:e.on(BCEvent.STREAM_PUBLISHED,(e=>{eventQueue.addQueue(handleStreamPublished.bind(null,e,i,n,s),BCEvent.STREAM_PUBLISHED)}));break;case BCEvent.BRTC_SYNC_ROOM_COMPLETED:e.on(BCEvent.BRTC_SYNC_ROOM_COMPLETED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(n.handleResetOtherStreamStatus.bind(n),BCEvent.BRTC_SYNC_ROOM_COMPLETED)}))));break;case BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED:e.on(BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED,(()=>{info("brtc share client sync completed, retry publish share stream"),eventQueue.addQueue(handleShareStreamFailed.bind(null,n,i),BCEvent.BRTC_SHARE_SYNC_ROOM_COMPLETED)}));break;case BCEvent.BRTC_ROOM_ROCONNECTING:e.on(BCEvent.BRTC_ROOM_ROCONNECTING,(e=>{eventQueue.addQueue(handleBrtcRoomReconnecting.bind(null,e,n,s),BCEvent.BRTC_ROOM_ROCONNECTING)}));break;case BCEvent.BRTC_ROOM_RECONNECTED:e.on(BCEvent.BRTC_ROOM_RECONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBrtcRoomReconnected.bind(null,e,n,s),BCEvent.BRTC_ROOM_RECONNECTED)}))));break;case BCEvent.CLIENT_BANNED:e.on(BCEvent.CLIENT_BANNED,(e=>{info("brtc client banned"),handleUserRejoined(s,BCEvent,e)}));break;case BCEvent.ERROR:e.on(BCEvent.ERROR,(t=>__awaiter$2(this,void 0,void 0,(function*(){n.netConnecting?eventQueue.addQueue(handleBRTCRoomError.bind(null,t,n,e,i,s),BCEvent.ERROR):NETWORK_ERROR_QUEUE.add(handleBRTCRoomError.bind(null,t,n,e,i,s))}))));break;case BCEvent.ROOM_CONNECTED:e.on(BCEvent.ROOM_CONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){return handleRoomConnected(e,n,t,s)}))));break;case BCEvent.JOIN_READY:e.on(BCEvent.JOIN_READY,(()=>handleInitJoinRoomUsers(n)));break;case BCEvent.JOINUSER:e.on(BCEvent.JOINUSER,(o=>__awaiter$2(this,void 0,void 0,(function*(){n.isInWaitRoom||eventQueue.addQueue(handleParticipantJoin.bind(null,o,t,i,e,r,s),BCEvent.JOINUSER)}))));break;case BCEvent.LEAVEUSER:e.on(BCEvent.LEAVEUSER,(o=>{n.isInWaitRoom||eventQueue.addQueue(handleParticipantLeft.bind(null,o,t,n,s,i,e,r),BCEvent.LEAVEUSER)}));break;case BCEvent.LEAVE_USERS:e.on(BCEvent.LEAVE_USERS,(o=>eventQueue.addQueue(handleLeaveUsers.bind(null,o,t,n,s,i,e,r),BCEvent.LEAVE_USERS)));break;case BCEvent.CHANGEMASTER:e.on(BCEvent.CHANGEMASTER,(e=>{eventQueue.addQueue(handleChangeMaster.bind(null,e,t,n,s,i),BCEvent.CHANGEMASTER)}));break;case BCEvent.SENDMESSAGE:e.on(BCEvent.SENDMESSAGE,(e=>{eventQueue.addQueue(handleSendMessage.bind(null,e,t,r,s),BCEvent.SENDMESSAGE)}));break;case BCEvent.CUSTOMMESSAGE:e.on(BCEvent.CUSTOMMESSAGE,(e=>{eventQueue.addQueue(handleCustomMessage.bind(null,e,n,s),BCEvent.CUSTOMMESSAGE)}));break;case BCEvent.EVICTED:e.on(BCEvent.EVICTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleEvict.bind(null,e,t,i,n,s),BCEvent.EVICTED)}))));break;case BCEvent.UPDATEUSER:e.on(BCEvent.UPDATEUSER,(e=>{eventQueue.addQueue(handleUpdateUser.bind(null,e,t,n,i,s),BCEvent.UPDATEUSER)}));break;case BCEvent.UPDATESTATS:e.on(BCEvent.UPDATESTATS,(e=>{eventQueue.addQueue(handleRoomUpdated.bind(null,e,n),BCEvent.UPDATESTATS)}));break;case BCEvent.CUSTOMSTATS:e.on(BCEvent.CUSTOMSTATS,(e=>{eventQueue.addQueue(handleCustomStats.bind(null,e,n,s),BCEvent.CUSTOMSTATS)}));break;case BCEvent.NETWORK_ERROR:e.on(BCEvent.NETWORK_ERROR,(t=>{eventQueue.addQueue(handleBloudError.bind(null,n,e,i,t,s),BCEvent.NETWORK_ERROR)}));break;case BCEvent.USERREJOINED:e.on(BCEvent.USERREJOINED,(e=>{info("bloud user rejoined"),handleUserRejoined(s,BCEvent,e)}));break;case BCEvent.ROOM_RECONNECTING:e.on(BCEvent.ROOM_RECONNECTING,(e=>{eventQueue.addQueue(handleBloudRoomReconnecting.bind(null,e,n,s),BCEvent.ROOM_RECONNECTING)}));break;case BCEvent.ROOM_RECONNECTED:e.on(BCEvent.ROOM_RECONNECTED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomReconnected.bind(null,e,n,s),BCEvent.ROOM_RECONNECTED)}))));break;case BCEvent.ROOM_SYNC:e.on(BCEvent.ROOM_SYNC,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudRoomSync.bind(null,e,t,n,i,s),BCEvent.ROOM_SYNC)}))));break;case BCEvent.PUBLISHED:e.on(BCEvent.PUBLISHED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPublished.bind(null,e,i,s),BCEvent.PUBLISHED)}))));break;case BCEvent.UNPUBLISH:e.on(BCEvent.UNPUBLISH,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamUnPublished.bind(null,e,i,s),BCEvent.UNPUBLISH)}))));break;case BCEvent.BLOUD_STREAM_UPDATED:e.on(BCEvent.BLOUD_STREAM_UPDATED,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleBloudStreamPubAUpdate.bind(null,e,i),BCEvent.BLOUD_STREAM_UPDATED)}))));break;case BCEvent.MOVE_USER_ROOM:e.on(BCEvent.MOVE_USER_ROOM,(e=>__awaiter$2(this,void 0,void 0,(function*(){eventQueue.addQueue(handleMoveUserRoom.bind(null,n,t,e,s),BCEvent.MOVE_USER_ROOM)}))));break;default:e.on(o,(e=>s[o].next(e)))}})),s}!function(e){e.INIT="init",e.VIDEO_FORCE_CHANGE="video-force-change",e.AUDIO_FORCE_CHANGE="audio-force-change"}(MessageType||(MessageType={}));class BMRoomVM{constructor(e,t,i){this.room=null,this.tipQueueObj={},this.roomInfo=i,this.userVM=t,this.boomCore=e,this.giveLikeList=[],this.giveLikeListWatcher=new Subject}initWithRoom(e){this.room=e}evictUser(e,t){return __awaiter$2(this,void 0,void 0,(function*(){if(!e)return Promise.reject(BmEvictUserError("未传递用户id"));if(!this.userVM.checkLocalHasMaster())return Promise.reject(BmEvictUserError("只有主持人权限才能踢出用户"));if(this.userVM.checkIsMaster(e))return Promise.reject(BmEvictUserError("主持人不能被踢出"));try{yield this.boomCore.evictUser(e,t)}catch(e){return Promise.reject(BmEvictUserError(`踢出用户失败${JSON.stringify(e)}`))}}))}updateUser(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return e?t?void(yield this.boomCore.updateUser(e,{customInfo:t}).catch((e=>Promise.reject(BmUpdateUserError(`boomCore updateUser出错 ${JSON.stringify(e)}`))))):Promise.reject(BmUpdateUserError("info为空,请写入要更新的信息")):Promise.reject(BmUpdateUserError("未传递目标用户id"))}))}changeMaster(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()||(null===(i=this.userVM.getUser(e))||void 0===i?void 0:i.isCreate)?yield this.boomCore.changeMaster(e,t).catch((e=>Promise.reject(BmChangeMasterError(`boomCore changeMaster error ${e}`)))):(console.error("该用户没有管理员权限, 无法改变主持人",LOGGER_TAG_CLIENT,e),Promise.reject(BmChangeMasterError("您没有管理员权限, 无法改变主持人"))):Promise.reject(BmChangeMasterError("未传递主持人id"))}))}updateManager(e,t,i=!0){return __awaiter$2(this,void 0,void 0,(function*(){return e?this.userVM.checkLocalHasMaster()?this.userVM.updateManager(e,t,i):(console.error("该用户没有管理员权限, 无法改变联席主持人",LOGGER_TAG_CLIENT,e),Promise.reject(BmUpdateManagerError("该用户没有管理员权限, 无法改变主持人"))):Promise.reject(BmUpdateManagerError("未传递联席主持人id"))}))}changeNickName(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const i={nickname:t};yield this.updateUser(e,i)}))}sendMessageWithMaster(e,t){return __awaiter$2(this,void 0,void 0,(function*(){if(!this.userVM.checkLocalHasMaster())return Promise.reject(BmSetRemoteAudioEnable("您不是主持人,没有该权限"));if(t){if(!this.userVM.getUser(t))return Promise.reject(BmSetRemoteAudioEnable(`uid: ${t} 未找到用户`))}try{yield this.boomCore.customMessage(JSON.stringify(e),t)}catch(e){return Promise.reject(e)}}))}setRemoteAudioEnable(e,t,i){return __awaiter$2(this,void 0,void 0,(function*(){let r=e?"enabled":"disabled";"enabled"==r&&i&&(r="checkUserAudio");let n={domain:"room-control",method:"audio-force-change",params:{status:r,isNotCancelRootReport:i,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(n,t).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}setRemoteVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){let i={domain:"room-control",method:"video-force-change",params:{status:e?"enabled":"disabled",fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(i,t).catch((e=>Promise.reject(BmSetRemoteVideoEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}closeRemoteShare(e){return __awaiter$2(this,void 0,void 0,(function*(){let t={domain:"room-control",method:"close-remote-share",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${e}`))))}))}tipUser(e,t,i,r){return __awaiter$2(this,void 0,void 0,(function*(){let n={domain:"room-control",method:"tip-user",params:{fromUserId:this.boomCore.getLocalParticipant().getID(),message:t,richMsg:i}};r?this.tipQueueObj[e]=setTimeout((()=>{this.sendMessageWithMaster(n,e)}),60*(r.minutes||0)*1e3+1e3*(r.seconds||0)):this.sendMessageWithMaster(n,e).catch((e=>Promise.reject(BmSetRemoteAudioEnable(`boomCore.sendMessage发生错误 ${JSON.stringify(e)}`))))}))}raiseHands(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){const r=null===(i=this.room)||void 0===i?void 0:i.getLocalParticipant().getID();let n={};"raiseHand"===e?(n.raiseHand=t,n.raiseHandTime=Math.floor((new Date).getTime()/1e3)):n["audio"===e?"raiseHandsAudio":"raiseHandsVideo"]=t,yield this.updateUser(r,n)}))}handleRaiseHands(e,t,i){var r,n,s;return __awaiter$2(this,void 0,void 0,(function*(){let o={domain:"user-control",method:"raise-hands",params:{raiseHandsType:e,raiseHands:t}};try{if(i)yield this.boomCore.customMessage(JSON.stringify(o),i);else{const t=null===(r=this.room)||void 0===r?void 0:r.roomInfo.raiseHandsWatcher.getValue(),i=null===(n=this.room)||void 0===n?void 0:n.roomInfo.raiseVideoHandsWatcher.getValue(),a=null===(s=this.room)||void 0===s?void 0:s.roomInfo.raiseSimpleHandsWatcher.getValue();0===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})),null==i||i.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),1===e&&(null==t||t.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),2===e&&(null==i||i.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)}))),3===e&&(null==a||a.forEach((e=>{this.boomCore.customMessage(JSON.stringify(o),e.userId)})))}}catch(e){return Promise.reject(new BoomError$1(LOCAL_ERROR,"boomCore.sendMessage发生错误"))}}))}updateCustomStats(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){yield this.boomCore.updateCustomStats(e,t).catch((t=>Promise.reject(updateCustomStatsError(`${JSON.stringify(e)} - ${JSON.stringify(t)}`))))}))}sendChatNotice(e,t,i){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatNotice:e,chatNoticeRich:t,showTipNotice:i}).catch((e=>e))}))}giveLikeEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({giveLikeEnable:e}).catch((e=>e))}))}changeAutoMute(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({autoMute:e})}))}allUserReceiveJoinLeaveMessages(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({allUserReceiveJoinLeaveMessages:e})}))}userJoinMasterVoice(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.updateCustomStats({userJoinMasterVoice:e})}))}userGiveLike(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){let r=(new Date).getTime(),n={domain:"room-control",method:"give-like",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:r,nickname:this.userVM.localUser.nickName,type:e||1}}},s=this.userVM.getLocalUser();try{yield this.boomCore.customMessage(JSON.stringify(n),void 0),this.giveLikeList.push({userId:null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant().userId,nickName:null===(i=this.room)||void 0===i?void 0:i.getLocalParticipant().nickName,time:(new Date).getTime(),type:e}),this.giveLikeListWatcher.next(this.giveLikeList)}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==s?void 0:s.userId),new BoomError$1(CLIENT_BANNED,"用户点赞==>sendMessage出错")}}))}chatEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({chatEnable:e}).catch((e=>e))}))}joinAudioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinAudioEnable:e}).catch((e=>e))}))}joinVideoEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinVideoEnable:e}).catch((e=>e))}))}userListEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({userListEnable:e}).catch((e=>e))}))}audioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({audioEnable:e}).catch((e=>e))}))}videoEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({videoEnable:e}).catch((e=>e))}))}modifyNameEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({modifyNameEnable:e}).catch((e=>e))}))}backgroundAIEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({backgroundAIEnable:e}).catch((e=>e))}))}forceOpenUserCamera(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserCamera:e}).catch((e=>e))}))}forceOpenUserMic(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOpenUserMic:e}).catch((e=>e))}))}joinCueVoice(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCueVoice:e}).catch((e=>e))}))}recordEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({recordEnable:e}).catch((e=>e))}))}raiseHandEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({raiseHandEnable:e}).catch((e=>e))}))}joinMicrophoneDisable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinMicrophoneDisable:e}).catch((e=>e))}))}joinCameraDisable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({joinCameraDisable:e}).catch((e=>e))}))}changeFileUpdateModelPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateModel:e}).catch((e=>e))}))}changeFileUpdateLookPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateLook:e}).catch((e=>e))}))}changeFileUpdateDownPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateDown:e}).catch((e=>e))}))}changeFileUpdateEditPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({fileUpdateEdit:e}).catch((e=>e))}))}changeScreenShareModelPermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({screenShareModel:e}).catch((e=>e))}))}changeOnlyOnePersonSharePermission(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({onlyOnePersonShare:e}).catch((e=>e))}))}setForceOnUser(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.updateCustomStats({forceOn:{user:e}}).catch((e=>e))}))}updateHostLayout(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){if(this.userVM.checkLocalHasMaster())return this.updateCustomStats({from:{fromTag:"masterId"},hostLayout:e},t);info("您不是主持人,没有该上报权限",LOGGER_TAG_CLIENT)}))}checkDevices(e){return __awaiter$2(this,void 0,void 0,(function*(){const t={domain:"user-control",method:"check-devices",params:{fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(t,e).catch((e=>Promise.reject(BmCheckDeviceError(`检测对方设备send-message发生错误: ${e}`))))}))}resp2CheckDevices(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"resp-to-check-devices",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};if(!t)return Promise.reject(BmCheckDeviceError(`响应设备检测: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(i),t)}catch(e){return Promise.reject(BmCheckDeviceError(`响应响应设备检测send-message发生错误 ${e}`))}}))}changeRemoteVideoProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"change-video-profile",params:Object.assign(Object.assign({},e),{fromUserId:this.boomCore.getLocalParticipant().getID()})};this.sendMessageWithMaster(i,t).catch((e=>Promise.reject(BmChangeVideoProfileError(`调节对方的视频分辨率send-message发生错误: ${e}`))))}))}resp2ChangeRemoteVideoProfile(e,t,i){return __awaiter$2(this,void 0,void 0,(function*(){const r={domain:"user-control",method:"resp-to-change-video-profile",params:{status:e,profile:i,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(BmChangeVideoProfileError(`响应调节视频分辨率: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(r),t)}catch(e){return Promise.reject(BmChangeVideoProfileError(`响应调节视频分辨率send-message发生错误 ${e}`))}}))}changeRemoteAudioProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"change-audio-profile",params:{microphoneDevice:e.microphoneDevice,speakerDevice:e.speakerDevice,echoCancellation:e.echoCancellation,noiseSuppression:e.noiseSuppression,autoGainControl:e.autoGainControl,speakerVolume:e.speakerVolume,microVolume:e.microVolume,fromUserId:this.boomCore.getLocalParticipant().getID()}};this.sendMessageWithMaster(i,t).catch((e=>Promise.reject(BmChangeAudioProfileError(`调节音频send-message发生错误 ${JSON.stringify(e)}`))))}))}resp2ChangeRemoteAudioProfile(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const i={domain:"user-control",method:"resp-to-change-audio-profile",params:{status:e,fromUserId:this.boomCore.getLocalParticipant().getID()}};if(!t)return Promise.reject(BmChangeAudioProfileError(`响应调节音频: uid: ${t} 未找到用户`));try{yield this.boomCore.customMessage(JSON.stringify(i),t)}catch(e){return Promise.reject(BmChangeAudioProfileError(`响应调节音频send-message发生错误 ${e}`))}}))}}class BMChatVM{constructor(e,t,i){this.messageList=[],this.hasDangerMessageWatcher=new Subject,this.notificationMessageList=debounce((()=>{this.messageListWatcher.next(this.messageList)}),500),this.boomCore=e,this.userVM=t,this.bmRoom=i,this.messageListWatcher=new BehaviorSubject(this.messageList)}sendMessage(e,t,i){return __awaiter$2(this,void 0,void 0,(function*(){let r=e.replace(/(^\s*)|(\s*$)/g,""),n=(new Date).getTime(),s={domain:"room-control",method:"send-talk",params:{stream:{user:this.userVM.localUser.userId,avatar:this.userVM.localUser.avatar,sendTime:n,nickname:this.userVM.localUser.nickName},status:r}},o=this.userVM.getLocalUser();try{let e,a=!1,c=i;c||(yield this.boomCore.sendMessage(JSON.stringify(s),t).then((t=>{e=t.seq})).catch((e=>{warn$1("sendmessage 出错","",null==o?void 0:o.userId,[e]),e&&39===e.code&&(a=!0,this.hasDangerMessageWatcher.next(!0))})));const u=new BMMessageInfo({userId:null==o?void 0:o.userId,message:r,isLocal:null==o?void 0:o.isLocal,avatar:null==o?void 0:o.avatar,nickName:null==o?void 0:o.nickName,sendTime:n,to:t,isDanger:a,seq:e,failed:c});return this.addMessage(u,!1),c?Promise.reject(u):Promise.resolve()}catch(e){throw error$1(e,LOGGER_TAG_CLIENT,null==o?void 0:o.userId),new BoomError$1(CLIENT_BANNED,"发送聊天消息==>sendMessage出错")}}))}addMessage(e,t){if(!t||this.bmRoom.participantNotice){if(0==this.messageList.length||e.timeStamp-this.messageList[this.messageList.length-1].timeStamp>=notGetTalkInterval){const e=new BMMessageInfo({isMeetingNotice:!0,message:""});this.messageList.push(e)}this.messageList.push(e),this.notificationMessageList()}}updateMessageListWatcher(e){this.messageList=e,this.messageListWatcher.next(this.messageList)}getHistoryMessage(){return __awaiter$2(this,void 0,void 0,(function*(){const e=yield this.boomCore.getMessages(0,this.boomCore.getMsgSeq());let t=[];return e.items.forEach((e=>{if(e.private||e.to)return!1;if(0==e.msg.length||-1==e.msg.indexOf("{"))return!1;const i=JSON.parse(e.msg);if("send-talk"!=i.method)return!1;const r=e.seq;let n=i.params,s=n.stream.user?n.stream.user:e.userId;n.stream.nickname,n.status,(new Date).getTime();const o=new BMMessageInfo({userId:s,message:n.status,nickName:n.stream.nickname,isLocal:s==this.userVM.localUser.userId,avatar:n.stream.avatar,sendTime:n.stream.sendTime,seq:r});t.push(o)})),Promise.resolve(t)}))}}class CustomEvent{constructor(e,t){this.type=e,this.phase=CustomEvent.PHASE_CURRENT,t&&(this.originalEvent=t)}preventDefault(){const e=this;if(!e.isPrevented){const{originalEvent:t}=e;t&&t.preventDefault(),e.isPrevented=TRUE}return e}stopPropagation(){const e=this;if(!e.isStoped){const{originalEvent:t}=e;t&&t.stopPropagation(),e.isStoped=TRUE}return e}prevent(){return this.preventDefault()}stop(){return this.stopPropagation()}}function each$1(e,t,i){const{length:r}=e;if(r)if(i)for(let i=r-1;i>=0&&t(e[i],i)!==FALSE;i--);else for(let i=0;i<r&&t(e[i],i)!==FALSE;i++);}function nativePush(e,t){e[e.length]=t}function addItem(e,t,i){array(t)?each$1(t,(function(t){i(e,t)})):i(e,t)}function push(e,t){addItem(e,t,nativePush)}function indexOf(e,t,i){let r=MINUS_ONE;return each$1(e,(function(e,n){if(i===FALSE?e==t:e===t)return r=n,FALSE})),r}function has(e,t,i){return indexOf(e,t,i)>=0}function each(e,t){for(let i in e)if(t(e[i],i)===FALSE)break}function copy(e,t){let i=e;return array(e)?t?(i=[],each$1(e,(function(e,r){i[r]=copy(e,t)}))):i=e.slice():object(e)&&(i={},each(e,(function(e,r){i[r]=t?copy(e,t):e}))),i}CustomEvent.PHASE_CURRENT=0,CustomEvent.PHASE_UPWARD=1,CustomEvent.PHASE_DOWNWARD=MINUS_ONE;const DEBUG=1,INFO=2,WARN=3,FATAL=5,nativeConsole=typeof console!==RAW_UNDEFINED?console:NULL,defaultLogLevel=/yox/.test(toString(EMPTY_FUNCTION))?INFO:WARN,stylePrefix=WINDOW&&/edge|msie|trident/i.test(WINDOW.navigator.userAgent)?EMPTY_STRING:"%c",printLog=nativeConsole?stylePrefix?function(e,t,i,r){r?nativeConsole.log(stylePrefix+e,i,t,r):nativeConsole.log(stylePrefix+e,i,t)}:function(e,t,i){i?nativeConsole.log(e,t,i):nativeConsole.log(e,t)}:EMPTY_FUNCTION;function getLogLevel(){if(GLOBAL){const e=GLOBAL.YOX_LOG_LEVEL;if(e>=DEBUG&&e<=FATAL)return e}return defaultLogLevel}function getStyle(e){return`background-color:${e};border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;`}function warn(e,t){getLogLevel()<=WARN&&printLog(t||"bjy warn",e,getStyle("#f90"))}function fatal(e,t){if(getLogLevel()<=FATAL)throw new Error(`[${t||"bjy fatal"}]: ${e}`)}class Emitter{constructor(e){this.ns=e||FALSE,this.listeners={}}fire(e,t,i){let r=this,n=string(e)?r.parse(e):e,s=r.listeners[n.type],o=TRUE;if(s){s=copy(s);const e=t&&t[0]instanceof CustomEvent?t[0]:UNDEFINED;each$1(s,(function(a){if(!matchNamespace(n.ns,a,TRUE)||!has(s,a)||i&&!i(n,t,a))return;e&&(e.listener=a.fn);let c=execute(a.fn,a.ctx,t);return e&&(e.listener=UNDEFINED),a.num=a.num?a.num+1:1,a.num===a.max&&r.off(n,a.fn),e&&(c===FALSE?e.prevent().stop():e.isStoped&&(c=FALSE)),c===FALSE?o=FALSE:void 0}))}return o}on(e,t){const i=this,r=i.listeners,n=func(t)?{fn:t}:t;if(object(n)&&func(n.fn)){const t=string(e)?i.parse(e):e;n.ns=t.ns,push(r[t.type]||(r[t.type]=[]),n)}else"development"===process.env.NODE_ENV&&fatal('emitter.on(type, listener) invoke failed:\n\n"listener" is expected to be a Function or an EmitterOptions.\n')}off(e,t){const i=this,r=i.listeners;if(e){const n=string(e)?i.parse(e):e,s=n.type,o=n.ns,a=createMatchListener(t),c=function(e,t){each$1(e,(function(t,i){a(t)&&e.splice(i,1)}),TRUE),e.length||delete r[t]},u=function(e,t){each$1(e,(function(t,i){matchNamespace(o,t)&&e.splice(i,1)}),TRUE),e.length||delete r[t]};s?r[s]&&c(r[s],s):o&&each(r,u),"development"===process.env.NODE_ENV&&arguments.length>1&&t==NULL&&warn(`emitter.off(type, listener) is invoked, but "listener" is ${t}.`)}else i.listeners={},"development"===process.env.NODE_ENV&&arguments.length>0&&warn(`emitter.off(type) is invoked, but "type" is ${e}.`)}has(e,t){let i=this.listeners,r=string(e)?this.parse(e):e,n=r.type,s=r.ns,o=TRUE,a=createMatchListener(t),c=function(e){return each$1(e,(function(e){if(a(e))return o=FALSE})),o};return n?i[n]&&c(i[n]):s&&each(i,c),!o}parse(e){const t={type:e,ns:EMPTY_STRING};if(this.ns){const i=indexOf$1(e,RAW_DOT);i>=0&&(t.type=slice(e,0,i),t.ns=slice(e,i+1))}return t}}function matchTrue(){return TRUE}function createMatchListener(e){return func(e)?function(t){return e===t.fn}:matchTrue}function matchNamespace(e,t,i){const{ns:r}=t;return r&&e?r===e:i?TRUE:FALSE}const namespace$1=`.speaker${Math.random()}`;class BMSpeaker{constructor(e,t){this.collectAudioLevel=()=>{this.close(),this._stream.on("audio-level"+namespace$1,this.handleAudioLevel)},this.handleAudioLevel=e=>{this._emitter.fire("audio-level",[e])},this.close=()=>{this._stream.off(namespace$1)},this._emitter=new Emitter(!0),this._user=e,this._stream=t}getID(){return this._stream.getStreamId()}getUser(){return this._user}on(e,t){return this._emitter.on(e,{fn:t,ctx:this}),this}}function getMasterSort(e,t){return 16|~~e<<1|~~t}function getLocalSort(e,t){return 12|~~e<<1|~~t}function getManagerSort(e,t){return 8|~~e<<1|~~t}function getGuestSort(e,t){return 4|~~e<<1|~~t}function getCommonSort(e,t){return~~e<<1|~~t}const namespace=`.connect${Math.random()}`;class BMStreamModel{constructor(e,t){this.streamType=STREAM_TYPE.OTHER,this.pullFailedNum=0,this._video_enable=!1,this._audio_enable=!1,this.videoEnableWatcher=new BehaviorSubject(this._video_enable),this.audioEnableWatcher=new BehaviorSubject(this._audio_enable),this.streamUpdateWatcher=new Subject,this.isSubScribedWatcher=new Subject,this.playStateChangeWatcher=new Subject,this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.audioLevelWatcher=new Subject,this.isCurrentDisplay=!1,this.isDisplay=!1,this.isDisplayObserve=new Subject,this.isInBig=!1,this.isInBigObserve=new Subject,this._hasPulled=!1,this.playerId="",this.shouldPull=!1,this._pulledStreamType="small",this.pulledStreamGoal="small",this.bigPlayerId="",this.isPlayingBig=!1,this.muted=!1,this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount=0,this.sortNum=-1,this.handleDisplayChange=e=>{var t;this.isDisplay!==e&&(this.isDisplay=e,null===(t=this.stream)||void 0===t||t.stop(),this.isDisplay?this.checkVideo():(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.pulledStreamType="small"),this.sendMessage2Room())},this.onPlayerStateChange=e=>{var t,i;"error"===e.type&&e.reason&&"NotAllowedError"===e.reason.name&&(info("播放失败, 需要调用 resume 方法"),this.playStateChangeWatcher.next(this)),"PAUSED"!==e.state&&"pause"!==e.reason||(this.player&&(null===(t=this.player)||void 0===t||t.resume()),null===(i=this.stream)||void 0===i||i.resume())},this.handleStreamConnectError=()=>{info("流出现的connect-error userId","",this.userId,["streamId ==>",this.streamId,"nickname =>",this.nickname]),this.isLocal?BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!0}):BoomEmitter.emitter.emit(HANDLE_STREAM_CONNECT_ERROR,{stream:this,isLocal:!1})},this.bindElement=e=>{this.playerId=e,this.emitBindElement()},this.bindBigElement=e=>{this.bigPlayerId=e,this.emitBindBigElement()},this.sendMessage2Room=debounce((()=>{BoomEmitter.emitter.emit(RECEIVE_SUBSCRIBE_MESSAGE,{stream:this})}),30),this.emitBindElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_ELEMENT,{stream:this})}),50),this.emitBindBigElement=debounce((()=>{BoomEmitter.emitter.emit(BIND_BIG_ELEMENT,{stream:this})}),50),this.currentIsPlaying=()=>{const e=document.getElementById(this.playerId);let t=!1,i=0;if(e){const r=e.querySelectorAll('div[id^="player_"]');t=r.length>0,r.forEach((e=>{0===e.children.length&&(i+=1)}))}return t&&0>i},this.currentBigIsPlaying=()=>{if(!!!document.getElementById(this.bigPlayerId))return!1;if(this.stream){const e=document.getElementById(`player_${this.stream.getStreamId()}_big_container`);let t=0,i=0;if(e){e.querySelectorAll('div[id^="player_"]').forEach((e=>{0===e.children.length&&(i+=1)}))}return e&&t>i}},this.play=debounce(((e=!1)=>__awaiter$2(this,void 0,void 0,(function*(){var t,i;const r=this.stream;if(r)if(this.isDisplay||this.audioEnable||(null===(t=this.stream)||void 0===t?void 0:t.getAudioOn())){const t=document.getElementById(this.playerId),i=!!t;let n=!1;if(t){const e=t.querySelectorAll('div[id^="player_"]');n=e.length>0,e.forEach((e=>{0===e.children.length&&(e.style.display="none",null==t||t.removeChild(e))}))}if(i)try{r.isPlaying()&&n||(yield r.stop(),yield r.play(this.playerId,{backgroundColor:"#202020",fit:"contain",audio:!autoPlayAudio})),info("远端流播放结束",this.userId,this.streamId,[this.nickname])}catch(t){yield r.stop(),setTimeout((()=>{error$1("播放小流失败, 尝试重新播放","播放",this.userId,[this.streamId,this.stream,"error => ",JSON.stringify(t)]),this.play(e)}),2e3)}else warn$1("找不到播放器容器","stream play",this.userId,["流 id =>",this.streamId,"nickname =>",this.nickname,"playerId =>",this.playerId]),this.playerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"small"})}else null===(i=this.stream)||void 0===i||i.stop()}))),300),this.playInBig=debounce(((e=!0)=>__awaiter$2(this,void 0,void 0,(function*(){var t,i;const r=this.stream;if(r){const n=!!document.getElementById(this.bigPlayerId),s=document.getElementById(`player_${r.getStreamId()}_big_container`);s&&s.children.length,this.isInBig?n?(null===(t=this.player)||void 0===t||t.destroy(),this.player=null,this.initBigPlayer(e),this.player&&(yield this.player.play(r),this.isPlayingBig=!0),info("远端流大流播放结束",this.userId,this.streamId,[this.nickname])):(warn$1("找不到 bigPlayerId","大流播放",this.userId,["流 id =>",this.streamId,"canGetContainer =>",n,"canGetPlayer =>",s]),this.bigPlayerId||BoomEmitter.emitter.emit(NO_CONTAINER,{type:this.isShare?"share":"normal",id:this.userId,container:"big"})):(null===(i=this.player)||void 0===i||i.destroy(),this.player=null,this.isPlayingBig=!1)}}))),300),this.collectAudioLevel=()=>{this.stream?this.stream.on("audio-level"+namespace,this.handleAudioLevel):warn$1("collection audio level but not have brtc stream")},this.handleAudioLevel=e=>{this.audioLevelWatcher.next(e)},this.user=e,this.updateUser(e),this._stream=t,this.isDisplayObserve.subscribe((e=>{this.handleDisplayChange(e)})),this.isInBigObserve.subscribe((e=>{this.handleIsInBig(e)})),this.updateSortNum(!1)}get hasPulled(){return this._hasPulled}set hasPulled(e){this._hasPulled=e}get pulledStreamType(){return this._pulledStreamType}set pulledStreamType(e){this._pulledStreamType=e}get uuid(){return this.isShare?`${this.userId}_share`:this.userId}get isAudience(){return this.user.isAudience}get canShow(){return!this.isAudience||(this.audioEnable||this.videoEnable)}changeMute(e){this.muted!==e&&(this.muted=e,this.handleSpeakerChange())}handleSpeakerChange(){var e,t;this.isLocal||(this.muted?null===(e=this.stream)||void 0===e||e.setAudioVolume(0):null===(t=this.stream)||void 0===t||t.setAudioVolume(1))}get isToupingma(){return this.user.isToupingma}get isMixer(){return this.user.isMixer}get isSignal(){return this.user.isSignal}genReceiveSubMsg(){let e=null;return e=this.isDisplay?{audio:!0,video:!0,streamType:"small"}:{audio:!0,video:!1,streamType:"small"},e}handleIsInBig(e){this.isInBig===e&&this.pulledStreamType===this.pulledStreamGoal||(this.isInBig=e,info("isInBig change","",this.userId,["streamId =>",this.streamId,"isInBig => ",e]),this.isInBig?this.pulledStreamGoal="big":this.pulledStreamGoal="small",this.sendMessage2Room(),this.isShare&&(this.isInBig?this.checkVideo():(this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0)))}setVideoEnable(e){this._video_enable!==e&&(this._video_enable=e,this.videoEnableWatcher.next(e))}setAudioEnable(e){this._audio_enable!==e&&(this._audio_enable=e,this.audioEnableWatcher.next(e))}updateStream(e,t=!0,i){if(this._stream&&this._stream.off(namespace),this._stream=e,e){this.streamType=e.type;const r=e.getVideoOn(),n=e.getAudioOn();info("更新用户的流","updateStream",null==e?void 0:e.getUserId(),["nickname =>",this.nickname,"audioOn",n,"videoOn",r,"streamId",e.getStreamId()]),r&&this.isDisplay&&this.checkVideo(),n&&(this.isShare||i.addToDetector(new BMSpeaker(this.user,e)),this.collectAudioLevel()),e.on("player-state-changed"+namespace,this.onPlayerStateChange),e.on("connect-error"+namespace,this.handleStreamConnectError),e.on("stream-connection-error"+namespace,this.handleStreamConnectError),t&&this.sendMessage2Room()}else this.hasPulled=!1,this.pulledStreamType="small",this.streamType=STREAM_TYPE.OTHER}updateBloudStream(e,t,i=!1){var r,n,s;e?(this.bloudStream={audio:e.audio,video:e.video,isScreen:e.isScreen},this.stream&&(this.bloudStream.audio?(t.addToDetector(new BMSpeaker(this.user,this.stream)),this.collectAudioLevel()):t.removeFromDetector(this.stream.getStreamId())),this.setVideoEnable(this.bloudStream.video),this.setAudioEnable(this.bloudStream.audio),i&&(null===(r=this.stream)||void 0===r||r.destroy(),this.stream&&(null===(n=t.room.audioPlayer)||void 0===n||n.removeStream(this.stream)),this.updateStream(void 0,!1,t),this._stream=void 0),!this.audioEnable&&this.stream&&(null===(s=t.room.audioPlayer)||void 0===s||s.removeStream(this.stream)),(this.bloudStream.audio||this.bloudStream&&this.isDisplay)&&(!this.stream||i?BoomEmitter.emitter.emit(ADD_PULL_USER,{id:this.userId,isWeb:this.isWeb,isScreen:this.isShare}):this.sendMessage2Room())):(this.bloudStream=void 0,this.setVideoEnable(!1),this.setAudioEnable(!1),this.stream&&t.removeFromDetector(this.stream.getStreamId())),this.updateSortNum(!0),this.streamUpdateWatcher.next(!0)}get streamId(){return this._stream?this._stream.getStreamId():this.userId}get bStreamId(){return this.isShare?`${this.userId}_screen`:this.userId}get userId(){return this.user.userId}get stream(){return this._stream}get isLocal(){return this.user.isLocal}get isShare(){var e,t,i;return this.stream?this.user.isWeb?null===(t=null===(e=this.stream)||void 0===e?void 0:e.getUserId())||void 0===t?void 0:t.endsWith(STREAM_SUFFIX_SCREEN):!(!this.stream||!this.stream.getType||"assist"!==this.stream.getType()):!!(null===(i=this.bloudStream)||void 0===i?void 0:i.isScreen)}get isWeb(){return this.user.isWeb}get audioEnable(){return this._audio_enable}get videoEnable(){return this._video_enable}get nickname(){var e;return this.user.isToupingma?`${this.user.nickName}(的投屏)`:(null===(e=this.streamId)||void 0===e?void 0:e.includes(STREAM_SUFFIX_SCREEN))?`${this.user.nickName}(的屏幕共享)`:this.user.nickName}get audioLevel(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.getAudioLevel())||0}getUser(){return this.user}setRemoteAudioLevel(e){if(this.isLocal)throw new Error("不能设置本地流的音量");BoomEmitter.emitter.emit(SET_VOLUME,{streamId:this.streamId,volume:e})}getStats(){var e;return null===(e=this._stream)||void 0===e?void 0:e.getStats()}initBigPlayer(e){try{if(this.bigPlayerId){const e=document.querySelector(`#${this.bigPlayerId}`);e||console.error("播放大流失败,找不到大流容器",this.userId,this.streamId,this.bigPlayerId),!this.player&&e&&(this.player=new Player(e,{fit:"contain"}))}}catch(e){error$1("初始化大窗口的播放器失败",this.userId,this.streamId,e.message)}}stop(){var e;null===(e=this._stream)||void 0===e||e.stop()}destroy(){var e;null===(e=this._stream)||void 0===e||e.destroy()}isPlaying(){var e;return null===(e=this._stream)||void 0===e?void 0:e.isPlaying()}replay(){var e;return null===(e=this._stream)||void 0===e?void 0:e.replay()}resume(){var e;return null===(e=this._stream)||void 0===e?void 0:e.resume()}hasAudio(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasAudio())||!1}hasVideo(){var e;return(null===(e=this._stream)||void 0===e?void 0:e.hasVideo())||!1}updateUser(e){this.user=e;const t=this.user.userInfo.pos;t?t.includes("web")||t.includes("pc")?this.streamType=STREAM_TYPE.SUB_MAIN:t.includes("_toupingma")?this.streamType=STREAM_TYPE.SHARE:this.streamType=STREAM_TYPE.SINGLE:this.streamType=STREAM_TYPE.SINGLE}updateSortNum(e=!0){const t=this.getSortNum();this.setSortNum(t,e)}setSortNum(e,t){this.sortNum!==e&&(this.sortNum=e,t&&BoomEmitter.emitter.emit(MODEL_SORT_NUM_CHANGE,null))}getSortNum(){return this.user.isMaster?getMasterSort(this.audioEnable,this.videoEnable):this.user.isLocal?getLocalSort(this.audioEnable,this.videoEnable):this.user.isManager?getManagerSort(this.audioEnable,this.videoEnable):this.user.isMaster||this.user.isManager||this.user.isCommonUser?getCommonSort(this.audioEnable,this.videoEnable):getGuestSort(this.audioEnable,this.videoEnable)}checkVideo(){if(this.videoEnable&&this.stream){if(!this.isShare&&this.isDisplay&&this.playerId){const e=`video_${this.stream.getStreamId()}_big`,t=`video_${this.stream.getStreamId()}`,i=!!document.getElementById(e),r=!!document.getElementById(t);if(this.isInBig&&i)return void this.checkVideoDecodeFrame(e);if(r)return void this.checkVideoDecodeFrame(t)}this.isShare&&this.isInBig&&this.bigPlayerId&&this.checkVideoDecodeFrame(`video_${this.stream.getStreamId()}_big`)}}checkVideoDecodeFrame(e){const t=document.getElementById(e);this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),t?this.checkVideoTimer=setTimeout((()=>{var i,r,n;const s=(null==t?void 0:t.getVideoPlaybackQuality)&&(null===(i=null==t?void 0:t.getVideoPlaybackQuality())||void 0===i?void 0:i.totalVideoFrames)||0;if(!t||t.getVideoPlaybackQuality)return s>0?(clearTimeout(this.checkVideoTimer),void(this.checkFailedCount=0)):this.checkCount>10?(error$1("检测超过了十次,还没有视频流,需要重新拉取","黑帧检测",this.userId,["streamId =>",this.streamId,"nickname =>",this.nickname]),this.checkVideoTimer&&clearTimeout(this.checkVideoTimer),this.checkVideoTimer=null,this.checkCount=0,this.checkFailedCount+=1,void(this.checkFailedCount<=3&&(this.hasPulled=!1,this.pulledStreamType="small",null===(r=this._stream)||void 0===r||r.off(namespace),null===(n=this._stream)||void 0===n||n.destroy(),this._stream=void 0,this.sendMessage2Room()))):(this.checkCount+=1,void this.checkVideoDecodeFrame(e));this.checkVideoTimer&&clearTimeout(this.checkVideoTimer)}),1e3):info("黑帧检测没有播放容器",this.userId,"",["streamId =>",this.streamId,"isShare =>",this.isShare])}subscribeStream(){this.shouldPull=!0,BoomEmitter.emitter.emit(MANUAL_SUBSCRIPTION,{stream:this})}unSubscribeStream(){this.shouldPull=!1,BoomEmitter.emitter.emit(UNSUBSCRIBE_STREAM,{stream:this})}}function getHTMLMediaStreamOptions(e){let t=null;const i=e.videoElement,r=i.offsetWidth,n=i.offsetHeight;if(i.captureStream?t=i.captureStream():i.mozCaptureStream&&(t=i.mozCaptureStream()),t){const e=t.getVideoTracks()[0],i=t.getAudioTracks()[0];return{video:!!e,audio:!!i,videoSource:e,audioSource:i,width:r,height:n}}return null}function getMediaStreamInfo(e,t){try{const i=e.getVideoTracks()[0],r=e.getAudioTracks()[0];return{video:!!i,audio:!!r,videoSource:i,audioSource:r,width:t.width,height:t.height}}catch(e){return console.log("获取共享音频参数有误",e),null}}function transShareScreen2User(e){return e.split("_")[0]}class BMStreamModelVM{constructor(){this.streamModels=new Map,this.streamModelsWatcher=new BehaviorSubject(BMStreamModelVM.filterStreamModels(this.sortStreamModels())),this.shareStreamModels=new Map,this.shareStreamModelsWatcher=new BehaviorSubject(Array.from(this.shareStreamModels.values())),this.localStreamErrorWatcher=new Subject,this.localModel=null,this.room=null,this.bloudStream=null,this.videoStream=null,this.audioStream=null,this.audioStats=!1,this.videoStats=!1,this.localIsShare=!1,this.isShareWatcher=new Subject,this._speaker_enable=!0,this.speakerEnableWatcher=new BehaviorSubject(this._speaker_enable),this.mixStreamModelWatcher=new BehaviorSubject(null),this.canvasTimer=null,this._isRecording=!1,this._slicingRecord=!1,this.isRecordingWatcher=new BehaviorSubject(this._isRecording),this._speaker=null,this._speakers=new Map,this.speakerWatcher=new BehaviorSubject(this._speaker),this.noContainerWatcher=new Subject,this.noBigContainerWatcher=new Subject,this.localStreamConnectErrorWatcher=new Subject,this.localShareError=new Subject,this.updateModelSort=debounce((()=>{const e=this.sortStreamModels();this.streamModelsWatcher.next(BMStreamModelVM.filterStreamModels(e))}),200,{maxWait:500}),this.handleNoContainer=e=>{const{type:t,container:i,id:r}=e;let n;n="share"===t?this.shareStreamModels.get(r):this.streamModels.get(r),n&&("small"===i?this.noContainerWatcher.next(n):this.noBigContainerWatcher.next(n))},this.getHTMLMediaStream=getHTMLMediaStreamOptions,this.getMediaStream=getMediaStreamInfo,this.createCanvas(),setTimeout((()=>{this.canvasDisplay()}),100),BoomEmitter.emitter.on(MODEL_SORT_NUM_CHANGE,this.updateModelSort),BoomEmitter.emitter.on(NO_CONTAINER,this.handleNoContainer)}static filterStreamModels(e){return e.filter((e=>!e.isToupingma)).filter((e=>!ignoreUserId.some((t=>e.userId.includes(t))))).filter((e=>e.canShow))}initWithRoom(e){return this.room=e,this}setSpeakerEnable(e){var t;this._speaker_enable!==e&&(null===(t=this.room.audioPlayer)||void 0===t||t.mute(!e),this._speaker_enable=e,this.speakerEnableWatcher.next(e))}getStreamModels(){return Array.from(this.streamModels.values())}getStreamModelByUId(e){return this.streamModels.get(e)}getShareStreamModelByUId(e){return this.shareStreamModels.get(e)}getLocalStreamModel(){return this.localModel}createStreamModel(e,t){const i=new BMStreamModel(e,void 0);return t&&i.updateStream(t,!0,this),i.isShare?(e.addStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`,i),this.addShareStreamModel(i)):(e.addStream(e.userId,i),this.addStreamModel(i)),i}addStreamModel(e){e&&(e.isLocal?this.localModel||(this.localModel=e,this.streamModels.set(this.localModel.userId,this.localModel)):this.streamModels.set(e.userId,e))}addShareStreamModel(e){e&&(e.isLocal||(this.shareStreamModels.set(e.userId,e),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))))}removeStreamModel(e){if(!e)return;const t=e.getUser();this.streamModels.delete(e.userId),t.removeStream(e.userId)}removeShareStreamModelByUId(e){var t,i;const r=this.shareStreamModels.get(e);r&&(null===(t=r.stream)||void 0===t||t.stop(),null===(i=r.stream)||void 0===i||i.destroy(),this.removeShareStreamModel(r))}removeShareStreamModel(e){if(!e)return;const t=e.getUser();this.shareStreamModels.delete(e.userId),t.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}removeStreamModelByUId(e){const t=this.getStreamModelByUId(e);return t&&(t.stream&&(this.removeFromDetector(t.streamId),t.stream.stop(),t.stream.destroy()),this.removeStreamModel(t)),t}remoteStreamPublished(e){const t=e.getStreamId(),i=e.getUserId();let r,n=this.getStreamModelByUId(i);if(n||(r=transShareScreen2User(String(i)),n=this.getStreamModelByUId(r)),n){if(isShareStream(e)){let t;if(r&&(t=this.shareStreamModels.get(r)),t){if(t.isLocal)return;t.hasPulled=!1,t.pulledStreamType="small",t.updateStream(e,!0,this),this.shareStreamModelsWatcher.next(Array.from(this.shareStreamModels.values()))}else{const t=this.createStreamModel(n.getUser(),e),i=e.getVideoOn(),r=e.getAudioOn();t.updateBloudStream({audio:r,video:i,isScreen:!0},this),t.streamType=STREAM_TYPE.SHARE}}else n.hasPulled=!1,n.pulledStreamType="small",this.updateStreamModel(n,e);n.getUser().isMixer&&this.mixStreamModelWatcher.next(n),this.changeSingleStreamSpeaker(n).catch((e=>{error$1("设置单股流的扬声器的播放出现了问题","设置播放音量",null==n?void 0:n.userId)}))}else error$1("brtc有人推流了,但是找不到对应的streamModel, 找不到对应的用户","",i,["streamId => ",t,"type =>",e.getType&&e.getType()])}remoteStreamUnpublished(e){var t,i,r;let n;const s=e.getUserId(),o=e.getStreamId();let a=!1;if(s.includes(STREAM_SUFFIX_SCREEN)){const e=transShareScreen2User(String(s));if(e==(null===(i=null===(t=this.room)||void 0===t?void 0:t.getLocalParticipant())||void 0===i?void 0:i.userId))return info("本地用户取消共享屏幕","取消共享屏幕",s),void this.localModel.getUser().removeStream(s);n=this.getShareStreamModelByUId(e),a=!0}else o.startsWith(MOBILE_STREAM_SUFFIX_SCREEN)||e.getType&&"assist"===e.getType()?(n=this.getShareStreamModelByUId(s),a=!0):n=this.getStreamModelByUId(s);if(this.removeFromDetector(o),this.removeFromRecorder(e),!n)return void error$1("brtc有人取消推流 但是找不到对应的streamModel","取消推流",s,[o]);const c=null===(r=n.stream)||void 0===r?void 0:r.getStreamId();if(c===o)return n.hasPulled=!1,n.pulledStreamType="small",a||n.streamType===STREAM_TYPE.SHARE?(this.removeShareStreamModel(n),void n.updateStream(void 0,!0,this)):(n.updateStream(void 0,!0,this),n);error$1("当前取消推流的和当前绑定的不是同一股流","",s,["streamId =>",o,"streamModel.streamId",c])}sortStreamModels(){return sortStreamModelsOrUser(Array.from(this.streamModels.values()),!0)}updateStreamModel(e,t){e.updateStream(t,!0,this)}updateShareStreamModel(e,t){e.updateStream(t,!0,this)}setLocalVideoEnable(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){if(!(null===(i=this.room)||void 0===i?void 0:i.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地摄像头,不与响应");if(!this.room.mediaPermission.camera)return Promise.reject(BMCameraNotAuthError());const r=this.getLocalStreamModel();if(info(`开关本地摄像头, 状态 => ${e}`,"本地用户",null==r?void 0:r.userId),r)if(e)if(null==r?void 0:r.stream){if(t)yield r.stream.replaceTrack(t).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}));else{if("CanvasCaptureMediaStreamTrack"===r.stream.getVideoTrack().constructor.name){const e=yield this.createVideoStream().catch((e=>Promise.reject(e)));yield r.stream.replaceTrack(e).then((()=>{info("replace video track success")})).catch((e=>(error$1("本地视频流更换视频流失败","","",JSON.stringify(e)),this.handleStreamUpdateFailed(),Promise.reject(BMOpenCameraError()))))}}if(!(yield r.stream.unmuteVideo()))return error$1("brtc unmuteVideo失败"),this.handleStreamUpdateFailed(),Promise.reject(BMOpenCameraError());info("brtc unmute video success"),yield this.bloudStream.setVideoEnabled(!0).then((()=>{r.updateStream(r.stream,!0,this),r.updateBloudStream({video:!0,audio:r.audioEnable,isScreen:!1},this),r.playInBig()})).catch((e=>{error$1("bloud unmuteVideo失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!1,!0,r,t).catch((e=>{var t,i,r,n,s;return error$1("开启本地摄像头失败","","",[JSON.stringify(e)]),null===(i=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===i||i.destroy(),(null===(r=this.bloudStream)||void 0===r?void 0:r.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));else{r.stream&&(yield this.muteOrUnpublishStream("video",!0,r).catch((e=>(error$1("关闭本地摄像头失败","","",[e]),Promise.reject(BmSetLocalVideoEnable(e))))))}}))}handleStreamUpdateFailed(){return __awaiter$2(this,void 0,void 0,(function*(){error$1("brtc unmute stream failed, now unpublish"),yield this.unpublishStream()}))}setLocalAudioEnable(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(!(null===(t=this.room)||void 0===t?void 0:t.networkState.brtc)||!this.room.netConnecting)return void error$1("断网期间开本地麦克风,不与响应");if(!this.room.mediaPermission.microphone)return Promise.reject(BMMicNotAuthError());const i=this.getLocalStreamModel();if(info(`开关本地麦克风, 状态 => ${e}`,"本地用户",null==i?void 0:i.userId),i)if(e){if(null==i?void 0:i.stream){const e=yield i.stream.unmuteAudio();if(info(`unmute local stream audio res : ${e}`),!e)return error$1("brtc unmuteAudio失败","本地用户",""),yield this.handleStreamUpdateFailed(),Promise.reject(BMOpenMicroError());info("unmute audio success"),yield this.bloudStream.setAudioEnabled(!0).then((()=>{info("bloud stream set audio enable"),i.updateStream(i.stream,!0,this),i.updateBloudStream({audio:!0,video:i.videoEnable,isScreen:!1},this)})).catch((e=>{error$1("bloud unmuteAudio失败","本地用户","",[JSON.stringify(e)]),this.handleStreamUpdateFailed()}))}else yield this.createStreamAndPublish(!0,!1,i).catch((e=>{var t,i,r,n,s;return error$1("开启本地麦克风失败","","",[e]),null===(i=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===i||i.destroy(),(null===(r=this.bloudStream)||void 0===r?void 0:r.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}));(null==i?void 0:i.stream)&&this.addToRecorder(null==i?void 0:i.stream)}else{const e=i.stream;if(e){this.removeFromRecorder(e),this.removeFromDetector(e.getStreamId());try{yield this.muteOrUnpublishStream("audio",!0,i)}catch(e){return error$1("关闭本地麦克风失败","","",[JSON.stringify(e)]),Promise.reject(BmSetLocalAudioEnable(e))}}}}))}joinWithAudioAndAudio(e,t){return __awaiter$2(this,void 0,void 0,(function*(){const i=this.getLocalStreamModel();if(i)try{yield this.createStreamAndPublish(e,t,i).catch((e=>{var t,i,r,n,s;return null===(i=null===(t=this.localModel)||void 0===t?void 0:t.stream)||void 0===i||i.destroy(),(null===(r=this.bloudStream)||void 0===r?void 0:r.published)&&this.bloudStream.unpublish(),null===(n=this.localModel)||void 0===n||n.updateStream(void 0,!0,this),null===(s=this.localModel)||void 0===s||s.updateBloudStream(void 0,this),Promise.reject(e)}))}catch(e){return Promise.reject(e)}}))}changeSpeaker(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){if(!e.deviceId)throw new BoomError$1(LOCAL_ERROR,"切换扬声器失败!,原因: 选择的设备没有deviceId"+(null==e?void 0:e.name));try{this.room.setSelectSpeakerDevice(e),null===(i=null===(t=this.room)||void 0===t?void 0:t.audioPlayer)||void 0===i||i.setDevice(e.deviceId)}catch(e){throw new BoomError$1(LOCAL_ERROR,"切换扬声器失败!,原因:"+e,e)}}))}changeSingleStreamSpeaker(e){return __awaiter$2(this,void 0,void 0,(function*(){const t=this.room.selectAudioOutputDevice;t&&(e.isLocal||e.stream&&(yield e.stream.setAudioOutput(t.deviceId)))}))}changeAudioInput(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){const r=null===(t=this.localModel)||void 0===t?void 0:t.stream;null===(i=this.room)||void 0===i||i.setSelectAudioDevice(e),r&&(this.removeFromRecorder(r),yield r.switchDevice("audio",e.deviceId),this.addToRecorder(r))}))}changeVideoInput(e){var t,i,r;return __awaiter$2(this,void 0,void 0,(function*(){const n=null===(t=this.localModel)||void 0===t?void 0:t.stream;null===(i=this.room)||void 0===i||i.setSelectVideoDevice(e),n&&(yield n.switchDevice("video",e.deviceId),(null===(r=this.localModel)||void 0===r?void 0:r.isDisplay)&&this.localModel.isInBig&&this.localModel.playInBig())}))}muteSpeaker(e){return __awaiter$2(this,void 0,void 0,(function*(){info("静音扬声器 状态 =>","","",["status =>",e]);try{this.setSpeakerEnable(e)}catch(t){return Promise.reject(BmSetLocalSpeakerEnable(`开关扬声器失败 ${e} error: ${JSON.stringify(t)}`))}}))}createStreamAndPublish(e,t,i,r){var n,s,o,a,c,u,d,l;return __awaiter$2(this,void 0,void 0,(function*(){let h=BMStreamModelVM.getCanvasStream();if(yield this.room.initDevices(),t)null===(a=this.brtcStream)||void 0===a||a.destroy(),(null===(c=this.room)||void 0===c?void 0:c.audioDevices.length)||(error$1("当前电脑中没有音频输入设备,重新获取"),yield null===(u=this.room)||void 0===u?void 0:u.initDevices()),(null===(d=this.room)||void 0===d?void 0:d.videoDevices.length)||(error$1("当前电脑中没有视频输入设备, 重新获取"),yield null===(l=this.room)||void 0===l?void 0:l.initDevices()),this.room.audioDevices.length>0?this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:this.room.mediaPermission.microphone},i.userId).catch((e=>(error$1("create brtc audio and video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))):(error$1("没有音频输入设备,只能创建视频流"),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!1},i.userId).catch((e=>(error$1("create brtc video stream failed","","",[JSON.stringify(e)]),Promise.reject(e)))));else{const e=h.getVideoTracks()[0];this.audioStream||(this.audioStream=yield this.room.createSingleLocalStream({video:!1,audio:!0},i.userId).catch((e=>(error$1("create brtc stream error","","",[JSON.stringify(e)]),Promise.reject(e)))));const t=null===(n=this.audioStream)||void 0===n?void 0:n.getAudioTrack();if(!t||t&&t.muted)throw null===(s=this.audioStream)||void 0===s||s.destroy(),this.audioStream=null,this.localStreamErrorWatcher.next("audio"),error$1("麦克风设备不可用","","",["muted => ?",null==t?void 0:t.muted]),getStreamError("麦克风");null===(o=this.brtcStream)||void 0===o||o.destroy(),this.brtcStream=yield this.room.createSingleLocalStream({video:!0,audio:!0,videoSource:e,audioSource:t},i.userId).catch((e=>Promise.reject(e)))}this.brtcStream&&(t||(yield this.brtcStream.muteVideo()),e||(yield this.brtcStream.muteAudio()),r&&(yield this.brtcStream.replaceTrack(r).catch((e=>{error$1("美颜 videoTrack replace 失败","","",JSON.stringify(e))}))),yield this.room.publish(this.brtcStream).catch((e=>{var t,i;return null===(t=this.brtcStream)||void 0===t||t.destroy(),null===(i=this.localModel)||void 0===i||i.updateBloudStream(void 0,this),Promise.reject(e)})),this.brtcStream.on("video-track-mute",this.muteHandler.bind(this,"video")),this.brtcStream.on("video-track-ended",this.muteHandler.bind(this,"video")),this.brtcStream.on("audio-track-mute",this.muteHandler.bind(this,"audio")),this.brtcStream.on("audio-track-ended",this.muteHandler.bind(this,"audio")),yield this.publishBloudStream(e,t))}))}publishBloudStream(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){const r=this.localModel.userId;this.bloudStream=this.room.boomCore.creteBloudLocalStream({audio_enable:e,video_enable:t},r),yield this.bloudStream.publish({video_enable:t,audio_enable:e}),null===(i=this.localModel)||void 0===i||i.updateBloudStream({video:t,audio:e,isScreen:!1},this)}))}muteHandler(e){var t,i,r,n,s,o;return __awaiter$2(this,void 0,void 0,(function*(){this.localStreamConnectErrorWatcher.next(BMStreamDisconnectedError("video"===e?"摄像头":"麦克风"));error$1("brtc本地流出现异常,需要重新推流处理","","",["videoEnable",null===(t=this.localModel)||void 0===t?void 0:t.videoEnable,"audioEnable",null===(i=this.localModel)||void 0===i?void 0:i.audioEnable,"type",e]);const a=()=>__awaiter$2(this,void 0,void 0,(function*(){var e,t,i,r,n,s,o,a;(null===(e=this.localModel)||void 0===e?void 0:e.stream)&&(yield null===(t=this.room)||void 0===t?void 0:t.boomCore.unpublish(this.localModel.stream)),null===(r=null===(i=this.localModel)||void 0===i?void 0:i.stream)||void 0===r||r.destroy(),null===(n=this.audioStream)||void 0===n||n.destroy(),null===(s=this.videoStream)||void 0===s||s.destroy(),this.audioStream=null,this.videoStream=null,null===(o=this.localModel)||void 0===o||o.updateStream(void 0,!0,this),yield this.bloudStream.unpublish(),this.bloudStream=null,null===(a=this.localModel)||void 0===a||a.updateBloudStream(void 0,this)}));if(null===(r=this.localModel)||void 0===r?void 0:r.stream)if("video"===e)info("video track has problem, now unpublish"),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),yield a();else{null===(n=this.audioStream)||void 0===n||n.destroy(),this.audioStream=null,this.audioStream=yield null===(s=this.room)||void 0===s?void 0:s.createPBSingleLocalStream({video:!1,audio:!0});const e=null===(o=this.audioStream)||void 0===o?void 0:o.getAudioTrack();e&&!e.muted?this.localModel.stream&&(yield this.localModel.stream.replaceTrack(e).catch((e=>{error$1("本地流出现异常, 重新创建audio stream replace 失败","本地流出现异常","",[JSON.stringify(e)]),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),a()}))):(error$1("recreate audio stream failed, now unpub"),this.localStreamConnectErrorWatcher.next(BmSyncStreamFailError()),a())}this.localStreamErrorWatcher.next(e)}))}unpublishStream(){var e,t,i,r;return __awaiter$2(this,void 0,void 0,(function*(){const n=this.getLocalStreamModel();if(n){const s=n.stream;s&&(yield null===(e=this.room)||void 0===e?void 0:e.unpublish(s).catch((e=>{error$1("brtc 取消发布失败","取消推流",n.userId,[JSON.stringify(e)])})));try{this.removeFromRecorder(s),null==s||s.destroy(),null===(t=this.videoStream)||void 0===t||t.destroy(),null===(i=this.audioStream)||void 0===i||i.destroy(),null===(r=this.brtcStream)||void 0===r||r.destroy(),this.videoStream=null,this.audioStream=null,this.brtcStream=void 0,n.updateStream(void 0,!0,this),yield this.bloudStream.unpublish(),n.updateBloudStream(void 0,this),this.bloudStream=null}catch(e){error$1("stream destroy failed","取消推流",n.userId,[JSON.stringify(e)])}}}))}muteOrUnpublishStream(e,t,i){var r;return __awaiter$2(this,void 0,void 0,(function*(){const t=i.stream;let n=!0;if("audio"===e?n=t.getVideoOn():"video"===e&&(n=t.getAudioOn()),n){if("audio"===e){(yield t.muteAudio())||error$1("brtc muteAudio失败","关闭本地音频","本地"),yield this.bloudStream.setAudioEnabled(!1).catch((e=>{error$1("bloud setAudioEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),i.updateBloudStream({audio:!1,video:!0,isScreen:!1},this)}else if("video"===e){const e=BMStreamModelVM.getCanvasStream().getVideoTracks()[0];try{yield t.replaceTrack(e),yield t.muteVideo()}catch(e){error$1("关闭本地视频失败","关闭本地视频","本地",[JSON.stringify(e)])}try{null===(r=this.videoStream)||void 0===r||r.destroy(),this.videoStream=null}catch(e){error$1("this.videoStream destroy failed")}yield this.bloudStream.setVideoEnabled(!1).catch((e=>{error$1("bloud setVideoEnabled 失败","关闭本地音频","本地",[JSON.stringify(e)])})),i.updateBloudStream({video:!1,audio:!0,isScreen:!1},this)}}else yield this.unpublishStream()}))}toggleShareScreen(e,t,i){var r,n,s,o,a;return __awaiter$2(this,void 0,void 0,(function*(){return info("开关共享屏幕","","开关共享屏幕",["stats => ",e]),!e&&(null===(r=this.room)||void 0===r?void 0:r.boomCore.shareScreenStream)&&this.removeFromRecorder(null===(n=this.room)||void 0===n?void 0:n.boomCore.shareScreenStream),yield null===(s=this.room)||void 0===s?void 0:s.boomCore.toggleShareScreen(e,t,i).then((()=>{var t;if(e){const e=null===(t=this.room)||void 0===t?void 0:t.boomCore.shareScreenStream;e&&this.remoteStreamPublished(e)}else this.localModel.getUser().removeStream(`${this.localModel.userId}_screen`),this.removeShareStreamModelByUId(this.localModel.userId)})).catch((i=>(error$1("bmStreamVm toggleShareScreen error","切换共享屏幕","",["enable =>",e,"options =>",t]),Promise.reject(i)))),e&&(null===(o=this.room)||void 0===o?void 0:o.boomCore.shareScreenStream)&&this.addToRecorder(null===(a=this.room)||void 0===a?void 0:a.boomCore.shareScreenStream),this.localIsShare=e,this.isShareWatcher.next(e),Promise.resolve(!0)}))}setShareScreenContentHint(e){var t;null===(t=this.room)||void 0===t||t.boomCore.setShareScreenContentHint(e)}createCanvas(){const e=document.createElement("canvas");e.id="tarCanvas",e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.bottom="0",document.body.appendChild(e)}canvasDisplay(){let e=document.getElementById("tarCanvas");if(e){e.width=640,e.height=360;let t=e.getContext("2d");t.fill(),t.beginPath(),t.fillStyle="rgb(0,0,0)",t.fillRect(0,0,e.width,e.height),this.canvasTimer&&clearTimeout(this.canvasTimer),this.canvasTimer=setTimeout((()=>{this.canvasDisplay()}),1e3)}}static getCanvasStream(){return document.getElementById("tarCanvas").captureStream()}createVideoStream(){var e,t,i;return __awaiter$2(this,void 0,void 0,(function*(){return yield this.room.initDevices(),null===(e=this.videoStream)||void 0===e||e.destroy(),this.videoStream=yield this.room.createPBSingleLocalStream({video:!0,audio:!1},this.localModel.userId).catch((e=>Promise.reject(BMCreateStreamError("视频")))),null===(t=this.videoStream)||void 0===t||t.on("video-track-mute",this.muteHandler.bind(this,"video")),null===(i=this.videoStream)||void 0===i||i.on("video-track-ended",this.muteHandler.bind(this,"video")),this.videoStream.getVideoTrack()}))}startRecord(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(this._recorder)return;this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(e),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended")})),this._recorder.on("started",(()=>{info("record started.")}));let i=!0;try{yield this._recorder.start(),this._isRecording=!0,this.isRecordingWatcher.next(!0),this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),i=!1,yield t.stop()}return i}))}addToRecorder(e){this._isRecording&&!this._slicingRecord&&(e.on("audio-track-ended",(()=>{this.removeFromRecorder(e)})),this._recorder.addStream(e))}removeFromRecorder(e){this._isRecording&&!this._slicingRecord&&this._recorder.removeStream(e)}stopRecord(){return __awaiter$2(this,void 0,void 0,(function*(){this._recorder&&(this._isRecording=!1,this.isRecordingWatcher.next(!1),yield this._recorder.stop(),this._recorder=void 0)}))}sliceRecord(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(!this._isRecording)return;let i=this._recorder._opts;this._slicingRecord=!0;try{yield this._recorder.stop()}catch(e){error$1("stop record exception","","",[JSON.stringify(e)])}i.filename=e,this._recorder=null===(t=this.room)||void 0===t?void 0:t.boomCore.createRecorder(i),this._recorder.on("track-ended",(()=>{this.stopRecord(),info("record ended.")})),this._recorder.on("started",(()=>{info("record started.")}));let r=!0;try{yield this._recorder.start(),this._slicingRecord=!1,this.shareStreamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)})),this.streamModels.forEach((e=>{e.stream&&!e.stream.isLocalStream()&&e.stream.isSubscribed()&&this.addToRecorder(e.stream)}))}catch(e){let t=this._recorder;this._recorder=void 0,this._isRecording=!1,this.isRecordingWatcher.next(!1),this._slicingRecord=!1,r=!1,yield t.stop()}return r}))}startSpeakerDetector(){var e;this._speaker=null,this._speakerDetector=null===(e=this.room)||void 0===e?void 0:e.boomCore.createSpeakerDetector(),this._speakerDetector.on("speaker",(e=>{var t,i;let r=!0;e?((null===(t=this._speaker)||void 0===t?void 0:t.getUserInfo().userId)===e.getUser().userId&&(r=!1),this._speaker=e.getUser()):(this._speaker||(r=!1),this._speaker=null),r&&(info("当前讲话人","语音激励",null===(i=this._speaker)||void 0===i?void 0:i.userId),this.speakerWatcher.next(this._speaker))}))}addToDetector(e){this._speakers.set(e.getID(),e),this._speakerDetector&&this._speakerDetector.addStream(e)}removeFromDetector(e){let t=this._speakers.get(e);this._speakerDetector&&t&&(t.close(),this._speakers.delete(e),this._speakerDetector.removeStream(t))}shareCustomMedia(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){return null===(i=this.room)||void 0===i?void 0:i.boomCore.shareHTMLMedia(e,t)}))}clearCache(){var e,t,i,r;null===(t=null===(e=this.localModel)||void 0===e?void 0:e.stream)||void 0===t||t.destroy(),null===(i=this.videoStream)||void 0===i||i.destroy(),this.streamModels.clear(),this.shareStreamModels.clear(),null===(r=this.room)||void 0===r||r.userVM.clearUsers()}}class BMRoomInfo{constructor(){this.room=null,this._roomName="",this.msgSeq="",this.roomID="",this.audioOff=!1,this.selfopenaudio=!1,this.lock=!1,this.leaveNotice=!1,this.openSelf=!1,this.chatNotice="",this.chatNoticeRich="",this.raiseHandsList=new Map,this.raiseHandsWatcher=new BehaviorSubject(Array.from(this.raiseHandsList.values())),this.raiseVideoHandsList=new Map,this.raiseVideoHandsWatcher=new BehaviorSubject(Array.from(this.raiseVideoHandsList.values())),this.raiseSimpleHandsList=new Map,this.raiseSimpleHandsWatcher=new BehaviorSubject(Array.from(this.raiseSimpleHandsList.values())),this.operationPermissionWatcher=new Subject,this.chatNoticeWatcher=new Subject,this.totalUserWatcher=new BehaviorSubject(0),this.totalWaitRoomUserWatcher=new BehaviorSubject(0),this.isOpenWaitRoom=new Subject,this.audioOffWatcher=new Subject,this.lockWatcher=new BehaviorSubject(this.lock),this.leaveNoticeWatcher=new BehaviorSubject(this.leaveNotice),this.openSelfWatcher=new BehaviorSubject(this.openSelf),this.setRaiseHandsWatcherValue=debounce((()=>{this.raiseHandsWatcher.next(Array.from(this.raiseHandsList.values()))}),1e3),this.setVideoRaiseHandsWatcherValue=debounce((()=>{this.raiseVideoHandsWatcher.next(Array.from(this.raiseVideoHandsList.values()))}),1e3),this.setSimpleRaiseHandsWatcherValue=debounce((()=>{this.raiseSimpleHandsWatcher.next(Array.from(this.raiseSimpleHandsList.values()))}),1e3),BoomEmitter.emitter.on(RAISE_HAND,(e=>{"raiseHandsAudio"===e.status?e.user.raiseAudioHands?this.addRaiseHandUser(e.user):this.removeRaiseHandUser(e.user.userId):"raiseHandsVideo"===e.status?e.user.raiseVideoHands?this.addVideoRaiseHandUser(e.user):this.removeVideoRaiseHandUser(e.user.userId):"raiseHand"===e.status&&(e.user.raiseHand?this.addSimpleRaiseHandUser(e.user):this.removeSimpleRaiseHandUser(e.user.userId))}))}get roomName(){return this._roomName||(this._roomName=this.room.getName()),this._roomName}get isBigRoom(){return this.room.isBig}setup(e){this.roomID=e.room,this.handleInitParams()}bindRoom(e){this.room=e}initCustomStats(e){this.operationPermission=e,void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}updateOperationPermission(e){this.operationPermission=Object.assign(Object.assign({},this.operationPermission),e),void 0!==e.chatNotice&&(this.chatNotice=e.chatNotice),void 0!==e.chatNoticeRich&&(this.chatNoticeRich=e.chatNoticeRich),this.operationPermissionWatcher.next(this.operationPermission)}handleInitParams(){const e=this.room.boomCore.getAudioOff(),t=this.room.boomCore.getSelfOpenAudio();this.setAudioOff(e,t)}setAudioOff(e,t){this.audioOff=e,this.selfopenaudio=t,this.audioOffWatcher.next({audioOff:e,selfopenaudio:t})}setlock(e){this.lock=e,this.lockWatcher.next(e)}setLeaveNotice(e){this.leaveNotice=e,this.leaveNoticeWatcher.next(e)}setRaiseHandsList(e){e.forEach((e=>{e.raiseAudioHands&&this.raiseHandsList.set(e.getID(),e),e.raiseVideoHands&&this.raiseVideoHandsList.set(e.getID(),e),e.raiseHand&&this.raiseSimpleHandsList.set(e.getID(),e)})),this.setRaiseHandsWatcherValue(),this.setVideoRaiseHandsWatcherValue(),this.setSimpleRaiseHandsWatcherValue()}addRaiseHandUser(e){this.raiseHandsList.set(e.getID(),e),this.setRaiseHandsWatcherValue()}removeRaiseHandUser(e){this.raiseHandsList.delete(e),this.setRaiseHandsWatcherValue()}addVideoRaiseHandUser(e){this.raiseVideoHandsList.set(e.getID(),e),this.setVideoRaiseHandsWatcherValue()}removeVideoRaiseHandUser(e){this.raiseVideoHandsList.delete(e),this.setVideoRaiseHandsWatcherValue()}addSimpleRaiseHandUser(e){this.raiseSimpleHandsList.set(e.getID(),e),this.setSimpleRaiseHandsWatcherValue()}removeSimpleRaiseHandUser(e){this.raiseSimpleHandsList.delete(e),this.setSimpleRaiseHandsWatcherValue()}}var name="@hysc/meeting",version="10.0.67",description="boom meeting",main="umd/index.js",module$1="esm/index.js",types="esm/index.d.ts",scripts={dev:"tsc --watch",build:"tsc",docs:"rimraf docs && typedoc"},keywords=[],files=["esm","umd"],author="yangliye",license="MIT",dependencies={"@hysc/core":"workspace:*","@hysc/logger":"workspace:*","lodash-es":"^4.17.21",mitt:"^3.0.0","@hysc/p-queue":"6.3.0",rxjs:"^7.5.5",typescript:"^4.6.3","@hysc/utils":"workspace:*"},peerDependencies={"@hysc/core":"workspace:*"},devDependencies={"@types/lodash-es":"^4.17.6"},PackageJson={name:name,version:version,description:description,main:main,module:module$1,types:types,private:!1,scripts:scripts,keywords:keywords,files:files,author:author,license:license,dependencies:dependencies,peerDependencies:peerDependencies,devDependencies:devDependencies};class BMLiveVM{constructor(e){this.room=e}get localBMUser(){return this.room.getLocalParticipant()}get localIsAudience(){return this.room.getLocalParticipant().isAudience}handlePull(e){return __awaiter$2(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePull(e)):yield this.room.handlePull(e)}))}handleChangeStreamType(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.room.handleChangeStreamType(e)}))}handlePlay(e,t){return __awaiter$2(this,void 0,void 0,(function*(){this.localIsAudience&&!this.localBMUser.audienceEnableSpeaking?e.isMixer&&(yield this.room.handlePlay(e,t,!1)):yield this.room.handlePlay(e,t,!0)}))}handleAudienceDisable(){return __awaiter$2(this,void 0,void 0,(function*(){this.room.bmStreamVm.getStreamModels().forEach((e=>{var t;(null===(t=null==e?void 0:e.stream)||void 0===t?void 0:t.isSubscribed())&&e.hasPulled&&(e.hasPulled=!1,e.pulledStreamType="small",this.room.unsubscribe(e.stream).then((()=>{console.log("观众取消订阅这股流",e.userId,e.nickname,e.isDisplay,e.isCurrentDisplay)})))}));const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1))}))}handleAudienceEnable(){return __awaiter$2(this,void 0,void 0,(function*(){const e=this.room.bmStreamVm.mixStreamModelWatcher.getValue();e&&(yield this.handlePlay(e,!1)),this.room.bmStreamVm.getStreamModels().forEach((e=>{streamPullQueue.addQueue(this.room.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}))}))}}function addBrtcNetEvent(e){var t,i;null===(t=e.brtcClient.client)||void 0===t||t.signal.channel.on("reconnecting",(()=>e.fire(BCEvent$1.BRTC_ROOM_ROCONNECTING))),null===(i=e.brtcClient.client)||void 0===i||i.signal.channel.on("reconnected",(()=>e.fire(BCEvent$1.BRTC_ROOM_RECONNECTED)))}class SingletonQueue{constructor(){return this.pullMap=new Map,SingletonQueue.instance?SingletonQueue.instance:(SingletonQueue.instance=this,this)}addUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.set(`${e.id}_screen`,e):this.pullMap.set(e.id,e)})),this._callback&&this._callback(this.pullMap)}removeUsers(e){e.forEach((e=>{e.isScreen?this.pullMap.delete(`${e.id}_screen`):this.pullMap.delete(e.id)}))}restart(){if(!this._callback)throw error$1("no callback exists in streamQueue please setQueueProcessor first!"),new Error("no callback");this._callback(this.pullMap)}setQueueProcessor(e){this._callback=e}removeQueueProcessor(){this._callback=void 0}}class AudioPlay{constructor(e,t){this.playMap=new WeakSet,this.playerMap=new Map,this.muted=!1;const i=document.getElementById(e);if(!i)throw new Error("no container found, play failed");this.container=i,this.room=t}addStream(e){if(info("add stream to player","",e.getUserId(),["streamId ",e.getStreamId()]),this.room.shouldPlayAudio&&this.room.autoPlayAudio)if(this.playMap.has(e)){warn$1("stream is playing, replay",e.getUserId());const t=this.playerMap.get(e.getStreamId());t&&t.replay(e)}else this.playMap.add(e),this.play(e)}removeStream(e){const t=e.getStreamId();let i=this.playerMap.get(t);i&&i.destroy(),this.playerMap.delete(t),this.playMap.delete(e)}play(e){return __awaiter$2(this,void 0,void 0,(function*(){if(e.hasAudio()&&this.container){const t=new AudioPlayer(this.container,{});yield t.play(e),this.muted&&t.setVolume(0),this.playerMap.set(e.getStreamId(),t)}}))}mute(e){this.muted=e,e?this.playerMap.forEach((e=>e.setVolume(0))):this.playerMap.forEach((e=>{e.audioLevel>0?e.setVolume(e.audioLevel):e.setVolume(1)}))}setVolume(e,t){const i=this.playerMap.get(e);if(i){if(i.audioLevel=t,this.muted)return;i.setVolume(t)}else error$1("设置了流的音量,但是没有找到对应的播放器",e)}setDevice(e){this.playerMap.forEach((t=>t.setSinkId(e)))}}let _selfSortType=1;const subscribeOptions={audio:!0,video:!0,streamType:"small",videoEnable:!0,audioEnable:!0};let autoPlayAudio=!0;class BMRoom{constructor({initDevices:e}={initDevices:!0}){this.roomVM=null,this.videoDevices=[],this.audioDevices=[],this.audioOutputDevices=[],this.selectVideoDevice=null,this.selectAudioDevice=null,this.selectAudioOutputDevice=null,this.streamQueue=new SingletonQueue,this.userListColumns=1,this.sortType=1,this.BRTCConnectFailed=!1,this.pubFailedNum=0,this.streamConnectedErrorQueue=[],this.conferenceMode=1,this.isBig=!1,this.selectVideoDeviceWatcher=new BehaviorSubject(this.selectVideoDevice),this.selectAudioDeviceWatcher=new BehaviorSubject(this.selectAudioDevice),this.selectAudioOutputDeviceWatcher=new BehaviorSubject(this.selectAudioOutputDevice),this.audioDevicesWatcher=new Subject,this.videoDevicesWatcher=new Subject,this.audioOutputDevicesWatcher=new Subject,this.raiseHandleRespWatcher=new Subject,this.enableAudienceSpeakingWatcher=new Subject,this.mediaPermission={microphone:!0,camera:!0,screen:!0},this.videoProfile="360p",this.audioProfile=null,this.streamWSReconnectWatcher=new Subject,this.bloudWSReconnectWatcher=new Subject,this.netConnecting=!0,this.netConnectingWatcher=new Subject,this.hasSyncPermission=!0,this.meetingControlOptions={cancelAutoPull:!1},this.forceId="",this.networkState={bloud:!0,brtc:!0},this.brtcNetEnableWatcher=new Subject,this.autoPlayAudio=!0,this.messageWatcher=new BehaviorSubject({type:MessageType.INIT,status:!1,isNotCancelRootReport:!1}),this.isInWaitRoom=!1,this.shouldPlayAudio=!0,this.handleReprocessStreamError=()=>{this.netConnecting&&this.networkState.brtc&&this.networkState.bloud&&this.streamConnectedErrorQueue.length&&(info("brtc 网络恢复正常,处理重推逻辑"),this.streamConnectedErrorQueue.forEach((e=>{this.handleStreamConnectError(e)}))),this.streamConnectedErrorQueue=[]},this.handleMediaDevicesChange=debounce((()=>__awaiter$2(this,void 0,void 0,(function*(){const e=this.filterDevice(this.audioDevices);yield this.bmStreamVm.changeAudioInput(e);const t=this.filterDevice(this.audioOutputDevices);yield this.bmStreamVm.changeSpeaker(t)}))),1e3),this.enumVideoDevices=enumVideoDevices,this.enumAudioInputDevices=enumAudioInputDevices,this.enumAudioOutputDevices=enumAudioOutputDevices,this.getPermissions=getPermissions,this.checkSystemSupport=checkSystemSupport,this.createStream=createStream,this.participantNotice=!1,this.handleQueueTask=(e,t=!1)=>__awaiter$2(this,void 0,void 0,(function*(){this.BRTCConnectFailed||(e.isLocal||!this.meetingControlOptions.cancelAutoPull||e.shouldPull)&&(yield this.handleStreamTask(e,t))})),this.processUser=e=>__awaiter$2(this,void 0,void 0,(function*(){const t=new Set;if(e.forEach((e=>{if(e.isScreen){const i=this.bmStreamVm.getShareStreamModelByUId(e.id);i&&i.stream||(e.isWeb?t.add(`${e.id}_screen`):t.add(e.id))}else{let i=this.bmStreamVm.streamModels.get(e.id);i&&!i.stream&&t.add(e.id)}})),info("brtc query streams","","",["queryIds => ",t]),t.size){const e=yield this.queryBrtcStreams(Array.from(t)).catch((e=>{error$1("query stream error","","",[JSON.stringify(e)])}));info("brtc query streams result","","",["streams =>",e]),e&&this.handleAddStreams(e)}})),this.queueProcessor=debounce(this.processUser,500,{maxWait:1e3}),info(`\n******************************************************************************\n* 欢迎使用 BoomMeeting(${PackageJson.version}) Web SDK\n******************************************************************************\n `);const t=BoomEmitter.getInstance();this.localUser=new BMUser({},!0),this.roomInfo=new BMRoomInfo,this.roomInfo.bindRoom(this),this.bmLiveVM=new BMLiveVM(this),this.bmStreamVm=(new BMStreamModelVM).initWithRoom(this),this.boomCore=new BCClient({}),t.on(RECEIVE_SUBSCRIBE_MESSAGE,(e=>{this.handleSubMessage(e)})),t.on(HANDLE_STREAM_CONNECT_ERROR,(e=>{this.handleStreamConnectError(e)})),t.on(ADD_PULL_USER,(e=>{this.addUser2Queue(e)})),t.on(MANUAL_SUBSCRIPTION,(e=>{this.manualSubscribeStreamModel(e.stream)})),t.on(UNSUBSCRIBE_STREAM,(e=>{this.handleUnsubscribe(e.stream)})),t.on(BIND_ELEMENT,(e=>{this.handleStreamBindElement(e.stream)})),t.on(BIND_BIG_ELEMENT,(e=>{this.handleStreamBindBigElement(e.stream)})),t.on(SET_VOLUME,(e=>{var t;null===(t=this.audioPlayer)||void 0===t||t.setVolume(e.streamId,e.volume)})),window.addEventListener("offline",(()=>{this.netConnecting=!1,this.netConnectingWatcher.next(!1)})),window.addEventListener("online",(()=>{this.netConnecting=!0,this.netConnectingWatcher.next(!0),NETWORK_ERROR_QUEUE.forEach((e=>{e()})),NETWORK_ERROR_QUEUE.clear(),this.handleReprocessStreamError()})),window.navigator.mediaDevices&&e&&(window.navigator.mediaDevices.ondevicechange=()=>__awaiter$2(this,void 0,void 0,(function*(){yield this.initDevices(),yield this.handleMediaDevicesChange()})),this.initDevices()),this.streamQueue.setQueueProcessor(this.queueProcessor),this.brtcNetEnableWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()})),this.bloudWSReconnectWatcher.subscribe((e=>{e&&this.handleReprocessStreamError()}))}get isSingleColumns(){return 1===this.userListColumns}setAutoPlayAudio(e){this.autoPlayAudio=e,autoPlayAudio=e}setMediaPermission(e){this.mediaPermission=Object.assign(Object.assign({},this.mediaPermission),e),info("current media permission is ","","",[JSON.stringify(this.mediaPermission)])}setShouldPlayAudio(e){this.shouldPlayAudio=e}initAudioPlayer(e){this.audioPlayer=new AudioPlay(e,this)}setupMeetingControlOptions(e){e&&(this.meetingControlOptions=Object.assign(Object.assign({},this.meetingControlOptions),e))}handleSubMessage(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e.stream),`${e.stream.streamId} - 订阅流 - display ${e.stream.isDisplay} - currentDisplay - ${e.stream.isCurrentDisplay}`,0,e.stream.nickname)}setVideoProfile(e){e&&(this.videoProfile=e)}setUserListColumns(e){const t=toNumber(e);if(!isNumber(t))throw new Error("参数必须是数字");this.userListColumns=t}setSortType(e){const t=toNumber(e);if(t>2||t<1)throw new Error("排序映射只能为 2 或者 1");this.sortType=t,_selfSortType=this.sortType}setAudioProfile(e){this.audioProfile=e}setSig(e){this.boomCore.setShareSig(e)}initDevices(){return __awaiter$2(this,void 0,void 0,(function*(){return Promise.all([this.enumVideoDevices().then((e=>{this.videoDevices=e,this.videoDevicesWatcher.next(e)})),this.enumAudioInputDevices().then((e=>{this.audioDevices=e,this.audioDevicesWatcher.next(e)})),this.enumAudioOutputDevices().then((e=>{this.audioOutputDevices=e,this.audioOutputDevicesWatcher.next(e)}))]).then((()=>{let e=this.videoDevices.filter((e=>{var t;return e.name==(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.name)}));const t=e[0]?e[0]:this.filterDevice(this.videoDevices);t&&this.setSelectVideoDevice(t);let i=this.audioDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.name)}));const r=i[0]?i[0]:this.filterDevice(this.audioDevices);r&&this.setSelectAudioDevice(r);let n=this.audioOutputDevices.filter((e=>{var t;return e.name==(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.name)}));const s=n[0]?n[0]:this.filterDevice(this.audioOutputDevices);return s&&this.setSelectSpeakerDevice(s),{videoDevices:this.videoDevices,audioDevices:this.audioDevices,audioOutputDevices:this.audioOutputDevices,selectVideoDevice:this.selectVideoDevice,selectAudioDevice:this.selectAudioDevice,selectAudioOutputDevice:this.selectAudioOutputDevice}}))}))}filterDevice(e){const t=e.filter((e=>e.default))[0];return t||e[0]}setSelectAudioDevice(e){var t;(null===(t=this.selectAudioDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(this.selectAudioDevice=e,this.selectAudioDeviceWatcher.next(e))}setSelectVideoDevice(e){var t;(null===(t=this.selectVideoDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(this.selectVideoDevice=e,this.selectVideoDeviceWatcher.next(e))}setSelectSpeakerDevice(e){var t;(null===(t=this.selectAudioOutputDevice)||void 0===t?void 0:t.deviceId)!==e.deviceId&&(this.selectAudioOutputDevice=e,this.selectAudioOutputDeviceWatcher.next(e))}observe(e,t){return this.observes[e].subscribe(t)}join(e){return __awaiter$2(this,void 0,void 0,(function*(){const t=e.brtc_host;t&&this.setCustomUrl(t);try{if(this.boomCore.client)return error$1("重复 join,请先调用 destroy"),Promise.reject(RepeatJoinError);this.conferenceMode=e.roomType,this.isBig=e.is_big,info("========================join room ===================="),info("","join info",e.userId,["roomId: ",e.room," roomType: ",e.roomType," roomName: ",e.name]),info("========================join room end ===================="),this.localUser.setup(e.userId,e.userinfo,e.nickname),this.bmStreamVm.createStreamModel(this.localUser),this.userVM=new BMUserVM(this.boomCore,this.localUser,this),this.isBig&&(this.userVM.commTimer=1e3),this.roomVM=new BMRoomVM(this.boomCore,this.userVM,this.roomInfo),this.roomVM.initWithRoom(this),this.chatVM=new BMChatVM(this.boomCore,this.userVM,this),this._attachEvents(),yield this.boomCore.join(e).catch((e=>Promise.reject(e))),this.roomInfo.setup(this.boomCore.getRoomInfo());for(let e in this.observes)this.observe(e,(()=>{}));this.bmStreamVm.startSpeakerDetector(),this.roomInfo.setlock(this.boomCore.client.lock),addBrtcNetEvent(this.boomCore)}catch(e){return error$1("join room error","","",[JSON.stringify(e)]),Promise.reject(e)}}))}leave(){var e;return __awaiter$2(this,void 0,void 0,(function*(){try{BoomEmitter.removeEmitter(),autoPlayAudio=!0,this.bmStreamVm.clearCache(),this.bmStreamVm.canvasTimer&&clearTimeout(this.bmStreamVm.canvasTimer);const t=yield this.boomCore.leave().catch((()=>{error$1("bloud离会失败")}));for(let t in this.observes)null===(e=this.observes[t])||void 0===e||e.unsubscribe();return this.observes={},t}catch(e){return error$1("leave room error","","",[JSON.stringify(e)]),Promise.reject(BmLeaveError(JSON.stringify(e)))}}))}releaseRoom(){return __awaiter$2(this,void 0,void 0,(function*(){yield this.boomCore.releaseRoom()}))}startRecord(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.startRecord(e)}))}stopRecord(){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.stopRecord()}))}sliceRecord(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.bmStreamVm.sliceRecord(e)}))}close(){this.bmStreamVm.clearCache(),this.boomCore.close()}setRemoteVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setRemoteAudioEnable(e,t,i){return __awaiter$2(this,void 0,void 0,(function*(){yield this.roomVM.setRemoteAudioEnable(e,t,i).catch((e=>Promise.reject(e)))}))}setLocalVideoEnable(e,t){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalVideoEnable(e,t).catch((e=>Promise.reject(e)))}))}setLocalAudioEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.setLocalAudioEnable(e).catch((e=>Promise.reject(e)))}))}setLocalSpeakerEnable(e){return __awaiter$2(this,void 0,void 0,(function*(){yield this.bmStreamVm.muteSpeaker(e).catch((e=>Promise.reject(e)))}))}_attachEvents(){this.observes=attachEvents(this.boomCore,this.userVM,this.bmStreamVm,this.chatVM,this)}createSingleLocalStream(e={video:!0,audio:!0},t){var i,r;return __awaiter$2(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(i=this.selectVideoDevice)||void 0===i?void 0:i.deviceId,microphoneId:null===(r=this.selectAudioDevice)||void 0===r?void 0:r.deviceId};e.videoSource&&(n.videoSource=e.videoSource),e.audioSource&&(n.audioSource=e.audioSource),n.echoCancellation=!0,n.noiseSuppression=!0,n.autoGainControl=!0;const s=yield this.boomCore.createLocalStream(n,t).catch((t=>(error$1("create brtc stream error","","",[JSON.stringify(t),null==t?void 0:t.message]),Promise.reject(getStreamError(e.video?"摄像头":"麦克风")))));e.video&&("720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile));try{yield s.init()}catch(t){if(error$1("brtc init stream failed","","",[null==t?void 0:t.message]),String(t).includes("Permission denied by system")){if(e.video)return Promise.reject(BMCameraNotAuthError());if(e.audio)return Promise.reject(BMMicNotAuthError())}else{if(String(t).includes("Could not start video source"))return Promise.reject(BMCameraOccupyError());if(String(t).includes("Could not start audio source"))return Promise.reject(BMMicOccupyError())}return Promise.reject(BMCreateStreamError(e.video?"摄像头":"麦克风"))}return s}))}createPBSingleLocalStream(e={video:!0,audio:!0},t){var i,r;return __awaiter$2(this,void 0,void 0,(function*(){const n={video:e.video,audio:e.audio,cameraId:null===(i=this.selectVideoDevice)||void 0===i?void 0:i.deviceId,microphoneId:null===(r=this.selectAudioDevice)||void 0===r?void 0:r.deviceId,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},s=yield this.boomCore.createPBLocalStream(n,t).catch((e=>Promise.reject(e)));return"720p"===this.videoProfile?s.setVideoEncoderConfiguration({width:1280,height:720,bitrate:1500,frameRate:25}):s.setVideoProfile(this.videoProfile),yield s.init(),s}))}subscribe(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return this.boomCore.subscribe(e,t)}))}unsubscribe(e){return this.boomCore.unsubscribe(e).catch((e=>Promise.reject(e)))}publish(e){return new Promise(((t,i)=>{this.boomCore.publish(e).then((()=>{t(!0)})).catch((()=>__awaiter$2(this,void 0,void 0,(function*(){error$1(`local publish stream failed, retry failed num: ${this.pubFailedNum}`),this.pubFailedNum<=3?(this.pubFailedNum+=1,setTimeout((()=>{this.publish(e)}),3e3)):(error$1("retry publish local stream failed, ubpublish now"),yield this.bmStreamVm.unpublishStream(),i(!1))}))))}))}unpublish(e){return this.boomCore.unpublish(e).catch((e=>Promise.reject(e)))}getUser(e){return this.userVM.getUser(e)}changeMaster(e,t=!1){var i;return __awaiter$2(this,void 0,void 0,(function*(){return null===(i=this.roomVM)||void 0===i?void 0:i.changeMaster(e,t).catch((e=>e))}))}updateManager(e,t,i=!0){return __awaiter$2(this,void 0,void 0,(function*(){return this.roomVM.updateManager(e,t,i).catch((e=>e))}))}getMaster(){return this.boomCore.getMaster()}getCreator(){return this.boomCore.getCreator()}getName(){return this.boomCore.getName()}evictUser(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){yield null===(i=this.roomVM)||void 0===i?void 0:i.evictUser(e,t).catch((e=>e))}))}updateUser(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){null===(i=this.roomVM)||void 0===i||i.updateUser(e,t).catch((e=>e))}))}getMsgSeq(){return this.boomCore.getMsgSeq()}getLimits(){return this.boomCore.getLimits()}getSwitch(){return this.boomCore.getSwitch()}syncRoom(){return this.boomCore.syncRoom()}update(e){return this.boomCore.update(e)}getUsers(){return this.userVM.userList}getTotalUsers(){return this.userVM.userList.size}sendMessage(e,t){return this.boomCore.sendMessage(e,t)}customMessage(e,t){return this.boomCore.customMessage(e,t)}getMessages(e,t){return this.boomCore.getMessages(e,t)}getLocalParticipant(){var e;let t=null===(e=this.userVM)||void 0===e?void 0:e.getLocalUser();return t||(t=this.localUser),t}getAudioOff(){return this.boomCore.getAudioOff()}getSelfOpenAudio(){return this.boomCore.getSelfOpenAudio()}getVideoOff(){return this.boomCore.getVideoOff()}getMsgOff(){return this.boomCore.getMsgOff()}getLock(){return this.boomCore.getLock()}getRoomInfo(){return this.roomInfo}setAudioOff(e,t){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.setAudioOff(e,t).catch((e=>Promise.reject(BmSetAudioOffError(`boomCore.setAudioOff error ${JSON.stringify(e)}`))))}))}updateRoom(e){return __awaiter$2(this,void 0,void 0,(function*(){return this.boomCore.client.update(e)}))}setVideoOff(e){return this.boomCore.setVideoOff(e).catch((e=>Promise.reject(BmSetVideoOffError(`boomCore.setVideoOff error ${JSON.stringify(e)}`))))}setMsgOff(e){return this.boomCore.setMsgOff(e).catch((e=>Promise.reject(BmSetMsgOffError(`boomCore.setMsgOff error ${JSON.stringify(e)}`))))}setSwitch(e){return this.boomCore.setSwitch(e)}setLock(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.setLock(e),this.boomCore.getLock()}))}sendChatMessage(e,t,i){if(!this.chatVM)throw new BoomError$1(INVALID_OPERATION,"未初始化chatVM, 无法发送聊天信息");return this.chatVM.sendMessage(e,t,i)}getChatMessage(){if(!this.chatVM)throw new BoomError$1(INVALID_OPERATION,"未初始化chatVM, 无法获取聊天室消息");return this.chatVM.messageList}getHistoryMessage(){return __awaiter$2(this,void 0,void 0,(function*(){return this.chatVM.getHistoryMessage()}))}updateCustomStats(e){return this.boomCore.updateCustomStats(Object.assign(Object.assign({},e),{pos:"web"})).catch((e=>Promise.reject(BmUpdateCustomStatsError(`.boomCore.updateCustomStats ${JSON.stringify(e)}`))))}getCustomStats(){return this.boomCore.getCustomStats()}getDuration(){return this.boomCore.getDuration()}checkUserHasMaster(e){return this.userVM.checkUserHasMaster(e)}changeNickName(e,t){var i;return __awaiter$2(this,void 0,void 0,(function*(){yield null===(i=this.roomVM)||void 0===i?void 0:i.changeNickName(e,t)}))}handleStreamTask(e,t=!1){return __awaiter$2(this,void 0,void 0,(function*(){e.stream?1===this.conferenceMode?(yield this.handlePull(e),yield this.handleChangeStreamType(e),yield this.handlePlay(e,t)):(yield this.bmLiveVM.handlePull(e),yield this.bmLiveVM.handleChangeStreamType(e),yield this.bmLiveVM.handlePlay(e,t)):(e.isDisplay&&e.bloudStream||e.audioEnable)&&(yield this.addUser2Queue({id:e.userId,isScreen:e.isShare,isWeb:e.isWeb}))}))}handlePull(e){var t,i,r,n;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal||(e.isMixer&&(yield this.handleSubscribeSteam(e)),e.isDisplay===e.isCurrentDisplay&&e.hasPulled?e.stream&&e.audioEnable&&(null===(n=this.audioPlayer)||void 0===n||n.addStream(e.stream)):(info(" 订阅流 => ","订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(i=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===i?void 0:i.call(t)]),e.isCurrentDisplay=e.isDisplay,e.checkCount=0,e.isDisplay||!e.isDisplay&&(e.audioEnable||(null===(r=e.stream)||void 0===r?void 0:r.getAudioOn()))?yield this.handleSubscribeSteam(e):yield this.handleUnsubscribeStream(e)))}))}manualSubscribeStreamModel(e){streamPullQueue.addQueue(this.handleStreamTask.bind(this,e),e.streamId,0,e.nickname)}handleUnsubscribe(e){streamPullQueue.addQueue(this.handleUnsubscribeStream.bind(this,e),e.streamId,0,e.nickname)}handleStreamBindElement(e){streamPullQueue.addQueue(this.handlePlay.bind(this,e),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleStreamBindBigElement(e){streamPullQueue.addQueue(this.handlePlayInBIg.bind(this,e),`bindElement-${e.userId}-${e.nickname}`,0,e.nickname)}handleUnsubscribeStream(e){var t,i,r,n,s;return __awaiter$2(this,void 0,void 0,(function*(){e.stream&&((null===(i=null===(t=e.stream)||void 0===t?void 0:t.isSubscribed)||void 0===i?void 0:i.call(t))||e.hasPulled)&&(info("取消订阅流 => ","取消订阅",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," isDisplay => ",e.isDisplay," isCurrentDisplay => ",e.isCurrentDisplay," audioEnable => ",e.audioEnable,"videoEnable => ",e.videoEnable," hasPulled => ",e.hasPulled," isSubscribed => ",null===(n=null===(r=e.stream)||void 0===r?void 0:r.isSubscribed)||void 0===n?void 0:n.call(r)]),e.hasPulled=!1,e.pulledStreamType="small",e.isInBig=!1,yield null===(s=e.stream)||void 0===s?void 0:s.stop(),yield this.unsubscribe(e.stream).then((()=>{var t;e.stream&&(null===(t=this.audioPlayer)||void 0===t||t.removeStream(e.stream)),e.isSubScribedWatcher.next(!1),info("取消订阅这股流","",e.userId,[e.nickname,e.isDisplay,e.isCurrentDisplay])})).catch((()=>{error$1("unsubscribe error")})))}))}handleSubscribeSteam(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){try{e.hasPulled&&e.stream.isSubscribed()?e.videoEnable&&(e.isDisplay?null===(t=e.stream)||void 0===t||t.unmuteVideo():null===(i=e.stream)||void 0===i||i.muteVideo()):(e.hasPulled=!0,yield this.subscribe(e.stream,subscribeOptions).then((()=>{var t,i;e.isDisplay||null===(t=e.stream)||void 0===t||t.muteVideo(),e.stream&&e.audioEnable&&(null===(i=this.audioPlayer)||void 0===i||i.addStream(e.stream)),e.pullFailedNum=0,info("订阅流结束","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId,"display =>",e.isDisplay]),e.isSubScribedWatcher.next(!0),this.bmStreamVm.addToRecorder(e.stream),e.isDisplay&&e.videoEnable&&(e.checkVideo(),checkStreamIsNormal(e))})).catch((t=>{var i;if(error$1("订阅流失败","订阅",e.userId,[" nickname =>",e.nickname,"streamId =>",e.streamId," error => ",JSON.stringify(t)]),e.hasPulled=!1,e.pulledStreamType="small",e.pullFailedNum+=1,e.pullFailedNum<=3)this.handlePulledFailed(e);else{e.pullFailedNum=0;const r=e.isShare;try{null===(i=e.stream)||void 0===i||i.destroy()}catch(t){}e.updateStream(void 0,!1,this.bmStreamVm),this.addUser2Queue({id:e.userId,isWeb:e.isWeb,isScreen:r})}})))}catch(t){e.hasPulled=!0,console.error("订阅流失败","",e.userId,e.nickname,"错误 =>",t)}}))}handleChangeStreamType(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal||e.pulledStreamType!==e.pulledStreamGoal&&(null===(t=e.stream)||void 0===t?void 0:t.isSubscribed())&&((null===(i=e.stream)||void 0===i?void 0:i.isSubscribed())||e.hasPulled)&&(info("大小流切换 => ","切换大小流",e.userId,[" streamId => ",e.streamId," nickname => ",e.nickname," 是否有流 => ",!!e.stream," pulledStreamType =>",e.pulledStreamType," pulledStreamGoal =>",e.pulledStreamGoal]),e.pulledStreamType=e.pulledStreamGoal,yield this.boomCore.brtcClient.setRemoteVideoStreamType(e.stream,e.pulledStreamGoal).catch((t=>{error$1("大小流切换失败","",e.userId,["error => ",JSON.stringify(t)])})),info("大小流切换结束","",e.userId,["nickname =>",e.nickname," isInBig => ",e.isInBig," pulledStreamGoal => ",e.pulledStreamGoal,"pulledStreamType => ",e.pulledStreamType]))}))}handlePlay(e,t,i=!0){var r,n,s,o;return __awaiter$2(this,void 0,void 0,(function*(){e.isLocal?e.isShare||t||(e.play(),e.playInBig()):(e.hasPulled||(null===(r=null==e?void 0:e.stream)||void 0===r?void 0:r.isSubscribed()))&&(t&&!e.isShare||e.play(),e.stream&&e.audioEnable&&((null===(n=this.audioPlayer)||void 0===n?void 0:n.playMap.has(e.stream))?info("stream state changed ,and player has this stream, don't need to play","",e.streamId,["stream ",e.stream]):null===(s=this.audioPlayer)||void 0===s||s.addStream(e.stream)),yield this.handlePlayInBIg(e,i),e.isDisplay&&e.videoEnable&&(null===(o=e.stream)||void 0===o?void 0:o.isSubscribed())&&e.checkVideo())}))}handlePlayInBIg(e,t=!0){return __awaiter$2(this,void 0,void 0,(function*(){let i=t;e.isShare&&(i=!1),yield e.playInBig(i)}))}handlePulledFailed(e){streamPullQueue.addQueue(this.handleQueueTask.bind(this,e),e.streamId,0,e.nickname)}handleStreamConnectError(e){var t,i;return __awaiter$2(this,void 0,void 0,(function*(){const{stream:r,isLocal:n}=e;if(n){if(r.stream)if(r.isShare?this.bmStreamVm.localShareError.next(BMShareStreamConnectError()):this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamConnectError()),this.netConnecting&&this.networkState.brtc&&this.networkState.bloud)if(r.isShare)info("Local share stream has problem, now ,republish"),handleShareStreamFailed(this,this.bmStreamVm);else{info("brtc 网络正常,重新推流");const e=(null===(t=r.stream)||void 0===t?void 0:t.getAudioOn())||!1,n=(null===(i=r.stream)||void 0===i?void 0:i.getVideoOn())||!1;yield this.publish(r.stream).then((()=>__awaiter$2(this,void 0,void 0,(function*(){var t;if(this.bmStreamVm.bloudStream)try{yield null===(t=this.bmStreamVm.bloudStream)||void 0===t?void 0:t.publish({video_enable:n,audio_enable:e}).then((()=>{info("localstream connect error, and repub success, bloud stream repub success","","",["audio =>",e," video => ",n]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess$1(e,n))}))}catch(t){error$1("brtc stream repub, but bloud stream pub failed"),r.stream&&(yield this.bmStreamVm.publishBloudStream(e,n),info("localstream connect error, and repub success, bloud stream repub success","","",["audio =>",e," video => ",n]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess$1(e,n)))}else yield this.bmStreamVm.publishBloudStream(e,n),info("localstream connect error, and repub success, bloud stream repub success","","",["audio =>",e," video => ",n]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectSuccess$1(e,n))})))).catch((()=>{info("localstream connect error, and repub failed","","",["audio =>",e," video => ",n]),this.bmStreamVm.localStreamConnectErrorWatcher.next(BMStreamReconnectFailed())}))}else error$1("brtc 网络还没恢复,等恢复了在重新推流 ","",r.userId,["nickname =>",r.nickname]),this.streamConnectedErrorQueue.push(e)}else this.netConnecting&&this.networkState.brtc?(r.hasPulled=!1,r.pulledStreamType="small",streamPullQueue.addQueue(this.handleQueueTask.bind(this,r),r.streamId,0,r.nickname)):(error$1("brtc 网络还没恢复,等恢复了在重新拉流 ","",r.userId,["nickname =>",r.nickname]),this.streamConnectedErrorQueue.push(e))}))}toggleAudienceSpeaking(e,t){e.permission.setAudio(t),this.updateUser(e.userId,{permission:e.permission.get()})}updateUserIsGuest(e,t){return __awaiter$2(this,void 0,void 0,(function*(){e.permission.setSubscribe(t),yield this.updateUser(e.userId,{permission:e.permission.get()})}))}managerChangeToGuest(e){this.userVM.managerChangeToGuest(e)}moveUserRoom(e,t=!1,i=!1){return this.boomCore.client.moveUserRoom(e,t,i)}getParticipantNotice(e){this.participantNotice=e}setCustomUrl(e){this.boomCore.setCustomUrl(e)}handleRePushSelf(){var e,t;return __awaiter$2(this,void 0,void 0,(function*(){const i=null===(t=null===(e=this.getLocalParticipant())||void 0===e?void 0:e.getMainStreamModel())||void 0===t?void 0:t.stream;i&&(yield this.publish(i))}))}handleResetOtherStreamStatus(){info("brtc sync-room-completed"),this.bmStreamVm.streamModels.forEach((e=>{var t;e.isLocal||(e.hasPulled=!1,e.pulledStreamType="small",e.stream&&e.stream.stop(),null===(t=e.stream)||void 0===t||t.destroy(),e.updateStream(void 0,!1,this.bmStreamVm))})),this.bmStreamVm.shareStreamModels.forEach((e=>{var t,i;if(!e.isLocal){e.hasPulled=!1,e.pulledStreamType="small";const r=e.getUser();null===(t=e.stream)||void 0===t||t.stop(),null===(i=e.stream)||void 0===i||i.destroy(),r.removeStream(`${e.userId}${STREAM_SUFFIX_SCREEN}`)}})),this.bmStreamVm.shareStreamModels.clear(),this.bmStreamVm.shareStreamModelsWatcher.next(Array.from(this.bmStreamVm.shareStreamModels.values())),this.networkState.brtc=!0,setTimeout((()=>{this.brtcNetEnableWatcher.next(!0),this.streamWSReconnectWatcher.next(!0)}),2e3),handleReconnectedStream(this)}addUser2Queue(e){var t;return __awaiter$2(this,void 0,void 0,(function*(){if(e.isScreen)this.streamQueue.addUsers([e]);else{const i=this.bmStreamVm.streamModels.get(e.id);i&&!i.isLocal&&(i.stream||i&&((null===(t=i.bloudStream)||void 0===t?void 0:t.audio)||i.bloudStream&&i.isDisplay)&&this.streamQueue.addUsers([e]))}}))}queryBrtcStreams(e){return __awaiter$2(this,void 0,void 0,(function*(){return yield this.boomCore.brtcClient.queryUsers(e)}))}handleAddStreams(e){e.forEach((e=>{if(isShareStream(e)){const t=this.bmStreamVm.shareStreamModels.get(transShareScreen2User(e.getUserId()));(!t||t&&!t.stream)&&this.bmStreamVm.remoteStreamPublished(e)}else{const t=this.bmStreamVm.streamModels.get(e.getUserId());t&&!t.stream&&this.bmStreamVm.remoteStreamPublished(e)}}))}getForceUser(e){return __awaiter$2(this,void 0,void 0,(function*(){const{users:t}=yield this.boomCore.queryUsers([e]);this.userVM.addBcUsersMap(t,!0),this.userVM.getForceUserWatcher.next(!0)}))}getVersion(){return PackageJson.version}}window.BoomMeeting=BMRoom,window.BoomError=BoomError;export{BMRoom as default};
|